From 0ed899bd591ea06838c0f26d5e036cdd0e4baa2a Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:46:34 -0400 Subject: [PATCH] fix(iam): give a role's tags to the policies an AssumeRole is checked against (#9474) IAM's stored lookup answered no tags, so a role or user was never given its aws:ResourceTag or iam:ResourceTag keys outside the IAM condition-key table's fromTarget route, and an AssumeRole saw none of the role's tags: a caller's policy allowing sts:AssumeRole on roles carrying a tag (the guide's "Assume roles that have a specific tag") matched no role, and a trust policy keyed on its own role's tags never matched. IamStoredResourceArns.storedTags now gives the tags of the user or role an ARN names, in the account it names, path included: the identity resources iam:ResourceTag reads ("the tag attached to the identity resource (user or role)"), which IAM and STS read aws:ResourceTag on alike. The trust policy of an AssumeRole, and of the role a Step Functions Lambda task assumes, is read with the role's tags under the keys the generated table gives the role type, through IamConditionContextResolver.resourceTagKeys, which resourceTags now shares. A resource-tag key the generated IAM condition-key table does not read for the action being checked is left out of its context (IamConditionContextResolver.resourceTags(action, resource), from IamConditionKeys.unreadTagPrefixes): the table reads none for iam:PassRole, AWS warning that ResourceTag conditions with PassRole "do not have reliable results", so a PassRole check still sees no role tags. --- docs/services/iam.md | 3 + docs/services/sts.md | 17 +++-- .../common/IamConditionContextResolver.java | 39 ++++++++++- .../aws/core/common/IamConditionKeys.java | 38 ++++++++++- .../aws/core/common/IamEnforcementFilter.java | 2 +- .../services/iam/IamStoredResourceArns.java | 50 +++++++++++++- .../aws/services/iam/StsQueryHandler.java | 4 ++ .../stepfunctions/LambdaTaskAuthorizer.java | 8 ++- .../IamConditionContextResolverTest.java | 30 ++++++++ ...IamPassRoleEnforcementIntegrationTest.java | 20 ++++++ .../iam/IamStoredResourceArnsTest.java | 29 +++++++- ...oleResourceEnforcementIntegrationTest.java | 68 ++++++++++++++++++- 12 files changed, 291 insertions(+), 17 deletions(-) diff --git a/docs/services/iam.md b/docs/services/iam.md index 57bff6ce74..8d7629ab4f 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -3743,6 +3743,9 @@ floci populates: the request account and the tags before any mutation. The table retains the source resource types so a secondary `RoleName`, such as on `AddRoleToInstanceProfile`, cannot supply the instance profile's tags. Missing targets carry no resource-tag values. + IAM's stored lookup answers the same tags for the user or role ARN a request is checked on, + in the account the ARN names, so `sts:AssumeRole`, which this table does not cover, sees the + role's tags too; on an IAM action both routes give the same values. Creation of the target, unsupported target types, and ARN/task-ID-based lookups are recorded in `notRead`. `PassRole` is a reasoned generator exception: the [IAM guide](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_tags.html) warns that diff --git a/docs/services/sts.md b/docs/services/sts.md index a4b1d6eca5..98cba85f97 100644 --- a/docs/services/sts.md +++ b/docs/services/sts.md @@ -590,13 +590,20 @@ absent, which is what the guide's own example policy tests with a `Null` conditi in the context of the caller's own identity-based policies, which is read from the generated `request-condition-keys.json`, and that file does not list the key for `sts:AssumeRole`. +The role's own tags are its `aws:ResourceTag/` and `iam:ResourceTag/` in both evaluations +of an `AssumeRole`: the caller's identity-based policies, checked on the role's ARN, and the role's +trust policy, which the session tags page has reading them ("you can allow the principal to pass +session tags only if the role they assume includes the specified tags"). The keys are the ones the +generated `resourceTagKeys` table gives the `role` type, and the tags are read from the role the ARN +names, in the account it names. A trust policy read for `AssumeRoleWithWebIdentity` or +`AssumeRoleWithSAML` does not see them. + One rule of the chain is not implemented. Transitive tags "replace matching ResourceTag values after the evaluation of the role trust policy", so a chained session's tag shadows the assumed role's tag -of that key. Floci publishes no `aws:ResourceTag/` for the role in either evaluation, so there -is no value for a transitive tag to replace: what has to come first is the role's own tags reaching -those contexts. The guide's example also says a session tag naming the role tag of an earlier link -fails, which does not follow from the published rule, that tag being nothing the earlier session -passed down, so what is built here is the rule the API Reference states. +of that key; Floci evaluates the role's own tag. The guide's example also says a session tag naming +the role tag of an earlier link fails, which does not follow from the published rule, that tag +being nothing the earlier session passed down, so what is built here is the rule the API Reference +states. ### Known limitations diff --git a/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java b/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java index 0c8304db26..4c0e78afd7 100644 --- a/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java +++ b/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java @@ -183,8 +183,43 @@ public class IamConditionContextResolver { Map> types = RequestResourceMembers.table().resourceTagKeys() .getOrDefault(namespace, Map.of()); StoredResourceArns stored = types.isEmpty() ? null : storedResourceArns(namespace); - Map tags = stored == null ? Map.of() : stored.storedTags(resource); - List prefixes = tags.isEmpty() ? List.of() : resourceTagPrefixes(namespace, resource, types); + return resourceTagKeys(resource, stored == null ? Map.of() : stored.storedTags(resource)); + } + + /** + * The condition keys {@link #resourceTags(String)} gives the resource {@code resource} names, as a request for + * {@code action} reads them: without the keys the generated IAM condition-key table does not read for the action + * (it reads no resource tag for {@code iam:PassRole}). Null when none is left. + */ + public Map> resourceTags(String action, String resource) { + Map> tags = resourceTags(resource); + Set unread = IamConditionKeys.unreadTagPrefixes(action); + if (tags == null || unread.isEmpty()) { + return tags; + } + Map> read = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + tags.forEach((key, values) -> { + if (unread.stream().noneMatch(prefix -> key.regionMatches(true, 0, prefix, 0, prefix.length()))) { + read.put(key, values); + } + }); + return read.isEmpty() ? null : read; + } + + /** + * The condition keys {@code tags}, the tags of the resource {@code resource} names, give it: each resource-tag key + * the request-resources table gives the ARN's type for each tag, as {@link #resourceTags} gives them for the tags a + * service holds, for a caller that holds the resource itself (the role a trust policy belongs to). Null when the + * table gives the type no such keys or there are no tags. + */ + public static Map> resourceTagKeys(String resource, Map tags) { + if (!AwsArnUtils.isArn(resource) || tags == null || tags.isEmpty()) { + return null; + } + String namespace = AwsArnUtils.parse(resource).service(); + Map> types = RequestResourceMembers.table().resourceTagKeys() + .getOrDefault(namespace, Map.of()); + List prefixes = types.isEmpty() ? List.of() : resourceTagPrefixes(namespace, resource, types); if (prefixes.isEmpty()) { return null; } diff --git a/src/main/java/io/floci/aws/core/common/IamConditionKeys.java b/src/main/java/io/floci/aws/core/common/IamConditionKeys.java index 21ae27043a..af6738e56c 100644 --- a/src/main/java/io/floci/aws/core/common/IamConditionKeys.java +++ b/src/main/java/io/floci/aws/core/common/IamConditionKeys.java @@ -3,8 +3,10 @@ package io.floci.aws.core.common; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; +import java.util.Set; import java.util.function.Function; import java.util.regex.Pattern; @@ -25,7 +27,10 @@ final class IamConditionKeys { private record Table(Map> members, Map> targets, Map> resources, - Map> requestTags) {} + Map> requestTags, + Map> unreadTagPrefixes) {} + + private static final String TAG_KEY = "${TagKey}"; private static final Table TABLE = VendoredResources.read( "aws/iam-condition-keys.json", "IAM condition keys", input -> { @@ -37,7 +42,8 @@ final class IamConditionKeys { RequestResourceMembers.pattern(text(entry, "arn")))), section(document.path("requestTags"), entry -> new RequestTags(text(entry, "member"), entry.has("keyMember") ? text(entry, "keyMember") : null, - entry.has("keyMember") ? text(entry, "valueMember") : null))); + entry.has("keyMember") ? text(entry, "valueMember") : null)), + unreadTagPrefixes(document.path("notRead"))); }); private IamConditionKeys() {} @@ -55,6 +61,25 @@ final class IamConditionKeys { return Map.copyOf(byAction); } + /** + * For each action, the prefixes of the tag keys the table does not read for it ({@code aws:ResourceTag/} for a + * {@code notRead} entry on {@code aws:ResourceTag/${TagKey}}). + */ + private static Map> unreadTagPrefixes(JsonNode entries) { + Map> byAction = new LinkedHashMap<>(); + if (entries.isArray()) { + for (JsonNode entry : entries) { + String key = text(entry, "key"); + if (key.endsWith(TAG_KEY)) { + byAction.computeIfAbsent(text(entry, "action"), action -> new HashSet<>()) + .add(key.substring(0, key.length() - TAG_KEY.length())); + } + } + } + byAction.replaceAll((action, prefixes) -> Set.copyOf(prefixes)); + return Map.copyOf(byAction); + } + private static String text(JsonNode entry, String field) { if (!entry.path(field).isTextual()) { throw new IllegalStateException("Malformed IAM condition key entry: " + entry); @@ -86,4 +111,13 @@ final class IamConditionKeys { static Map requestTags(String action) { return TABLE.requestTags().getOrDefault(action, Map.of()); } + + /** + * The prefixes of the tag keys ({@code aws:ResourceTag/}, {@code iam:ResourceTag/}) the table does not read for + * {@code action}: {@code iam:PassRole}'s resource-tag keys, AWS warning that ResourceTag conditions with PassRole + * "do not have reliable results". Empty when it reads them all. + */ + static Set unreadTagPrefixes(String action) { + return action == null ? Set.of() : TABLE.unreadTagPrefixes().getOrDefault(action, Set.of()); + } } diff --git a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java index c20c97f632..1aefe72cbe 100644 --- a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java @@ -1266,7 +1266,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter { credentialScope, operationAction, resource, region, accountId, targetContext); } taggedContext = IamConditionContextResolver.withResourceTags(taggedContext, - conditionContextResolver.resourceTags(resource)); + conditionContextResolver.resourceTags(action, resource)); taggedContext = IamConditionContextResolver.withResourceTags(taggedContext, conditionContextResolver.resourceKeys(action, resource)); Map> effectiveContext = IamConditionContextResolver.withGlobalContext( diff --git a/src/main/java/io/floci/aws/services/iam/IamStoredResourceArns.java b/src/main/java/io/floci/aws/services/iam/IamStoredResourceArns.java index 4c6162351d..0722e11356 100644 --- a/src/main/java/io/floci/aws/services/iam/IamStoredResourceArns.java +++ b/src/main/java/io/floci/aws/services/iam/IamStoredResourceArns.java @@ -13,14 +13,15 @@ import jakarta.enterprise.inject.Instance; import jakarta.inject.Inject; import java.util.List; +import java.util.Map; import java.util.Optional; /** * What IAM asks of its own resources a request names: the ARN a user, group, role, instance profile or server * certificate a name names is stored under, its path included, which the name alone does not carry; the user an access * key, an SSH public key or a service-specific credential belongs to; the role a service-linked role deletion task - * deleted; the user who signs a request; and what a delegation request records, which is the owner the condition key - * the Service Reference publishes on that type is evaluated against. + * deleted; the user who signs a request; what a delegation request records, which is the owner the condition key + * the Service Reference publishes on that type is evaluated against; and the tags of a user or a role. * *

Both stores are reached lazily, through providers, rather than injected: the enforcement filter that asks is not a * dependency of {@link IamService}, and the delegation store is reached through {@link DelegationRequestOwnership}, as @@ -142,4 +143,49 @@ public class IamStoredResourceArns implements StoredResourceArns { } return delegationRequests.get().ownerArnOf(parsed.accountId(), id); } + + /** + * {@inheritDoc} + * + *

The tags of the user or role the ARN names, in the account the ARN names, path included: the identity resources + * {@code iam:ResourceTag} reads, "the tag attached to the identity resource (user or role)", which IAM and STS read + * {@code aws:ResourceTag} on alike. So a policy on {@code sts:AssumeRole} or {@code iam:DeleteUser} keyed on the + * tags of the role or user it names sees them. Any other ARN, and one whose path is not the stored one, names none. + */ + @Override + public Map storedTags(String arn) { + if (!AwsArnUtils.isArn(arn) || iamService.isUnsatisfied()) { + return Map.of(); + } + AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); + String resource = parsed.resource(); + if (!"iam".equals(parsed.service())) { + return Map.of(); + } + IamService iam = iamService.get(); + String name = resource.substring(resource.lastIndexOf('/') + 1); + Optional> tags; + if (resource.startsWith("role/")) { + tags = iam.findRole(parsed.accountId(), name) + .filter(role -> IamService.roleArnMatches(arn, role)) + .map(IamRole::getTags); + } else if (resource.startsWith("user/")) { + tags = iam.findUser(parsed.accountId(), name) + .filter(user -> namesTheSameResource(parsed, user.getArn())) + .map(IamUser::getTags); + } else { + tags = Optional.empty(); + } + return tags.map(Map::copyOf).orElse(Map.of()); + } + + /** Whether {@code stored} is an ARN of the account, Region and resource {@code requested} names, as a role's is matched. */ + private static boolean namesTheSameResource(AwsArnUtils.Arn requested, String stored) { + if (!AwsArnUtils.isArn(stored)) { + return false; + } + AwsArnUtils.Arn held = AwsArnUtils.parse(stored); + return requested.accountId().equals(held.accountId()) && requested.region().equals(held.region()) + && requested.resource().equals(held.resource()); + } } diff --git a/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java b/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java index 78ecc0a552..6f9eb11ce3 100644 --- a/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java +++ b/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java @@ -558,6 +558,10 @@ public class StsQueryHandler { if (!requestedTransitiveKeys.isEmpty()) { trustContext.put("sts:TransitiveTagKeys", requestedTransitiveKeys); } + // A trust policy reads the tags of its own role as aws:ResourceTag: "you can allow the principal + // to pass session tags only if the role they assume includes the specified tags". + trustContext = IamConditionContextResolver.withResourceTags(trustContext, + IamConditionContextResolver.resourceTagKeys(roleArn, role.getTags())); if (!trustPolicyEvaluator.allows(role.getAssumeRolePolicyDocument(), caller, callerAccount, trustContext)) { return AwsQueryResponse.error("AccessDenied", diff --git a/src/main/java/io/floci/aws/services/stepfunctions/LambdaTaskAuthorizer.java b/src/main/java/io/floci/aws/services/stepfunctions/LambdaTaskAuthorizer.java index 5f87d34d2e..538140836e 100644 --- a/src/main/java/io/floci/aws/services/stepfunctions/LambdaTaskAuthorizer.java +++ b/src/main/java/io/floci/aws/services/stepfunctions/LambdaTaskAuthorizer.java @@ -209,9 +209,11 @@ public class LambdaTaskAuthorizer { AwsArnUtils.Arn callerId = AwsArnUtils.parse(callerRoleArn); String roleAccount = AwsArnUtils.parse(targetRoleArn).accountId(); List> scpLevels = access.scpLevels(callerId.accountId()); - Map> context = IamConditionContextResolver.withGlobalContext( - Map.of("aws:PrincipalArn", List.of(callerRoleArn), "sts:ExternalId", List.of(stateMachineArn)), - targetRoleArn, AwsArnUtils.parse(stateMachineArn).region(), callerId.accountId(), roleAccount); + Map> context = IamConditionContextResolver.withResourceTags( + IamConditionContextResolver.withGlobalContext( + Map.of("aws:PrincipalArn", List.of(callerRoleArn), "sts:ExternalId", List.of(stateMachineArn)), + targetRoleArn, AwsArnUtils.parse(stateMachineArn).region(), callerId.accountId(), roleAccount), + IamConditionContextResolver.resourceTagKeys(targetRoleArn, target.get().getTags())); // Step Functions assumes the execution role on the state machine's behalf, so the caller // is a session of it and carries AssumedRole as its aws:PrincipalType. That path mints no diff --git a/src/test/java/io/floci/aws/core/common/IamConditionContextResolverTest.java b/src/test/java/io/floci/aws/core/common/IamConditionContextResolverTest.java index a7feb23573..8677edcbbd 100644 --- a/src/test/java/io/floci/aws/core/common/IamConditionContextResolverTest.java +++ b/src/test/java/io/floci/aws/core/common/IamConditionContextResolverTest.java @@ -1014,6 +1014,34 @@ class IamConditionContextResolverTest { assertEquals(List.of("requested"), context.get("aws:RequestTag/Team")); } + @Test + void aRolesTagsAreNotReadForPassRole() { + // The generated IAM condition-key table reads no resource tag for iam:PassRole: AWS warns that + // ResourceTag conditions with it "do not have reliable results". sts:AssumeRole reads both keys. + String role = "arn:aws:iam::123456789012:role/app"; + IamConditionContextResolver reading = resolverReading(new StoredResourceArns() { + @Override + public String namespace() { + return "iam"; + } + + @Override + public Optional find(String type, List names, String region) { + return Optional.empty(); + } + + @Override + public Map storedTags(String arn) { + return role.equals(arn) ? Map.of("Project", "Alpha") : Map.of(); + } + }); + + assertNull(reading.resourceTags("iam:PassRole", role)); + Map> assumed = reading.resourceTags("sts:AssumeRole", role); + assertEquals(List.of("Alpha"), assumed.get("aws:ResourceTag/Project")); + assertEquals(List.of("Alpha"), assumed.get("iam:ResourceTag/Project")); + } + @Test void resourceTagsAreTheGeneratedKeysOfTheArnsTypeValuedFromItsServicesStoredTags() { String secret = "arn:aws:secretsmanager:eu-west-1:123456789012:secret:app-AbCdEf"; @@ -1038,6 +1066,8 @@ class IamConditionContextResolverTest { }); Map> tags = reading.resourceTags(secret); + // An action the IAM condition-key table reads every key for sees the same keys. + assertEquals(tags, reading.resourceTags("secretsmanager:GetSecretValue", secret)); assertEquals(2, tags.size()); assertEquals(List.of("prod", "dev"), tags.get("aws:ResourceTag/Environment")); assertEquals(List.of("prod", "dev"), tags.get("secretsmanager:resourcetag/environment")); diff --git a/src/test/java/io/floci/aws/services/iam/IamPassRoleEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamPassRoleEnforcementIntegrationTest.java index adc40fa7c3..e8d516820d 100644 --- a/src/test/java/io/floci/aws/services/iam/IamPassRoleEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamPassRoleEnforcementIntegrationTest.java @@ -98,6 +98,26 @@ class IamPassRoleEnforcementIntegrationTest { .delete("/2015-03-31/functions/{name}", name)); } + @Test + void aPassRoleGrantKeyedOnTheRolesTagIsNotSatisfiedByTheTag() { + // The IAM guide warns that ResourceTag conditions with PassRole "do not have reliable results", so the + // generated condition-key table reads no resource tag for it: a role carrying the tag does not pass. + String role = role("fn-tagged"); + String roleName = role.substring(role.lastIndexOf('/') + 1); + admin("iam").formParam("Action", "TagRole").formParam("RoleName", roleName) + .formParam("Tags.member.1.Key", "Project").formParam("Tags.member.1.Value", "Alpha") + .post("/").then().statusCode(200); + User user = user("passrole-tagged"); + String name = "passrole-tagged-fn-" + suffix(); + String body = """ + {"FunctionName":"%s","Runtime":"nodejs20.x","Handler":"index.handler","Role":"%s"}""" + .formatted(name, role); + + user.policy(allow("lambda:CreateFunction", "*") + ",{\"Effect\":\"Allow\",\"Action\":\"iam:PassRole\"," + + "\"Resource\":\"*\",\"Condition\":{\"StringEquals\":{\"iam:ResourceTag/Project\":\"Alpha\"}}}"); + denied(user.lambda().body(body).post("/2015-03-31/functions").then()); + } + @Test void updatingAFunctionNeedsPassRoleOnlyWhenItSetsTheRole() { String first = role("fn-first"); diff --git a/src/test/java/io/floci/aws/services/iam/IamStoredResourceArnsTest.java b/src/test/java/io/floci/aws/services/iam/IamStoredResourceArnsTest.java index 613451f293..e108a6bcca 100644 --- a/src/test/java/io/floci/aws/services/iam/IamStoredResourceArnsTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamStoredResourceArnsTest.java @@ -11,6 +11,7 @@ import org.junit.jupiter.api.Test; import java.security.KeyPairGenerator; import java.security.interfaces.RSAPublicKey; import java.util.List; +import java.util.Map; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -19,7 +20,8 @@ import static org.mockito.Mockito.when; /** * What IAM gives the request-resources table of its own resources: the ARN a name names, path included, the user a key - * or a credential belongs to, the role a deletion task deleted and the user who signs a request. + * or a credential belongs to, the role a deletion task deleted, the user who signs a request and the tags of a user or + * a role. */ class IamStoredResourceArnsTest { @@ -61,6 +63,31 @@ class IamStoredResourceArnsTest { assertEquals(Optional.empty(), stored.find("policy", List.of("bob"), "")); } + @Test + void aUserOrARoleGivesTheTagsItCarries() { + iam.createUser("bob", "/team/"); + iam.tagUser("bob", Map.of("status", "terminated")); + iam.createRole("app", "/service-role/", TRUST_POLICY, null, 0, null); + iam.tagRole("app", Map.of("Project", "Alpha")); + assertEquals(Map.of("status", "terminated"), stored.storedTags("arn:aws:iam::000000000000:user/team/bob")); + assertEquals(Map.of("Project", "Alpha"), stored.storedTags("arn:aws:iam::000000000000:role/service-role/app")); + // A role's ARN in another partition names the same role, as STS takes it. + assertEquals(Map.of("Project", "Alpha"), + stored.storedTags("arn:aws-cn:iam::000000000000:role/service-role/app")); + } + + @Test + void anArnNamingNoStoredUserOrRoleGivesNoTags() { + iam.createRole("app", "/service-role/", TRUST_POLICY, null, 0, null); + iam.tagRole("app", Map.of("Project", "Alpha")); + // Another path, another account and another type name none. + assertEquals(Map.of(), stored.storedTags("arn:aws:iam::000000000000:role/app")); + assertEquals(Map.of(), stored.storedTags("arn:aws:iam::111111111111:role/service-role/app")); + assertEquals(Map.of(), stored.storedTags("arn:aws:iam::000000000000:instance-profile/service-role/app")); + assertEquals(Map.of(), stored.storedTags("arn:aws:s3:::app")); + assertEquals(Map.of(), stored.storedTags("not-an-arn")); + } + @Test void aKeyOrACredentialNamesTheUserItBelongsTo() { iam.createUser("bob", "/team/"); diff --git a/src/test/java/io/floci/aws/services/iam/StsAssumeRoleResourceEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/StsAssumeRoleResourceEnforcementIntegrationTest.java index 5e71a2f9f8..a87916c23d 100644 --- a/src/test/java/io/floci/aws/services/iam/StsAssumeRoleResourceEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/StsAssumeRoleResourceEnforcementIntegrationTest.java @@ -8,6 +8,7 @@ import io.quarkus.test.common.http.TestHTTPResource; import io.quarkus.test.junit.QuarkusTest; import io.quarkus.test.junit.TestProfile; import io.restassured.response.Response; +import io.restassured.specification.RequestSpecification; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -25,7 +26,9 @@ import static org.hamcrest.Matchers.not; * With {@code iam.enforcement-enabled=true}, {@code sts:AssumeRole} is authorized against the role it * names, in the account its ARN names, so an identity policy can allow assuming one role and not another * (IAM User Guide, "Granting a user permissions to switch roles": the policy's Resource is the role's ARN), - * and {@code sts:GetFederationToken} against the federated user its name names. + * and {@code sts:GetFederationToken} against the federated user its name names. The role's tags are its + * {@code aws:ResourceTag} and {@code iam:ResourceTag} keys, in the caller's policy and in the role's own trust + * policy. */ @QuarkusTest @TestProfile(IamEnforcementProfile.class) @@ -33,6 +36,9 @@ class StsAssumeRoleResourceEnforcementIntegrationTest { private static final String ACCOUNT = "111111111111"; private static final String OTHER_ACCOUNT = "222222222222"; + private static final String LIST_USERS = """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"iam:ListUsers","Resource":"*"}]}"""; @TestHTTPResource URI baseUri; @@ -142,6 +148,66 @@ class StsAssumeRoleResourceEnforcementIntegrationTest { .then().statusCode(not(200)).body(not(containsString("AccessKeyId"))); } + @Test + void aPolicyKeyedOnARolesTagAllowsAssumingOnlyARoleCarryingIt() { + // IAM User Guide, "IAM: Assume roles that have a specific tag": a user may assume any role whose + // iam:ResourceTag/Project is ExampleCorpABC. + String suffix = UUID.randomUUID().toString().substring(0, 8); + String taggedArn = createRole("tagged-" + suffix); + tagRole("tagged-" + suffix, "Project", "ExampleCorpABC"); + String untaggedArn = createRole("untagged-" + suffix); + String user = "tag-caller-" + suffix; + String iamAuth = auth(ACCOUNT, "iam"); + UserCredentials caller = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), iamAuth, user); + EnforcementFixtures.putUserPolicy(baseUri.getPort(), iamAuth, user, "assume", """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole","Resource":"*", + "Condition":{"StringEquals":{"iam:ResourceTag/Project":"ExampleCorpABC"}}}]}"""); + + assumeRole(caller, taggedArn).then().statusCode(200); + assumeRole(caller, untaggedArn).then().statusCode(403); + } + + @Test + void aTrustPolicyKeyedOnItsRolesTagAllowsAssumingOnlyARoleCarryingIt() { + // A trust policy reads the tags of its own role as aws:ResourceTag. + String suffix = UUID.randomUUID().toString().substring(0, 8); + String trust = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Principal":{"AWS":"arn:aws:iam::%s:root"},"Action":"sts:AssumeRole", + "Condition":{"StringEquals":{"aws:ResourceTag/Team":"Blue"}}}]}""".formatted(ACCOUNT); + String blueArn = EnforcementFixtures.createRole(cleanup, baseUri.getPort(), ACCOUNT, "/", "blue-" + suffix, + trust, LIST_USERS); + tagRole("blue-" + suffix, "Team", "Blue"); + String redArn = EnforcementFixtures.createRole(cleanup, baseUri.getPort(), ACCOUNT, "/", "red-" + suffix, + trust, LIST_USERS); + tagRole("red-" + suffix, "Team", "Red"); + String user = "trust-tag-caller-" + suffix; + String iamAuth = auth(ACCOUNT, "iam"); + UserCredentials caller = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), iamAuth, user); + EnforcementFixtures.putUserPolicy(baseUri.getPort(), iamAuth, user, "assume", """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"sts:AssumeRole","Resource":"*"}]}"""); + + assumeRole(caller, blueArn).then().statusCode(200); + assumeRole(caller, redArn).then().statusCode(403); + } + + private void tagRole(String role, String key, String value) { + iamCall(auth(ACCOUNT, "iam"), "TagRole", "RoleName", role, "Tags.member.1.Key", key, + "Tags.member.1.Value", value).then().statusCode(200); + } + + private Response iamCall(String authorization, String action, String... parameters) { + RequestSpecification request = given().port(baseUri.getPort()) + .contentType("application/x-www-form-urlencoded") + .header("Authorization", authorization) + .formParam("Action", action); + for (int index = 0; index < parameters.length; index += 2) { + request = request.formParam(parameters[index], parameters[index + 1]); + } + return request.when().post("/"); + } + private String createRole(String role) { return EnforcementFixtures.createRole(cleanup, baseUri.getPort(), ACCOUNT, "/", role, """ {"Version":"2012-10-17","Statement":[