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

@@ -559,7 +559,8 @@ class RequestResourceMembersTest {
/**
* Each resource a create whose action acts on no type, or on other types alone, makes, from a request naming it,
* is where its tags go, and a create acting on no type names nothing itself.
* is where its tags go, and a create acting on no type names nothing itself, unless {@code MEASURED} gives it the
* resource AWS checks (EKS's {@code CreateCluster}).
*/
@TestFactory
Stream<DynamicTest> everyResourceACreateMakesIsWhereItsTagsGo() {
@@ -582,7 +583,8 @@ class RequestResourceMembersTest {
"000000000000");
assertEquals(List.of(expected), RequestResources.created(operation.getKey(), null, json(body.toString()),
"aws", "us-east-1", "000000000000", labels), body + " " + labels);
if (table.types().getOrDefault(operation.getKey(), List.of()).isEmpty()) {
if (table.types().getOrDefault(operation.getKey(), List.of()).isEmpty()
&& table.operations().getOrDefault(operation.getKey(), List.of()).isEmpty()) {
assertEquals(List.of(), RequestResources.of(operation.getKey(), json(body.toString()), "aws",
"us-east-1", "000000000000", null, labels));
}
@@ -676,6 +678,10 @@ class RequestResourceMembersTest {
* {@code ""}).
*/
private static boolean sharesAMember(Resource resource, Map<Member, String> given) {
// A resource its service finds by several members is found only from a request giving every one of them.
if (!resource.find().isEmpty() && !given.keySet().containsAll(resource.find())) {
return false;
}
if (resource.arn() != null || Stream.concat(resource.fill().values().stream(), resource.find().stream())
.noneMatch(member -> given.containsKey(member) && (!resource.arnOf().containsKey(member.path())
|| !AwsArnUtils.isArn(given.get(member))))) {
@@ -8,6 +8,8 @@ import org.junit.jupiter.api.Test;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
@@ -148,8 +150,8 @@ class CloudFormationEksIntegrationTest {
List<String> names = given().get(base).jsonPath().getList("nodegroups");
assertEquals(1, names.size());
String arn = given().get(base + "/" + names.getFirst()).jsonPath().getString("nodegroup.nodegroupArn");
given().contentType("application/json").body(Map.of("tags", Map.of("ext", "1")))
.post("/tags/" + arn).then().statusCode(200);
given().urlEncodingEnabled(false).contentType("application/json").body(Map.of("tags", Map.of("ext", "1")))
.post("/tags/" + URLEncoder.encode(arn, StandardCharsets.UTF_8)).then().statusCode(200);
createUpdateChangeSet(client, stack, "tags", nodegroup("two", ""));
executeAndAwaitUpdate(client, stack, "tags");
@@ -4,6 +4,8 @@ import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
@@ -58,12 +60,12 @@ class EksResourceTaggingIntegrationTest {
for (Map.Entry<String, String> resource : arns.entrySet()) {
String arn = resource.getValue();
eks().contentType("application/json").body(Map.of("tags", Map.of("team", resource.getKey(), "env", "dev")))
.post("/tags/" + arn).then().statusCode(200);
eks().get("/tags/" + arn).then().statusCode(200)
.post(tagsPath(arn)).then().statusCode(200);
eks().get(tagsPath(arn)).then().statusCode(200)
.body("tags.team", equalTo(resource.getKey()))
.body("tags.env", equalTo("dev"));
eks().queryParam("tagKeys", "env").delete("/tags/" + arn).then().statusCode(200);
eks().get("/tags/" + arn).then().statusCode(200)
eks().queryParam("tagKeys", "env").delete(tagsPath(arn)).then().statusCode(200);
eks().get(tagsPath(arn)).then().statusCode(200)
.body("tags", not(hasKey("env")))
.body("tags.team", equalTo(resource.getKey()));
}
@@ -75,20 +77,20 @@ class EksResourceTaggingIntegrationTest {
// A child ARN whose id is not the stored resource's, or whose cluster does not exist, names nothing.
String staleNodegroup = arns.get("nodegroup").substring(0, arns.get("nodegroup").lastIndexOf('/') + 1)
+ UUID.randomUUID();
eks().get("/tags/" + staleNodegroup).then().statusCode(404)
eks().get(tagsPath(staleNodegroup)).then().statusCode(404)
.body("__type", equalTo("NotFoundException"));
eks().get("/tags/" + arns.get("addon").replace("/" + name + "/", "/no-such-cluster/")).then()
eks().get(tagsPath(arns.get("addon").replace("/" + name + "/", "/no-such-cluster/"))).then()
.statusCode(404).body("__type", equalTo("NotFoundException"));
eks().get("/tags/arn:aws:eks:us-east-1:" + ACCOUNT + ":identityproviderconfig/" + name + "/oidc/x/y")
eks().get(tagsPath("arn:aws:eks:us-east-1:" + ACCOUNT + ":identityproviderconfig/" + name + "/oidc/x/y"))
.then().statusCode(404).body("__type", equalTo("NotFoundException"));
eks().get("/tags/" + arns.get("cluster")).then().statusCode(200).body("tags", not(anEmptyMap()));
eks().get(tagsPath(arns.get("cluster"))).then().statusCode(200).body("tags", not(anEmptyMap()));
// An ARN that names a resource type but no cluster is a bad request, not a server error.
String noCluster = "arn:aws:eks:us-east-1:" + ACCOUNT + ":cluster/";
eks().get("/tags/" + noCluster).then().statusCode(400).body("__type", equalTo("BadRequestException"));
eks().queryParam("tagKeys", "team").delete("/tags/" + noCluster).then().statusCode(400)
eks().get(tagsPath(noCluster)).then().statusCode(400).body("__type", equalTo("BadRequestException"));
eks().queryParam("tagKeys", "team").delete(tagsPath(noCluster)).then().statusCode(400)
.body("__type", equalTo("BadRequestException"));
eks().get("/tags/" + arns.get("addon").substring(0, arns.get("addon").indexOf(name)) + name + "/")
eks().get(tagsPath(arns.get("addon").substring(0, arns.get("addon").indexOf(name)) + name + "/"))
.then().statusCode(400).body("__type", equalTo("BadRequestException"));
// TagResource keeps every resource within the TagMap limits, counting the tags it already has.
@@ -97,15 +99,15 @@ class EksResourceTaggingIntegrationTest {
fortyNine.put("k" + i, "v");
}
eks().contentType("application/json").body(Map.of("tags", fortyNine))
.post("/tags/" + arns.get("addon")).then().statusCode(200);
.post(tagsPath(arns.get("addon"))).then().statusCode(200);
eks().contentType("application/json").body(Map.of("tags", Map.of("one-too-many", "v")))
.post("/tags/" + arns.get("addon")).then().statusCode(400)
.post(tagsPath(arns.get("addon"))).then().statusCode(400)
.body("__type", equalTo("BadRequestException"));
eks().get("/tags/" + arns.get("addon")).then().statusCode(200)
eks().get(tagsPath(arns.get("addon"))).then().statusCode(200)
.body("tags", not(hasKey("one-too-many")))
.body("tags.team", equalTo("addon"));
eks().contentType("application/json").body(Map.of("tags", Map.of("k", "v".repeat(257))))
.post("/tags/" + arns.get("access-entry")).then().statusCode(400)
.post(tagsPath(arns.get("access-entry"))).then().statusCode(400)
.body("__type", equalTo("BadRequestException"));
} finally {
eks().delete("/clusters/" + name + "/addons/vpc-cni");
@@ -117,8 +119,14 @@ class EksResourceTaggingIntegrationTest {
}
}
/** Sends paths as given, so a tags path keeps the one encoding {@link #tagsPath} gives it. */
private static RequestSpecification eks() {
return given().header("Authorization", auth("eks"));
return given().urlEncodingEnabled(false).header("Authorization", auth("eks"));
}
/** The modeled {@code /tags/{resourceArn}} for an ARN, encoded as one path segment as an SDK sends it. */
private static String tagsPath(String arn) {
return "/tags/" + URLEncoder.encode(arn, StandardCharsets.UTF_8);
}
private static void createRole(String role) {
@@ -0,0 +1,44 @@
package io.floci.aws.services.eks;
import io.floci.aws.core.common.RegionResolver;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class EksStoredResourceArnsTest {
private static final String ACCOUNT = "123456789012";
/** A resource's tags are read from EKS by its whole ARN, in the request's account. */
@Test
void aWholeArnReadsTheTagsEksHolds() {
EksService eks = mock(EksService.class);
String entry = "arn:aws:eks:us-east-1:" + ACCOUNT + ":access-entry/prod/role/" + ACCOUNT + "/admin/1a2b";
when(eks.tagsInAccount(ACCOUNT, entry)).thenReturn(Map.of("team", "data"));
EksStoredResourceArns stored = new EksStoredResourceArns(eks, new RegionResolver("us-east-1", ACCOUNT));
assertEquals(Map.of("team", "data"), stored.storedTags(entry));
}
/**
* An access entry or Pod Identity association a request names by no id is checked with that part open, which names
* no resource EKS holds, so EKS is not asked: finding an access entry by its ARN walks its cluster's entries.
*/
@Test
void anArnWithAPartLeftOpenIsNotLookedUp() {
EksService eks = mock(EksService.class);
EksStoredResourceArns stored = new EksStoredResourceArns(eks, new RegionResolver("us-east-1", ACCOUNT));
assertEquals(Map.of(), stored.storedTags("arn:aws:eks:us-east-1:" + ACCOUNT + ":access-entry/prod/*"));
assertEquals(Map.of(), stored.storedTags("arn:aws:eks:us-east-1:" + ACCOUNT
+ ":podidentityassociation/prod/*"));
verify(eks, never()).tagsInAccount(anyString(), anyString());
}
}
@@ -315,17 +315,33 @@ class IamRestRouteEnforcementIntegrationTest {
as(user, "eks").get(path).then().statusCode(200).body("nodegroup.nodegroupArn", equalTo(nodegroup));
}
/** A resource-tag condition reads the tags EKS holds on the cluster a request names. */
@Test
void anEksResourceTagConditionReadsTheTagsOfTheCluster() {
String tagged = "route-eks-data-" + suffix();
String other = "route-eks-web-" + suffix();
eksCluster(tagged, "{\"team\":\"data\"}");
eksCluster(other, "{\"team\":\"web\"}");
String user = user("route-eks-tags");
policy(user, onTeam("Allow", "eks:DescribeCluster", "data"));
request(user, "eks", "GET", "/clusters/" + tagged, null).statusCode(200);
refused(request(user, "eks", "GET", "/clusters/" + other, null), "eks:DescribeCluster");
}
@Test
void deletedEksAddonRemainsAuthorizedForItsScopedDescribeWaiter() {
String name = "addon-waiter-" + suffix();
eksCluster(name);
String cluster = eksCluster(name);
String base = "/clusters/" + name + "/addons";
String arn = eks().body("{\"addonName\":\"vpc-cni\"}").post(base).then().statusCode(200)
.extract().path("addon.addonArn");
String user = "addon-waiter-user-" + suffix();
EnforcementFixtures.UserCredentials credentials = EnforcementFixtures.createUser(
cleanup, baseUri.getPort(), auth(ADMIN, "iam"), user);
policy(user, allow("eks:DescribeAddon", arn) + "," + allow("eks:DeleteAddon", arn));
// The Service Reference lists the cluster's Pod Identity associations for DeleteAddon, beside the add-on.
policy(user, allow("eks:DescribeAddon", arn) + "," + allow("eks:DeleteAddon", arn) + ","
+ allow("eks:DeleteAddon", cluster.replace(":cluster/", ":podidentityassociation/") + "/*"));
try (EksClient client = AwsTestClients.create(EksClient.builder(), credentials.accessKeyId(),
credentials.secretAccessKey(), Region.US_EAST_1, baseUri)) {
assertEquals(arn, client.describeAddon(r -> r.clusterName(name).addonName("vpc-cni")).addon().addonArn());
@@ -370,13 +386,15 @@ class IamRestRouteEnforcementIntegrationTest {
}
@Test
void eachResourceAnEksClusterHoldsIsCheckedAgainstTheArnEksHoldsItUnder() {
// Each is looked up as EKS looks it up, so a Deny on its own ARN applies where the action is allowed
// on every resource, and a grant on that ARN alone covers it.
void eachResourceAnEksClusterHoldsIsCheckedAsTheGeneratedTableReadsIt() {
// A Fargate profile and an add-on, whose ARNs end in an id EKS minted, are found as EKS finds them, so a Deny
// on their own ARN applies where the action is allowed on every resource, and a grant on that ARN alone
// covers them. An update is checked on its cluster, and an access entry or a Pod Identity association with the
// parts of its ARN the request does not give open, so a policy names those with a wildcard.
String user = user("route-eks-held");
String name = "route-held-" + suffix();
String base = "/clusters/" + name;
eksCluster(name);
String cluster = eksCluster(name);
String role = EnforcementFixtures.createRole(cleanup, baseUri.getPort(), ACCOUNT, "/", "route-held-" + suffix(),
"{\"Version\":\"2012-10-17\",\"Statement\":[" + allow("s3:*", "*") + "]}");
String profile = eks().body("{\"fargateProfileName\":\"fp\",\"podExecutionRoleArn\":\"" + role + "\"}")
@@ -387,20 +405,19 @@ class IamRestRouteEnforcementIntegrationTest {
.extract().path("addon.addonArn");
String update = eks().body("{}").post(base + "/addons/vpc-cni/update").then().statusCode(200)
.extract().path("update.id");
String entry = eks().body("{\"principalArn\":\"" + role + "\"}").post(base + "/access-entries").then()
.statusCode(200).extract().path("accessEntry.accessEntryArn");
eks().body("{\"principalArn\":\"" + role + "\"}").post(base + "/access-entries").then().statusCode(200);
String association = eks().body("{\"namespace\":\"default\",\"serviceAccount\":\"app\",\"roleArn\":\"" + role
+ "\"}").post(base + "/pod-identity-associations").then().statusCode(200)
.extract().path("association.associationArn");
String[][] routes = {
{"eks:DescribeFargateProfile", base + "/fargate-profiles/fp", profile},
{"eks:DescribeAddon", base + "/addons/vpc-cni", addon},
// EKS returns an add-on's update without its addonName, so the update is its add-on's.
{"eks:DescribeUpdate", base + "/updates/" + update, addon},
{"eks:DescribeAccessEntry", base + "/access-entries/" + encoded(role), entry},
{"eks:DescribeUpdate", base + "/updates/" + update, cluster},
{"eks:DescribeAccessEntry", base + "/access-entries/" + encoded(role),
cluster.replace(":cluster/", ":access-entry/") + "/*"},
{"eks:DescribePodIdentityAssociation",
base + "/pod-identity-associations/" + association.substring(association.lastIndexOf('/') + 1),
association},
cluster.replace(":cluster/", ":podidentityassociation/") + "/*"},
};
for (String[] route : routes) {
policy(user, allow(route[0], "*") + "," + deny(route[0], route[2]));
@@ -432,8 +449,9 @@ class IamRestRouteEnforcementIntegrationTest {
@Test
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.
// Associating, listing and disassociating an entry's access policies act on the cluster's entries, the parts
// of an entry's ARN the request does not give open, so a grant on another cluster's entries does not cover
// them, and one on this cluster's does.
String user = user("route-eks-entry");
String name = "route-entry-" + suffix();
String base = "/clusters/" + name + "/access-entries";
@@ -445,8 +463,9 @@ class IamRestRouteEnforcementIntegrationTest {
"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");
eks().body("{\"principalArn\":\"" + otherRole + "\"}").post(base).then().statusCode(200);
String entries = entry.substring(0, entry.indexOf(":access-entry/")) + ":access-entry/" + name + "/*";
String other = entries.replace("/" + name + "/", "/" + name + "-other/");
String policies = base + "/" + encoded(role) + "/access-policies";
String admin = "arn:aws:eks::aws:cluster-access-policy/AmazonEKSClusterAdminPolicy";
String associate = "{\"policyArn\":\"" + admin + "\",\"accessScope\":{\"type\":\"cluster\"}}";
@@ -460,7 +479,7 @@ class IamRestRouteEnforcementIntegrationTest {
refused(as(user, "eks").urlEncodingEnabled(false).delete(policies + "/" + encoded(admin)).then(),
"eks:DisassociateAccessPolicy");
policy(user, "{\"Effect\":\"Allow\",\"Action\":" + actions + ",\"Resource\":\"" + entry + "\"}");
policy(user, "{\"Effect\":\"Allow\",\"Action\":" + actions + ",\"Resource\":\"" + entries + "\"}");
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));
@@ -472,19 +491,24 @@ class IamRestRouteEnforcementIntegrationTest {
}
@Test
void eksTaggingIsCheckedAgainstTheCallersClusterOfThatName() {
// EKS tags the caller's own cluster named after the ARN's last /, whatever account the ARN names, so a
// grant on another account's cluster of that name does not cover it, and one on the caller's own does.
void eksTaggingIsCheckedOnTheArnItCarriesAndTagsOnlyThatResource() {
// A tagging request is checked on the ARN its modeled route carries, and on the caller's resource of that name
// when the ARN names another account; EKS tags only the resource whose ARN is the whole ARN, so another
// account's ARN tags nothing.
String user = user("route-eks-tags");
String cluster = eksCluster("route-tagged-" + suffix());
String foreign = cluster.replace(ACCOUNT, "111122223333");
String body = "{\"tags\":{\"team\":\"a\"}}";
policy(user, allow("eks:TagResource", foreign));
refused(as(user, "eks").body(body).post("/tags/" + foreign).then(), "eks:TagResource");
refused(as(user, "eks").urlEncodingEnabled(false).body(body).post("/tags/" + encoded(foreign)).then(),
"eks:TagResource");
policy(user, allow("eks:TagResource", foreign) + "," + allow("eks:TagResource", cluster));
as(user, "eks").urlEncodingEnabled(false).body(body).post("/tags/" + encoded(foreign)).then().statusCode(404);
policy(user, allow("eks:TagResource", cluster));
as(user, "eks").body(body).post("/tags/" + foreign).then().statusCode(not(403));
eks().get("/tags/" + cluster).then().statusCode(200).body("tags.team", equalTo("a"));
as(user, "eks").urlEncodingEnabled(false).body(body).post("/tags/" + encoded(cluster)).then().statusCode(200);
eks().urlEncodingEnabled(false).get("/tags/" + encoded(cluster)).then().statusCode(200)
.body("tags.team", equalTo("a"));
}
@Test
@@ -525,8 +549,13 @@ class IamRestRouteEnforcementIntegrationTest {
/** Creates an EKS cluster as the account's admin, removed afterwards, and returns its ARN. */
private String eksCluster(String name) {
return eksCluster(name, "{}");
}
/** A cluster an administrator creates with {@code tags}, a JSON map, removed afterwards; its ARN. */
private String eksCluster(String name, String tags) {
String arn = eks().body("{\"name\":\"" + name + "\",\"roleArn\":\"arn:aws:iam::" + ACCOUNT
+ ":role/route-cluster\",\"accessConfig\":{\"authenticationMode\":\"API\"}}")
+ ":role/route-cluster\",\"accessConfig\":{\"authenticationMode\":\"API\"},\"tags\":" + tags + "}")
.post("/clusters").then().statusCode(200).extract().path("cluster.arn");
cleanup.register(() -> eks().delete("/clusters/" + name));
return arn;
@@ -15,6 +15,7 @@ import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsDeliveryService;
import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsStoredResourceArns;
import io.floci.aws.services.cloudwatch.logs.model.Delivery;
import io.floci.aws.services.eks.EksService;
import io.floci.aws.services.eks.EksStoredResourceArns;
import io.floci.aws.services.iam.model.AccessKey;
import io.floci.aws.services.iam.model.IamGroup;
import io.floci.aws.services.iam.model.IamRole;
@@ -188,14 +189,6 @@ class ResourceArnBuilderTest {
return new ResourceArnBuilder(new ObjectMapper(), instance);
}
/** A builder reading {@code eks}, for an EKS route naming a cluster or what it holds. */
private static ResourceArnBuilder backedBy(EksService eks) {
@SuppressWarnings("unchecked")
Instance<EksService> instance = mock(Instance.class);
when(instance.get()).thenReturn(eks);
return new ResourceArnBuilder(new ObjectMapper(), null, instance);
}
private static IamService storeHolding(String userName, String path, String arn) {
IamUser user = new IamUser();
user.setUserName(userName);
@@ -1459,7 +1452,7 @@ class ResourceArnBuilderTest {
@SuppressWarnings("unchecked")
Instance<KmsService> instance = mock(Instance.class);
when(instance.get()).thenReturn(kms);
return new ResourceArnBuilder(new ObjectMapper(), null, null, instance);
return new ResourceArnBuilder(new ObjectMapper(), null, instance);
}
/** A builder reading the stored ARNs of a namespace, for every request of that namespace. */
@@ -1467,7 +1460,7 @@ class ResourceArnBuilderTest {
@SuppressWarnings("unchecked")
Instance<StoredResourceArns> instance = mock(Instance.class);
when(instance.iterator()).thenAnswer(invocation -> List.of(stored).iterator());
return new ResourceArnBuilder(new ObjectMapper(), null, null, null, instance);
return new ResourceArnBuilder(new ObjectMapper(), null, null, instance);
}
/** The finder of the stored ARNs of a namespace, answering one name of one type with one ARN. */
@@ -2683,138 +2676,70 @@ class ResourceArnBuilderTest {
// ── EKS ──────────────────────────────────────────────────────────────────────
/** The cluster {@code held}, which EKS keeps in the request's Region (us-east-1), and what it holds. */
private static final String HELD_CLUSTER = "arn:aws:eks:us-east-1: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";
/** The node group and add-on EKS holds in the cluster {@code held}, in the request's Region (us-east-1). */
private static final String HELD_NODEGROUP = "arn:aws:eks:us-east-1:000000000000:nodegroup/held/ng/1";
private static final String HELD_ADDON = "arn:aws:eks:us-east-1:000000000000:addon/held/vpc-cni/4";
/** A builder reading what EKS holds through its lookup, which the table asks to find what ends in an id. */
private static ResourceArnBuilder eksHolding() {
EksService eks = mock(EksService.class);
when(eks.findResourceArn(any(), any(), any())).thenReturn(Optional.empty());
when(eks.findResourceArn("held", null, null)).thenReturn(Optional.of(HELD_CLUSTER));
for (String[] held : new String[][] {
{"node-groups", "ng", "nodegroup/held/ng/1"}, {"node-groups", "a/b", "nodegroup/held/a/b/2"},
{"fargate-profiles", "fp", "fargateprofile/held/fp/3"}, {"addons", "vpc-cni", "addon/held/vpc-cni/4"},
{"updates", "u-1", "addon/held/vpc-cni/4"},
{"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-east-1:000000000000:" + held[2]));
}
return backedBy(eks);
}
private String eksResource(ResourceArnBuilder eks, String method, String sent) {
when(ctx.getMethod()).thenReturn(method);
request(sent);
return eks.build("eks", ctx, "us-east-1", ACCOUNT);
}
@Test
void anEksClusterRouteActsOnTheClusterEksHoldsOrTheOneACreateMints() {
ResourceArnBuilder eks = eksHolding();
String minted = "arn:aws:eks:us-east-1:000000000000:cluster/";
assertEquals(HELD_CLUSTER, eksResource(eks, "GET", "/clusters/held"));
assertEquals(minted + "gone", eksResource(eks, "DELETE", "/clusters/gone"));
for (String route : List.of("/node-groups", "/addons", "/access-entries", "/pod-identity-associations",
"/update-config", "/updates", "/updates/u-1/cancel-update", "/insights/i-1",
"/certificate-authorities/ca-1/activate", "/identity-provider-configs/associate")) {
assertEquals(HELD_CLUSTER, eksResource(eks, "POST", "/clusters/held" + route), route);
}
assertEquals(HELD_CLUSTER, eksResource(eks, "DELETE", "/cluster-registrations/held"));
// A create is checked against the cluster its body names; listing clusters names none.
setJsonBody("{\"name\":\"fresh\",\"roleArn\":\"arn:aws:iam::000000000000:role/r\"}");
assertEquals(minted + "fresh", eksResource(eks, "POST", "/clusters"));
assertEquals("*", eksResource(eks, "GET", "/clusters"));
}
@Test
void anEksRouteOnWhatAClusterHoldsActsOnTheArnEksHoldsItUnder() {
ResourceArnBuilder eks = eksHolding();
String held = "arn:aws:eks:us-east-1:000000000000:";
assertEquals(held + "nodegroup/held/ng/1", eksResource(eks, "GET", "/clusters/held/node-groups/ng"));
assertEquals(held + "nodegroup/held/ng/1",
eksResource(eks, "POST", "/clusters/held/node-groups/ng/update-version"));
// The router keeps an encoded / inside the name, and EKS looks the node group up by it.
assertEquals(held + "nodegroup/held/a/b/2", eksResource(eks, "GET", "/clusters/held/node-groups/a%2Fb"));
assertEquals(held + "fargateprofile/held/fp/3", eksResource(eks, "DELETE", "/clusters/held/fargate-profiles/fp"));
assertEquals(held + "addon/held/vpc-cni/4", eksResource(eks, "POST", "/clusters/held/addons/vpc-cni/update"));
assertEquals(held + "podidentityassociation/held/a-1",
eksResource(eks, "POST", "/clusters/held/pod-identity-associations/a-1"));
// An access entry's principal is the rest of the path, encoded or not.
assertEquals(held + "access-entry/held/role/000000000000/worker/5", eksResource(eks, "GET",
"/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));
// 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"));
assertEquals("*", eksResource(eks, "POST", "/clusters/held/identity-provider-configs/describe"));
assertEquals("*", eksResource(eks, "GET", "/clusters/held/capabilities/argocd"));
}
@Test
void anEksUpdateActsOnItsAddonAndATagOnTheCallersClusterOfThatName() {
ResourceArnBuilder eks = eksHolding();
// EKS returns an add-on's update whatever add-on the request names, if any, so it acts on its own add-on.
String addon = "arn:aws:eks:us-east-1:000000000000:addon/held/vpc-cni/4";
assertEquals(addon, eksResource(eks, "GET", "/clusters/held/updates/u-1"));
queryParams.putSingle("addonName", "coredns");
assertEquals(addon, eksResource(eks, "GET", "/clusters/held/updates/u-1"));
queryParams.clear();
assertEquals(HELD_CLUSTER, eksResource(eks, "GET", "/clusters/held/updates/u-2"));
assertEquals(HELD_CLUSTER, eksResource(eks, "POST", "/clusters/held/updates/u-1/cancel-update"));
// EKS tags the caller's cluster named after the ARN's last /, whatever account or Region it names.
assertEquals(HELD_CLUSTER, eksResource(eks, "POST", "/tags/arn:aws:eks:eu-west-1:111122223333:cluster/held"));
queryParams.putSingle("resourceArn", "arn:aws:eks:eu-west-1:111122223333:cluster/held");
assertEquals(HELD_CLUSTER, eksResource(eks, "DELETE", "/tags"));
queryParams.clear();
assertEquals("*", eksResource(eks, "GET", "/tags/no-slash"));
assertEquals("arn:aws:eks:us-east-1:000000000000:eks-anywhere-subscription/sub-1",
eksResource(eks, "GET", "/eks-anywhere-subscriptions/sub-1"));
for (String route : List.of("/addons/supported-versions", "/access-policies", "/cluster-versions",
"/cluster-registrations", "/eks-anywhere-subscriptions")) {
assertEquals("*", eksResource(eks, "GET", route), route);
}
}
@Test
void anEksRouteOnAClusterHeldInAnotherRegionActsOnTheRequestsRegion() {
// EKS clusters are Regional: a request signed for us-east-1 does not reach a cluster EKS keeps in us-west-2,
// so it acts on the cluster of that name a create would mint in us-east-1, and on nothing the other holds.
EksService eks = mock(EksService.class);
when(eks.findResourceArn(any(), any(), any())).thenReturn(Optional.empty());
when(eks.findResourceArn("west", null, null))
.thenReturn(Optional.of("arn:aws:eks:us-west-2:000000000000:cluster/west"));
when(eks.findResourceArn("held", "node-groups", "ng")).thenReturn(Optional.of(HELD_NODEGROUP));
when(eks.findResourceArn("held", "addons", "vpc-cni")).thenReturn(Optional.of(HELD_ADDON));
when(eks.findResourceArn("west", "node-groups", "ng"))
.thenReturn(Optional.of("arn:aws:eks:us-west-2:000000000000:nodegroup/west/ng/1"));
ResourceArnBuilder builder = backedBy(eks);
return reading(new EksStoredResourceArns(eks, new RegionResolver("us-east-1", ACCOUNT)));
}
assertEquals("arn:aws:eks:us-east-1:000000000000:cluster/west", eksResource(builder, "GET", "/clusters/west"));
assertEquals("*", eksResource(builder, "GET", "/clusters/west/node-groups/ng"));
private List<String> eks(ResourceArnBuilder eks, String method, String sent, String operation) {
when(ctx.getMethod()).thenReturn(method);
request(sent);
return eks.buildResources("eks", operation, ctx, "us-east-1", ACCOUNT, "aws");
}
/** A cluster route is checked on the cluster its path names, from the table. */
@Test
void anEksClusterRouteIsCheckedOnTheClusterItsPathNames() {
ResourceArnBuilder eks = eksHolding();
assertEquals(List.of("arn:aws:eks:us-east-1:000000000000:cluster/held"),
eks(eks, "GET", "/clusters/held", "eks:DescribeCluster"));
assertEquals(List.of("arn:aws:eks:us-east-1:000000000000:cluster/held"),
eks(eks, "GET", "/clusters/held/node-groups", "eks:ListNodegroups"));
assertEquals(List.of("*"), eks(eks, "GET", "/clusters", "eks:ListClusters"));
}
/** CreateCluster is checked on the cluster its body names, as the EKS user guide's example policy grants it. */
@Test
void anEksCreateClusterIsCheckedOnTheClusterItsBodyNames() {
setJsonBody("{\"name\":\"new\",\"roleArn\":\"arn:aws:iam::000000000000:role/eks\"}");
assertEquals(List.of("arn:aws:eks:us-east-1:000000000000:cluster/new"),
eks(eksHolding(), "POST", "/clusters", "eks:CreateCluster"));
}
/**
* A node group or an add-on, whose ARN ends in an id EKS minted, is checked on the one EKS holds under the names
* its path gives, found in the request's Region; one EKS holds none of, or holds in another Region, has its ARN's
* names open.
*/
@Test
void anEksNodegroupOrAddonIsCheckedOnTheOneEksHolds() {
ResourceArnBuilder eks = eksHolding();
assertEquals(List.of(HELD_NODEGROUP),
eks(eks, "GET", "/clusters/held/node-groups/ng", "eks:DescribeNodegroup"));
assertEquals(List.of(HELD_ADDON), eks(eks, "GET", "/clusters/held/addons/vpc-cni", "eks:DescribeAddon"));
List<String> missing = eks(eks, "GET", "/clusters/held/node-groups/gone", "eks:DescribeNodegroup");
assertEquals(1, missing.size());
assertTrue(missing.getFirst().startsWith("arn:aws:eks:us-east-1:000000000000:nodegroup/"), missing.toString());
assertTrue(missing.getFirst().endsWith("*"), missing.toString());
assertEquals(missing, eks(eks, "GET", "/clusters/west/node-groups/ng", "eks:DescribeNodegroup"));
}
/** A tagging route is checked on the ARN its modeled path carries. */
@Test
void anEksTaggingRouteIsCheckedOnTheArnItCarries() {
String cluster = "arn:aws:eks:us-east-1:000000000000:cluster/held";
String encoded = cluster.replace(":", "%3A").replace("/", "%2F");
assertEquals(List.of(cluster), eks(eksHolding(), "GET", "/tags/" + encoded, "eks:ListTagsForResource"));
}
/** Stubs the request path as sent and, decoded, as {@link UriInfo#getPath()} gives it. */