diff --git a/.github/workflows/iam-data-drift.yml b/.github/workflows/iam-data-drift.yml index 3459809f79..0e83942904 100644 --- a/.github/workflows/iam-data-drift.yml +++ b/.github/workflows/iam-data-drift.yml @@ -106,6 +106,9 @@ on: - 'tools/aws/sources/sts-source-identity.json' - 'tools/aws/fetch_sts_source_identity.py' - 'tools/aws/test_fetch_sts_source_identity.py' + - 'tools/aws/sources/sts-session-tags.json' + - 'tools/aws/fetch_sts_session_tags.py' + - 'tools/aws/test_fetch_sts_session_tags.py' - 'src/main/resources/aws/rest-routes.json' - 'tools/aws/regen_rest_routes.py' - 'tools/aws/test_regen_rest_routes.py' diff --git a/Makefile b/Makefile index 4db960fd97..849d3f4c28 100644 --- a/Makefile +++ b/Makefile @@ -622,7 +622,8 @@ IAM_AUTHORIZED_ACTIONS_PATHS := src/main/resources/aws/iam-authorized-actions.js src/main/resources/aws/rest-routes.json tools/aws/sources/s3-required-actions.json \ tools/aws/fetch_s3_required_actions.py tools/aws/test_fetch_s3_required_actions.py \ tools/aws/sources/sts-source-identity.json tools/aws/fetch_sts_source_identity.py \ - tools/aws/test_fetch_sts_source_identity.py + tools/aws/test_fetch_sts_source_identity.py tools/aws/sources/sts-session-tags.json \ + tools/aws/fetch_sts_session_tags.py tools/aws/test_fetch_sts_session_tags.py IAM_PASSED_ROLES_PATHS := src/main/resources/aws/iam-passed-roles.json $(IAM_PASSED_ROLES_GENERATOR) \ tools/aws/test_regen_iam_passed_roles.py tools/aws/sources/eks-roles.json tools/aws/fetch_eks_roles.py \ tools/aws/test_fetch_eks_roles.py tools/aws/sources/emr-roles.json tools/aws/fetch_emr_roles.py \ diff --git a/docs/services/sts.md b/docs/services/sts.md index a47fb40c41..3b0e4f7f78 100644 --- a/docs/services/sts.md +++ b/docs/services/sts.md @@ -483,7 +483,23 @@ sts:TagSession permission. For roles without this permission in the trust policy operation fails." All three assume operations read their trust policy for `sts:TagSession` when the request, the assertion or the token carries a tag, with the same principals and conditions as the assume itself, and answer `AccessDenied` naming that action when it is not allowed. An untagged -request is not held to it. `AssumeRole` reads its trust policy under the enforcement this section +request is not held to it. The action is generated data: `AssumeRole`'s is the tagging action the +generated `iam-tag-on-create.json` gives it, and the federated operations', which the Service +Authorization Reference lists no authorized actions for, is the companion the generated +`iam-authorized-actions.json` gives each from the session tags page, vendored into +`tools/aws/sources/sts-session-tags.json` by `tools/aws/fetch_sts_session_tags.py`. The same +companions name where the tags arrive, the assertion's +`https://aws.amazon.com/SAML/Attributes/PrincipalTag:{TagKey}` attributes and the token's +`https://aws.amazon.com/tags` claim, which is what the assertion and the token are read under. + +The tags an assertion or a token passes are request tags of its trust policy as well, as +`aws:RequestTag/` and `aws:TagKeys`, the keys the Service Authorization Reference gives both +actions, written as an `AssumeRole`'s are. The IAM user guide's SAML ABAC tutorial has a trust +policy reading them on the assume and the tagging alike, "aws:RequestTag/access-team" required to be +`eng` or `qas`, so a statement requiring a tag allows an assertion passing one of its values and not +one passing another or none. The federated trust policies read the `String` operators; a set +operator such as `ForAllValues` is not read by them, so a statement using one does not allow the +assume. `AssumeRole` reads its trust policy under the enforcement this section describes, so the permission is read there too; the assertion and the token are read against their trust policy on every call, as they always have been. @@ -697,10 +713,6 @@ AssumeRoleWithSAML does not require the use of AWS security credentials", and so `SourceIdentity` attribute carrying several values or one outside botocore's type, and a token's `source_identity` claim that is not one such string, answer `InvalidIdentityToken` with a sentence of Floci's own: nothing published says what AWS answers. -- **A federated assume's tags are not request tags of its trust policy.** The trust policy of an - `AssumeRoleWithSAML` or `AssumeRoleWithWebIdentity` does not see the tags the assertion or the - token passes as `aws:RequestTag/` and `aws:TagKeys`, which the Service Authorization Reference - gives both actions; [Session tags](#session-tags) says how they reach the session. ## Web Identity Validation (IRSA) 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 d20a6204a0..e786b5bbc1 100644 --- a/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java +++ b/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java @@ -469,6 +469,24 @@ public class IamConditionContextResolver { .map(TagOnCreate::requestTagContexts).orElse(List.of())); } + /** + * The tags a request passes as the keys it carries them as, {@code aws:RequestTag/} and {@code aws:TagKeys}, + * written as the caller's own policies read a tagged create's: for a trust policy an operation reads itself with + * tags that arrive outside the request's members, an assertion's or a token's. Empty for no tags. + */ + public static Map> requestTagKeys(Map tags) { + return tags == null || tags.isEmpty() ? Map.of() : TagOnCreate.requestTagContext(tags); + } + + /** + * The tagging action the generated tag-on-create table gives {@code operation} for the tags its request passes + * ({@code sts:TagSession} for an AssumeRole), or null for an operation it gives none. + */ + public static String taggingAction(String operation) { + TagOnCreateMembers.Entry entry = TagOnCreateMembers.of(operation); + return entry == null ? null : entry.tagging(); + } + /** * Whether the request names {@code member}: a Query form's parameter, or a JSON body's top-level member. */ diff --git a/src/main/java/io/floci/aws/core/common/TagOnCreate.java b/src/main/java/io/floci/aws/core/common/TagOnCreate.java index 5df710ad2c..b462a21ddc 100644 --- a/src/main/java/io/floci/aws/core/common/TagOnCreate.java +++ b/src/main/java/io/floci/aws/core/common/TagOnCreate.java @@ -525,6 +525,13 @@ final class TagOnCreate { return contexts; } + /** + * {@code tags} as the keys a request passing them carries, {@code aws:RequestTag/} and {@code aws:TagKeys}. + */ + static Map> requestTagContext(Map tags) { + return requestTagContext(new TagSet(null, tags)); + } + private static Map> requestTagContext(TagSet set) { Map> context = new HashMap<>(); set.tags().forEach((key, value) -> context.put("aws:RequestTag/" + key, List.of(value))); diff --git a/src/main/java/io/floci/aws/core/common/WebIdentityTokenVerifier.java b/src/main/java/io/floci/aws/core/common/WebIdentityTokenVerifier.java index 132d4d96ff..003080a32c 100644 --- a/src/main/java/io/floci/aws/core/common/WebIdentityTokenVerifier.java +++ b/src/main/java/io/floci/aws/core/common/WebIdentityTokenVerifier.java @@ -2,6 +2,7 @@ package io.floci.aws.core.common; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.services.iam.IamAuthorizedActions; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; @@ -38,8 +39,14 @@ public class WebIdentityTokenVerifier { /** Tolerance for clock drift between Floci and a token minted elsewhere. */ private static final long CLOCK_SKEW_SECONDS = 60; - /** The namespace AWS publishes a token's session tags under, whichever format they take. */ - private static final String TAGS_CLAIM = "https://aws.amazon.com/tags"; + /** + * The namespace AWS publishes a token's session tags under, whichever format they take: the claim the generated + * {@code iam-authorized-actions.json} gives AssumeRoleWithWebIdentity's session tags, from the IAM user guide's + * "the nested claim format uses a structure within the https://aws.amazon.com/tags namespace in the JWT". None + * where the file gives no such companion, and then a token passes no session tags. + */ + private static final String TAGS_CLAIM = IamAuthorizedActions.sessionTags("sts:AssumeRoleWithWebIdentity") + .map(IamAuthorizedActions.Companion::carrier).orElse(null); private static final String FLATTENED_TAG_CLAIM = TAGS_CLAIM + "/principal_tags/"; /** The nested member, and the flattened claim, naming the keys to set as transitive. */ private static final String TRANSITIVE_KEYS = "transitive_tag_keys"; @@ -205,6 +212,9 @@ public class WebIdentityTokenVerifier { */ private Map readPrincipalTags(JsonNode claims) throws InvalidTokenException { Map tags = new LinkedHashMap<>(); + if (TAGS_CLAIM == null) { + return tags; + } for (Map.Entry tag : claims.path(TAGS_CLAIM).path("principal_tags").properties()) { tags.put(tag.getKey(), singleValue(tag.getKey(), tag.getValue())); } @@ -236,6 +246,9 @@ public class WebIdentityTokenVerifier { */ private static List readTransitiveTagKeys(JsonNode claims) throws InvalidTokenException { List keys = new ArrayList<>(); + if (TAGS_CLAIM == null) { + return keys; + } readTransitiveKeysInto(claims.path(TAGS_CLAIM).path(TRANSITIVE_KEYS), keys); readTransitiveKeysInto(claims.path(FLATTENED_TRANSITIVE_CLAIM), keys); return keys; 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 6fcd55362e..035355fdee 100644 --- a/src/main/java/io/floci/aws/services/iam/AssumeRolePolicyEvaluator.java +++ b/src/main/java/io/floci/aws/services/iam/AssumeRolePolicyEvaluator.java @@ -48,13 +48,6 @@ public class AssumeRolePolicyEvaluator { private static final Logger LOG = Logger.getLogger(AssumeRolePolicyEvaluator.class); private static final String ASSUME_ROLE_ACTION = "sts:AssumeRole"; - /** - * What a trust policy has to allow beside the assume for the request's session tags to be - * taken: "when using session tags, trust policies for all roles connected to the identity - * provider passing tags must have the sts:TagSession permission. For roles without this - * permission in the trust policy, the AssumeRole operation fails." - */ - public static final String TAG_SESSION_ACTION = "sts:TagSession"; private static final Pattern ACCOUNT_ROOT_ARN = Pattern.compile("^arn:" + AwsArnUtils.PARTITION_REGEX + ":iam::(\\d{12}):root$"); @@ -104,22 +97,10 @@ public class AssumeRolePolicyEvaluator { } /** - * Whether the trust policy lets this caller tag the session it is assuming, which is the - * {@link #TAG_SESSION_ACTION} permission read on the same document, with the same principals - * and the same conditions as the assume itself. - */ - public boolean allowsTagging(String trustPolicyDocument, IamService.CallerArns caller, - String callerAccount, Map> requestContext) { - TrustDecision decision = decide(TAG_SESSION_ACTION, trustPolicyDocument, caller, callerAccount, - requestContext); - return decision == TrustDecision.ALLOW || decision == TrustDecision.ALLOW_ACCOUNT; - } - - /** - * Whether the trust policy lets this caller perform {@code action} on the role beside the assume: an action the - * generated {@code iam-authorized-actions.json} gives the assume for a value it sets - * ({@code sts:SetSourceIdentity}), read on the same document, with the same principals and the same conditions - * as the assume itself. + * Whether the trust policy lets this caller perform {@code action} on the role beside the assume: an action a + * generated table gives the assume for a value it sets, {@code sts:SetSourceIdentity} from + * {@code iam-authorized-actions.json} or {@code sts:TagSession} from {@code iam-tag-on-create.json}, read on the + * same document, with the same principals and the same conditions as the assume itself. */ public boolean allowsCompanion(String action, String trustPolicyDocument, IamService.CallerArns caller, String callerAccount, Map> requestContext) { @@ -447,7 +428,8 @@ public class AssumeRolePolicyEvaluator { /** * True if the statement's action element applies to {@code action}, which is the assume itself - * or the {@link #TAG_SESSION_ACTION} a tagged assume also needs. An {@code Action} element + * or an action a generated table gives the assume beside it ({@code sts:TagSession}, + * {@code sts:SetSourceIdentity}). An {@code Action} element * applies when any of its patterns match; a {@code NotAction} element applies when none * of its patterns match (AWS semantics, mirroring {@link IamPolicyEvaluator}'s action handling). * A statement with neither key expresses no action constraint and does not apply. diff --git a/src/main/java/io/floci/aws/services/iam/IamAuthorizedActions.java b/src/main/java/io/floci/aws/services/iam/IamAuthorizedActions.java index 07f1a6af2a..5106d6609d 100644 --- a/src/main/java/io/floci/aws/services/iam/IamAuthorizedActions.java +++ b/src/main/java/io/floci/aws/services/iam/IamAuthorizedActions.java @@ -13,6 +13,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Optional; import java.util.Set; /** @@ -101,8 +102,26 @@ public final class IamAuthorizedActions { */ public record Companion(String action, String member, String attribute, String claim, String key, String carried, boolean callerPolicyWhenChained) { + + /** + * Whether the companion's key names each tag its value carries, under the Service Reference's + * {@code ${TagKey}} placeholder ({@code aws:RequestTag/${TagKey}}), as a session tag companion's does, rather + * than one value. + */ + public boolean namesEachTag() { + return key != null && key.contains(TAG_KEY); + } + + /** The SAML attribute or token claim the companion reads, its {@code {TagKey}} placeholder left off. */ + public String carrier() { + String named = attribute != null ? attribute : claim; + return named == null ? null : named.replace("{TagKey}", ""); + } } + /** The placeholder the Service Reference names a tag's key with inside a condition key. */ + private static final String TAG_KEY = "${TagKey}"; + /** * An operation whose action is one or another by whether its request names {@code parameter}: S3's GetObject is * {@code s3:GetObject}, and {@code s3:GetObjectVersion} for a request naming a {@code versionId}. @@ -179,6 +198,17 @@ public final class IamAuthorizedActions { return Holder.TABLE.companions().getOrDefault(operation, List.of()); } + /** + * The companion of {@code operation} reading the session tags an identity provider passes: the SAML attribute or + * token claim carrying them and the action a trust policy has to allow for them. Empty for an operation the file + * gives none. + */ + public static Optional sessionTags(String operation) { + return companions(operation).stream() + .filter(companion -> companion.member() == null && companion.namesEachTag()) + .findFirst(); + } + /** The file's entries. */ static Table parse(InputStream in) throws IOException { JsonNode document = MAPPER.readTree(in); diff --git a/src/main/java/io/floci/aws/services/iam/SAMLAssertionVerifier.java b/src/main/java/io/floci/aws/services/iam/SAMLAssertionVerifier.java index e8364c6fe6..eddf8dff82 100644 --- a/src/main/java/io/floci/aws/services/iam/SAMLAssertionVerifier.java +++ b/src/main/java/io/floci/aws/services/iam/SAMLAssertionVerifier.java @@ -46,8 +46,14 @@ final class SAMLAssertionVerifier { static final String ASSERTION_INVALID = "The SAML assertion is invalid."; static final String SIGNATURE_INVALID = "Response signature invalid"; private static final String ROLE_SESSION_NAME = "https://aws.amazon.com/SAML/Attributes/RoleSessionName"; - /** What an attribute carrying a session tag is named, the tag's key following the colon. */ - private static final String PRINCIPAL_TAG = "https://aws.amazon.com/SAML/Attributes/PrincipalTag:"; + /** + * What an attribute carrying a session tag is named, the tag's key following it: the attribute the generated + * {@code iam-authorized-actions.json} gives AssumeRoleWithSAML's session tags, from the IAM user guide's "include + * the Attribute element with the Name attribute set to https://aws.amazon.com/SAML/Attributes/PrincipalTag:{TagKey}". + * None where the file gives no such companion, and then no attribute is a session tag. + */ + private static final String PRINCIPAL_TAG = IamAuthorizedActions.sessionTags("sts:AssumeRoleWithSAML") + .map(IamAuthorizedActions.Companion::carrier).orElse(null); /** What a session tag attribute naming no key is refused with, this package's own wording. */ static final String TAG_KEY_MISSING = "A PrincipalTag attribute must name the tag key after the colon."; @@ -264,7 +270,7 @@ final class SAMLAssertionVerifier { for (int i = 0; i < attributes.getLength(); i++) { Element attribute = (Element) attributes.item(i); String name = attribute.getAttribute("Name"); - if (name == null || !name.startsWith(PRINCIPAL_TAG)) { + if (PRINCIPAL_TAG == null || name == null || !name.startsWith(PRINCIPAL_TAG)) { continue; } String key = name.substring(PRINCIPAL_TAG.length()); 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 5933669958..e1f0835624 100644 --- a/src/main/java/io/floci/aws/services/iam/SAMLTrustPolicyEvaluator.java +++ b/src/main/java/io/floci/aws/services/iam/SAMLTrustPolicyEvaluator.java @@ -34,10 +34,10 @@ public class SAMLTrustPolicyEvaluator { } /** - * Whether the trust policy lets this assertion's holder perform {@code action} beside the assume, an action the - * generated {@code iam-authorized-actions.json} gives it for a value the assertion sets - * ({@code sts:SetSourceIdentity}), read on the same document with the same principal and the same conditions as - * the assume itself. + * Whether the trust policy lets this assertion's holder perform {@code action} beside the assume, an action + * the generated {@code iam-authorized-actions.json} gives it for a value the assertion sets + * ({@code sts:SetSourceIdentity}, {@code sts:TagSession}), read on the same document with the same principal + * and the same conditions as the assume itself. */ public boolean allowsCompanion(String action, String document, String providerArn, Map> claims, String roleSessionName, @@ -45,15 +45,6 @@ public class SAMLTrustPolicyEvaluator { return allows(action, document, providerArn, claims, roleSessionName, roleTags); } - /** - * Whether the trust policy lets this assertion's holder tag the session it is assuming, read on - * 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, Map> roleTags) { - return allows(AssumeRolePolicyEvaluator.TAG_SESSION_ACTION, document, providerArn, claims, - roleSessionName, roleTags); - } private boolean allows(String action, String document, String providerArn, Map> claims, String roleSessionName, 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 7b766dcb23..cd4c047549 100644 --- a/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java +++ b/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java @@ -325,10 +325,21 @@ public class StsQueryHandler { */ private static Optional federatedSourceIdentity(String operation) { return IamAuthorizedActions.companions(operation).stream() - .filter(companion -> companion.attribute() != null || companion.claim() != null) + .filter(companion -> (companion.attribute() != null || companion.claim() != null) + && !companion.namesEachTag()) .findFirst(); } + /** The trust policy's keys given in full, with the tags an assertion or a token passes as its request tags. */ + private static Map> withRequestTags(Map> keys, Map tags) { + if (tags.isEmpty()) { + return keys; + } + Map> withTags = new LinkedHashMap<>(keys); + withTags.putAll(IamConditionContextResolver.requestTagKeys(tags)); + return withTags; + } + /** * The source identity an assertion's attribute or a token's claim carries, {@code carrier} naming which: none where * it carries none, and refused with InvalidIdentityToken where it carries several values or one outside @@ -730,15 +741,16 @@ public class StsQueryHandler { // mints: the guide lists "incoming transitive session tags" among the tags a principal // carries, and where a base role's tags are passed on by STS "the trust policy must also // allow sts:TagSession", the refusal naming that action as this one does. - if (requestTags(params).isEmpty() && inheritedTags.isEmpty()) { + String tagging = IamConditionContextResolver.taggingAction("sts:AssumeRole"); + if (tagging == null || (requestTags(params).isEmpty() && inheritedTags.isEmpty())) { return null; } for (Map> context : trustContexts) { - if (!trustPolicyEvaluator.allowsTagging(role.getAssumeRolePolicyDocument(), caller, callerAccount, - context)) { + if (!trustPolicyEvaluator.allowsCompanion(tagging, role.getAssumeRolePolicyDocument(), caller, + callerAccount, context)) { return AwsQueryResponse.error("AccessDenied", "User: " + callerArn - + " is not authorized to perform: " + AssumeRolePolicyEvaluator.TAG_SESSION_ACTION - + " on resource: " + roleArn, AwsNamespaces.STS, 403); + + " is not authorized to perform: " + tagging + " on resource: " + roleArn, + AwsNamespaces.STS, 403); } } return null; @@ -1056,8 +1068,14 @@ public class StsQueryHandler { .orElse(null); String sourceIdentity = sourceIdentityKey == null ? null : tokenSourceIdentity(claims.claims().path(sourceIdentityKey.claim()), sourceIdentityKey.claim()); - Map> roleTags = withSourceIdentity(roleTagKeys(role.get()), sourceIdentityKey, - sourceIdentity); + // The tags the token passes are request tags of the trust policy too, aws:RequestTag/ and aws:TagKeys, + // as the Service Authorization Reference gives the action, and passing them needs the action the generated + // table gives the token's tags: "trust policies for all roles connected to the identity provider (IdP) + // passing tags must have the sts:TagSession permission". + IamAuthorizedActions.Companion taggingKey = IamAuthorizedActions.sessionTags("sts:AssumeRoleWithWebIdentity") + .orElse(null); + Map> roleTags = withRequestTags(withSourceIdentity(roleTagKeys(role.get()), + sourceIdentityKey, sourceIdentity), claims.principalTags()); if (sourceIdentity != null && !webIdentityTrustEvaluator.allowsCompanion(sourceIdentityKey.action(), role.get().getAssumeRolePolicyDocument(), oidcProviderArn, issuerKeyPrefix, conditionClaims, sessionName, roleTags)) { @@ -1071,13 +1089,13 @@ public class StsQueryHandler { roleArn, claims.subject()); return WebIdentityOutcome.deny(accessDenied("sts:AssumeRoleWithWebIdentity", roleArn)); } - if (!claims.principalTags().isEmpty() - && !webIdentityTrustEvaluator.allowsTagging(role.get().getAssumeRolePolicyDocument(), - oidcProviderArn, issuerKeyPrefix, conditionClaims, sessionName, roleTags)) { + if (!claims.principalTags().isEmpty() && taggingKey != null + && !webIdentityTrustEvaluator.allowsCompanion(taggingKey.action(), + role.get().getAssumeRolePolicyDocument(), 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( - accessDenied(AssumeRolePolicyEvaluator.TAG_SESSION_ACTION, roleArn)); + return WebIdentityOutcome.deny(accessDenied(taggingKey.action(), roleArn)); } // verify() already required the audience list to hold one of the accepted audiences. @@ -1211,7 +1229,15 @@ public class StsQueryHandler { String sourceIdentity = sourceIdentityKey == null ? null : federatedSourceIdentityValue( verified.attributes().getOrDefault(sourceIdentityKey.attribute(), List.of()), "SAML attribute " + sourceIdentityKey.attribute()); - Map> roleTags = withSourceIdentity(roleTagKeys(role), sourceIdentityKey, sourceIdentity); + // The tags the assertion passes are request tags of the trust policy too, aws:RequestTag/ and + // aws:TagKeys, as the Service Authorization Reference gives the action and the IAM user guide's SAML ABAC + // tutorial's trust policy reads them, and passing them needs the action the generated table gives the + // assertion's tags: "trust policies for all roles connected to the identity provider (IdP) passing tags must + // have the sts:TagSession permission". + IamAuthorizedActions.Companion taggingKey = IamAuthorizedActions.sessionTags("sts:AssumeRoleWithSAML") + .orElse(null); + Map> roleTags = withRequestTags(withSourceIdentity(roleTagKeys(role), sourceIdentityKey, + sourceIdentity), verified.principalTags()); if (sourceIdentity != null && !samlTrustEvaluator.allowsCompanion(sourceIdentityKey.action(), role.getAssumeRolePolicyDocument(), principalArn, assertionClaims, verified.roleSessionName(), roleTags)) { @@ -1222,11 +1248,11 @@ public class StsQueryHandler { 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(), roleTags)) { - throw new AwsException("AccessDenied", "Not authorized to perform " - + AssumeRolePolicyEvaluator.TAG_SESSION_ACTION + " on resource: " + roleArn, 403); + if (!verified.principalTags().isEmpty() && taggingKey != null + && !samlTrustEvaluator.allowsCompanion(taggingKey.action(), role.getAssumeRolePolicyDocument(), + principalArn, assertionClaims, verified.roleSessionName(), roleTags)) { + throw new AwsException("AccessDenied", "Not authorized to perform " + taggingKey.action() + + " on resource: " + roleArn, 403); } Response roleDurationError = validateMaxSessionDuration(durationSeconds, role); 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 dc1f1df5c5..491448419e 100644 --- a/src/main/java/io/floci/aws/services/iam/WebIdentityTrustPolicyEvaluator.java +++ b/src/main/java/io/floci/aws/services/iam/WebIdentityTrustPolicyEvaluator.java @@ -32,8 +32,6 @@ public class WebIdentityTrustPolicyEvaluator { private static final Logger LOG = Logger.getLogger(WebIdentityTrustPolicyEvaluator.class); private static final String WEB_IDENTITY_ACTION = "sts:assumerolewithwebidentity"; - /** What a trust policy also has to allow for the token's session tags to be taken. */ - private static final String TAG_SESSION_ACTION = AssumeRolePolicyEvaluator.TAG_SESSION_ACTION; private static final String ROLE_SESSION_NAME_KEY = "sts:RoleSessionName"; private final ObjectMapper objectMapper; @@ -65,10 +63,10 @@ public class WebIdentityTrustPolicyEvaluator { } /** - * Whether the trust policy lets this token's holder perform {@code action} beside the assume, an action the - * generated {@code iam-authorized-actions.json} gives it for a value the token sets - * ({@code sts:SetSourceIdentity}), read on the same document with the same principal and the same conditions as - * the assume itself. + * Whether the trust policy lets this token's holder perform {@code action} beside the assume, an action + * the generated {@code iam-authorized-actions.json} gives it for a value the token sets + * ({@code sts:SetSourceIdentity}, {@code sts:TagSession}), read on the same document with the same principal + * and the same conditions as the assume itself. */ public boolean allowsCompanion(String action, String trustPolicyDocument, String oidcProviderArn, String issuerKeyPrefix, Map> claims, String roleSessionName, @@ -77,16 +75,6 @@ public class WebIdentityTrustPolicyEvaluator { roleTags); } - /** - * Whether the trust policy lets this token's holder tag the session it is assuming, read on the - * 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> roleTags) { - return allows(TAG_SESSION_ACTION, trustPolicyDocument, oidcProviderArn, issuerKeyPrefix, claims, - roleSessionName, roleTags); - } private boolean allows(String action, String trustPolicyDocument, String oidcProviderArn, String issuerKeyPrefix, Map> claims, diff --git a/src/main/resources/aws/iam-authorized-actions.json b/src/main/resources/aws/iam-authorized-actions.json index 485486e306..32be860d32 100644 --- a/src/main/resources/aws/iam-authorized-actions.json +++ b/src/main/resources/aws/iam-authorized-actions.json @@ -1819,6 +1819,13 @@ "key": "sts:SourceIdentity", "carried": "aws:SourceIdentity", "callerPolicyWhenChained": false + }, + { + "action": "sts:TagSession", + "attribute": "https://aws.amazon.com/SAML/Attributes/PrincipalTag:{TagKey}", + "key": "aws:RequestTag/${TagKey}", + "carried": "aws:PrincipalTag/${TagKey}", + "callerPolicyWhenChained": false } ], "AssumeRoleWithWebIdentity": [ @@ -1828,6 +1835,13 @@ "key": "sts:SourceIdentity", "carried": "aws:SourceIdentity", "callerPolicyWhenChained": false + }, + { + "action": "sts:TagSession", + "claim": "https://aws.amazon.com/tags", + "key": "aws:RequestTag/${TagKey}", + "carried": "aws:PrincipalTag/${TagKey}", + "callerPolicyWhenChained": false } ] } 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 db9a15099e..21edf5147e 100644 --- a/src/test/java/io/floci/aws/services/iam/AssumeRoleWithSamlValidationIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/AssumeRoleWithSamlValidationIntegrationTest.java @@ -730,6 +730,24 @@ class AssumeRoleWithSamlValidationIntegrationTest { iamService.resolveCallerArns(accessKeyId).orElseThrow().principalTags()); } + /** + * The assertion's tags are request tags of the trust policy, {@code aws:RequestTag/} and {@code aws:TagKeys}, + * as the IAM user guide's SAML ABAC tutorial's trust policy reads them: a statement requiring a tag allows the + * assertion passing one of its values, and not one passing another value or none. + */ + @Test + void theAssertionsTagsAreRequestTagsOfTheTrustPolicy() { + String role = createRole("saml-request-tags-", "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":" + + "\"Allow\",\"Principal\":{\"Federated\":\"" + PROVIDER + "\"}," + + "\"Action\":[\"sts:AssumeRoleWithSAML\",\"sts:TagSession\"]," + + "\"Condition\":{\"StringLike\":{\"aws:RequestTag/access-team\":[\"eng\",\"qas\"]}}}]}"); + + assume(role, assertionCarryingTags(role, tag("access-team", "eng")), PROVIDER).statusCode(200); + assume(role, assertionCarryingTags(role, tag("access-team", "ops")), PROVIDER).statusCode(403) + .body("ErrorResponse.Error.Code", equalTo("AccessDenied")); + assume(role, assertionCarryingTags(role, Map.of()), PROVIDER).statusCode(403); + } + /** * The keys the assertion asks to set as transitive pass down to a session assumed from this * one: the attribute naming them "is an optional multivalued attribute that sets your session 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 080c29df42..c7d3ef9d91 100644 --- a/src/test/java/io/floci/aws/services/iam/StsQueryHandlerTest.java +++ b/src/test/java/io/floci/aws/services/iam/StsQueryHandlerTest.java @@ -1143,8 +1143,8 @@ class StsQueryHandlerTest { 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"), - anyMap())) + when(trust.allowsCompanion(eq("sts:TagSession"), eq("{}"), eq(providerArn), eq("oidc.example.com/id/ABC"), + anyMap(), eq("app"), anyMap())) .thenReturn(true); StsQueryHandler handler = new StsQueryHandler(iamService, mock(AccountResolver.class), diff --git a/src/test/java/io/floci/aws/services/iam/StsRegisteredOidcProviderIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/StsRegisteredOidcProviderIntegrationTest.java index 0d7b1f0c00..f0a9dfa8e2 100644 --- a/src/test/java/io/floci/aws/services/iam/StsRegisteredOidcProviderIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/StsRegisteredOidcProviderIntegrationTest.java @@ -296,6 +296,36 @@ class StsRegisteredOidcProviderIntegrationTest { } } + /** + * The token's tags are request tags of the trust policy, {@code aws:RequestTag/} and {@code aws:TagKeys}: a + * statement requiring a tag allows the token passing it and not one passing another value. + */ + @Test + void aTokensTagsAreRequestTagsOfTheTrustPolicy() throws Exception { + String host = issuer.substring("https://".length()); + String trust = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{" + + "\"Federated\":\"" + providerArn + "\"},\"Action\":[\"sts:AssumeRoleWithWebIdentity\"," + + "\"sts:TagSession\"],\"Condition\":{\"StringEquals\":{\"" + host + ":sub\":\"" + SUBJECT + + "\",\"aws:RequestTag/Project\":\"atlas\"}}}]}"; + Role tagged = iam.createRole(b -> b.roleName("web-tags-" + UUID.randomUUID().toString().substring(0, 8)) + .assumeRolePolicyDocument(trust)).role(); + try { + assume(tagged, token(issuer, "sts.amazonaws.com", privateKey, KEY_ID, principalTag("atlas"))); + StsException other = assertThrows(StsException.class, () -> assume(tagged, token(issuer, + "sts.amazonaws.com", privateKey, KEY_ID, principalTag("orion")))); + assertEquals(403, other.statusCode()); + } finally { + iam.deleteRole(b -> b.roleName(tagged.roleName())); + } + } + + /** The nested claim the IAM user guide gives a token's session tags in, passing Project as {@code value}. */ + private ObjectNode principalTag(String value) { + ObjectNode claims = objectMapper.createObjectNode(); + claims.putObject("https://aws.amazon.com/tags").putObject("principal_tags").putArray("Project").add(value); + return claims; + } + private ObjectNode sourceIdentity(JsonNode value) { ObjectNode claims = objectMapper.createObjectNode(); claims.set("https://aws.amazon.com/source_identity", value); diff --git a/tools/aws/fetch_sts_session_tags.py b/tools/aws/fetch_sts_session_tags.py new file mode 100644 index 0000000000..118e59d4a9 --- /dev/null +++ b/tools/aws/fetch_sts_session_tags.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python3 +"""Vendor what the IAM user guide says about the session tags a federated assume passes into +tools/aws/sources/sts-session-tags.json, a source of the authorized actions table. + +AWS's Service Reference gives AssumeRoleWithSAML and AssumeRoleWithWebIdentity the keys `aws:RequestTag/${TagKey}` +and `aws:TagKeys` but lists no authorized actions for either operation, and botocore models no tags on their requests: +an identity provider passes them in the assertion or the token. The IAM user guide's page on session tags says where, +and what passing them needs: + + When using session tags, trust policies for all roles connected to the identity provider (IdP) passing tags must + have the sts:TagSession permission. + + To pass SAML attributes as session tags, include the Attribute element with the Name attribute set to + https://aws.amazon.com/SAML/Attributes/PrincipalTag:{TagKey}. + + The nested claim format uses a structure within the https://aws.amazon.com/tags namespace in the JWT. + + https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html + +This script copies those sentences as they stand, with what each names: the SAML attribute or the token claim each +"Passing session tags using " section carries the tags in (`federated`), the action a role an identity +provider is connected to needs of its trust policy, the key a request passing tags carries them as and the key the +session's later requests carry them as. A section naming neither is not read here. Nothing in the output is written by +hand; regen_iam_authorized_actions.py reads it. + +Run from anywhere in the repo: + python3 tools/aws/fetch_sts_session_tags.py # rewrite the vendored file from the page + python3 tools/aws/fetch_sts_session_tags.py --verify # online: the file still says what the page does +""" +from __future__ import annotations + +import argparse +import html +import json +import re +import sys +import urllib.request +from datetime import datetime, timezone +from pathlib import Path + +PAGE = "https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html" +REPO_ROOT = Path(__file__).resolve().parents[2] +OUTPUT = REPO_ROOT / "tools/aws/sources/sts-session-tags.json" + +OPERATION_HEADING_RE = re.compile(r"^Passing session tags using (?P[A-Z][A-Za-z]+)$") +# The attribute and the claim are read from the markup, where the page nests the tag key's placeholder and a link +# inside the code element naming them. +def _markup(sentence: str) -> str: + """A sentence's pattern as the page's markup carries it, any whitespace between its words.""" + return sentence.replace(" ", r"\s+") + + +ATTRIBUTE_RE = re.compile(_markup(r"\bTo pass SAML attributes as session tags, include the ]*>Attribute " + r"element with the ]*>Name attribute set to " + r"]*>(?P.*?)\."), re.S) +CLAIM_RE = re.compile(_markup(r"\bThe nested claim format uses a structure within the ]*>(?P.*?) " + r"namespace in the JWT\."), re.S) +IDP_RE = re.compile(r"\bWhen using session tags, trust policies for all roles connected to the identity provider " + r"\(IdP\) passing tags must have the (?Psts:[A-Za-z]+) permission\.") +REQUEST_KEY_RE = re.compile(r"\b(?Paws:RequestTag) [–-] Compares the tag key-value pair passed in the request " + r"with the tag pair you specified in the policy\.") +SESSION_KEY_RE = re.compile(r"\bWhen you use the session credentials to make a subsequent request, the request " + r"context includes the (?Paws:PrincipalTag) context key\.") + + +def text(fragment: str) -> str: + """A fragment of a page as text, spaces collapsed, and none left before a mark an inline tag ends ahead of.""" + collapsed = re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", fragment))).strip() + return re.sub(r" (?=[.,;)])", "", re.sub(r"\( ", "(", collapsed)) + + +def code_text(fragment: str) -> str: + """A code element's text, whatever markup the page puts inside it.""" + return re.sub(r"\s+", "", html.unescape(re.sub(r"<[^>]+>", "", fragment))) + + +def body(page: str) -> str: + """The page's own content, its navigation left out.""" + match = re.search(r'
(?P.*?)(?:
dict[str, str]: + """Each second-level section of the page as its markup, under its heading as text.""" + parts = re.split(r"]*>(.*?)", body(page), flags=re.S) + return {text(parts[i]): parts[i + 1] for i in range(1, len(parts) - 1, 2)} + + +def _sentence(pattern: re.Pattern, where: str, what: str) -> re.Match: + found = pattern.search(where) + if found is None: + raise ValueError(f"{PAGE} no longer says {what}: its layout or its wording changed") + return found + + +def build(fetch) -> dict: + page = fetch(PAGE) + whole = text(body(page)) + federated = [] + for heading, markup in sections(page).items(): + operation = OPERATION_HEADING_RE.match(heading) + if operation is None: + continue + attribute = ATTRIBUTE_RE.search(markup) + claim = CLAIM_RE.search(markup) + if attribute is not None: + federated.append({"operation": operation.group("operation"), + "attribute": code_text(attribute.group("attribute")), + "row": text(attribute.group(0).replace(attribute.group("attribute"), + code_text(attribute.group("attribute"))))}) + elif claim is not None: + federated.append({"operation": operation.group("operation"), "claim": code_text(claim.group("claim")), + "row": text(claim.group(0))}) + if not federated: + raise ValueError(f"{PAGE} names no attribute or claim an identity provider passes tags in: its layout changed") + idp = _sentence(IDP_RE, whole, "which action a role an identity provider passes tags to needs of its trust") + request = _sentence(REQUEST_KEY_RE, whole, "which key the tags a request passes are present as") + session = _sentence(SESSION_KEY_RE, whole, "which key a session's later requests carry its tags as") + return { + "_source": { + "page": PAGE, + "fetcher": str(Path(__file__).resolve().relative_to(REPO_ROOT)), + "retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"), + "note": "The page's sentences on the session tags a federated assume passes, copied as they stand, with " + "what each names: the SAML attribute or the token claim each operation's section carries them " + "in, the action a role an identity provider is connected to needs of its trust policy, and the " + "keys a request and the session's later requests carry them as.", + }, + "federated": sorted(federated, key=lambda entry: entry["operation"]), + "permission": {"action": idp.group("action"), "identityProvider": idp.group(0)}, + "requestKey": {"key": request.group("key"), "sentence": request.group(0)}, + "sessionKey": {"key": session.group("key"), "sentence": session.group(0)}, + } + + +def fetch_url(url: str) -> str: + request = urllib.request.Request(url, headers={"User-Agent": "floci-tools"}) + with urllib.request.urlopen(request, timeout=60) as response: + return response.read().decode("utf-8") + + +def stale(vendored: dict, page: str) -> bool: + """Whether the page now gives something other than the vendored file, its date aside.""" + built = build(lambda url: page) + return {key: value for key, value in vendored.items() if key != "_source"} != { + key: value for key, value in built.items() if key != "_source"} + + +def main(argv: list[str] | None = None, fetch=fetch_url) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--verify", action="store_true", help="online: the vendored file matches the page") + args = parser.parse_args(argv) + try: + page = fetch(PAGE) + except OSError as e: + print(f"error: could not read the IAM user guide's session tags page ({e})", file=sys.stderr) + return 2 + if args.verify: + vendored = json.loads(OUTPUT.read_text(encoding="utf-8")) + if stale(vendored, page): + print(f"error: {OUTPUT.relative_to(REPO_ROOT)} no longer says what the IAM user guide does: run " + f"tools/aws/fetch_sts_session_tags.py and then make iam-authorized-actions-sync", file=sys.stderr) + return 1 + print(f"{OUTPUT.relative_to(REPO_ROOT)} matches the IAM user guide") + return 0 + built = build(lambda url: page) + OUTPUT.write_text(json.dumps(built, indent=2) + "\n", encoding="utf-8") + print(f"wrote {OUTPUT.relative_to(REPO_ROOT)} ({len(built['federated'])} operations)") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/aws/regen_iam_authorized_actions.py b/tools/aws/regen_iam_authorized_actions.py index b13eefe4d3..7ee028afdf 100644 --- a/tools/aws/regen_iam_authorized_actions.py +++ b/tools/aws/regen_iam_authorized_actions.py @@ -78,7 +78,12 @@ whatever the target's trust policy grants (`callerPolicyWhenChained`). AssumeRol which the reference lists with no authorized actions, take the value from the assertion's attribute or the token's claim the page names, and need the same action of a trust policy, "trust policies for all roles connected to an identity provider (IdP) must have the sts:SetSourceIdentity permission", where the reference's action of the -operation's name takes the key the page says the value is present in the request as, `sts:SourceIdentity`. +operation's name takes the key the page says the value is present in the request as, `sts:SourceIdentity`. The page on +session tags, copied by tools/aws/fetch_sts_session_tags.py into tools/aws/sources/sts-session-tags.json, gives the +same two operations `sts:TagSession` of a trust policy, "trust policies for all roles connected to the identity +provider (IdP) passing tags must have the sts:TagSession permission", for the tags the assertion's +`https://aws.amazon.com/SAML/Attributes/PrincipalTag:{TagKey}` attributes or the token's `https://aws.amazon.com/tags` +claim pass, where the reference's action of the operation's name takes `aws:RequestTag/${TagKey}`. The file also lists, for each credential scope whose REST routes `rest-routes.json` reads, the actions of that namespace the reference gives no resource type, from its `Actions`. A REST request @@ -146,7 +151,9 @@ ROUTES = REPO_ROOT / "src/main/resources/aws/rest-routes.json" S3_REQUIRED = REPO_ROOT / "tools/aws/sources/s3-required-actions.json" # The IAM user guide's page on source identity, as tools/aws/fetch_sts_source_identity.py copies it. SOURCE_IDENTITY = REPO_ROOT / "tools/aws/sources/sts-source-identity.json" -CARRIED_KEY_RE = re.compile(r"^aws:[A-Za-z]+$") +# The IAM user guide's page on session tags, as tools/aws/fetch_sts_session_tags.py copies it. +SESSION_TAGS = REPO_ROOT / "tools/aws/sources/sts-session-tags.json" +CARRIED_KEY_RE = re.compile(r"^aws:[A-Za-z]+(?:/\$\{TagKey\})?$") LEVEL_RE = re.compile(r"^([A-Z][A-Za-z0-9]+)(?: \((Bucket|Account)-level\))?$") SPECIFYING_RE = re.compile(r"\bspecifying (\w+) in the request") _S3_ACTIONS_TABLE = "https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazons3.html" @@ -573,6 +580,11 @@ def load_source_identity(source: Path = SOURCE_IDENTITY) -> dict | None: return json.loads(source.read_text(encoding="utf-8")) if source.exists() else None +def load_session_tags(source: Path = SESSION_TAGS) -> dict | None: + """The vendored IAM user guide page on session tags, none when the file is missing.""" + return json.loads(source.read_text(encoding="utf-8")) if source.exists() else None + + def request_members(namespace: str) -> dict[str, set[str]]: """The members of each operation's request in botocore's model of the namespace.""" data, _ = resolve_botocore_data(None) @@ -582,7 +594,8 @@ def request_members(namespace: str) -> dict[str, set[str]]: def companions(documents: list[dict], page: dict | None, - requests: dict[str, dict[str, set[str]]] | None = None) -> dict[str, dict[str, list[dict]]]: + requests: dict[str, dict[str, set[str]]] | None = None, + session_tags: dict | None = None) -> dict[str, dict[str, list[dict]]]: """The actions an operation needs beside its own only when it sets a value, from the IAM user guide's page on source identity (`page`, `load_source_identity`): for each operation the page names the request member passing the value in, the action the page says setting one needs, where the reference lists it among the operation's actions, with @@ -590,12 +603,15 @@ def companions(documents: list[dict], page: dict | None, allow it, which the page's sentence on role chaining says. The member must be one of the operation's request in botocore (`requests` by namespace, `request_members` unless given). For each operation the page names the SAML attribute or the token claim carrying the value of, the same action, with the attribute or claim and the key the - value is present in the request as.""" + value is present in the request as. And from the page on session tags (`session_tags`, `load_session_tags`), for + each operation it names the attribute or claim an identity provider passes tags in, the action it says a role the + provider is connected to needs of its trust policy, with the reference's spelling of the key the tags are present + in the request as and the key the session's requests carry them as.""" + found = _session_tag_companions(documents, session_tags) if not page: - return {} + return {namespace: dict(sorted(operations.items())) for namespace, operations in sorted(found.items())} action = page["permission"]["action"] namespace = action.split(":", 1)[0] - found = {} for document in documents: if document.get("Name") != namespace: continue @@ -611,9 +627,9 @@ def companions(documents: list[dict], page: dict | None, if entry["member"] not in members.get(entry["operation"], set()): raise ValueError(f"botocore gives {namespace}:{entry['operation']} no request member " f"{entry['member']}, which the source identity page passes the value in") - found.setdefault(namespace, {})[entry["operation"]] = [ + found.setdefault(namespace, {}).setdefault(entry["operation"], []).insert(0, {"action": action, "member": entry["member"], "carried": page["sessionKey"]["key"], - "callerPolicyWhenChained": bool(page["permission"].get("chaining"))}] + "callerPolicyWhenChained": bool(page["permission"].get("chaining"))}) # An operation taking the value from an identity provider's assertion or token rather than a request member # lists no authorized actions in the reference, so the page's sentence on roles an identity provider is # connected to says which it needs, where the reference's action of the operation's name takes the key the @@ -625,12 +641,42 @@ def companions(documents: list[dict], page: dict | None, or action.split(":", 1)[1] not in actions: continue source = {"attribute": entry["attribute"]} if "attribute" in entry else {"claim": entry["claim"]} - found.setdefault(namespace, {})[entry["operation"]] = [ + found.setdefault(namespace, {}).setdefault(entry["operation"], []).insert(0, {"action": action, **source, "key": entry["key"], "carried": page["sessionKey"]["key"], - "callerPolicyWhenChained": False}] + "callerPolicyWhenChained": False}) return {namespace: dict(sorted(operations.items())) for namespace, operations in sorted(found.items())} +def _session_tag_companions(documents: list[dict], page: dict | None) -> dict[str, dict[str, list[dict]]]: + """The session tag companions of `companions`: an operation the page names the attribute or claim of needs the + page's action where the reference's action of the operation's name takes a key of the page's request key, and + the namespace publishes the action. The key is the reference's spelling (`aws:RequestTag/${TagKey}`), and the key + the session's requests carry the tags as takes the same placeholder.""" + if not page or not page["permission"].get("identityProvider"): + return {} + action = page["permission"]["action"] + namespace, name = action.split(":", 1) + found = {} + for document in documents: + if document.get("Name") != namespace: + continue + actions = {reference.get("Name"): reference for reference in document.get("Actions") or []} + if name not in actions: + continue + for entry in page["federated"]: + reference = actions.get(entry["operation"]) + keys = [key for key in (reference or {}).get("ActionConditionKeys") or [] + if key.startswith(page["requestKey"]["key"] + "/")] + if len(keys) != 1: + continue + placeholder = keys[0][len(page["requestKey"]["key"]):] + source = {"attribute": entry["attribute"]} if "attribute" in entry else {"claim": entry["claim"]} + found.setdefault(namespace, {}).setdefault(entry["operation"], []).append( + {"action": action, **source, "key": keys[0], "carried": page["sessionKey"]["key"] + placeholder, + "callerPolicyWhenChained": False}) + return found + + def vendored_sections(documents: list[dict], page: dict | None, models: dict | None, query: dict[str, list[str]] | None, renamed: dict[str, dict[str, str]]) -> dict[str, dict]: """The `authorizedByModel`, `versioned` and `spellings` sections, given the operations `authorized_actions` renames @@ -648,11 +694,12 @@ def vendored_sections(documents: list[dict], page: dict | None, models: dict | N def build(documents: list[dict], provenance: str, routed: list[str], methods: dict[str, dict[str, list[str]]] | None = None, page: dict | None = None, models: dict | None = None, query: dict[str, list[str]] | None = None, - source_identity: dict | None = None, requests: dict[str, dict[str, set[str]]] | None = None) -> dict: + source_identity: dict | None = None, requests: dict[str, dict[str, set[str]]] | None = None, + session_tags: dict | None = None) -> dict: """The vendored document; `page` is the S3 user guide's operations (`load_s3_required`), `models` the vendored routes' models, `query` botocore's S3 query parameters (`s3_query_parameters`, unless given), `source_identity` - the IAM user guide's page on source identity (`load_source_identity`) and `requests` botocore's request members - (`request_members`, unless given).""" + the IAM user guide's page on source identity (`load_source_identity`), `requests` botocore's request members + (`request_members`, unless given) and `session_tags` its page on session tags (`load_session_tags`).""" if query is None and any(document.get("Name") == "s3" for document in documents): query = s3_query_parameters() renamed = authorized_actions(documents, page, models, query) @@ -667,7 +714,7 @@ def build(documents: list[dict], provenance: str, routed: list[str], "actionsWithoutResourceTypes": actions_without_resource_types(documents, routed), "authorizedByMethod": authorized_by_method(documents, methods or {}, renamed), **vendored_sections(documents, page, models, query, renamed), - "companions": companions(documents, source_identity, requests), + "companions": companions(documents, source_identity, requests, session_tags), } @@ -755,7 +802,7 @@ def _companion_source_holds(namespace: str, companion: dict) -> bool: source = fields - {"key"} return "key" in fields and source in ({"attribute"}, {"claim"}) \ and str(companion[source.pop()]).startswith("https://") \ - and str(companion["key"]).startswith(namespace + ":") + and str(companion["key"]).startswith((namespace + ":", "aws:")) def _unscoped_problems(unscoped: object, routed: list[str]) -> list[str]: @@ -936,6 +983,15 @@ def main(argv: list[str] | None = None) -> int: file=sys.stderr) return 1 source_identity = load_source_identity() + session_tags = load_session_tags() + if args.source_dir is None and session_tags is not None: + import fetch_sts_session_tags + if fetch_sts_session_tags.stale(session_tags, fetch_sts_session_tags.fetch_url( + fetch_sts_session_tags.PAGE)): + print(f"error: {SESSION_TAGS.relative_to(REPO_ROOT)} no longer says what " + f"{fetch_sts_session_tags.PAGE} does (run tools/aws/fetch_sts_session_tags.py)", + file=sys.stderr) + return 1 if args.source_dir is None and source_identity is not None: import fetch_sts_source_identity if fetch_sts_source_identity.stale(source_identity, fetch_sts_source_identity.fetch_url( @@ -958,7 +1014,7 @@ def main(argv: list[str] | None = None) -> int: return 2 untrue, added = verify_against(vendored, upstream) sections = {**vendored_sections(documents, page, models, query, upstream), - "companions": companions(documents, source_identity)} + "companions": companions(documents, source_identity, None, session_tags)} for section, value in sections.items(): if vendored_document.get(section, {}) != value: untrue.append(f"{section} differs from what AWS gives: expected {json.dumps(value)}") @@ -989,7 +1045,7 @@ def main(argv: list[str] | None = None) -> int: routed = routed_namespaces(routes) methods = route_methods(routes) document = build(documents, provenance, routed, methods, load_s3_required(), routes["models"], - source_identity=load_source_identity()) + source_identity=load_source_identity(), session_tags=load_session_tags()) except (OSError, ValueError) as e: print(f"error: could not read the Service Reference ({e})", file=sys.stderr) return 2 diff --git a/tools/aws/sources/sts-session-tags.json b/tools/aws/sources/sts-session-tags.json new file mode 100644 index 0000000000..74dd44e0a6 --- /dev/null +++ b/tools/aws/sources/sts-session-tags.json @@ -0,0 +1,32 @@ +{ + "_source": { + "page": "https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html", + "fetcher": "tools/aws/fetch_sts_session_tags.py", + "retrieved": "2026-11-29", + "note": "The page's sentences on the session tags a federated assume passes, copied as they stand, with what each names: the SAML attribute or the token claim each operation's section carries them in, the action a role an identity provider is connected to needs of its trust policy, and the keys a request and the session's later requests carry them as." + }, + "federated": [ + { + "operation": "AssumeRoleWithSAML", + "attribute": "https://aws.amazon.com/SAML/Attributes/PrincipalTag:{TagKey}", + "row": "To pass SAML attributes as session tags, include the Attribute element with the Name attribute set to https://aws.amazon.com/SAML/Attributes/PrincipalTag:{TagKey}." + }, + { + "operation": "AssumeRoleWithWebIdentity", + "claim": "https://aws.amazon.com/tags", + "row": "The nested claim format uses a structure within the https://aws.amazon.com/tags namespace in the JWT." + } + ], + "permission": { + "action": "sts:TagSession", + "identityProvider": "When using session tags, trust policies for all roles connected to the identity provider (IdP) passing tags must have the sts:TagSession permission." + }, + "requestKey": { + "key": "aws:RequestTag", + "sentence": "aws:RequestTag \u2013 Compares the tag key-value pair passed in the request with the tag pair you specified in the policy." + }, + "sessionKey": { + "key": "aws:PrincipalTag", + "sentence": "When you use the session credentials to make a subsequent request, the request context includes the aws:PrincipalTag context key." + } +} diff --git a/tools/aws/test_fetch_sts_session_tags.py b/tools/aws/test_fetch_sts_session_tags.py new file mode 100644 index 0000000000..bda9716c9b --- /dev/null +++ b/tools/aws/test_fetch_sts_session_tags.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 +"""Tests for fetch_sts_session_tags.py, on a page in the IAM user guide's markup.""" +from __future__ import annotations + +import pytest + +import fetch_sts_session_tags as f + +THINGS = ("

Things to know about session tags

When using session tags, trust policies for all roles connected " + "to the identity provider (IdP) passing tags must have the sts:TagSession permission.

When " + "you use the session credentials to make a subsequent request, the request context includes the " + "aws:PrincipalTag context key.

") +PERMISSIONS = ("

Permissions required to add session tags

  • aws:RequestTag – Compares the " + "tag key-value pair passed in the request with the tag pair you specified in the policy.

") +SAML = ('

Passing session tags using AssumeRoleWithSAML

To pass SAML attributes as session tags, include the ' + 'Attribute element with\n the Name attribute set to\n ' + 'https://aws.amazon.com/SAML/Attributes/PrincipalTag:{' + 'TagKey}.\n Use the AttributeValue element.

') +WEB_IDENTITY = ('

Passing session tags using AssumeRoleWithWebIdentity

The nested claim format uses a structure ' + 'within the\n https://aws.amazon.com/tags namespace in the JWT. In this ' + 'format:

') +ASSUME_ROLE = "

Passing session tags using AssumeRole

Use the Tags parameter.

" + + +def page(*parts: str) -> str: + sections = parts or (THINGS, PERMISSIONS, ASSUME_ROLE, SAML, WEB_IDENTITY) + return f'

Session tags

{"".join(sections)}
' + + +def test_each_federated_operation_is_read_with_the_attribute_or_claim_carrying_its_tags(): + built = f.build(lambda url: page()) + federated = {entry["operation"]: entry for entry in built["federated"]} + # A section naming neither, as AssumeRole's, is not read here. + assert set(federated) == {"AssumeRoleWithSAML", "AssumeRoleWithWebIdentity"} + assert federated["AssumeRoleWithSAML"]["attribute"] == "https://aws.amazon.com/SAML/Attributes/PrincipalTag:{TagKey}" + assert federated["AssumeRoleWithWebIdentity"]["claim"] == "https://aws.amazon.com/tags" + assert built["permission"]["action"] == "sts:TagSession" + assert built["requestKey"]["key"] == "aws:RequestTag" + assert built["sessionKey"]["key"] == "aws:PrincipalTag" + + +def test_a_page_whose_layout_or_wording_changed_is_refused(): + with pytest.raises(ValueError, match="names no attribute or claim"): + f.build(lambda url: page(THINGS, PERMISSIONS, ASSUME_ROLE)) + with pytest.raises(ValueError, match="which action a role an identity provider passes tags to needs"): + f.build(lambda url: page(PERMISSIONS, SAML, THINGS.replace("must have the", "should have the"))) + with pytest.raises(ValueError, match="which key the tags a request passes are present as"): + f.build(lambda url: page(THINGS, SAML)) + + +def test_the_file_is_stale_when_the_page_says_something_else(): + vendored = f.build(lambda url: page()) + assert not f.stale(vendored, page()) + assert f.stale(vendored, page(THINGS, PERMISSIONS, SAML.replace("PrincipalTag:", "SessionTag:"), WEB_IDENTITY)) diff --git a/tools/aws/test_regen_iam_authorized_actions.py b/tools/aws/test_regen_iam_authorized_actions.py index 185edbd2e5..44035eed7b 100644 --- a/tools/aws/test_regen_iam_authorized_actions.py +++ b/tools/aws/test_regen_iam_authorized_actions.py @@ -830,3 +830,50 @@ def test_a_malformed_federated_companion_is_rejected(companion): document = anchored() document["companions"] = {"sts": {"AssumeRoleWithSAML": [companion]}} assert any("companions sts:AssumeRoleWithSAML" in problem for problem in r.validate(document, [])) + + +SESSION_TAGS_PAGE = { + "federated": [{"operation": "AssumeRoleWithSAML", + "attribute": "https://aws.amazon.com/SAML/Attributes/PrincipalTag:{TagKey}"}, + {"operation": "AssumeRoleWithWebIdentity", "claim": "https://aws.amazon.com/tags"}], + "permission": {"action": "sts:TagSession", "identityProvider": "When using session tags, trust policies ..."}, + "requestKey": {"key": "aws:RequestTag"}, + "sessionKey": {"key": "aws:PrincipalTag"}, +} + + +def tagged_sts(saml_keys: list[str], actions: list[str] | None = None) -> dict: + document = service("sts", {"AssumeRole": ["sts:AssumeRole"], "AssumeRoleWithSAML": [], + "AssumeRoleWithWebIdentity": []}, + actions if actions is not None else ["AssumeRole", "TagSession"]) + document["Actions"] += [{"Name": "AssumeRoleWithSAML", "ActionConditionKeys": saml_keys}, + {"Name": "AssumeRoleWithWebIdentity", + "ActionConditionKeys": ["aws:RequestTag/${TagKey}", "aws:TagKeys"]}] + return document + + +def test_a_federated_operation_passing_tags_needs_the_tagging_action_with_the_references_key(): + found = r.companions([tagged_sts(["aws:RequestTag/${TagKey}", "aws:TagKeys"])], None, None, + SESSION_TAGS_PAGE)["sts"] + assert found["AssumeRoleWithSAML"] == [{ + "action": "sts:TagSession", "attribute": "https://aws.amazon.com/SAML/Attributes/PrincipalTag:{TagKey}", + "key": "aws:RequestTag/${TagKey}", "carried": "aws:PrincipalTag/${TagKey}", "callerPolicyWhenChained": False}] + assert found["AssumeRoleWithWebIdentity"][0]["claim"] == "https://aws.amazon.com/tags" + document = anchored() + document["companions"] = {"sts": found} + assert r.validate(document, []) == [] + + +def test_no_tagging_companion_where_the_reference_gives_no_such_key_or_no_tagging_action(): + found = r.companions([tagged_sts(["sts:RoleSessionName"])], None, None, SESSION_TAGS_PAGE)["sts"] + assert "AssumeRoleWithSAML" not in found and "AssumeRoleWithWebIdentity" in found + assert r.companions([tagged_sts(["aws:RequestTag/${TagKey}"], ["AssumeRole"])], None, None, + SESSION_TAGS_PAGE) == {} + + +def test_both_pages_give_a_federated_operation_its_companions_source_identity_first(): + document = federated_sts(["sts:SourceIdentity", "aws:RequestTag/${TagKey}"]) + document["Actions"].append({"Name": "TagSession"}) + found = r.companions([document], FEDERATED_PAGE, STS_REQUESTS, SESSION_TAGS_PAGE)["sts"] + assert [companion["action"] for companion in found["AssumeRoleWithSAML"]] == [ + "sts:SetSourceIdentity", "sts:TagSession"]