Light, fluffy, and always free - The AWS Local Emulator alternative
fix(iam): give a role session's aws:PrincipalArn as its role's ARN under enforcement (#4810)
Priamo Germosencf04f433b695
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamEnforcementTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamEnforcementTest.javaindex a08d7c45ae..e14a8cd5e0 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamEnforcementTest.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamEnforcementTest.java@@ -59,6 +59,7 @@ class IamEnforcementTest {// ── Resource names ─────────────────────────────────────────────────────────private static final String USER = "iam-enf-test-user";private static final String ROLE = "iam-enf-test-role";+ private static final String PATH_ROLE = "iam-enf-test-path-role";private static final String POLICY_NAME = "iam-enf-allow-s3list";private static final String TRUST_POLICY = """@@ -162,6 +163,11 @@ class IamEnforcementTest {try { iam.deleteAccessKey(DeleteAccessKeyRequest.builder().userName(USER).accessKeyId(userAccessKeyId).build()); } catch (Exception ignored) {}try { iam.deleteRole(DeleteRoleRequest.builder().roleName(ROLE).build()); } catch (Exception ignored) {}+ cleanupResource("delete principal-arn policy from role " + PATH_ROLE,+ () -> iam.deleteRolePolicy(DeleteRolePolicyRequest.builder()+ .roleName(PATH_ROLE).policyName("principal-arn").build()));+ cleanupResource("delete role " + PATH_ROLE,+ () -> iam.deleteRole(DeleteRoleRequest.builder().roleName(PATH_ROLE).build()));try { iam.deletePolicy(DeletePolicyRequest.builder().policyArn(allowPolicyArn).build()); } catch (Exception ignored) {}try { iam.deleteUser(DeleteUserRequest.builder().userName(USER).build()); } catch (Exception ignored) {}iam.close();@@ -505,6 +511,58 @@ class IamEnforcementTest {}}+ @Test+ @Order(13)+ @DisplayName("a role session's aws:PrincipalArn is its role's ARN, path included")+ void roleSessionPrincipalArnIsTheRolesArnWithItsPath() {+ assumeEnforcementEnabled();+ String pathRoleArn = iam.createRole(CreateRoleRequest.builder()+ .roleName(PATH_ROLE)+ .path("/team/")+ .assumeRolePolicyDocument(TRUST_POLICY)+ .build()).role().arn();+ AssumeRoleResponse assumed = sts.assumeRole(AssumeRoleRequest.builder()+ .roleArn(pathRoleArn)+ .roleSessionName("principal-arn")+ .build());+ String sessionArn = assumed.assumedRoleUser().arn();+ // AWS reports the role's ARN in aws:PrincipalArn, not the session's: a condition on the role+ // matches, one on the session ARN does not, and a Deny keyed on the role fires.+ iam.putRolePolicy(PutRolePolicyRequest.builder()+ .roleName(PATH_ROLE)+ .policyName("principal-arn")+ .policyDocument("""+ {"Version":"2012-10-17","Statement":[+ {"Effect":"Allow","Action":"iam:ListUsers","Resource":"*",+ "Condition":{"ArnEquals":{"aws:PrincipalArn":"%1$s"}}},+ {"Effect":"Allow","Action":"iam:ListRoles","Resource":"*",+ "Condition":{"ArnEquals":{"aws:PrincipalArn":"%2$s"}}},+ {"Effect":"Allow","Action":"iam:ListGroups","Resource":"*"},+ {"Effect":"Deny","Action":"iam:ListGroups","Resource":"*",+ "Condition":{"ArnEquals":{"aws:PrincipalArn":"%1$s"}}}+ ]}""".formatted(pathRoleArn, sessionArn))+ .build());++ try (IamClient session = IamClient.builder()+ .endpointOverride(TestFixtures.endpoint())+ .region(Region.US_EAST_1)+ .credentialsProvider(StaticCredentialsProvider.create(AwsSessionCredentials.create(+ assumed.credentials().accessKeyId(),+ assumed.credentials().secretAccessKey(),+ assumed.credentials().sessionToken())))+ .build()) {+ assertThatCode(session::listUsers).doesNotThrowAnyException();+ assertThatThrownBy(session::listRoles)+ .isInstanceOf(IamException.class)+ .extracting(e -> ((IamException) e).statusCode())+ .isEqualTo(403);+ assertThatThrownBy(session::listGroups)+ .isInstanceOf(IamException.class)+ .extracting(e -> ((IamException) e).statusCode())+ .isEqualTo(403);+ }+ }+private static StaticCredentialsProvider userCredentials() {return StaticCredentialsProvider.create(AwsBasicCredentials.create(userAccessKeyId, userSecretKey));}diff --git a/docs/services/iam.md b/docs/services/iam.mdindex c0ead58572..1b50bba920 100644--- a/docs/services/iam.md+++ b/docs/services/iam.md@@ -692,9 +692,11 @@ floci populates:check is made without the object's tags in the context, as measured on AWS. `If-None-Match`needs no such permission.- `aws:PrincipalArn`: the caller's ARN, resolved from the signing access key. It is the- IAM-user ARN for a user access key, the assumed-role ARN for an STS session, and- `arn:aws:iam::<account>:root` for the bare account-id key (floci's account-root principal),- matching the ARN shape AWS itself reports for the account root. It is **absent** only for+ IAM-user ARN for a user access key, and `arn:aws:iam::<account>:root` for the bare account-id+ key (floci's account-root principal), matching the ARN shape AWS itself reports for the account+ root. For an STS role session it is the ARN of the role that was assumed, path included, not the+ `assumed-role` session ARN, as AWS reports it ("For IAM roles, the request context returns the+ ARN of the role"); a condition naming the session ARN does not match. It is **absent** only forunknown keys, where nothing about the caller can be resolved.- `dynamodb:LeadingKeys`, `dynamodb:Attributes`, `dynamodb:Select`: from the DynamoDB requestbody, for `GetItem`, `PutItem`, `UpdateItem`, `DeleteItem`, `Query`, `BatchGetItem` and@@ -724,10 +726,6 @@ being bounded by SCPs (below): both forms of root enforcement now agree. A negatabsent key cannot equal what the policy names, so the condition holds, and a `Deny` writtenthat way applies when the key is missing.-**Caveat:** `resolveCallerArn` hardcodes the assumed-role session name as `floci-session`,-so `aws:PrincipalArn` for an assumed-role caller will not match a condition that pins a-different session name. This matches what `sts:GetCallerIdentity` already reports.-**Not yet supported**: `NotPrincipal`, resource-based policies (S3 bucket policy, Lambda resourcepolicy), and `dynamodb:LeadingKeys` for `Scan`, `TransactWriteItems` / `TransactGetItems` and thePartiQL operations.diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.javaindex 1bd91d24d4..11c724a680 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision;import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourceAccountRelationship;import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourcePolicyDecision;import io.github.hectorvent.floci.services.iam.IamService;+import io.github.hectorvent.floci.services.iam.IamService.CallerArns;import io.github.hectorvent.floci.services.iam.IamService.PresignedScope;import io.github.hectorvent.floci.services.iam.ResourceArnBuilder;import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider;@@ -388,24 +389,26 @@ public class IamEnforcementFilter implements ContainerRequestFilter {conditionContextResolver.resolveRemainingTargets(credentialScope, action, ctx);// aws:PrincipalArn is populated for every principal this filter can identify — IAM users,- // assumed-role sessions, and now the synthesized account-root principal above, using AWS's- // own root ARN shape (arn:aws:iam::<account>:root). Real AWS populates this key for the+ // assumed-role sessions (as the ARN of the role that was assumed, as AWS reports it), and now+ // the synthesized account-root principal above, using AWS's own root ARN shape+ // (arn:aws:iam::<account>:root). Real AWS populates this key for the// root user, so a DenyRootUser guardrail keyed on it must fire against floci's account-root// stand-in the same way it enforces SCPs against it (the account-root SCP change above);// leaving it absent here would have made the two forms of root enforcement inconsistent.- Optional<String> principalArn = accountRootPrincipal- ? Optional.of(AwsArnUtils.Arn.global(requestPartition(), "iam", accountId, "root").toString())- : iamService.resolveCallerArn(akid);- if (principalArn.isPresent()) {- caller = caller.withPrincipalArn(principalArn.get());+ // The session ARN stays the caller's principal for matching a resource policy's Principal.+ Optional<CallerArns> callerArns = accountRootPrincipal+ ? Optional.of(accountRootArns(accountId))+ : iamService.resolveCallerArns(akid);+ if (callerArns.isPresent()) {+ caller = caller.withPrincipalArn(callerArns.get().callerArn());conditionContext = conditionContext == null ? new HashMap<>() : new HashMap<>(conditionContext);- conditionContext.put("aws:PrincipalArn", List.of(principalArn.get()));+ conditionContext.put("aws:PrincipalArn", List.of(callerArns.get().principalArn()));}List<Map<String, List<String>>> targetContexts = new ArrayList<>();targetContexts.add(conditionContext);for (Map<String, List<String>> target : remainingTargets) {Map<String, List<String>> targetContext = new HashMap<>(target);- principalArn.ifPresent(arn -> targetContext.put("aws:PrincipalArn", List.of(arn)));+ callerArns.ifPresent(arns -> targetContext.put("aws:PrincipalArn", List.of(arns.principalArn())));targetContexts.add(targetContext);}@@ -507,6 +510,12 @@ public class IamEnforcementFilter implements ContainerRequestFilter {private record ResolvedAuthorization(String credentialScope, String action) {}+ /** Floci's account-root principal, which is both the caller and the request's aws:PrincipalArn. */+ private CallerArns accountRootArns(String accountId) {+ String rootArn = AwsArnUtils.Arn.global(requestPartition(), "iam", accountId, "root").toString();+ return new CallerArns(rootArn, rootArn);+ }+/*** Evaluates one action against every resource and target context, aborting the request with* AccessDenied on the first DENY. Returns true when the request was aborted.@@ -725,13 +734,13 @@ public class IamEnforcementFilter implements ContainerRequestFilter {}Map<String, List<String>> conditionContext = null;- Optional<String> principalArn = accountRootPrincipal- ? Optional.of(AwsArnUtils.Arn.global(requestPartition(), "iam", accountId, "root").toString())- : iamService.resolveCallerArn(akid);- if (principalArn.isPresent()) {- caller = caller.withPrincipalArn(principalArn.get());+ Optional<CallerArns> callerArns = accountRootPrincipal+ ? Optional.of(accountRootArns(accountId))+ : iamService.resolveCallerArns(akid);+ if (callerArns.isPresent()) {+ caller = caller.withPrincipalArn(callerArns.get().callerArn());conditionContext = new HashMap<>();- conditionContext.put("aws:PrincipalArn", List.of(principalArn.get()));+ conditionContext.put("aws:PrincipalArn", List.of(callerArns.get().principalArn()));}ResourcePolicyDecision effectiveDecision = resourcePolicyDecision;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 a1bc9acef0..ba2a87a254 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@@ -2619,6 +2619,24 @@ public class IamService implements SessionAccountLookup, ResourceProvider {}public Optional<String> resolveCallerArn(String accessKeyId) {+ return resolveCallerArns(accessKeyId).map(CallerArns::callerArn);+ }++ /**+ * The two ARNs a caller's access key stands for, read from one lookup of the key.+ *+ * @param callerArn the identity the caller acts as: the user's ARN, or for a role session its+ * {@code assumed-role} session ARN, as {@link #resolveCallerArn} returns it+ * @param principalArn the request's {@code aws:PrincipalArn}: the user's ARN, or for a role+ * session the ARN of the role that was assumed, path included+ */+ public record CallerArns(String callerArn, String principalArn) {}++ /**+ * Both of the caller's ARNs from a single lookup, so they always describe the same credential:+ * two lookups could straddle a session's expiry and answer for it only once.+ */+ public Optional<CallerArns> resolveCallerArns(String accessKeyId) {if (accessKeyId == null || accessKeyId.isBlank()) {return Optional.empty();}@@ -2626,7 +2644,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {Optional<AccessKey> akOpt = accessKeys.get(accessKeyId);if (akOpt.isPresent()) {String userName = akOpt.get().getUserName();- return users.get(userName).map(IamUser::getArn);+ return users.get(userName).map(IamUser::getArn).map(arn -> new CallerArns(arn, arn));}Optional<SessionCredential> sessionOpt = findSessionForCallerContext(accessKeyId);@@ -2650,8 +2668,9 @@ public class IamService implements SessionAccountLookup, ResourceProvider {// The session lives in its role's partition, as AssumeRole issued it, whatever region// a later call is signed for.String partition = AwsArnUtils.partitionOrDefault(roleArn, regionResolver.getPartition());- return Optional.of(AwsArnUtils.Arn.global(partition, "sts", accountId,- "assumed-role/" + roleName + "/" + sessionName).toString());+ String sessionArn = AwsArnUtils.Arn.global(partition, "sts", accountId,+ "assumed-role/" + roleName + "/" + sessionName).toString();+ return Optional.of(new CallerArns(sessionArn, roleArn));}return Optional.empty();@@ -2663,14 +2682,10 @@ public class IamService implements SessionAccountLookup, ResourceProvider {* was assumed, path included, rather than the assumed-role session ARN, which names the role* without its path. That is the ARN the session recorded when it was issued, read back as is:* looking the role up by name would hand an old session the ARN of a same-named role created- * after it.+ * after it. A caller that needs the caller ARN too reads both through {@link #resolveCallerArns}.*/public Optional<String> resolvePrincipalArn(String accessKeyId) {- Optional<String> callerArn = resolveCallerArn(accessKeyId);- if (callerArn.isEmpty() || accessKeys.get(accessKeyId).isPresent()) {- return callerArn;- }- return findSessionForCallerContext(accessKeyId).map(SessionCredential::getRoleArn);+ return resolveCallerArns(accessKeyId).map(CallerArns::principalArn);}public Optional<String> resolveCallerUserId(String accessKeyId) {diff --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 0777fb04fc..8c2d5fa2bd 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@@ -178,9 +178,10 @@ public class StsQueryHandler {uriInfo == null ? null : uriInfo.getQueryParameters());String callerAccount = regionResolver.getAccountId();String accessKeyId = auth == null ? null : accountResolver.extractAccessKeyId(auth);- String callerArn = iamService.resolveCallerArn(accessKeyId)+ Optional<IamService.CallerArns> callerArns = iamService.resolveCallerArns(accessKeyId);+ String callerArn = callerArns.map(IamService.CallerArns::callerArn).orElse(regionResolver.buildGlobalArn("iam", callerAccount, "root"));- String principalArn = iamService.resolvePrincipalArn(accessKeyId).orElse(callerArn);+ String principalArn = callerArns.map(IamService.CallerArns::principalArn).orElse(callerArn);Map<String, List<String>> requestContext = IamConditionContextResolver.withGlobalContext(null, roleArn, regionResolver.getRegion(), callerAccount, roleAccountId);requestContext.put("sts:RoleSessionName", List.of(getParam(params, "RoleSessionName")));diff --git a/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java b/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.javaindex 9a205a9d6a..d783d21578 100644--- a/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java+++ b/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourceAccountRelationship;import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourcePolicyDecision;import io.github.hectorvent.floci.services.iam.IamService;+import io.github.hectorvent.floci.services.iam.IamService.CallerArns;import io.github.hectorvent.floci.services.iam.ResourceArnBuilder;import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider;import io.github.hectorvent.floci.services.iam.ScpProvider;@@ -1201,9 +1202,9 @@ class IamEnforcementFilterTest {}// aws:PrincipalArn is populated only for principals whose ARN is known — IAM users and- // assumed-role sessions (IamService.resolveCallerArn). A condition-scoped SCP keyed on the+ // assumed-role sessions (IamService.resolveCallerArns). A condition-scoped SCP keyed on the// principal ARN must therefore fire for a real IAM identity. It stays inert for the bare- // account-root key, whose resolveCallerArn is empty (see the workload-guardrails test above).+ // account-root key, whose resolveCallerArns is empty (see the workload-guardrails test above).private static final String DENY_IAM_USER_PRINCIPAL ="{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\",\"Action\":\"*\","+ "\"Resource\":\"*\",\"Condition\":{\"StringLike\":"@@ -1228,8 +1229,8 @@ class IamEnforcementFilterTest {// A real IAM user: full-access identity policy plus a known principal ARN.when(iamService.resolveCallerContext(akid)).thenReturn(CallerContext.of(List.of(FULL_AWS_ACCESS)));- when(iamService.resolveCallerArn(akid))- .thenReturn(Optional.of("arn:aws:iam::" + account + ":user/alice"));+ String userArn = "arn:aws:iam::" + account + ":user/alice";+ when(iamService.resolveCallerArns(akid)).thenReturn(Optional.of(new CallerArns(userArn, userArn)));when(arnBuilder.build(eq("organizations"), eq(containerRequest), eq("us-east-1"), eq(account))).thenReturn("*");when(conditionContextResolver.resolve(eq("organizations"), anyString(), eq(containerRequest)))@@ -1252,7 +1253,7 @@ class IamEnforcementFilterTest {// lets a principal-scoped Allow match. An identity policy that grants access only when the caller// is an IAM user must therefore ALLOW a real IAM user. Before aws:PrincipalArn was populated the// key was absent, the StringLike failed, the sole Allow never matched, and the request was denied- // by default — so stubbing resolveCallerArn empty makes this test RED, proving it is load-bearing.+ // by default, so stubbing resolveCallerArns empty makes this test RED, proving it is load-bearing.private static final String ALLOW_IF_IAM_USER_PRINCIPAL ="{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"*\","+ "\"Resource\":\"*\",\"Condition\":{\"StringLike\":"@@ -1276,8 +1277,8 @@ class IamEnforcementFilterTest {// A real IAM user whose ONLY grant is conditional on being an IAM-user principal.when(iamService.resolveCallerContext(akid)).thenReturn(CallerContext.of(List.of(ALLOW_IF_IAM_USER_PRINCIPAL)));- when(iamService.resolveCallerArn(akid))- .thenReturn(Optional.of("arn:aws:iam::" + account + ":user/bob"));+ String userArn = "arn:aws:iam::" + account + ":user/bob";+ when(iamService.resolveCallerArns(akid)).thenReturn(Optional.of(new CallerArns(userArn, userArn)));when(arnBuilder.buildResources(eq("organizations"), eq(containerRequest), eq("us-east-1"), eq(account))).thenReturn(List.of("*"));when(conditionContextResolver.resolve(eq("organizations"), anyString(), eq(containerRequest)))diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.javaindex 0374d46e11..3ed58fc574 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java@@ -138,6 +138,24 @@ class IamServiceTest {assertEquals(restored.getAssumedRoleId(), service.resolveCallerUserId(accessKeyId).orElseThrow());}+ @Test+ void aSessionsCallerAndPrincipalArnsComeFromOneLookup() {+ IamService service = iamService(false, new InMemoryStorage<>(), new InMemoryStorage<>());+ service.registerSession("ASIALIVESESSION", "secret", "token",+ "arn:aws:iam::123456789012:role/team/TestRole", Instant.now().plusSeconds(3600),+ null, "123456789012", "s", "AROATESTROLEID:s");+ service.registerSession("ASIAEXPIREDSESSION", "secret", "token",+ "arn:aws:iam::123456789012:role/team/TestRole", Instant.now().minusSeconds(1),+ null, "123456789012", "s", "AROATESTROLEID:s");++ // The session ARN carries only the role's name; aws:PrincipalArn is the role's own ARN.+ assertEquals(new IamService.CallerArns("arn:aws:sts::123456789012:assumed-role/TestRole/s",+ "arn:aws:iam::123456789012:role/team/TestRole"),+ service.resolveCallerArns("ASIALIVESESSION").orElseThrow());+ // An expired session answers for neither, never for one and not the other.+ assertTrue(service.resolveCallerArns("ASIAEXPIREDSESSION").isEmpty());+ }+@Testvoid ec2SessionMarkerSurvivesPersistenceAndExpiredCredentialsCannotAuthenticate() throws Exception {SessionCredential expired = new SessionCredential("ASIAEXPIREDEC2", "secret", "token",diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/RoleSessionPrincipalArnEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/RoleSessionPrincipalArnEnforcementIntegrationTest.javanew file mode 100644index 0000000000..5876529d4a--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/iam/RoleSessionPrincipalArnEnforcementIntegrationTest.java@@ -0,0 +1,120 @@+package io.github.hectorvent.floci.services.iam;++import io.github.hectorvent.floci.testing.IamEnforcementProfile;+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import io.quarkus.test.junit.TestProfile;+import io.restassured.response.Response;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++import java.util.UUID;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.equalTo;++/**+ * With {@code iam.enforcement-enabled=true}, a role session's {@code aws:PrincipalArn} is the ARN of+ * the role that was assumed, path included, not the session's ARN (IAM User Guide, global condition+ * keys, {@code aws:PrincipalArn}: "For IAM roles, the request context returns the ARN of the role").+ */+@QuarkusTest+@TestProfile(IamEnforcementProfile.class)+class RoleSessionPrincipalArnEnforcementIntegrationTest {++ private static final String ACCOUNT = "111111111111";++ private record Session(String accessKeyId, String sessionToken) {+ }++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @Test+ void aRoleSessionsPrincipalArnIsItsRolesArnWithItsPath() {+ String role = "principal-arn-" + UUID.randomUUID().toString().substring(0, 8);+ String roleArn = "arn:aws:iam::" + ACCOUNT + ":role/team/" + role;+ String sessionArn = "arn:aws:sts::" + ACCOUNT + ":assumed-role/" + role + "/s";+ createRole(role, """+ {"Version":"2012-10-17","Statement":[+ {"Effect":"Allow","Action":"iam:ListUsers","Resource":"*",+ "Condition":{"ArnEquals":{"aws:PrincipalArn":"%1$s"}}},+ {"Effect":"Allow","Action":"iam:ListRoles","Resource":"*",+ "Condition":{"ArnEquals":{"aws:PrincipalArn":"%2$s"}}},+ {"Effect":"Allow","Action":"iam:ListGroups","Resource":"*"},+ {"Effect":"Deny","Action":"iam:ListGroups","Resource":"*",+ "Condition":{"ArnEquals":{"aws:PrincipalArn":"%1$s"}}}]}""".formatted(roleArn, sessionArn));+ Session session = assumeRole(roleArn);++ // A condition on the role's own ARN matches the session.+ iamCall(session, "ListUsers").then().statusCode(200);+ // A condition on the session ARN does not: that is not what the key carries.+ iamCall(session, "ListRoles").then().statusCode(403);+ // A Deny keyed on the role's ARN fires for its sessions.+ iamCall(session, "ListGroups").then().statusCode(403);+ }++ @Test+ void theSecondResourceAnOperationChecksSeesTheRolesArnToo() {+ // GetParameter on a Secrets Manager reference also needs secretsmanager:GetSecretValue on+ // the secret, which the filter checks as a second resource of the same request.+ String secret = "principal-arn-" + UUID.randomUUID().toString().substring(0, 8);+ given().header("Authorization", auth(ACCOUNT, "secretsmanager"))+ .header("X-Amz-Target", "secretsmanager.CreateSecret")+ .contentType("application/x-amz-json-1.1")+ .body("{\"Name\": \"" + secret + "\", \"SecretString\": \"secret-value\"}")+ .when().post("/").then().statusCode(200);+ String role = "principal-arn-" + UUID.randomUUID().toString().substring(0, 8);+ String roleArn = "arn:aws:iam::" + ACCOUNT + ":role/team/" + role;+ createRole(role, """+ {"Version":"2012-10-17","Statement":[+ {"Effect":"Allow","Action":"ssm:GetParameter","Resource":"*"},+ {"Effect":"Allow","Action":"secretsmanager:GetSecretValue","Resource":"*",+ "Condition":{"ArnEquals":{"aws:PrincipalArn":"%s"}}}]}""".formatted(roleArn));+ Session session = assumeRole(roleArn);++ given().header("Authorization", auth(session.accessKeyId(), "ssm"))+ .header("X-Amz-Security-Token", session.sessionToken())+ .header("X-Amz-Target", "AmazonSSM.GetParameter")+ .contentType("application/x-amz-json-1.1")+ .body("{\"Name\": \"/aws/reference/secretsmanager/" + secret + "\", \"WithDecryption\": true}")+ .when().post("/")+ .then().statusCode(200)+ .body("Parameter.Value", equalTo("secret-value"));+ }++ /** A role under /team/ that its own account may assume, with {@code policy} inline. */+ private static void createRole(String role, String policy) {+ given().formParam("Action", "CreateRole").formParam("RoleName", role).formParam("Path", "/team/")+ .formParam("AssumeRolePolicyDocument", """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow",+ "Principal":{"AWS":"arn:aws:iam::%s:root"},"Action":"sts:AssumeRole"}]}""".formatted(ACCOUNT))+ .header("Authorization", auth(ACCOUNT, "iam")).when().post("/").then().statusCode(200);+ given().formParam("Action", "PutRolePolicy").formParam("RoleName", role).formParam("PolicyName", "p")+ .formParam("PolicyDocument", policy)+ .header("Authorization", auth(ACCOUNT, "iam")).when().post("/").then().statusCode(200);+ }++ private static Session assumeRole(String roleArn) {+ Response response = given().formParam("Action", "AssumeRole").formParam("RoleArn", roleArn)+ .formParam("RoleSessionName", "s")+ .header("Authorization", auth(ACCOUNT, "sts")).when().post("/");+ response.then().statusCode(200);+ return new Session(response.path("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId"),+ response.path("AssumeRoleResponse.AssumeRoleResult.Credentials.SessionToken"));+ }++ private static Response iamCall(Session session, String action) {+ return given().formParam("Action", action)+ .header("Authorization", auth(session.accessKeyId(), "iam"))+ .header("X-Amz-Security-Token", session.sessionToken())+ .when().post("/");+ }++ private static String auth(String accessKeyId, String service) {+ return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20261001/us-east-1/" + service+ + "/aws4_request, SignedHeaders=host, Signature=abc";+ }+}