fix(iam): check EKS requests on the resources the generated table gives them (#9070)

EKS was built by hand: ResourceArnBuilder walked an EKS path, looked
each resource up through EksService, and checked a tagging route on the
caller's cluster named after the ARN's last segment; the request
resources table held no EKS operation, and nothing gave a policy
condition an EKS resource's tags. eks moves from HAND_BUILT to
NAMESPACES, so the table gives each operation the cluster its path
names, the node group, add-on or Fargate profile EksStoredResourceArns
finds by its cluster and name, the ARN a tagging route carries, and
parts of an ARN the request does not give open. CreateCluster, for which
the Service Reference lists no resource type, is checked on the cluster
its body names from a MEASURED entry quoting the EKS user guide's
example policy for creating a cluster. ResourceArnBuilder's EKS section
and its EksService dependency go. EksStoredResourceArns answers the
stored tags of a cluster, node group, Fargate profile, add-on, Pod
Identity association or access entry; EKS's tag changes take one lock
and give a cluster, node group or Fargate profile a new map, whose tags
field is now volatile, and a cluster is tagged only when its ARN is the
whole ARN the request names. Tag changes and tag reads find a cluster,
node group or Fargate profile through one lookup, and an ARN with a part
left open is not looked up. Read from its model, EKS tags only on
/tags/{resourceArn} with the ARN encoded, as the SDKs send it, so the
tagging tests that sent it unencoded now encode it. Only EKS's
operations change in the table.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-19 23:25:25 -04:00
1 parent e50e7dac36
commit e8f16911d2
19 files changed
+509 -364

No files matched your search

@@ -60,9 +60,10 @@ import java.util.Optional;
* Map, for the tags of a namespace or a service; Elastic Load Balancing, for the tags of a load balancer, a target
* group, a listener, a rule or a Classic Load Balancer; SQS, for the tags of a queue; SNS, for the tags of a topic;
* Kinesis Data Streams, for the tags of a stream or a consumer; EventBridge Pipes, for the tags of a pipe; Aurora DSQL,
* for the tags of a cluster); looked up lazily by {@code ResourceArnBuilder} and {@code IamConditionContextResolver}
* through {@code Instance<StoredResourceArns>} for the namespace a request or an ARN is of, so IAM never depends on
* that service directly.</p>
* for the tags of a cluster; EKS, for the tags of a cluster, a node group, a Fargate profile, an add-on, a Pod Identity
* association or an access entry); looked up lazily by {@code ResourceArnBuilder} and
* {@code IamConditionContextResolver} through {@code Instance<StoredResourceArns>} for the namespace a request or an
* ARN is of, so IAM never depends on that service directly.</p>
*
* <p>Each answer is a lookup of what the service holds, asked for by an entry of the generated table ({@code find},
* {@code through}, a default, {@code forwarded}, a type's {@code resourceTagKeys}): never a fact about what an operation acts on, which the table alone
@@ -305,6 +305,26 @@ public class EksAccessEntryService {
return Optional.empty();
}
/**
* The tags of the access entry of {@code cluster} in {@code account} whose ARN is {@code accessEntryArn}, read in
* place.
*/
Optional<Map<String, String>> tagsInAccount(String account, Cluster cluster, String accessEntryArn) {
String prefix = prefix(cluster);
for (String key : entries.keys()) {
if (!key.startsWith(prefix)) {
continue;
}
Optional<Map<String, String>> tags = AccountAwareStorageBackend.readInAccount(entries, account, key)
.filter(stored -> accessEntryArn.equals(stored.entry().accessEntryArn()))
.map(stored -> stored.entry().tags());
if (tags.isPresent()) {
return tags;
}
}
return Optional.empty();
}
private static String prefix(Cluster cluster) {
// A recreated cluster must not inherit access entries or pagination tokens from its predecessor.
return cluster.getArn() + "/" + Objects.toString(cluster.getCreatedAt()) + "/";
@@ -541,6 +541,17 @@ public class EksAddonService {
return Optional.of(tags);
}
/**
* The tags of the add-on {@code addonName} of {@code cluster} in {@code account}, read in place, if its ARN is
* {@code addonArn}.
*/
Optional<Map<String, String>> tagsInAccount(String account, Cluster cluster, String addonName, String addonArn) {
return AccountAwareStorageBackend.readInAccount(storage, account,
prefix(cluster) + addonName.toLowerCase(Locale.ROOT))
.filter(stored -> addonArn.equals(stored.addon().addonArn()))
.map(stored -> stored.addon().tags());
}
private static String prefix(Cluster cluster) {
return cluster.getArn() + "/" + Objects.toString(cluster.getCreatedAt()) + "/";
}
@@ -6,6 +6,7 @@ import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.Base64Url;
import io.floci.aws.core.common.EpochSeconds;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.eks.model.Cluster;
@@ -324,6 +325,17 @@ public class EksPodIdentityAssociationService {
return Optional.of(tags);
}
/**
* The tags of the association {@code associationId} of {@code cluster} in {@code account}, read in place, if its ARN
* is {@code associationArn}.
*/
Optional<Map<String, String>> tagsInAccount(String account, Cluster cluster, String associationId,
String associationArn) {
return AccountAwareStorageBackend.readInAccount(associations, account, prefix(cluster) + associationId)
.filter(stored -> associationArn.equals(stored.association().associationArn()))
.map(stored -> stored.association().tags());
}
private static String prefix(Cluster cluster) {
String base = cluster.getArn() != null ? cluster.getArn() : cluster.getName();
return base + "/" + Objects.toString(cluster.getCreatedAt()) + "/";
@@ -131,6 +131,8 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
private final Map<String, CompletableFuture<Boolean>> pendingFirstNodeGroups = new ConcurrentHashMap<>();
// Storage hands every caller the same live Cluster, and Cluster keeps identity equality.
private final Set<Cluster> clustersBeingDeleted = ConcurrentHashMap.newKeySet();
/** Held by every tag change, so two of them on one resource cannot lose one another's tags. */
private final Object tagLock = new Object();
private final Set<String> restoringClusters = ConcurrentHashMap.newKeySet();
/** {@code <account>/<cluster key>} of each cluster a CreateCluster call is building. */
private final Set<String> clustersBeingCreated = ConcurrentHashMap.newKeySet();
@@ -1839,9 +1841,17 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
/**
* Applies {@code edit} to the tags of the resource {@code resourceArn} names and returns them.
* TagResource takes a cluster, node group, Fargate profile, add-on, pod identity association or
* access entry ARN; each child ARN names its cluster as the segment after the resource type.
* access entry ARN; each child ARN names its cluster as the segment after the resource type, and the
* resource found is the one whose ARN is the whole of {@code resourceArn}. One change at a time, each
* giving the resource a new map, so a lookup that takes no lock reads one whole set.
*/
private Map<String, String> retag(String resourceArn, UnaryOperator<Map<String, String>> edit) {
synchronized (tagLock) {
return retagHoldingLock(resourceArn, edit);
}
}
private Map<String, String> retagHoldingLock(String resourceArn, UnaryOperator<Map<String, String>> edit) {
String resource = AwsArnUtils.isArnFor(resourceArn, "eks") ? AwsArnUtils.parse(resourceArn).resource() : "";
String[] parts = resource.split("/", -1);
boolean child = !"cluster".equals(parts[0]);
@@ -1859,23 +1869,11 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
}
return next;
};
TaggableReads reads = new TaggableReads(storage::get, nodeGroupStorage::get, fargateProfileStorage::get);
Optional<Map<String, String>> tags = switch (parts[0]) {
case "cluster" -> storage.get(clusterKey).map(cluster -> applyTags(cluster.getTags(), change, next -> {
cluster.setTags(new HashMap<>(next));
storage.put(clusterKey, cluster);
}));
case "nodegroup" -> nodeGroupStorage.get(nodeGroupKey(clusterKey, childName))
.filter(nodegroup -> resourceArn.equals(nodegroup.getNodegroupArn()))
.map(nodegroup -> applyTags(nodegroup.getTags(), change, next -> {
nodegroup.setTags(new HashMap<>(next));
nodeGroupStorage.put(nodeGroupKey(clusterKey, childName), nodegroup);
}));
case "fargateprofile" -> fargateProfileStorage.get(fargateProfileKey(clusterKey, childName))
.filter(profile -> resourceArn.equals(profile.getFargateProfileArn()))
.map(profile -> applyTags(profile.getTags(), change, next -> {
profile.setTags(new HashMap<>(next));
fargateProfileStorage.put(fargateProfileKey(clusterKey, childName), profile);
}));
case "cluster", "nodegroup", "fargateprofile" ->
taggable(parts[0], clusterKey, childName, resourceArn, reads)
.map(found -> applyTags(found.tags(), change, found.retag()));
case "addon" -> addons == null ? Optional.empty() : storage.get(clusterKey)
.flatMap(cluster -> addons.retag(cluster, childName, resourceArn, change));
case "podidentityassociation" -> podIdentityAssociations == null ? Optional.empty()
@@ -1889,6 +1887,74 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
"Resource not found: " + resourceArn, 404));
}
/**
* The tags of the cluster, node group, Fargate profile, add-on, Pod Identity association or access entry whose
* ARN is {@code arn} in {@code account}, read in place where the tag handlers read them and matched on the whole
* ARN each records; none when there is no such resource.
*/
Map<String, String> tagsInAccount(String account, String arn) {
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
String[] parts = parsed.resource().split("/", -1);
if (parts.length < 2 || parts[1].isEmpty()) {
return Map.of();
}
String clusterKey = clusterKey(parsed.region(), parts[1]);
String child = parts.length > 2 ? parts[2] : "";
TaggableReads reads = new TaggableReads(
key -> AccountAwareStorageBackend.readInAccount(storage, account, key),
key -> AccountAwareStorageBackend.readInAccount(nodeGroupStorage, account, key),
key -> AccountAwareStorageBackend.readInAccount(fargateProfileStorage, account, key));
Optional<Cluster> cluster = reads.cluster().apply(clusterKey);
Optional<Map<String, String>> tags = switch (parts[0]) {
case "cluster", "nodegroup", "fargateprofile" -> taggable(parts[0], clusterKey, child, arn, reads)
.map(Taggable::tags);
case "addon" -> addons == null ? Optional.empty()
: cluster.flatMap(found -> addons.tagsInAccount(account, found, child, arn));
case "podidentityassociation" -> podIdentityAssociations == null ? Optional.empty()
: cluster.flatMap(found -> podIdentityAssociations.tagsInAccount(account, found, child, arn));
case "access-entry" -> accessEntries == null ? Optional.empty()
: cluster.flatMap(found -> accessEntries.tagsInAccount(account, found, arn));
default -> Optional.empty();
};
return tags.orElse(Map.of());
}
/** How a cluster, node group or Fargate profile is read by its key: in the request's account, or in a given one. */
private record TaggableReads(Function<String, Optional<Cluster>> cluster,
Function<String, Optional<Nodegroup>> nodegroup,
Function<String, Optional<FargateProfile>> fargateProfile) {}
/** A cluster, node group or Fargate profile found for its tags: the tags it holds, and how to store new ones. */
private record Taggable(Map<String, String> tags, Consumer<Map<String, String>> retag) {}
/**
* The cluster, node group or Fargate profile of {@code type} whose ARN is the whole of {@code arn}, read through
* {@code reads} by its cluster's key and its own name. Tag changes and tag reads both find it here, so they agree
* on which resource an ARN names.
*/
private Optional<Taggable> taggable(String type, String clusterKey, String name, String arn, TaggableReads reads) {
return switch (type) {
case "cluster" -> reads.cluster().apply(clusterKey).filter(cluster -> arn.equals(cluster.getArn()))
.map(cluster -> new Taggable(cluster.getTags(), next -> {
cluster.setTags(new HashMap<>(next));
storage.put(clusterKey, cluster);
}));
case "nodegroup" -> reads.nodegroup().apply(nodeGroupKey(clusterKey, name))
.filter(nodegroup -> arn.equals(nodegroup.getNodegroupArn()))
.map(nodegroup -> new Taggable(nodegroup.getTags(), next -> {
nodegroup.setTags(new HashMap<>(next));
nodeGroupStorage.put(nodeGroupKey(clusterKey, name), nodegroup);
}));
case "fargateprofile" -> reads.fargateProfile().apply(fargateProfileKey(clusterKey, name))
.filter(profile -> arn.equals(profile.getFargateProfileArn()))
.map(profile -> new Taggable(profile.getTags(), next -> {
profile.setTags(new HashMap<>(next));
fargateProfileStorage.put(fargateProfileKey(clusterKey, name), profile);
}));
default -> Optional.empty();
};
}
/** The TagMap limits: at most 50 tags, keys of 1 to 128 characters and values of at most 256. */
private static void checkTagLimits(Map<String, String> tags) {
if (tags.size() > 50) {
@@ -0,0 +1,77 @@
package io.floci.aws.services.eks;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.StoredResourceArns;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* IAM's lookups of what EKS holds, for the {@code eks} namespace: the node group, add-on or Fargate profile a request
* names by its cluster and its name, whose ARN ends in an id EKS minted, which the generated request-resource table
* asks EKS to find, and the tags of what EKS holds.
*/
@ApplicationScoped
public class EksStoredResourceArns implements StoredResourceArns {
private static final String NAMESPACE = "eks";
private static final Map<String, String> COLLECTIONS = Map.of(
"nodegroup", "node-groups",
"addon", "addons",
"fargateprofile", "fargate-profiles");
private final EksService eks;
private final RegionResolver regionResolver;
@Inject
public EksStoredResourceArns(EksService eks, RegionResolver regionResolver) {
this.eks = eks;
this.regionResolver = regionResolver;
}
@Override
public String namespace() {
return NAMESPACE;
}
/**
* The ARN EKS holds the node group, add-on or Fargate profile under that {@code names}, its cluster's name and its
* own, name in {@code region}, found as its handlers find it. None for another type, which EKS does not hold, or
* when it holds no such resource.
*/
@Override
public Optional<String> find(String type, List<String> names, String region) {
String collection = COLLECTIONS.get(type);
if (collection == null || names.size() != 2 || !region.equals(regionResolver.getRegion())) {
return Optional.empty();
}
return eks.findResourceArn(names.get(0), collection, names.get(1))
.filter(arn -> region.equals(AwsArnUtils.regionOrDefault(arn, null)));
}
/**
* The tags of the cluster, node group, Fargate profile, add-on, Pod Identity association or access entry whose ARN
* is {@code arn}, in the request's account, where the tag handlers read: an ARN of another account names none. The
* resource is read in place and matched on the whole ARN it records. A tag without a value reads as an empty one.
* Tag calls give the resource a new map one at a time, so the read is of one whole set. An ARN with a part left
* open ({@code *}), as the table gives an access entry or a Pod Identity association a request names by no id,
* names no resource EKS holds, so it is not looked up: finding an access entry by its ARN walks its cluster's
* entries.
*/
@Override
public Map<String, String> storedTags(String arn) {
if (!AwsArnUtils.isArnFor(arn, NAMESPACE) || arn.indexOf('*') >= 0) {
return Map.of();
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
String account = regionResolver.getAccountId();
if (!parsed.accountId().equals(account) || parsed.region().isBlank()) {
return Map.of();
}
return StoredResourceArns.withEmptyValues(eks.tagsInAccount(account, arn));
}
}
@@ -62,7 +62,7 @@ public class Cluster {
private String platformVersion;
@JsonProperty("tags")
private Map<String, String> tags;
private volatile Map<String, String> tags;
@JsonIgnore
private String containerId;
@@ -43,7 +43,7 @@ public class FargateProfile {
private Health health;
@JsonProperty("tags")
private Map<String, String> tags;
private volatile Map<String, String> tags;
@JsonIgnore
private String accountId;
@@ -98,7 +98,7 @@ public class Nodegroup {
private Object warmPoolConfig;
@JsonProperty("tags")
private Map<String, String> tags;
private volatile Map<String, String> tags;
@JsonProperty("clientRequestToken")
@JsonIgnore
@@ -15,8 +15,6 @@ import io.floci.aws.core.common.auth.SigV4Canonicalization;
import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsCrossAccountService;
import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsDeliveryService;
import io.floci.aws.services.cloudwatch.logs.LogGroupTagTarget;
import io.floci.aws.services.eks.EksController;
import io.floci.aws.services.eks.EksService;
import io.floci.aws.services.kms.KmsService;
import io.floci.aws.services.s3.S3ControlArnUtils;
import io.floci.aws.services.s3.S3ObjectKeys;
@@ -43,7 +41,6 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.StringJoiner;
import java.util.regex.Pattern;
/**
* Constructs the target resource ARN for a request so the policy evaluator
@@ -55,7 +52,6 @@ import java.util.regex.Pattern;
@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://";
@@ -83,8 +79,6 @@ public class ResourceArnBuilder {
* which IamService itself does not depend on, and a direct injection would close that loop.
*/
private final Instance<IamService> iamService;
/** Looked up lazily for the same reason, to read the ARN an EKS cluster or what it holds is stored under. */
private final Instance<EksService> eksService;
/** Looked up lazily for the same reason, to resolve a key named by an id, an alias or an ARN to its stored ARN. */
private final Instance<KmsService> kmsService;
/**
@@ -101,34 +95,25 @@ public class ResourceArnBuilder {
@Inject
public ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService,
Instance<EksService> eksService,
Instance<KmsService> kmsService,
Instance<StoredResourceArns> storedResourceArns,
CurrentVertxRequest currentVertxRequest) {
this.objectMapper = objectMapper;
this.iamService = iamService;
this.eksService = eksService;
this.kmsService = kmsService;
this.storedResourceArns = storedResourceArns;
this.currentVertxRequest = currentVertxRequest;
}
public ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService,
Instance<EksService> eksService,
Instance<KmsService> kmsService,
Instance<StoredResourceArns> storedResourceArns) {
this(objectMapper, iamService, eksService, kmsService, storedResourceArns, null);
this(objectMapper, iamService, kmsService, storedResourceArns, null);
}
public ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService,
Instance<EksService> eksService,
Instance<KmsService> kmsService) {
this(objectMapper, iamService, eksService, kmsService, null);
}
public ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService,
Instance<EksService> eksService) {
this(objectMapper, iamService, eksService, null);
this(objectMapper, iamService, kmsService, null);
}
ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService) {
@@ -144,7 +129,7 @@ public class ResourceArnBuilder {
}
ResourceArnBuilder(ObjectMapper objectMapper, CurrentVertxRequest currentVertxRequest) {
this(objectMapper, null, null, null, null, currentVertxRequest);
this(objectMapper, null, null, null, currentVertxRequest);
}
public String build(String credentialScope, ContainerRequestContext ctx,
@@ -188,7 +173,6 @@ public class ResourceArnBuilder {
case "dynamodb" -> buildDynamoDbArns(ctx, region, accountId);
case "iam" -> buildIamArns(ctx, region, accountId);
case "resource-groups" -> List.of(buildResourceGroupArn(ctx, region, accountId));
case "eks" -> List.of(buildEksArn(path, ctx, region, accountId));
case "apigateway" -> List.of(buildApiGatewayArn(ctx, region, partition));
case "bedrock" -> List.of(buildBedrockArn(path, ctx));
default -> namedResources(credentialScope, operation, ctx, region, accountId, partition);
@@ -975,124 +959,6 @@ public class ResourceArnBuilder {
return new AwsArnUtils.Arn(partition, "apigateway", region, "", resource.toString()).toString();
}
/**
* The resource of an EKS route, as the Service Reference gives it, in the caller's account, where EKS
* looks everything up. A cluster is the ARN EKS holds it under, or for one it holds none of, the ARN a
* create mints in the request's Region; {@code CreateCluster} is checked against the cluster its body
* names, as the EKS user guide's example policy for creating a cluster grants it. A node group, Fargate
* profile, add-on, access entry or Pod Identity association is the ARN EKS holds it under in the request's
* Region (clusters are Regional), which ends in an id the request does not carry, or {@code *} when EKS
* holds none to act on; listing or creating
* them, and every other route under a cluster, act on the cluster. The path is split as the router
* splits it, before decoding, so an encoded {@code /} stays inside a name, and an access entry's
* principal is the rest of the path, as EKS takes it. {@code DescribeUpdate} acts on the add-on its
* {@code addonName} names, since the updates EKS keeps are its add-ons', and otherwise on the cluster. A
* tagging route acts on the caller's cluster named by what follows the ARN's last {@code /}, as EKS tags
* it, whatever the ARN names before that. Deregistering a cluster acts on that cluster, and an EKS
* Anywhere subscription route on the subscription its id names. Listing clusters, registering one, the
* account-wide reads, and an identity provider config or capability, which end in an id Floci does not
* keep, name no resource, so they are {@code *}.
*/
private String buildEksArn(String path, ContainerRequestContext ctx, String region, String accountId) {
if (path.equals("/tags") || path.startsWith("/tags/")) {
String tagged = taggedArn(ctx);
int slash = tagged == null ? -1 : tagged.lastIndexOf('/');
return slash < 0 || slash == tagged.length() - 1 ? "*"
: eksClusterArn(tagged.substring(slash + 1), region, accountId);
}
String[] segments = IamActionRegistry.routedPath(ctx).substring(1).split("/", -1);
if (segments.length == 1) {
JsonNode body = "clusters".equals(segments[0]) && "POST".equalsIgnoreCase(ctx.getMethod())
? readJsonBody(ctx) : null;
String cluster = body == null ? null : body.path("name").asText(null);
return cluster == null || cluster.isBlank() ? "*" : eksClusterArn(cluster, region, accountId);
}
String name = pathSegment(segments[1]);
if (name.isEmpty()) {
return "*";
}
return switch (segments[0]) {
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();
default -> "*";
};
}
/** 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);
}
String collection = segments[2];
return switch (collection) {
case "node-groups", "fargate-profiles", "addons", "pod-identity-associations" ->
eksHeldArn(cluster, collection, pathSegment(segments[3]), region);
case "access-entries" -> eksHeldArn(cluster, collection,
pathSegment(String.join("/", List.of(segments).subList(3, accessEntryEnd(segments, method)))),
region);
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.
Optional<String> addon = segments.length == 4
? eksHeld(cluster, collection, pathSegment(segments[3]), region)
: Optional.empty();
yield addon.orElseGet(() -> eksClusterArn(cluster, region, accountId));
}
case "identity-provider-configs" ->
"associate".equals(segments[3]) ? eksClusterArn(cluster, region, accountId) : "*";
case "capabilities" -> "*";
default -> eksClusterArn(cluster, region, accountId);
};
}
/**
* 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) {
return eksHeld(name, null, null, region)
.orElseGet(() -> AwsArnUtils.Arn.of("eks", region, accountId, "cluster/" + name).toString());
}
/** The ARN EKS holds {@code name} of {@code collection} in the cluster under, or {@code *} when it holds none. */
private String eksHeldArn(String cluster, String collection, String name, String region) {
return eksHeld(cluster, collection, name, region).orElse("*");
}
/**
* The ARN EKS holds the resource under, when the cluster is in {@code region}. EKS clusters are Regional, so a
* request signed for another Region does not reach them, and is checked as acting on a resource of its own Region.
*/
private Optional<String> eksHeld(String cluster, String collection, String name, String region) {
if (eksService == null) {
return Optional.empty();
}
return eksService.get().findResourceArn(cluster, collection, name)
.filter(arn -> region.equals(AwsArnUtils.regionOrDefault(arn, null)));
}
/**
* The ARN a shared tagging route acts on, read where its controller reads it: after {@code /tags/} or
* {@code /v1/tags/} in the path; on {@code POST /tags}, the body's {@code resourceArn}; and on the other