mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
feat(eks): associate access policies with access entries (#6427)
AssociateAccessPolicy, ListAssociatedAccessPolicies and DisassociateAccessPolicy had no route, so their requests fell through to S3's path-style catch-all and came back as an S3 XML error. Terraform's aws_eks_access_policy_association could not be created. The three operations follow access entries: they are management metadata, stored and returned but not enforced in Kubernetes. Each association is kept on its access entry, so deleting the entry or the cluster removes it, and entries persisted before this change load with no policies. ListAccessEntries now honours associatedPolicyArn. Validation follows the EKS user guide: only STANDARD entries take access policies, the scope is cluster (no namespaces) or namespace (one or more names, wildcards kept, a repeated name stored once), and associating a policy again replaces its scope and keeps its associatedAt. policyArn must be an EKS cluster access policy ARN in the cluster's partition; the name is not checked against AWS's list. Listing pages from 1 to 100, with tokens bound to the entry they came from. Disassociating a policy the entry does not hold succeeds, since EKS documents no error for it; a missing entry is still ResourceNotFoundException, and an ARN that associate would refuse is InvalidParameterException. ListAccessEntries now pages through the shared Pagination helper too, so a token issued before this change is refused. Under IAM enforcement the list and disassociate routes were checked as DescribeAccessEntry and DeleteAccessEntry, and all three against a principal ending in /access-policies, so a grant scoped to the entry never matched. They are now checked as their own actions, against the entry's ARN. A DELETE is a disassociate only when a cluster access policy ARN follows access-policies, in the route, the IAM rule and the resource, so an entry whose IAM path holds an access-policies segment can still be deleted. The router matches the encoded path, so a principal sent URL-encoded, as the SDKs send it, is never split. Co-authored-by: Robin Baeckman <27041454+RobinBaeckman@users.noreply.github.com>
This commit is contained in:
1 parent
bc75edb4c4
commit
7453011c43
15 files changed
+719
-79
No files matched your search
+21
@@ -39,6 +39,27 @@ class EksAccessEntryTest {
|
||||
assertThat(eks.describeAccessEntry(builder -> builder.clusterName(cluster).principalArn(first))
|
||||
.accessEntry().principalArn()).isEqualTo(first);
|
||||
eks.createAccessEntry(builder -> builder.clusterName(cluster).principalArn(second));
|
||||
String admin = "arn:aws:eks::aws:cluster-access-policy/AmazonEKSClusterAdminPolicy";
|
||||
AssociateAccessPolicyResponse associated = eks.associateAccessPolicy(builder -> builder
|
||||
.clusterName(cluster).principalArn(second).policyArn(admin)
|
||||
.accessScope(scope -> scope.type(AccessScopeType.NAMESPACE).namespaces("dev-*", "payments")));
|
||||
assertThat(associated.principalArn()).isEqualTo(second);
|
||||
assertThat(associated.associatedAccessPolicy().associatedAt()).isNotNull();
|
||||
ListAssociatedAccessPoliciesResponse policies = eks.listAssociatedAccessPolicies(builder -> builder
|
||||
.clusterName(cluster).principalArn(second));
|
||||
assertThat(policies.associatedAccessPolicies()).singleElement().satisfies(policy -> {
|
||||
assertThat(policy.policyArn()).isEqualTo(admin);
|
||||
assertThat(policy.accessScope().type()).isEqualTo(AccessScopeType.NAMESPACE);
|
||||
assertThat(policy.accessScope().namespaces()).containsExactly("dev-*", "payments");
|
||||
});
|
||||
assertThatThrownBy(() -> eks.associateAccessPolicy(builder -> builder.clusterName(cluster)
|
||||
.principalArn(first).policyArn(admin).accessScope(scope -> scope.type(AccessScopeType.CLUSTER))))
|
||||
.isInstanceOf(InvalidRequestException.class);
|
||||
eks.disassociateAccessPolicy(builder -> builder.clusterName(cluster).principalArn(second).policyArn(admin));
|
||||
assertThat(eks.listAssociatedAccessPolicies(builder -> builder.clusterName(cluster).principalArn(second))
|
||||
.associatedAccessPolicies()).isEmpty();
|
||||
// Removing a policy the entry no longer holds succeeds, like the first removal.
|
||||
eks.disassociateAccessPolicy(builder -> builder.clusterName(cluster).principalArn(second).policyArn(admin));
|
||||
ListAccessEntriesResponse page = eks.listAccessEntries(builder -> builder.clusterName(cluster).maxResults(1));
|
||||
assertThat(page.accessEntries()).hasSize(1);
|
||||
assertThat(page.nextToken()).isNotBlank();
|
||||
|
||||
@@ -17,6 +17,9 @@ EKS uses a standard REST API with JSON bodies: not the JSON 1.1 (`X-Amz-Target`)
|
||||
| `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 |
|
||||
| `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 |
|
||||
| `DescribePodIdentityAssociation` | Describe a pod identity association by association ID |
|
||||
| `ListPodIdentityAssociations` | List pod identity associations in a cluster with optional filtering and pagination |
|
||||
@@ -45,7 +48,11 @@ EKS uses a standard REST API with JSON bodies: not the JSON 1.1 (`X-Amz-Target`)
|
||||
|
||||
`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.
|
||||
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.
|
||||
|
||||
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`.
|
||||
|
||||
The principal ARN in an access-entry path should be URL-encoded, as the SDKs and the CLI send it. Sent unencoded, a principal whose ARN ends in `/access-policies` (a role named `access-policies`) is read as the access-policies route of the shorter principal before it. A DELETE is a disassociate only when a cluster access policy ARN follows `access-policies`, so an entry with `access-policies` inside its IAM path can always be deleted.
|
||||
|
||||
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.
|
||||
|
||||
@@ -66,7 +73,7 @@ rejects instance credentials. Obtain fresh IMDS credentials after upgrading so t
|
||||
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.
|
||||
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, ListAccessPolicies, 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 \
|
||||
|
||||
@@ -3,11 +3,15 @@ package io.github.hectorvent.floci.services.eks;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.Base64Url;
|
||||
import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
import io.github.hectorvent.floci.core.common.Pagination;
|
||||
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;
|
||||
import io.github.hectorvent.floci.services.eks.model.AccessScope;
|
||||
import io.github.hectorvent.floci.services.eks.model.AssociateAccessPolicyRequest;
|
||||
import io.github.hectorvent.floci.services.eks.model.AssociatedAccessPolicy;
|
||||
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;
|
||||
@@ -18,19 +22,22 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.Clock;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashSet;
|
||||
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. */
|
||||
/** Access-entry and access-policy management metadata; Kubernetes authorization is handled separately. */
|
||||
@ApplicationScoped
|
||||
public class EksAccessEntryService {
|
||||
private final StorageBackend<String, StoredEntry> entries;
|
||||
private final IamService iam;
|
||||
private final Clock clock;
|
||||
|
||||
@Inject
|
||||
public EksAccessEntryService(StorageFactory factory, IamService iam) {
|
||||
@@ -38,16 +45,104 @@ public class EksAccessEntryService {
|
||||
}
|
||||
|
||||
EksAccessEntryService(StorageBackend<String, StoredEntry> entries, IamService iam) {
|
||||
this(entries, iam, Clock.systemUTC());
|
||||
}
|
||||
|
||||
EksAccessEntryService(StorageBackend<String, StoredEntry> entries, IamService iam, Clock clock) {
|
||||
this.entries = entries;
|
||||
this.iam = iam;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
public record StoredEntry(AccessEntry entry, String principalId, String clientRequestToken) {}
|
||||
public record StoredEntry(AccessEntry entry, String principalId, String clientRequestToken,
|
||||
List<AssociatedAccessPolicy> accessPolicies) {
|
||||
public StoredEntry {
|
||||
accessPolicies = accessPolicies == null ? List.of() : List.copyOf(accessPolicies);
|
||||
}
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
public record Page(List<String> accessEntries, String nextToken) {}
|
||||
|
||||
@RegisterForReflection
|
||||
public record PolicyPage(List<AssociatedAccessPolicy> associatedAccessPolicies, String nextToken) {}
|
||||
|
||||
public synchronized AssociatedAccessPolicy associate(Cluster cluster, String principal,
|
||||
AssociateAccessPolicyRequest request) {
|
||||
StoredEntry stored = storedEntry(cluster, principal);
|
||||
if (request == null || request.policyArn() == null) {
|
||||
throw invalid("policyArn is required");
|
||||
}
|
||||
requireAccessPolicyArn(cluster, request.policyArn());
|
||||
AccessScope scope = accessScope(request.accessScope());
|
||||
if (!"STANDARD".equals(stored.entry().type())) {
|
||||
throw new AwsException("InvalidRequestException",
|
||||
"Access policies can only be associated with STANDARD access entries", 400);
|
||||
}
|
||||
double now = clock.millis() / 1000.0;
|
||||
double associatedAt = stored.accessPolicies().stream()
|
||||
.filter(existing -> existing.policyArn().equals(request.policyArn()))
|
||||
.mapToDouble(AssociatedAccessPolicy::associatedAt).findFirst().orElse(now);
|
||||
AssociatedAccessPolicy association = new AssociatedAccessPolicy(request.policyArn(), scope, associatedAt, now);
|
||||
List<AssociatedAccessPolicy> policies = new ArrayList<>(stored.accessPolicies());
|
||||
policies.removeIf(existing -> existing.policyArn().equals(request.policyArn()));
|
||||
policies.add(association);
|
||||
policies.sort(Comparator.comparing(AssociatedAccessPolicy::policyArn));
|
||||
entries.put(prefix(cluster) + principal, new StoredEntry(stored.entry(), stored.principalId(),
|
||||
stored.clientRequestToken(), policies));
|
||||
return association;
|
||||
}
|
||||
|
||||
public synchronized PolicyPage listAccessPolicies(Cluster cluster, String principal, Integer maxResults,
|
||||
String nextToken) {
|
||||
List<AssociatedAccessPolicy> policies = storedEntry(cluster, principal).accessPolicies();
|
||||
// The newline ends the principal, so a token for role/a:b is not read as one for role/a.
|
||||
PaginatedResult<AssociatedAccessPolicy> page = Pagination.paginate(policies, AssociatedAccessPolicy::policyArn,
|
||||
pageSize(maxResults), nextToken, "policies:" + prefix(cluster) + principal + "\n",
|
||||
token -> invalid("Invalid nextToken"));
|
||||
return new PolicyPage(page.items(), page.nextToken());
|
||||
}
|
||||
|
||||
public synchronized void disassociate(Cluster cluster, String principal, String policyArn) {
|
||||
StoredEntry stored = storedEntry(cluster, principal);
|
||||
requireAccessPolicyArn(cluster, policyArn);
|
||||
List<AssociatedAccessPolicy> policies = stored.accessPolicies().stream()
|
||||
.filter(existing -> !existing.policyArn().equals(policyArn)).toList();
|
||||
if (policies.size() == stored.accessPolicies().size()) {
|
||||
return; // EKS documents no error for a policy the entry does not hold
|
||||
}
|
||||
entries.put(prefix(cluster) + principal, new StoredEntry(stored.entry(), stored.principalId(),
|
||||
stored.clientRequestToken(), policies));
|
||||
}
|
||||
|
||||
private StoredEntry storedEntry(Cluster cluster, String principal) {
|
||||
requireApiAccess(cluster);
|
||||
return entries.get(prefix(cluster) + principal)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Access entry not found", 404));
|
||||
}
|
||||
|
||||
private static AccessScope accessScope(AccessScope scope) {
|
||||
if (scope == null || scope.type() == null) {
|
||||
throw invalid("accessScope.type is required");
|
||||
}
|
||||
List<String> namespaces = scope.namespaces() == null ? List.of() : scope.namespaces();
|
||||
if ("cluster".equals(scope.type())) {
|
||||
if (!namespaces.isEmpty()) {
|
||||
throw invalid("namespaces can only be specified for a namespace access scope");
|
||||
}
|
||||
return new AccessScope("cluster", List.of());
|
||||
}
|
||||
if (!"namespace".equals(scope.type())) {
|
||||
throw invalid("accessScope.type must be cluster or namespace");
|
||||
}
|
||||
if (namespaces.isEmpty() || namespaces.stream().anyMatch(namespace -> namespace == null || namespace.isBlank())) {
|
||||
throw invalid("A namespace access scope requires nonempty namespace names");
|
||||
}
|
||||
// Terraform models namespaces as a set, so a repeated name must not come back twice.
|
||||
return new AccessScope("namespace", List.copyOf(new LinkedHashSet<>(namespaces)));
|
||||
}
|
||||
|
||||
public synchronized AccessEntry create(Cluster cluster, CreateAccessEntryRequest request) {
|
||||
requireApiAccess(cluster);
|
||||
if (request == null || request.principalArn() == null) {
|
||||
@@ -125,13 +220,13 @@ public class EksAccessEntryService {
|
||||
if (entries.get(key).isPresent()) {
|
||||
throw new AwsException("ResourceInUseException", "Access entry already exists", 409);
|
||||
}
|
||||
double now = Instant.now().toEpochMilli() / 1000.0;
|
||||
double now = clock.millis() / 1000.0;
|
||||
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,
|
||||
type, username, List.copyOf(groups), Map.copyOf(tags), now, now);
|
||||
entries.put(key, new StoredEntry(entry, principalId, token));
|
||||
entries.put(key, new StoredEntry(entry, principalId, token, List.of()));
|
||||
return entry;
|
||||
}
|
||||
|
||||
@@ -145,9 +240,7 @@ public class EksAccessEntryService {
|
||||
}
|
||||
|
||||
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));
|
||||
return storedEntry(cluster, principal).entry();
|
||||
}
|
||||
|
||||
public synchronized void delete(Cluster cluster, String principal) {
|
||||
@@ -156,34 +249,19 @@ public class EksAccessEntryService {
|
||||
}
|
||||
|
||||
public synchronized Page list(Cluster cluster, Integer maxResults, String nextToken) {
|
||||
return list(cluster, maxResults, nextToken, null);
|
||||
}
|
||||
|
||||
public synchronized Page list(Cluster cluster, Integer maxResults, String nextToken, String associatedPolicyArn) {
|
||||
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 = Base64Url.decode(nextToken);
|
||||
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 ? Base64Url.encode(prefix + "\n" + page.getLast()) : null;
|
||||
return new Page(page, token);
|
||||
List<String> principals = entries.scan(key -> key.startsWith(prefix)).stream()
|
||||
.filter(stored -> associatedPolicyArn == null || stored.accessPolicies().stream()
|
||||
.anyMatch(policy -> policy.policyArn().equals(associatedPolicyArn)))
|
||||
.map(stored -> stored.entry().principalArn()).toList();
|
||||
PaginatedResult<String> page = Pagination.paginate(principals, principal -> principal, pageSize(maxResults),
|
||||
nextToken, "entries:" + prefix, token -> invalid("Invalid nextToken"));
|
||||
return new Page(page.items(), page.nextToken());
|
||||
}
|
||||
|
||||
public synchronized void deleteClusterEntries(Cluster cluster) {
|
||||
@@ -207,6 +285,31 @@ public class EksAccessEntryService {
|
||||
}
|
||||
}
|
||||
|
||||
private static int pageSize(Integer maxResults) {
|
||||
int limit = maxResults == null ? 100 : maxResults;
|
||||
if (limit < 1 || limit > 100) {
|
||||
throw invalid("maxResults must be between 1 and 100");
|
||||
}
|
||||
return limit;
|
||||
}
|
||||
|
||||
private static void requireAccessPolicyArn(Cluster cluster, String policyArn) {
|
||||
AwsArnUtils.Arn arn;
|
||||
try {
|
||||
arn = AwsArnUtils.parse(policyArn);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw invalid("policyArn must identify an EKS cluster access policy");
|
||||
}
|
||||
boolean accessPolicy = arn.partition().equals(AwsArnUtils.parse(cluster.getArn()).partition())
|
||||
&& arn.service().equals("eks")
|
||||
&& arn.region().isEmpty()
|
||||
&& arn.accountId().equals("aws") // partition-literal: the AWS-managed account, "aws" in every partition
|
||||
&& arn.resource().matches("cluster-access-policy/[A-Za-z0-9]+");
|
||||
if (!accessPolicy) {
|
||||
throw invalid("policyArn must identify an EKS cluster access policy");
|
||||
}
|
||||
}
|
||||
|
||||
private static AwsException invalid(String message) {
|
||||
return new AwsException("InvalidParameterException", message, 400);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ package io.github.hectorvent.floci.services.eks;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.Pagination;
|
||||
import io.github.hectorvent.floci.services.eks.model.Addon;
|
||||
import io.github.hectorvent.floci.services.eks.model.AssociateAccessPolicyRequest;
|
||||
import io.github.hectorvent.floci.services.eks.model.AssociatedAccessPolicy;
|
||||
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.CreateAddonRequest;
|
||||
@@ -27,6 +29,7 @@ import jakarta.ws.rs.QueryParam;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -42,6 +45,15 @@ import java.util.Map;
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
public class EksController {
|
||||
|
||||
/**
|
||||
* A cluster access policy ARN as a path carries it, its {@code :} and {@code /} encoded or not. Only such an
|
||||
* ARN after {@code access-policies} makes a DELETE a disassociate, so an entry whose IAM path holds an
|
||||
* {@code access-policies} segment can still be deleted.
|
||||
*/
|
||||
public static final String ACCESS_POLICY_ARN = "arn(?::|%3[aA])[a-z-]+(?::|%3[aA])eks(?::|%3[aA])(?::|%3[aA])"
|
||||
+ "aws(?::|%3[aA])cluster-access-policy(?:/|%2[fF])[^/]+";
|
||||
|
||||
|
||||
private final EksService eksService;
|
||||
private final EksAccessEntryService accessEntries;
|
||||
private final EksPodIdentityAssociationService podIdentityAssociations;
|
||||
@@ -183,9 +195,10 @@ public class EksController {
|
||||
@Path("/clusters/{name}/access-entries")
|
||||
public Response listAccessEntries(@PathParam("name") String name,
|
||||
@QueryParam("maxResults") String maxResults,
|
||||
@QueryParam("nextToken") String nextToken) {
|
||||
@QueryParam("nextToken") String nextToken,
|
||||
@QueryParam("associatedPolicyArn") String associatedPolicyArn) {
|
||||
EksAccessEntryService.Page page = accessEntries.list(eksService.describeCluster(name),
|
||||
Pagination.parseMaxResults(maxResults, "InvalidParameterException"), nextToken);
|
||||
Pagination.parseMaxResults(maxResults, "InvalidParameterException"), nextToken, associatedPolicyArn);
|
||||
return Response.ok(page.nextToken() == null ? Map.of("accessEntries", page.accessEntries())
|
||||
: Map.of("accessEntries", page.accessEntries(), "nextToken", page.nextToken())).build();
|
||||
}
|
||||
@@ -203,6 +216,42 @@ public class EksController {
|
||||
return Response.ok(Map.of()).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/clusters/{name}/access-entries/{principalArn: .+}/access-policies")
|
||||
public Response associateAccessPolicy(@PathParam("name") String name, @PathParam("principalArn") String principalArn,
|
||||
AssociateAccessPolicyRequest request) {
|
||||
AssociatedAccessPolicy policy = accessEntries.associate(eksService.describeCluster(name), principalArn, request);
|
||||
return Response.ok(Map.of("clusterName", name, "principalArn", principalArn,
|
||||
"associatedAccessPolicy", policy)).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/clusters/{name}/access-entries/{principalArn: .+}/access-policies")
|
||||
public Response listAssociatedAccessPolicies(@PathParam("name") String name,
|
||||
@PathParam("principalArn") String principalArn,
|
||||
@QueryParam("maxResults") String maxResults,
|
||||
@QueryParam("nextToken") String nextToken) {
|
||||
EksAccessEntryService.PolicyPage page = accessEntries.listAccessPolicies(eksService.describeCluster(name),
|
||||
principalArn, Pagination.parseMaxResults(maxResults, "InvalidParameterException"), nextToken);
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("clusterName", name);
|
||||
body.put("principalArn", principalArn);
|
||||
body.put("associatedAccessPolicies", page.associatedAccessPolicies());
|
||||
if (page.nextToken() != null) {
|
||||
body.put("nextToken", page.nextToken());
|
||||
}
|
||||
return Response.ok(body).build();
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/clusters/{name}/access-entries/{principalArn: .+}/access-policies/{policyArn: " + ACCESS_POLICY_ARN + "}")
|
||||
public Response disassociateAccessPolicy(@PathParam("name") String name,
|
||||
@PathParam("principalArn") String principalArn,
|
||||
@PathParam("policyArn") String policyArn) {
|
||||
accessEntries.disassociate(eksService.describeCluster(name), principalArn, policyArn);
|
||||
return Response.ok(Map.of()).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/clusters/{name}/addons")
|
||||
public Response createAddon(@PathParam("name") String name, CreateAddonRequest request) {
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package io.github.hectorvent.floci.services.eks.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public record AccessScope(String type, List<String> namespaces) {}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package io.github.hectorvent.floci.services.eks.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public record AssociateAccessPolicyRequest(String policyArn, AccessScope accessScope) {}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.eks.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
public record AssociatedAccessPolicy(String policyArn, AccessScope accessScope, double associatedAt,
|
||||
double modifiedAt) {}
|
||||
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.common.AwsQueryServiceResolver;
|
||||
import io.github.hectorvent.floci.core.common.ProtocolClaim;
|
||||
import io.github.hectorvent.floci.core.common.WireProtocol;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbPartiQLParser;
|
||||
import io.github.hectorvent.floci.services.eks.EksController;
|
||||
import io.github.hectorvent.floci.services.s3.S3ObjectActions;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
@@ -288,12 +289,15 @@ public class IamActionRegistry {
|
||||
rule("pipes", "DELETE", "^/tags(/.+)?$", "pipes:UntagResource"),
|
||||
|
||||
// ── EKS ────────────────────────────────────────────────────────────────
|
||||
// Floci takes an access entry's principal ARN whole, slashes included, so a GET or DELETE under an
|
||||
// entry is DescribeAccessEntry or DeleteAccessEntry: the entry's access policy routes, which Floci
|
||||
// does not serve, run as those and are checked as those.
|
||||
// Floci takes an access entry's principal ARN whole, slashes included, so any other GET or DELETE under
|
||||
// an entry is DescribeAccessEntry or DeleteAccessEntry. The entry's access policy routes come first, as
|
||||
// they win in the router; a DELETE is a disassociate only when a cluster access policy ARN follows.
|
||||
rule("eks", "GET", "^/clusters/[^/]+/access-entries/.+/access-policies$", "eks:ListAssociatedAccessPolicies"),
|
||||
rule("eks", "POST", "^/clusters/[^/]+/access-entries/.+/access-policies$", "eks:AssociateAccessPolicy"),
|
||||
rule("eks", "DELETE", "^/clusters/[^/]+/access-entries/.+/access-policies/" + EksController.ACCESS_POLICY_ARN + "$",
|
||||
"eks:DisassociateAccessPolicy"),
|
||||
rule("eks", "GET", "^/clusters/[^/]+/access-entries/.+$", "eks:DescribeAccessEntry"),
|
||||
rule("eks", "DELETE", "^/clusters/[^/]+/access-entries/.+$", "eks:DeleteAccessEntry"),
|
||||
rule("eks", "POST", "^/clusters/[^/]+/access-entries/.+/access-policies$", "eks:AssociateAccessPolicy"),
|
||||
rule("eks", "POST", "^/clusters/[^/]+/access-entries/.+$", "eks:UpdateAccessEntry"),
|
||||
rule("eks", "GET", "^/clusters/[^/]+/access-entries$", "eks:ListAccessEntries"),
|
||||
rule("eks", "POST", "^/clusters/[^/]+/access-entries$", "eks:CreateAccessEntry"),
|
||||
|
||||
@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.core.common.ServicePrincipals;
|
||||
import io.github.hectorvent.floci.core.common.SigV4CredentialScope;
|
||||
import io.github.hectorvent.floci.core.common.StoredResourceArns;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.LogGroupTagTarget;
|
||||
import io.github.hectorvent.floci.services.eks.EksController;
|
||||
import io.github.hectorvent.floci.services.eks.EksService;
|
||||
import io.github.hectorvent.floci.services.kms.KmsService;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaArnUtils;
|
||||
@@ -37,6 +38,7 @@ import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Constructs the target resource ARN for a request so the policy evaluator
|
||||
@@ -48,6 +50,8 @@ import java.util.regex.Matcher;
|
||||
@ApplicationScoped
|
||||
public class ResourceArnBuilder {
|
||||
|
||||
private static final Pattern ACCESS_POLICY_ARN = Pattern.compile(EksController.ACCESS_POLICY_ARN);
|
||||
|
||||
/** The only scheme IAM accepts on an OIDC provider URL, and the part its ARN drops. */
|
||||
private static final String OIDC_URL_SCHEME = "https://";
|
||||
|
||||
@@ -1164,7 +1168,7 @@ public class ResourceArnBuilder {
|
||||
return "*";
|
||||
}
|
||||
return switch (segments[0]) {
|
||||
case "clusters" -> eksClusterRouteArn(name, segments, region, accountId);
|
||||
case "clusters" -> eksClusterRouteArn(name, segments, ctx.getMethod(), region, accountId);
|
||||
case "cluster-registrations" -> eksClusterArn(name, region, accountId);
|
||||
case "eks-anywhere-subscriptions" ->
|
||||
AwsArnUtils.Arn.of("eks", region, accountId, "eks-anywhere-subscription/" + name).toString();
|
||||
@@ -1172,8 +1176,9 @@ public class ResourceArnBuilder {
|
||||
};
|
||||
}
|
||||
|
||||
/** The resource of a route under the cluster {@code cluster}, its path split into {@code segments}. */
|
||||
private String eksClusterRouteArn(String cluster, String[] segments, String region, String accountId) {
|
||||
/** The resource of a {@code method} route under the cluster {@code cluster}, its path split into {@code segments}. */
|
||||
private String eksClusterRouteArn(String cluster, String[] segments, String method, String region,
|
||||
String accountId) {
|
||||
if (segments.length < 4 || segments[3].isEmpty()) {
|
||||
return eksClusterArn(cluster, region, accountId);
|
||||
}
|
||||
@@ -1182,7 +1187,7 @@ public class ResourceArnBuilder {
|
||||
case "node-groups", "fargate-profiles", "addons", "pod-identity-associations" ->
|
||||
eksHeldArn(cluster, collection, pathSegment(segments[3]));
|
||||
case "access-entries" -> eksHeldArn(cluster, collection,
|
||||
pathSegment(String.join("/", List.of(segments).subList(3, segments.length))));
|
||||
pathSegment(String.join("/", List.of(segments).subList(3, accessEntryEnd(segments, method)))));
|
||||
case "updates" -> {
|
||||
// The updates Floci keeps are its add-ons', and EKS returns one whether or not the request names
|
||||
// its add-on, so the update is checked against the add-on it was made to.
|
||||
@@ -1198,6 +1203,28 @@ public class ResourceArnBuilder {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Where an access entry's principal ends in {@code segments}: before {@code access-policies} on the routes
|
||||
* that act on the entry's policies, as the router reads them (a DELETE only when a cluster access policy
|
||||
* ARN follows), and at the end on every other route.
|
||||
*/
|
||||
private static int accessEntryEnd(String[] segments, String method) {
|
||||
int last = segments.length - 1;
|
||||
if (("GET".equalsIgnoreCase(method) || "POST".equalsIgnoreCase(method))
|
||||
&& last > 3 && "access-policies".equals(segments[last])) {
|
||||
return last;
|
||||
}
|
||||
if ("DELETE".equalsIgnoreCase(method)) {
|
||||
for (int i = last - 1; i > 3; i--) {
|
||||
if ("access-policies".equals(segments[i]) && ACCESS_POLICY_ARN.matcher(
|
||||
String.join("/", List.of(segments).subList(i + 1, segments.length))).matches()) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
}
|
||||
return segments.length;
|
||||
}
|
||||
|
||||
/** The ARN EKS holds the cluster {@code name} under, or else the one a create mints in {@code region}. */
|
||||
private String eksClusterArn(String name, String region, String accountId) {
|
||||
Optional<String> held = eksService == null ? Optional.empty()
|
||||
|
||||
+127
@@ -7,6 +7,7 @@ import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
@@ -65,6 +66,78 @@ class EksAccessEntryIntegrationTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void accessPoliciesRouteToEksWithEncodedPrincipalAndPolicyArns() {
|
||||
String account = "135791357913";
|
||||
String name = "policies-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String role = "admin-" + name;
|
||||
String principal = "arn:aws:iam::" + account + ":role/path/" + role;
|
||||
String policy = "arn:aws:eks::aws:cluster-access-policy/AmazonEKSClusterAdminPolicy";
|
||||
String entryPath = "/clusters/" + name + "/access-entries/" + URLEncoder.encode(principal, StandardCharsets.UTF_8);
|
||||
String policiesPath = entryPath + "/access-policies";
|
||||
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 {
|
||||
given().header("Authorization", auth(account, "eks")).contentType("application/json")
|
||||
.body(Map.of("principalArn", principal)).post("/clusters/" + name + "/access-entries")
|
||||
.then().statusCode(200);
|
||||
given().header("Authorization", auth(account, "eks")).contentType("application/json")
|
||||
.urlEncodingEnabled(false)
|
||||
.body(Map.of("policyArn", policy, "accessScope", Map.of("type", "cluster")))
|
||||
.post(policiesPath).then().statusCode(200).contentType(containsString("application/json"))
|
||||
.body("clusterName", equalTo(name)).body("principalArn", equalTo(principal))
|
||||
.body("associatedAccessPolicy.policyArn", equalTo(policy))
|
||||
.body("associatedAccessPolicy.accessScope.type", equalTo("cluster"))
|
||||
.body("associatedAccessPolicy.accessScope.namespaces", empty())
|
||||
.body("associatedAccessPolicy.associatedAt", instanceOf(Number.class))
|
||||
.body("associatedAccessPolicy.modifiedAt", instanceOf(Number.class));
|
||||
String view = "arn:aws:eks::aws:cluster-access-policy/AmazonEKSViewPolicy";
|
||||
given().header("Authorization", auth(account, "eks")).contentType("application/json")
|
||||
.urlEncodingEnabled(false)
|
||||
.body(Map.of("policyArn", view, "accessScope",
|
||||
Map.of("type", "namespace", "namespaces", List.of("dev-*", "payments"))))
|
||||
.post(policiesPath).then().statusCode(200)
|
||||
.body("associatedAccessPolicy.accessScope.type", equalTo("namespace"))
|
||||
.body("associatedAccessPolicy.accessScope.namespaces", contains("dev-*", "payments"));
|
||||
given().header("Authorization", auth(account, "eks")).queryParam("associatedPolicyArn", view)
|
||||
.get("/clusters/" + name + "/access-entries").then().statusCode(200)
|
||||
.body("accessEntries", contains(principal));
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.queryParam("associatedPolicyArn", "arn:aws:eks::aws:cluster-access-policy/AmazonEKSEditPolicy")
|
||||
.get("/clusters/" + name + "/access-entries").then().statusCode(200)
|
||||
.body("accessEntries", empty());
|
||||
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
|
||||
.get(policiesPath).then().statusCode(200)
|
||||
.body("clusterName", equalTo(name)).body("principalArn", equalTo(principal))
|
||||
.body("associatedAccessPolicies.policyArn", contains(policy, view))
|
||||
.body("associatedAccessPolicies[1].accessScope.namespaces", contains("dev-*", "payments"))
|
||||
.body("nextToken", nullValue());
|
||||
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
|
||||
.get(entryPath).then().statusCode(200).body("accessEntry.principalArn", equalTo(principal));
|
||||
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
|
||||
.delete(policiesPath + "/" + URLEncoder.encode(policy, StandardCharsets.UTF_8))
|
||||
.then().statusCode(200).body(equalTo("{}"));
|
||||
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
|
||||
.delete(policiesPath + "/" + URLEncoder.encode(policy, StandardCharsets.UTF_8))
|
||||
.then().statusCode(200).body(equalTo("{}"));
|
||||
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
|
||||
.get(policiesPath).then().statusCode(200).body("associatedAccessPolicies.policyArn", contains(view));
|
||||
given().header("Authorization", auth(account, "eks")).contentType("application/json")
|
||||
.urlEncodingEnabled(false)
|
||||
.body(Map.of("policyArn", policy, "accessScope", Map.of("type", "namespace")))
|
||||
.post(policiesPath).then().statusCode(400).body("__type", equalTo("InvalidParameterException"));
|
||||
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
|
||||
.delete(entryPath).then().statusCode(200);
|
||||
} 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) {
|
||||
@@ -101,6 +174,60 @@ class EksAccessEntryIntegrationTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPrincipalWithAnAccessPoliciesPathSegmentKeepsItsEntryRoutes() {
|
||||
// An IAM path or role name may be access-policies. Sent as the SDK sends it, %2F and all, such an entry
|
||||
// is still read and deleted as an entry, never as one of a shorter principal's access policies.
|
||||
String account = "135791357913";
|
||||
String name = "odd-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String runner = "runner-" + name;
|
||||
String midPath = "arn:aws:iam::" + account + ":role/ci/access-policies/" + runner;
|
||||
String named = "arn:aws:iam::" + account + ":role/" + name + "/access-policies";
|
||||
String path = "/clusters/" + name + "/access-entries";
|
||||
createRole(account, runner, "/ci/access-policies/");
|
||||
createRole(account, "access-policies", "/" + name + "/");
|
||||
createCluster(account, name, "API");
|
||||
try {
|
||||
for (String principal : List.of(midPath, named)) {
|
||||
String entryPath = path + "/" + URLEncoder.encode(principal, StandardCharsets.UTF_8);
|
||||
given().header("Authorization", auth(account, "eks")).contentType("application/json")
|
||||
.body(Map.of("principalArn", principal)).post(path).then().statusCode(200);
|
||||
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
|
||||
.get(entryPath).then().statusCode(200).body("accessEntry.principalArn", equalTo(principal));
|
||||
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
|
||||
.get(entryPath + "/access-policies").then().statusCode(200)
|
||||
.body("principalArn", equalTo(principal)).body("associatedAccessPolicies", empty());
|
||||
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"));
|
||||
}
|
||||
// Unencoded, the slashes are the router's: a DELETE is a disassociate only when what follows
|
||||
// access-policies is a cluster access policy ARN, so this one still deletes the entry.
|
||||
given().header("Authorization", auth(account, "eks")).contentType("application/json")
|
||||
.body(Map.of("principalArn", midPath)).post(path).then().statusCode(200);
|
||||
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
|
||||
.delete(path + "/" + midPath).then().statusCode(200).body(equalTo("{}"));
|
||||
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
|
||||
.get(path + "/" + URLEncoder.encode(midPath, StandardCharsets.UTF_8)).then().statusCode(404);
|
||||
} finally {
|
||||
given().header("Authorization", auth(account, "eks")).delete("/clusters/" + name).then().statusCode(200);
|
||||
deleteRole(account, runner);
|
||||
deleteRole(account, "access-policies");
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
.formParam("AssumeRolePolicyDocument", "{}").post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private static void deleteRole(String account, String role) {
|
||||
given().header("Authorization", auth(account, "iam")).contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DeleteRole").formParam("RoleName", role).post("/").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",
|
||||
|
||||
+234
-8
@@ -1,10 +1,15 @@
|
||||
package io.github.hectorvent.floci.services.eks;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
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.core.storage.PersistentStorage;
|
||||
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.AccessScope;
|
||||
import io.github.hectorvent.floci.services.eks.model.AssociateAccessPolicyRequest;
|
||||
import io.github.hectorvent.floci.services.eks.model.AssociatedAccessPolicy;
|
||||
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;
|
||||
@@ -12,8 +17,14 @@ 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 org.junit.jupiter.api.function.Executable;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -23,6 +34,9 @@ import static org.mockito.Mockito.*;
|
||||
|
||||
class EksAccessEntryServiceTest {
|
||||
private static final String PRINCIPAL = "arn:aws:iam::123456789012:role/path/worker";
|
||||
private static final String ADMIN = "arn:aws:eks::aws:cluster-access-policy/AmazonEKSClusterAdminPolicy";
|
||||
private static final String VIEW = "arn:aws:eks::aws:cluster-access-policy/AmazonEKSViewPolicy";
|
||||
private static final String EDIT = "arn:aws:eks::aws:cluster-access-policy/AmazonEKSEditPolicy";
|
||||
|
||||
@Test
|
||||
void nodeEntryUsesGeneratedIdentityAndCapturesStablePrincipalId() throws Exception {
|
||||
@@ -105,21 +119,48 @@ class EksAccessEntryServiceTest {
|
||||
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"));
|
||||
for (Executable invalid : List.<Executable>of(
|
||||
() -> fixture.service.list(fixture.cluster, 0, null),
|
||||
() -> fixture.service.list(fixture.cluster, 101, null),
|
||||
() -> fixture.service.list(fixture.cluster, 1, "invalid"))) {
|
||||
assertEquals("InvalidParameterException", assertThrows(AwsException.class, invalid).getErrorCode());
|
||||
}
|
||||
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()));
|
||||
assertEquals("InvalidParameterException", assertThrows(AwsException.class,
|
||||
() -> fixture.service.list(fixture.cluster, 1, first.nextToken())).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listingByAssociatedPolicyReturnsOnlyTheEntriesHoldingIt() {
|
||||
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));
|
||||
fixture.service.associate(fixture.cluster, second, policy(ADMIN, "cluster", null));
|
||||
fixture.service.associate(fixture.cluster, PRINCIPAL, policy(VIEW, "cluster", null));
|
||||
assertEquals(List.of(second), fixture.service.list(fixture.cluster, null, null, ADMIN).accessEntries());
|
||||
assertEquals(List.of(PRINCIPAL), fixture.service.list(fixture.cluster, null, null, VIEW).accessEntries());
|
||||
assertEquals(List.of(PRINCIPAL, second), fixture.service.list(fixture.cluster, null, null, null).accessEntries());
|
||||
// A page token carries on the filtered listing it came from.
|
||||
fixture.service.associate(fixture.cluster, PRINCIPAL, policy(ADMIN, "cluster", null));
|
||||
EksAccessEntryService.Page first = fixture.service.list(fixture.cluster, 1, null, ADMIN);
|
||||
assertEquals(List.of(PRINCIPAL), first.accessEntries());
|
||||
assertEquals(List.of(second), fixture.service.list(fixture.cluster, 1, first.nextToken(), ADMIN).accessEntries());
|
||||
}
|
||||
|
||||
@Test
|
||||
void clusterDeletionCleansEntriesAndRecreationCannotInheritThem() {
|
||||
Fixture fixture = fixture();
|
||||
fixture.service.create(fixture.cluster, request(PRINCIPAL, "EC2_LINUX", null));
|
||||
fixture.service.create(fixture.cluster, request(PRINCIPAL, "STANDARD", null));
|
||||
fixture.service.associate(fixture.cluster, PRINCIPAL, policy(ADMIN, "cluster", null));
|
||||
fixture.service.deleteClusterEntries(fixture.cluster);
|
||||
assertTrue(fixture.storage.scan(key -> true).isEmpty());
|
||||
fixture.service.create(fixture.cluster, request(PRINCIPAL, "EC2_LINUX", null));
|
||||
fixture.service.create(fixture.cluster, request(PRINCIPAL, "STANDARD", null));
|
||||
assertTrue(fixture.service.listAccessPolicies(fixture.cluster, PRINCIPAL, null, null)
|
||||
.associatedAccessPolicies().isEmpty());
|
||||
fixture.cluster.setCreatedAt(fixture.cluster.getCreatedAt().plusSeconds(1));
|
||||
assertTrue(fixture.service.list(fixture.cluster, null, null).accessEntries().isEmpty());
|
||||
assertEquals(404, assertThrows(AwsException.class,
|
||||
@@ -138,19 +179,204 @@ class EksAccessEntryServiceTest {
|
||||
request(PRINCIPAL, "EC2_LINUX", null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void associatingAgainReplacesTheScopeAndKeepsTheAssociationTime() {
|
||||
Fixture fixture = fixture();
|
||||
Clock clock = mock(Clock.class);
|
||||
when(clock.millis()).thenReturn(1_000L, 2_000L, 3_000L);
|
||||
EksAccessEntryService service = new EksAccessEntryService(fixture.storage, fixture.iam, clock);
|
||||
service.create(fixture.cluster, request(PRINCIPAL, "STANDARD", null));
|
||||
AssociatedAccessPolicy first = service.associate(fixture.cluster, PRINCIPAL, policy(ADMIN, "cluster", null));
|
||||
assertEquals(new AccessScope("cluster", List.of()), first.accessScope());
|
||||
assertEquals(2.0, first.associatedAt());
|
||||
assertEquals(2.0, first.modifiedAt());
|
||||
AssociatedAccessPolicy replaced = service.associate(fixture.cluster, PRINCIPAL,
|
||||
policy(ADMIN, "namespace", List.of("dev-*", "payments", "dev-*")));
|
||||
assertEquals(new AccessScope("namespace", List.of("dev-*", "payments")), replaced.accessScope());
|
||||
assertEquals(2.0, replaced.associatedAt());
|
||||
assertEquals(3.0, replaced.modifiedAt());
|
||||
service.associate(fixture.cluster, PRINCIPAL, policy(VIEW, "cluster", List.of()));
|
||||
assertEquals(List.of(ADMIN, VIEW), service.listAccessPolicies(fixture.cluster, PRINCIPAL, null, null)
|
||||
.associatedAccessPolicies().stream().map(AssociatedAccessPolicy::policyArn).toList());
|
||||
assertEquals(replaced, service.listAccessPolicies(fixture.cluster, PRINCIPAL, null, null)
|
||||
.associatedAccessPolicies().getFirst());
|
||||
}
|
||||
|
||||
@Test
|
||||
void disassociatingRemovesOnlyThatPolicyAndAMissingOneIsANoOp() {
|
||||
Fixture fixture = fixture();
|
||||
fixture.service.create(fixture.cluster, request(PRINCIPAL, "STANDARD", null));
|
||||
fixture.service.associate(fixture.cluster, PRINCIPAL, policy(ADMIN, "cluster", null));
|
||||
fixture.service.associate(fixture.cluster, PRINCIPAL, policy(VIEW, "cluster", null));
|
||||
fixture.service.disassociate(fixture.cluster, PRINCIPAL, ADMIN);
|
||||
assertEquals(List.of(VIEW), fixture.service.listAccessPolicies(fixture.cluster, PRINCIPAL, null, null)
|
||||
.associatedAccessPolicies().stream().map(AssociatedAccessPolicy::policyArn).toList());
|
||||
// EKS documents no error for a policy the entry does not hold, so removing it again succeeds; the
|
||||
// entry itself must still exist.
|
||||
fixture.service.disassociate(fixture.cluster, PRINCIPAL, ADMIN);
|
||||
assertEquals(List.of(VIEW), fixture.service.listAccessPolicies(fixture.cluster, PRINCIPAL, null, null)
|
||||
.associatedAccessPolicies().stream().map(AssociatedAccessPolicy::policyArn).toList());
|
||||
AwsException missing = assertThrows(AwsException.class,
|
||||
() -> fixture.service.disassociate(fixture.cluster, PRINCIPAL.replace("worker", "absent"), ADMIN));
|
||||
assertEquals("ResourceNotFoundException", missing.getErrorCode());
|
||||
assertEquals(404, missing.getHttpStatus());
|
||||
// The no-op covers a policy that could be associated, not an ARN associate would refuse.
|
||||
AwsException otherPartition = assertThrows(AwsException.class,
|
||||
() -> fixture.service.disassociate(fixture.cluster, PRINCIPAL, VIEW.replace("arn:aws:", "arn:aws-cn:")));
|
||||
assertEquals("InvalidParameterException", otherPartition.getErrorCode());
|
||||
assertEquals(List.of(VIEW), fixture.service.listAccessPolicies(fixture.cluster, PRINCIPAL, null, null)
|
||||
.associatedAccessPolicies().stream().map(AssociatedAccessPolicy::policyArn).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingTheEntryDropsItsPoliciesSoARecreatedEntryStartsEmpty() {
|
||||
Fixture fixture = fixture();
|
||||
fixture.service.create(fixture.cluster, request(PRINCIPAL, "STANDARD", null));
|
||||
fixture.service.associate(fixture.cluster, PRINCIPAL, policy(ADMIN, "cluster", null));
|
||||
fixture.service.delete(fixture.cluster, PRINCIPAL);
|
||||
assertEquals(404, assertThrows(AwsException.class, () -> fixture.service.listAccessPolicies(
|
||||
fixture.cluster, PRINCIPAL, null, null)).getHttpStatus());
|
||||
fixture.service.create(fixture.cluster, request(PRINCIPAL, "STANDARD", null));
|
||||
assertTrue(fixture.service.listAccessPolicies(fixture.cluster, PRINCIPAL, null, null)
|
||||
.associatedAccessPolicies().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidAssociationsAreRejectedWithoutStoringAnything() {
|
||||
Fixture fixture = fixture();
|
||||
fixture.service.create(fixture.cluster, request(PRINCIPAL, "STANDARD", null));
|
||||
for (AssociateAccessPolicyRequest invalid : List.of(
|
||||
new AssociateAccessPolicyRequest(null, new AccessScope("cluster", null)),
|
||||
new AssociateAccessPolicyRequest(ADMIN, null),
|
||||
policy("arn:aws:iam::aws:policy/AdministratorAccess", "cluster", null),
|
||||
policy(ADMIN.replace("arn:aws:", "arn:aws-cn:"), "cluster", null),
|
||||
policy(ADMIN + "/extra", "cluster", null),
|
||||
policy("", "cluster", null),
|
||||
policy("not-an-arn", "cluster", null),
|
||||
policy(ADMIN.replace("eks::", "eks:us-east-1:"), "cluster", null),
|
||||
policy(ADMIN.replace("::aws:", "::123456789012:"), "cluster", null),
|
||||
policy(ADMIN.replace("AdminPolicy", "Admin.Policy"), "cluster", null),
|
||||
policy(ADMIN.replace("AmazonEKSClusterAdminPolicy", ""), "cluster", null),
|
||||
policy(ADMIN.replace("cluster-access-policy/", "policy/"), "cluster", null),
|
||||
policy(ADMIN, null, null),
|
||||
policy(ADMIN, "global", null),
|
||||
policy(ADMIN, "namespace", null),
|
||||
policy(ADMIN, "namespace", List.of()),
|
||||
policy(ADMIN, "namespace", Arrays.asList("dev", null)),
|
||||
policy(ADMIN, "namespace", List.of("dev", " ")),
|
||||
policy(ADMIN, "cluster", List.of("dev")))) {
|
||||
assertEquals("InvalidParameterException", assertThrows(AwsException.class,
|
||||
() -> fixture.service.associate(fixture.cluster, PRINCIPAL, invalid)).getErrorCode(),
|
||||
invalid.toString());
|
||||
}
|
||||
assertTrue(fixture.service.listAccessPolicies(fixture.cluster, PRINCIPAL, null, null)
|
||||
.associatedAccessPolicies().isEmpty());
|
||||
assertEquals(404, assertThrows(AwsException.class, () -> fixture.service.associate(fixture.cluster,
|
||||
PRINCIPAL.replace("worker", "absent"), policy(ADMIN, "cluster", null))).getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyStandardEntriesTakeAccessPolicies() {
|
||||
Fixture fixture = fixture();
|
||||
fixture.service.create(fixture.cluster, request(PRINCIPAL, "EC2_LINUX", null));
|
||||
assertEquals("InvalidRequestException", assertThrows(AwsException.class, () -> fixture.service.associate(
|
||||
fixture.cluster, PRINCIPAL, policy(ADMIN, "cluster", null))).getErrorCode());
|
||||
assertTrue(fixture.service.listAccessPolicies(fixture.cluster, PRINCIPAL, null, null)
|
||||
.associatedAccessPolicies().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void associatedPolicyPagesCannotBeContinuedForAnotherEntry() {
|
||||
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));
|
||||
fixture.service.associate(fixture.cluster, PRINCIPAL, policy(ADMIN, "cluster", null));
|
||||
fixture.service.associate(fixture.cluster, PRINCIPAL, policy(VIEW, "cluster", null));
|
||||
fixture.service.associate(fixture.cluster, second, policy(EDIT, "cluster", null));
|
||||
fixture.service.associate(fixture.cluster, second, policy(VIEW, "cluster", null));
|
||||
EksAccessEntryService.PolicyPage first = fixture.service.listAccessPolicies(fixture.cluster, PRINCIPAL, 1, null);
|
||||
assertEquals(List.of(ADMIN), first.associatedAccessPolicies().stream().map(AssociatedAccessPolicy::policyArn).toList());
|
||||
assertNotNull(first.nextToken());
|
||||
EksAccessEntryService.PolicyPage next = fixture.service.listAccessPolicies(fixture.cluster, PRINCIPAL, 1,
|
||||
first.nextToken());
|
||||
assertEquals(List.of(VIEW), next.associatedAccessPolicies().stream().map(AssociatedAccessPolicy::policyArn).toList());
|
||||
assertNull(next.nextToken());
|
||||
for (Executable invalid : List.<Executable>of(
|
||||
() -> fixture.service.listAccessPolicies(fixture.cluster, second, 1, first.nextToken()),
|
||||
() -> fixture.service.listAccessPolicies(fixture.cluster, PRINCIPAL, 0, null),
|
||||
() -> fixture.service.listAccessPolicies(fixture.cluster, PRINCIPAL, 101, null),
|
||||
() -> fixture.service.listAccessPolicies(fixture.cluster, PRINCIPAL, 1, "x"))) {
|
||||
assertEquals("InvalidParameterException", assertThrows(AwsException.class, invalid).getErrorCode());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void entriesPersistedBeforeAccessPoliciesExistedStillLoad(@TempDir Path directory) throws Exception {
|
||||
Fixture fixture = fixture();
|
||||
fixture.service.create(fixture.cluster, request(PRINCIPAL, "STANDARD", null));
|
||||
String key = fixture.storage.keys().iterator().next();
|
||||
EksAccessEntryService.StoredEntry stored = fixture.storage.get(key).orElseThrow();
|
||||
Path file = directory.resolve("eks-access-entries.json");
|
||||
Files.writeString(file, new ObjectMapper().writeValueAsString(Map.of(key,
|
||||
Map.of("entry", stored.entry(), "principalId", stored.principalId()))));
|
||||
TypeReference<Map<String, EksAccessEntryService.StoredEntry>> type = new TypeReference<>() {};
|
||||
PersistentStorage<String, EksAccessEntryService.StoredEntry> persisted = new PersistentStorage<>(file, type);
|
||||
persisted.load();
|
||||
EksAccessEntryService service = new EksAccessEntryService(persisted, fixture.iam);
|
||||
assertTrue(service.listAccessPolicies(fixture.cluster, PRINCIPAL, null, null).associatedAccessPolicies().isEmpty());
|
||||
AssociatedAccessPolicy association = service.associate(fixture.cluster, PRINCIPAL,
|
||||
policy(ADMIN, "namespace", List.of("dev")));
|
||||
persisted.flush();
|
||||
PersistentStorage<String, EksAccessEntryService.StoredEntry> reloaded = new PersistentStorage<>(file, type);
|
||||
reloaded.load();
|
||||
assertEquals(List.of(association), new EksAccessEntryService(reloaded, fixture.iam)
|
||||
.listAccessPolicies(fixture.cluster, PRINCIPAL, null, null).associatedAccessPolicies());
|
||||
}
|
||||
|
||||
@Test
|
||||
void policiesFollowTheClusterPartition() {
|
||||
Fixture fixture = fixture("aws-cn");
|
||||
String principal = cn(PRINCIPAL);
|
||||
fixture.service.create(fixture.cluster, request(principal, "STANDARD", null));
|
||||
fixture.service.associate(fixture.cluster, principal, policy(cn(ADMIN), "cluster", null));
|
||||
assertEquals(List.of(cn(ADMIN)), fixture.service.listAccessPolicies(fixture.cluster, principal, null, null)
|
||||
.associatedAccessPolicies().stream().map(AssociatedAccessPolicy::policyArn).toList());
|
||||
assertEquals("InvalidParameterException", assertThrows(AwsException.class,
|
||||
() -> fixture.service.associate(fixture.cluster, principal, policy(VIEW, "cluster", null))).getErrorCode());
|
||||
fixture.service.disassociate(fixture.cluster, principal, cn(ADMIN));
|
||||
assertTrue(fixture.service.listAccessPolicies(fixture.cluster, principal, null, null)
|
||||
.associatedAccessPolicies().isEmpty());
|
||||
}
|
||||
|
||||
private static String cn(String arn) {
|
||||
return arn.replace("arn:aws:", "arn:aws-cn:");
|
||||
}
|
||||
|
||||
private static AssociateAccessPolicyRequest policy(String arn, String type, List<String> namespaces) {
|
||||
return new AssociateAccessPolicyRequest(arn, new AccessScope(type, namespaces));
|
||||
}
|
||||
|
||||
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() {
|
||||
return fixture("aws");
|
||||
}
|
||||
|
||||
private static Fixture fixture(String partition) {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setName("nodes");
|
||||
cluster.setArn("arn:aws:eks:us-east-1:123456789012:cluster/nodes");
|
||||
cluster.setArn("arn:" + partition + ":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, "{}");
|
||||
IamRole role = new IamRole("AROA-worker", "worker", "/path/",
|
||||
PRINCIPAL.replace("arn:aws:", "arn:" + partition + ":"), "{}");
|
||||
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));
|
||||
|
||||
@@ -387,13 +387,24 @@ class IamActionRegistryTest {
|
||||
|
||||
@Test
|
||||
void anEksAccessEntryRouteTakesThePrincipalAsTheRestOfThePath() {
|
||||
// EKS reads the principal greedily, so a GET or DELETE under an entry reads or deletes an entry.
|
||||
// EKS reads the principal greedily, but an entry's access policy routes win over the entry's own, as
|
||||
// they do in the router.
|
||||
String entry = "/clusters/c/access-entries/arn:aws:iam::000000000000:role/team/worker";
|
||||
String[][] routes = {
|
||||
{"GET", entry, "eks:DescribeAccessEntry"},
|
||||
{"GET", entry + "/access-policies", "eks:DescribeAccessEntry"},
|
||||
{"DELETE", entry + "/access-policies/arn:aws:eks::aws:cluster-access-policy/Admin", "eks:DeleteAccessEntry"},
|
||||
{"DELETE", entry, "eks:DeleteAccessEntry"},
|
||||
{"GET", entry + "/access-policies", "eks:ListAssociatedAccessPolicies"},
|
||||
{"DELETE", entry + "/access-policies/arn:aws:eks::aws:cluster-access-policy/Admin",
|
||||
"eks:DisassociateAccessPolicy"},
|
||||
{"POST", entry + "/access-policies", "eks:AssociateAccessPolicy"},
|
||||
{"DELETE", entry + "/access-policies/arn%3Aaws%3Aeks%3A%3Aaws%3Acluster-access-policy%2FAdmin",
|
||||
"eks:DisassociateAccessPolicy"},
|
||||
// A principal whose IAM path holds an access-policies segment is still an entry: only a cluster
|
||||
// access policy ARN after it makes a DELETE a disassociate.
|
||||
{"DELETE", "/clusters/c/access-entries/arn:aws:iam::000000000000:role/ci/access-policies/runner",
|
||||
"eks:DeleteAccessEntry"},
|
||||
{"GET", "/clusters/c/access-entries/arn:aws:iam::000000000000:role/ci/access-policies/runner",
|
||||
"eks:DescribeAccessEntry"},
|
||||
{"POST", entry, "eks:UpdateAccessEntry"},
|
||||
{"GET", "/clusters/c/access-entries", "eks:ListAccessEntries"},
|
||||
};
|
||||
|
||||
+10
-7
@@ -45,14 +45,11 @@ class IamRestRouteCoverageTest {
|
||||
* Operations Floci does not serve, whose request runs as another operation instead and so is checked
|
||||
* as that one: S3 has no bucket metadata configuration, and {@code ?metadataConfiguration} on a
|
||||
* bucket falls through to ListObjects and DeleteBucket. Checking it as the metadata table action
|
||||
* would let that action list or delete the bucket. EKS takes an access entry's principal as the rest
|
||||
* of the path, so an entry's access policy routes read and delete the entry of a longer principal.
|
||||
* would let that action list or delete the bucket.
|
||||
*/
|
||||
private static final Map<String, String> RUN_AS_ANOTHER_OPERATION = Map.of(
|
||||
"GetBucketMetadataConfiguration", "s3:ListBucket",
|
||||
"DeleteBucketMetadataConfiguration", "s3:DeleteBucket",
|
||||
"ListAssociatedAccessPolicies", "eks:DescribeAccessEntry",
|
||||
"DisassociateAccessPolicy", "eks:DeleteAccessEntry");
|
||||
"DeleteBucketMetadataConfiguration", "s3:DeleteBucket");
|
||||
|
||||
/** Models every operation of which is checked: the services whose routes the registry maps in full. */
|
||||
private static final Set<String> FULLY_ROUTED_MODELS =
|
||||
@@ -153,12 +150,18 @@ class IamRestRouteCoverageTest {
|
||||
return ctx;
|
||||
}
|
||||
|
||||
/** The path with each {@code {label}} filled in, and a greedy {@code {label+}} given two segments. */
|
||||
/**
|
||||
* The path with each {@code {label}} filled in, and a greedy {@code {label+}} given two segments. A
|
||||
* {@code {policyArn}} gets a cluster access policy ARN, encoded as an SDK sends it, since only that
|
||||
* shape routes to the policy operations.
|
||||
*/
|
||||
private static String fill(String template) {
|
||||
Matcher label = LABEL.matcher(template);
|
||||
StringBuilder path = new StringBuilder();
|
||||
while (label.find()) {
|
||||
String value = label.group(1).toLowerCase() + "-value";
|
||||
String value = label.group(1).equals("policyArn")
|
||||
? "arn%3Aaws%3Aeks%3A%3Aaws%3Acluster-access-policy%2FAmazonEKSViewPolicy"
|
||||
: label.group(1).toLowerCase() + "-value";
|
||||
label.appendReplacement(path, label.group(2).isEmpty() ? value : value + "/part");
|
||||
}
|
||||
label.appendTail(path);
|
||||
|
||||
+33
-13
@@ -207,24 +207,44 @@ class IamRestRouteEnforcementIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEksAccessEntrysPolicyRoutesAreCheckedAsTheEntryRoutesTheyRunAs() {
|
||||
// EKS takes an access entry's principal as the rest of the path, so a request on an entry's access
|
||||
// policies reads or deletes the entry of a longer principal, and is checked as that.
|
||||
void anEksAccessEntrysPolicyRoutesAreCheckedAsTheirOwnActionsOnTheEntry() {
|
||||
// Associating, listing and disassociating an entry's access policies act on that entry, so a grant on
|
||||
// another entry does not cover them, and one on the entry's own ARN does.
|
||||
String user = user("route-eks-entry");
|
||||
String name = "route-entry-" + suffix();
|
||||
String base = "/clusters/" + name + "/access-entries";
|
||||
eksCluster(name);
|
||||
String principal = encoded("arn:aws:iam::" + ACCOUNT + ":role/route-entry");
|
||||
String policies = "/clusters/" + name + "/access-entries/" + principal + "/access-policies";
|
||||
String admin = encoded("arn:aws:eks::aws:cluster-access-policy/AmazonEKSClusterAdminPolicy");
|
||||
String trust = "{\"Version\":\"2012-10-17\",\"Statement\":[" + allow("s3:*", "*") + "]}";
|
||||
String role = EnforcementFixtures.createRole(cleanup, baseUri.getPort(), ACCOUNT, "/", "route-entry-" + suffix(),
|
||||
trust);
|
||||
String otherRole = EnforcementFixtures.createRole(cleanup, baseUri.getPort(), ACCOUNT, "/",
|
||||
"route-other-" + suffix(), trust);
|
||||
String entry = eks().body("{\"principalArn\":\"" + role + "\"}").post(base).then().statusCode(200)
|
||||
.extract().path("accessEntry.accessEntryArn");
|
||||
String other = eks().body("{\"principalArn\":\"" + otherRole + "\"}").post(base).then().statusCode(200)
|
||||
.extract().path("accessEntry.accessEntryArn");
|
||||
String policies = base + "/" + encoded(role) + "/access-policies";
|
||||
String admin = "arn:aws:eks::aws:cluster-access-policy/AmazonEKSClusterAdminPolicy";
|
||||
String associate = "{\"policyArn\":\"" + admin + "\",\"accessScope\":{\"type\":\"cluster\"}}";
|
||||
String actions = "[\"eks:AssociateAccessPolicy\",\"eks:ListAssociatedAccessPolicies\","
|
||||
+ "\"eks:DisassociateAccessPolicy\"]";
|
||||
|
||||
policy(user, allow("eks:ListAssociatedAccessPolicies", "*") + "," + allow("eks:DisassociateAccessPolicy", "*"));
|
||||
refused(as(user, "eks").urlEncodingEnabled(false).get(policies).then(), "eks:DescribeAccessEntry");
|
||||
refused(as(user, "eks").urlEncodingEnabled(false).delete(policies + "/" + admin).then(),
|
||||
policy(user, "{\"Effect\":\"Allow\",\"Action\":" + actions + ",\"Resource\":\"" + other + "\"}");
|
||||
refused(as(user, "eks").urlEncodingEnabled(false).body(associate).post(policies).then(),
|
||||
"eks:AssociateAccessPolicy");
|
||||
refused(as(user, "eks").urlEncodingEnabled(false).get(policies).then(), "eks:ListAssociatedAccessPolicies");
|
||||
refused(as(user, "eks").urlEncodingEnabled(false).delete(policies + "/" + encoded(admin)).then(),
|
||||
"eks:DisassociateAccessPolicy");
|
||||
|
||||
policy(user, "{\"Effect\":\"Allow\",\"Action\":" + actions + ",\"Resource\":\"" + entry + "\"}");
|
||||
as(user, "eks").urlEncodingEnabled(false).body(associate).post(policies).then().statusCode(200);
|
||||
as(user, "eks").urlEncodingEnabled(false).get(policies).then().statusCode(200)
|
||||
.body("associatedAccessPolicies[0].policyArn", equalTo(admin));
|
||||
as(user, "eks").urlEncodingEnabled(false).delete(policies + "/" + encoded(admin)).then().statusCode(200);
|
||||
// A principal whose IAM path holds access-policies is an entry, so deleting it is DeleteAccessEntry.
|
||||
refused(as(user, "eks").urlEncodingEnabled(false)
|
||||
.delete(base + "/arn:aws:iam::" + ACCOUNT + ":role/ci/access-policies/runner").then(),
|
||||
"eks:DeleteAccessEntry");
|
||||
// Allowed, it reaches EKS, which looks up the entry of a principal ending in /access-policies.
|
||||
policy(user, allow("eks:DescribeAccessEntry", "*"));
|
||||
as(user, "eks").urlEncodingEnabled(false).get(policies).then().statusCode(404)
|
||||
.body("message", equalTo("Access entry not found"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -2053,6 +2053,7 @@ class ResourceArnBuilderTest {
|
||||
/** The cluster {@code held}, which EKS keeps in us-west-2 and finds by its name alone, and what it holds. */
|
||||
private static final String HELD_CLUSTER = "arn:aws:eks:us-west-2:000000000000:cluster/held";
|
||||
private static final String WORKER = "arn:aws:iam::000000000000:role/team/worker";
|
||||
private static final String RUNNER = "arn:aws:iam::000000000000:role/ci/access-policies/runner";
|
||||
|
||||
private static ResourceArnBuilder eksHolding() {
|
||||
EksService eks = mock(EksService.class);
|
||||
@@ -2065,6 +2066,7 @@ class ResourceArnBuilderTest {
|
||||
{"pod-identity-associations", "a-1", "podidentityassociation/held/a-1"},
|
||||
{"access-entries", WORKER, "access-entry/held/role/000000000000/worker/5"},
|
||||
{"access-entries", WORKER + "/access-policies", "access-entry/held/role/000000000000/access-policies/6"},
|
||||
{"access-entries", RUNNER, "access-entry/held/role/000000000000/runner/7"},
|
||||
}) {
|
||||
when(eks.findResourceArn("held", held[0], held[1]))
|
||||
.thenReturn(Optional.of("arn:aws:eks:us-west-2:000000000000:" + held[2]));
|
||||
@@ -2115,8 +2117,23 @@ class ResourceArnBuilderTest {
|
||||
"/clusters/held/access-entries/arn%3Aaws%3Aiam%3A%3A000000000000%3Arole%2Fteam%2Fworker"));
|
||||
assertEquals(held + "access-entry/held/role/000000000000/worker/5",
|
||||
eksResource(eks, "DELETE", "/clusters/held/access-entries/" + WORKER));
|
||||
assertEquals(held + "access-entry/held/role/000000000000/access-policies/6",
|
||||
// An entry's access policy routes act on the entry, as the router serves them.
|
||||
String admin = "/access-policies/arn:aws:eks::aws:cluster-access-policy/AmazonEKSClusterAdminPolicy";
|
||||
assertEquals(held + "access-entry/held/role/000000000000/worker/5",
|
||||
eksResource(eks, "GET", "/clusters/held/access-entries/" + WORKER + "/access-policies"));
|
||||
assertEquals(held + "access-entry/held/role/000000000000/worker/5",
|
||||
eksResource(eks, "POST", "/clusters/held/access-entries/" + WORKER + "/access-policies"));
|
||||
assertEquals(held + "access-entry/held/role/000000000000/worker/5",
|
||||
eksResource(eks, "DELETE", "/clusters/held/access-entries/" + WORKER + admin));
|
||||
assertEquals(held + "access-entry/held/role/000000000000/worker/5", eksResource(eks, "DELETE",
|
||||
"/clusters/held/access-entries/" + WORKER
|
||||
+ "/access-policies/arn%3Aaws%3Aeks%3A%3Aaws%3Acluster-access-policy%2FAdmin"));
|
||||
// Any other route under the entry takes the rest of the path as its principal, an IAM path holding
|
||||
// access-policies included.
|
||||
assertEquals(held + "access-entry/held/role/000000000000/runner/7",
|
||||
eksResource(eks, "DELETE", "/clusters/held/access-entries/" + RUNNER));
|
||||
assertEquals(held + "access-entry/held/role/000000000000/access-policies/6",
|
||||
eksResource(eks, "DELETE", "/clusters/held/access-entries/" + WORKER + "/access-policies"));
|
||||
// What EKS does not hold names no resource, nor do what Floci keeps no id for.
|
||||
assertEquals("*", eksResource(eks, "GET", "/clusters/held/node-groups/other"));
|
||||
assertEquals("*", eksResource(eks, "GET", "/clusters/gone/addons/vpc-cni"));
|
||||
|
||||
Reference in new issue
Block a user