Light, fluffy, and always free - The AWS Local Emulator alternative
fix(eks): accept a role ARN from another partition the way STS does (#5398)
Hector Venturafb202cce6a64
diff --git a/docs/configuration/partitions.md b/docs/configuration/partitions.mdindex dd7aad05b6..29e4986718 100644--- a/docs/configuration/partitions.md+++ b/docs/configuration/partitions.md@@ -211,7 +211,9 @@ partition.namespace, and `ListBuckets` lists buckets created from every partition; IAM, Organizations,Route 53, CloudFront and the IAM Identity Center instance keep one set of resources per account,whichever partition a request is signed for. AWS keeps them per partition. A deployment that serves one partition is- unaffected.+ unaffected. For the same reason, STS `AssumeRole`, EKS Pod Identity and EKS add-ons accept a role ARN from+ any partition and resolve it to the account's role of that path and name; the session is named+ with the role's own ARN.- **AWS managed policies** are the commercial catalog in every partition, with their ARNs andregional hosts rewritten; AWS publishes no per-partition list.- **Client tooling** that computes partition values itself (CDK bootstrap anddiff --git a/docs/services/eks.md b/docs/services/eks.mdindex 7b70ed2679..43a39fee6a 100644--- a/docs/services/eks.md+++ b/docs/services/eks.md@@ -116,7 +116,8 @@ The credentials endpoint performs the following validations:2. Identifies the matching EKS cluster by comparing the token issuer URL to cluster OIDC issuer URLs.3. Validates the token signature against the cluster OIDC public key, confirming the token is unexpired and carries audience `pods.eks.amazonaws.com`.4. Extracts the subject claim (`system:serviceaccount:<namespace>:<serviceAccount>`) and looks up the pod identity association for the cluster, namespace, and service account.-5. Issues temporary session credentials (`ASIA...`) for the associated IAM role and returns them in standard AWS container credentials format (`AccessKeyId`, `SecretAccessKey`, `Token`, `AccountId`, `Expiration`).+5. Confirms the associated IAM role still exists under the ARN the association names. A role that was deleted, or recreated under another path, gets `400 AccessDeniedException` and no credentials.+6. Issues temporary session credentials (`ASIA...`) for the associated IAM role and returns them in standard AWS container credentials format (`AccessKeyId`, `SecretAccessKey`, `Token`, `AccountId`, `Expiration`).#### TLS is requireddiff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksAddonService.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksAddonService.javaindex 8b9e26d1db..af81b4bee8 100644--- a/src/main/java/io/github/hectorvent/floci/services/eks/EksAddonService.java+++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksAddonService.java@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.eks;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.core.type.TypeReference;import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.PaginatedResult;import io.github.hectorvent.floci.core.common.Pagination;@@ -120,7 +121,7 @@ public class EksAddonService {}if (request.serviceAccountRoleArn() != null && !request.serviceAccountRoleArn().isBlank()) {- validateRoleArn(cluster, request.serviceAccountRoleArn(), "serviceAccountRoleArn");+ validateRoleArn(request.serviceAccountRoleArn(), "serviceAccountRoleArn");}if (request.resolveConflicts() != null && !request.resolveConflicts().isBlank()) {@@ -221,7 +222,7 @@ public class EksAddonService {if (request.serviceAccountRoleArn() != null) {if (!request.serviceAccountRoleArn().isBlank()) {- validateRoleArn(cluster, request.serviceAccountRoleArn(), "serviceAccountRoleArn");+ validateRoleArn(request.serviceAccountRoleArn(), "serviceAccountRoleArn");}params.add(new UpdateParam("ServiceAccountRoleArn", request.serviceAccountRoleArn()));}@@ -383,7 +384,7 @@ public class EksAddonService {throw new AwsException("InvalidParameterException","roleArn and serviceAccount are required for podIdentityAssociations", 400);}- validateRoleArn(cluster, assoc.roleArn(), "roleArn");+ validateRoleArn(assoc.roleArn(), "roleArn");}}@@ -469,13 +470,12 @@ public class EksAddonService {}}- private void validateRoleArn(Cluster cluster, String roleArn, String fieldName) {+ private void validateRoleArn(String roleArn, String fieldName) {if (roleArn == null || roleArn.isBlank()) {throw new AwsException("InvalidParameterException", fieldName + " is required", 400);}String[] arn = roleArn.split(":", 6);- String[] clusterArn = cluster.getArn().split(":", 6);- if (arn.length != 6 || !"arn".equals(arn[0]) || !arn[1].equals(clusterArn[1])+ if (arn.length != 6 || !"arn".equals(arn[0]) || !arn[1].matches(AwsArnUtils.PARTITION_REGEX)|| !"iam".equals(arn[2]) || !arn[3].isEmpty() || !arn[4].matches("[0-9]{12}")|| !arn[5].startsWith("role/") || arn[5].startsWith("role/aws-service-role/")|| roleArn.endsWith("/")) {@@ -484,7 +484,7 @@ public class EksAddonService {if (iam != null) {String roleName = roleArn.substring(roleArn.lastIndexOf('/') + 1);iam.findRole(arn[4], roleName)- .filter(role -> roleArn.equals(role.getArn()))+ .filter(role -> IamService.roleArnMatches(roleArn, role)).orElseThrow(() -> new AwsException("InvalidParameterException", "Role not found: " + roleArn, 400));}}diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityAssociationService.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityAssociationService.javaindex fa79aac63d..62b9a19c49 100644--- a/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityAssociationService.java+++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityAssociationService.java@@ -84,10 +84,10 @@ public class EksPodIdentityAssociationService {if (roleArn == null || roleArn.isBlank()) {throw invalid("roleArn is required");}- validateRoleArn(cluster, roleArn, "roleArn");+ validateRoleArn(roleArn, "roleArn");if (request.targetRoleArn() != null && !request.targetRoleArn().isBlank()) {- validateTargetRoleArn(cluster, request.targetRoleArn());+ validateTargetRoleArn(request.targetRoleArn());}Map<String, String> tags = request.tags() == null ? Map.of() : request.tags();@@ -194,12 +194,12 @@ public class EksPodIdentityAssociationService {String newRoleArn = current.roleArn();if (request.roleArn() != null) {- validateRoleArn(cluster, request.roleArn(), "roleArn");+ validateRoleArn(request.roleArn(), "roleArn");newRoleArn = request.roleArn();}String newTargetRoleArn = current.targetRoleArn();if (request.targetRoleArn() != null) {- validateTargetRoleArn(cluster, request.targetRoleArn());+ validateTargetRoleArn(request.targetRoleArn());newTargetRoleArn = request.targetRoleArn();}Boolean newDisableSessionTags = request.disableSessionTags() != null@@ -313,16 +313,14 @@ public class EksPodIdentityAssociationService {}}- /** The partition role ARNs must share with the cluster: its own, or the deployment's without an ARN. */- private String clusterPartition(Cluster cluster) {- return AwsArnUtils.partitionOrDefault(cluster != null ? cluster.getArn() : null,- regionResolver.getDefaultPartition());- }-- private void validateRoleArn(Cluster cluster, String roleArn, String fieldName) {+ /**+ * The role must exist in the account the ARN names. Its partition only has to be well formed:+ * an account keeps one IAM namespace whichever partition a request is for, and STS AssumeRole+ * accepts the same role ARNs through {@link IamService#roleArnMatches}.+ */+ private void validateRoleArn(String roleArn, String fieldName) {String[] arn = roleArn.split(":", 6);- String expectedPartition = clusterPartition(cluster);- if (arn.length != 6 || !"arn".equals(arn[0]) || !arn[1].equals(expectedPartition)+ if (arn.length != 6 || !"arn".equals(arn[0]) || !arn[1].matches(AwsArnUtils.PARTITION_REGEX)|| !"iam".equals(arn[2]) || !arn[3].isEmpty() || !arn[4].matches("[0-9]{12}")|| !arn[5].startsWith("role/") || arn[5].startsWith("role/aws-service-role/")|| roleArn.endsWith("/")) {@@ -330,14 +328,13 @@ public class EksPodIdentityAssociationService {}String roleName = roleArn.substring(roleArn.lastIndexOf('/') + 1);iam.findRole(arn[4], roleName)- .filter(role -> roleArn.equals(role.getArn()))+ .filter(role -> IamService.roleArnMatches(roleArn, role)).orElseThrow(() -> invalid("IAM role does not exist"));}- private void validateTargetRoleArn(Cluster cluster, String targetRoleArn) {+ private static void validateTargetRoleArn(String targetRoleArn) {String[] arn = targetRoleArn.split(":", 6);- String expectedPartition = clusterPartition(cluster);- if (arn.length != 6 || !"arn".equals(arn[0]) || !arn[1].equals(expectedPartition)+ if (arn.length != 6 || !"arn".equals(arn[0]) || !arn[1].matches(AwsArnUtils.PARTITION_REGEX)|| !"iam".equals(arn[2]) || !arn[3].isEmpty() || !arn[4].matches("[0-9]{12}")|| !arn[5].startsWith("role/") || targetRoleArn.endsWith("/")) {throw invalid("targetRoleArn must identify an IAM role");diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityCredentialsController.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityCredentialsController.javaindex 7a26928e5a..11199e1713 100644--- a/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityCredentialsController.java+++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityCredentialsController.java@@ -136,12 +136,24 @@ public class EksPodIdentityCredentialsController {String sessionName = podIdentitySessionName(cluster.getName(), association.serviceAccount());String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : roleArn;- Optional<IamRole> role = iamService.findRole(roleAccountId, roleName);+ // EKS Auth assumes the association's role through STS, so a role that is gone gets no+ // credentials. The lookup is by name only, and enforcement loads a session's policies the+ // same way, so a role recreated under another path is refused too: it is not the role the+ // association names.+ Optional<IamRole> role = iamService.findRole(roleAccountId, roleName)+ .filter(found -> IamService.roleArnMatches(roleArn, found));+ if (role.isEmpty()) {+ return error(400, "AccessDeniedException: The role of the association cannot be assumed: "+ + roleArn + "\n");+ }String assumedRoleId = role.map(IamRole::getRoleId).filter(id -> !id.isBlank()).map(id -> id + ":" + sessionName).orElse(null);- iamService.registerSession(accessKeyId, secretAccessKey, sessionToken, roleArn,+ // Like STS AssumeRole, the session names the stored role, so it lives in the role's+ // partition even when the association was made with the role's ARN in another partition.+ String sessionRoleArn = role.map(IamRole::getArn).filter(AwsArnUtils::isArn).orElse(roleArn);+ iamService.registerSession(accessKeyId, secretAccessKey, sessionToken, sessionRoleArn,expiration, association.policy(), callerAccountId, sessionName, assumedRoleId);EksPodIdentityCredentialsResponse response = new EksPodIdentityCredentialsResponse(diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.javaindex 997d9c8e1d..db3a2818da 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java@@ -1078,6 +1078,34 @@ public class IamService implements SessionAccountLookup, ResourceProvider {+ " at 'roleName' failed to satisfy constraint: " + constraint, 400);}+ /**+ * Whether {@code requestedRoleArn} names {@code role}: same account, same path and name, no region.+ *+ * <p>The ARN's partition only has to be well formed. One process serves several partitions but+ * keeps one IAM namespace per account, so a role ARN from another partition resolves to the+ * account's one role (see the partitions guide). STS AssumeRole and EKS Pod Identity both match+ * role ARNs through here so they accept the same ARNs.+ */+ public static boolean roleArnMatches(String requestedRoleArn, IamRole role) {+ if (requestedRoleArn == null || role == null || !AwsArnUtils.isArn(requestedRoleArn)) {+ return false;+ }+ AwsArnUtils.Arn requested = AwsArnUtils.parse(requestedRoleArn);+ if (!"iam".equals(requested.service())+ || !requested.partition().matches(AwsArnUtils.PARTITION_REGEX)) {+ return false;+ }+ String storedArn = role.getArn();+ if (storedArn != null && AwsArnUtils.isArn(storedArn)) {+ AwsArnUtils.Arn stored = AwsArnUtils.parse(storedArn);+ return requested.accountId().equals(stored.accountId())+ && requested.region().equals(stored.region())+ && requested.resource().equals(stored.resource());+ }+ String expectedResource = "role" + normalizePath(role.getPath()) + role.getRoleName();+ return requested.region().isEmpty() && requested.resource().equals(expectedResource);+ }+/*** AWS publishes UnmodifiableEntity on twelve role actions, and its message names the linked* service the caller has to go through instead. This guards the eleven of them the emulatordiff --git a/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.javaindex c5d7b7dd83..18710501a3 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java@@ -177,7 +177,7 @@ public class StsQueryHandler {.orElse(regionResolver.buildGlobalArn("iam", callerAccount, "root"));String principalArn = callerArns.map(IamService.CallerArns::principalArn).orElse(callerArn);- if (role == null || !roleArnMatches(roleArn, role)) {+ if (role == null || !IamService.roleArnMatches(roleArn, role)) {return AwsQueryResponse.error("AccessDenied","User: " + callerArn + " is not authorized to perform: sts:AssumeRole on resource: " + roleArn,AwsNamespaces.STS, 403);@@ -210,26 +210,6 @@ public class StsQueryHandler {"role" + IamService.normalizePath(role.getPath()) + roleName);}- static boolean roleArnMatches(String requestedRoleArn, IamRole role) {- if (requestedRoleArn == null || role == null || !AwsArnUtils.isArn(requestedRoleArn)) {- return false;- }- AwsArnUtils.Arn requested = AwsArnUtils.parse(requestedRoleArn);- if (!"iam".equals(requested.service())- || !requested.partition().matches(AwsArnUtils.PARTITION_REGEX)) {- return false;- }- String storedArn = role.getArn();- if (storedArn != null && AwsArnUtils.isArn(storedArn)) {- AwsArnUtils.Arn stored = AwsArnUtils.parse(storedArn);- return requested.accountId().equals(stored.accountId())- && requested.region().equals(stored.region())- && requested.resource().equals(stored.resource());- }- String expectedResource = "role" + IamService.normalizePath(role.getPath()) + role.getRoleName();- return requested.region().isEmpty() && requested.resource().equals(expectedResource);- }-private Response handleGetCallerIdentity(MultivaluedMap<String, String> params) {String accountId = regionResolver.getAccountId();String authorization = headers == null ? null : headers.getHeaderString("Authorization");@@ -298,7 +278,7 @@ public class StsQueryHandler {IamRole role = outcome.role();if (role == null) {role = iamService.findRole(accountId, roleName).orElse(null);- if (role == null || !roleArnMatches(roleArn, role)) {+ if (role == null || !IamService.roleArnMatches(roleArn, role)) {return accessDenied(roleArn);}}@@ -406,7 +386,7 @@ public class StsQueryHandler {}Optional<IamRole> role = iamService.findRole(roleAccountId, roleName);- if (role.isEmpty() || !roleArnMatches(roleArn, role.get())) {+ if (role.isEmpty() || !IamService.roleArnMatches(roleArn, role.get())) {return WebIdentityOutcome.deny(accessDenied(roleArn));}diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksPodIdentityAssociationServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksPodIdentityAssociationServiceTest.javaindex a2ed0b9880..fb05182b64 100644--- a/src/test/java/io/github/hectorvent/floci/services/eks/EksPodIdentityAssociationServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksPodIdentityAssociationServiceTest.java@@ -286,6 +286,32 @@ class EksPodIdentityAssociationServiceTest {+ created.associationId(), created.associationArn());}+ @Test+ void aRoleArnFromAnotherPartitionResolvesTheAccountsRoleTheWayStsDoes() {+ Fixture fixture = fixture();+ String chinaRole = "arn:aws-cn:iam::123456789012:role/pod-role";+ String govTarget = "arn:aws-us-gov:iam::210987654321:role/target-role";++ PodIdentityAssociation created = fixture.service.create(fixture.cluster, new CreatePodIdentityAssociationRequest(+ fixture.cluster.getName(), NAMESPACE, SERVICE_ACCOUNT, chinaRole, null, Map.of(), govTarget,+ null, null));++ assertEquals(chinaRole, created.roleArn());+ assertEquals(govTarget, created.targetRoleArn());+ PodIdentityAssociation updated = fixture.service.update(fixture.cluster, created.associationId(),+ new UpdatePodIdentityAssociationRequest(ROLE, null, null, null, null));+ assertEquals(ROLE, updated.roleArn());++ for (String rejected : List.of("arn:aws-cn:iam::123456789012:role/team/pod-role",+ "arn:aws-cn:iam::111111111111:role/pod-role", "arn:bogus:iam::123456789012:role/pod-role")) {+ AwsException ex = assertThrows(AwsException.class, () -> fixture.service.update(fixture.cluster,+ created.associationId(), new UpdatePodIdentityAssociationRequest(rejected, null, null, null, null)),+ rejected);+ assertEquals("InvalidParameterException", ex.getErrorCode(), rejected);+ assertEquals(ROLE, fixture.service.describe(fixture.cluster, created.associationId()).roleArn(), rejected);+ }+ }+private static Fixture fixture() {Cluster cluster = new Cluster();cluster.setName("test-cluster");diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksPodIdentityCredentialsControllerTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksPodIdentityCredentialsControllerTest.javaindex d0dfe64526..2a0a3f810e 100644--- a/src/test/java/io/github/hectorvent/floci/services/eks/EksPodIdentityCredentialsControllerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksPodIdentityCredentialsControllerTest.java@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.services.eks.model.ClusterStatus;import io.github.hectorvent.floci.services.eks.model.EksPodIdentityCredentialsResponse;import io.github.hectorvent.floci.services.eks.model.PodIdentityAssociation;import io.github.hectorvent.floci.services.iam.IamService;+import io.github.hectorvent.floci.services.iam.model.IamRole;import jakarta.ws.rs.core.Response;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;@@ -29,6 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.never;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.verifyNoInteractions;import static org.mockito.Mockito.when;@@ -92,6 +94,8 @@ class EksPodIdentityCredentialsControllerTest {);when(associationService.findAssociation(cluster, NAMESPACE, SERVICE_ACCOUNT)).thenReturn(Optional.of(association));+ when(iamService.findRole(ACCOUNT_ID, "app-role"))+ .thenReturn(Optional.of(new IamRole("AROA-app", "app-role", "/", ROLE_ARN, "{}")));}private static KeyPair newKeyPair() throws GeneralSecurityException {@@ -145,6 +149,48 @@ class EksPodIdentityCredentialsControllerTest {assertTrue(sessionNameCaptor.getValue().startsWith("eks-" + CLUSTER_NAME + "-" + SERVICE_ACCOUNT + "-"));}+ @Test+ void aSessionOnARoleArnFromAnotherPartitionNamesTheStoredRoleLikeSts() throws Exception {+ String chinaRoleArn = "arn:aws-cn:iam::123456789012:role/app-role";+ PodIdentityAssociation association = new PodIdentityAssociation(CLUSTER_NAME, NAMESPACE, SERVICE_ACCOUNT,+ chinaRoleArn, "arn:aws:eks:us-east-1:" + ACCOUNT_ID + ":podidentityassociation/" + CLUSTER_NAME+ + "/assoc-1", "assoc-1", null, 1000.0, 1000.0, null, null, false, null, null);+ when(associationService.findAssociation(cluster, NAMESPACE, SERVICE_ACCOUNT))+ .thenReturn(Optional.of(association));+ when(iamService.findRole(ACCOUNT_ID, "app-role"))+ .thenReturn(Optional.of(new IamRole("AROA-app", "app-role", "/", ROLE_ARN, "{}")));++ Response response = controller.getCredentials("Bearer " + validToken());++ assertEquals(200, response.getStatus());+ verify(iamService).registerSession(any(), any(), any(), eq(ROLE_ARN), any(Instant.class), eq(null),+ eq(ACCOUNT_ID), any(), any());+ }++ @Test+ void aRoleRecreatedUnderAnotherPathGetsNoCredentials() throws Exception {+ String replacementArn = "arn:aws:iam::" + ACCOUNT_ID + ":role/team/app-role";+ when(iamService.findRole(ACCOUNT_ID, "app-role"))+ .thenReturn(Optional.of(new IamRole("AROA-replacement", "app-role", "/team/", replacementArn, "{}")));++ Response response = controller.getCredentials("Bearer " + validToken());++ assertEquals(400, response.getStatus());+ assertTrue(response.getEntity().toString().startsWith("AccessDeniedException"));+ verify(iamService, never()).registerSession(any(), any(), any(), any(), any(), any(), any(), any(), any());+ }++ @Test+ void aDeletedRoleGetsNoCredentials() throws Exception {+ when(iamService.findRole(ACCOUNT_ID, "app-role")).thenReturn(Optional.empty());++ Response response = controller.getCredentials("Bearer " + validToken());++ assertEquals(400, response.getStatus());+ assertTrue(response.getEntity().toString().startsWith("AccessDeniedException"));+ verify(iamService, never()).registerSession(any(), any(), any(), any(), any(), any(), any(), any(), any());+ }+@Testvoid supportsRawTokenWithoutBearerPrefix() throws Exception {Response response = controller.getCredentials(validToken());diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/StsQueryHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/StsQueryHandlerTest.javaindex 6f4b4a95a2..a1e331c3fa 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/StsQueryHandlerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/StsQueryHandlerTest.java@@ -57,10 +57,16 @@ class StsQueryHandlerTest {}private static StsQueryHandler newHandlerForRegion(RegionResolver regionResolver) {- return newHandler(null, regionResolver);+ return newHandler((IamRole) null, regionResolver);}private static StsQueryHandler newHandler(IamRole role, RegionResolver regionResolver) {+ IamService iamService = mock(IamService.class);+ when(iamService.findRole(anyString(), anyString())).thenReturn(Optional.ofNullable(role));+ return newHandler(iamService, regionResolver);+ }++ private static StsQueryHandler newHandler(IamService iamService, RegionResolver regionResolver) {EmulatorConfig config = mock(EmulatorConfig.class);EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);EmulatorConfig.IamServiceConfig iam = mock(EmulatorConfig.IamServiceConfig.class);@@ -68,9 +74,6 @@ class StsQueryHandlerTest {when(services.iam()).thenReturn(iam);when(iam.enforcementEnabled()).thenReturn(false);- IamService iamService = mock(IamService.class);- when(iamService.findRole(anyString(), anyString())).thenReturn(Optional.ofNullable(role));-return new StsQueryHandler(iamService,mock(AccountResolver.class),@@ -178,6 +181,24 @@ class StsQueryHandlerTest {"AssumedRoleUser Arn must use the stored role's partition");}+ @Test+ void assumeRoleOnARoleArnFromAnotherPartitionRegistersTheAccountsOneRole() {+ String storedArn = "arn:aws:iam::000000000000:role/TestRole";+ IamService iamService = mock(IamService.class);+ when(iamService.findRole("000000000000", "TestRole"))+ .thenReturn(Optional.of(new IamRole("AROA-test", "TestRole", "/", storedArn, "{}")));+ StsQueryHandler handler = newHandler(iamService, new RegionResolver(REGION, "000000000000"));++ MultivaluedMap<String, String> params = new MultivaluedHashMap<>();+ params.putSingle("RoleArn", "arn:aws-cn:iam::000000000000:role/TestRole");+ params.putSingle("RoleSessionName", "test-session");+ Response response = handler.handle("AssumeRole", params);++ assertEquals(200, response.getStatus(), (String) response.getEntity());+ verify(iamService).registerSession(anyString(), anyString(), anyString(), eq(storedArn), any(),+ any(), eq("000000000000"), eq("test-session"), eq("AROA-test:test-session"));+ }+@Testvoid roleArnMatchesValidatesPartitionsAndPaths() {IamRole role = new IamRole();@@ -185,16 +206,16 @@ class StsQueryHandlerTest {role.setPath("/team/");role.setArn("arn:aws:iam::000000000000:role/team/TestRole");- assertTrue(StsQueryHandler.roleArnMatches("arn:aws:iam::000000000000:role/team/TestRole", role));- assertTrue(StsQueryHandler.roleArnMatches("arn:aws-cn:iam::000000000000:role/team/TestRole", role));- assertTrue(StsQueryHandler.roleArnMatches("arn:aws-us-gov:iam::000000000000:role/team/TestRole", role));+ assertTrue(IamService.roleArnMatches("arn:aws:iam::000000000000:role/team/TestRole", role));+ assertTrue(IamService.roleArnMatches("arn:aws-cn:iam::000000000000:role/team/TestRole", role));+ assertTrue(IamService.roleArnMatches("arn:aws-us-gov:iam::000000000000:role/team/TestRole", role));- assertFalse(StsQueryHandler.roleArnMatches("arn:aws:iam::000000000000:role/other/TestRole", role));- assertFalse(StsQueryHandler.roleArnMatches("arn:aws:iam::111111111111:role/team/TestRole", role));- assertFalse(StsQueryHandler.roleArnMatches("arn:aws:iam:us-east-1:000000000000:role/team/TestRole", role));- assertFalse(StsQueryHandler.roleArnMatches("arn:aws:s3:::bucket", role));- assertFalse(StsQueryHandler.roleArnMatches("not-an-arn", role));- assertFalse(StsQueryHandler.roleArnMatches(null, role));+ assertFalse(IamService.roleArnMatches("arn:aws:iam::000000000000:role/other/TestRole", role));+ assertFalse(IamService.roleArnMatches("arn:aws:iam::111111111111:role/team/TestRole", role));+ assertFalse(IamService.roleArnMatches("arn:aws:iam:us-east-1:000000000000:role/team/TestRole", role));+ assertFalse(IamService.roleArnMatches("arn:aws:s3:::bucket", role));+ assertFalse(IamService.roleArnMatches("not-an-arn", role));+ assertFalse(IamService.roleArnMatches(null, role));}@ParameterizedTest