fix(iam): check EKS's REST routes and roles, and routes with a trailing slash (#6323)

Under IAM enforcement a REST request whose route no rule maps is let through unchecked. No EKS
route had a rule, so any signed caller could create, read, change or delete clusters, node groups,
Fargate profiles, add-ons, access entries and Pod Identity associations with no EKS permission, and
without iam:PassRole on the roles they named. A Pod Identity association hands its service
account's pods the credentials of its role, so a caller could have pods run as any role in the
account.

Every operation of the eks model now has a rule and is checked as the action of its own name, as
the Service Authorization Reference gives it, including the routes Floci does not serve yet, and
IamRestRouteCoverageTest checks the whole model. Floci takes an access entry's principal as the
rest of the path, so a GET or DELETE under an entry reads or deletes an entry: the entry's access
policy routes, which Floci does not serve, run as DescribeAccessEntry and DeleteAccessEntry and are
checked as those.

Each is checked against the resource the reference gives it, in the caller's account, where EKS
looks everything up:
- a cluster against the ARN EKS holds it under, or cluster/<name> in the request's Region for one
  it holds none of, and CreateCluster 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 against the ARN
  EKS holds it under, which ends in an id the request does not carry, read through
  EksService.findResourceArn with the lookups its handlers make; listing and creating them, and the
  other routes under a cluster, against the cluster;
- DescribeUpdate against the add-on the update was made to, since the updates Floci keeps are its
  add-ons' and EKS returns one whether or not the request names its add-on, and otherwise the
  cluster;
- a tagging request against the caller's cluster named after the ARN's last /, as EKS tags it.

The roles each operation passes need iam:PassRole, with iam:PassedToService the value the Service
Reference gives: the cluster role, node role, Fargate pod execution role and an add-on's service
account and Pod Identity roles go to eks.amazonaws.com, a Pod Identity association's roleArn to
pods.eks.amazonaws.com ("The IAM principal that is creating the association must have
iam:PassRole."), and an EC2_LINUX or EC2_WINDOWS access entry's principal to ec2.amazonaws.com.

The router also matches a path with a trailing slash as the path without it, while the rules
matched the slash: POST /clusters/, GET /schedules/ and GET /2015-03-31/functions/<name>/ reached
their operation unchecked. A route is now matched without its trailing slash, as the router
matches it. An S3 path is matched as sent, as before: an S3 key may end in a slash, as a folder
marker's does, and S3's rules already take a bucket's one trailing slash.

docs/services/iam.md says which EKS routes are mapped, what each is checked against and the roles
they pass.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-23 22:15:46 -05:00
1 parent 16c159e5b2
commit ec5597eb5c
14 files changed
+814 -18

No files matched your search

@@ -205,6 +205,40 @@ class PassedRolesTest {
PassedRoles.of("lambda:UpdateNetworkConnector", json(operator), LOOKUPS));
}
@Test
void eksPassesItsClusterNodePodAndAddonRolesAndANodeAccessEntrysPrincipal() {
String eks = "eks.amazonaws.com";
assertEquals(List.of(passed("cluster", eks)), PassedRoles.of("eks:CreateCluster",
json("{\"name\":\"c\",\"roleArn\":\"" + ROLES + "cluster\"}"), LOOKUPS));
assertEquals(List.of(passed("node", eks)), PassedRoles.of("eks:CreateNodegroup",
json("{\"nodeRole\":\"" + ROLES + "node\"}"), LOOKUPS));
assertEquals(List.of(passed("fargate", eks)), PassedRoles.of("eks:CreateFargateProfile",
json("{\"podExecutionRoleArn\":\"" + ROLES + "fargate\"}"), LOOKUPS));
String addon = """
{"serviceAccountRoleArn":"%1$saddon","podIdentityAssociations":[
{"serviceAccount":"a","roleArn":"%1$spod-a"},{"serviceAccount":"b","roleArn":"%1$spod-b"}]}"""
.formatted(ROLES);
for (String action : List.of("eks:CreateAddon", "eks:UpdateAddon")) {
assertEquals(List.of(passed("addon", eks), passed("pod-a", eks), passed("pod-b", eks)),
PassedRoles.of(action, json(addon), LOOKUPS));
}
// The association's role goes to Pod Identity; its target role is assumed with it, not passed.
String association = "{\"roleArn\":\"" + ROLES + "pod\",\"targetRoleArn\":\"" + ROLES + "target\"}";
for (String action : List.of("eks:CreatePodIdentityAssociation", "eks:UpdatePodIdentityAssociation")) {
assertEquals(List.of(passed("pod", "pods.eks.amazonaws.com")), PassedRoles.of(action, json(association),
LOOKUPS));
}
// Only a node access entry passes its principal, to EC2.
for (String type : List.of("EC2_LINUX", "EC2_WINDOWS")) {
assertEquals(List.of(passed("worker", EC2)), PassedRoles.of("eks:CreateAccessEntry",
json("{\"principalArn\":\"" + ROLES + "worker\",\"type\":\"" + type + "\"}"), LOOKUPS));
}
assertEquals(List.of(), PassedRoles.of("eks:CreateAccessEntry",
json("{\"principalArn\":\"" + ROLES + "admin\",\"type\":\"STANDARD\"}"), LOOKUPS));
assertEquals(List.of(), PassedRoles.of("eks:CreateAccessEntry",
json("{\"principalArn\":\"" + ROLES + "admin\"}"), LOOKUPS));
}
@Test
void outsideEcsOnlyARoleArnIsPassed() {
assertEquals(List.of(), PassedRoles.of("states:CreateStateMachine", json("{\"roleArn\":\"sm\"}"), LOOKUPS));
@@ -363,6 +363,46 @@ class IamActionRegistryTest {
MediaType.APPLICATION_JSON_TYPE, "{}")));
}
@Test
void aTrailingSlashIsCheckedAsTheRouteWithoutIt() {
// The router matches /clusters/ as /clusters, so the rule ending at the route's last segment covers it.
// An S3 path is matched as sent, as before: a key may end in a slash.
String[][] routes = {
{"eks", "POST", "/clusters/", "eks:CreateCluster"},
{"eks", "GET", "/clusters/c/node-groups/ng/", "eks:DescribeNodegroup"},
{"scheduler", "GET", "/schedules/", "scheduler:ListSchedules"},
{"pipes", "GET", "/v1/pipes/p/", "pipes:DescribePipe"},
{"lambda", "GET", "/2015-03-31/functions/fn/", "lambda:GetFunction"},
{"s3", "GET", "/bucket/", "s3:ListBucket"},
{"s3", "GET", "/bucket/folder/", "s3:GetObject"},
{"s3", "PUT", "/bucket//", "s3:PutObject"},
{"s3", "GET", "/bucket//", "s3:GetObject"},
{"s3", "DELETE", "/bucket//", "s3:DeleteObject"},
};
for (String[] route : routes) {
assertEquals(route[3], registry.resolveRoute(route[0], mockCtx(route[1], route[2],
new MultivaluedHashMap<>(), MediaType.APPLICATION_JSON_TYPE, "{}")), route[2]);
}
}
@Test
void anEksAccessEntryRouteTakesThePrincipalAsTheRestOfThePath() {
// EKS reads the principal greedily, so a GET or DELETE under an entry reads or deletes an entry.
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"},
{"POST", entry + "/access-policies", "eks:AssociateAccessPolicy"},
{"POST", entry, "eks:UpdateAccessEntry"},
{"GET", "/clusters/c/access-entries", "eks:ListAccessEntries"},
};
for (String[] route : routes) {
assertEquals(route[2], registry.resolveRoute("eks", mockCtx(route[0], route[1],
new MultivaluedHashMap<>(), MediaType.APPLICATION_JSON_TYPE, "{}")), route[1]);
}
}
@Test
void returnsNullForUnknownRestJsonRoute() {
ContainerRequestContext ctx = mockCtx(
@@ -471,6 +471,83 @@ class IamPassRoleEnforcementIntegrationTest {
user.rest("pipes").body(update).put(path).then().statusCode(200);
}
@Test
void anEksPodIdentityAssociationNeedsPassRoleOnItsRoleForPodIdentity() {
// Pod Identity hands the service account's pods the association role's credentials, so naming a role
// needs iam:PassRole on it, passed to Pod Identity rather than to EKS.
String role = role("eks-pod");
String other = role("eks-pod-other");
User user = user("passrole-eks-pod");
String path = "/clusters/" + eksCluster() + "/pod-identity-associations";
String create = "{\"namespace\":\"default\",\"serviceAccount\":\"app\",\"roleArn\":\"" + role + "\"}";
String pods = "pods.eks.amazonaws.com";
user.policy(allow("eks:CreatePodIdentityAssociation", "*") + "," + passRole(role, "eks.amazonaws.com"));
denied(user.rest("eks").body(create).post(path).then());
user.policy(allow("eks:CreatePodIdentityAssociation", "*") + "," + passRole(role, pods));
String id = user.rest("eks").body(create).post(path).then().statusCode(200)
.extract().path("association.associationId");
String update = "{\"roleArn\":\"" + other + "\"}";
user.policy(allow("eks:UpdatePodIdentityAssociation", "*") + "," + passRole(role, pods));
denied(user.rest("eks").body(update).post(path + "/" + id).then());
user.policy(allow("eks:UpdatePodIdentityAssociation", "*") + "," + passRole(other, pods));
user.rest("eks").body(update).post(path + "/" + id).then().statusCode(200);
}
@Test
void anEksClusterNodeGroupFargateProfileAndNodeAccessEntryNeedPassRoleOnTheirRoles() {
String clusterRole = role("eks-cluster");
String nodeRole = role("eks-node");
String podRole = role("eks-fargate");
User user = user("passrole-eks");
String eks = "eks.amazonaws.com";
String name = "passrole-eks-" + suffix();
String path = "/clusters/" + name;
String cluster = "{\"name\":\"" + name + "\",\"roleArn\":\"" + clusterRole
+ "\",\"accessConfig\":{\"authenticationMode\":\"API\"}}";
user.policy(allow("eks:CreateCluster", "*"));
denied(user.rest("eks").body(cluster).post("/clusters").then());
user.policy(allow("eks:CreateCluster", "*") + "," + passRole(clusterRole, eks));
user.rest("eks").body(cluster).post("/clusters").then().statusCode(200);
cleanup.register(() -> admin("eks").delete(path));
String nodegroup = "{\"nodegroupName\":\"ng\",\"subnets\":[\"subnet-abc\"],\"nodeRole\":\"" + nodeRole + "\"}";
user.policy(allow("eks:CreateNodegroup", "*"));
denied(user.rest("eks").body(nodegroup).post(path + "/node-groups").then());
user.policy(allow("eks:CreateNodegroup", "*") + "," + passRole(nodeRole, eks));
user.rest("eks").body(nodegroup).post(path + "/node-groups").then().statusCode(200);
cleanup.register(() -> admin("eks").delete(path + "/node-groups/ng"));
String profile = "{\"fargateProfileName\":\"fp\",\"podExecutionRoleArn\":\"" + podRole + "\"}";
user.policy(allow("eks:CreateFargateProfile", "*"));
denied(user.rest("eks").body(profile).post(path + "/fargate-profiles").then());
user.policy(allow("eks:CreateFargateProfile", "*") + "," + passRole(podRole, eks));
user.rest("eks").body(profile).post(path + "/fargate-profiles").then().statusCode(200);
cleanup.register(() -> admin("eks").delete(path + "/fargate-profiles/fp"));
// A node access entry passes its role to EC2, whose instances join as it; a standard one passes nothing.
String node = "{\"principalArn\":\"" + nodeRole + "\",\"type\":\"EC2_LINUX\"}";
user.policy(allow("eks:CreateAccessEntry", "*") + "," + passRole(nodeRole, eks));
denied(user.rest("eks").body(node).post(path + "/access-entries").then());
user.policy(allow("eks:CreateAccessEntry", "*") + "," + passRole(nodeRole, "ec2.amazonaws.com"));
user.rest("eks").body(node).post(path + "/access-entries").then().statusCode(200);
user.policy(allow("eks:CreateAccessEntry", "*"));
user.rest("eks").body("{\"principalArn\":\"" + podRole + "\"}").post(path + "/access-entries").then()
.statusCode(200);
}
/** Creates an EKS cluster as the account's admin, removed afterwards, and returns its name. */
private String eksCluster() {
String name = "passrole-cluster-" + suffix();
admin("eks").contentType("application/json")
.body("{\"name\":\"" + name + "\",\"roleArn\":\"arn:aws:iam::" + ACCOUNT + ":role/passrole-cluster\"}")
.post("/clusters").then().statusCode(200);
cleanup.register(() -> admin("eks").delete("/clusters/" + name));
return name;
}
@Test
void aMicrovmImageAndANetworkConnectorNeedPassRoleOnTheRolesTheyName() {
String build = role("microvm-build");
@@ -45,15 +45,18 @@ 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.
* 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.
*/
private static final Map<String, String> RUN_AS_ANOTHER_OPERATION = Map.of(
"GetBucketMetadataConfiguration", "s3:ListBucket",
"DeleteBucketMetadataConfiguration", "s3:DeleteBucket");
"DeleteBucketMetadataConfiguration", "s3:DeleteBucket",
"ListAssociatedAccessPolicies", "eks:DescribeAccessEntry",
"DisassociateAccessPolicy", "eks:DeleteAccessEntry");
/** Models every operation of which is checked: the services whose routes the registry maps in full. */
private static final Set<String> FULLY_ROUTED_MODELS =
Set.of("scheduler", "pipes", "lambda", "lambda-microvms", "lambda-core", "dsql");
Set.of("scheduler", "pipes", "eks", "lambda", "lambda-microvms", "lambda-core", "dsql");
private final IamActionRegistry registry = new IamActionRegistry();
@@ -91,7 +94,8 @@ class IamRestRouteCoverageTest {
Map.Entry<String, JsonNode> operation = operations.next();
Route route = new Route(scope, model, operation.getKey(), operation.getValue().path("method").asText(),
operation.getValue().path("requestUri").asText());
String expected = authorized.path(scope).path(operation.getKey()).asText(scope + ":" + operation.getKey());
String expected = RUN_AS_ANOTHER_OPERATION.getOrDefault(operation.getKey(),
authorized.path(scope).path(operation.getKey()).asText(scope + ":" + operation.getKey()));
tests.add(DynamicTest.dynamicTest(model + " " + operation.getKey(),
() -> assertEquals(expected, resolve(route), route.toString())));
}
@@ -12,12 +12,15 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
/**
@@ -109,15 +112,166 @@ class IamRestRouteEnforcementIntegrationTest {
// tagging rule does not let the request through unchecked.
String user = user("route-tags-scope");
String group = scheduleGroup("route-group-" + suffix());
String cluster = "arn:aws:eks:us-east-1:" + ACCOUNT + ":cluster/route-cluster-" + suffix();
String queue = "arn:aws:batch:us-east-1:" + ACCOUNT + ":job-queue/route-queue-" + suffix();
// Nor is an ARN of a service with no tagging rule checked as the signing scope's action.
as(user, "pipes").body(tagBody(cluster)).post("/tags").then().body(not(containsString("pipes:TagResource")));
as(user, "pipes").body(tagBody(queue)).post("/tags").then().body(not(containsString("pipes:TagResource")));
policy(user, allow("pipes:TagResource", "*"));
refused(as(user, "pipes").body(tagBody(group)).post("/tags").then(), "scheduler:TagResource");
refused(as(user, "sqs").body(tagBody(group)).post("/tags").then(), "scheduler:TagResource");
}
@Test
void eksRoutesAreCheckedAgainstTheClusterAndTheNodeGroupEksHolds() {
// Every EKS route was let through unchecked. A cluster route is checked against the cluster, and a node
// group route against the ARN EKS holds the node group under, which ends in an id the request does not
// carry, so a Deny on that node group applies where the action is allowed on every resource.
String user = user("route-eks");
String name = "route-eks-" + suffix();
String cluster = eksCluster(name);
String nodegroup = eks().body("{\"nodegroupName\":\"ng\",\"subnets\":[\"subnet-abc\"],"
+ "\"nodeRole\":\"arn:aws:iam::" + ACCOUNT + ":role/route-node\"}")
.post("/clusters/" + name + "/node-groups").then().statusCode(200)
.extract().path("nodegroup.nodegroupArn");
cleanup.register(() -> eks().delete("/clusters/" + name + "/node-groups/ng"));
policy(user, allow("eks:DescribeCluster", cluster + "-other"));
refused(as(user, "eks").get("/clusters/" + name).then(), "eks:DescribeCluster");
policy(user, allow("eks:DescribeCluster", cluster));
as(user, "eks").get("/clusters/" + name).then().statusCode(200);
String path = "/clusters/" + name + "/node-groups/ng";
policy(user, allow("eks:DescribeNodegroup", "*") + "," + deny("eks:DescribeNodegroup", nodegroup));
refused(as(user, "eks").get(path).then(), "eks:DescribeNodegroup");
policy(user, allow("eks:DescribeNodegroup", cluster.replace(":cluster/", ":nodegroup/") + "/ng/*"));
as(user, "eks").get(path).then().statusCode(200).body("nodegroup.nodegroupArn", equalTo(nodegroup));
}
@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.
String user = user("route-eks-held");
String name = "route-held-" + suffix();
String base = "/clusters/" + name;
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 + "\"}")
.post(base + "/fargate-profiles").then().statusCode(200)
.extract().path("fargateProfile.fargateProfileArn");
cleanup.register(() -> eks().delete(base + "/fargate-profiles/fp"));
String addon = eks().body("{\"addonName\":\"vpc-cni\"}").post(base + "/addons").then().statusCode(200)
.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");
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:DescribePodIdentityAssociation",
base + "/pod-identity-associations/" + association.substring(association.lastIndexOf('/') + 1),
association},
};
for (String[] route : routes) {
policy(user, allow(route[0], "*") + "," + deny(route[0], route[2]));
refused(as(user, "eks").urlEncodingEnabled(false).get(route[1]).then(), route[0]);
policy(user, allow(route[0], route[2]));
as(user, "eks").urlEncodingEnabled(false).get(route[1]).then().statusCode(200);
}
}
@Test
void anEksClusterRouteIsCheckedAgainstTheClusterEksActsOn() {
// EKS finds a cluster by its name alone, whatever Region a request is signed for, so a request signed
// for another Region is checked against the cluster it acts on.
String user = user("route-eks-region");
String name = "route-west-" + suffix();
String cluster = given().header("Authorization", auth(ADMIN, "us-west-2", "eks"))
.contentType("application/json")
.body("{\"name\":\"" + name + "\",\"roleArn\":\"arn:aws:iam::" + ACCOUNT + ":role/route-cluster\"}")
.post("/clusters").then().statusCode(200).extract().path("cluster.arn");
cleanup.register(() -> eks().delete("/clusters/" + name));
policy(user, allow("eks:DescribeCluster", "*") + "," + deny("eks:DescribeCluster", cluster));
refused(as(user, "eks").get("/clusters/" + name).then(), "eks:DescribeCluster");
policy(user, allow("eks:DescribeCluster", cluster));
as(user, "eks").get("/clusters/" + name).then().statusCode(200);
}
@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.
String user = user("route-eks-entry");
String name = "route-entry-" + suffix();
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");
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(),
"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
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.
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");
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"));
}
@Test
void aTrailingSlashDoesNotLetARouteThroughUnchecked() {
// The router matches /clusters/ as /clusters, so the request is checked as the route it reaches.
String user = user("route-trailing-slash");
policy(user, allow("sqs:ListQueues", "*"));
refused(as(user, "eks").body("{\"name\":\"route-slash-" + suffix() + "\"}").post("/clusters/").then(),
"eks:CreateCluster");
refused(as(user, "eks").get("/clusters/").then(), "eks:ListClusters");
refused(as(user, "scheduler").get("/schedules/").then(), "scheduler:ListSchedules");
refused(as(user, "lambda").get("/2015-03-31/functions/route-fn/").then(), "lambda:GetFunction");
}
/** Creates an EKS cluster as the account's admin, removed afterwards, and returns its ARN. */
private String eksCluster(String name) {
String arn = eks().body("{\"name\":\"" + name + "\",\"roleArn\":\"arn:aws:iam::" + ACCOUNT
+ ":role/route-cluster\",\"accessConfig\":{\"authenticationMode\":\"API\"}}")
.post("/clusters").then().statusCode(200).extract().path("cluster.arn");
cleanup.register(() -> eks().delete("/clusters/" + name));
return arn;
}
private static RequestSpecification eks() {
return given().header("Authorization", auth(ADMIN, "eks")).contentType("application/json");
}
private static String encoded(String value) {
return URLEncoder.encode(value, StandardCharsets.UTF_8);
}
private static String scheduleGroup(String name) {
return "arn:aws:scheduler:us-east-1:" + ACCOUNT + ":schedule-group/" + name;
}
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.eks.EksService;
import io.github.hectorvent.floci.services.iam.model.AccessKey;
import io.github.hectorvent.floci.services.iam.model.IamGroup;
import io.github.hectorvent.floci.services.iam.model.IamRole;
@@ -128,6 +129,14 @@ class ResourceArnBuilderTest {
return new ResourceArnBuilder(new ObjectMapper(), null, 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, null, null, instance);
}
private static IamService storeHolding(String userName, String path, String arn) {
IamUser user = new IamUser();
user.setUserName(userName);
@@ -1630,6 +1639,109 @@ class ResourceArnBuilderTest {
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function:1/durable-execution/run-1/0b1c", arn);
}
// ── EKS ──────────────────────────────────────────────────────────────────────
/** 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 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"},
}) {
when(eks.findResourceArn("held", held[0], held[1]))
.thenReturn(Optional.of("arn:aws:eks:us-west-2: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-west-2: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));
assertEquals(held + "access-entry/held/role/000000000000/access-policies/6",
eksResource(eks, "GET", "/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-west-2: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);
}
}
/** Stubs the request path as sent and, decoded, as {@link UriInfo#getPath()} gives it. */
private void request(String sent) {
when(uriInfo.getRequestUri()).thenReturn(URI.create("http://localhost:4566" + sent));