diff --git a/docs/services/sts.md b/docs/services/sts.md index 98cba85f97..fd13dc72f7 100644 --- a/docs/services/sts.md +++ b/docs/services/sts.md @@ -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 diff --git a/src/main/java/io/floci/aws/services/appsync/graphql/datasource/AppSyncDataSourceAuthorizer.java b/src/main/java/io/floci/aws/services/appsync/graphql/datasource/AppSyncDataSourceAuthorizer.java index b0fe8a2f58..a798a5d0a7 100644 --- a/src/main/java/io/floci/aws/services/appsync/graphql/datasource/AppSyncDataSourceAuthorizer.java +++ b/src/main/java/io/floci/aws/services/appsync/graphql/datasource/AppSyncDataSourceAuthorizer.java @@ -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); } diff --git a/src/main/java/io/floci/aws/services/iam/AssumeRolePolicyEvaluator.java b/src/main/java/io/floci/aws/services/iam/AssumeRolePolicyEvaluator.java index f1cca998fd..1d192526fd 100644 --- a/src/main/java/io/floci/aws/services/iam/AssumeRolePolicyEvaluator.java +++ b/src/main/java/io/floci/aws/services/iam/AssumeRolePolicyEvaluator.java @@ -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/}, + * {@code iam:ResourceTag/}), 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> 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> context = IamConditionContextResolver.serviceCallContext( - servicePrincipal, null, null, sourceArn, sourceAccount); + Map> context = IamConditionContextResolver.withResourceTags( + IamConditionContextResolver.serviceCallContext(servicePrincipal, null, null, sourceArn, sourceAccount), + roleTags); boolean allow = false; if (statements.isArray()) { for (JsonNode statement : statements) { diff --git a/src/main/java/io/floci/aws/services/iam/SAMLTrustPolicyEvaluator.java b/src/main/java/io/floci/aws/services/iam/SAMLTrustPolicyEvaluator.java index e56faa04ea..25d6294297 100644 --- a/src/main/java/io/floci/aws/services/iam/SAMLTrustPolicyEvaluator.java +++ b/src/main/java/io/floci/aws/services/iam/SAMLTrustPolicyEvaluator.java @@ -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/}, {@code iam:ResourceTag/}), which a policy reads on it. */ public boolean allows(String document, String providerArn, Map> claims, - String roleSessionName) { - return allows(SAML_ACTION, document, providerArn, claims, roleSessionName); + String roleSessionName, Map> 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> claims, - String roleSessionName) { + String roleSessionName, Map> roleTags) { return allows(AssumeRolePolicyEvaluator.TAG_SESSION_ACTION, document, providerArn, claims, - roleSessionName); + roleSessionName, roleTags); } private boolean allows(String action, String document, String providerArn, - Map> claims, String roleSessionName) { + Map> claims, String roleSessionName, + Map> 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> claims, String roleSessionName) { + Map> claims, String roleSessionName, + Map> 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> claims, - String roleSessionName) { + String roleSessionName, Map> roleTags) { if (condition == null || condition.isNull()) { return true; } @@ -93,7 +97,8 @@ public class SAMLTrustPolicyEvaluator { Iterator> entries = operator.getValue().fields(); while (entries.hasNext()) { Map.Entry entry = entries.next(); - List actual = conditionValues(entry.getKey(), claims, roleSessionName); + List actual = TrustPolicyStatements.roleValues(entry.getKey(), roleTags) + .orElseGet(() -> conditionValues(entry.getKey(), claims, roleSessionName)); List expected = entry.getValue().isArray() ? StreamSupport.stream(entry.getValue().spliterator(), false) .filter(JsonNode::isTextual).map(JsonNode::asText).toList() diff --git a/src/main/java/io/floci/aws/services/iam/ServiceRoleAuthorizer.java b/src/main/java/io/floci/aws/services/iam/ServiceRoleAuthorizer.java index f72a75ddb4..c7fb0ec379 100644 --- a/src/main/java/io/floci/aws/services/iam/ServiceRoleAuthorizer.java +++ b/src/main/java/io/floci/aws/services/iam/ServiceRoleAuthorizer.java @@ -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 + "."); } 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 6f9eb11ce3..2b6d1b3889 100644 --- a/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java +++ b/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java @@ -884,15 +884,16 @@ public class StsQueryHandler { "sub", List.of(claims.subject()), "aud", claims.audiences()); + Map> 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> roleTagKeys(IamRole role) { + Map> 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> 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); } diff --git a/src/main/java/io/floci/aws/services/iam/TrustPolicyStatements.java b/src/main/java/io/floci/aws/services/iam/TrustPolicyStatements.java index 624cac5dca..20e58b8efc 100644 --- a/src/main/java/io/floci/aws/services/iam/TrustPolicyStatements.java +++ b/src/main/java/io/floci/aws/services/iam/TrustPolicyStatements.java @@ -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/}, {@code iam:ResourceTag/}), a key matched whatever its + * case, as AWS matches a tag key; empty for a key the role gives no value under. + */ + static Optional> roleValues(String conditionKey, Map> 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()); diff --git a/src/main/java/io/floci/aws/services/iam/WebIdentityTrustPolicyEvaluator.java b/src/main/java/io/floci/aws/services/iam/WebIdentityTrustPolicyEvaluator.java index aefe519a1c..dd61eaff33 100644 --- a/src/main/java/io/floci/aws/services/iam/WebIdentityTrustPolicyEvaluator.java +++ b/src/main/java/io/floci/aws/services/iam/WebIdentityTrustPolicyEvaluator.java @@ -50,13 +50,17 @@ public class WebIdentityTrustPolicyEvaluator { *

{@code claims} holds the OIDC condition context keyed without the provider * prefix — {@code sub}, {@code aud} — which this evaluator resolves against policy keys of the * form {@code :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/}, {@code iam:ResourceTag/}), 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> claims, String roleSessionName) { + Map> claims, String roleSessionName, + Map> 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> claims, String roleSessionName) { + Map> claims, String roleSessionName, + Map> 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> claims, - String roleSessionName) { + String roleSessionName, Map> 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> claims, String roleSessionName) { + Map> claims, String roleSessionName, + Map> 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> claims, String roleSessionName) { + Map> claims, String roleSessionName, + Map> 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 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> claims, - String roleSessionName) { + String roleSessionName, Map> roleTags) { List 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 expectedValues = textValues(expected); if (expectedValues.isEmpty()) { return false; diff --git a/src/main/java/io/floci/aws/services/lambdaweb/LambdaWebExecutionRole.java b/src/main/java/io/floci/aws/services/lambdaweb/LambdaWebExecutionRole.java index db2b2dbc96..aa49642d66 100644 --- a/src/main/java/io/floci/aws/services/lambdaweb/LambdaWebExecutionRole.java +++ b/src/main/java/io/floci/aws/services/lambdaweb/LambdaWebExecutionRole.java @@ -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(); } } diff --git a/src/main/java/io/floci/aws/services/stepfunctions/ApiGatewayTaskInvoker.java b/src/main/java/io/floci/aws/services/stepfunctions/ApiGatewayTaskInvoker.java index 5531770a6c..8f683580b4 100644 --- a/src/main/java/io/floci/aws/services/stepfunctions/ApiGatewayTaskInvoker.java +++ b/src/main/java/io/floci/aws/services/stepfunctions/ApiGatewayTaskInvoker.java @@ -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"); } 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 538140836e..e79fcbc995 100644 --- a/src/main/java/io/floci/aws/services/stepfunctions/LambdaTaskAuthorizer.java +++ b/src/main/java/io/floci/aws/services/stepfunctions/LambdaTaskAuthorizer.java @@ -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."); diff --git a/src/test/java/io/floci/aws/services/iam/AssumeRolePolicyEvaluatorTest.java b/src/test/java/io/floci/aws/services/iam/AssumeRolePolicyEvaluatorTest.java index c7d7d09963..8f40b5ab00 100644 --- a/src/test/java/io/floci/aws/services/iam/AssumeRolePolicyEvaluatorTest.java +++ b/src/test/java/io/floci/aws/services/iam/AssumeRolePolicyEvaluatorTest.java @@ -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":[ diff --git a/src/test/java/io/floci/aws/services/iam/AssumeRoleWithSamlValidationIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/AssumeRoleWithSamlValidationIntegrationTest.java index b986c4fd1b..fafb94f44c 100644 --- a/src/test/java/io/floci/aws/services/iam/AssumeRoleWithSamlValidationIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/AssumeRoleWithSamlValidationIntegrationTest.java @@ -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(); diff --git a/src/test/java/io/floci/aws/services/iam/SAMLTrustPolicyEvaluatorTest.java b/src/test/java/io/floci/aws/services/iam/SAMLTrustPolicyEvaluatorTest.java index b94d0cd7c7..f595d6bdce 100644 --- a/src/test/java/io/floci/aws/services/iam/SAMLTrustPolicyEvaluatorTest.java +++ b/src/test/java/io/floci/aws/services/iam/SAMLTrustPolicyEvaluatorTest.java @@ -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> 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 diff --git a/src/test/java/io/floci/aws/services/iam/ServiceRoleAuthorizerTest.java b/src/test/java/io/floci/aws/services/iam/ServiceRoleAuthorizerTest.java index 128397a32f..a8a6ae1394 100644 --- a/src/test/java/io/floci/aws/services/iam/ServiceRoleAuthorizerTest.java +++ b/src/test/java/io/floci/aws/services/iam/ServiceRoleAuthorizerTest.java @@ -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 = """ diff --git a/src/test/java/io/floci/aws/services/iam/StsQueryHandlerTest.java b/src/test/java/io/floci/aws/services/iam/StsQueryHandlerTest.java index 53cd262de2..080c29df42 100644 --- a/src/test/java/io/floci/aws/services/iam/StsQueryHandlerTest.java +++ b/src/test/java/io/floci/aws/services/iam/StsQueryHandlerTest.java @@ -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 diff --git a/src/test/java/io/floci/aws/services/iam/TrustPolicyStatementsTest.java b/src/test/java/io/floci/aws/services/iam/TrustPolicyStatementsTest.java index e55a16eaaa..18d6d6f183 100644 --- a/src/test/java/io/floci/aws/services/iam/TrustPolicyStatementsTest.java +++ b/src/test/java/io/floci/aws/services/iam/TrustPolicyStatementsTest.java @@ -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()); }; } diff --git a/src/test/java/io/floci/aws/services/iam/WebIdentityRoleSessionNameIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/WebIdentityRoleSessionNameIntegrationTest.java index d679e5f396..a7a7419fde 100644 --- a/src/test/java/io/floci/aws/services/iam/WebIdentityRoleSessionNameIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/WebIdentityRoleSessionNameIntegrationTest.java @@ -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); diff --git a/src/test/java/io/floci/aws/services/iam/WebIdentityTrustPolicyEvaluatorTest.java b/src/test/java/io/floci/aws/services/iam/WebIdentityTrustPolicyEvaluatorTest.java index b55b556edf..57c63daaf8 100644 --- a/src/test/java/io/floci/aws/services/iam/WebIdentityTrustPolicyEvaluatorTest.java +++ b/src/test/java/io/floci/aws/services/iam/WebIdentityTrustPolicyEvaluatorTest.java @@ -46,7 +46,25 @@ class WebIdentityTrustPolicyEvaluatorTest { } private boolean allows(String policy, Map> 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> 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"))); } }