feat(eks): authenticate EC2 workers through access entries (#3805)

This commit is contained in:
luiseterc authored and GitHub committed 2026-09-17 10:09:21 -04:00
1 parent 459e2bbe7a
commit 6b389c33eb
16 files changed
+464 -34

No files matched your search

@@ -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)));
@@ -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<String, Object> 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";
}
}
@@ -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"
+ "&region=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"));
@@ -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<String, Object> 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<String, Object> 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"));
}
@@ -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<Map<String, Object>> 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));
}
}