fix(iam): read the role's tags in federated and service trust policies (#9486)

A role's trust policy read for AssumeRoleWithWebIdentity or
AssumeRoleWithSAML, or when a service assumes the role, never saw the
role's own tags: a condition on aws:ResourceTag/<key> or
iam:ResourceTag/<key> matched nothing, so a trust policy allowing an
assume only onto roles carrying a tag refused every one, and one denying
it onto such roles never applied. AssumeRole has read them since the
role's stored tags were given to its trust policy; these paths run their
own condition reading and were left out.

Each of those assumes acts on the role, which the Service Authorization
Reference gives aws:ResourceTag/${TagKey} and iam:ResourceTag/${TagKey},
and the global condition keys page has aws:ResourceTag in the request
context "when the requested resource already has attached tags". The
web identity and SAML evaluators now read the role's tags, under the keys
the generated resourceTagKeys table gives the role type, beside the
token's claims or the assertion's attributes, a tag key matched whatever
its case. A service's assume reads them through a new
AssumeRolePolicyEvaluator.allowsService taking the role, which the
service-role authorizer, the AppSync data source authorizer, Step
Functions' Lambda and API Gateway tasks and the Lambda web adapter's
execution role now use, beside the service's principal and source keys.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-25 22:26:18 -04:00
1 parent 952667294d
commit fb658f01ee
19 files changed
+241 -52

No files matched your search

+6 -1
View File
@@ -596,7 +596,12 @@ trust policy, which the session tags page has reading them ("you can allow the p
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.
`AssumeRoleWithSAML` sees them too, under the same keys, beside the token's or the assertion's own:
the role is the resource each of those actions acts on, which the Service Authorization Reference gives
those keys, and `aws:ResourceTag` is in the request context "when the requested resource already has
attached tags". So does the trust policy read when a service assumes the role on a caller's behalf (a
Step Functions execution role, the role an EventBridge target or an AppSync data source runs as, a Lambda
web adapter's execution role), beside the service's own principal and source keys.
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
@@ -95,8 +95,7 @@ public class AppSyncDataSourceAuthorizer {
throw denied(dataSource, "service role does not exist");
}
String servicePrincipal = ServicePrincipals.of("appsync");
if (!trustEvaluator.allowsService(role.get().getAssumeRolePolicyDocument(),
servicePrincipal, sourceArn, sourceAccount)) {
if (!trustEvaluator.allowsService(role.get(), servicePrincipal, sourceArn, sourceAccount)) {
throw denied(dataSource, "service role does not trust " + servicePrincipal);
}
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.IamConditionContextResolver;
import io.floci.aws.core.common.ServicePrincipals;
import io.floci.aws.services.iam.model.IamRole;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
@@ -296,6 +297,22 @@ public class AssumeRolePolicyEvaluator {
*/
public boolean allowsService(String trustPolicyDocument, String servicePrincipal,
String sourceArn, String sourceAccount) {
return allowsService(trustPolicyDocument, servicePrincipal, sourceArn, sourceAccount, null);
}
/**
* As {@link #allowsService(String, String, String, String)}, for the role the service assumes: its trust policy,
* read with the role's tags under the keys the generated table gives its type ({@code aws:ResourceTag/<key>},
* {@code iam:ResourceTag/<key>}), as every assume of the role reads them, the role being the resource
* {@code sts:AssumeRole} acts on.
*/
public boolean allowsService(IamRole role, String servicePrincipal, String sourceArn, String sourceAccount) {
return allowsService(role.getAssumeRolePolicyDocument(), servicePrincipal, sourceArn, sourceAccount,
IamConditionContextResolver.resourceTagKeys(role.getArn(), role.getTags()));
}
private boolean allowsService(String trustPolicyDocument, String servicePrincipal, String sourceArn,
String sourceAccount, Map<String, List<String>> roleTags) {
if (trustPolicyDocument == null || trustPolicyDocument.isBlank()) {
return false;
}
@@ -311,8 +328,9 @@ public class AssumeRolePolicyEvaluator {
return false;
}
String version = root.path("Version").asText(null);
Map<String, List<String>> context = IamConditionContextResolver.serviceCallContext(
servicePrincipal, null, null, sourceArn, sourceAccount);
Map<String, List<String>> context = IamConditionContextResolver.withResourceTags(
IamConditionContextResolver.serviceCallContext(servicePrincipal, null, null, sourceArn, sourceAccount),
roleTags);
boolean allow = false;
if (statements.isArray()) {
for (JsonNode statement : statements) {
@@ -23,11 +23,13 @@ public class SAMLTrustPolicyEvaluator {
/**
* {@code roleSessionName} is the assertion's {@code RoleSessionName} attribute, which a policy
* reads as {@code sts:RoleSessionName}, or null when the assertion carries none.
* reads as {@code sts:RoleSessionName}, or null when the assertion carries none. {@code roleTags}
* holds the tags of the role being assumed under the keys the generated table gives its type
* ({@code aws:ResourceTag/<key>}, {@code iam:ResourceTag/<key>}), which a policy reads on it.
*/
public boolean allows(String document, String providerArn, Map<String, List<String>> claims,
String roleSessionName) {
return allows(SAML_ACTION, document, providerArn, claims, roleSessionName);
String roleSessionName, Map<String, List<String>> roleTags) {
return allows(SAML_ACTION, document, providerArn, claims, roleSessionName, roleTags);
}
/**
@@ -35,13 +37,14 @@ public class SAMLTrustPolicyEvaluator {
* the same document with the same principal and the same conditions as the assume itself.
*/
public boolean allowsTagging(String document, String providerArn, Map<String, List<String>> claims,
String roleSessionName) {
String roleSessionName, Map<String, List<String>> roleTags) {
return allows(AssumeRolePolicyEvaluator.TAG_SESSION_ACTION, document, providerArn, claims,
roleSessionName);
roleSessionName, roleTags);
}
private boolean allows(String action, String document, String providerArn,
Map<String, List<String>> claims, String roleSessionName) {
Map<String, List<String>> claims, String roleSessionName,
Map<String, List<String>> roleTags) {
try {
JsonNode statements = mapper.readTree(document).path("Statement");
if (!TrustPolicyStatements.wellFormed(statements)) {
@@ -50,7 +53,7 @@ public class SAMLTrustPolicyEvaluator {
if (statements.isArray()) {
boolean allowed = false;
for (JsonNode statement : statements) {
int result = evaluate(action, statement, providerArn, claims, roleSessionName);
int result = evaluate(action, statement, providerArn, claims, roleSessionName, roleTags);
if (result < 0) {
return false;
}
@@ -61,23 +64,24 @@ public class SAMLTrustPolicyEvaluator {
return allowed;
}
return statements.isObject()
&& evaluate(action, statements, providerArn, claims, roleSessionName) > 0;
&& evaluate(action, statements, providerArn, claims, roleSessionName, roleTags) > 0;
} catch (Exception e) {
return false;
}
}
private int evaluate(String action, JsonNode statement, String providerArn,
Map<String, List<String>> claims, String roleSessionName) {
Map<String, List<String>> claims, String roleSessionName,
Map<String, List<String>> roleTags) {
if (!actionApplies(statement, action) || !principal(statement.path("Principal"), providerArn)
|| !conditionsSatisfied(statement.get("Condition"), claims, roleSessionName)) {
|| !conditionsSatisfied(statement.get("Condition"), claims, roleSessionName, roleTags)) {
return 0;
}
return TrustPolicyStatements.denies(statement) ? -1 : 1;
}
private boolean conditionsSatisfied(JsonNode condition, Map<String, List<String>> claims,
String roleSessionName) {
String roleSessionName, Map<String, List<String>> roleTags) {
if (condition == null || condition.isNull()) {
return true;
}
@@ -93,7 +97,8 @@ public class SAMLTrustPolicyEvaluator {
Iterator<Map.Entry<String, JsonNode>> entries = operator.getValue().fields();
while (entries.hasNext()) {
Map.Entry<String, JsonNode> entry = entries.next();
List<String> actual = conditionValues(entry.getKey(), claims, roleSessionName);
List<String> actual = TrustPolicyStatements.roleValues(entry.getKey(), roleTags)
.orElseGet(() -> conditionValues(entry.getKey(), claims, roleSessionName));
List<String> expected = entry.getValue().isArray()
? StreamSupport.stream(entry.getValue().spliterator(), false)
.filter(JsonNode::isTextual).map(JsonNode::asText).toList()
@@ -80,7 +80,7 @@ public class ServiceRoleAuthorizer {
if (role.isEmpty()) {
return Optional.of("The role " + roleArn + " does not exist.");
}
if (!trustEvaluator.allowsService(role.get().getAssumeRolePolicyDocument(), servicePrincipal,
if (!trustEvaluator.allowsService(role.get(), servicePrincipal,
sourceArn, accountId)) {
return Optional.of("The role " + roleArn + " does not trust " + servicePrincipal + ".");
}
@@ -884,15 +884,16 @@ public class StsQueryHandler {
"sub", List.of(claims.subject()),
"aud", claims.audiences());
Map<String, List<String>> roleTags = roleTagKeys(role.get());
if (!webIdentityTrustEvaluator.allows(role.get().getAssumeRolePolicyDocument(),
oidcProviderArn, issuerKeyPrefix, conditionClaims, sessionName)) {
oidcProviderArn, issuerKeyPrefix, conditionClaims, sessionName, roleTags)) {
LOG.debugv("Trust policy on role {0} denies web identity subject {1}",
roleArn, claims.subject());
return WebIdentityOutcome.deny(accessDenied("sts:AssumeRoleWithWebIdentity", roleArn));
}
if (!claims.principalTags().isEmpty()
&& !webIdentityTrustEvaluator.allowsTagging(role.get().getAssumeRolePolicyDocument(),
oidcProviderArn, issuerKeyPrefix, conditionClaims, sessionName)) {
oidcProviderArn, issuerKeyPrefix, conditionClaims, sessionName, roleTags)) {
LOG.debugv("Trust policy on role {0} does not permit tagging the session of subject {1}",
roleArn, claims.subject());
return WebIdentityOutcome.deny(
@@ -921,6 +922,15 @@ public class StsQueryHandler {
}
}
/**
* The tags of the role being assumed under the keys the generated table gives its type, as a trust policy reads
* them on that role; empty for a role with none.
*/
private static Map<String, List<String>> roleTagKeys(IamRole role) {
Map<String, List<String>> keys = IamConditionContextResolver.resourceTagKeys(role.getArn(), role.getTags());
return keys == null ? Map.of() : keys;
}
private static String assumedRoleId(IamRole role, String sessionName) {
String roleId = (role != null && role.getRoleId() != null) ? role.getRoleId() : ("AROA" + randomId(16));
return roleId + ":" + sessionName;
@@ -995,13 +1005,14 @@ public class StsQueryHandler {
"iss", List.of(verified.issuer()),
"sub", List.of(verified.subject()),
"namequalifier", List.of(verified.nameQualifier()));
Map<String, List<String>> roleTags = roleTagKeys(role);
if (!samlTrustEvaluator.allows(role.getAssumeRolePolicyDocument(), principalArn, assertionClaims,
verified.roleSessionName())) {
verified.roleSessionName(), roleTags)) {
throw new AwsException("AccessDenied", "Not authorized to perform sts:AssumeRoleWithSAML on resource: " + roleArn, 403);
}
if (!verified.principalTags().isEmpty()
&& !samlTrustEvaluator.allowsTagging(role.getAssumeRolePolicyDocument(), principalArn,
assertionClaims, verified.roleSessionName())) {
assertionClaims, verified.roleSessionName(), roleTags)) {
throw new AwsException("AccessDenied", "Not authorized to perform "
+ AssumeRolePolicyEvaluator.TAG_SESSION_ACTION + " on resource: " + roleArn, 403);
}
@@ -2,6 +2,10 @@ package io.floci.aws.services.iam;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* How a role's trust policy statements are read, the same way on every path that assumes the role:
* {@code sts:AssumeRole}, {@code sts:AssumeRoleWithWebIdentity} and {@code sts:AssumeRoleWithSAML}.
@@ -32,6 +36,19 @@ final class TrustPolicyStatements {
return validStatement(statements);
}
/**
* The values a condition key reads from the role being assumed: its tags, given under the keys the generated table
* gives the role's type ({@code aws:ResourceTag/<key>}, {@code iam:ResourceTag/<key>}), a key matched whatever its
* case, as AWS matches a tag key; empty for a key the role gives no value under.
*/
static Optional<List<String>> roleValues(String conditionKey, Map<String, List<String>> roleTags) {
if (conditionKey == null || roleTags == null) {
return Optional.empty();
}
return roleTags.entrySet().stream().filter(entry -> entry.getKey().equalsIgnoreCase(conditionKey))
.map(Map.Entry::getValue).findFirst();
}
/** True when a statement of a {@linkplain #wellFormed well-formed} document is a {@code Deny}. */
static boolean denies(JsonNode statement) {
return "Deny".equals(statement.path("Effect").asText());
@@ -50,13 +50,17 @@ public class WebIdentityTrustPolicyEvaluator {
* <p>{@code claims} holds the OIDC condition context keyed <em>without</em> the provider
* prefix — {@code sub}, {@code aud} — which this evaluator resolves against policy keys of the
* form {@code <provider-host-and-path>:sub}. {@code roleSessionName} is the request's
* {@code RoleSessionName}, which a policy reads as {@code sts:RoleSessionName}. An explicit
* {@code RoleSessionName}, which a policy reads as {@code sts:RoleSessionName}. {@code roleTags} holds
* the tags of the role being assumed under the keys the generated table gives its type
* ({@code aws:ResourceTag/<key>}, {@code iam:ResourceTag/<key>}), which a policy reads on it as on the
* resource of the request, as AWS includes them when the resource already has tags. An explicit
* {@code Deny} wins over any {@code Allow}, per AWS precedence.
*/
public boolean allows(String trustPolicyDocument, String oidcProviderArn, String issuerKeyPrefix,
Map<String, List<String>> claims, String roleSessionName) {
Map<String, List<String>> claims, String roleSessionName,
Map<String, List<String>> roleTags) {
return allows(WEB_IDENTITY_ACTION, trustPolicyDocument, oidcProviderArn, issuerKeyPrefix, claims,
roleSessionName);
roleSessionName, roleTags);
}
/**
@@ -64,14 +68,15 @@ public class WebIdentityTrustPolicyEvaluator {
* same document with the same principal and the same conditions as the assume itself.
*/
public boolean allowsTagging(String trustPolicyDocument, String oidcProviderArn, String issuerKeyPrefix,
Map<String, List<String>> claims, String roleSessionName) {
Map<String, List<String>> claims, String roleSessionName,
Map<String, List<String>> roleTags) {
return allows(TAG_SESSION_ACTION, trustPolicyDocument, oidcProviderArn, issuerKeyPrefix, claims,
roleSessionName);
roleSessionName, roleTags);
}
private boolean allows(String action, String trustPolicyDocument, String oidcProviderArn,
String issuerKeyPrefix, Map<String, List<String>> claims,
String roleSessionName) {
String roleSessionName, Map<String, List<String>> roleTags) {
if (trustPolicyDocument == null || trustPolicyDocument.isBlank()) {
return false;
}
@@ -89,7 +94,7 @@ public class WebIdentityTrustPolicyEvaluator {
boolean allow = false;
if (statements.isArray()) {
for (JsonNode stmt : statements) {
switch (evaluate(action, stmt, oidcProviderArn, issuerKeyPrefix, claims, roleSessionName)) {
switch (evaluate(action, stmt, oidcProviderArn, issuerKeyPrefix, claims, roleSessionName, roleTags)) {
case DENY -> { return false; }
case ALLOW -> allow = true;
case NO_MATCH -> { }
@@ -98,8 +103,8 @@ public class WebIdentityTrustPolicyEvaluator {
return allow;
}
if (statements.isObject()) {
return evaluate(action, statements, oidcProviderArn, issuerKeyPrefix, claims, roleSessionName)
== Match.ALLOW;
return evaluate(action, statements, oidcProviderArn, issuerKeyPrefix, claims, roleSessionName,
roleTags) == Match.ALLOW;
}
return false;
}
@@ -107,14 +112,15 @@ public class WebIdentityTrustPolicyEvaluator {
private enum Match { ALLOW, DENY, NO_MATCH }
private Match evaluate(String action, JsonNode stmt, String oidcProviderArn, String issuerKeyPrefix,
Map<String, List<String>> claims, String roleSessionName) {
Map<String, List<String>> claims, String roleSessionName,
Map<String, List<String>> roleTags) {
if (!actionApplies(stmt, action)) {
return Match.NO_MATCH;
}
if (!matchesFederatedPrincipal(stmt.get("Principal"), oidcProviderArn)) {
return Match.NO_MATCH;
}
if (!conditionsSatisfied(stmt.get("Condition"), issuerKeyPrefix, claims, roleSessionName)) {
if (!conditionsSatisfied(stmt.get("Condition"), issuerKeyPrefix, claims, roleSessionName, roleTags)) {
return Match.NO_MATCH;
}
return TrustPolicyStatements.denies(stmt) ? Match.DENY : Match.ALLOW;
@@ -192,7 +198,8 @@ public class WebIdentityTrustPolicyEvaluator {
* using anything else does not match, which fails closed.
*/
private boolean conditionsSatisfied(JsonNode conditionNode, String issuerKeyPrefix,
Map<String, List<String>> claims, String roleSessionName) {
Map<String, List<String>> claims, String roleSessionName,
Map<String, List<String>> roleTags) {
if (conditionNode == null || conditionNode.isNull()) {
// No condition constraints — the federated principal alone is enough.
return true;
@@ -213,7 +220,7 @@ public class WebIdentityTrustPolicyEvaluator {
while (keyIterator.hasNext()) {
Map.Entry<String, JsonNode> keyEntry = keyIterator.next();
if (!keySatisfied(operator, keyEntry.getKey(), keyEntry.getValue(),
issuerKeyPrefix, claims, roleSessionName)) {
issuerKeyPrefix, claims, roleSessionName, roleTags)) {
return false;
}
}
@@ -223,10 +230,11 @@ public class WebIdentityTrustPolicyEvaluator {
private boolean keySatisfied(String operator, String conditionKey, JsonNode expected,
String issuerKeyPrefix, Map<String, List<String>> claims,
String roleSessionName) {
String roleSessionName, Map<String, List<String>> roleTags) {
List<String> actual = ROLE_SESSION_NAME_KEY.equalsIgnoreCase(conditionKey)
? (roleSessionName == null ? List.of() : List.of(roleSessionName))
: resolveClaim(conditionKey, issuerKeyPrefix, claims);
: TrustPolicyStatements.roleValues(conditionKey, roleTags)
.orElseGet(() -> resolveClaim(conditionKey, issuerKeyPrefix, claims));
List<String> expectedValues = textValues(expected);
if (expectedValues.isEmpty()) {
return false;
@@ -46,8 +46,7 @@ public class LambdaWebExecutionRole {
String name = arn.resource().substring(arn.resource().lastIndexOf('/') + 1);
return iamService.findRole(arn.accountId(), name)
.filter(role -> IamService.roleArnMatches(roleArn, role))
.filter(role -> trust.allowsService(role.getAssumeRolePolicyDocument(), LAMBDA, sourceArn,
sourceAccount))
.filter(role -> trust.allowsService(role, LAMBDA, sourceArn, sourceAccount))
.isPresent();
}
}
@@ -182,7 +182,7 @@ public class ApiGatewayTaskInvoker {
IamRole role = iam.findRole(executionRole.accountId(), name)
.filter(found -> IamService.roleArnMatches(machine.getRoleArn(), found))
.orElseThrow(() -> failure(403, "Execution role does not exist"));
if (!trust.allowsService(role.getAssumeRolePolicyDocument(), ServicePrincipals.of("states"),
if (!trust.allowsService(role, ServicePrincipals.of("states"),
machine.getStateMachineArn(), owner.accountId())) {
throw failure(403, "Execution role does not trust Step Functions");
}
@@ -129,7 +129,7 @@ public class LambdaTaskAuthorizer {
IamRole executionRole = access.role(machine.getRoleArn()).orElseThrow(
() -> new AslExecutor.FailStateException("States.Permissions",
"The execution role " + machine.getRoleArn() + " does not exist."));
if (!trustEvaluator.allowsService(executionRole.getAssumeRolePolicyDocument(),
if (!trustEvaluator.allowsService(executionRole,
ServicePrincipals.of("states"), machine.getStateMachineArn(), owner.accountId())) {
throw new AslExecutor.FailStateException("States.Permissions",
"The execution role " + machine.getRoleArn() + " does not trust Step Functions.");
@@ -2,6 +2,7 @@ package io.floci.aws.services.iam;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.services.iam.AssumeRolePolicyEvaluator.TrustDecision;
import io.floci.aws.services.iam.model.IamRole;
import org.junit.jupiter.api.Test;
import java.util.List;
@@ -452,6 +453,24 @@ class AssumeRolePolicyEvaluatorTest {
"lambda.amazonaws.com", null, null));
}
/**
* The tags of the role a service assumes, the resource {@code sts:AssumeRole} acts on, which its trust policy reads
* under the keys the generated table gives the role type: a tag key matched whatever its case, its value exactly.
* Read from the document alone, with no role, they are absent.
*/
@Test
void serviceTrustReadsTheTagsOfTheRoleTheServiceAssumes() {
IamRole role = new IamRole("id", "tagged", "/", "arn:aws:iam::000000000000:role/tagged",
serviceTrust("{\"StringEquals\":{\"aws:ResourceTag/Team\":\"data\"}}"));
role.setTags(Map.of("team", "data"));
assertTrue(evaluator.allowsService(role, "lambda.amazonaws.com", null, null));
assertFalse(evaluator.allowsService(role.getAssumeRolePolicyDocument(), "lambda.amazonaws.com", null, null));
role.setTags(Map.of("team", "Data"));
assertFalse(evaluator.allowsService(role, "lambda.amazonaws.com", null, null));
role.setAssumeRolePolicyDocument(serviceTrust("{\"StringEquals\":{\"iam:ResourceTag/team\":\"Data\"}}"));
assertTrue(evaluator.allowsService(role, "lambda.amazonaws.com", null, null));
}
private static String serviceTrust(String condition) {
return """
{"Version":"2012-10-17","Statement":[
@@ -259,6 +259,26 @@ class AssumeRoleWithSamlValidationIntegrationTest {
endsWith(":alice@example.test"));
}
/**
* The tags of the role being assumed, the resource of the request, which the Service Authorization Reference gives
* the {@code role} type as {@code aws:ResourceTag/${TagKey}} and {@code iam:ResourceTag/${TagKey}}.
*/
@Test
void trustPolicyReadingTheRolesOwnTagAllowsTheRoleCarryingIt() {
// Tag keys are not case-sensitive: the role carries `team`.
String role = createRoleWithCondition("{\"StringEquals\":{\"aws:ResourceTag/Team\":\"federated\"}}");
tagRole(role, "team", "federated");
assume(role, assertionNamingSession(role, "alice@example.test"), PROVIDER).statusCode(200);
}
@Test
void trustPolicyReadingAnotherValueOfTheRolesTagRefusesIt() {
String role = createRoleWithCondition("{\"StringEquals\":{\"iam:ResourceTag/team\":\"other\"}}");
tagRole(role, "team", "federated");
assume(role, assertionNamingSession(role, "alice@example.test"), PROVIDER)
.statusCode(403).body(containsString("AccessDenied"));
}
@Test
void trustPolicyRequiringTheSessionNameRefusesAnotherName() {
String role = createRoleWithCondition("{\"StringEquals\":{\"sts:RoleSessionName\":\"alice@example.test\"}}");
@@ -741,6 +761,13 @@ class AssumeRoleWithSamlValidationIntegrationTest {
return "arn:aws:iam::" + ACCOUNT + ":role/" + role;
}
private static void tagRole(String roleArn, String key, String value) {
given().contentType("application/x-www-form-urlencoded").formParam("Action", "TagRole")
.formParam("RoleName", roleArn.substring(roleArn.lastIndexOf('/') + 1))
.formParam("Tags.member.1.Key", key).formParam("Tags.member.1.Value", value)
.header("Authorization", auth("iam")).when().post("/").then().statusCode(200);
}
private static void ensureProviderRegistered() {
if (!providerRegistered) {
registerProvider();
@@ -32,7 +32,25 @@ class SAMLTrustPolicyEvaluatorTest {
}
private boolean allows(String policy, String roleSessionName) {
return evaluator.allows(policy, PROVIDER, CLAIMS, roleSessionName);
return evaluator.allows(policy, PROVIDER, CLAIMS, roleSessionName, Map.of());
}
/**
* The tags of the role being assumed, which a trust policy reads under the keys its type carries: a tag key matched
* whatever its case, its value exactly, and a role without the tag not matching.
*/
@Test
void readsTheTagsOfTheRoleBeingAssumed() {
Map<String, List<String>> roleTags = Map.of("aws:ResourceTag/team", List.of("data"),
"iam:ResourceTag/team", List.of("data"));
assertTrue(evaluator.allows(policy("{\"StringEquals\":{\"aws:ResourceTag/Team\":\"data\"}}"), PROVIDER, CLAIMS,
"alice", roleTags));
assertTrue(evaluator.allows(policy("{\"StringEquals\":{\"iam:ResourceTag/team\":\"data\"}}"), PROVIDER, CLAIMS,
"alice", roleTags));
assertFalse(evaluator.allows(policy("{\"StringEquals\":{\"aws:ResourceTag/team\":\"Data\"}}"), PROVIDER, CLAIMS,
"alice", roleTags));
assertFalse(evaluator.allows(policy("{\"StringEquals\":{\"aws:ResourceTag/team\":\"data\"}}"), PROVIDER, CLAIMS,
"alice", Map.of()));
}
@Test
@@ -10,6 +10,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -56,10 +57,11 @@ class ServiceRoleAuthorizerTest {
new AssumeRolePolicyEvaluator(new ObjectMapper(), evaluator), scpProvider);
}
private void role(String trust, String... policies) {
private IamRole role(String trust, String... policies) {
IamRole role = new IamRole("id", "service-role", "/", ROLE_ARN, trust);
when(iamService.findRole(ACCOUNT_ID, "service-role")).thenReturn(Optional.of(role));
when(iamService.resolvePrincipalContext(ROLE_ARN)).thenReturn(CallerContext.of(List.of(policies)));
return role;
}
@Test
@@ -170,6 +172,24 @@ class ServiceRoleAuthorizerTest {
List.of(PERMISSION)).isPresent());
}
/** The role's own tags are in its trust policy's context, as for every assume of the role. */
@Test
void roleTagTrustConditionIsEvaluated() {
String conditionalTrust = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"Service":"events.amazonaws.com"},"Action":"sts:AssumeRole",
"Condition":{"StringEquals":{"aws:ResourceTag/team":"%s"}}}]}""";
role(conditionalTrust.formatted("data"), ALLOW).setTags(Map.of("team", "data"));
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, SERVICE_PRINCIPAL, SOURCE_ARN,
List.of(PERMISSION)).isEmpty());
role(conditionalTrust.formatted("other"), ALLOW).setTags(Map.of("team", "data"));
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, SERVICE_PRINCIPAL, SOURCE_ARN,
List.of(PERMISSION)).isPresent());
}
@Test
void sourceAccountTrustConditionIsEvaluated() {
String conditionalTrust = """
@@ -1140,9 +1140,11 @@ class StsQueryHandlerTest {
OidcIssuerKeyLookup keys = mock(OidcIssuerKeyLookup.class);
when(keys.findVerificationKey(issuer)).thenReturn(Optional.of(mock(RSAPublicKey.class)));
WebIdentityTrustPolicyEvaluator trust = mock(WebIdentityTrustPolicyEvaluator.class);
when(trust.allows(eq("{}"), eq(providerArn), eq("oidc.example.com/id/ABC"), anyMap(), eq("app"))).thenReturn(true);
when(trust.allows(eq("{}"), eq(providerArn), eq("oidc.example.com/id/ABC"), anyMap(), eq("app"), anyMap()))
.thenReturn(true);
// The token passes a session tag, which the trust policy has to permit as well.
when(trust.allowsTagging(eq("{}"), eq(providerArn), eq("oidc.example.com/id/ABC"), anyMap(), eq("app")))
when(trust.allowsTagging(eq("{}"), eq(providerArn), eq("oidc.example.com/id/ABC"), anyMap(), eq("app"),
anyMap()))
.thenReturn(true);
StsQueryHandler handler = new StsQueryHandler(iamService, mock(AccountResolver.class),
@@ -1158,7 +1160,7 @@ class StsQueryHandlerTest {
Response response = handler.handle("AssumeRoleWithWebIdentity", params);
assertEquals(200, response.getStatus(), (String) response.getEntity());
verify(trust).allows(eq("{}"), eq(providerArn), eq("oidc.example.com/id/ABC"), anyMap(), eq("app"));
verify(trust).allows(eq("{}"), eq(providerArn), eq("oidc.example.com/id/ABC"), anyMap(), eq("app"), anyMap());
assertEquals("arn:aws-cn:sts::000000000000:assumed-role/web-role/app",
extract(ARN, (String) response.getEntity()));
// The token's own transitive key is recorded with its tags, so a session assumed from this
@@ -55,8 +55,9 @@ class TrustPolicyStatementsTest {
String document = "{\"Version\":\"2012-10-17\",\"Statement\":[" + String.join(",", statements) + "]}";
return switch (path) {
case ASSUME_ROLE -> assumeRole.allows(document, new IamService.CallerArns(USER, USER), ACCOUNT, Map.of());
case WEB_IDENTITY -> webIdentity.allows(document, OIDC_PROVIDER, OIDC_PREFIX, Map.of(), "session");
case SAML -> saml.allows(document, SAML_PROVIDER, Map.of(), "session");
case WEB_IDENTITY -> webIdentity.allows(document, OIDC_PROVIDER, OIDC_PREFIX, Map.of(), "session",
Map.of());
case SAML -> saml.allows(document, SAML_PROVIDER, Map.of(), "session", Map.of());
};
}
@@ -29,7 +29,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
* {@code sts:RoleSessionName} in an {@code AssumeRoleWithWebIdentity} trust policy, which the
* Service Authorization Reference lists for the action and which holds the {@code RoleSessionName}
* the request passes: "Your administrator might require that you specify your user name as the
* session name when you assume the role. For more information, see sts:RoleSessionName."
* session name when you assume the role. For more information, see sts:RoleSessionName." And the
* tags of the role being assumed, the resource of the request, which the reference gives the
* {@code role} type as {@code aws:ResourceTag/${TagKey}} and {@code iam:ResourceTag/${TagKey}}.
*/
@QuarkusTest
class WebIdentityRoleSessionNameIntegrationTest {
@@ -128,6 +130,26 @@ class WebIdentityRoleSessionNameIntegrationTest {
assertEquals(403, error.statusCode());
}
@Test
void trustPolicyReadingTheRolesOwnTagAllowsTheRoleCarryingIt() {
// Tag keys are not case-sensitive: the role carries `team`.
Role role = role("{\"StringEquals\":{\"aws:ResourceTag/Team\":\"federated\"}}");
AssumeRoleWithWebIdentityResponse response = assume(role, "tagged");
FederatedSessionAssertions.assertIdentity(endpoint, iamService, role, "tagged", response);
}
@Test
void trustPolicyReadingAnotherValueOfTheRolesTagRefusesIt() {
Role role = role("{\"StringEquals\":{\"iam:ResourceTag/team\":\"other\"}}");
StsException error = assertThrows(StsException.class, () -> assume(role, "tagged"));
assertEquals("AccessDenied", error.awsErrorDetails().errorCode());
assertEquals(403, error.statusCode());
}
@Test
void trustPolicyWithoutTheConditionAcceptsAnySessionName() {
Role role = role(null);
@@ -46,7 +46,25 @@ class WebIdentityTrustPolicyEvaluatorTest {
}
private boolean allows(String policy, Map<String, List<String>> claims) {
return evaluator.allows(policy, PROVIDER_ARN, PREFIX, claims, SESSION_NAME);
return evaluator.allows(policy, PROVIDER_ARN, PREFIX, claims, SESSION_NAME, Map.of());
}
/**
* The tags of the role being assumed, which a trust policy reads under the keys its type carries beside the
* token's claims: a tag key matched whatever its case, its value exactly, and a role without the tag not matching.
*/
@Test
void readsTheTagsOfTheRoleBeingAssumed() {
String policy = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"Federated":"%s"},"Action":"sts:AssumeRoleWithWebIdentity",
"Condition":{"StringEquals":{"%s:sub":"%s","aws:ResourceTag/Team":"data"}}}]}"""
.formatted(PROVIDER_ARN, PREFIX, SUBJECT);
Map<String, List<String>> roleTags = Map.of("aws:ResourceTag/team", List.of("data"));
assertTrue(evaluator.allows(policy, PROVIDER_ARN, PREFIX, claims(SUBJECT), SESSION_NAME, roleTags));
assertFalse(evaluator.allows(policy, PROVIDER_ARN, PREFIX, claims(SUBJECT), SESSION_NAME,
Map.of("aws:ResourceTag/team", List.of("Data"))));
assertFalse(allows(policy, claims(SUBJECT)));
}
@Test
@@ -88,7 +106,7 @@ class WebIdentityTrustPolicyEvaluatorTest {
String policy = irsaTrustPolicy(SUBJECT);
assertFalse(evaluator.allows(policy,
"arn:aws:iam::000000000000:oidc-provider/oidc.eks.us-east-1.amazonaws.com/id/OTHER",
PREFIX, claims(SUBJECT), SESSION_NAME));
PREFIX, claims(SUBJECT), SESSION_NAME, Map.of()));
}
@Test
@@ -281,7 +299,7 @@ class WebIdentityTrustPolicyEvaluatorTest {
"%s:sub":"%s","sts:RoleSessionName":"%s"}}}]}"""
.formatted(PROVIDER_ARN, PREFIX, SUBJECT, SESSION_NAME);
assertTrue(allows(policy, claims(SUBJECT)));
assertFalse(evaluator.allows(policy, PROVIDER_ARN, PREFIX, claims(SUBJECT), "other-session"));
assertFalse(evaluator.allows(policy, PROVIDER_ARN, PREFIX, claims(SUBJECT), "other-session", Map.of()));
assertFalse(allows(policy, claims("system:serviceaccount:my-namespace:other")));
}
}