diff --git a/docs/services/eks.md b/docs/services/eks.md index ea75349cba..02a9e3fcda 100644 --- a/docs/services/eks.md +++ b/docs/services/eks.md @@ -171,13 +171,13 @@ The credentials endpoint performs the following validations: #### TLS is required -Kubernetes only accepts an `https` `clientConfig.url` on a `MutatingWebhookConfiguration`, together with a `caBundle` the API server trusts. Floci serves HTTP with the default `floci.tls.enabled=false`, so the webhook is skipped with a warning in that case and pods start unmutated. Set `FLOCI_TLS_ENABLED=true` to get injection; the `caBundle` is then Floci's local CA, the same one served at `GET /_floci/ca.pem`. +Kubernetes only accepts an `https` `clientConfig.url` on a `MutatingWebhookConfiguration`, together with a `caBundle` the API server trusts. Floci serves HTTP with the default `floci.tls.enabled=false`, so the webhook is skipped with a warning in that case and pods start unmutated. Set `FLOCI_TLS_ENABLED=true` to get injection; the `caBundle` is then what `GET /_floci/ca.pem` serves: Floci's local CA, after the certificates in the `floci.tls.cert-path` file when Floci serves a certificate of your own. -The webhook URL uses the hostname containers reach Floci on. When Floci runs natively that is `host.docker.internal`, which the self-signed certificate covers. When Floci itself runs in a container the hostname is its container IP, and the self-signed certificate carries no SAN for it, so the API server rejects the handshake. Pods still start, unmutated. Point `FLOCI_SERVICES_LAMBDA_DOCKER_HOST_OVERRIDE` at a name the certificate covers (add it with `FLOCI_HOSTNAME`) to make the webhook reachable from that setup. +The API server also checks that the certificate names the webhook URL's host, so the URL uses a host the certificate Floci serves names. When the cluster resolves through Floci's embedded DNS (`FLOCI_SERVICES_EKS_EMBEDDED_DNS`, with the cluster on a Docker network that reaches Floci's DNS server, as it does by default with Floci in a container), that is Floci's hostname: `FLOCI_HOSTNAME`, or `localhost.floci.io`, both of which the self-signed certificate covers. Otherwise it is the host other containers reach Floci on: `host.docker.internal` when Floci runs natively, which the self-signed certificate also covers, or Floci's container IP, which it does not. When the certificate does not name that host, as with a certificate of your own issued for other names, pod identity injection is not available: the webhook is skipped with a warning naming the host, and pods start unmutated. To get it, have the API server call Floci by a name the certificate covers: with embedded DNS, set `FLOCI_HOSTNAME` to that name; without it, point `FLOCI_SERVICES_LAMBDA_DOCKER_HOST_OVERRIDE` at it. The self-signed certificate covers `FLOCI_HOSTNAME` too. The webhook carries `failurePolicy: Ignore`, and Floci admits the pod unchanged on any internal error, so a webhook that cannot be registered or cannot be reached never prevents a pod from being created. Registration failures log a warning and leave the cluster running. -The manifest is written into the cluster's k3s server manifests directory (`/var/lib/rancher/k3s/server/manifests`) before the container starts, so k3s applies it as the API server comes up. +The manifest is written into the cluster's k3s server manifests directory (`/var/lib/rancher/k3s/server/manifests`) before the container starts, so k3s applies it as the API server comes up. Floci writes it again when it adopts the cluster's surviving container after a restart, so the URL and `caBundle` follow Floci's current address and certificate. An adopted node keeps the resolvers it was created with, so its URL names Floci's hostname only when the node was created with Floci's DNS server, at the address that server has now. The cluster's data volume keeps the manifest, and the webhook k3s registered from it, across restarts and replaced containers, so when the webhook is skipped Floci writes a manifest that holds no objects, and k3s deletes the webhook an earlier start registered. ## Addon management diff --git a/src/main/java/io/floci/aws/config/ContainerCaBundle.java b/src/main/java/io/floci/aws/config/ContainerCaBundle.java index 8ce89ef8ea..15ebe09af1 100644 --- a/src/main/java/io/floci/aws/config/ContainerCaBundle.java +++ b/src/main/java/io/floci/aws/config/ContainerCaBundle.java @@ -181,6 +181,25 @@ public final class ContainerCaBundle { return certificates.toString(); } + /** + * The PEM a client must trust for Floci's HTTPS endpoint and the certificates Floci issues, served at + * {@code GET /_floci/ca.pem}: the local CA, {@code localCa}, alone by default. With a user-provided + * certificate the endpoint is signed by that certificate's issuer instead, so the certificates in the + * certificate file come first (never a private key it may also hold), then the local CA. A user-provided + * certificate is the one {@code TlsConfigSource} serves: TLS on, with both a certificate and a key path. + */ + public static String endpointTrustPem(EmulatorConfig config, String localCa) + throws IOException, GeneralSecurityException { + if (!config.tls().enabled() || config.tls().keyPath().filter(path -> !path.isBlank()).isEmpty()) { + return localCa; + } + Optional certificate = config.tls().certPath().filter(path -> !path.isBlank()); + if (certificate.isEmpty()) { + return localCa; + } + return certificatePem(Files.readString(Path.of(certificate.get()))) + localCa; + } + /** The {@code KEY=value} entries that make each runtime read {@link #CONTAINER_PATH}. */ public static List env() { return appendEnv(null); 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 d39ef1cd98..c977cee496 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 @@ -7,6 +7,8 @@ import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.eclipse.microprofile.config.inject.ConfigProperty; +import java.util.Optional; + /** * Computes the Floci base URL reachable from inside a Docker container that Floci launches. * @@ -24,7 +26,9 @@ import org.eclipse.microprofile.config.inject.ConfigProperty; * 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
  • + * {@link #baseUrl(boolean)} without the embedded DNS server, which a pod does not always resolve through + *
  • {@code EksClusterManager}, for the URL the k3s API server calls the Pod Identity admission webhook + * on, through {@link #httpsBaseUrl(boolean)}
  • * * *

    Lambda pods on Kubernetes do not use it: {@code KubernetesFlociAddressResolver} builds their @@ -98,8 +102,17 @@ public class ContainerReachableEndpoint { * check where http works, so that URL stays http. */ public String customResourceResponseBaseUrl() { - String host = host(true); - boolean https = tlsCertificates.serves(host); - return (https ? "https://" : "http://") + host + ":" + port(); + return httpsBaseUrl(true).orElseGet(this::baseUrl); + } + + /** + * {@link #baseUrl(boolean)} over https, when Floci serves TLS under a certificate that names its host, so + * a client that verifies the name accepts it. Empty otherwise: with TLS off, or for a host the certificate + * does not name, such as an IP from {@code docker-host-override}, the container-IP fallback, or a + * name a user-provided certificate was not issued for. + */ + public Optional httpsBaseUrl(boolean useEmbeddedDns) { + String host = host(useEmbeddedDns); + return tlsCertificates.serves(host) ? Optional.of("https://" + host + ":" + port()) : Optional.empty(); } } diff --git a/src/main/java/io/floci/aws/lifecycle/EmulatorInfoController.java b/src/main/java/io/floci/aws/lifecycle/EmulatorInfoController.java index 246ca7217d..3c917c07b0 100644 --- a/src/main/java/io/floci/aws/lifecycle/EmulatorInfoController.java +++ b/src/main/java/io/floci/aws/lifecycle/EmulatorInfoController.java @@ -22,13 +22,11 @@ import jakarta.ws.rs.core.Response; import org.jboss.logging.Logger; import java.io.IOException; -import java.nio.file.Files; import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import java.util.Optional; import java.util.TreeMap; @Path("{prefix:(_floci|_localstack)}") @@ -205,20 +203,7 @@ public class EmulatorInfoController { } private String trustBundle() throws IOException, GeneralSecurityException { - String localCa = certificateAuthority.caPem(); - Optional userCertificate = userCertificatePath(); - if (userCertificate.isEmpty()) { - return localCa; - } - return ContainerCaBundle.certificatePem(Files.readString(java.nio.file.Path.of(userCertificate.get()))) + localCa; - } - - /** Set when TLS serves a user-provided certificate, the same condition {@code TlsConfigSource} applies. */ - private Optional userCertificatePath() { - if (!config.tls().enabled() || config.tls().keyPath().filter(p -> !p.isBlank()).isEmpty()) { - return Optional.empty(); - } - return config.tls().certPath().filter(p -> !p.isBlank()); + return ContainerCaBundle.endpointTrustPem(config, certificateAuthority.caPem()); } @POST 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 ed03e22030..3094642277 100644 --- a/src/main/java/io/floci/aws/services/eks/EksClusterManager.java +++ b/src/main/java/io/floci/aws/services/eks/EksClusterManager.java @@ -7,6 +7,7 @@ import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.api.model.Container; import com.github.dockerjava.api.model.ContainerNetwork; import com.github.dockerjava.api.model.Info; +import io.floci.aws.config.ContainerCaBundle; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.config.FlociCertificateAuthority; import io.floci.aws.core.common.AwsArnUtils; @@ -27,6 +28,7 @@ import io.floci.aws.core.common.docker.ContainerLifecycleManager; import io.floci.aws.core.common.docker.ContainerLifecycleManager.ContainerInfo; import io.floci.aws.core.common.docker.ContainerLogStreamer; import io.floci.aws.core.common.docker.ContainerNetworks; +import io.floci.aws.core.common.docker.ContainerReachableEndpoint; import io.floci.aws.core.common.docker.ContainerSpec; import io.floci.aws.core.common.docker.ContainerStorageHelper; import io.floci.aws.core.common.docker.DockerHostResolver; @@ -85,6 +87,7 @@ import java.nio.file.attribute.PosixFilePermissions; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; +import java.util.Arrays; import java.util.Base64; import java.util.Comparator; import java.util.LinkedHashMap; @@ -105,6 +108,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.BiFunction; +import java.util.function.BooleanSupplier; import java.util.function.Consumer; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -150,6 +154,11 @@ public class EksClusterManager static final String CONTAINERD_CERTS_LINK = "etc/containerd/certs.d"; 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; + // The manifest while Floci registers no pod identity webhook: no objects, so k3s deletes what it held before. + static final String POD_IDENTITY_MANIFEST_REMOVED = """ + # Floci registers no EKS Pod Identity webhook for this cluster now; its log says why. + # k3s deletes the MutatingWebhookConfiguration an earlier version of this file created. + """; private static final String ENDPOINT_MODE_NETWORK = "network"; public static final String DEFAULT_POD_CIDR = "10.42.0.0/16"; @@ -191,6 +200,7 @@ public class EksClusterManager private final Ec2MetadataServer metadataServer; private final EksOidcService oidcService; private final FlociCertificateAuthority certificateAuthority; + private final ContainerReachableEndpoint reachableEndpoint; private final ContainerLogStreamer logStreamer; private final Ec2ImageCatalog imageCatalog; private final Ec2InstanceTypeCatalog instanceTypeCatalog = new Ec2InstanceTypeCatalog(); @@ -497,133 +507,6 @@ public class EksClusterManager entry -> clusterResourceName.equals(entry.getValue().clusterResourceName())); } - public EksClusterManager(ContainerBuilder containerBuilder, - ContainerLifecycleManager lifecycleManager, - ContainerDetector containerDetector, - PortAllocator portAllocator, - DockerHostResolver dockerHostResolver, - EcrRegistryManager ecrRegistryManager, - EmulatorConfig config, - RegionResolver regionResolver) { - this(containerBuilder, lifecycleManager, containerDetector, portAllocator, - dockerHostResolver, ecrRegistryManager, config, regionResolver, null, null, null, null); - } - - public EksClusterManager(ContainerBuilder containerBuilder, - ContainerLifecycleManager lifecycleManager, - ContainerDetector containerDetector, - PortAllocator portAllocator, - DockerHostResolver dockerHostResolver, - EcrRegistryManager ecrRegistryManager, - EmulatorConfig config, - RegionResolver regionResolver, - Ec2MetadataServer metadataServer) { - this(containerBuilder, lifecycleManager, containerDetector, portAllocator, - dockerHostResolver, ecrRegistryManager, config, regionResolver, metadataServer, null, 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, null); - } - - public EksClusterManager(ContainerBuilder containerBuilder, - ContainerLifecycleManager lifecycleManager, - ContainerDetector containerDetector, - PortAllocator portAllocator, - DockerHostResolver dockerHostResolver, - EcrRegistryManager ecrRegistryManager, - EmulatorConfig config, - RegionResolver regionResolver, - Ec2MetadataServer metadataServer, - EksOidcService oidcService, - FlociCertificateAuthority certificateAuthority) { - this(containerBuilder, lifecycleManager, containerDetector, portAllocator, - dockerHostResolver, ecrRegistryManager, config, regionResolver, metadataServer, oidcService, - certificateAuthority, null); - } - - public EksClusterManager(ContainerBuilder containerBuilder, - ContainerLifecycleManager lifecycleManager, - ContainerDetector containerDetector, - PortAllocator portAllocator, - DockerHostResolver dockerHostResolver, - EcrRegistryManager ecrRegistryManager, - EmulatorConfig config, - RegionResolver regionResolver, - Ec2MetadataServer metadataServer, - EksOidcService oidcService, - ContainerLogStreamer logStreamer) { - this(containerBuilder, lifecycleManager, containerDetector, portAllocator, - dockerHostResolver, ecrRegistryManager, config, regionResolver, metadataServer, oidcService, - null, logStreamer); - } - - public EksClusterManager(ContainerBuilder containerBuilder, - ContainerLifecycleManager lifecycleManager, - ContainerDetector containerDetector, - PortAllocator portAllocator, - DockerHostResolver dockerHostResolver, - EcrRegistryManager ecrRegistryManager, - EmulatorConfig config, - RegionResolver regionResolver, - Ec2MetadataServer metadataServer, - EksOidcService oidcService, - FlociCertificateAuthority certificateAuthority, - ContainerLogStreamer logStreamer) { - this(containerBuilder, lifecycleManager, containerDetector, portAllocator, - dockerHostResolver, ecrRegistryManager, config, regionResolver, metadataServer, - oidcService, certificateAuthority, logStreamer, (StorageBackend) null); - } - - public EksClusterManager(ContainerBuilder containerBuilder, - ContainerLifecycleManager lifecycleManager, - ContainerDetector containerDetector, - PortAllocator portAllocator, - DockerHostResolver dockerHostResolver, - EcrRegistryManager ecrRegistryManager, - EmulatorConfig config, - RegionResolver regionResolver, - Ec2MetadataServer metadataServer, - EksOidcService oidcService, - FlociCertificateAuthority certificateAuthority, - ContainerLogStreamer logStreamer, - StorageBackend nodeGroupStorage) { - this(containerBuilder, lifecycleManager, containerDetector, portAllocator, - dockerHostResolver, ecrRegistryManager, config, regionResolver, metadataServer, - oidcService, certificateAuthority, logStreamer, nodeGroupStorage, - RetryingTarCopier.DEFAULT_BACKOFF_MS); - } - - EksClusterManager(ContainerBuilder containerBuilder, - ContainerLifecycleManager lifecycleManager, - ContainerDetector containerDetector, - PortAllocator portAllocator, - DockerHostResolver dockerHostResolver, - EcrRegistryManager ecrRegistryManager, - EmulatorConfig config, - RegionResolver regionResolver, - Ec2MetadataServer metadataServer, - EksOidcService oidcService, - FlociCertificateAuthority certificateAuthority, - ContainerLogStreamer logStreamer, - StorageBackend nodeGroupStorage, - long archiveRetryBackoffMillis) { - this(containerBuilder, lifecycleManager, containerDetector, portAllocator, - dockerHostResolver, ecrRegistryManager, config, regionResolver, metadataServer, - oidcService, certificateAuthority, logStreamer, nodeGroupStorage, - archiveRetryBackoffMillis, new Ec2ImageCatalog()); - } - EksClusterManager(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager, ContainerDetector containerDetector, @@ -638,7 +521,8 @@ public class EksClusterManager ContainerLogStreamer logStreamer, StorageBackend nodeGroupStorage, long archiveRetryBackoffMillis, - Ec2ImageCatalog imageCatalog) { + Ec2ImageCatalog imageCatalog, + ContainerReachableEndpoint reachableEndpoint) { this.containerBuilder = containerBuilder; this.lifecycleManager = lifecycleManager; this.containerDetector = containerDetector; @@ -654,6 +538,7 @@ public class EksClusterManager this.nodeGroupStorage = nodeGroupStorage; this.archiveRetryBackoffMillis = archiveRetryBackoffMillis; this.imageCatalog = imageCatalog; + this.reachableEndpoint = reachableEndpoint; } @Inject @@ -670,14 +555,15 @@ public class EksClusterManager FlociCertificateAuthority certificateAuthority, ContainerLogStreamer logStreamer, StorageFactory storageFactory, - Ec2ImageCatalog imageCatalog) { + Ec2ImageCatalog imageCatalog, + ContainerReachableEndpoint reachableEndpoint) { this(containerBuilder, lifecycleManager, containerDetector, portAllocator, dockerHostResolver, ecrRegistryManager, config, regionResolver, metadataServer, oidcService, certificateAuthority, logStreamer, storageFactory != null ? storageFactory.create("eks", "eks-nodegroups.json", new TypeReference>() {}) - : null, RetryingTarCopier.DEFAULT_BACKOFF_MS, imageCatalog); + : null, RetryingTarCopier.DEFAULT_BACKOFF_MS, imageCatalog, reachableEndpoint); } /** @@ -1190,6 +1076,9 @@ public class EksClusterManager acquireClusterVpcLease(cluster, resolveClusterAccountId(cluster), clusterRegion(cluster), false); } recordClusterNodeInstance(cluster, info.containerId()); + // The manifest written at creation names the address and certificate Floci had then. + registerPodIdentityWebhook(info.containerId(), cluster, + () -> survivingNodeResolvesThroughFloci(info.containerId())); activeClusters.put(clusterResourceName(cluster), cluster); attachClusterLogs(cluster, true, true, false); @@ -2061,12 +1950,21 @@ public class EksClusterManager * 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)) { + if (EksClusterArgs.setsKubeletResolvConf(callerArgs)) { return null; } - return containerBuilder.embeddedDnsServerIpReachableOn(config.services().eks().dockerNetwork()) - .map(dnsServerIp -> "nameserver " + dnsServerIp + "\n") - .orElse(null); + return nodeDnsServerIp().map(dnsServerIp -> "nameserver " + dnsServerIp + "\n").orElse(null); + } + + /** + * Floci's embedded DNS server, when the cluster's node resolves through it: embedded DNS is on for EKS, so + * the node gets it as its resolver, and the server is running and reachable from the cluster's Docker network. + */ + private Optional nodeDnsServerIp() { + if (!config.services().eks().embeddedDns()) { + return Optional.empty(); + } + return containerBuilder.embeddedDnsServerIpReachableOn(config.services().eks().dockerNetwork()); } /** @@ -2704,10 +2602,27 @@ public class EksClusterManager * *

    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. + * warning in that case. The API server also checks that Floci's certificate names the URL's + * host, so the URL uses Floci's hostname when the node resolves through Floci's DNS, and the + * webhook is skipped with a warning when the certificate does not name the host. A skipped + * webhook still replaces the manifest, through {@link #removePodIdentityWebhook}. A failure + * here leaves the cluster running without pod identity injection, matching the token webhook + * and the ECR mirror. + * + *

    Also called when a surviving container is adopted: the manifest written at creation names + * Floci's address and certificate as they were then, and k3s applies the rewritten file. */ void registerPodIdentityWebhook(String containerId, Cluster cluster) { + registerPodIdentityWebhook(containerId, cluster, () -> nodeDnsServerIp().isPresent()); + } + + /** + * {@code nodeResolvesThroughFloci} answers whether the node finds Floci's hostname through Floci's DNS + * server. It is asked only once the webhook can be registered: an adopted node answers it with a Docker + * inspect. + */ + private void registerPodIdentityWebhook(String containerId, Cluster cluster, + BooleanSupplier nodeResolvesThroughFloci) { if (!config.services().eks().podIdentityWebhook()) { return; } @@ -2717,6 +2632,7 @@ public class EksClusterManager + "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); + removePodIdentityWebhook(containerId, cluster); return; } if (certificateAuthority == null) { @@ -2724,22 +2640,77 @@ public class EksClusterManager + "put in the webhook caBundle", clusterName); return; } - String url = "https://" + dockerHostResolver.resolve() + ":" + config.port() + boolean nodeUsesEmbeddedDns = nodeResolvesThroughFloci.getAsBoolean(); + Optional baseUrl = reachableEndpoint.httpsBaseUrl(nodeUsesEmbeddedDns); + if (baseUrl.isEmpty()) { + LOG.warnv("EKS Pod Identity injection is off for cluster {0}: the certificate Floci serves does not " + + "name the host of {1}, where the cluster''s API server would call the webhook, so it would " + + "refuse the handshake. Pods still start, without the pod identity token or credentials " + + "environment variables. To have them mutated, serve a certificate that names that host, or " + + "set FLOCI_HOSTNAME to a name the certificate covers while the cluster resolves through " + + "Floci''s embedded DNS (floci.services.eks.embedded-dns): the API server then calls Floci " + + "by that name.", clusterName, reachableEndpoint.baseUrl(nodeUsesEmbeddedDns)); + removePodIdentityWebhook(containerId, cluster); + return; + } + String url = baseUrl.get() + podIdentityWebhookPath(clusterName, resolveClusterAccountId(cluster), clusterRegion(cluster)); - String manifest = buildPodIdentityWebhookConfiguration(url, certificateAuthority.caPem()); - writeLocalCopy(localClusterFile(cluster, "webhook", POD_IDENTITY_MANIFEST_FILE), manifest, clusterName); try { - byte[] tar = tarSingleFile(POD_IDENTITY_MANIFEST_TAR_ENTRY, manifest); - RetryingTarCopier.copyStreamed(lifecycleManager.getDockerClient(), containerId, K3S_DATA_DIR, - POD_IDENTITY_MANIFEST_FILE, out -> out.write(tar), - RetryingTarCopier.DEFAULT_MAX_ATTEMPTS, archiveRetryBackoffMillis); + installPodIdentityManifest(containerId, cluster, buildPodIdentityWebhookConfiguration(url, + ContainerCaBundle.endpointTrustPem(config, certificateAuthority.caPem()))); 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 " + LOG.warnv("EKS cluster {0} gets no pod identity injection: could not install {1} into the k3s " + "container: {2}", clusterName, POD_IDENTITY_MANIFEST_FILE, e.getMessage()); } } + /** + * Replaces the manifest with {@link #POD_IDENTITY_MANIFEST_REMOVED}. The manifest, and the webhook + * configuration k3s created from it, live on the cluster's data volume, which outlives a restart and a + * replaced container, so a webhook registered under an earlier address, certificate or TLS setting would + * otherwise keep being called, each pod creation waiting out its timeout. k3s applies a changed manifest + * by pruning what the earlier version created, among the kinds it held, so a file with no objects deletes + * that configuration. + */ + private void removePodIdentityWebhook(String containerId, Cluster cluster) { + try { + installPodIdentityManifest(containerId, cluster, POD_IDENTITY_MANIFEST_REMOVED); + } catch (Exception e) { + LOG.warnv("EKS cluster {0} may keep a pod identity webhook registered before: could not replace {1} " + + "in the k3s container: {2}", cluster.getName(), POD_IDENTITY_MANIFEST_FILE, e.getMessage()); + } + } + + private void installPodIdentityManifest(String containerId, Cluster cluster, String manifest) { + writeLocalCopy(localClusterFile(cluster, "webhook", POD_IDENTITY_MANIFEST_FILE), manifest, cluster.getName()); + byte[] tar = tarSingleFile(POD_IDENTITY_MANIFEST_TAR_ENTRY, manifest); + RetryingTarCopier.copyStreamed(lifecycleManager.getDockerClient(), containerId, K3S_DATA_DIR, + POD_IDENTITY_MANIFEST_FILE, out -> out.write(tar), + RetryingTarCopier.DEFAULT_MAX_ATTEMPTS, archiveRetryBackoffMillis); + } + + /** + * Whether an adopted node resolves through Floci's DNS server. A container keeps the resolvers it was + * created with, so a node created while that server was off or out of its reach cannot find Floci's + * hostname now, nor can one created when the server had another address. + */ + private boolean survivingNodeResolvesThroughFloci(String containerId) { + Optional dnsServerIp = nodeDnsServerIp(); + if (dnsServerIp.isEmpty()) { + return false; + } + try { + InspectContainerResponse inspect = lifecycleManager.getDockerClient().inspectContainerCmd(containerId).exec(); + String[] resolvers = inspect.getHostConfig() == null ? null : inspect.getHostConfig().getDns(); + return resolvers != null && Arrays.asList(resolvers).contains(dnsServerIp.get()); + } catch (Exception e) { + LOG.warnv("Could not read the resolvers of k3s container {0}, so its pod identity webhook is called " + + "at the Docker host: {1}", containerId, e.getMessage()); + return false; + } + } + /** * 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 @@ -2752,8 +2723,8 @@ public class EksClusterManager /** * 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. + * from being created. The {@code caBundle} is what {@code GET /_floci/ca.pem} serves, which + * trusts Floci's HTTPS endpoint, base64 of the PEM as Kubernetes expects. * *

    {@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 diff --git a/src/test/java/io/floci/aws/config/ContainerCaBundleTest.java b/src/test/java/io/floci/aws/config/ContainerCaBundleTest.java index f712f5cf10..12ed5acf89 100644 --- a/src/test/java/io/floci/aws/config/ContainerCaBundleTest.java +++ b/src/test/java/io/floci/aws/config/ContainerCaBundleTest.java @@ -68,6 +68,41 @@ class ContainerCaBundleTest { System.clearProperty("floci.tls.enabled"); } + @Test + void endpointTrustIsTheConfiguredCertificatesThenTheLocalCa() throws Exception { + FlociCertificateAuthority configured = FlociCertificateAuthority.loadOrCreate(tempDir.resolve("configured")); + CertificateGenerator.GeneratedCertificate leaf = configured.issueServerCertificate("localhost", + List.of("localhost"), KeyAlgorithm.RSA_2048, null); + Path chain = Files.writeString(tempDir.resolve("chain.pem"), + leaf.certificatePem() + leaf.privateKeyPem() + configured.caPem()); + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.tls().enabled()).thenReturn(true); + when(config.tls().certPath()).thenReturn(Optional.of(chain.toString())); + when(config.tls().keyPath()).thenReturn(Optional.of(tempDir.resolve("server.key").toString())); + + String trust = ContainerCaBundle.endpointTrustPem(config, "local-ca"); + + assertEquals(ContainerCaBundle.certificatePem(leaf.certificatePem() + configured.caPem()) + "local-ca", trust); + assertFalse(trust.contains("PRIVATE KEY")); + } + + @Test + void endpointTrustKeepsLocalCaWithoutAnActiveConfiguredCertificate() throws Exception { + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.tls().certPath()).thenReturn(Optional.of("unreadable.pem")); + when(config.tls().keyPath()).thenReturn(Optional.of("server.key")); + when(config.tls().enabled()).thenReturn(false); + assertEquals("local-ca", ContainerCaBundle.endpointTrustPem(config, "local-ca")); + when(config.tls().enabled()).thenReturn(true); + when(config.tls().keyPath()).thenReturn(Optional.of(" ")); + assertEquals("local-ca", ContainerCaBundle.endpointTrustPem(config, "local-ca")); + when(config.tls().keyPath()).thenReturn(Optional.of("server.key")); + when(config.tls().certPath()).thenReturn(Optional.of(" ")); + assertEquals("local-ca", ContainerCaBundle.endpointTrustPem(config, "local-ca")); + when(config.tls().certPath()).thenReturn(Optional.empty()); + assertEquals("local-ca", ContainerCaBundle.endpointTrustPem(config, "local-ca")); + } + @Test void writeProducesTheSystemRootsFollowedByTheAnchor() throws Exception { Path tlsDir = tempDir.resolve("tls"); diff --git a/src/test/java/io/floci/aws/core/common/docker/ContainerReachableEndpointTest.java b/src/test/java/io/floci/aws/core/common/docker/ContainerReachableEndpointTest.java index adaf597406..9703ec1468 100644 --- a/src/test/java/io/floci/aws/core/common/docker/ContainerReachableEndpointTest.java +++ b/src/test/java/io/floci/aws/core/common/docker/ContainerReachableEndpointTest.java @@ -131,6 +131,32 @@ class ContainerReachableEndpointTest { assertEquals("http://172.18.0.2:4566", endpoint(4510).customResourceResponseBaseUrl()); } + @Test + void httpsBaseUrlWithoutEmbeddedDnsNamesTheDockerHostTheCertificateNames() { + // An EKS node that cannot use Floci's DNS server reaches Floci on the Docker host, which + // the self-signed certificate names when Floci runs natively. + when(tls.enabled()).thenReturn(true); + when(config.port()).thenReturn(4566); + lenient().when(embeddedDnsServer.getServerIp()).thenReturn(Optional.of("172.18.0.2")); + when(dockerHostResolver.resolve()).thenReturn("host.docker.internal"); + when(tlsCertificates.serves("host.docker.internal")).thenReturn(true); + + assertEquals(Optional.of("https://host.docker.internal:4566"), endpoint(4510).httpsBaseUrl(false)); + } + + @Test + void httpsBaseUrlIsEmptyForAHostTheCertificateDoesNotName() { + when(tls.enabled()).thenReturn(true); + when(config.hostname()).thenReturn(Optional.empty()); + when(embeddedDnsServer.getServerIp()).thenReturn(Optional.of("172.18.0.2")); + when(dockerHostResolver.resolve()).thenReturn("172.18.0.2"); + when(tlsCertificates.serves(EmbeddedDnsServer.DEFAULT_SUFFIX)).thenReturn(false); + when(tlsCertificates.serves("172.18.0.2")).thenReturn(false); + + assertEquals(Optional.empty(), endpoint(4510).httpsBaseUrl(true)); + assertEquals(Optional.empty(), endpoint(4510).httpsBaseUrl(false)); + } + @Test void customResourceResponseUrlIsHttpWithoutTls() { hostMappedTo4811(); diff --git a/src/test/java/io/floci/aws/services/eks/EksClusterGuestSetupTest.java b/src/test/java/io/floci/aws/services/eks/EksClusterGuestSetupTest.java index 050534152a..5e8b9515e7 100644 --- a/src/test/java/io/floci/aws/services/eks/EksClusterGuestSetupTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksClusterGuestSetupTest.java @@ -104,7 +104,7 @@ class EksClusterGuestSetupTest { when(lifecycleManager.create(any())).thenReturn(CONTAINER_ID); when(lifecycleManager.startCreated(any(), any())).thenReturn(new ContainerInfo(CONTAINER_ID, Map.of())); - manager = Mockito.spy(new EksClusterManager(containerBuilder, lifecycleManager, + manager = Mockito.spy(EksClusterManagers.create(containerBuilder, lifecycleManager, Mockito.mock(ContainerDetector.class), portAllocator, Mockito.mock(DockerHostResolver.class), Mockito.mock(EcrRegistryManager.class), config, Mockito.mock(RegionResolver.class))); @@ -352,7 +352,7 @@ class EksClusterGuestSetupTest { RegionResolver regionResolver = Mockito.mock(RegionResolver.class); when(regionResolver.getAccountId()).thenReturn("000000000000"); when(regionResolver.getDefaultRegion()).thenReturn("us-east-1"); - EksClusterManager logging = Mockito.spy(new EksClusterManager(containerBuilder, lifecycleManager, + EksClusterManager logging = Mockito.spy(EksClusterManagers.create(containerBuilder, lifecycleManager, Mockito.mock(ContainerDetector.class), portAllocator, Mockito.mock(DockerHostResolver.class), Mockito.mock(EcrRegistryManager.class), config, regionResolver, null, null, Mockito.mock(ContainerLogStreamer.class))); diff --git a/src/test/java/io/floci/aws/services/eks/EksClusterManagerArchiveRetryTest.java b/src/test/java/io/floci/aws/services/eks/EksClusterManagerArchiveRetryTest.java index 4d86998aa9..1477699e1c 100644 --- a/src/test/java/io/floci/aws/services/eks/EksClusterManagerArchiveRetryTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksClusterManagerArchiveRetryTest.java @@ -14,6 +14,7 @@ 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.ec2.Ec2ImageCatalog; import io.floci.aws.services.ecr.registry.EcrRegistryManager; import io.floci.aws.services.eks.model.Cluster; import io.floci.aws.services.eks.model.ClusterIdentity; @@ -126,7 +127,7 @@ class EksClusterManagerArchiveRetryTest { manager = new EksClusterManager(containerBuilder, lifecycleManager, mock(ContainerDetector.class), mock(PortAllocator.class), dockerHostResolver, mock(EcrRegistryManager.class), config, regionResolver, null, oidcService, certificateAuthority, - null, null, 0L); + null, null, 0L, new Ec2ImageCatalog(), EksTestEndpoints.dockerHostEndpoint()); } @Test diff --git a/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java b/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java index 6fb97236d7..6357988172 100644 --- a/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java @@ -16,6 +16,7 @@ import com.github.dockerjava.api.command.InspectVolumeCmd; import com.github.dockerjava.api.model.Container; import com.github.dockerjava.api.model.ContainerNetwork; import com.github.dockerjava.api.model.Frame; +import com.github.dockerjava.api.model.HostConfig; import com.github.dockerjava.api.model.Info; import com.github.dockerjava.api.model.NetworkSettings; import io.floci.aws.config.EmulatorConfig; @@ -32,6 +33,7 @@ import io.floci.aws.core.common.docker.ContainerExec; import io.floci.aws.core.common.docker.ContainerLifecycleManager; import io.floci.aws.core.common.docker.ContainerLifecycleManager.ContainerInfo; import io.floci.aws.core.common.docker.ContainerLogStreamer; +import io.floci.aws.core.common.docker.ContainerReachableEndpoint; import io.floci.aws.core.common.docker.ContainerSpec; import io.floci.aws.core.common.docker.DockerHostResolver; import io.floci.aws.core.common.docker.PortAllocator; @@ -457,7 +459,7 @@ class EksClusterManagerTest { when(regionResolver.buildGlobalArn(anyString(), anyString(), anyString())).thenAnswer(invocation -> "arn:aws:" + invocation.getArgument(0) + "::" + invocation.getArgument(1) + ":" + invocation.getArgument(2)); - EksClusterManager manager = new EksClusterManager(containerBuilder, lifecycleManager, + EksClusterManager manager = EksClusterManagers.create(containerBuilder, lifecycleManager, Mockito.mock(ContainerDetector.class), Mockito.mock(PortAllocator.class), Mockito.mock(DockerHostResolver.class), Mockito.mock(EcrRegistryManager.class), config, regionResolver); @@ -493,7 +495,7 @@ class EksClusterManagerTest { when(containerBuilder.newContainer(anyString())).thenReturn(builder); when(builder.build()).thenReturn(new ContainerSpec("test-image")); - EksClusterManager manager = new EksClusterManager(containerBuilder, lifecycleManager, + EksClusterManager manager = EksClusterManagers.create(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")); @@ -525,7 +527,7 @@ class EksClusterManagerTest { when(containerBuilder.newContainer(anyString())).thenReturn(builder); when(builder.build()).thenReturn(new ContainerSpec("test-image")); - EksClusterManager manager = new EksClusterManager(containerBuilder, lifecycleManager, + EksClusterManager manager = EksClusterManagers.create(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")); @@ -559,7 +561,7 @@ class EksClusterManagerTest { when(containerBuilder.newContainer(anyString())).thenReturn(builder); when(builder.build()).thenReturn(new ContainerSpec("test-image")); - EksClusterManager manager = new EksClusterManager(containerBuilder, lifecycleManager, + EksClusterManager manager = EksClusterManagers.create(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")); @@ -637,7 +639,7 @@ class EksClusterManagerTest { when(lifecycleManager.getDockerClient()).thenReturn(dockerClient); containerDetector = Mockito.mock(ContainerDetector.class); - manager = new EksClusterManager(containerBuilder, lifecycleManager, + manager = EksClusterManagers.create(containerBuilder, lifecycleManager, containerDetector, portAllocator, Mockito.mock(DockerHostResolver.class), Mockito.mock(EcrRegistryManager.class), config, Mockito.mock(RegionResolver.class)); @@ -1658,7 +1660,7 @@ class EksClusterManagerTest { DockerHostResolver dockerHostResolver = Mockito.mock(DockerHostResolver.class); when(dockerHostResolver.resolve()).thenReturn("floci"); - manager = new EksClusterManager( + manager = EksClusterManagers.create( Mockito.mock(ContainerBuilder.class), lifecycleManager, Mockito.mock(ContainerDetector.class), Mockito.mock(PortAllocator.class), dockerHostResolver, registryManager, config, @@ -1823,7 +1825,7 @@ class EksClusterManagerTest { when(lifecycleManager.getDockerClient()).thenReturn(dockerClient); when(dockerClient.copyArchiveToContainerCmd(anyString())).thenReturn(copyCmd); - manager = new EksClusterManager( + manager = EksClusterManagers.create( Mockito.mock(ContainerBuilder.class), lifecycleManager, Mockito.mock(ContainerDetector.class), Mockito.mock(PortAllocator.class), Mockito.mock(DockerHostResolver.class), Mockito.mock(EcrRegistryManager.class), @@ -1956,7 +1958,7 @@ class EksClusterManagerTest { when(containerResponse.getNetworkSettings()).thenReturn(netSettings); when(netSettings.getIpAddress()).thenReturn("172.17.0.2"); - manager = new EksClusterManager( + manager = EksClusterManagers.create( Mockito.mock(ContainerBuilder.class), lifecycleManager, Mockito.mock(ContainerDetector.class), Mockito.mock(PortAllocator.class), dockerHostResolver, Mockito.mock(EcrRegistryManager.class), @@ -2558,7 +2560,7 @@ class EksClusterManagerTest { addons = Mockito.mock(EksAddonService.class); when(addons.isInstalled(any(), eq(EksPodIdentityWebhook.POD_IDENTITY_ADDON))).thenReturn(true); - manager = new EksClusterManager( + manager = EksClusterManagers.create( Mockito.mock(ContainerBuilder.class), lifecycleManager, Mockito.mock(ContainerDetector.class), Mockito.mock(PortAllocator.class), dockerHostResolver, Mockito.mock(EcrRegistryManager.class), @@ -2801,7 +2803,7 @@ class EksClusterManagerTest { "https://oidc.eks.us-east-1.amazonaws.com/id/TESTISSUER12345678901234567890"); nodeGroupStorage = new InMemoryStorage<>(); - manager = new EksClusterManager(containerBuilder, lifecycleManager, + manager = EksClusterManagers.create(containerBuilder, lifecycleManager, Mockito.mock(ContainerDetector.class), Mockito.mock(PortAllocator.class), Mockito.mock(DockerHostResolver.class), Mockito.mock(EcrRegistryManager.class), config, regionResolver, null, oidcService, null, null, nodeGroupStorage); @@ -3747,7 +3749,7 @@ class EksClusterManagerTest { when(regionResolver.buildGlobalArn(anyString(), anyString(), anyString())).thenAnswer(invocation -> "arn:aws:" + invocation.getArgument(0) + "::" + invocation.getArgument(1) + ":" + invocation.getArgument(2)); - manager = new EksClusterManager(containerBuilder, lifecycleManager, + manager = EksClusterManagers.create(containerBuilder, lifecycleManager, Mockito.mock(ContainerDetector.class), portAllocator, Mockito.mock(DockerHostResolver.class), Mockito.mock(EcrRegistryManager.class), config, regionResolver, null, Mockito.mock(EksOidcService.class)); @@ -4052,7 +4054,10 @@ class EksClusterManagerTest { private EmulatorConfig.EksServiceConfig eks; private EmulatorConfig.TlsConfig tls; private ContainerLifecycleManager lifecycleManager; + private DockerClient dockerClient; private CopyArchiveToContainerCmd copyCmd; + private ContainerBuilder containerBuilder; + private ContainerReachableEndpoint reachableEndpoint; private EksClusterManager manager; @BeforeEach @@ -4074,7 +4079,7 @@ class EksClusterManagerTest { when(tls.enabled()).thenReturn(true); lifecycleManager = Mockito.mock(ContainerLifecycleManager.class); - DockerClient dockerClient = Mockito.mock(DockerClient.class); + dockerClient = Mockito.mock(DockerClient.class); copyCmd = Mockito.mock(CopyArchiveToContainerCmd.class, Mockito.RETURNS_SELF); when(lifecycleManager.getDockerClient()).thenReturn(dockerClient); when(dockerClient.copyArchiveToContainerCmd(anyString())).thenReturn(copyCmd); @@ -4082,7 +4087,7 @@ class EksClusterManagerTest { when(lifecycleManager.startCreated(any(), any())) .thenReturn(new ContainerInfo("container-1", Map.of())); - ContainerBuilder containerBuilder = Mockito.mock(ContainerBuilder.class); + 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(new ContainerSpec("test-image")); @@ -4099,11 +4104,56 @@ class EksClusterManagerTest { FlociCertificateAuthority certificateAuthority = inlineMock(FlociCertificateAuthority.class); when(certificateAuthority.caPem()).thenReturn(CA_PEM); + reachableEndpoint = EksTestEndpoints.dockerHostEndpoint(); + manager = new EksClusterManager( containerBuilder, lifecycleManager, Mockito.mock(ContainerDetector.class), Mockito.mock(PortAllocator.class), dockerHostResolver, Mockito.mock(EcrRegistryManager.class), config, - regionResolver, null, null, certificateAuthority); + regionResolver, null, null, certificateAuthority, null, null, 0L, new Ec2ImageCatalog(), + reachableEndpoint); + } + + private String writtenManifest() throws Exception { + return Files.readString(tempDir.resolve("webhook/000000000000/us-east-1/demo") + .resolve("floci-eks-pod-identity.yaml")); + } + + private String writtenCaBundle() throws Exception { + String encoded = writtenManifest().split("caBundle: \"")[1].split("\"")[0]; + return new String(Base64.getDecoder().decode(encoded), StandardCharsets.UTF_8); + } + + private void assertTheWebhookIsRemoved(String containerId) throws Exception { + verify(dockerClient).copyArchiveToContainerCmd(containerId); + verify(copyCmd).withRemotePath("/var/lib/rancher/k3s"); + assertEquals(EksClusterManager.POD_IDENTITY_MANIFEST_REMOVED, writtenManifest()); + } + + private Cluster adoptSurvivingCluster() { + when(lifecycleManager.findByName("floci-eks-demo")).thenReturn(Optional.of(containerFromJson( + "{\"Id\":\"cid-1\",\"Labels\":{\"io.floci.eks.node-capacity\":\"m5.large:unbounded\"," + + "\"io.floci.eks.shared-mounts\":\"true\"}}"))); + when(lifecycleManager.adopt("cid-1", List.of(6443), Optional.empty())) + .thenReturn(new ContainerInfo("cid-1", Map.of(), Map.of(6443, 6512))); + Cluster cluster = cluster(); + cluster.setDockerName("floci-eks-demo"); + manager.restoreCluster(cluster); + return cluster; + } + + private void flocisDnsServerIsUp() { + when(eks.embeddedDns()).thenReturn(true); + when(containerBuilder.embeddedDnsServerIpReachableOn(Optional.empty())).thenReturn(Optional.of("172.18.0.2")); + when(reachableEndpoint.httpsBaseUrl(true)).thenReturn(Optional.of("https://localhost.floci.io:4566")); + } + + private void survivingNodeResolvesThrough(String... resolvers) { + InspectContainerCmd inspect = Mockito.mock(InspectContainerCmd.class); + InspectContainerResponse response = Mockito.mock(InspectContainerResponse.class); + when(dockerClient.inspectContainerCmd("cid-1")).thenReturn(inspect); + when(inspect.exec()).thenReturn(response); + when(response.getHostConfig()).thenReturn(HostConfig.newHostConfig().withDns(resolvers)); } private Cluster cluster() { @@ -4158,12 +4208,120 @@ class EksClusterManagerTest { } @Test - void skipsWithAWarningWhenTlsIsDisabled() { + void theApiServerCallsFlociByItsHostnameWhenTheNodeResolvesThroughFlocisDns() throws Exception { + // Floci's own certificate names its hostname but not the container IP the Docker host is + // in a container, and the node finds the hostname through Floci's DNS server. + when(eks.embeddedDns()).thenReturn(true); + when(containerBuilder.embeddedDnsServerIpReachableOn(Optional.empty())).thenReturn(Optional.of("172.18.0.2")); + when(reachableEndpoint.httpsBaseUrl(true)).thenReturn(Optional.of("https://localhost.floci.io:4566")); + + manager.registerPodIdentityWebhook("container-1", cluster()); + + assertTrue(writtenManifest().contains("url: \"https://localhost.floci.io:4566" + + "/_floci/eks/clusters/demo/pod-identity-webhook/scope/000000000000/us-east-1\"")); + } + + @Test + void theApiServerCallsTheDockerHostWhenTheClusterCannotReachFlocisDns() throws Exception { + when(eks.embeddedDns()).thenReturn(true); + when(containerBuilder.embeddedDnsServerIpReachableOn(Optional.empty())).thenReturn(Optional.empty()); + when(reachableEndpoint.httpsBaseUrl(true)).thenReturn(Optional.of("https://localhost.floci.io:4566")); + + manager.registerPodIdentityWebhook("container-1", cluster()); + + assertTrue(writtenManifest().contains("url: \"https://host.docker.internal:4566/")); + } + + @Test + void theApiServerCallsTheDockerHostWhenTheNodeIsNotGivenFlocisDns() throws Exception { + when(eks.embeddedDns()).thenReturn(false); + when(containerBuilder.embeddedDnsServerIpReachableOn(Optional.empty())).thenReturn(Optional.of("172.18.0.2")); + when(reachableEndpoint.httpsBaseUrl(true)).thenReturn(Optional.of("https://localhost.floci.io:4566")); + + manager.registerPodIdentityWebhook("container-1", cluster()); + + assertTrue(writtenManifest().contains("url: \"https://host.docker.internal:4566/")); + } + + @Test + void aCertificateThatDoesNotNameTheHostRemovesTheWebhook() throws Exception { + // The API server checks the host against Floci's certificate, so it would refuse every call, and the + // cluster's data volume may hold a webhook registered under an earlier certificate. + when(reachableEndpoint.httpsBaseUrl(false)).thenReturn(Optional.empty()); + + manager.registerPodIdentityWebhook("container-1", cluster()); + + assertTheWebhookIsRemoved("container-1"); + } + + @Test + void theManifestThatRemovesTheWebhookHoldsNoObjects() { + // k3s prunes what an earlier version of a manifest created when the new one no longer holds it. + assertTrue(EksClusterManager.POD_IDENTITY_MANIFEST_REMOVED.lines() + .allMatch(line -> line.isBlank() || line.startsWith("#"))); + } + + @Test + void theCaBundleTrustsAConfiguredCertificateAndKeepsTheLocalCa() throws Exception { + FlociCertificateAuthority configured = FlociCertificateAuthority.loadOrCreate(tempDir.resolve("configured")); + when(tls.certPath()).thenReturn(Optional.of(configured.certificatePath().toString())); + when(tls.keyPath()).thenReturn(Optional.of(tempDir.resolve("server.key").toString())); + + manager.registerPodIdentityWebhook("container-1", cluster()); + + assertEquals(configured.caPem() + CA_PEM, writtenCaBundle()); + } + + @Test + void adoptingASurvivingClusterRewritesItsManifest() throws Exception { + // The manifest written at creation names the address and certificate Floci had then. + Cluster cluster = adoptSurvivingCluster(); + + assertEquals("cid-1", cluster.getContainerId()); + verify(lifecycleManager, never()).create(any()); + verify(dockerClient).copyArchiveToContainerCmd("cid-1"); + assertTrue(writtenManifest().contains("url: \"https://host.docker.internal:4566" + + "/_floci/eks/clusters/demo/pod-identity-webhook/scope/000000000000/us-east-1\"")); + } + + @Test + void anAdoptedNodeCreatedWithFlocisDnsCallsFlociByItsHostname() throws Exception { + flocisDnsServerIsUp(); + survivingNodeResolvesThrough("172.18.0.2", "8.8.8.8"); + + adoptSurvivingCluster(); + + assertTrue(writtenManifest().contains("url: \"https://localhost.floci.io:4566/")); + } + + @Test + void anAdoptedNodeCreatedWithoutFlocisDnsCallsTheDockerHost() throws Exception { + // A container keeps the resolvers it was created with, so the node cannot find Floci's hostname + // through a DNS server that was not up, or had another address, when it was created. + flocisDnsServerIsUp(); + survivingNodeResolvesThrough("172.18.0.9"); + + adoptSurvivingCluster(); + + assertTrue(writtenManifest().contains("url: \"https://host.docker.internal:4566/")); + } + + @Test + void tlsOffRemovesTheWebhook() throws Exception { when(tls.enabled()).thenReturn(false); manager.registerPodIdentityWebhook("container-1", cluster()); - verify(lifecycleManager, never()).getDockerClient(); + assertTheWebhookIsRemoved("container-1"); + } + + @Test + void adoptingAClusterOnceTlsIsOffRemovesItsWebhook() throws Exception { + when(tls.enabled()).thenReturn(false); + + adoptSurvivingCluster(); + + assertTheWebhookIsRemoved("cid-1"); } @Test @@ -4251,7 +4409,7 @@ class EksClusterManagerTest { when(logStreamer.attachPolledFromNowForAccount(anyString(), anyString(), anyString(), anyString(), anyString(), anyString())) .thenReturn(mockHandle); - manager = new EksClusterManager(containerBuilder, lifecycleManager, + manager = EksClusterManagers.create(containerBuilder, lifecycleManager, Mockito.mock(ContainerDetector.class), portAllocator, Mockito.mock(DockerHostResolver.class), Mockito.mock(EcrRegistryManager.class), config, regionResolver, null, null, logStreamer); @@ -4691,7 +4849,7 @@ class EksClusterManagerTest { when(regionResolver.buildGlobalArn(anyString(), anyString(), anyString())).thenAnswer(invocation -> "arn:aws:" + invocation.getArgument(0) + "::" + invocation.getArgument(1) + ":" + invocation.getArgument(2)); - manager = new EksClusterManager(containerBuilder, lifecycleManager, + manager = EksClusterManagers.create(containerBuilder, lifecycleManager, Mockito.mock(ContainerDetector.class), Mockito.mock(PortAllocator.class), Mockito.mock(DockerHostResolver.class), Mockito.mock(EcrRegistryManager.class), config, regionResolver); @@ -4812,7 +4970,7 @@ class EksClusterManagerTest { Mockito.mock(EcrRegistryManager.class), config, new RegionResolver("us-east-1", "000000000000"), Mockito.mock(Ec2MetadataServer.class), Mockito.mock(EksOidcService.class), inlineMock(FlociCertificateAuthority.class), Mockito.mock(ContainerLogStreamer.class), - new InMemoryStorage<>(), 0, new Ec2ImageCatalog(config))); + new InMemoryStorage<>(), 0, new Ec2ImageCatalog(config), EksTestEndpoints.dockerHostEndpoint())); } private Cluster clusterNamed(String name, String containerId) { @@ -5067,7 +5225,7 @@ class EksClusterManagerTest { ec2Service = Mockito.mock(Ec2Service.class); when(ec2Service.attachContainerToVpc(anyString(), anyString(), anyString(), anyString(), anyString(), anyString())) .thenReturn(Optional.of("floci-vpc-1")); - manager = new EksClusterManager(containerBuilder, lifecycleManager, + manager = EksClusterManagers.create(containerBuilder, lifecycleManager, Mockito.mock(ContainerDetector.class), portAllocator, Mockito.mock(DockerHostResolver.class), Mockito.mock(EcrRegistryManager.class), config, regionResolver); diff --git a/src/test/java/io/floci/aws/services/eks/EksClusterManagers.java b/src/test/java/io/floci/aws/services/eks/EksClusterManagers.java new file mode 100644 index 0000000000..2bd54c05fc --- /dev/null +++ b/src/test/java/io/floci/aws/services/eks/EksClusterManagers.java @@ -0,0 +1,154 @@ +package io.floci.aws.services.eks; + +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.config.FlociCertificateAuthority; +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.ContainerLogStreamer; +import io.floci.aws.core.common.docker.DockerHostResolver; +import io.floci.aws.core.common.docker.PortAllocator; +import io.floci.aws.core.common.docker.RetryingTarCopier; +import io.floci.aws.core.storage.StorageBackend; +import io.floci.aws.services.ec2.Ec2ImageCatalog; +import io.floci.aws.services.ec2.Ec2MetadataServer; +import io.floci.aws.services.ecr.registry.EcrRegistryManager; +import io.floci.aws.services.eks.model.Nodegroup; + +/** + * Cluster managers for tests that leave some collaborators out. Each one left out is null, the + * archive retry backoff is the default, and the Floci endpoint is {@link EksTestEndpoints#dockerHostEndpoint()}. + */ +final class EksClusterManagers { + + private EksClusterManagers() { + } + + static EksClusterManager create(ContainerBuilder containerBuilder, + ContainerLifecycleManager lifecycleManager, + ContainerDetector containerDetector, + PortAllocator portAllocator, + DockerHostResolver dockerHostResolver, + EcrRegistryManager ecrRegistryManager, + EmulatorConfig config, + RegionResolver regionResolver) { + return create(containerBuilder, lifecycleManager, containerDetector, portAllocator, + dockerHostResolver, ecrRegistryManager, config, regionResolver, null, null, null, null); + } + + static EksClusterManager create(ContainerBuilder containerBuilder, + ContainerLifecycleManager lifecycleManager, + ContainerDetector containerDetector, + PortAllocator portAllocator, + DockerHostResolver dockerHostResolver, + EcrRegistryManager ecrRegistryManager, + EmulatorConfig config, + RegionResolver regionResolver, + Ec2MetadataServer metadataServer) { + return create(containerBuilder, lifecycleManager, containerDetector, portAllocator, + dockerHostResolver, ecrRegistryManager, config, regionResolver, metadataServer, null, null, null); + } + + static EksClusterManager create(ContainerBuilder containerBuilder, + ContainerLifecycleManager lifecycleManager, + ContainerDetector containerDetector, + PortAllocator portAllocator, + DockerHostResolver dockerHostResolver, + EcrRegistryManager ecrRegistryManager, + EmulatorConfig config, + RegionResolver regionResolver, + Ec2MetadataServer metadataServer, + EksOidcService oidcService) { + return create(containerBuilder, lifecycleManager, containerDetector, portAllocator, + dockerHostResolver, ecrRegistryManager, config, regionResolver, metadataServer, oidcService, null, null); + } + + static EksClusterManager create(ContainerBuilder containerBuilder, + ContainerLifecycleManager lifecycleManager, + ContainerDetector containerDetector, + PortAllocator portAllocator, + DockerHostResolver dockerHostResolver, + EcrRegistryManager ecrRegistryManager, + EmulatorConfig config, + RegionResolver regionResolver, + Ec2MetadataServer metadataServer, + EksOidcService oidcService, + FlociCertificateAuthority certificateAuthority) { + return create(containerBuilder, lifecycleManager, containerDetector, portAllocator, + dockerHostResolver, ecrRegistryManager, config, regionResolver, metadataServer, oidcService, + certificateAuthority, null); + } + + static EksClusterManager create(ContainerBuilder containerBuilder, + ContainerLifecycleManager lifecycleManager, + ContainerDetector containerDetector, + PortAllocator portAllocator, + DockerHostResolver dockerHostResolver, + EcrRegistryManager ecrRegistryManager, + EmulatorConfig config, + RegionResolver regionResolver, + Ec2MetadataServer metadataServer, + EksOidcService oidcService, + ContainerLogStreamer logStreamer) { + return create(containerBuilder, lifecycleManager, containerDetector, portAllocator, + dockerHostResolver, ecrRegistryManager, config, regionResolver, metadataServer, oidcService, + null, logStreamer); + } + + static EksClusterManager create(ContainerBuilder containerBuilder, + ContainerLifecycleManager lifecycleManager, + ContainerDetector containerDetector, + PortAllocator portAllocator, + DockerHostResolver dockerHostResolver, + EcrRegistryManager ecrRegistryManager, + EmulatorConfig config, + RegionResolver regionResolver, + Ec2MetadataServer metadataServer, + EksOidcService oidcService, + FlociCertificateAuthority certificateAuthority, + ContainerLogStreamer logStreamer) { + return create(containerBuilder, lifecycleManager, containerDetector, portAllocator, + dockerHostResolver, ecrRegistryManager, config, regionResolver, metadataServer, + oidcService, certificateAuthority, logStreamer, (StorageBackend) null); + } + + static EksClusterManager create(ContainerBuilder containerBuilder, + ContainerLifecycleManager lifecycleManager, + ContainerDetector containerDetector, + PortAllocator portAllocator, + DockerHostResolver dockerHostResolver, + EcrRegistryManager ecrRegistryManager, + EmulatorConfig config, + RegionResolver regionResolver, + Ec2MetadataServer metadataServer, + EksOidcService oidcService, + FlociCertificateAuthority certificateAuthority, + ContainerLogStreamer logStreamer, + StorageBackend nodeGroupStorage) { + return create(containerBuilder, lifecycleManager, containerDetector, portAllocator, + dockerHostResolver, ecrRegistryManager, config, regionResolver, metadataServer, + oidcService, certificateAuthority, logStreamer, nodeGroupStorage, + RetryingTarCopier.DEFAULT_BACKOFF_MS); + } + + static EksClusterManager create(ContainerBuilder containerBuilder, + ContainerLifecycleManager lifecycleManager, + ContainerDetector containerDetector, + PortAllocator portAllocator, + DockerHostResolver dockerHostResolver, + EcrRegistryManager ecrRegistryManager, + EmulatorConfig config, + RegionResolver regionResolver, + Ec2MetadataServer metadataServer, + EksOidcService oidcService, + FlociCertificateAuthority certificateAuthority, + ContainerLogStreamer logStreamer, + StorageBackend nodeGroupStorage, + long archiveRetryBackoffMillis) { + return new EksClusterManager(containerBuilder, lifecycleManager, containerDetector, portAllocator, + dockerHostResolver, ecrRegistryManager, config, regionResolver, metadataServer, + oidcService, certificateAuthority, logStreamer, nodeGroupStorage, + archiveRetryBackoffMillis, new Ec2ImageCatalog(), EksTestEndpoints.dockerHostEndpoint()); + } +} diff --git a/src/test/java/io/floci/aws/services/eks/EksClusterPodResolvConfTest.java b/src/test/java/io/floci/aws/services/eks/EksClusterPodResolvConfTest.java index 55ad495d34..6606d93c87 100644 --- a/src/test/java/io/floci/aws/services/eks/EksClusterPodResolvConfTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksClusterPodResolvConfTest.java @@ -98,7 +98,7 @@ class EksClusterPodResolvConfTest { return copyCmd; }); - manager = new EksClusterManager(containerBuilder, lifecycleManager, + manager = EksClusterManagers.create(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); diff --git a/src/test/java/io/floci/aws/services/eks/EksTestEndpoints.java b/src/test/java/io/floci/aws/services/eks/EksTestEndpoints.java new file mode 100644 index 0000000000..07d405e119 --- /dev/null +++ b/src/test/java/io/floci/aws/services/eks/EksTestEndpoints.java @@ -0,0 +1,24 @@ +package io.floci.aws.services.eks; + +import io.floci.aws.core.common.docker.ContainerReachableEndpoint; + +import java.util.Optional; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** The Floci endpoint EKS tests give the cluster manager: the Docker host, under a certificate that names it. */ +final class EksTestEndpoints { + + static final String DOCKER_HOST_HTTPS = "https://host.docker.internal:4566"; + + private EksTestEndpoints() { + } + + static ContainerReachableEndpoint dockerHostEndpoint() { + ContainerReachableEndpoint endpoint = mock(ContainerReachableEndpoint.class); + when(endpoint.httpsBaseUrl(false)).thenReturn(Optional.of(DOCKER_HOST_HTTPS)); + when(endpoint.baseUrl(false)).thenReturn("http://host.docker.internal:4566"); + return endpoint; + } +}