Light, fluffy, and always free - The AWS Local Emulator alternative
feat(eks): sign k3s service account tokens with the cluster OIDC key (#3783)
Simone Primarosa0f6b5ee3a24b
diff --git a/docs/services/eks.md b/docs/services/eks.mdindex fc9de75cb4..e159594b6d 100644--- a/docs/services/eks.md+++ b/docs/services/eks.md@@ -157,6 +157,7 @@ back (for example Docker is unavailable), the cluster is marked `FAILED` instead| `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 || `FLOCI_SERVICES_EKS_ECR_REGISTRY_MIRROR` | `true` | Inject a containerd `registries.yaml` so pods can pull images pushed to [Floci ECR](ecr.md) |+| `FLOCI_SERVICES_EKS_IRSA_SIGNING_KEY` | `true` | Pass the cluster OIDC signing key to k3s so in-cluster projected service account tokens can assume IAM roles via Floci STS || `FLOCI_SERVICES_EKS_IMDS` | `false` | Enable link-local IMDS (`169.254.169.254`) proxy in cluster containers |### Pulling images from Floci ECR@@ -265,9 +266,58 @@ Every cluster gets an OIDC identity provider, so the full IRSA flow (trust policThe issuer URL is a faithful string for building trust policies, but it is not fetched: Floci's STS resolves the signing key in-process. The private key is held in storage separate from the cluster model and is never returned by any API.-### Minting a service-account token+### Service-account tokens-Real EKS has the kubelet project a token into the pod. Floci has no kubelet, so a local-dev harness requests one and writes it to the file named by `AWS_WEB_IDENTITY_TOKEN_FILE`. Signing happens server-side, so the private key never leaves Floci.+Floci supports two ways to obtain IRSA service account tokens:++#### 1. In-cluster projected tokens (real k3s mode)++In real mode (`mock: false`), Floci starts a k3s container for the cluster. When IRSA signing key support is enabled (`FLOCI_SERVICES_EKS_IRSA_SIGNING_KEY=true`, default `true`), Floci exports the cluster RSA keypair to `/etc/rancher/k3s/sa-signing-key.pem` and `/etc/rancher/k3s/sa-public-key.pem` with restrictive filesystem permissions (`0600`) before k3s starts.++The k3s API server is configured with:+- `--kube-apiserver-arg=service-account-signing-key-file=/etc/rancher/k3s/sa-signing-key.pem`+- `--kube-apiserver-arg=service-account-key-file=/etc/rancher/k3s/sa-public-key.pem`+- `--kube-apiserver-arg=service-account-issuer=<cluster-oidc-issuer>`+- `--kube-apiserver-arg=service-account-issuer=https://kubernetes.default.svc.cluster.local`+- `--kube-apiserver-arg=api-audiences=https://kubernetes.default.svc.cluster.local,sts.amazonaws.com`++This enables in-cluster pods to project service account tokens directly using Kubernetes standard projected volumes:++```yaml+apiVersion: v1+kind: Pod+metadata:+ name: irsa-workload+ namespace: default+spec:+ serviceAccountName: my-service-account+ containers:+ - name: workload+ image: my-workload:latest+ env:+ - name: AWS_ROLE_ARN+ value: arn:aws:iam::000000000000:role/my-irsa-role+ - name: AWS_WEB_IDENTITY_TOKEN_FILE+ value: /var/run/secrets/eks.amazonaws.com/serviceaccount/token+ volumeMounts:+ - mountPath: /var/run/secrets/eks.amazonaws.com/serviceaccount+ name: aws-iam-token+ readOnly: true+ volumes:+ - name: aws-iam-token+ projected:+ sources:+ - serviceAccountToken:+ path: token+ expirationSeconds: 86400+ audience: sts.amazonaws.com+```++Tokens projected with audience `sts.amazonaws.com` are signed by k3s using the cluster key and advertise the cluster issuer URL. When the AWS SDK inside the container calls `sts:AssumeRoleWithWebIdentity`, Floci verifies the signature against the cluster public key and checks the trust policy conditions. In-cluster components that do not specify an audience receive tokens with both the in-cluster audience and STS audience, allowing normal Kubernetes operation without disruption.++#### 2. Minting a service-account token via HTTP (mock mode & out-of-cluster testing)++For local development harnesses running outside Kubernetes or when using mock mode (`FLOCI_SERVICES_EKS_MOCK=true`), tokens can be requested directly from Floci via HTTP. Signing happens server-side, so the private key never leaves Floci:```bashcurl -sX POST http://localhost:4566/_floci/eks/clusters/my-cluster/oidc-token \@@ -284,8 +334,7 @@ curl -sX POST http://localhost:4566/_floci/eks/clusters/my-cluster/oidc-token \}```-`audience` (default `sts.amazonaws.com`) and `expirySeconds` (default 24h, max 7d) are optional.-This is Floci plumbing under `_floci/…`, not an AWS API.+`audience` (default `sts.amazonaws.com`) and `expirySeconds` (default 24h, max 7d) are optional. This is Floci plumbing under `_floci/…`, not an AWS API.### Trust policydiff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.javaindex a215cde92b..8e67e37147 100644--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java@@ -2800,6 +2800,13 @@ public interface EmulatorConfig {*/@WithDefault("false")boolean imds();++ /**+ * When true, configures k3s with the cluster's per-cluster OIDC signing keypair and+ * advertises Floci's OIDC issuer URL, enabling in-cluster IAM Roles for Service Accounts (IRSA).+ */+ @WithDefault("true")+ boolean irsaSigningKey();}/**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.javaindex 7a2ba7bd14..6fd2d7fb74 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@@ -14,6 +14,9 @@ import io.github.hectorvent.floci.core.common.docker.PortAllocator;import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;import io.github.hectorvent.floci.services.eks.model.CertificateAuthority;import io.github.hectorvent.floci.services.eks.model.Cluster;+import io.github.hectorvent.floci.services.eks.model.ClusterIdentity;+import io.github.hectorvent.floci.services.eks.model.ClusterOidcKey;+import io.github.hectorvent.floci.services.eks.model.OidcIdentity;import com.github.dockerjava.api.DockerClient;import com.github.dockerjava.api.async.ResultCallback;import com.github.dockerjava.api.command.ExecCreateCmdResponse;@@ -33,6 +36,7 @@ import org.jboss.logging.Logger;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;+import java.io.File;import java.io.IOException;import java.net.HttpURLConnection;import java.net.URI;@@ -40,6 +44,10 @@ import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;+import java.nio.file.attribute.PosixFileAttributeView;+import java.nio.file.attribute.PosixFilePermission;+import java.nio.file.attribute.PosixFilePermissions;+import java.time.Instant;import java.util.ArrayList;import java.util.LinkedHashSet;import java.util.List;@@ -68,6 +76,12 @@ public class EksClusterManager {private static final String REGISTRIES_TAR_ENTRY = "rancher/k3s/registries.yaml";private static final String ENDPOINT_MODE_NETWORK = "network";+ static final String SA_SIGNING_KEY_FILE = "sa-signing-key.pem";+ static final String SA_PUBLIC_KEY_FILE = "sa-public-key.pem";+ static final String SA_SIGNING_KEY_CONTAINER_PATH = WEBHOOK_CONFIG_DIR + "/" + SA_SIGNING_KEY_FILE;+ static final String SA_PUBLIC_KEY_CONTAINER_PATH = WEBHOOK_CONFIG_DIR + "/" + SA_PUBLIC_KEY_FILE;+ static final String KUBERNETES_DEFAULT_ISSUER = "https://kubernetes.default.svc.cluster.local";+private final ContainerBuilder containerBuilder;private final ContainerLifecycleManager lifecycleManager;private final ContainerDetector containerDetector;@@ -77,6 +91,7 @@ public class EksClusterManager {private final EmulatorConfig config;private final RegionResolver regionResolver;private final Ec2MetadataServer metadataServer;+ private final EksOidcService oidcService;private final Map<String, Instance> clusterNodeInstances = new ConcurrentHashMap<>();public EksClusterManager(ContainerBuilder containerBuilder,@@ -88,10 +103,9 @@ public class EksClusterManager {EmulatorConfig config,RegionResolver regionResolver) {this(containerBuilder, lifecycleManager, containerDetector, portAllocator,- dockerHostResolver, ecrRegistryManager, config, regionResolver, null);+ dockerHostResolver, ecrRegistryManager, config, regionResolver, null, null);}- @Injectpublic EksClusterManager(ContainerBuilder containerBuilder,ContainerLifecycleManager lifecycleManager,ContainerDetector containerDetector,@@ -101,6 +115,21 @@ public class EksClusterManager {EmulatorConfig config,RegionResolver regionResolver,Ec2MetadataServer metadataServer) {+ this(containerBuilder, lifecycleManager, containerDetector, portAllocator,+ dockerHostResolver, ecrRegistryManager, config, regionResolver, metadataServer, null);+ }++ @Inject+ public EksClusterManager(ContainerBuilder containerBuilder,+ ContainerLifecycleManager lifecycleManager,+ ContainerDetector containerDetector,+ PortAllocator portAllocator,+ DockerHostResolver dockerHostResolver,+ EcrRegistryManager ecrRegistryManager,+ EmulatorConfig config,+ RegionResolver regionResolver,+ Ec2MetadataServer metadataServer,+ EksOidcService oidcService) {this.containerBuilder = containerBuilder;this.lifecycleManager = lifecycleManager;this.containerDetector = containerDetector;@@ -110,6 +139,7 @@ public class EksClusterManager {this.config = config;this.regionResolver = regionResolver;this.metadataServer = metadataServer;+ this.oidcService = oidcService;}/**@@ -191,9 +221,7 @@ public class EksClusterManager {// The account label comes from the cluster record when set (restore runs with no request// context); regionResolver is the fallback for the create path.- String labelAccountId = cluster.getAccountId() != null- ? cluster.getAccountId()- : regionResolver.getAccountId();+ String labelAccountId = resolveClusterAccountId(cluster);ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image).withName(containerName).withEnv("K3S_KUBECONFIG_MODE", "644")@@ -203,7 +231,7 @@ public class EksClusterManager {.withPrivileged(true).withLogRotation().withLabels(ContainerStorageHelper.resourceIdentityLabels(- "eks", cluster.getName(), labelAccountId, regionResolver.getDefaultRegion()));+ "eks", cluster.getName(), labelAccountId, clusterRegion(cluster)));if (config.services().eks().ecrRegistryMirror() && config.services().ecr().enabled()) {specBuilder.withHostDockerInternalOnLinux();@@ -227,6 +255,22 @@ public class EksClusterManager {}}+ SigningKeyFiles signingKeyFiles = null;+ if (config.services().eks().irsaSigningKey() && oidcService != null) {+ try {+ String accountId = resolveClusterAccountId(cluster);+ String issuer = resolveClusterIssuer(cluster);+ ClusterOidcKey oidcKey = oidcService.ensureKeyForAccount(accountId, cluster.getName(), issuer);+ signingKeyFiles = writeSigningKeyFiles(cluster, oidcKey);+ if (signingKeyFiles != null) {+ serverArgs.addAll(buildIrsaServerArgs(oidcKey.getIssuer()));+ }+ } catch (Exception e) {+ LOG.warnv("EKS IRSA signing key injection disabled for cluster {0}: could not prepare keys: {1}",+ cluster.getName(), e.getMessage());+ }+ }+if (config.services().eks().disableCni()) {// A container's /sys mount defaults to private propagation, which breaks// Cilium's BPF filesystem mount ("mounted on /sys but it is not a shared or@@ -249,6 +293,9 @@ public class EksClusterManager {copyWebhookIntoContainer(containerId, webhookLocalFile, cluster.getName());}injectEcrRegistryMirror(containerId, cluster.getName());+ if (signingKeyFiles != null) {+ copySigningKeysIntoContainer(containerId, signingKeyFiles, cluster.getName());+ }ContainerInfo info = lifecycleManager.startCreated(containerId, spec);applyEndpoints(cluster, containerName, hostPort, info);@@ -280,6 +327,10 @@ public class EksClusterManager {return;}+ if (config.services().eks().irsaSigningKey() && oidcService != null) {+ reinjectSigningKeys(existing.get().getId(), cluster);+ }+ContainerInfo info;try {info = lifecycleManager.adopt(existing.get().getId(), List.of(K3S_API_SERVER_PORT));@@ -602,6 +653,170 @@ public class EksClusterManager {}}+ /**+ * Builds the API server arguments configuring k3s to sign service account tokens with the+ * cluster's OIDC keypair and advertise the cluster's OIDC issuer URL. api-audiences includes+ * both the standard Kubernetes in-cluster audience and STS_AUDIENCE.+ */+ static List<String> buildIrsaServerArgs(String issuerUrl) {+ if (issuerUrl == null || issuerUrl.isBlank()) {+ throw new IllegalArgumentException("issuerUrl is required");+ }+ return List.of(+ "--kube-apiserver-arg=service-account-signing-key-file=" + SA_SIGNING_KEY_CONTAINER_PATH,+ "--kube-apiserver-arg=service-account-key-file=" + SA_PUBLIC_KEY_CONTAINER_PATH,+ "--kube-apiserver-arg=service-account-issuer=" + issuerUrl,+ "--kube-apiserver-arg=service-account-issuer=" + KUBERNETES_DEFAULT_ISSUER,+ "--kube-apiserver-arg=api-audiences=" + KUBERNETES_DEFAULT_ISSUER + "," + EksOidcService.STS_AUDIENCE+ );+ }++ String resolveClusterIssuer(Cluster cluster) {+ if (cluster.getIdentity() != null && cluster.getIdentity().getOidc() != null+ && cluster.getIdentity().getOidc().getIssuer() != null+ && !cluster.getIdentity().getOidc().getIssuer().isBlank()) {+ return cluster.getIdentity().getOidc().getIssuer();+ }+ String region = clusterRegion(cluster);+ String issuer = oidcService.newIssuerUrl(region);+ cluster.setIdentity(new ClusterIdentity(new OidcIdentity(issuer)));+ return issuer;+ }++ record SigningKeyFiles(Path signingKeyPath, Path publicKeyPath) {}++ String resolveClusterAccountId(Cluster cluster) {+ if (cluster != null) {+ if (cluster.getAccountId() != null && !cluster.getAccountId().isBlank()) {+ return cluster.getAccountId();+ }+ if (cluster.getArn() != null) {+ String[] parts = cluster.getArn().split(":");+ if (parts.length > 4 && !parts[4].isBlank()) {+ return parts[4];+ }+ }+ }+ if (regionResolver != null && regionResolver.getAccountId() != null && !regionResolver.getAccountId().isBlank()) {+ return regionResolver.getAccountId();+ }+ if (config != null && config.defaultAccountId() != null && !config.defaultAccountId().isBlank()) {+ return config.defaultAccountId();+ }+ return "000000000000";+ }++ Path resolveKeysDir(Cluster cluster) {+ String accountId = resolveClusterAccountId(cluster);+ String region = clusterRegion(cluster);+ return Paths.get(config.services().eks().dataPath(), "keys", accountId, region, cluster.getName())+ .toAbsolutePath().normalize();+ }++ /**+ * Writes the cluster's RSA signing key and public key PEM files to Floci's local filesystem+ * under the account- and region-qualified EKS data path with restrictive permissions (0600 for+ * files, 0700 for directories). Files are created with owner-only permissions atomically from+ * creation, avoiding any window with default umask permissions. Returns the paths or null if+ * writing failed.+ */+ SigningKeyFiles writeSigningKeyFiles(Cluster cluster, ClusterOidcKey oidcKey) {+ Path keysDir = resolveKeysDir(cluster);+ try {+ if (!Files.isDirectory(keysDir)) {+ if (Files.getFileAttributeView(keysDir.getParent(), PosixFileAttributeView.class) != null) {+ Files.createDirectories(keysDir, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------")));+ } else {+ Files.createDirectories(keysDir);+ }+ }+ setRestrictivePermissions(keysDir, true);++ Path signingKeyPath = keysDir.resolve(SA_SIGNING_KEY_FILE);+ writeSecureFile(signingKeyPath, oidcService.exportSigningKeyPem(oidcKey), "rw-------");++ Path publicKeyPath = keysDir.resolve(SA_PUBLIC_KEY_FILE);+ writeSecureFile(publicKeyPath, oidcService.exportPublicKeyPem(oidcKey), "rw-------");++ return new SigningKeyFiles(signingKeyPath, publicKeyPath);+ } catch (IOException e) {+ LOG.warnv("EKS IRSA signing key disabled for cluster {0}: could not write key files: {1}",+ cluster.getName(), e.getMessage());+ return null;+ }+ }++ private static void writeSecureFile(Path path, String content, String posixPerms) throws IOException {+ Files.deleteIfExists(path);+ if (Files.getFileAttributeView(path.getParent(), PosixFileAttributeView.class) != null) {+ Files.createFile(path, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString(posixPerms)));+ } else {+ Files.createFile(path);+ }+ Files.writeString(path, content);+ setRestrictivePermissions(path, false);+ }++ private static void setRestrictivePermissions(Path path, boolean isDirectory) {+ try {+ Set<PosixFilePermission> perms = isDirectory+ ? PosixFilePermissions.fromString("rwx------")+ : PosixFilePermissions.fromString("rw-------");+ Files.setPosixFilePermissions(path, perms);+ } catch (UnsupportedOperationException | IOException ignored) {+ File file = path.toFile();+ file.setReadable(false, false);+ file.setReadable(true, true);+ file.setWritable(false, false);+ file.setWritable(true, true);+ if (isDirectory) {+ file.setExecutable(false, false);+ file.setExecutable(true, true);+ } else {+ file.setExecutable(false, false);+ }+ }+ }++ /**+ * Streams the signing key and public key PEM files into the k3s container at /etc using the Docker API.+ * A failure logs a warning and lets cluster startup continue.+ */+ void copySigningKeysIntoContainer(String containerId, SigningKeyFiles keyFiles, String clusterName) {+ try {+ lifecycleManager.getDockerClient()+ .copyArchiveToContainerCmd(containerId)+ .withHostResource(keyFiles.signingKeyPath().toString())+ .withRemotePath(WEBHOOK_CONFIG_DIR)+ .exec();+ lifecycleManager.getDockerClient()+ .copyArchiveToContainerCmd(containerId)+ .withHostResource(keyFiles.publicKeyPath().toString())+ .withRemotePath(WEBHOOK_CONFIG_DIR)+ .exec();+ LOG.debugv("Injected IRSA OIDC signing keypair into k3s container {0} for cluster {1}",+ containerId, clusterName);+ } catch (Exception e) {+ LOG.warnv("EKS IRSA service account tokens may not verify for cluster {0}: could not copy "+ + "key files into the k3s container: {1}", clusterName, e.getMessage());+ }+ }++ void reinjectSigningKeys(String containerId, Cluster cluster) {+ try {+ String accountId = resolveClusterAccountId(cluster);+ String issuer = resolveClusterIssuer(cluster);+ ClusterOidcKey oidcKey = oidcService.ensureKeyForAccount(accountId, cluster.getName(), issuer);+ SigningKeyFiles keyFiles = writeSigningKeyFiles(cluster, oidcKey);+ if (keyFiles != null) {+ copySigningKeysIntoContainer(containerId, keyFiles, cluster.getName());+ }+ } catch (Exception e) {+ LOG.warnv("Could not re-inject IRSA signing keys for surviving EKS cluster {0}: {1}",+ cluster.getName(), e.getMessage());+ }+ }+/*** Generates and injects {@code /etc/rancher/k3s/registries.yaml} into the (created,* not-yet-started) k3s container so its containerd can pull images pushed to the Floci ECR@@ -701,8 +916,19 @@ public class EksClusterManager {static String webhookPath(Cluster cluster) {// client-go replaces a server URL query when constructing its TokenReview request.- return webhookPath(cluster.getName()) + "/scope/" + cluster.getAccountId()- + "/" + cluster.getArn().split(":", 6)[3] + "/" + cluster.getCreatedAt();+ String accountId = cluster.getAccountId() != null && !cluster.getAccountId().isBlank()+ ? cluster.getAccountId()+ : (cluster.getArn() != null && cluster.getArn().split(":", 6).length > 4 ? cluster.getArn().split(":", 6)[4] : "000000000000");+ String region = "us-east-1";+ if (cluster.getArn() != null) {+ String[] parts = cluster.getArn().split(":", 6);+ if (parts.length > 3 && !parts[3].isBlank()) {+ region = parts[3];+ }+ }+ Instant createdAt = cluster.getCreatedAt() != null ? cluster.getCreatedAt() : Instant.EPOCH;+ return webhookPath(cluster.getName()) + "/scope/" + accountId+ + "/" + region + "/" + createdAt;}static String webhookPath(String clusterName) {@@ -737,9 +963,7 @@ public class EksClusterManager {return;}try {- String accountId = cluster.getAccountId() != null- ? cluster.getAccountId()- : regionResolver.getAccountId();+ String accountId = resolveClusterAccountId(cluster);String region = clusterRegion(cluster);ContainerIps containerIps = resolveContainerIps(containerId);@@ -783,14 +1007,20 @@ public class EksClusterManager {}}- private String clusterRegion(Cluster cluster) {+ String clusterRegion(Cluster cluster) {if (cluster != null && cluster.getArn() != null) {String[] parts = cluster.getArn().split(":");if (parts.length > 3 && !parts[3].isBlank()) {return parts[3];}}- return regionResolver.getDefaultRegion();+ if (regionResolver != null && regionResolver.getDefaultRegion() != null && !regionResolver.getDefaultRegion().isBlank()) {+ return regionResolver.getDefaultRegion();+ }+ if (config != null && config.defaultRegion() != null && !config.defaultRegion().isBlank()) {+ return config.defaultRegion();+ }+ return "us-east-1";}Instance synthesizeClusterNodeInstance(Cluster cluster, String containerIp, String region, String accountId) {diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksOidcService.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksOidcService.javaindex 663aac8b4b..de5910e3f0 100644--- a/src/main/java/io/github/hectorvent/floci/services/eks/EksOidcService.java+++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksOidcService.java@@ -262,4 +262,36 @@ public class EksOidcService implements OidcIssuerKeyLookup {private static String base64Url(byte[] data) {return Base64.getUrlEncoder().withoutPadding().encodeToString(data);}++ /**+ * Exports the cluster's RSA signing key in PKCS#8 PEM format for the k3s API server's+ * {@code --service-account-signing-key-file} argument.+ */+ public String exportSigningKeyPem(ClusterOidcKey key) {+ if (key == null || key.getPrivateKey() == null) {+ throw new IllegalArgumentException("ClusterOidcKey and its private key must not be null");+ }+ return toPem("PRIVATE KEY", key.getPrivateKey());+ }++ /**+ * Exports the cluster's RSA public key in X.509 PEM format for the k3s API server's+ * {@code --service-account-key-file} argument.+ */+ public String exportPublicKeyPem(ClusterOidcKey key) {+ if (key == null || key.getPublicKey() == null) {+ throw new IllegalArgumentException("ClusterOidcKey and its public key must not be null");+ }+ return toPem("PUBLIC KEY", key.getPublicKey());+ }++ private static String toPem(String type, String base64) {+ StringBuilder pem = new StringBuilder();+ pem.append("-----BEGIN ").append(type).append("-----\n");+ for (int i = 0; i < base64.length(); i += 64) {+ pem.append(base64, i, Math.min(i + 64, base64.length())).append("\n");+ }+ pem.append("-----END ").append(type).append("-----\n");+ return pem.toString();+ }}diff --git a/src/main/resources/application.yml b/src/main/resources/application.ymlindex d90818cbea..ac4989b3cb 100644--- a/src/main/resources/application.yml+++ b/src/main/resources/application.yml@@ -596,6 +596,7 @@ floci:ecr-registry-mirror: true # inject a registries.yaml so pods can pull images pushed to Floci ECRdisable-cni: false # start k3s without its bundled flannel/kube-proxy so a real CNI (e.g. Cilium) can take overimds: false # expose link-local IMDS (169.254.169.254) inside the cluster container+ irsa-signing-key: true # sign k3s service account tokens with the cluster OIDC keymwaa:enabled: truemock: falsediff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.javaindex 7916feb4db..07f198ea7a 100644--- a/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java@@ -11,7 +11,11 @@ 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.ecr.registry.EcrRegistryManager;+import io.github.hectorvent.floci.services.eks.model.CertificateAuthority;import io.github.hectorvent.floci.services.eks.model.Cluster;+import io.github.hectorvent.floci.services.eks.model.ClusterIdentity;+import io.github.hectorvent.floci.services.eks.model.ClusterOidcKey;+import io.github.hectorvent.floci.services.eks.model.OidcIdentity;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.ObjectMapper;@@ -35,24 +39,31 @@ import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Nested;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.io.TempDir;+import org.mockito.ArgumentCaptor;import org.mockito.Mockito;-import java.time.Instant;+import java.nio.file.Files;import java.nio.file.Path;+import java.nio.file.attribute.PosixFilePermission;+import java.nio.file.attribute.PosixFilePermissions;+import java.time.Instant;import java.util.ArrayList;import java.util.Arrays;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.assertNotEquals;import static org.junit.jupiter.api.Assertions.assertNotNull;import static org.junit.jupiter.api.Assertions.assertNull;+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.atLeastOnce;import static org.mockito.Mockito.never;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.verifyNoInteractions;@@ -71,6 +82,15 @@ class EksClusterManagerTest {+ "/us-west-2/2026-09-17T00:00:00Z", EksClusterManager.webhookPath(cluster));}+ @Test+ void webhookPathHandlesMissingArnOrCreatedAtGracefully() {+ Cluster cluster = new Cluster();+ cluster.setName("demo");+ cluster.setAccountId("123456789012");+ assertEquals("/_floci/eks/clusters/demo/token-webhook/scope/123456789012"+ + "/us-east-1/1970-01-01T00:00:00Z", EksClusterManager.webhookPath(cluster));+ }+@Testvoid webhookPathBindsAuthenticationToOneCluster() {assertEquals("/_floci/eks/clusters/demo/token-webhook", EksClusterManager.webhookPath("demo"));@@ -803,4 +823,318 @@ class EksClusterManagerTest {assertNull(manager.getRegisteredClusterNodeInstance(cluster));}}++ @Nested+ class IrsaSigningKey {++ private EmulatorConfig config;+ private EmulatorConfig.EksServiceConfig eks;+ private ContainerLifecycleManager lifecycleManager;+ private ContainerBuilder.Builder builder;+ private DockerClient dockerClient;+ private CopyArchiveToContainerCmd copyCmd;+ private EksOidcService oidcService;+ private RegionResolver regionResolver;+ private EksClusterManager manager;++ @BeforeEach+ void setUp() {+ config = Mockito.mock(EmulatorConfig.class);+ EmulatorConfig.ServicesConfig services = Mockito.mock(EmulatorConfig.ServicesConfig.class);+ eks = Mockito.mock(EmulatorConfig.EksServiceConfig.class);+ when(config.services()).thenReturn(services);+ when(services.eks()).thenReturn(eks);+ when(eks.defaultImage()).thenReturn("rancher/k3s:v1.30.0-k3s1");+ when(eks.apiServerBasePort()).thenReturn(6440);+ when(eks.apiServerMaxPort()).thenReturn(6499);+ when(eks.dockerNetwork()).thenReturn(Optional.empty());+ when(eks.disableCni()).thenReturn(false);+ when(eks.iamAuthWebhook()).thenReturn(false);+ when(eks.ecrRegistryMirror()).thenReturn(false);+ when(eks.imds()).thenReturn(false);+ when(eks.endpointMode()).thenReturn("host");+ when(config.defaultAccountId()).thenReturn("000000000000");++ lifecycleManager = Mockito.mock(ContainerLifecycleManager.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);+ when(lifecycleManager.create(any())).thenReturn("container-id");+ when(lifecycleManager.startCreated(any(), any())).thenReturn(+ new ContainerInfo("container-id", Map.of()));++ ContainerBuilder containerBuilder = Mockito.mock(ContainerBuilder.class);+ builder = Mockito.mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);+ when(containerBuilder.newContainer(anyString())).thenReturn(builder);+ when(builder.build()).thenReturn(Mockito.mock(ContainerSpec.class));++ regionResolver = Mockito.mock(RegionResolver.class);+ when(regionResolver.getAccountId()).thenReturn("000000000000");+ when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");++ oidcService = Mockito.mock(EksOidcService.class);+ when(oidcService.newIssuerUrl(anyString())).thenReturn(+ "https://oidc.eks.us-east-1.amazonaws.com/id/TESTISSUER12345678901234567890");++ manager = new EksClusterManager(containerBuilder, lifecycleManager,+ Mockito.mock(ContainerDetector.class), Mockito.mock(PortAllocator.class),+ Mockito.mock(DockerHostResolver.class), Mockito.mock(EcrRegistryManager.class),+ config, regionResolver, null, oidcService);+ }++ @Test+ void buildIrsaServerArgsProducesCorrectFlagsAndAudiences() {+ String issuer = "https://oidc.eks.us-west-2.amazonaws.com/id/MYISSUER";+ List<String> args = EksClusterManager.buildIrsaServerArgs(issuer);++ assertTrue(args.contains("--kube-apiserver-arg=service-account-signing-key-file=/etc/sa-signing-key.pem"));+ assertTrue(args.contains("--kube-apiserver-arg=service-account-key-file=/etc/sa-public-key.pem"));+ assertTrue(args.contains("--kube-apiserver-arg=service-account-issuer=" + issuer));+ assertTrue(args.contains("--kube-apiserver-arg=service-account-issuer=https://kubernetes.default.svc.cluster.local"));+ assertTrue(args.contains("--kube-apiserver-arg=api-audiences=https://kubernetes.default.svc.cluster.local,sts.amazonaws.com"));++ assertThrows(IllegalArgumentException.class, () -> EksClusterManager.buildIrsaServerArgs(null));+ assertThrows(IllegalArgumentException.class, () -> EksClusterManager.buildIrsaServerArgs(" "));+ }++ @Test+ void startClusterInjectsKeysAndConfiguresArgsWhenEnabled(@TempDir Path tempDir) {+ when(eks.irsaSigningKey()).thenReturn(true);+ when(eks.dataPath()).thenReturn(tempDir.toString());++ String issuer = "https://oidc.eks.us-east-1.amazonaws.com/id/TESTISSUER";+ ClusterOidcKey key = new ClusterOidcKey(issuer, "kid-1", "pubKeyBase64", "privKeyBase64");+ when(oidcService.ensureKeyForAccount(anyString(), anyString(), anyString())).thenReturn(key);+ when(oidcService.exportSigningKeyPem(key)).thenReturn("-----BEGIN PRIVATE KEY-----\npriv\n-----END PRIVATE KEY-----\n");+ when(oidcService.exportPublicKeyPem(key)).thenReturn("-----BEGIN PUBLIC KEY-----\npub\n-----END PUBLIC KEY-----\n");++ Cluster cluster = new Cluster();+ cluster.setName("my-cluster");+ cluster.setIdentity(new ClusterIdentity(new OidcIdentity(issuer)));++ manager.startCluster(cluster);++ @SuppressWarnings("unchecked")+ ArgumentCaptor<List<String>> cmdCaptor = ArgumentCaptor.forClass(List.class);+ verify(builder).withCmd(cmdCaptor.capture());+ List<String> cmd = cmdCaptor.getValue();++ assertTrue(cmd.contains("--kube-apiserver-arg=service-account-signing-key-file=/etc/sa-signing-key.pem"));+ assertTrue(cmd.contains("--kube-apiserver-arg=service-account-key-file=/etc/sa-public-key.pem"));+ assertTrue(cmd.contains("--kube-apiserver-arg=service-account-issuer=" + issuer));+ assertTrue(cmd.contains("--kube-apiserver-arg=service-account-issuer=https://kubernetes.default.svc.cluster.local"));+ assertTrue(cmd.contains("--kube-apiserver-arg=api-audiences=https://kubernetes.default.svc.cluster.local,sts.amazonaws.com"));++ Path keysDir = manager.resolveKeysDir(cluster);+ Path privFile = keysDir.resolve(EksClusterManager.SA_SIGNING_KEY_FILE);+ Path pubFile = keysDir.resolve(EksClusterManager.SA_PUBLIC_KEY_FILE);+ assertEquals(tempDir.resolve("keys").resolve("000000000000").resolve("us-east-1").resolve("my-cluster"), keysDir);+ assertTrue(Files.exists(privFile));+ assertTrue(Files.exists(pubFile));++ verify(copyCmd).withHostResource(privFile.toString());+ verify(copyCmd).withHostResource(pubFile.toString());+ verify(copyCmd, atLeastOnce()).withRemotePath("/etc");+ verify(copyCmd, atLeastOnce()).exec();+ }++ @Test+ void startClusterOmitsIrsaArgsAndKeyInjectionWhenDisabled(@TempDir Path tempDir) {+ when(eks.irsaSigningKey()).thenReturn(false);+ when(eks.dataPath()).thenReturn(tempDir.toString());++ Cluster cluster = new Cluster();+ cluster.setName("my-cluster");++ manager.startCluster(cluster);++ @SuppressWarnings("unchecked")+ ArgumentCaptor<List<String>> cmdCaptor = ArgumentCaptor.forClass(List.class);+ verify(builder).withCmd(cmdCaptor.capture());+ List<String> cmd = cmdCaptor.getValue();++ assertFalse(cmd.stream().anyMatch(a -> a.contains("service-account-signing-key-file")));+ assertFalse(cmd.stream().anyMatch(a -> a.contains("service-account-key-file")));+ assertFalse(cmd.stream().anyMatch(a -> a.contains("service-account-issuer")));+ assertFalse(cmd.stream().anyMatch(a -> a.contains("api-audiences")));++ verifyNoInteractions(dockerClient);+ assertFalse(Files.exists(tempDir.resolve("keys")));+ }++ @Test+ void startClusterContinuesWhenSigningKeyInjectionFails(@TempDir Path tempDir) {+ when(eks.irsaSigningKey()).thenReturn(true);+ when(eks.dataPath()).thenReturn(tempDir.toString());++ String issuer = "https://oidc.eks.us-east-1.amazonaws.com/id/TESTISSUER";+ ClusterOidcKey key = new ClusterOidcKey(issuer, "kid-1", "pubKeyBase64", "privKeyBase64");+ when(oidcService.ensureKeyForAccount(anyString(), anyString(), anyString())).thenReturn(key);+ when(oidcService.exportSigningKeyPem(key)).thenReturn("-----BEGIN PRIVATE KEY-----\npriv\n-----END PRIVATE KEY-----\n");+ when(oidcService.exportPublicKeyPem(key)).thenReturn("-----BEGIN PUBLIC KEY-----\npub\n-----END PUBLIC KEY-----\n");++ when(copyCmd.exec()).thenThrow(new RuntimeException("Docker copy failed"));++ Cluster cluster = new Cluster();+ cluster.setName("my-cluster");++ // Must not throw despite injection failure+ manager.startCluster(cluster);+ assertEquals("container-id", cluster.getContainerId());+ }++ @Test+ void startClusterContinuesWhenWritingKeysFails(@TempDir Path tempDir) throws Exception {+ when(eks.irsaSigningKey()).thenReturn(true);+ when(eks.dataPath()).thenReturn(tempDir.toString());++ Cluster cluster = new Cluster();+ cluster.setName("my-cluster");++ // Create a regular file where the keys directory would be, causing createDirectories to fail+ Path blocker = manager.resolveKeysDir(cluster);+ Files.createDirectories(blocker.getParent());+ Files.writeString(blocker, "blocker");++ String issuer = "https://oidc.eks.us-east-1.amazonaws.com/id/TESTISSUER";+ ClusterOidcKey key = new ClusterOidcKey(issuer, "kid-1", "pubKeyBase64", "privKeyBase64");+ when(oidcService.ensureKeyForAccount(anyString(), anyString(), anyString())).thenReturn(key);++ // Must not throw despite file write failure+ manager.startCluster(cluster);+ assertEquals("container-id", cluster.getContainerId());+ }++ @Test+ void restoreClusterReinjectsSigningKeysForSurvivingContainer(@TempDir Path tempDir) {+ when(eks.irsaSigningKey()).thenReturn(true);+ when(eks.dataPath()).thenReturn(tempDir.toString());++ String issuer = "https://oidc.eks.us-east-1.amazonaws.com/id/TESTISSUER";+ ClusterOidcKey key = new ClusterOidcKey(issuer, "kid-1", "pubKeyBase64", "privKeyBase64");+ when(oidcService.ensureKeyForAccount(anyString(), anyString(), anyString())).thenReturn(key);+ when(oidcService.exportSigningKeyPem(key)).thenReturn("-----BEGIN PRIVATE KEY-----\npriv\n-----END PRIVATE KEY-----\n");+ when(oidcService.exportPublicKeyPem(key)).thenReturn("-----BEGIN PUBLIC KEY-----\npub\n-----END PUBLIC KEY-----\n");++ Container container = Mockito.mock(Container.class);+ when(container.getId()).thenReturn("surviving-container-id");+ when(lifecycleManager.findByName("floci-eks-my-cluster")).thenReturn(Optional.of(container));+ when(lifecycleManager.adopt(anyString(), any())).thenReturn(+ new ContainerInfo("surviving-container-id", Map.of(6443, new ContainerLifecycleManager.EndpointInfo("localhost", 6500)), Map.of(6443, 6500)));++ Cluster cluster = new Cluster();+ cluster.setName("my-cluster");+ cluster.setIdentity(new ClusterIdentity(new OidcIdentity(issuer)));++ manager.restoreCluster(cluster);++ Path keysDir = manager.resolveKeysDir(cluster);+ Path privFile = keysDir.resolve(EksClusterManager.SA_SIGNING_KEY_FILE);+ Path pubFile = keysDir.resolve(EksClusterManager.SA_PUBLIC_KEY_FILE);+ assertTrue(Files.exists(privFile));+ assertTrue(Files.exists(pubFile));++ verify(copyCmd).withHostResource(privFile.toString());+ verify(copyCmd).withHostResource(pubFile.toString());+ }++ @Test+ void signingKeyFilesWrittenWithRestrictivePermissions(@TempDir Path tempDir) throws Exception {+ when(eks.irsaSigningKey()).thenReturn(true);+ when(eks.dataPath()).thenReturn(tempDir.toString());++ String issuer = "https://oidc.eks.us-east-1.amazonaws.com/id/TESTISSUER";+ ClusterOidcKey key = new ClusterOidcKey(issuer, "kid-1", "pubKeyBase64", "privKeyBase64");+ when(oidcService.ensureKeyForAccount(anyString(), anyString(), anyString())).thenReturn(key);+ when(oidcService.exportSigningKeyPem(key)).thenReturn("-----BEGIN PRIVATE KEY-----\npriv\n-----END PRIVATE KEY-----\n");+ when(oidcService.exportPublicKeyPem(key)).thenReturn("-----BEGIN PUBLIC KEY-----\npub\n-----END PUBLIC KEY-----\n");++ Cluster cluster = new Cluster();+ cluster.setName("perm-cluster");++ manager.startCluster(cluster);++ Path keysDir = manager.resolveKeysDir(cluster);+ Path privFile = keysDir.resolve(EksClusterManager.SA_SIGNING_KEY_FILE);+ Path pubFile = keysDir.resolve(EksClusterManager.SA_PUBLIC_KEY_FILE);++ try {+ Set<PosixFilePermission> dirPerms = Files.getPosixFilePermissions(keysDir);+ assertEquals(PosixFilePermissions.fromString("rwx------"), dirPerms);++ Set<PosixFilePermission> privPerms = Files.getPosixFilePermissions(privFile);+ assertEquals(PosixFilePermissions.fromString("rw-------"), privPerms);++ Set<PosixFilePermission> pubPerms = Files.getPosixFilePermissions(pubFile);+ assertEquals(PosixFilePermissions.fromString("rw-------"), pubPerms);+ } catch (UnsupportedOperationException ignored) {+ // Ignore on non-POSIX platforms+ }+ }++ @Test+ void twoAccountsWithSameClusterNameHaveIsolatedSigningKeyFiles(@TempDir Path tempDir) throws Exception {+ when(eks.irsaSigningKey()).thenReturn(true);+ when(eks.dataPath()).thenReturn(tempDir.toString());++ String clusterName = "shared-cluster";++ Cluster cluster1 = new Cluster();+ cluster1.setName(clusterName);+ cluster1.setAccountId("111122223333");+ cluster1.setArn("arn:aws:eks:us-east-1:111122223333:cluster/" + clusterName);+ String issuer1 = "https://oidc.eks.us-east-1.amazonaws.com/id/ISSUER1111";+ cluster1.setIdentity(new ClusterIdentity(new OidcIdentity(issuer1)));+ ClusterOidcKey key1 = new ClusterOidcKey(issuer1, "kid-1", "pub1", "priv1");++ Cluster cluster2 = new Cluster();+ cluster2.setName(clusterName);+ cluster2.setAccountId("444455556666");+ cluster2.setArn("arn:aws:eks:us-east-1:444455556666:cluster/" + clusterName);+ String issuer2 = "https://oidc.eks.us-east-1.amazonaws.com/id/ISSUER4444";+ cluster2.setIdentity(new ClusterIdentity(new OidcIdentity(issuer2)));+ ClusterOidcKey key2 = new ClusterOidcKey(issuer2, "kid-2", "pub2", "priv2");++ Cluster cluster3 = new Cluster();+ cluster3.setName(clusterName);+ cluster3.setAccountId("111122223333");+ cluster3.setArn("arn:aws:eks:eu-west-1:111122223333:cluster/" + clusterName);+ String issuer3 = "https://oidc.eks.eu-west-1.amazonaws.com/id/ISSUER3333";+ cluster3.setIdentity(new ClusterIdentity(new OidcIdentity(issuer3)));+ ClusterOidcKey key3 = new ClusterOidcKey(issuer3, "kid-3", "pub3", "priv3");++ when(oidcService.exportSigningKeyPem(key1)).thenReturn("priv-key-1");+ when(oidcService.exportPublicKeyPem(key1)).thenReturn("pub-key-1");+ when(oidcService.exportSigningKeyPem(key2)).thenReturn("priv-key-2");+ when(oidcService.exportPublicKeyPem(key2)).thenReturn("pub-key-2");+ when(oidcService.exportSigningKeyPem(key3)).thenReturn("priv-key-3");+ when(oidcService.exportPublicKeyPem(key3)).thenReturn("pub-key-3");++ EksClusterManager.SigningKeyFiles files1 = manager.writeSigningKeyFiles(cluster1, key1);+ EksClusterManager.SigningKeyFiles files2 = manager.writeSigningKeyFiles(cluster2, key2);+ EksClusterManager.SigningKeyFiles files3 = manager.writeSigningKeyFiles(cluster3, key3);++ assertNotNull(files1);+ assertNotNull(files2);+ assertNotNull(files3);+ assertNotEquals(files1.signingKeyPath(), files2.signingKeyPath());+ assertNotEquals(files1.signingKeyPath(), files3.signingKeyPath());+ assertNotEquals(files2.signingKeyPath(), files3.signingKeyPath());++ Path expectedDir1 = tempDir.resolve("keys").resolve("111122223333").resolve("us-east-1").resolve(clusterName);+ Path expectedDir2 = tempDir.resolve("keys").resolve("444455556666").resolve("us-east-1").resolve(clusterName);+ Path expectedDir3 = tempDir.resolve("keys").resolve("111122223333").resolve("eu-west-1").resolve(clusterName);+ assertEquals(expectedDir1, manager.resolveKeysDir(cluster1));+ assertEquals(expectedDir2, manager.resolveKeysDir(cluster2));+ assertEquals(expectedDir3, manager.resolveKeysDir(cluster3));++ assertEquals("priv-key-1", Files.readString(files1.signingKeyPath()));+ assertEquals("pub-key-1", Files.readString(files1.publicKeyPath()));+ assertEquals("priv-key-2", Files.readString(files2.signingKeyPath()));+ assertEquals("pub-key-2", Files.readString(files2.publicKeyPath()));+ assertEquals("priv-key-3", Files.readString(files3.signingKeyPath()));+ assertEquals("pub-key-3", Files.readString(files3.publicKeyPath()));+ }+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksIrsaDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksIrsaDockerIntegrationTest.javanew file mode 100644index 0000000000..1bbc7a4a52--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksIrsaDockerIntegrationTest.java@@ -0,0 +1,371 @@+package io.github.hectorvent.floci.services.eks;++import com.github.dockerjava.api.DockerClient;+import com.github.dockerjava.api.async.ResultCallback;+import com.github.dockerjava.api.command.ExecCreateCmdResponse;+import com.github.dockerjava.api.model.Frame;+import io.github.hectorvent.floci.services.eks.model.Cluster;+import io.quarkus.test.junit.QuarkusTest;+import io.quarkus.test.junit.QuarkusTestProfile;+import io.quarkus.test.junit.TestProfile;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.Assumptions;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.nio.charset.StandardCharsets;+import java.time.Instant;+import java.util.Map;+import java.util.UUID;+import java.util.concurrent.TimeUnit;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsString;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertTrue;++/**+ * Docker integration test for EKS IRSA: verifies that k3s signs projected service account tokens+ * with the cluster's OIDC keypair and advertises the cluster's Floci OIDC issuer URL.+ *+ * Runs a pod with a projected service account token volume with audience sts.amazonaws.com,+ * calls sts:AssumeRoleWithWebIdentity with the pod's token against an IAM role with a federated+ * trust policy pinning the cluster's OIDC provider and subject, and asserts real temporary+ * credentials and claims are returned. Also asserts rejection when the subject is mismatched+ * or the cluster issuer is untrusted under IAM enforcement.+ */+@QuarkusTest+@TestProfile(EksIrsaDockerIntegrationTest.Profile.class)+class EksIrsaDockerIntegrationTest {++ private static final Logger LOG = Logger.getLogger(EksIrsaDockerIntegrationTest.class);+ private static final String FORM = "application/x-www-form-urlencoded";+ private static final String ACCOUNT = "000000000000";++ public static final class Profile implements QuarkusTestProfile {+ @Override+ public Map<String, String> getConfigOverrides() {+ return Map.of(+ "floci.services.eks.mock", "false",+ "floci.services.eks.irsa-signing-key", "true",+ "floci.services.iam.enforcement-enabled", "true"+ );+ }+ }++ @Inject+ DockerClient dockerClient;++ @Inject+ EksClusterManager eksClusterManager;++ @Inject+ EksOidcService oidcService;++ private Cluster cluster;+ private String roleName;+ private String wrongSubjectRoleName;+ private String wrongClusterRoleName;++ @BeforeEach+ void requireDocker() {+ boolean dockerAvailable = isDockerAvailable();+ if (!dockerAvailable) {+ LOG.warn("Docker daemon is not available; skipping EksIrsaDockerIntegrationTest");+ }+ Assumptions.assumeTrue(dockerAvailable, "Docker daemon must be available for EKS IRSA integration test");+ }++ @AfterEach+ void tearDown() {+ if (roleName != null) {+ deleteRole(roleName);+ }+ if (wrongSubjectRoleName != null) {+ deleteRole(wrongSubjectRoleName);+ }+ if (wrongClusterRoleName != null) {+ deleteRole(wrongClusterRoleName);+ }+ if (cluster != null) {+ try {+ eksClusterManager.stopCluster(cluster);+ } catch (Exception e) {+ LOG.warnv("Failed to stop test cluster: {0}", e.getMessage());+ }+ }+ }++ @Test+ void projectedServiceAccountTokenAssumesRoleAndEnforcesPolicy() throws Exception {+ String suffix = UUID.randomUUID().toString().substring(0, 8);+ String clusterName = "irsa-dock-" + suffix;+ roleName = "irsa-dock-role-" + suffix;+ wrongSubjectRoleName = "irsa-dock-wrong-sub-" + suffix;+ wrongClusterRoleName = "irsa-dock-wrong-clus-" + suffix;++ cluster = new Cluster();+ cluster.setName(clusterName);+ cluster.setAccountId(ACCOUNT);+ cluster.setArn("arn:aws:eks:us-east-1:" + ACCOUNT + ":cluster/" + clusterName);+ cluster.setCreatedAt(Instant.now());+ cluster.setRoleArn("arn:aws:iam::" + ACCOUNT + ":role/eks-service-role");++ String issuer = oidcService.newIssuerUrl("us-east-1");+ cluster.setIdentity(new io.github.hectorvent.floci.services.eks.model.ClusterIdentity(+ new io.github.hectorvent.floci.services.eks.model.OidcIdentity(issuer)));+ oidcService.ensureKeyForAccount(ACCOUNT, clusterName, issuer);++ eksClusterManager.startCluster(cluster);+ assertNotNull(cluster.getContainerId(), "Container ID must not be null");++ // Wait for k3s API server readiness (up to 60s)+ long deadline = System.currentTimeMillis() + 60000;+ boolean ready = false;+ while (System.currentTimeMillis() < deadline) {+ if (eksClusterManager.isReady(cluster)) {+ ready = true;+ break;+ }+ Thread.sleep(2000);+ }+ assertTrue(ready, "k3s API server must become ready within 60 seconds");+ eksClusterManager.finalizeCluster(cluster);++ String containerId = cluster.getContainerId();++ // Wait for default serviceaccount to be created by controller manager (up to 30s)+ long saDeadline = System.currentTimeMillis() + 30000;+ boolean saReady = false;+ while (System.currentTimeMillis() < saDeadline) {+ ExecResult saResult = execInContainerWithExitCode(containerId,+ new String[]{"kubectl", "get", "serviceaccount", "default"});+ if (saResult.exitCode() == 0) {+ saReady = true;+ break;+ }+ Thread.sleep(1000);+ }+ assertTrue(saReady, "default serviceaccount must be created within 30 seconds");++ // Create a pod with a projected service account token with audience sts.amazonaws.com+ String podYaml = """+ apiVersion: v1+ kind: Pod+ metadata:+ name: irsa-workload-pod+ namespace: default+ spec:+ containers:+ - name: workload+ image: alpine:3.21+ command: ["sleep", "3600"]+ volumeMounts:+ - mountPath: /var/run/secrets/tokens+ name: sa-token+ serviceAccountName: default+ volumes:+ - name: sa-token+ projected:+ sources:+ - serviceAccountToken:+ path: token+ expirationSeconds: 86400+ audience: sts.amazonaws.com+ """;++ execInContainer(containerId, new String[]{"sh", "-c",+ "cat << 'EOF' | kubectl apply -f -\n" + podYaml + "\nEOF"});++ // Wait for the pod to be running (up to 45s)+ long podDeadline = System.currentTimeMillis() + 45000;+ boolean podRunning = false;+ while (System.currentTimeMillis() < podDeadline) {+ ExecResult statusResult = execInContainerWithExitCode(containerId,+ new String[]{"kubectl", "get", "pod", "irsa-workload-pod", "-o", "jsonpath={.status.phase}"});+ if ("Running".equalsIgnoreCase(statusResult.stdout().trim())) {+ podRunning = true;+ break;+ }+ Thread.sleep(2000);+ }+ assertTrue(podRunning, "irsa-workload-pod must reach Running state");++ // Extract the projected token from the pod volume+ String token = execInContainer(containerId,+ new String[]{"kubectl", "exec", "irsa-workload-pod", "--", "cat", "/var/run/secrets/tokens/token"}).trim();+ assertNotNull(token);+ assertFalse(token.isBlank(), "Projected service account token must not be blank");++ // Create IAM role with federated trust policy matching cluster issuer and subject+ String issuerPrefix = issuer.replaceFirst("^https://", "");+ String trustPolicy = """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{\+ "Federated":"arn:aws:iam::%s:oidc-provider/%s"},\+ "Action":"sts:AssumeRoleWithWebIdentity","Condition":{"StringEquals":{\+ "%s:sub":"system:serviceaccount:default:default","%s:aud":"sts.amazonaws.com"}}}]}"""+ .formatted(ACCOUNT, issuerPrefix, issuerPrefix, issuerPrefix);++ String roleArn = createRole(roleName, trustPolicy);+ assertNotNull(roleArn);++ // 1. Positive case: call AssumeRoleWithWebIdentity with pod token -> succeeds with real credentials+ given()+ .contentType(FORM)+ .formParam("Action", "AssumeRoleWithWebIdentity")+ .formParam("Version", "2011-06-15")+ .formParam("RoleArn", roleArn)+ .formParam("RoleSessionName", "irsa-docker-session")+ .formParam("WebIdentityToken", token)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("<AccessKeyId>ASIA"))+ .body(containsString("<SecretAccessKey>"))+ .body(containsString("<SessionToken>"))+ .body(containsString("<SubjectFromWebIdentityToken>system:serviceaccount:default:default</SubjectFromWebIdentityToken>"))+ .body(containsString("<Provider>" + issuer + "</Provider>"))+ .body(containsString("<Audience>sts.amazonaws.com</Audience>"));++ // 2. Negative case: role trust policy requires different subject -> 403 AccessDenied+ String wrongSubjectTrustPolicy = """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{\+ "Federated":"arn:aws:iam::%s:oidc-provider/%s"},\+ "Action":"sts:AssumeRoleWithWebIdentity","Condition":{"StringEquals":{\+ "%s:sub":"system:serviceaccount:default:other-service-account","%s:aud":"sts.amazonaws.com"}}}]}"""+ .formatted(ACCOUNT, issuerPrefix, issuerPrefix, issuerPrefix);++ String wrongSubjectRoleArn = createRole(wrongSubjectRoleName, wrongSubjectTrustPolicy);+ given()+ .contentType(FORM)+ .formParam("Action", "AssumeRoleWithWebIdentity")+ .formParam("Version", "2011-06-15")+ .formParam("RoleArn", wrongSubjectRoleArn)+ .formParam("RoleSessionName", "wrong-sub-session")+ .formParam("WebIdentityToken", token)+ .when()+ .post("/")+ .then()+ .statusCode(403)+ .body(containsString("AccessDenied"));++ // 3. Negative case: role trusts a different cluster / provider -> 403 AccessDenied+ String untrustedIssuerPrefix = "oidc.eks.us-east-1.amazonaws.com/id/UNTRUSTEDCLUSTER999999999999";+ String wrongClusterTrustPolicy = """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{\+ "Federated":"arn:aws:iam::%s:oidc-provider/%s"},\+ "Action":"sts:AssumeRoleWithWebIdentity","Condition":{"StringEquals":{\+ "%s:sub":"system:serviceaccount:default:default","%s:aud":"sts.amazonaws.com"}}}]}"""+ .formatted(ACCOUNT, untrustedIssuerPrefix, untrustedIssuerPrefix, untrustedIssuerPrefix);++ String wrongClusterRoleArn = createRole(wrongClusterRoleName, wrongClusterTrustPolicy);+ given()+ .contentType(FORM)+ .formParam("Action", "AssumeRoleWithWebIdentity")+ .formParam("Version", "2011-06-15")+ .formParam("RoleArn", wrongClusterRoleArn)+ .formParam("RoleSessionName", "wrong-cluster-session")+ .formParam("WebIdentityToken", token)+ .when()+ .post("/")+ .then()+ .statusCode(403)+ .body(containsString("AccessDenied"));++ // 4. Negative case: tampered / invalid signature on token -> 400 InvalidIdentityToken+ given()+ .contentType(FORM)+ .formParam("Action", "AssumeRoleWithWebIdentity")+ .formParam("Version", "2011-06-15")+ .formParam("RoleArn", roleArn)+ .formParam("RoleSessionName", "tampered-token-session")+ .formParam("WebIdentityToken", token + "invalid-signature")+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body(containsString("InvalidIdentityToken"));+ }++ private String createRole(String name, String trustPolicy) {+ return given()+ .contentType(FORM)+ .formParam("Action", "CreateRole")+ .formParam("Version", "2010-05-08")+ .formParam("RoleName", name)+ .formParam("AssumeRolePolicyDocument", trustPolicy)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract().path("CreateRoleResponse.CreateRoleResult.Role.Arn");+ }++ private void deleteRole(String name) {+ try {+ given()+ .contentType(FORM)+ .formParam("Action", "DeleteRole")+ .formParam("Version", "2010-05-08")+ .formParam("RoleName", name)+ .when()+ .post("/");+ } catch (Exception ignored) {+ }+ }++ private boolean isDockerAvailable() {+ try {+ dockerClient.pingCmd().exec();+ return true;+ } catch (Exception e) {+ return false;+ }+ }++ record ExecResult(long exitCode, String stdout, String stderr) {}++ private ExecResult execInContainerWithExitCode(String containerId, String[] cmd) throws Exception {+ ExecCreateCmdResponse exec = dockerClient.execCreateCmd(containerId)+ .withCmd(cmd)+ .withAttachStdout(true)+ .withAttachStderr(true)+ .exec();++ StringBuilder stdout = new StringBuilder();+ StringBuilder stderr = new StringBuilder();+ boolean completed = dockerClient.execStartCmd(exec.getId())+ .exec(new ResultCallback.Adapter<Frame>() {+ @Override+ public void onNext(Frame frame) {+ if (frame != null && frame.getPayload() != null) {+ String text = new String(frame.getPayload(), StandardCharsets.UTF_8);+ if (frame.getStreamType() == com.github.dockerjava.api.model.StreamType.STDERR) {+ stderr.append(text);+ } else {+ stdout.append(text);+ }+ }+ }+ })+ .awaitCompletion(30, TimeUnit.SECONDS);++ if (!completed) {+ throw new RuntimeException("exec timed out in container " + containerId);+ }+ Long exitCode = dockerClient.inspectExecCmd(exec.getId()).exec().getExitCodeLong();+ return new ExecResult(exitCode != null ? exitCode : -1L, stdout.toString(), stderr.toString());+ }++ private String execInContainer(String containerId, String[] cmd) throws Exception {+ ExecResult result = execInContainerWithExitCode(containerId, cmd);+ if (result.exitCode() != 0) {+ throw new RuntimeException("exec failed with code " + result.exitCode() + ": " + result.stderr());+ }+ return result.stdout();+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksOidcServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksOidcServiceTest.javaindex 5592ff7eaa..8cdd917f2f 100644--- a/src/test/java/io/github/hectorvent/floci/services/eks/EksOidcServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksOidcServiceTest.java@@ -11,12 +11,20 @@ import io.github.hectorvent.floci.services.eks.model.ClusterOidcKey;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;+import java.nio.charset.StandardCharsets;+import java.security.KeyFactory;+import java.security.PrivateKey;+import java.security.PublicKey;+import java.security.Signature;+import java.security.spec.PKCS8EncodedKeySpec;+import java.security.spec.X509EncodedKeySpec;import java.util.Base64;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.assertNotEquals;+import static org.junit.jupiter.api.Assertions.assertNotNull;import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;@@ -162,4 +170,82 @@ class EksOidcServiceTest {assertFalse(payload.contains("\n"), "raw newline leaked into the JWT payload");assertTrue(payload.contains("\\n"));}++ @Test+ void exportSigningKeyPemProducesValidPkcs8MatchingClusterKey() throws Exception {+ ClusterOidcKey key = oidcService.ensureKey(CLUSTER, ISSUER);+ String pem = oidcService.exportSigningKeyPem(key);++ assertTrue(pem.startsWith("-----BEGIN PRIVATE KEY-----\n"));+ assertTrue(pem.endsWith("-----END PRIVATE KEY-----\n"));++ String base64 = pem.replace("-----BEGIN PRIVATE KEY-----", "")+ .replace("-----END PRIVATE KEY-----", "")+ .replaceAll("\\s+", "");+ assertEquals(key.getPrivateKey(), base64);++ PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(base64));+ PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(spec);+ assertNotNull(privateKey);+ assertEquals("PKCS#8", privateKey.getFormat());+ }++ @Test+ void exportPublicKeyPemProducesValidX509MatchingClusterKey() throws Exception {+ ClusterOidcKey key = oidcService.ensureKey(CLUSTER, ISSUER);+ String pem = oidcService.exportPublicKeyPem(key);++ assertTrue(pem.startsWith("-----BEGIN PUBLIC KEY-----\n"));+ assertTrue(pem.endsWith("-----END PUBLIC KEY-----\n"));++ String base64 = pem.replace("-----BEGIN PUBLIC KEY-----", "")+ .replace("-----END PUBLIC KEY-----", "")+ .replaceAll("\\s+", "");+ assertEquals(key.getPublicKey(), base64);++ X509EncodedKeySpec spec = new X509EncodedKeySpec(Base64.getDecoder().decode(base64));+ PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(spec);+ assertNotNull(publicKey);+ assertEquals("X.509", publicKey.getFormat());+ }++ @Test+ void exportedKeyPairSignsAndVerifies() throws Exception {+ ClusterOidcKey key = oidcService.ensureKey(CLUSTER, ISSUER);+ String signingPem = oidcService.exportSigningKeyPem(key);+ String publicPem = oidcService.exportPublicKeyPem(key);++ String privateBase64 = signingPem.replace("-----BEGIN PRIVATE KEY-----", "")+ .replace("-----END PRIVATE KEY-----", "")+ .replaceAll("\\s+", "");+ String publicBase64 = publicPem.replace("-----BEGIN PUBLIC KEY-----", "")+ .replace("-----END PUBLIC KEY-----", "")+ .replaceAll("\\s+", "");++ PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(+ new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateBase64)));+ PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(+ new X509EncodedKeySpec(Base64.getDecoder().decode(publicBase64)));++ byte[] payload = "test-jwt-header.test-jwt-claims".getBytes(StandardCharsets.UTF_8);+ Signature signer = Signature.getInstance("SHA256withRSA");+ signer.initSign(privateKey);+ signer.update(payload);+ byte[] signature = signer.sign();++ Signature verifier = Signature.getInstance("SHA256withRSA");+ verifier.initVerify(publicKey);+ verifier.update(payload);+ assertTrue(verifier.verify(signature), "signature must verify against exported public key");+ }++ @Test+ void exportThrowsOnNullKeyOrField() {+ assertThrows(IllegalArgumentException.class, () -> oidcService.exportSigningKeyPem(null));+ assertThrows(IllegalArgumentException.class, () -> oidcService.exportPublicKeyPem(null));++ ClusterOidcKey incomplete = new ClusterOidcKey(ISSUER, "kid", null, null);+ assertThrows(IllegalArgumentException.class, () -> oidcService.exportSigningKeyPem(incomplete));+ assertThrows(IllegalArgumentException.class, () -> oidcService.exportPublicKeyPem(incomplete));+ }}diff --git a/src/test/resources/application.yml b/src/test/resources/application.ymlindex 45c3bf0be5..9a000e6712 100644--- a/src/test/resources/application.yml+++ b/src/test/resources/application.yml@@ -313,6 +313,7 @@ floci:mock: trueecr-registry-mirror: trueimds: false+ irsa-signing-key: truemwaa:enabled: truemock: true