Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(eks): make real-mode clusters reachable and authenticable from the host (#1167)

Hector Ventura7128758a631a
diff --git a/docs/services/eks.md b/docs/services/eks.md
index f5c76779d6..e4cec5d86c 100644
--- a/docs/services/eks.md
+++ b/docs/services/eks.md
@@ -27,6 +27,26 @@ Cluster metadata is stored in-process. No Docker containers are started. The clu
Floci starts a **k3s** (`rancher/k3s`) container for each cluster. The k3s API server is exposed on a host port from the configured range (`6500–6599`). Once `/readyz` responds, the cluster transitions to `ACTIVE` and the CA certificate is extracted from the kubeconfig.
+By default `describe-cluster` returns a **host-reachable** endpoint (`https://localhost:<hostPort>`); the k3s server certificate includes a `localhost` SAN, so it verifies against the CA in `cluster.certificateAuthority.data`. Set `endpoint-mode: network` to return the container DNS name (`https://floci-eks-<name>:6443`) instead — reachable from other containers on the Docker network (the pre-#1118 behaviour). In `network` mode the endpoint falls back to the host-reachable form when Floci runs natively, since there is no container DNS name a host client could use.
+
+#### Connecting with `kubectl` (native AWS workflow)
+
+The standard AWS flow works end to end:
+
+```bash
+aws eks update-kubeconfig --name my-cluster
+kubectl get nodes
+```
+
+`aws eks update-kubeconfig` wires `aws eks get-token` into the kubeconfig as an exec credential. The bearer token it produces is validated by a **token-authentication webhook** that Floci wires into k3s: the k3s API server POSTs a Kubernetes `TokenReview` to Floci's `/_floci/eks/token-webhook` endpoint, and Floci maps the token to the `system:masters` group (bound to `cluster-admin`). No `aws-iam-authenticator` is required.
+
+This webhook is enabled by default (`iam-auth-webhook: true`). Set it to `false` to start k3s without it (in which case `aws eks get-token` tokens are rejected with `401`).
+
+!!! note "Webhook reachability & networking"
+ The k3s API server must be able to reach Floci's webhook URL. When Floci runs natively, k3s containers reach it via `host.docker.internal`; when Floci runs in a container (`floci start`), Floci and the k3s containers share a Docker network. The k3s network is taken from `FLOCI_SERVICES_EKS_DOCKER_NETWORK` if set, otherwise the global `FLOCI_SERVICES_DOCKER_NETWORK`, otherwise the network Floci is itself attached to (auto-detected) — so no EKS-specific network configuration is required in the standard compose setup.
+
+ The webhook kubeconfig is copied into the k3s container via the Docker API (not bind-mounted), so the token-webhook works the same in native and Docker-in-Docker modes with **no host-path / `host-persistent-path` configuration**.
+
!!! note "Docker socket required"
Real mode starts privileged Docker containers. Mount the Docker socket and set the Docker network so containers can reach each other.
@@ -55,8 +75,10 @@ services:
| `FLOCI_SERVICES_EKS_API_SERVER_BASE_PORT` | `6500` | First port in the k3s API server range |
| `FLOCI_SERVICES_EKS_API_SERVER_MAX_PORT` | `6599` | Last port in the k3s API server range |
| `FLOCI_SERVICES_EKS_DATA_PATH` | `./data/eks` | Host bind-mount root for cluster data |
-| `FLOCI_SERVICES_EKS_DOCKER_NETWORK` | *(unset)* | Docker network for k3s containers |
+| `FLOCI_SERVICES_EKS_DOCKER_NETWORK` | *(unset)* | Docker network for k3s containers (falls back to the global `FLOCI_SERVICES_DOCKER_NETWORK`, then Floci's own network) |
| `FLOCI_SERVICES_EKS_KEEP_RUNNING_ON_SHUTDOWN` | `false` | Leave k3s containers running after Floci stops |
+| `FLOCI_SERVICES_EKS_ENDPOINT_MODE` | `host` | `describe-cluster` endpoint: `host` (`localhost:<hostPort>`) or `network` (container DNS) |
+| `FLOCI_SERVICES_EKS_IAM_AUTH_WEBHOOK` | `true` | Wire a token-auth webhook into k3s so `aws eks get-token` works |
### Mock mode (CI / tests)
diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
index 1d6f2a7309..c720e97614 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -988,6 +988,27 @@ public interface EmulatorConfig {
@WithDefault("false")
boolean keepRunningOnShutdown();
+
+ /**
+ * Controls the endpoint that {@code describe-cluster} returns in real mode:
+ * <ul>
+ * <li>{@code host} (default) — {@code https://localhost:<hostPort>}, reachable from the
+ * host so {@code kubectl}/{@code aws eks} work out of the box.</li>
+ * <li>{@code network} — the container DNS name {@code https://floci-eks-<name>:6443},
+ * reachable from other containers on the Docker network (pre-#1118 behaviour). Falls
+ * back to the host endpoint when Floci runs natively.</li>
+ * </ul>
+ */
+ @WithDefault("host")
+ String endpointMode();
+
+ /**
+ * When true, wires a token-authentication webhook into k3s so that the bearer token
+ * produced by {@code aws eks get-token} is validated by Floci and mapped to cluster-admin.
+ * This makes the native {@code aws eks update-kubeconfig} + {@code kubectl} flow work.
+ */
+ @WithDefault("true")
+ boolean iamAuthWebhook();
}
interface InitHooksConfig {
diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java
index c3216ecfaa..0fb1e3a62e 100644
--- a/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java
+++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
+import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
import io.github.hectorvent.floci.core.common.docker.PortAllocator;
import io.github.hectorvent.floci.services.eks.model.CertificateAuthority;
import io.github.hectorvent.floci.services.eks.model.Cluster;
@@ -22,6 +23,8 @@ import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
@@ -35,10 +38,16 @@ public class EksClusterManager {
private static final Logger LOG = Logger.getLogger(EksClusterManager.class);
private static final int K3S_API_SERVER_PORT = 6443;
+ private static final String WEBHOOK_CONFIG_DIR = "/etc";
+ private static final String WEBHOOK_CONFIG_FILE = "token-webhook.yaml";
+ private static final String WEBHOOK_CONFIG_PATH = WEBHOOK_CONFIG_DIR + "/" + WEBHOOK_CONFIG_FILE;
+ private static final String ENDPOINT_MODE_NETWORK = "network";
+
private final ContainerBuilder containerBuilder;
private final ContainerLifecycleManager lifecycleManager;
private final ContainerDetector containerDetector;
private final PortAllocator portAllocator;
+ private final DockerHostResolver dockerHostResolver;
private final EmulatorConfig config;
@Inject
@@ -46,11 +55,13 @@ public class EksClusterManager {
ContainerLifecycleManager lifecycleManager,
ContainerDetector containerDetector,
PortAllocator portAllocator,
+ DockerHostResolver dockerHostResolver,
EmulatorConfig config) {
this.containerBuilder = containerBuilder;
this.lifecycleManager = lifecycleManager;
this.containerDetector = containerDetector;
this.portAllocator = portAllocator;
+ this.dockerHostResolver = dockerHostResolver;
this.config = config;
}
@@ -71,6 +82,8 @@ public class EksClusterManager {
config.services().eks().apiServerBasePort(),
config.services().eks().apiServerMaxPort());
+ cluster.setHostPort(hostPort);
+
// Remove any stale container
lifecycleManager.removeIfExists(containerName);
@@ -84,41 +97,67 @@ public class EksClusterManager {
// k3s before it can start. Named volumes live in the Docker VM's Linux
// filesystem, so chmod works correctly and data persists across container restarts.
String volumeName = "floci-eks-" + cluster.getName();
- ContainerSpec spec = containerBuilder.newContainer(image)
+
+ List<String> serverArgs = new ArrayList<>(List.of("server",
+ "--disable=traefik",
+ "--tls-san=localhost"));
+
+ ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)
.withName(containerName)
- .withCmd(List.of("server",
- "--disable=traefik",
- "--tls-san=localhost"))
.withEnv("K3S_KUBECONFIG_MODE", "644")
.withPortBinding(K3S_API_SERVER_PORT, hostPort)
.withNamedVolume(volumeName, "/var/lib/rancher/k3s")
.withDockerNetwork(config.services().eks().dockerNetwork())
.withPrivileged(true)
- .withLogRotation()
- .build();
+ .withLogRotation();
+
+ // Wire a token-authentication webhook so `aws eks get-token` bearer tokens are validated by
+ // Floci and mapped to cluster-admin. The k3s API server POSTs a TokenReview to Floci's
+ // _floci/eks/token-webhook endpoint. The kubeconfig is copied into the container via the
+ // Docker API after create and before start (below) — not bind-mounted — so it works the same
+ // natively and in Docker-in-Docker, with no host-path / host-persistent-path requirement.
+ String webhookLocalFile = null;
+ if (config.services().eks().iamAuthWebhook()) {
+ webhookLocalFile = writeWebhookKubeconfig(cluster.getName());
+ if (webhookLocalFile != null) {
+ specBuilder.withHostDockerInternalOnLinux();
+ serverArgs.add("--kube-apiserver-arg=authentication-token-webhook-config-file="
+ + WEBHOOK_CONFIG_PATH);
+ serverArgs.add("--kube-apiserver-arg=authentication-token-webhook-version=v1");
+ serverArgs.add("--kube-apiserver-arg=authentication-token-webhook-cache-ttl=30s");
+ }
+ }
+
+ ContainerSpec spec = specBuilder.withCmd(serverArgs).build();
+
+ // create -> inject webhook kubeconfig -> start, so the file exists before the API server boots.
+ String containerId = lifecycleManager.create(spec);
+ cluster.setContainerId(containerId);
+ if (webhookLocalFile != null) {
+ copyWebhookIntoContainer(containerId, webhookLocalFile, cluster.getName());
+ }
+ ContainerInfo info = lifecycleManager.startCreated(containerId, spec);
- ContainerInfo info = lifecycleManager.createAndStart(spec);
- cluster.setContainerId(info.containerId());
+ // Public endpoint: see floci.services.eks.endpoint-mode. `host` (default) is the host-reachable
+ // published port (k3s cert carries `--tls-san=localhost`, so it verifies against the CA that
+ // describe-cluster returns); `network` is the container DNS name (pre-#1118 behaviour).
+ cluster.setEndpoint(resolvePublicEndpoint(
+ containerDetector.isRunningInContainer(), config.services().eks().endpointMode(),
+ containerName, hostPort));
- // Public endpoint uses the container name (DNS-resolvable on user-defined networks).
- // Internal endpoint uses the resolved IP from ContainerLifecycleManager so the
- // readiness poller works on the default bridge network where container-name DNS
- // is not available.
+ // Internal endpoint uses the resolved container IP so the readiness poller works from inside
+ // the Docker network (where localhost:<hostPort> would not reach the k3s container).
if (containerDetector.isRunningInContainer()) {
- cluster.setEndpoint("https://" + containerName + ":" + K3S_API_SERVER_PORT);
ContainerLifecycleManager.EndpointInfo ep = info.getEndpoint(K3S_API_SERVER_PORT);
- if (ep != null) {
- cluster.setInternalEndpoint("https://" + ep.host() + ":" + ep.port());
- } else {
- cluster.setInternalEndpoint(cluster.getEndpoint());
- }
+ cluster.setInternalEndpoint(ep != null
+ ? "https://" + ep.host() + ":" + ep.port()
+ : "https://localhost:" + hostPort);
} else {
- cluster.setEndpoint("https://localhost:" + hostPort);
- cluster.setInternalEndpoint(cluster.getEndpoint());
+ cluster.setInternalEndpoint("https://localhost:" + hostPort);
}
LOG.infov("k3s container {0} started for cluster {1} on port {2} (internal: {3})",
- info.containerId(), cluster.getName(), String.valueOf(hostPort), cluster.getInternalEndpoint());
+ containerId, cluster.getName(), String.valueOf(hostPort), cluster.getInternalEndpoint());
}
/**
@@ -195,6 +234,86 @@ public class EksClusterManager {
LOG.infov("Stopped k3s container for cluster {0}", cluster.getName());
}
+ /**
+ * Resolves the public {@code describe-cluster} endpoint. Returns the container DNS name only when
+ * Floci runs in a container and {@code endpoint-mode=network}; otherwise the host-reachable
+ * published port (the default, and the only usable value in native mode).
+ */
+ static String resolvePublicEndpoint(boolean inContainer, String endpointMode,
+ String containerName, int hostPort) {
+ if (inContainer && ENDPOINT_MODE_NETWORK.equalsIgnoreCase(endpointMode)) {
+ return "https://" + containerName + ":" + K3S_API_SERVER_PORT;
+ }
+ return "https://localhost:" + hostPort;
+ }
+
+ /**
+ * Writes the token-webhook kubeconfig for the given cluster to Floci's local filesystem and
+ * returns its path (basename {@value #WEBHOOK_CONFIG_FILE}), or {@code null} if it could not be
+ * written (in which case the caller skips the webhook so cluster creation still succeeds). The
+ * file is later streamed into the container via the Docker API, so no host path is involved.
+ */
+ private String writeWebhookKubeconfig(String clusterName) {
+ Path localFile = Paths.get(config.services().eks().dataPath(), "webhook", clusterName, WEBHOOK_CONFIG_FILE)
+ .toAbsolutePath().normalize();
+ try {
+ Files.createDirectories(localFile.getParent());
+ Files.writeString(localFile, buildWebhookKubeconfig(webhookUrl()));
+ } catch (IOException e) {
+ LOG.warnv("EKS token-webhook disabled for cluster {0}: could not write kubeconfig: {1}",
+ clusterName, e.getMessage());
+ return null;
+ }
+ return localFile.toString();
+ }
+
+ /**
+ * Streams the webhook kubeconfig from Floci's filesystem into the (created, not-yet-started)
+ * k3s container at {@value #WEBHOOK_CONFIG_PATH}, using the Docker API. Reading the file
+ * client-side avoids any host bind-mount, so this works in native and Docker-in-Docker modes
+ * alike. A failure here disables the webhook for the cluster but does not abort its startup.
+ */
+ private void copyWebhookIntoContainer(String containerId, String localFile, String clusterName) {
+ try {
+ lifecycleManager.getDockerClient()
+ .copyArchiveToContainerCmd(containerId)
+ .withHostResource(localFile)
+ .withRemotePath(WEBHOOK_CONFIG_DIR)
+ .exec();
+ } catch (Exception e) {
+ LOG.warnv("EKS token-webhook may not authenticate for cluster {0}: could not copy kubeconfig "
+ + "into the k3s container: {1}", clusterName, e.getMessage());
+ }
+ }
+
+ /** The Floci token-webhook URL as reachable from inside the k3s container. */
+ String webhookUrl() {
+ return "http://" + dockerHostResolver.resolve() + ":" + config.port() + "/_floci/eks/token-webhook";
+ }
+
+ /**
+ * Builds a minimal kubeconfig that points the k3s API server's token-authentication webhook
+ * at Floci. The webhook server uses anonymous access (no client credentials needed).
+ */
+ static String buildWebhookKubeconfig(String serverUrl) {
+ return """
+ apiVersion: v1
+ kind: Config
+ clusters:
+ - name: floci-token-webhook
+ cluster:
+ server: %s
+ users:
+ - name: floci-token-webhook
+ contexts:
+ - name: floci-token-webhook
+ context:
+ cluster: floci-token-webhook
+ user: floci-token-webhook
+ current-context: floci-token-webhook
+ """.formatted(serverUrl);
+ }
+
private String execInContainer(String containerId, String[] cmd) throws Exception {
var dockerClient = lifecycleManager.getDockerClient();
ExecCreateCmdResponse exec = dockerClient
diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksTokenWebhookController.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksTokenWebhookController.java
new file mode 100644
index 0000000000..b970d24902
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksTokenWebhookController.java
@@ -0,0 +1,80 @@
+package io.github.hectorvent.floci.services.eks;
+
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.ws.rs.Consumes;
+import jakarta.ws.rs.POST;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import org.jboss.logging.Logger;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Kubernetes token-authentication webhook for k3s-backed EKS clusters.
+ *
+ * <p>The k3s API server is configured (see {@code EksClusterManager}) to POST a
+ * {@code TokenReview} here whenever it receives a bearer token it does not recognise — notably the
+ * {@code k8s-aws-v1.<presigned-sts-url>} token produced by {@code aws eks get-token}. Floci accepts
+ * the token and maps it to the {@code system:masters} group, which is bound to {@code cluster-admin}
+ * by default. This is what makes the native {@code aws eks update-kubeconfig} + {@code kubectl}
+ * workflow authenticate against a Floci EKS cluster.
+ *
+ * <p>This is Floci plumbing under the {@code _floci/...} namespace, not an AWS API.
+ */
+@ApplicationScoped
+@Path("_floci/eks/token-webhook")
+@Produces(MediaType.APPLICATION_JSON)
+@Consumes(MediaType.APPLICATION_JSON)
+public class EksTokenWebhookController {
+
+ private static final Logger LOG = Logger.getLogger(EksTokenWebhookController.class);
+ private static final String EKS_TOKEN_PREFIX = "k8s-aws-v1.";
+
+ @POST
+ public Response review(Map<String, Object> tokenReview) {
+ // The response apiVersion MUST match the request's (the kube-apiserver sends v1beta1 by
+ // default and cannot convert a v1 response back). Echo whatever the apiserver sent.
+ String apiVersion = tokenReview != null && tokenReview.get("apiVersion") instanceof String v
+ ? v : "authentication.k8s.io/v1";
+
+ String token = extractToken(tokenReview);
+ boolean authenticated = token != null && token.startsWith(EKS_TOKEN_PREFIX);
+
+ if (authenticated) {
+ LOG.debug("EKS token-webhook: authenticated aws-iam token as cluster-admin");
+ return Response.ok(Map.of(
+ "apiVersion", apiVersion,
+ "kind", "TokenReview",
+ "status", Map.of(
+ "authenticated", true,
+ "user", Map.of(
+ "username", "floci:aws-iam",
+ "uid", "floci-aws-iam",
+ "groups", List.of("system:masters"))))).build();
+ }
+
+ LOG.debug("EKS token-webhook: rejecting unrecognised token");
+ return Response.ok(Map.of(
+ "apiVersion", apiVersion,
+ "kind", "TokenReview",
+ "status", Map.of("authenticated", false))).build();
+ }
+
+ @SuppressWarnings("unchecked")
+ private String extractToken(Map<String, Object> tokenReview) {
+ if (tokenReview == null) {
+ return null;
+ }
+ Object spec = tokenReview.get("spec");
+ if (spec instanceof Map<?, ?> specMap) {
+ Object token = ((Map<String, Object>) specMap).get("token");
+ if (token instanceof String s) {
+ return s;
+ }
+ }
+ return null;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/model/Cluster.java b/src/main/java/io/github/hectorvent/floci/services/eks/model/Cluster.java
index 2817812d5d..88511aa2ae 100644
--- a/src/main/java/io/github/hectorvent/floci/services/eks/model/Cluster.java
+++ b/src/main/java/io/github/hectorvent/floci/services/eks/model/Cluster.java
@@ -59,6 +59,9 @@ public class Cluster {
@JsonIgnore
private String internalEndpoint;
+ @JsonIgnore
+ private int hostPort;
+
public Cluster() {}
public String getName() { return name; }
@@ -105,4 +108,7 @@ public class Cluster {
public String getInternalEndpoint() { return internalEndpoint; }
public void setInternalEndpoint(String internalEndpoint) { this.internalEndpoint = internalEndpoint; }
+
+ public int getHostPort() { return hostPort; }
+ public void setHostPort(int hostPort) { this.hostPort = hostPort; }
}
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index 8d03c0ffdf..bb62b3dffd 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -264,6 +264,8 @@ floci:
api-server-max-port: 6599
data-path: ./data/eks
keep-running-on-shutdown: false
+ endpoint-mode: host # host = https://localhost:<hostPort> (host-reachable); network = container DNS name
+ iam-auth-webhook: true # wire a token-auth webhook into k3s so `aws eks get-token` works
elbv2:
enabled: true
mock: false
diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java
new file mode 100644
index 0000000000..245288bd07
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java
@@ -0,0 +1,53 @@
+package io.github.hectorvent.floci.services.eks;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class EksClusterManagerTest {
+
+ @Test
+ void webhookKubeconfigEmbedsServerUrl() {
+ String url = "http://host.docker.internal:4566/_floci/eks/token-webhook";
+ String yaml = EksClusterManager.buildWebhookKubeconfig(url);
+
+ assertTrue(yaml.contains("kind: Config"), "should be a kubeconfig");
+ assertTrue(yaml.contains("server: " + url), "should point the webhook at Floci");
+ assertTrue(yaml.contains("current-context: floci-token-webhook"),
+ "should select the webhook context");
+ }
+
+ @Test
+ void webhookKubeconfigUsesContainerNetworkAddress() {
+ String url = "http://172.18.0.5:4566/_floci/eks/token-webhook";
+ String yaml = EksClusterManager.buildWebhookKubeconfig(url);
+ assertTrue(yaml.contains("server: " + url));
+ }
+
+ @Test
+ void hostModeAlwaysReturnsHostReachableEndpoint() {
+ assertEquals("https://localhost:6500",
+ EksClusterManager.resolvePublicEndpoint(true, "host", "floci-eks-demo", 6500));
+ assertEquals("https://localhost:6500",
+ EksClusterManager.resolvePublicEndpoint(false, "host", "floci-eks-demo", 6500));
+ }
+
+ @Test
+ void networkModeReturnsContainerDnsOnlyInContainer() {
+ assertEquals("https://floci-eks-demo:6443",
+ EksClusterManager.resolvePublicEndpoint(true, "network", "floci-eks-demo", 6500));
+ // Native mode has no usable container DNS name — falls back to the host endpoint.
+ assertEquals("https://localhost:6500",
+ EksClusterManager.resolvePublicEndpoint(false, "network", "floci-eks-demo", 6500));
+ }
+
+ @Test
+ void endpointModeIsCaseInsensitiveAndDefaultsToHost() {
+ assertEquals("https://floci-eks-demo:6443",
+ EksClusterManager.resolvePublicEndpoint(true, "NETWORK", "floci-eks-demo", 6500));
+ // Unknown / unset modes behave as host.
+ assertEquals("https://localhost:6500",
+ EksClusterManager.resolvePublicEndpoint(true, "bogus", "floci-eks-demo", 6500));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksTokenWebhookControllerTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksTokenWebhookControllerTest.java
new file mode 100644
index 0000000000..4f24af366e
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksTokenWebhookControllerTest.java
@@ -0,0 +1,78 @@
+package io.github.hectorvent.floci.services.eks;
+
+import jakarta.ws.rs.core.Response;
+import org.junit.jupiter.api.Test;
+
+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.assertTrue;
+
+class EksTokenWebhookControllerTest {
+
+ private final EksTokenWebhookController controller = new EksTokenWebhookController();
+
+ @SuppressWarnings("unchecked")
+ private Map<String, Object> status(Response response) {
+ Map<String, Object> body = (Map<String, Object>) response.getEntity();
+ return (Map<String, Object>) body.get("status");
+ }
+
+ private Map<String, Object> tokenReview(String token) {
+ return Map.of(
+ "apiVersion", "authentication.k8s.io/v1",
+ "kind", "TokenReview",
+ "spec", Map.of("token", token));
+ }
+
+ @Test
+ @SuppressWarnings("unchecked")
+ void awsIamTokenAuthenticatesAsClusterAdmin() {
+ Response response = controller.review(tokenReview("k8s-aws-v1.aHR0cHM6Ly9zdHM..."));
+
+ Map<String, Object> status = status(response);
+ assertEquals(Boolean.TRUE, status.get("authenticated"));
+
+ Map<String, Object> user = (Map<String, Object>) status.get("user");
+ assertEquals(List.of("system:masters"), user.get("groups"));
+ }
+
+ @Test
+ void unrecognisedTokenIsRejected() {
+ Response response = controller.review(tokenReview("some-random-bearer-token"));
+ assertEquals(Boolean.FALSE, status(response).get("authenticated"));
+ }
+
+ @Test
+ void emptyOrMalformedReviewIsRejected() {
+ assertFalse((Boolean) status(controller.review(Map.of())).get("authenticated"));
+ assertFalse((Boolean) status(controller.review(
+ Map.of("spec", Map.of()))).get("authenticated"));
+ }
+
+ @Test
+ void responseIsAlwaysAWellFormedTokenReview() {
+ Response response = controller.review(tokenReview("k8s-aws-v1.abc"));
+ Map<?, ?> body = (Map<?, ?>) response.getEntity();
+ assertEquals("authentication.k8s.io/v1", body.get("apiVersion"));
+ assertEquals("TokenReview", body.get("kind"));
+ assertTrue(body.containsKey("status"));
+ }
+
+ @Test
+ void responseEchoesRequestApiVersion() {
+ // The kube-apiserver defaults to the v1beta1 webhook API and cannot convert a v1
+ // response back to v1beta1 — the response apiVersion MUST match the request's.
+ Map<String, Object> v1beta1Review = Map.of(
+ "apiVersion", "authentication.k8s.io/v1beta1",
+ "kind", "TokenReview",
+ "spec", Map.of("token", "k8s-aws-v1.abc"));
+
+ Response response = controller.review(v1beta1Review);
+ Map<?, ?> body = (Map<?, ?>) response.getEntity();
+ assertEquals("authentication.k8s.io/v1beta1", body.get("apiVersion"));
+ assertEquals(Boolean.TRUE, status(response).get("authenticated"));
+ }
+}