feat(eks): implement access-entry management (#3745)

* feat(eks): implement access-entry management

* test(eks): wait for cluster activation in access-entry compatibility test

* fix(eks): validate access-entry maxResults with shared parser
This commit is contained in:
luiseterc authored and GitHub committed 2026-09-16 18:50:39 -04:00
1 parent 2b091608af
commit 98c47c4347
14 files changed
+687 -21

No files matched your search

@@ -0,0 +1,77 @@
package com.floci.test;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.waiters.WaiterResponse;
import software.amazon.awssdk.services.eks.EksClient;
import software.amazon.awssdk.services.eks.model.*;
import software.amazon.awssdk.services.eks.waiters.EksWaiter;
import software.amazon.awssdk.services.iam.IamClient;
import java.time.Duration;
import java.util.Map;
import java.util.UUID;
import static org.assertj.core.api.Assertions.*;
class EksAccessEntryTest {
@Test
void sdkRoundTripPaginationAndClusterCleanup() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String cluster = "access-" + suffix;
String firstRole = "access-a-" + suffix;
String secondRole = "access-b-" + suffix;
try (EksClient eks = TestFixtures.eksClient(); IamClient iam = TestFixtures.iamClient()) {
String first = iam.createRole(builder -> builder.roleName(firstRole).path("/nodes/")
.assumeRolePolicyDocument("{}")).role().arn();
String second = iam.createRole(builder -> builder.roleName(secondRole)
.assumeRolePolicyDocument("{}")).role().arn();
try {
createCluster(eks, cluster, first);
CreateAccessEntryRequest request = CreateAccessEntryRequest.builder().clusterName(cluster)
.principalArn(first).type("EC2_LINUX").tags(Map.of("team", "platform"))
.clientRequestToken("sdk-retry").build();
AccessEntry entry = eks.createAccessEntry(request).accessEntry();
assertThat(entry.username()).isEqualTo("system:node:{{EC2PrivateDNSName}}");
assertThat(entry.kubernetesGroups()).containsExactly("system:nodes");
assertThat(entry.createdAt()).isNotNull();
assertThat(entry.tags()).containsEntry("team", "platform");
assertThat(eks.createAccessEntry(request).accessEntry().accessEntryArn()).isEqualTo(entry.accessEntryArn());
assertThat(eks.describeAccessEntry(builder -> builder.clusterName(cluster).principalArn(first))
.accessEntry().principalArn()).isEqualTo(first);
eks.createAccessEntry(builder -> builder.clusterName(cluster).principalArn(second));
ListAccessEntriesResponse page = eks.listAccessEntries(builder -> builder.clusterName(cluster).maxResults(1));
assertThat(page.accessEntries()).hasSize(1);
assertThat(page.nextToken()).isNotBlank();
ListAccessEntriesResponse next = eks.listAccessEntries(builder -> builder.clusterName(cluster)
.maxResults(1).nextToken(page.nextToken()));
assertThat(next.accessEntries()).hasSize(1).doesNotContain(page.accessEntries().get(0));
assertThat(next.nextToken()).isNull();
eks.deleteAccessEntry(builder -> builder.clusterName(cluster).principalArn(first));
assertThatThrownBy(() -> eks.describeAccessEntry(builder -> builder.clusterName(cluster).principalArn(first)))
.isInstanceOf(ResourceNotFoundException.class);
eks.deleteCluster(builder -> builder.name(cluster));
createCluster(eks, cluster, first);
assertThat(eks.listAccessEntries(builder -> builder.clusterName(cluster)).accessEntries()).isEmpty();
} finally {
eks.deleteCluster(builder -> builder.name(cluster));
iam.deleteRole(builder -> builder.roleName(firstRole));
iam.deleteRole(builder -> builder.roleName(secondRole));
}
}
}
private static void createCluster(EksClient eks, String name, String role) {
eks.createCluster(builder -> builder.name(name).roleArn(role)
.resourcesVpcConfig(VpcConfigRequest.builder().build())
.accessConfig(CreateAccessConfigRequest.builder().authenticationMode(AuthenticationMode.API)
.bootstrapClusterCreatorAdminPermissions(false).build()));
try (EksWaiter waiter = eks.waiter()) {
WaiterResponse<DescribeClusterResponse> result = waiter.waitUntilClusterActive(
request -> request.name(name),
configuration -> configuration.waitTimeout(Duration.ofMinutes(3)));
assertThat(result.matched().response())
.withFailMessage("Cluster %s did not become ACTIVE: %s", name, result.matched().exception())
.isPresent();
}
}
}
+26
View File
@@ -13,6 +13,10 @@ EKS uses a standard REST API with JSON bodies — not the JSON 1.1 (`X-Amz-Targe
| `DescribeCluster` | Describe a cluster by name |
| `ListClusters` | List all cluster names |
| `DeleteCluster` | Delete a cluster |
| `CreateAccessEntry` | Create STANDARD or EC2_LINUX access-entry metadata |
| `DescribeAccessEntry` | Describe an access entry by IAM principal ARN |
| `ListAccessEntries` | List principal ARNs with pagination |
| `DeleteAccessEntry` | Delete access-entry metadata |
| `CreateNodegroup` | Create node group metadata for a cluster |
| `DescribeNodegroup` | Describe a node group by cluster and name |
| `ListNodegroups` | List node group names for a cluster |
@@ -25,6 +29,28 @@ EKS uses a standard REST API with JSON bodies — not the JSON 1.1 (`X-Amz-Targe
| `UntagResource` | Remove tags from a cluster |
| `ListTagsForResource` | List tags on a cluster |
## Access-entry management
`CreateCluster` accepts `accessConfig.authenticationMode` (`CONFIG_MAP`, `API_AND_CONFIG_MAP`, or `API`) and `bootstrapClusterCreatorAdminPermissions`. The API default is `CONFIG_MAP`; access-entry operations require an ACTIVE cluster created with `API` or `API_AND_CONFIG_MAP`.
The four access-entry management operations support `STANDARD` (the default) and `EC2_LINUX`. STANDARD accepts existing IAM users or roles, including principals in another account. EC2_LINUX requires a role in the cluster account and generates `system:node:{{EC2PrivateDNSName}}`; custom usernames and Kubernetes groups are not accepted for node entries. Tags supplied at creation are preserved. Repeating a create with the same client token and normalized parameters returns the existing entry. Listing accepts `maxResults` from 1 to 100 and cluster-specific `nextToken` values.
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.
```bash
aws --endpoint-url http://localhost:4566 eks create-cluster \
--name local-nodes --role-arn arn:aws:iam::000000000000:role/cluster \
--resources-vpc-config '{}' \
--access-config authenticationMode=API,bootstrapClusterCreatorAdminPermissions=false
# The IAM role must already exist.
aws --endpoint-url http://localhost:4566 eks create-access-entry \
--cluster-name local-nodes --principal-arn arn:aws:iam::000000000000:role/worker \
--type EC2_LINUX
```
## Modes
### Mock mode (`mock: true`)
@@ -0,0 +1,202 @@
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.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.eks.model.AccessEntry;
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.model.IamRole;
import io.github.hectorvent.floci.services.iam.model.IamUser;
import io.quarkus.runtime.annotations.RegisterForReflection;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Base64;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
/** Access-entry management metadata; Kubernetes authorization is handled separately. */
@ApplicationScoped
public class EksAccessEntryService {
private final StorageBackend<String, StoredEntry> entries;
private final IamService iam;
@Inject
public EksAccessEntryService(StorageFactory factory, IamService iam) {
this(factory.create("eks", "eks-access-entries.json", new TypeReference<Map<String, StoredEntry>>() {}), iam);
}
EksAccessEntryService(StorageBackend<String, StoredEntry> entries, IamService iam) {
this.entries = entries;
this.iam = iam;
}
@RegisterForReflection
public record StoredEntry(AccessEntry entry, String principalId, String clientRequestToken) {}
@RegisterForReflection
public record Page(List<String> accessEntries, String nextToken) {}
public synchronized AccessEntry create(Cluster cluster, CreateAccessEntryRequest request) {
requireApiAccess(cluster);
if (request == null || request.principalArn() == null) {
throw invalid("principalArn is required");
}
String type = request.type() == null ? "STANDARD" : request.type();
if (!"STANDARD".equals(type) && !"EC2_LINUX".equals(type)) {
throw invalid("Floci currently supports STANDARD and EC2_LINUX access entries");
}
boolean node = "EC2_LINUX".equals(type);
if (node && (request.username() != null || request.kubernetesGroups() != null)) {
throw invalid("EC2_LINUX entries cannot specify username or kubernetesGroups");
}
String principal = request.principalArn();
String[] arn = principal.split(":", 6);
String[] clusterArn = cluster.getArn().split(":", 6);
if (arn.length != 6 || !"arn".equals(arn[0]) || !arn[1].equals(clusterArn[1])
|| !"iam".equals(arn[2]) || !arn[3].isEmpty() || !arn[4].matches("[0-9]{12}")
|| !(arn[5].startsWith("role/") || (!node && arn[5].startsWith("user/")))
|| arn[5].startsWith("role/aws-service-role/")
|| principal.endsWith("/") || (node && !arn[4].equals(clusterArn[4]))) {
throw invalid("principalArn must identify an IAM principal; EC2_LINUX requires a role in the cluster account");
}
String name = principal.substring(principal.lastIndexOf('/') + 1);
boolean role = arn[5].startsWith("role/");
String principalId = role
? iam.findRole(arn[4], name).filter(value -> principal.equals(value.getArn()))
.map(IamRole::getRoleId).orElseThrow(() -> invalid("IAM role does not exist"))
: iam.findUser(arn[4], name).filter(value -> principal.equals(value.getArn()))
.map(IamUser::getUserId).orElseThrow(() -> invalid("IAM user does not exist"));
String username = node ? "system:node:{{EC2PrivateDNSName}}" : request.username();
if (username != null && !node && (username.isBlank()
|| username.matches("^(system|eks|aws|amazon|iam):.*"))) {
throw invalid("Invalid username");
}
if (username != null && !node) {
for (String placeholder : List.of("{{SessionName}}", "{{SessionNameRaw}}")) {
int position = username.indexOf(placeholder);
if (position >= 0 && !username.substring(0, position).contains(":")) {
throw invalid("A session-name placeholder must be preceded by a colon");
}
}
}
if (username == null) {
username = role ? "arn:" + arn[1] + ":sts::" + arn[4] + ":assumed-role/" + name + "/{{SessionName}}"
: principal;
}
List<String> groups = node ? List.of("system:nodes")
: request.kubernetesGroups() == null ? List.of() : request.kubernetesGroups();
if (groups.stream().anyMatch(group -> group == null || group.isBlank())) {
throw invalid("kubernetesGroups must contain nonempty strings");
}
Map<String, String> tags = request.tags() == null ? Map.of() : request.tags();
if (tags.size() > 50 || tags.entrySet().stream().anyMatch(tag -> tag.getKey() == null
|| tag.getKey().isEmpty() || tag.getKey().length() > 128 || tag.getValue() == null
|| tag.getValue().length() > 256)) {
throw invalid("Invalid access entry tags");
}
String prefix = prefix(cluster);
String token = request.clientRequestToken();
if (token != null) {
for (StoredEntry stored : entries.scan(key -> key.startsWith(prefix))) {
if (token.equals(stored.clientRequestToken())) {
AccessEntry previous = stored.entry();
if (principal.equals(previous.principalArn()) && type.equals(previous.type())
&& username.equals(previous.username()) && groups.equals(previous.kubernetesGroups())
&& tags.equals(previous.tags())) {
return previous;
}
throw invalid("clientRequestToken was already used with different parameters");
}
}
}
String key = prefix + principal;
if (entries.get(key).isPresent()) {
throw new AwsException("ResourceInUseException", "Access entry already exists", 409);
}
double now = Instant.now().toEpochMilli() / 1000.0;
AccessEntry entry = new AccessEntry("arn:" + clusterArn[1] + ":eks:" + clusterArn[3] + ":"
+ clusterArn[4] + ":access-entry/" + cluster.getName() + "/" + (role ? "role" : "user")
+ "/" + arn[4] + "/" + name + "/" + UUID.randomUUID(), cluster.getName(), principal,
type, username, List.copyOf(groups), Map.copyOf(tags), now, now);
entries.put(key, new StoredEntry(entry, principalId, token));
return entry;
}
public synchronized AccessEntry describe(Cluster cluster, String principal) {
requireApiAccess(cluster);
return entries.get(prefix(cluster) + principal).map(StoredEntry::entry)
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Access entry not found", 404));
}
public synchronized void delete(Cluster cluster, String principal) {
describe(cluster, principal);
entries.delete(prefix(cluster) + principal);
}
public synchronized Page list(Cluster cluster, Integer maxResults, String nextToken) {
requireApiAccess(cluster);
int limit = maxResults == null ? 100 : maxResults;
if (limit < 1 || limit > 100) {
throw invalid("maxResults must be between 1 and 100");
}
String prefix = prefix(cluster);
String after = "";
if (nextToken != null) {
try {
String decoded = new String(Base64.getUrlDecoder().decode(nextToken), StandardCharsets.UTF_8);
if (!decoded.startsWith(prefix + "\n")) {
throw invalid("nextToken does not belong to this cluster");
}
after = decoded.substring(prefix.length() + 1);
if (after.isBlank()) {
throw invalid("Invalid nextToken");
}
} catch (IllegalArgumentException exception) {
throw invalid("Invalid nextToken");
}
}
String cursor = after;
List<String> remaining = entries.scan(key -> key.startsWith(prefix)).stream()
.map(stored -> stored.entry().principalArn()).filter(principal -> principal.compareTo(cursor) > 0)
.sorted(Comparator.naturalOrder()).toList();
List<String> page = remaining.stream().limit(limit).toList();
String token = remaining.size() > limit ? Base64.getUrlEncoder().withoutPadding().encodeToString(
(prefix + "\n" + page.getLast()).getBytes(StandardCharsets.UTF_8)) : null;
return new Page(page, token);
}
public synchronized void deleteClusterEntries(Cluster cluster) {
String prefix = prefix(cluster);
for (StoredEntry stored : entries.scan(key -> key.startsWith(prefix))) {
entries.delete(prefix + stored.entry().principalArn());
}
}
private static String prefix(Cluster cluster) {
// A recreated cluster must not inherit access entries or pagination tokens from its predecessor.
return cluster.getArn() + "/" + Objects.toString(cluster.getCreatedAt()) + "/";
}
private static void requireApiAccess(Cluster cluster) {
if (cluster.getAccessConfig() == null || "CONFIG_MAP".equals(cluster.getAccessConfig().authenticationMode())) {
throw new AwsException("InvalidRequestException", "Cluster authentication mode must be API or API_AND_CONFIG_MAP", 400);
}
if (cluster.getStatus() != ClusterStatus.ACTIVE) {
throw new AwsException("InvalidRequestException", "Cluster must be ACTIVE", 400);
}
}
private static AwsException invalid(String message) {
return new AwsException("InvalidParameterException", message, 400);
}
}
@@ -1,6 +1,8 @@
package io.github.hectorvent.floci.services.eks;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.services.eks.model.Cluster;
import io.github.hectorvent.floci.services.eks.model.CreateAccessEntryRequest;
import io.github.hectorvent.floci.services.eks.model.CreateClusterRequest;
import io.github.hectorvent.floci.services.eks.model.CreateFargateProfileRequest;
import io.github.hectorvent.floci.services.eks.model.CreateNodeGroupRequest;
@@ -14,6 +16,7 @@ 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;
@@ -33,10 +36,12 @@ import java.util.Map;
public class EksController {
private final EksService eksService;
private final EksAccessEntryService accessEntries;
@Inject
public EksController(EksService eksService) {
public EksController(EksService eksService, EksAccessEntryService accessEntries) {
this.eksService = eksService;
this.accessEntries = accessEntries;
}
@POST
@@ -134,11 +139,34 @@ public class EksController {
// (issue #1754, same family as #1137): validate the cluster, then return the documented
// empty list under each operation's model-exact result key.
@POST
@Path("/clusters/{name}/access-entries")
public Response createAccessEntry(@PathParam("name") String name, CreateAccessEntryRequest request) {
return Response.ok(Map.of("accessEntry", accessEntries.create(eksService.describeCluster(name), request))).build();
}
@GET
@Path("/clusters/{name}/access-entries")
public Response listAccessEntries(@PathParam("name") String name) {
eksService.describeCluster(name);
return Response.ok(Map.of("accessEntries", List.of())).build();
public Response listAccessEntries(@PathParam("name") String name,
@QueryParam("maxResults") String maxResults,
@QueryParam("nextToken") String nextToken) {
EksAccessEntryService.Page page = accessEntries.list(eksService.describeCluster(name),
Pagination.parseMaxResults(maxResults, "InvalidParameterException"), nextToken);
return Response.ok(page.nextToken() == null ? Map.of("accessEntries", page.accessEntries())
: Map.of("accessEntries", page.accessEntries(), "nextToken", page.nextToken())).build();
}
@GET
@Path("/clusters/{name}/access-entries/{principalArn: .+}")
public Response describeAccessEntry(@PathParam("name") String name, @PathParam("principalArn") String principalArn) {
return Response.ok(Map.of("accessEntry", accessEntries.describe(eksService.describeCluster(name), principalArn))).build();
}
@DELETE
@Path("/clusters/{name}/access-entries/{principalArn: .+}")
public Response deleteAccessEntry(@PathParam("name") String name, @PathParam("principalArn") String principalArn) {
accessEntries.delete(eksService.describeCluster(name), principalArn);
return Response.ok(Map.of()).build();
}
@GET
@@ -11,6 +11,7 @@ import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
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.AccessConfig;
import io.github.hectorvent.floci.services.eks.model.ClusterIdentity;
import io.github.hectorvent.floci.services.eks.model.ClusterStatus;
import io.github.hectorvent.floci.services.eks.model.OidcIdentity;
@@ -64,12 +65,13 @@ public class EksService implements TagHandler, ResourceProvider {
private final EksClusterManager clusterManager;
private final Ec2Service ec2Service;
private final EksOidcService oidcService;
private final EksAccessEntryService accessEntries;
private final ScheduledExecutorService poller = Executors.newSingleThreadScheduledExecutor();
@Inject
public EksService(StorageFactory storageFactory, EmulatorConfig config,
RegionResolver regionResolver, EksClusterManager clusterManager, Ec2Service ec2Service,
EksOidcService oidcService) {
EksOidcService oidcService, EksAccessEntryService accessEntries) {
this.storage = storageFactory.create("eks", "eks-clusters.json",
new TypeReference<Map<String, Cluster>>() {
});
@@ -84,6 +86,7 @@ public class EksService implements TagHandler, ResourceProvider {
this.clusterManager = clusterManager;
this.ec2Service = ec2Service;
this.oidcService = oidcService;
this.accessEntries = accessEntries;
}
@PostConstruct
@@ -235,6 +238,15 @@ public class EksService implements TagHandler, ResourceProvider {
"Cluster already exists: " + name, 409);
}
AccessConfig requestedAccess = request.getAccessConfig();
String authenticationMode = requestedAccess == null || requestedAccess.authenticationMode() == null
? "CONFIG_MAP" : requestedAccess.authenticationMode();
if (!Set.of("CONFIG_MAP", "API_AND_CONFIG_MAP", "API").contains(authenticationMode)) {
throw new AwsException("InvalidParameterException", "Invalid authenticationMode", 400);
}
AccessConfig accessConfig = new AccessConfig(authenticationMode,
requestedAccess == null || requestedAccess.bootstrapClusterCreatorAdminPermissions() == null
|| requestedAccess.bootstrapClusterCreatorAdminPermissions());
String region = regionResolver.getRegion();
String resolvedVpcId = validateSubnetsAndResolveVpcId(region, request.getResourcesVpcConfig());
String accountId = regionResolver.getAccountId();
@@ -242,6 +254,7 @@ public class EksService implements TagHandler, ResourceProvider {
Cluster cluster = new Cluster();
cluster.setName(name);
cluster.setAccessConfig(accessConfig);
cluster.setArn(arn);
cluster.setAccountId(accountId);
cluster.setCreatedAt(Instant.now());
@@ -310,6 +323,7 @@ public class EksService implements TagHandler, ResourceProvider {
if (!config.services().eks().mock()) {
clusterManager.stopCluster(cluster);
}
accessEntries.deleteClusterEntries(cluster);
storage.delete(name);
oidcService.deleteKey(name);
return cluster;
@@ -0,0 +1,6 @@
package io.github.hectorvent.floci.services.eks.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
public record AccessConfig(String authenticationMode, Boolean bootstrapClusterCreatorAdminPermissions) {}
@@ -0,0 +1,11 @@
package io.github.hectorvent.floci.services.eks.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
import java.util.Map;
@RegisterForReflection
public record AccessEntry(String accessEntryArn, String clusterName, String principalArn, String type,
String username, List<String> kubernetesGroups, Map<String, String> tags,
double createdAt, double modifiedAt) {}
@@ -73,6 +73,11 @@ public class Cluster {
@JsonIgnore
private String dockerName;
private AccessConfig accessConfig;
public AccessConfig getAccessConfig() { return accessConfig; }
public void setAccessConfig(AccessConfig accessConfig) { this.accessConfig = accessConfig; }
public Cluster() {}
public String getName() { return name; }
@@ -0,0 +1,13 @@
package io.github.hectorvent.floci.services.eks.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
import java.util.Map;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public record CreateAccessEntryRequest(String principalArn, String type, String username,
List<String> kubernetesGroups, Map<String, String> tags,
String clientRequestToken) {}
@@ -31,6 +31,11 @@ public class CreateClusterRequest {
@JsonProperty("clientRequestToken")
private String clientRequestToken;
private AccessConfig accessConfig;
public AccessConfig getAccessConfig() { return accessConfig; }
public void setAccessConfig(AccessConfig accessConfig) { this.accessConfig = accessConfig; }
public CreateClusterRequest() {}
public String getName() { return name; }
@@ -0,0 +1,117 @@
package io.github.hectorvent.floci.services.eks;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
@QuarkusTest
class EksAccessEntryIntegrationTest {
@Test
void nodeEntryRoundTripUsesJsonAndEncodedPrincipalPaths() {
String account = "135791357913";
String name = "entries-" + UUID.randomUUID().toString().substring(0, 8);
String role = "worker-" + name;
String principal = "arn:aws:iam::" + account + ":role/path/" + role;
String path = "/clusters/" + name + "/access-entries";
String entryPath = path + "/" + URLEncoder.encode(principal, StandardCharsets.UTF_8);
given().header("Authorization", auth(account, "iam")).contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateRole").formParam("RoleName", role).formParam("Path", "/path/")
.formParam("AssumeRolePolicyDocument", "{}").post("/").then().statusCode(200);
createCluster(account, name, "API");
try {
Map<String, Object> request = Map.of("principalArn", principal, "type", "EC2_LINUX",
"tags", Map.of("team", "platform"), "clientRequestToken", "retry-token");
String arn = given().header("Authorization", auth(account, "eks")).contentType("application/json")
.body(request).post(path).then().statusCode(200)
.body("accessEntry.username", equalTo("system:node:{{EC2PrivateDNSName}}"))
.body("accessEntry.createdAt", instanceOf(Number.class))
.body("accessEntry.tags.team", equalTo("platform"))
.body("accessEntry.principalId", nullValue())
.extract().path("accessEntry.accessEntryArn");
given().header("Authorization", auth(account, "eks")).contentType("application/json")
.body(request).post(path).then().statusCode(200)
.body("accessEntry.accessEntryArn", equalTo(arn));
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
.get(entryPath).then().statusCode(200).contentType(containsString("application/json"))
.body("accessEntry.principalArn", equalTo(principal));
given().header("Authorization", auth(account, "eks")).get(path).then().statusCode(200)
.body("accessEntries", contains(principal)).body("nextToken", nullValue());
given().header("Authorization", auth("246802468024", "eks")).get(path).then().statusCode(404);
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
.delete(entryPath).then().statusCode(200).body(equalTo("{}"));
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
.get(entryPath).then().statusCode(404).body("__type", equalTo("ResourceNotFoundException"));
given().header("Authorization", auth(account, "eks")).contentType("application/json")
.body(request).post(path).then().statusCode(200);
given().header("Authorization", auth(account, "eks")).delete("/clusters/" + name)
.then().statusCode(200);
createCluster(account, name, "API");
given().header("Authorization", auth(account, "eks")).get(path).then().statusCode(200)
.body("accessEntries", empty());
} finally {
given().header("Authorization", auth(account, "eks")).delete("/clusters/" + name)
.then().statusCode(200);
given().header("Authorization", auth(account, "iam")).contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteRole").formParam("RoleName", role).post("/").then().statusCode(200);
}
}
@ParameterizedTest
@ValueSource(strings = {"abc", "1.5", "2147483648", "0", "-1", "101"})
void invalidMaxResultsReturnsAwsJsonError(String maxResults) {
String account = "135791357913";
String name = "pagination-" + UUID.randomUUID().toString().substring(0, 8);
createCluster(account, name, "API");
try {
given().header("Authorization", auth(account, "eks")).queryParam("maxResults", maxResults)
.get("/clusters/" + name + "/access-entries").then().statusCode(400)
.contentType(containsString("application/json"))
.body("__type", equalTo("InvalidParameterException"))
.body("message", not(emptyOrNullString()));
} finally {
given().header("Authorization", auth(account, "eks")).delete("/clusters/" + name)
.then().statusCode(200);
}
}
@Test
void configMapModeRejectsEntriesAndUnknownModeIsRejectedAtCreate() {
String name = "config-" + UUID.randomUUID().toString().substring(0, 8);
String account = "135791357913";
createCluster(account, name, "CONFIG_MAP");
try {
given().header("Authorization", auth(account, "eks"))
.get("/clusters/" + name + "/access-entries").then().statusCode(400)
.body("__type", equalTo("InvalidRequestException"));
given().header("Authorization", auth(account, "eks")).contentType("application/json")
.body(Map.of("name", name + "-invalid", "accessConfig", Map.of("authenticationMode", "invalid")))
.post("/clusters").then().statusCode(400).body("__type", equalTo("InvalidParameterException"));
} finally {
given().header("Authorization", auth(account, "eks")).delete("/clusters/" + name)
.then().statusCode(200);
}
}
private static void createCluster(String account, String name, String mode) {
given().header("Authorization", auth(account, "eks")).contentType("application/json")
.body(Map.of("name", name, "roleArn", "arn:aws:iam::" + account + ":role/cluster",
"accessConfig", Map.of("authenticationMode", mode, "bootstrapClusterCreatorAdminPermissions", false)))
.post("/clusters").then().statusCode(200)
.body("cluster.accessConfig.authenticationMode", equalTo(mode))
.body("cluster.accessConfig.bootstrapClusterCreatorAdminPermissions", equalTo(false));
}
private static String auth(String account, String service) {
return "AWS4-HMAC-SHA256 Credential=" + account
+ "/20260916/us-east-1/" + service + "/aws4_request, SignedHeaders=host, Signature=abc";
}
}
@@ -0,0 +1,162 @@
package io.github.hectorvent.floci.services.eks;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.eks.model.AccessConfig;
import io.github.hectorvent.floci.services.eks.model.AccessEntry;
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.model.IamRole;
import io.github.hectorvent.floci.services.iam.model.IamUser;
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 EksAccessEntryServiceTest {
private static final String PRINCIPAL = "arn:aws:iam::123456789012:role/path/worker";
@Test
void nodeEntryUsesGeneratedIdentityAndCapturesStablePrincipalId() throws Exception {
Fixture fixture = fixture();
AccessEntry entry = fixture.service.create(fixture.cluster, request(PRINCIPAL, "EC2_LINUX", "retry"));
assertEquals("system:node:{{EC2PrivateDNSName}}", entry.username());
assertEquals(List.of("system:nodes"), entry.kubernetesGroups());
assertEquals(Map.of("team", "platform"), entry.tags());
assertTrue(entry.createdAt() > 0);
EksAccessEntryService.StoredEntry stored = fixture.storage.scan(key -> true).getFirst();
assertEquals("AROA-worker", stored.principalId());
ObjectMapper mapper = new ObjectMapper();
EksAccessEntryService.StoredEntry restored = mapper.readValue(mapper.writeValueAsBytes(stored),
EksAccessEntryService.StoredEntry.class);
assertEquals(stored, restored);
assertFalse(mapper.writeValueAsString(entry).contains("principalId"));
fixture.role.setRoleId("AROA-recreated");
assertEquals("AROA-worker", fixture.storage.scan(key -> true).getFirst().principalId());
assertEquals(entry, fixture.service.describe(fixture.cluster, PRINCIPAL));
}
@Test
void retriesAreIdempotentButConflictingRequestsAndDuplicatesFail() {
Fixture fixture = fixture();
CreateAccessEntryRequest request = request(PRINCIPAL, "EC2_LINUX", "retry");
AccessEntry first = fixture.service.create(fixture.cluster, request);
assertEquals(first, fixture.service.create(fixture.cluster, request));
assertEquals("InvalidParameterException", assertThrows(AwsException.class, () -> fixture.service.create(
fixture.cluster, request(PRINCIPAL, "STANDARD", "retry"))).getErrorCode());
assertEquals(409, assertThrows(AwsException.class, () -> fixture.service.create(
fixture.cluster, request(PRINCIPAL, "EC2_LINUX", "other"))).getHttpStatus());
}
@Test
void standardRoleDefaultsStripTheIamPath() {
Fixture fixture = fixture();
AccessEntry entry = fixture.service.create(fixture.cluster, request(PRINCIPAL, null, null));
assertEquals("STANDARD", entry.type());
assertEquals("arn:aws:sts::123456789012:assumed-role/worker/{{SessionName}}", entry.username());
}
@Test
void standardUserCanBelongToAnotherAccount() {
Fixture fixture = fixture();
String principal = "arn:aws:iam::999999999999:user/team/reader";
when(fixture.iam.findUser("999999999999", "reader")).thenReturn(Optional.of(
new IamUser("AIDA-reader", "reader", "/team/", principal)));
AccessEntry entry = fixture.service.create(fixture.cluster,
new CreateAccessEntryRequest(principal, null, null, List.of("readers"), null, null));
assertEquals(principal, entry.username());
assertEquals(List.of("readers"), entry.kubernetesGroups());
assertEquals("AIDA-reader", fixture.storage.scan(key -> true).getFirst().principalId());
}
@Test
void nodeOverridesForeignAccountsAndMissingPrincipalsAreRejected() {
Fixture fixture = fixture();
assertThrows(AwsException.class, () -> fixture.service.create(fixture.cluster,
new CreateAccessEntryRequest(PRINCIPAL, "EC2_LINUX", "custom", null, null, null)));
assertThrows(AwsException.class, () -> fixture.service.create(fixture.cluster,
new CreateAccessEntryRequest(PRINCIPAL, "EC2_LINUX", null, List.of(), null, null)));
assertThrows(AwsException.class, () -> fixture.service.create(fixture.cluster,
request(PRINCIPAL.replace("123456789012", "999999999999"), "EC2_LINUX", null)));
when(fixture.iam.findRole("123456789012", "worker")).thenReturn(Optional.empty());
assertThrows(AwsException.class, () -> fixture.service.create(fixture.cluster,
request(PRINCIPAL, "STANDARD", null)));
}
@Test
void paginationTokensCannotCrossClusterOrAccountBoundaries() {
Fixture fixture = fixture();
fixture.service.create(fixture.cluster, request(PRINCIPAL, "STANDARD", null));
String second = PRINCIPAL.replace("worker", "worker2");
when(fixture.iam.findRole("123456789012", "worker2")).thenReturn(Optional.of(
new IamRole("AROA-second", "worker2", "/path/", second, "{}")));
fixture.service.create(fixture.cluster, request(second, "STANDARD", null));
EksAccessEntryService.Page first = fixture.service.list(fixture.cluster, 1, null);
assertEquals(List.of(PRINCIPAL), first.accessEntries());
assertNotNull(first.nextToken());
EksAccessEntryService.Page next = fixture.service.list(fixture.cluster, 1, first.nextToken());
assertEquals(List.of(second), next.accessEntries());
assertNull(next.nextToken());
assertThrows(AwsException.class, () -> fixture.service.list(fixture.cluster, 0, null));
assertThrows(AwsException.class, () -> fixture.service.list(fixture.cluster, 101, null));
assertThrows(AwsException.class, () -> fixture.service.list(fixture.cluster, 1, "invalid"));
fixture.cluster.setArn(fixture.cluster.getArn().replace("123456789012", "999999999999"));
assertTrue(fixture.service.list(fixture.cluster, 100, null).accessEntries().isEmpty());
assertThrows(AwsException.class, () -> fixture.service.list(fixture.cluster, 1, first.nextToken()));
}
@Test
void clusterDeletionCleansEntriesAndRecreationCannotInheritThem() {
Fixture fixture = fixture();
fixture.service.create(fixture.cluster, request(PRINCIPAL, "EC2_LINUX", null));
fixture.service.deleteClusterEntries(fixture.cluster);
assertTrue(fixture.storage.scan(key -> true).isEmpty());
fixture.service.create(fixture.cluster, request(PRINCIPAL, "EC2_LINUX", null));
fixture.cluster.setCreatedAt(fixture.cluster.getCreatedAt().plusSeconds(1));
assertTrue(fixture.service.list(fixture.cluster, null, null).accessEntries().isEmpty());
assertEquals(404, assertThrows(AwsException.class,
() -> fixture.service.describe(fixture.cluster, PRINCIPAL)).getHttpStatus());
}
@Test
void configMapAndInactiveClustersRejectAccessEntryOperations() {
Fixture fixture = fixture();
fixture.cluster.setAccessConfig(new AccessConfig("CONFIG_MAP", true));
assertEquals("InvalidRequestException", assertThrows(AwsException.class,
() -> fixture.service.list(fixture.cluster, null, null)).getErrorCode());
fixture.cluster.setAccessConfig(new AccessConfig("API", false));
fixture.cluster.setStatus(ClusterStatus.CREATING);
assertThrows(AwsException.class, () -> fixture.service.create(fixture.cluster,
request(PRINCIPAL, "EC2_LINUX", null)));
}
private static CreateAccessEntryRequest request(String principal, String type, String token) {
return new CreateAccessEntryRequest(principal, type, null, null, Map.of("team", "platform"), token);
}
private static Fixture fixture() {
Cluster cluster = new Cluster();
cluster.setName("nodes");
cluster.setArn("arn:aws:eks:us-east-1:123456789012:cluster/nodes");
cluster.setCreatedAt(Instant.parse("2026-09-16T10:00:00Z"));
cluster.setStatus(ClusterStatus.ACTIVE);
cluster.setAccessConfig(new AccessConfig("API", false));
IamService iam = mock(IamService.class);
IamRole role = new IamRole("AROA-worker", "worker", "/path/", PRINCIPAL, "{}");
when(iam.findRole("123456789012", "worker")).thenReturn(Optional.of(role));
InMemoryStorage<String, EksAccessEntryService.StoredEntry> storage = new InMemoryStorage<>();
return new Fixture(cluster, iam, role, storage, new EksAccessEntryService(storage, iam));
}
private record Fixture(Cluster cluster, IamService iam, IamRole role,
InMemoryStorage<String, EksAccessEntryService.StoredEntry> storage,
EksAccessEntryService service) {}
}
@@ -67,7 +67,7 @@ class EksServiceTest {
Ec2Service ec2Service = null;
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
eksService = new EksService(storageFactory, config, regionResolver, clusterManager, ec2Service,
new EksOidcService(storageFactory, new ObjectMapper()));
new EksOidcService(storageFactory, new ObjectMapper()), mock(EksAccessEntryService.class));
}
private EmulatorConfig testConfig() {
@@ -227,7 +227,7 @@ class EksServiceTest {
EksOidcService oidcService = new EksOidcService(
fixedStorageFactory(keyStore), new ObjectMapper());
EksService restarted = new EksService(fixedStorageFactory(clusterStore), testConfig(),
new RegionResolver("us-east-1", "000000000000"), null, null, oidcService);
new RegionResolver("us-east-1", "000000000000"), null, null, oidcService, mock(EksAccessEntryService.class));
restarted.init();
Cluster migrated = restarted.describeCluster("legacy-cluster");
@@ -251,7 +251,7 @@ class EksServiceTest {
EksOidcService oidcService = new EksOidcService(
fixedStorageFactory(keyStore), new ObjectMapper());
EksService restarted = new EksService(fixedStorageFactory(clusterStore), testConfig(),
new RegionResolver("us-east-1", "000000000000"), null, null, oidcService);
new RegionResolver("us-east-1", "000000000000"), null, null, oidcService, mock(EksAccessEntryService.class));
restarted.init();
// The issuer a trust policy was written against must survive a restart, and its key must
@@ -282,7 +282,7 @@ class EksServiceTest {
EksOidcService oidcService = new EksOidcService(
fixedStorageFactory(keyStore), new ObjectMapper());
new EksService(fixedStorageFactory(clusterStore), testConfig(),
new RegionResolver("us-east-1", "000000000000"), null, null, oidcService).init();
new RegionResolver("us-east-1", "000000000000"), null, null, oidcService, mock(EksAccessEntryService.class)).init();
Cluster migrated = clusterStore.getForAccount(otherAccount, "legacy-cluster").orElseThrow();
String issuer = migrated.getIdentity().getOidc().getIssuer();
@@ -316,7 +316,7 @@ class EksServiceTest {
EksService restarted = new EksService(fixedStorageFactory(clusterStore), testConfig(false),
new RegionResolver("us-east-1", "000000000000"), clusterManager, null,
new EksOidcService(fixedStorageFactory(new InMemoryStorage<String, ClusterOidcKey>()),
new ObjectMapper()));
new ObjectMapper()), mock(EksAccessEntryService.class));
try {
restarted.init();
@@ -356,7 +356,7 @@ class EksServiceTest {
EksService restarted = new EksService(fixedStorageFactory(clusterStore), testConfig(false),
new RegionResolver("us-east-1", "000000000000"), clusterManager, null,
new EksOidcService(fixedStorageFactory(new InMemoryStorage<String, ClusterOidcKey>()),
new ObjectMapper()));
new ObjectMapper()), mock(EksAccessEntryService.class));
try {
restarted.init();
@@ -390,7 +390,7 @@ class EksServiceTest {
EksService restarted = new EksService(fixedStorageFactory(clusterStore), testConfig(false),
new RegionResolver("us-east-1", "000000000000"), clusterManager, null,
new EksOidcService(fixedStorageFactory(new InMemoryStorage<String, ClusterOidcKey>()),
new ObjectMapper()));
new ObjectMapper()), mock(EksAccessEntryService.class));
try {
restarted.init();
@@ -419,7 +419,7 @@ class EksServiceTest {
EksService restarted = new EksService(fixedStorageFactory(clusterStore), testConfig(false),
new RegionResolver("us-east-1", "000000000000"), clusterManager, null,
new EksOidcService(fixedStorageFactory(new InMemoryStorage<String, ClusterOidcKey>()),
new ObjectMapper()));
new ObjectMapper()), mock(EksAccessEntryService.class));
try {
restarted.init();
@@ -446,7 +446,7 @@ class EksServiceTest {
EksService restarted = new EksService(fixedStorageFactory(clusterStore), testConfig(false),
new RegionResolver("us-east-1", "000000000000"), clusterManager, null,
new EksOidcService(fixedStorageFactory(new InMemoryStorage<String, ClusterOidcKey>()),
new ObjectMapper()));
new ObjectMapper()), mock(EksAccessEntryService.class));
try {
restarted.init();
@@ -521,7 +521,7 @@ class EksServiceTest {
};
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
EksService service = new EksService(storageFactory, testConfig(), regionResolver, null, realEc2Service(),
new EksOidcService(storageFactory, new ObjectMapper()));
new EksOidcService(storageFactory, new ObjectMapper()), mock(EksAccessEntryService.class));
ResourcesVpcConfig vpcConfig = new ResourcesVpcConfig();
vpcConfig.setSubnetIds(List.of("subnet-1", "subnet-2"));
@@ -548,7 +548,7 @@ class EksServiceTest {
};
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
EksService service = new EksService(storageFactory, testConfig(), regionResolver, null, realEc2Service(),
new EksOidcService(storageFactory, new ObjectMapper()));
new EksOidcService(storageFactory, new ObjectMapper()), mock(EksAccessEntryService.class));
ResourcesVpcConfig vpcConfig = new ResourcesVpcConfig();
vpcConfig.setSubnetIds(List.of(Ec2Service.defaultSubnetId("us-east-1", "a"),
@@ -583,7 +583,7 @@ class EksServiceTest {
};
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
EksService service = new EksService(storageFactory, testConfig(), regionResolver, null,
realEc2Service(), new EksOidcService(storageFactory, new ObjectMapper()));
realEc2Service(), new EksOidcService(storageFactory, new ObjectMapper()), mock(EksAccessEntryService.class));
ResourcesVpcConfig vpcConfig = new ResourcesVpcConfig();
vpcConfig.setSubnetIds(List.of(Ec2Service.defaultSubnetId("us-east-1", "a"),
@@ -613,7 +613,7 @@ class EksServiceTest {
};
RegionResolver regionResolver = new RegionResolver("eu-west-2", "000000000000");
EksService service = new EksService(storageFactory, testConfig(), regionResolver, null,
realEc2Service(), new EksOidcService(storageFactory, new ObjectMapper()));
realEc2Service(), new EksOidcService(storageFactory, new ObjectMapper()), mock(EksAccessEntryService.class));
ResourcesVpcConfig vpcConfig = new ResourcesVpcConfig();
vpcConfig.setSubnetIds(List.of(Ec2Service.defaultSubnetId("eu-west-2", "a")));
@@ -660,7 +660,7 @@ class EksServiceTest {
// The request is for eu-west-2, where that subnet does not exist.
RegionResolver regionResolver = new RegionResolver("eu-west-2", "000000000000");
EksService service = new EksService(storageFactory, testConfig(), regionResolver, null,
ec2Service, new EksOidcService(storageFactory, new ObjectMapper()));
ec2Service, new EksOidcService(storageFactory, new ObjectMapper()), mock(EksAccessEntryService.class));
ResourcesVpcConfig vpcConfig = new ResourcesVpcConfig();
vpcConfig.setSubnetIds(List.of(usEastOnlySubnet));
@@ -991,7 +991,7 @@ class EksServiceTest {
};
return new EksService(storageFactory, testConfig(mock),
new RegionResolver("us-east-1", "000000000000"), clusterManager, null,
new EksOidcService(storageFactory, new ObjectMapper()));
new EksOidcService(storageFactory, new ObjectMapper()), mock(EksAccessEntryService.class));
}
@Test
@@ -51,7 +51,7 @@ class EksSubResourceListsIntegrationTest {
void createCluster() {
given().contentType(JSON)
.body("{\"name\":\"" + CLUSTER + "\",\"roleArn\":\"arn:aws:iam::000000000000:role/eks-role\","
+ "\"version\":\"1.29\"}")
+ "\"version\":\"1.29\",\"accessConfig\":{\"authenticationMode\":\"API\",\"bootstrapClusterCreatorAdminPermissions\":false}}")
.when().post("/clusters")
.then().statusCode(200)
.body("cluster.name", equalTo(CLUSTER));