diff --git a/docs/services/eks.md b/docs/services/eks.md index 5429b9aade..4d42f65bf8 100644 --- a/docs/services/eks.md +++ b/docs/services/eks.md @@ -37,8 +37,22 @@ The four access-entry management operations support `STANDARD` (the default) and Access entries use EKS storage and retain the IAM principal's stable ID internally. Cluster deletion removes its entries, and a cluster recreated with the same name does not inherit previous entries or pagination tokens. -!!! note "Management API scope" - These operations currently manage metadata only. They do not change the k3s token webhook's authorization behavior, create cluster-creator or managed-node entries automatically, or make native workers register. Authentication mode and the bootstrap flag are recorded; they are not yet enforced by the Kubernetes API server. Updating authentication mode, UpdateAccessEntry, access-policy association, and entry tag updates are not implemented. Worker authentication is a separate follow-up. +### EC2 Linux worker authentication + +IMDS instance-profile credentials authenticate through a matching `EC2_LINUX` entry as +`system:node:` with `system:bootstrappers` and `system:nodes` groups. +The webhook verifies the signed token, cluster account/region/incarnation, stored role ID, +running EC2 instance, and attached instance profile. Missing/deleted entries, recreated roles, +revoked sessions and terminated instances are rejected without falling back to administrator access. +The existing k3s webhook cache can retain a successful authentication for up to 30 seconds. + +New cluster webhook configurations carry the target account, region and creation timestamp. +Recreate older local clusters before using worker authentication; a legacy unscoped webhook +rejects instance credentials. Obtain fresh IMDS credentials after upgrading so the session +includes the stable role ID. + +!!! note "Authentication scope" + Non-worker IAM users and ordinary STS sessions retain the existing cluster-admin compatibility behavior. STANDARD entries, access policies, aws-auth ConfigMap, the cluster-creator bootstrap flag and automatic managed-node entries are not enforced by this change. Updating authentication mode, UpdateAccessEntry, access-policy association, and entry tag updates remain unimplemented. Native AL2023 images, bootstrap RBAC/CSR approval, CNI and worker networking are separate requirements for registration and Ready. ```bash aws --endpoint-url http://localhost:4566 eks create-cluster \ @@ -72,7 +86,7 @@ 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 contains a SigV4-presigned STS `GetCallerIdentity` request. Floci validates its signature and 60-second presign expiry, then verifies the signed `x-k8s-aws-id` header against the cluster-specific `/_floci/eks/clusters//token-webhook` endpoint before mapping the caller to the `system:masters` group (bound to `cluster-admin`). No `aws-iam-authenticator` is required. +`aws eks update-kubeconfig` wires `aws eks get-token` into the kubeconfig as an exec credential. The bearer token contains a SigV4-presigned STS `GetCallerIdentity` request. Floci validates its signature and 60-second presign expiry, then verifies the signed `x-k8s-aws-id` header against the cluster-specific `/_floci/eks/clusters//token-webhook` endpoint before resolving the caller identity. Instance-profile sessions require an EC2_LINUX access entry as described above; non-worker callers retain the `system:masters` mapping (bound to `cluster-admin`). No `aws-iam-authenticator` is required. Create an IAM access key before using EKS authentication. The public local-development pairs `test`/`test` and `floci`/`floci` are deliberately rejected because the webhook grants cluster-admin access. diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceCredentials.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceCredentials.java index 18fa63993a..8f44ca8061 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceCredentials.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceCredentials.java @@ -95,6 +95,7 @@ final class Ec2InstanceCredentials { SessionCredential session = new SessionCredential(accessKey, randomString(30), randomString(48), role.getArn(), now.plusSeconds(3600), null, account); session.setEc2InstanceId(instance.getInstanceId()); + session.setEc2RoleId(role.getRoleId()); iam.registerEc2InstanceSession(session); history.add(new Issued(session, role.getRoleId(), instance.getIamInstanceProfileArn())); return Optional.of(session); diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java index 74b670f6a8..d7ab8f0ed6 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java @@ -4632,6 +4632,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider { return kp; } + public Optional findInstanceForAccount(String accountId, String region, String instanceId) { + return instances instanceof AccountAwareStorageBackend aware + ? aware.getForAccount(accountId, key(region, instanceId)) : instances.get(key(region, instanceId)); + } + public Instance findInstanceById(String instanceId) { return instances.scan(k -> true).stream() .filter(i -> instanceId.equals(i.getInstanceId())) diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksAccessEntryService.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksAccessEntryService.java index 103628a4ba..642e88f982 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eks/EksAccessEntryService.java +++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksAccessEntryService.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.eks; import com.fasterxml.jackson.core.type.TypeReference; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.eks.model.AccessEntry; @@ -22,6 +23,7 @@ import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.UUID; /** Access-entry management metadata; Kubernetes authorization is handled separately. */ @@ -132,6 +134,15 @@ public class EksAccessEntryService { return entry; } + synchronized Optional workerEntry(Cluster cluster, String accountId, String principal, String roleId) { + requireApiAccess(cluster); + String key = prefix(cluster) + principal; + Optional stored = entries instanceof AccountAwareStorageBackend aware + ? aware.getForAccount(accountId, key) : entries.get(key); + return stored.filter(value -> roleId != null && roleId.equals(value.principalId())) + .map(StoredEntry::entry).filter(entry -> "EC2_LINUX".equals(entry.type())); + } + public synchronized AccessEntry describe(Cluster cluster, String principal) { requireApiAccess(cluster); return entries.get(prefix(cluster) + principal).map(StoredEntry::entry) 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 c2b5d3b7dc..153a3a5d9f 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 @@ -210,14 +210,14 @@ public class EksClusterManager { } // 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 and mapped to their Kubernetes identity. The k3s API server POSTs a TokenReview to Floci's // _floci/eks/clusters//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()); + webhookLocalFile = writeWebhookKubeconfig(cluster); if (webhookLocalFile != null) { specBuilder.withHostDockerInternalOnLinux(); serverArgs.add("--kube-apiserver-arg=authentication-token-webhook-config-file=" @@ -567,12 +567,14 @@ public class EksClusterManager { * 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) { + private String writeWebhookKubeconfig(Cluster cluster) { + String clusterName = cluster.getName(); 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(clusterName))); + Files.writeString(localFile, buildWebhookKubeconfig("http://" + dockerHostResolver.resolve() + ":" + + config.port() + webhookPath(cluster))); } catch (IOException e) { LOG.warnv("EKS token-webhook disabled for cluster {0}: could not write kubeconfig: {1}", clusterName, e.getMessage()); @@ -697,6 +699,11 @@ public class EksClusterManager { return "http://" + dockerHostResolver.resolve() + ":" + config.port() + webhookPath(clusterName); } + static String webhookPath(Cluster cluster) { + return webhookPath(cluster.getName()) + "?accountId=" + cluster.getAccountId() + + "®ion=" + cluster.getArn().split(":", 6)[3] + "&createdAt=" + cluster.getCreatedAt(); + } + static String webhookPath(String clusterName) { return "/_floci/eks/clusters/" + clusterName + "/token-webhook"; } diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksService.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksService.java index dc847b066b..d6c99b0492 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eks/EksService.java +++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksService.java @@ -38,6 +38,7 @@ import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.UUID; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; @@ -302,6 +303,11 @@ public class EksService implements TagHandler, ResourceProvider { cluster.setEndpoint("https://localhost:" + config.services().eks().apiServerBasePort()); } + public Optional findAuthenticationCluster(String accountId, String name) { + return storage instanceof AccountAwareStorageBackend aware + ? aware.getForAccount(accountId, name) : storage.get(name); + } + public Cluster describeCluster(String name) { return storage.get(name) .orElseThrow(() -> new AwsException("ResourceNotFoundException", diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksTokenValidator.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksTokenValidator.java index e8df4806d4..3bc2f47fc5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eks/EksTokenValidator.java +++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksTokenValidator.java @@ -54,32 +54,38 @@ class EksTokenValidator { this.clock = clock; } + record VerifiedToken(String accessKeyId, String region) {} + boolean validate(String token, String clusterName) { + return verify(token, clusterName).isPresent(); + } + + Optional verify(String token, String clusterName) { if (token == null || clusterName == null || clusterName.isBlank() || token.length() > MAX_TOKEN_LENGTH) { - return false; + return Optional.empty(); } try { URI request = parseToken(token); if (request == null) { - return false; + return Optional.empty(); } Map parameters = parseQuery(request.getRawQuery()); if (!hasExpectedRequestShape(request, parameters)) { - return false; + return Optional.empty(); } CredentialScope scope = parseCredentialScope(parameters.get("X-Amz-Credential")); Instant signedAt = Instant.from(DATETIME_FORMAT.parse(parameters.get("X-Amz-Date"))); if (!isCurrent(signedAt, parameters.get("X-Amz-Expires")) || !scope.date().equals(parameters.get("X-Amz-Date").substring(0, 8))) { - return false; + return Optional.empty(); } String secretKey = secretKey(scope.accessKeyId(), parameters.get("X-Amz-Security-Token")); if (secretKey == null) { - return false; + return Optional.empty(); } String canonicalRequest = canonicalRequest(request, parameters, clusterName); @@ -89,12 +95,13 @@ class EksTokenValidator { + sha256Hex(canonicalRequest); String expectedSignature = hexEncode(hmacSha256( deriveSigningKey(secretKey, scope.date(), scope.region(), scope.service()), stringToSign)); - return MessageDigest.isEqual( + boolean valid = MessageDigest.isEqual( expectedSignature.getBytes(StandardCharsets.UTF_8), parameters.get("X-Amz-Signature").getBytes(StandardCharsets.UTF_8)); + return valid ? Optional.of(new VerifiedToken(scope.accessKeyId(), scope.region())) : Optional.empty(); } catch (Exception exception) { LOG.debugv("EKS IAM token validation rejected a malformed token: {0}", exception.getMessage()); - return false; + return Optional.empty(); } } 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 index 13c1d9d2ee..2d6ead6026 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eks/EksTokenWebhookController.java +++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksTokenWebhookController.java @@ -7,12 +7,13 @@ import jakarta.ws.rs.POST; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; 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; +import java.util.Optional; /** * Kubernetes token-authentication webhook for k3s-backed EKS clusters. @@ -20,8 +21,8 @@ import java.util.Map; *

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.} token produced by {@code aws eks get-token}. Floci validates - * the request signature, expiration, and signed cluster ID before mapping the token to the - * {@code system:masters} group, which is bound to {@code cluster-admin} by default. + * the request signature, expiration, and signed cluster ID before resolving worker access entries. + * Non-worker credentials retain the legacy cluster-admin compatibility behavior. * *

This is Floci plumbing under the {@code _floci/...} namespace, not an AWS API. */ @@ -33,34 +34,36 @@ public class EksTokenWebhookController { private static final Logger LOG = Logger.getLogger(EksTokenWebhookController.class); private final EksTokenValidator tokenValidator; + private final EksWorkerAuthentication authentication; @Inject - public EksTokenWebhookController(EksTokenValidator tokenValidator) { + public EksTokenWebhookController(EksTokenValidator tokenValidator, EksWorkerAuthentication authentication) { this.tokenValidator = tokenValidator; + this.authentication = authentication; } @POST - public Response review(@PathParam("clusterName") String clusterName, Map tokenReview) { + public Response review(@PathParam("clusterName") String clusterName, @QueryParam("accountId") String accountId, + @QueryParam("region") String region, @QueryParam("createdAt") String createdAt, + Map 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 = tokenValidator.validate(token, clusterName); + Optional> user = tokenValidator.verify(token, clusterName) + .flatMap(verified -> authentication.authenticate(verified, clusterName, accountId, region, createdAt)); - if (authenticated) { - LOG.debugv("EKS token-webhook: authenticated aws-iam token for cluster {0} as cluster-admin", + if (user.isPresent()) { + LOG.debugv("EKS token-webhook: authenticated aws-iam token for cluster {0}", clusterName); 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(); + "user", user.get()))).build(); } LOG.debugv("EKS token-webhook: rejected aws-iam token for cluster {0}", clusterName); diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksWorkerAuthentication.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksWorkerAuthentication.java new file mode 100644 index 0000000000..b0f3d20a49 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksWorkerAuthentication.java @@ -0,0 +1,96 @@ +package io.github.hectorvent.floci.services.eks; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.ec2.Ec2Service; +import io.github.hectorvent.floci.services.ec2.model.Instance; +import io.github.hectorvent.floci.services.eks.model.Cluster; +import io.github.hectorvent.floci.services.iam.IamService; +import io.github.hectorvent.floci.services.iam.IamService.EksSessionIdentity; +import io.github.hectorvent.floci.services.iam.model.IamRole; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** Maps verified instance credentials to node identities using server-owned EC2 metadata. */ +@ApplicationScoped +class EksWorkerAuthentication { + private final IamService iam; + private final EksService eks; + private final Ec2Service ec2; + private final EksAccessEntryService entries; + + @Inject + EksWorkerAuthentication(IamService iam, EksService eks, Ec2Service ec2, EksAccessEntryService entries) { + this.iam = iam; + this.eks = eks; + this.ec2 = ec2; + this.entries = entries; + } + + Optional> authenticate(EksTokenValidator.VerifiedToken token, String name, + String account, String region, String createdAt) { + Optional session = iam.findEksSessionIdentity(token.accessKeyId()); + // Keep the existing non-worker compatibility path. Expired/revoked temporary sessions + // must never fall through to it after signature validation. + if (session.isEmpty()) { + return IamService.isTemporaryAccessKey(token.accessKeyId()) ? Optional.empty() : legacyIdentity(); + } + EksSessionIdentity identity = session.get(); + if (identity.instanceId() == null) { + return legacyIdentity(); + } + if (account == null || region == null || createdAt == null || !account.equals(identity.accountId()) + || !region.equals(token.region()) || identity.roleArn() == null || identity.roleId() == null) { + return Optional.empty(); + } + Optional cluster = eks.findAuthenticationCluster(account, name) + .filter(value -> value.getArn() != null && value.getArn().equals( + "arn:aws:eks:" + region + ":" + account + ":cluster/" + name)) + .filter(value -> createdAt.equals(String.valueOf(value.getCreatedAt()))); + if (cluster.isEmpty()) { + return Optional.empty(); + } + String roleName = identity.roleArn().substring(identity.roleArn().lastIndexOf('/') + 1); + Optional role = iam.findRole(account, roleName) + .filter(value -> identity.roleArn().equals(value.getArn()) && identity.roleId().equals(value.getRoleId())); + if (role.isEmpty()) { + return Optional.empty(); + } + try { + if (entries.workerEntry(cluster.get(), account, identity.roleArn(), identity.roleId()).isEmpty()) { + return Optional.empty(); + } + } catch (AwsException rejected) { + return Optional.empty(); + } + Optional instance = ec2.findInstanceForAccount(account, region, identity.instanceId()) + .filter(value -> value.getState() != null && "running".equals(value.getState().getName())) + .filter(value -> region.equals(value.getRegion())) + .filter(value -> profileMatches(value, account, roleName)); + if (instance.isEmpty() || instance.get().getPrivateDnsName() == null + || instance.get().getPrivateDnsName().isBlank()) { + return Optional.empty(); + } + return Optional.of(Map.of("username", "system:node:" + instance.get().getPrivateDnsName(), + "uid", account + ":" + identity.roleId() + ":" + identity.instanceId(), + "groups", List.of("system:bootstrappers", "system:nodes"))); + } + + private boolean profileMatches(Instance instance, String account, String roleName) { + String arn = instance.getIamInstanceProfileArn(); + if (arn == null || !arn.startsWith("arn:aws:iam::" + account + ":instance-profile/")) { + return false; + } + return iam.findInstanceProfile(account, arn.substring(arn.lastIndexOf('/') + 1)) + .filter(profile -> arn.equals(profile.getArn())) + .filter(profile -> List.of(roleName).equals(profile.getRoleNames())).isPresent(); + } + + private static Optional> legacyIdentity() { + return Optional.of(Map.of("username", "floci:aws-iam", "uid", "floci-aws-iam", + "groups", List.of("system:masters"))); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java index b3ee30084d..3bff7656f8 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java @@ -1883,6 +1883,14 @@ public class IamService implements SessionAccountLookup, ResourceProvider { .map(AccessKey::getSecretAccessKey); } + public record EksSessionIdentity(String accountId, String roleArn, String roleId, String instanceId) {} + + /** Returns only identity metadata, never the session secret or token. */ + public Optional findEksSessionIdentity(String accessKeyId) { + return currentSession(accessKeyId).map(session -> new EksSessionIdentity( + session.getOriginAccountId(), session.getRoleArn(), session.getEc2RoleId(), session.getEc2InstanceId())); + } + private Optional currentSession(String accessKeyId) { return findSessionAnyAccount(accessKeyId) .filter(session -> session.getExpiration() == null || Instant.now().isBefore(session.getExpiration())); diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCredential.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCredential.java index 9b33b4563c..412119ea60 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCredential.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCredential.java @@ -24,6 +24,7 @@ public class SessionCredential { /** True when this session belongs to a Floci-launched Lambda container. */ private boolean lambdaExecutionRole; private String ec2InstanceId; + private String ec2RoleId; public SessionCredential() {} @@ -92,6 +93,9 @@ public class SessionCredential { public String getOriginAccountId() { return originAccountId; } public void setOriginAccountId(String originAccountId) { this.originAccountId = originAccountId; } + public String getEc2RoleId() { return ec2RoleId; } + public void setEc2RoleId(String ec2RoleId) { this.ec2RoleId = ec2RoleId; } + public String getEc2InstanceId() { return ec2InstanceId; } public void setEc2InstanceId(String ec2InstanceId) { this.ec2InstanceId = ec2InstanceId; } diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceCredentialsTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceCredentialsTest.java index 4b79863785..107c0f9ff0 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceCredentialsTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceCredentialsTest.java @@ -32,6 +32,7 @@ class Ec2InstanceCredentialsTest { assertEquals(40, first.getSecretAccessKey().length()); assertEquals(ACCOUNT, first.getOriginAccountId()); assertEquals("i-first", first.getEc2InstanceId()); + assertEquals(fixture.role.getRoleId(), first.getEc2RoleId()); assertEquals(NOW.plusSeconds(3600), first.getExpiration()); verify(fixture.iam).registerEc2InstanceSession(first); assertSame(first, fixture.get(NOW.plusSeconds(3299))); diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/EksWorkerAuthenticationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/EksWorkerAuthenticationIntegrationTest.java new file mode 100644 index 0000000000..f74410ef65 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/EksWorkerAuthenticationIntegrationTest.java @@ -0,0 +1,99 @@ +package io.github.hectorvent.floci.services.ec2; + +import io.github.hectorvent.floci.services.ec2.model.Instance; +import io.github.hectorvent.floci.services.ec2.model.InstanceState; +import io.github.hectorvent.floci.services.eks.EksService; +import io.github.hectorvent.floci.services.iam.IamService; +import io.github.hectorvent.floci.services.iam.model.SessionCredential; +import io.github.hectorvent.floci.testutil.SigV4TokenTestHelper; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +import java.time.Instant; +import java.util.Map; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.*; + +@QuarkusTest +class EksWorkerAuthenticationIntegrationTest { + @Inject IamService iam; + @Inject Ec2Service ec2; + @Inject EksService eks; + + @Test + void instanceCredentialsAuthenticateOnlyWithMatchingLiveAccessEntry() throws Exception { + String account = "246813579012"; + String name = "worker-auth-" + UUID.randomUUID().toString().substring(0, 8); + String roleArn = "arn:aws:iam::" + account + ":role/path/" + name; + String profileArn = "arn:aws:iam::" + account + ":instance-profile/" + name; + given().header("Authorization", auth(account, "iam")) + .formParam("Action", "CreateRole").formParam("RoleName", name).formParam("Path", "/path/") + .formParam("AssumeRolePolicyDocument", "{}").post("/").then().statusCode(200); + given().header("Authorization", auth(account, "iam")) + .formParam("Action", "CreateInstanceProfile").formParam("InstanceProfileName", name) + .post("/").then().statusCode(200); + given().header("Authorization", auth(account, "iam")) + .formParam("Action", "AddRoleToInstanceProfile").formParam("InstanceProfileName", name) + .formParam("RoleName", name).post("/").then().statusCode(200); + String instanceId = given().header("Authorization", auth(account, "ec2")) + .formParam("Action", "RunInstances").formParam("ImageId", "ami-0abcdef1234567890") + .formParam("InstanceType", "t3.micro").formParam("MinCount", "1").formParam("MaxCount", "1") + .formParam("IamInstanceProfile.Arn", profileArn).post("/").then().statusCode(200) + .extract().path("RunInstancesResponse.instancesSet.item.instanceId"); + given().header("Authorization", auth(account, "eks")).contentType("application/json") + .body(Map.of("name", name, "roleArn", roleArn, "accessConfig", + Map.of("authenticationMode", "API", "bootstrapClusterCreatorAdminPermissions", false))) + .post("/clusters").then().statusCode(200); + Ec2InstanceCredentials credentials = new Ec2InstanceCredentials(iam); + try { + Instance instance = ec2.findInstanceForAccount(account, "us-east-1", instanceId).orElseThrow(); + // Mock EC2 launches remain pending because no container manager runs in this profile. + instance.setState(InstanceState.running()); + credentials.register(instance); + SessionCredential session = credentials.get(instance, name, Instant.now()).orElseThrow(); + String token = SigV4TokenTestHelper.createEksToken(name, session.getAccessKeyId(), + session.getSecretAccessKey(), Instant.now(), 60, session.getSessionToken()); + String incarnation = eks.findAuthenticationCluster(account, name).orElseThrow().getCreatedAt().toString(); + String path = "/_floci/eks/clusters/" + name + "/token-webhook"; + Map review = Map.of("apiVersion", "authentication.k8s.io/v1", "kind", "TokenReview", + "spec", Map.of("token", token)); + given().queryParam("accountId", account).queryParam("region", "us-east-1") + .queryParam("createdAt", incarnation).contentType("application/json").body(review) + .post(path).then().statusCode(200).body("status.authenticated", equalTo(false)); + given().header("Authorization", auth(account, "eks")).contentType("application/json") + .body(Map.of("principalArn", roleArn, "type", "EC2_LINUX")) + .post("/clusters/" + name + "/access-entries").then().statusCode(200); + given().queryParam("accountId", account).queryParam("region", "us-east-1") + .queryParam("createdAt", incarnation).contentType("application/json").body(review) + .post(path).then().statusCode(200).body("status.authenticated", equalTo(true)) + .body("status.user.username", equalTo("system:node:" + instance.getPrivateDnsName())) + .body("status.user.groups", contains("system:bootstrappers", "system:nodes")); + given().queryParam("accountId", "999999999999").queryParam("region", "us-east-1") + .queryParam("createdAt", incarnation).contentType("application/json").body(review) + .post(path).then().statusCode(200).body("status.authenticated", equalTo(false)); + credentials.unregister(instance); + given().queryParam("accountId", account).queryParam("region", "us-east-1") + .queryParam("createdAt", incarnation).contentType("application/json").body(review) + .post(path).then().statusCode(200).body("status.authenticated", equalTo(false)); + } finally { + credentials.clear(); + given().header("Authorization", auth(account, "eks")).delete("/clusters/" + name).then().statusCode(200); + given().header("Authorization", auth(account, "ec2")).formParam("Action", "TerminateInstances") + .formParam("InstanceId.1", instanceId).post("/").then().statusCode(200); + given().header("Authorization", auth(account, "iam")).formParam("Action", "RemoveRoleFromInstanceProfile") + .formParam("InstanceProfileName", name).formParam("RoleName", name).post("/").then().statusCode(200); + given().header("Authorization", auth(account, "iam")).formParam("Action", "DeleteInstanceProfile") + .formParam("InstanceProfileName", name).post("/").then().statusCode(200); + given().header("Authorization", auth(account, "iam")).formParam("Action", "DeleteRole") + .formParam("RoleName", name).post("/").then().statusCode(200); + } + } + + private static String auth(String account, String service) { + return "AWS4-HMAC-SHA256 Credential=" + account + + "/20260917/us-east-1/" + service + "/aws4_request, SignedHeaders=host, Signature=abc"; + } +} 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 index 76037be657..34fc86efe0 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 @@ -37,6 +37,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.mockito.Mockito; +import java.time.Instant; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; @@ -59,6 +60,17 @@ import static org.mockito.Mockito.when; class EksClusterManagerTest { + @Test + void workerWebhookBindsAccountRegionAndClusterIncarnation() { + Cluster cluster = new Cluster(); + cluster.setName("demo"); + cluster.setAccountId("123456789012"); + cluster.setArn("arn:aws:eks:us-west-2:123456789012:cluster/demo"); + cluster.setCreatedAt(Instant.parse("2026-09-17T00:00:00Z")); + assertEquals("/_floci/eks/clusters/demo/token-webhook?accountId=123456789012" + + "®ion=us-west-2&createdAt=2026-09-17T00:00:00Z", EksClusterManager.webhookPath(cluster)); + } + @Test void webhookPathBindsAuthenticationToOneCluster() { assertEquals("/_floci/eks/clusters/demo/token-webhook", EksClusterManager.webhookPath("demo")); 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 index f595111718..78726d38b8 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eks/EksTokenWebhookControllerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksTokenWebhookControllerTest.java @@ -22,7 +22,7 @@ class EksTokenWebhookControllerTest { private final IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey( ACCESS_KEY_ID, SECRET_ACCESS_KEY); private final EksTokenWebhookController controller = new EksTokenWebhookController( - new EksTokenValidator(iamService)); + new EksTokenValidator(iamService), new EksWorkerAuthentication(iamService, null, null, null)); @SuppressWarnings("unchecked") private Map status(Response response) { @@ -40,7 +40,7 @@ class EksTokenWebhookControllerTest { @Test @SuppressWarnings("unchecked") void awsIamTokenAuthenticatesAsClusterAdmin() throws Exception { - Response response = controller.review(CLUSTER_NAME, tokenReview(validToken())); + Response response = controller.review(CLUSTER_NAME, null, null, null, tokenReview(validToken())); Map status = status(response); assertEquals(Boolean.TRUE, status.get("authenticated")); @@ -51,20 +51,20 @@ class EksTokenWebhookControllerTest { @Test void unrecognisedTokenIsRejected() { - Response response = controller.review(CLUSTER_NAME, tokenReview("some-random-bearer-token")); + Response response = controller.review(CLUSTER_NAME, null, null, null, tokenReview("some-random-bearer-token")); assertEquals(Boolean.FALSE, status(response).get("authenticated")); } @Test void emptyOrMalformedReviewIsRejected() { - assertFalse((Boolean) status(controller.review(CLUSTER_NAME, Map.of())).get("authenticated")); - assertFalse((Boolean) status(controller.review(CLUSTER_NAME, + assertFalse((Boolean) status(controller.review(CLUSTER_NAME, null, null, null, Map.of())).get("authenticated")); + assertFalse((Boolean) status(controller.review(CLUSTER_NAME, null, null, null, Map.of("spec", Map.of()))).get("authenticated")); } @Test void responseIsAlwaysAWellFormedTokenReview() throws Exception { - Response response = controller.review(CLUSTER_NAME, tokenReview(validToken())); + Response response = controller.review(CLUSTER_NAME, null, null, null, tokenReview(validToken())); Map body = (Map) response.getEntity(); assertEquals("authentication.k8s.io/v1", body.get("apiVersion")); assertEquals("TokenReview", body.get("kind")); @@ -80,7 +80,7 @@ class EksTokenWebhookControllerTest { "kind", "TokenReview", "spec", Map.of("token", validToken())); - Response response = controller.review(CLUSTER_NAME, v1beta1Review); + Response response = controller.review(CLUSTER_NAME, null, null, null, v1beta1Review); Map body = (Map) response.getEntity(); assertEquals("authentication.k8s.io/v1beta1", body.get("apiVersion")); assertEquals(Boolean.TRUE, status(response).get("authenticated")); @@ -91,7 +91,7 @@ class EksTokenWebhookControllerTest { String token = SigV4TokenTestHelper.createEksToken( "other-cluster", ACCESS_KEY_ID, SECRET_ACCESS_KEY, Instant.now(), 60); - Response response = controller.review(CLUSTER_NAME, tokenReview(token)); + Response response = controller.review(CLUSTER_NAME, null, null, null, tokenReview(token)); assertEquals(Boolean.FALSE, status(response).get("authenticated")); } diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksWorkerAuthenticationTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksWorkerAuthenticationTest.java new file mode 100644 index 0000000000..f1576019cd --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksWorkerAuthenticationTest.java @@ -0,0 +1,156 @@ +package io.github.hectorvent.floci.services.eks; + +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.services.ec2.Ec2Service; +import io.github.hectorvent.floci.services.ec2.model.Instance; +import io.github.hectorvent.floci.services.ec2.model.InstanceState; +import io.github.hectorvent.floci.services.eks.model.AccessConfig; +import io.github.hectorvent.floci.services.eks.model.Cluster; +import io.github.hectorvent.floci.services.eks.model.ClusterStatus; +import io.github.hectorvent.floci.services.eks.model.CreateAccessEntryRequest; +import io.github.hectorvent.floci.services.iam.IamService; +import io.github.hectorvent.floci.services.iam.IamService.EksSessionIdentity; +import io.github.hectorvent.floci.services.iam.model.IamRole; +import io.github.hectorvent.floci.services.iam.model.InstanceProfile; +import io.github.hectorvent.floci.testutil.SigV4TokenTestHelper; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class EksWorkerAuthenticationTest { + private static final String ACCOUNT = "123456789012"; + private static final String REGION = "us-east-1"; + private static final String ROLE = "arn:aws:iam::" + ACCOUNT + ":role/path/worker"; + private static final String KEY = "ASIAWORKER"; + private static final Instant CREATED = Instant.parse("2026-09-17T00:00:00Z"); + private final IamService iam = mock(IamService.class); + private final EksService eks = mock(EksService.class); + private final Ec2Service ec2 = mock(Ec2Service.class); + private final EksAccessEntryService entries = new EksAccessEntryService(new InMemoryStorage<>(), iam); + private final Cluster cluster = new Cluster(); + private final Instance instance = new Instance(); + private final IamRole role = new IamRole("AROA-original", "worker", "/path/", ROLE, "{}"); + private final EksWorkerAuthentication auth = new EksWorkerAuthentication(iam, eks, ec2, entries); + private final EksTokenValidator.VerifiedToken verified = new EksTokenValidator.VerifiedToken(KEY, REGION); + + @BeforeEach + void setup() { + cluster.setName("demo"); + cluster.setArn("arn:aws:eks:" + REGION + ":" + ACCOUNT + ":cluster/demo"); + cluster.setCreatedAt(CREATED); + cluster.setStatus(ClusterStatus.ACTIVE); + cluster.setAccessConfig(new AccessConfig("API", false)); + instance.setInstanceId("i-worker"); + instance.setRegion(REGION); + instance.setState(InstanceState.running()); + instance.setPrivateDnsName("ip-10-0-0-1.ec2.internal"); + instance.setIamInstanceProfileArn("arn:aws:iam::" + ACCOUNT + ":instance-profile/path/worker-profile"); + InstanceProfile profile = new InstanceProfile("AIPA", "worker-profile", "/path/", instance.getIamInstanceProfileArn()); + profile.setRoleNames(List.of("worker")); + when(iam.findRole(ACCOUNT, "worker")).thenReturn(Optional.of(role)); + when(iam.findInstanceProfile(ACCOUNT, "worker-profile")).thenReturn(Optional.of(profile)); + when(iam.findEksSessionIdentity(KEY)).thenReturn(Optional.of( + new EksSessionIdentity(ACCOUNT, ROLE, role.getRoleId(), instance.getInstanceId()))); + when(eks.findAuthenticationCluster(ACCOUNT, "demo")).thenReturn(Optional.of(cluster)); + when(ec2.findInstanceForAccount(ACCOUNT, REGION, "i-worker")).thenReturn(Optional.of(instance)); + createEntry("EC2_LINUX"); + } + + @Test + void signedWorkerTokenProducesNodeIdentityWithoutAdministratorGroup() throws Exception { + when(iam.findSecretKey(KEY, "session-token")).thenReturn(Optional.of("worker-secret")); + String token = SigV4TokenTestHelper.createEksToken("demo", KEY, "worker-secret", Instant.now(), 60, "session-token"); + EksTokenWebhookController controller = new EksTokenWebhookController(new EksTokenValidator(iam), auth); + Map response = (Map) controller.review("demo", ACCOUNT, REGION, CREATED.toString(), + Map.of("spec", Map.of("token", token))).getEntity(); + Map status = (Map) response.get("status"); + assertEquals(true, status.get("authenticated")); + Map user = (Map) status.get("user"); + assertEquals("system:node:ip-10-0-0-1.ec2.internal", user.get("username")); + assertEquals(List.of("system:bootstrappers", "system:nodes"), user.get("groups")); + when(iam.findSecretKey(KEY, "session-token")).thenReturn(Optional.empty()); + response = (Map) controller.review("demo", ACCOUNT, REGION, CREATED.toString(), + Map.of("spec", Map.of("token", token))).getEntity(); + assertEquals(Map.of("authenticated", false), response.get("status")); + } + + @Test + void missingOrStandardEntryDoesNotFallBackToAdministrator() { + entries.delete(cluster, ROLE); + assertTrue(authenticate().isEmpty()); + createEntry("STANDARD"); + assertTrue(authenticate().isEmpty()); + } + + @Test + void changedRoleIdInvalidatesEntryAndOldInstanceCredentials() { + role.setRoleId("AROA-recreated"); + assertTrue(authenticate().isEmpty()); + when(iam.findEksSessionIdentity(KEY)).thenReturn(Optional.of( + new EksSessionIdentity(ACCOUNT, ROLE, role.getRoleId(), "i-worker"))); + assertTrue(authenticate().isEmpty()); + entries.delete(cluster, ROLE); + createEntry("EC2_LINUX"); + assertTrue(authenticate().isPresent()); + } + + @Test + void missingStoppedOrUnprofiledInstanceIsRejected() { + instance.setState(InstanceState.terminated()); + assertTrue(authenticate().isEmpty()); + instance.setState(InstanceState.running()); + instance.setIamInstanceProfileArn(null); + assertTrue(authenticate().isEmpty()); + when(ec2.findInstanceForAccount(ACCOUNT, REGION, "i-worker")).thenReturn(Optional.empty()); + assertTrue(authenticate().isEmpty()); + } + + @Test + void wrongTargetOrClusterIncarnationIsRejected() { + assertTrue(auth.authenticate(verified, "demo", "999999999999", REGION, CREATED.toString()).isEmpty()); + assertTrue(auth.authenticate(verified, "demo", ACCOUNT, "us-west-2", CREATED.toString()).isEmpty()); + assertTrue(auth.authenticate(verified, "other", ACCOUNT, REGION, CREATED.toString()).isEmpty()); + assertTrue(auth.authenticate(verified, "demo", null, null, null).isEmpty()); + cluster.setCreatedAt(CREATED.plusSeconds(1)); + assertTrue(authenticate().isEmpty()); + assertTrue(auth.authenticate(verified, "demo", ACCOUNT, REGION, cluster.getCreatedAt().toString()).isEmpty()); + } + + @Test + void configMapAndInactiveClustersRejectWorkers() { + cluster.setStatus(ClusterStatus.CREATING); + assertTrue(authenticate().isEmpty()); + cluster.setStatus(ClusterStatus.ACTIVE); + cluster.setAccessConfig(new AccessConfig("CONFIG_MAP", false)); + assertTrue(authenticate().isEmpty()); + } + + @Test + void revokedSessionDoesNotFallBackToAdministrator() { + when(iam.findEksSessionIdentity(KEY)).thenReturn(Optional.empty()); + assertTrue(authenticate().isEmpty()); + } + + @Test + void missingRoleIdOrPrivateDnsIsRejected() { + instance.setPrivateDnsName(""); + assertTrue(authenticate().isEmpty()); + when(iam.findEksSessionIdentity(KEY)).thenReturn(Optional.of(new EksSessionIdentity(ACCOUNT, ROLE, null, "i-worker"))); + assertTrue(authenticate().isEmpty()); + } + + private Optional> authenticate() { + return auth.authenticate(verified, "demo", ACCOUNT, REGION, CREATED.toString()); + } + + private void createEntry(String type) { + entries.create(cluster, new CreateAccessEntryRequest(ROLE, type, null, null, null, null)); + } +}