feat(eks): give an EKS Auto Mode cluster's node role its EC2 access entry (#9371)

CreateAccessEntry accepts the EC2 type (roles only, system:node:{{SessionName}} in system:nodes, AWS's refusals for groups, a username and an IAM user, access policies allowed), and turning Auto Mode compute on makes the node role's EC2 entry with AmazonEKSAutoNodePolicy, as measured on AWS.
This commit is contained in:
mrfelek authored and GitHub committed 2026-11-24 15:49:22 -04:00
1 parent 54961f0519
commit 941a700f60
5 files changed
+204 -15

No files matched your search

+3 -3
View File
@@ -42,11 +42,11 @@ or list operations. Resource tags are not retained for post-deletion policy cond
| `UpdateClusterConfig` | Update a cluster's endpoint access, logging, authentication mode or upgrade policy |
| `ListClusters` | List cluster names with pagination (`maxResults` 1-100 and `nextToken`) |
| `DeleteCluster` | Delete a cluster |
| `CreateAccessEntry` | Create STANDARD or EC2_LINUX access-entry metadata |
| `CreateAccessEntry` | Create STANDARD, EC2_LINUX or EC2 (EKS Auto Mode) access-entry metadata |
| `DescribeAccessEntry` | Describe an access entry by IAM principal ARN |
| `ListAccessEntries` | List principal ARNs with pagination |
| `DeleteAccessEntry` | Delete access-entry metadata |
| `AssociateAccessPolicy` | Associate an EKS access policy and its cluster or namespace scope with a STANDARD access entry |
| `AssociateAccessPolicy` | Associate an EKS access policy and its cluster or namespace scope with a STANDARD or EC2 access entry |
| `ListAssociatedAccessPolicies` | List the access policies associated with an access entry, with pagination |
| `DisassociateAccessPolicy` | Remove an access policy from an access entry |
| `CreatePodIdentityAssociation` | Create a pod identity association between a service account and IAM role |
@@ -78,7 +78,7 @@ or list operations. Resource tags are not retained for post-deletion policy cond
`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 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.
The 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. `EC2`, the type of EKS Auto Mode's node role, accepts roles only and generates `system:node:{{SessionName}}` in the `system:nodes` group; like AWS, it refuses Kubernetes groups, a username or an IAM user with AWS's messages, and access policies can be associated with it. When a cluster's EKS Auto Mode compute capability is turned on, by `CreateCluster` or `UpdateClusterConfig`, Floci makes the node role's `EC2` entry with `AmazonEKSAutoNodePolicy` on the cluster scope, as EKS does, unless the role already has an entry, IAM doesn't have the role, or the cluster's authentication mode is `CONFIG_MAP`. 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 policies are management metadata, like the entries they belong to: Floci stores and returns them but does not enforce their Kubernetes permissions. `policyArn` must be an `arn:<partition>:eks::aws:cluster-access-policy/<name>` ARN in the cluster's partition. The policy name itself is not checked against AWS's list of access policies. The scope `type` is `cluster` (no namespaces) or `namespace` (one or more names; wildcards such as `dev-*` are kept as given, and a repeated name is stored once). Associating a policy that is already associated replaces its scope and keeps its `associatedAt`. Only STANDARD entries accept access policies, and deleting an entry removes its policies. Disassociating a policy the entry does not hold succeeds. `ListAccessEntries` accepts `associatedPolicyArn`.
@@ -37,6 +37,11 @@ import java.util.function.UnaryOperator;
/** Access-entry and access-policy management metadata; Kubernetes authorization is handled separately. */
@ApplicationScoped
public class EksAccessEntryService {
/** The type of the access entry of an EKS Auto Mode cluster's node role. */
static final String AUTO_MODE_NODE_TYPE = "EC2";
static final String AUTO_MODE_NODE_USERNAME = "system:node:{{SessionName}}";
static final String AUTO_MODE_NODE_POLICY = "AmazonEKSAutoNodePolicy";
private final StorageBackend<String, StoredEntry> entries;
private final IamService iam;
private final Clock clock;
@@ -78,9 +83,9 @@ public class EksAccessEntryService {
}
requireAccessPolicyArn(cluster, request.policyArn());
AccessScope scope = accessScope(request.accessScope());
if (!"STANDARD".equals(stored.entry().type())) {
if (!"STANDARD".equals(stored.entry().type()) && !AUTO_MODE_NODE_TYPE.equals(stored.entry().type())) {
throw new AwsException("InvalidRequestException",
"Access policies can only be associated with STANDARD access entries", 400);
"Access policies can only be associated with STANDARD and EC2 access entries", 400);
}
double now = EpochSeconds.fromMillis(clock.millis());
double associatedAt = stored.accessPolicies().stream()
@@ -151,16 +156,28 @@ public class EksAccessEntryService {
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");
if (!"STANDARD".equals(type) && !"EC2_LINUX".equals(type) && !AUTO_MODE_NODE_TYPE.equals(type)) {
throw invalid("Floci currently supports STANDARD, EC2_LINUX and EC2 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");
}
boolean autoModeNode = AUTO_MODE_NODE_TYPE.equals(type);
if (autoModeNode && request.kubernetesGroups() != null) {
throw invalid("The specified kubernetesGroups is invalid: setting kubernetesGroups is not allowed when the "
+ "type is \"EC2\".");
}
if (autoModeNode && request.username() != null) {
throw invalid("The specified username is invalid: setting username is not allowed when the type is \"EC2\".");
}
String principal = request.principalArn();
AwsArnUtils.Arn arn = AwsArnUtils.isArn(principal) ? AwsArnUtils.parse(principal) : null;
AwsArnUtils.Arn clusterArn = AwsArnUtils.parse(cluster.getArn());
if (autoModeNode && arn != null && arn.resource().startsWith("user/")) {
throw invalid("AccessEntry principalArn must be IAM role when using types "
+ "[EC2_LINUX, EC2_WINDOWS, FARGATE_LINUX, HYBRID_LINUX, EC2]");
}
if (arn == null || !arn.partition().equals(clusterArn.partition())
|| !"iam".equals(arn.service()) || !arn.region().isEmpty() || !arn.accountId().matches("[0-9]{12}")
|| !(arn.resource().startsWith("role/") || (!node && arn.resource().startsWith("user/")))
@@ -175,12 +192,13 @@ public class EksAccessEntryService {
.map(IamRole::getRoleId).orElseThrow(() -> invalid("IAM role does not exist"))
: iam.findUser(arn.accountId(), 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()
String username = node ? "system:node:{{EC2PrivateDNSName}}"
: autoModeNode ? AUTO_MODE_NODE_USERNAME : request.username();
if (username != null && !node && !autoModeNode && (username.isBlank()
|| username.matches("^(system|eks|aws|amazon|iam):.*"))) {
throw invalid("Invalid username");
}
if (username != null && !node) {
if (username != null && !node && !autoModeNode) {
for (String placeholder : List.of("{{SessionName}}", "{{SessionNameRaw}}")) {
int position = username.indexOf(placeholder);
if (position >= 0 && !username.substring(0, position).contains(":")) {
@@ -192,7 +210,7 @@ public class EksAccessEntryService {
username = role ? AwsArnUtils.Arn.global(arn.partition(), "sts", arn.accountId(),
"assumed-role/" + name + "/{{SessionName}}").toString() : principal;
}
List<String> groups = node ? List.of("system:nodes")
List<String> groups = node || autoModeNode ? 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");
@@ -223,15 +241,55 @@ public class EksAccessEntryService {
throw new AwsException("ResourceInUseException", "Access entry already exists", 409);
}
double now = EpochSeconds.fromMillis(clock.millis());
String entryArn = new AwsArnUtils.Arn(clusterArn.partition(), "eks", clusterArn.region(), clusterArn.accountId(),
"access-entry/" + cluster.getName() + "/" + (role ? "role" : "user") + "/" + arn.accountId() + "/" + name
+ "/" + UUID.randomUUID()).toString();
AccessEntry entry = new AccessEntry(entryArn, cluster.getName(), principal,
AccessEntry entry = new AccessEntry(entryArn(cluster, arn, role), cluster.getName(), principal,
type, username, List.copyOf(groups), Map.copyOf(tags), now, now);
entries.put(key, new StoredEntry(entry, principalId, token, List.of()));
return entry;
}
private static String entryArn(Cluster cluster, AwsArnUtils.Arn principal, boolean role) {
AwsArnUtils.Arn clusterArn = AwsArnUtils.parse(cluster.getArn());
String name = principal.resource().substring(principal.resource().lastIndexOf('/') + 1);
return new AwsArnUtils.Arn(clusterArn.partition(), "eks", clusterArn.region(), clusterArn.accountId(),
"access-entry/" + cluster.getName() + "/" + (role ? "role" : "user") + "/" + principal.accountId() + "/"
+ name + "/" + UUID.randomUUID()).toString();
}
/**
* Makes the access entry EKS makes for the node role when a cluster's EKS Auto Mode compute capability is turned
* on: type {@code EC2}, username {@code system:node:{{SessionName}}}, group {@code system:nodes}, with
* {@code AmazonEKSAutoNodePolicy} on the cluster. An entry the role already has is kept as it is. Nothing is made
* for a cluster whose authentication mode is {@code CONFIG_MAP}, which has no access entries, or for a role IAM
* doesn't have.
*/
public synchronized void ensureAutoModeNodeEntry(Cluster cluster, String nodeRoleArn) {
if (nodeRoleArn == null || !AwsArnUtils.isArn(nodeRoleArn) || cluster.getAccessConfig() == null
|| "CONFIG_MAP".equals(cluster.getAccessConfig().authenticationMode())) {
return;
}
String key = prefix(cluster) + nodeRoleArn;
if (entries.get(key).isPresent()) {
return;
}
AwsArnUtils.Arn arn = AwsArnUtils.parse(nodeRoleArn);
String name = arn.resource().substring(arn.resource().lastIndexOf('/') + 1);
Optional<String> roleId = arn.resource().startsWith("role/")
? iam.findRole(arn.accountId(), name).filter(found -> nodeRoleArn.equals(found.getArn()))
.map(IamRole::getRoleId)
: Optional.empty();
if (roleId.isEmpty()) {
return;
}
double now = EpochSeconds.fromMillis(clock.millis());
AccessEntry entry = new AccessEntry(entryArn(cluster, arn, true), cluster.getName(), nodeRoleArn,
AUTO_MODE_NODE_TYPE, AUTO_MODE_NODE_USERNAME, List.of("system:nodes"), Map.of(), now, now);
String policy = new AwsArnUtils.Arn(AwsArnUtils.parse(cluster.getArn()).partition(), "eks", "",
"aws", // partition-literal: the AWS-managed account, "aws" in every partition
"cluster-access-policy/" + AUTO_MODE_NODE_POLICY).toString();
entries.put(key, new StoredEntry(entry, roleId.get(), null,
List.of(new AssociatedAccessPolicy(policy, new AccessScope("cluster", List.of()), now, now))));
}
synchronized Optional<AccessEntry> workerEntry(Cluster cluster, String accountId, String principal, String roleId) {
requireApiAccess(cluster);
String key = prefix(cluster) + principal;
@@ -1044,6 +1044,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
}
}
ensureAutoModeNodeEntry(cluster);
storage.put(clusterKey(region, name), cluster);
} catch (RuntimeException e) {
if (clusterSg != null) {
@@ -1316,6 +1317,9 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
&& !config.services().eks().mock() && clusterManager != null && cluster.getContainerId() != null) {
replaceNodeForServiceLb(requireClusterInRequestRegion(name));
}
if (nextAutoMode != null && nextAutoMode.computeOn()) {
ensureAutoModeNodeEntry(requireClusterInRequestRegion(name));
}
LOG.infov("Updated the configuration of EKS cluster {0}: {1}", cluster.getName(),
updates.stream().map(Update::type).toList());
return updates;
@@ -1365,6 +1369,17 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
}
}
/**
* EKS makes the node role's access entry, of type {@code EC2} with {@code AmazonEKSAutoNodePolicy}, once the
* cluster's EKS Auto Mode compute capability is on (measured on AWS for CreateCluster).
*/
private void ensureAutoModeNodeEntry(Cluster cluster) {
ComputeConfig compute = cluster.getComputeConfig();
if (accessEntries != null && compute != null && Boolean.TRUE.equals(compute.enabled())) {
accessEntries.ensureAutoModeNodeEntry(cluster, compute.nodeRoleArn());
}
}
private static AutoMode autoMode(Cluster cluster) {
return new AutoMode(cluster.getComputeConfig(), cluster.getStorageConfig(),
elasticLoadBalancing(cluster.getKubernetesNetworkConfig()));
@@ -223,6 +223,47 @@ class EksAccessEntryIntegrationTest {
}
}
/** EKS makes the node role's EC2 entry with AmazonEKSAutoNodePolicy when Auto Mode compute is on (measured). */
@ParameterizedTest
@ValueSource(booleans = {true, false})
void anAutoModeClustersNodeRoleGetsItsEc2EntryWithTheAutoNodePolicy(boolean atCreate) {
String account = "357913579135";
String name = "auto-node-" + UUID.randomUUID().toString().substring(0, 8);
String role = "node-" + name;
String principal = "arn:aws:iam::" + account + ":role/" + role;
String autoMode = """
"computeConfig":{"enabled":true,"nodePools":["general-purpose","system"],"nodeRoleArn":"%s"},
"storageConfig":{"blockStorage":{"enabled":true}},
"kubernetesNetworkConfig":{"elasticLoadBalancing":{"enabled":true}}""".formatted(principal);
createRole(account, role, "/");
try {
eks(account, REGION).body("""
{"name":"%s","roleArn":"arn:aws:iam::%s:role/cluster","accessConfig":{"authenticationMode":"API"}%s}"""
.formatted(name, account, atCreate ? "," + autoMode : "")).post("/clusters").then().statusCode(200);
if (!atCreate) {
eks(account, REGION).get("/clusters/" + name + "/access-entries").then().statusCode(200)
.body("accessEntries", empty());
eks(account, REGION).body("{" + autoMode + "}").post("/clusters/" + name + "/update-config").then()
.statusCode(200);
}
String entryPath = "/clusters/" + name + "/access-entries/" + URLEncoder.encode(principal, StandardCharsets.UTF_8);
eks(account, REGION).get("/clusters/" + name + "/access-entries").then().statusCode(200)
.body("accessEntries", contains(principal));
eks(account, REGION).urlEncodingEnabled(false).get(entryPath).then().statusCode(200)
.body("accessEntry.type", equalTo("EC2"))
.body("accessEntry.username", equalTo("system:node:{{SessionName}}"))
.body("accessEntry.kubernetesGroups", contains("system:nodes"));
eks(account, REGION).urlEncodingEnabled(false).get(entryPath + "/access-policies").then().statusCode(200)
.body("associatedAccessPolicies.policyArn",
contains("arn:aws:eks::aws:cluster-access-policy/AmazonEKSAutoNodePolicy"))
.body("associatedAccessPolicies[0].accessScope.type", equalTo("cluster"));
} finally {
eks(account, REGION).delete("/clusters/" + name);
deleteRole(account, role);
}
}
private static void createRole(String account, String role, String rolePath) {
given().header("Authorization", auth(account, "iam")).contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateRole").formParam("RoleName", role).formParam("Path", rolePath)
@@ -351,6 +351,81 @@ class EksAccessEntryServiceTest {
.associatedAccessPolicies().isEmpty());
}
/** Measured on AWS: an EC2 entry gets the Auto Mode node identity and can hold access policies. */
@Test
void anEc2EntryGetsTheAutoModeNodeIdentityAndTakesAccessPolicies() {
Fixture fixture = fixture();
AccessEntry entry = fixture.service.create(fixture.cluster, request(PRINCIPAL, "EC2", null));
assertEquals("EC2", entry.type());
assertEquals("system:node:{{SessionName}}", entry.username());
assertEquals(List.of("system:nodes"), entry.kubernetesGroups());
assertTrue(fixture.service.listAccessPolicies(fixture.cluster, PRINCIPAL, null, null)
.associatedAccessPolicies().isEmpty());
fixture.service.associate(fixture.cluster, PRINCIPAL, policy(ADMIN, "cluster", null));
assertEquals(List.of(ADMIN), fixture.service.listAccessPolicies(fixture.cluster, PRINCIPAL, null, null)
.associatedAccessPolicies().stream().map(AssociatedAccessPolicy::policyArn).toList());
}
/** AWS's messages, measured. */
@Test
void anEc2EntryRefusesGroupsAUsernameAndAnIamUserAsAwsDoes() {
Fixture fixture = fixture();
AwsException groups = assertThrows(AwsException.class, () -> fixture.service.create(fixture.cluster,
new CreateAccessEntryRequest(PRINCIPAL, "EC2", null, List.of("g1"), null, null)));
assertEquals("InvalidParameterException", groups.getErrorCode());
assertEquals("The specified kubernetesGroups is invalid: setting kubernetesGroups is not allowed when the type "
+ "is \"EC2\".", groups.getMessage());
AwsException username = assertThrows(AwsException.class, () -> fixture.service.create(fixture.cluster,
new CreateAccessEntryRequest(PRINCIPAL, "EC2", "someone", null, null, null)));
assertEquals("The specified username is invalid: setting username is not allowed when the type is \"EC2\".",
username.getMessage());
AwsException user = assertThrows(AwsException.class, () -> fixture.service.create(fixture.cluster,
request("arn:aws:iam::123456789012:user/floci-cli", "EC2", null)));
assertEquals("AccessEntry principalArn must be IAM role when using types "
+ "[EC2_LINUX, EC2_WINDOWS, FARGATE_LINUX, HYBRID_LINUX, EC2]", user.getMessage());
}
@Test
void autoModeMakesTheNodeRolesEntryWithTheAutoNodePolicyOnTheClusterOnce() {
Fixture fixture = fixture();
fixture.cluster.setStatus(ClusterStatus.CREATING);
fixture.service.ensureAutoModeNodeEntry(fixture.cluster, PRINCIPAL);
fixture.service.ensureAutoModeNodeEntry(fixture.cluster, PRINCIPAL);
fixture.cluster.setStatus(ClusterStatus.ACTIVE);
AccessEntry entry = fixture.service.describe(fixture.cluster, PRINCIPAL);
assertEquals("EC2", entry.type());
assertEquals("system:node:{{SessionName}}", entry.username());
assertEquals(List.of("system:nodes"), entry.kubernetesGroups());
assertEquals("AROA-worker", fixture.storage.scan(key -> true).getFirst().principalId());
List<AssociatedAccessPolicy> policies = fixture.service.listAccessPolicies(fixture.cluster, PRINCIPAL, null,
null).associatedAccessPolicies();
assertEquals(List.of("arn:aws:eks::aws:cluster-access-policy/AmazonEKSAutoNodePolicy"),
policies.stream().map(AssociatedAccessPolicy::policyArn).toList());
assertEquals(new AccessScope("cluster", List.of()), policies.getFirst().accessScope());
assertEquals(List.of(PRINCIPAL), fixture.service.list(fixture.cluster, null, null).accessEntries());
}
@Test
void autoModeKeepsAnEntryTheNodeRoleHasAndMakesNoneWithoutAccessEntriesOrTheRole() {
Fixture standard = fixture();
AccessEntry existing = standard.service.create(standard.cluster, request(PRINCIPAL, "STANDARD", null));
standard.service.ensureAutoModeNodeEntry(standard.cluster, PRINCIPAL);
assertEquals(existing, standard.service.describe(standard.cluster, PRINCIPAL));
Fixture configMap = fixture();
configMap.cluster.setAccessConfig(new AccessConfig("CONFIG_MAP", true));
configMap.service.ensureAutoModeNodeEntry(configMap.cluster, PRINCIPAL);
assertTrue(configMap.storage.scan(key -> true).isEmpty());
Fixture noRole = fixture();
when(noRole.iam.findRole("123456789012", "worker")).thenReturn(Optional.empty());
noRole.service.ensureAutoModeNodeEntry(noRole.cluster, PRINCIPAL);
assertTrue(noRole.storage.scan(key -> true).isEmpty());
}
private static String cn(String arn) {
return arn.replace("arn:aws:", "arn:aws-cn:");
}