diff --git a/docs/services/iam.md b/docs/services/iam.md index 7770d9a8ba..094766e969 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -4113,8 +4113,9 @@ floci populates: matches: a `Deny` on `DateLessThan` `aws:TokenIssueTime` refuses the sessions issued before that time and leaves later sessions and long-term keys alone. A session stored by an earlier floci version, which did not record its issue time, carries no value for it. -- `aws:SourceIdentity`: the source identity an `AssumeRole` session was minted with, on every request - it makes and every session assumed from it, as the IAM user guide gives it: "after a source identity +- `aws:SourceIdentity`: the source identity an `AssumeRole`, `AssumeRoleWithSAML` or + `AssumeRoleWithWebIdentity` session was minted with, on every request it makes and every session + assumed from it, as the IAM user guide gives it: "after a source identity is set, the aws:SourceIdentity key is present in all subsequent requests made during the role session". The key is the one the generated `iam-authorized-actions.json` gives the value its operation sets. Absent for a session minted with none and for every long-term key. See diff --git a/docs/services/sts.md b/docs/services/sts.md index dc3381bc5b..a47fb40c41 100644 --- a/docs/services/sts.md +++ b/docs/services/sts.md @@ -666,6 +666,23 @@ sentence on role chaining. A chained request naming the value its session carrie and one naming another is refused, before the trust policy is read, with `ValidationError` and `The source identity is already set for this assume role session`, as AWS answers it. +A federated assume sets the session's source identity from what its identity provider asserts, as +the same vendored page gives it: "to set a SAML attribute for source identity, include the Attribute +element with the Name attribute set to https://aws.amazon.com/SAML/Attributes/SourceIdentity", and +"include source identity in the https://aws.amazon.com/source_identity namespace in the token when +you submit the AssumeRoleWithWebIdentity request". The generated `iam-authorized-actions.json` gives +each operation the attribute or the claim, the Service Authorization Reference giving both actions +`sts:SourceIdentity`. The value is one of botocore's `sourceIdentityType`, the shape botocore gives +the response's `SourceIdentity`, and the response returns it. The trust policy reads it as +`sts:SourceIdentity` and has to allow setting it, "trust policies for all roles connected to an +identity provider (IdP) must have the sts:SetSourceIdentity permission", read before the assume, as +for `AssumeRole`, a refusal reading +`Not authorized to perform sts:SetSourceIdentity on resource: `. The session's requests carry +it as `aws:SourceIdentity`, and a session assumed from it carries it on. A calling session's own +source identity reaches neither operation, neither being a chained assume: "calling +AssumeRoleWithSAML does not require the use of AWS security credentials", and so too for +`AssumeRoleWithWebIdentity`. + ### Known limitations - **The transitive tag key is read for the trust policy alone.** `sts:TransitiveTagKeys` is @@ -676,13 +693,10 @@ and one naming another is refused, before the trust policy is read, with `Valida `sts:AssumeRole` and names whichever refuses. AWS's evaluation suite records that order where a statement granting both is conditioned on another `sts:SourceIdentity`, and records `sts:AssumeRole` where the chained session's target grants the assume alone. -- **A federated assume's source identity is not read.** The - `https://aws.amazon.com/SAML/Attributes/SourceIdentity` attribute of an `AssumeRoleWithSAML` - assertion and the `https://aws.amazon.com/source_identity` claim of an - `AssumeRoleWithWebIdentity` token set no source identity yet. A calling session's source identity - does not reach either: neither is a chained assume, "calling AssumeRoleWithSAML does not require the - use of AWS security credentials", and so too for `AssumeRoleWithWebIdentity`, so theirs is the - assertion's or the token's. +- **A federated assume's malformed source identity is refused in Floci's words.** An assertion's + `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 diff --git a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java index ad39f7eaa5..4986e249a3 100644 --- a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java @@ -661,6 +661,9 @@ public class IamEnforcementFilter implements ContainerRequestFilter { boolean roleSession = callerArns.map(arns -> CallerArns.TYPE_ASSUMED_ROLE.equals(arns.principalType())) .orElse(false); for (Companion companion : companions) { + if (companion.member() == null) { + continue; + } boolean sets = IamConditionContextResolver.namesMember(ctx, companion.member()) || (conditionContext != null && conditionContext.containsKey(companion.carried())); if (sets && roleSession && companion.callerPolicyWhenChained() @@ -1177,7 +1180,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter { Map> context) { Map> carried = context; for (Companion companion : companions) { - List value = carried == null ? null : carried.get(companion.carried()); + List value = carried == null || companion.member() == null ? null + : carried.get(companion.carried()); if (value != null && !value.isEmpty() && !IamConditionContextResolver.namesMember(ctx, companion.member())) { carried = IamConditionContextResolver.withCarriedMember(carried, action, companion.member(), diff --git a/src/main/java/io/floci/aws/core/common/QueryConstraintCheck.java b/src/main/java/io/floci/aws/core/common/QueryConstraintCheck.java index 9e5c7d7874..6034de6d08 100644 --- a/src/main/java/io/floci/aws/core/common/QueryConstraintCheck.java +++ b/src/main/java/io/floci/aws/core/common/QueryConstraintCheck.java @@ -2,6 +2,7 @@ package io.floci.aws.core.common; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.ws.rs.core.MultivaluedHashMap; import jakarta.ws.rs.core.MultivaluedMap; import java.math.BigInteger; @@ -191,6 +192,23 @@ public final class QueryConstraintCheck { return structureViolations(shape, "", "", params, documented); } + /** + * The violations {@code value} carries as {@code operation}'s top-level {@code member}, held to what the model + * declares for that member's shape as a request naming it would be: a value that reaches the operation some other + * way than as the member, as a source identity reaches AssumeRoleWithSAML in its assertion, the model giving that + * operation's response the shape AssumeRole's {@code SourceIdentity} member has. None for a member the operation + * does not declare. + */ + public List valueViolations(String operation, String member, String value) { + JsonNode shapeName = shapes.path(operations.path(operation).asText()).path("members").path(member); + if (!shapeName.isTextual()) { + return List.of(); + } + MultivaluedMap params = new MultivaluedHashMap<>(); + params.add(member, value); + return memberViolations(shapeName.asText(), member, VendoredShapes.memberName(member), false, params); + } + /** * The violations the members of {@code structure} carry, in the order the model lists them. * {@code prefix} is what the request names them under and {@code path} what a message calls diff --git a/src/main/java/io/floci/aws/core/common/WebIdentityToken.java b/src/main/java/io/floci/aws/core/common/WebIdentityToken.java index 03e0a406fd..09b224cc57 100644 --- a/src/main/java/io/floci/aws/core/common/WebIdentityToken.java +++ b/src/main/java/io/floci/aws/core/common/WebIdentityToken.java @@ -1,5 +1,8 @@ package io.floci.aws.core.common; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.MissingNode; + import java.util.List; import java.util.Map; @@ -13,12 +16,19 @@ import java.util.Map; * AWS publishes for them, and empty when it passes none * @param transitiveTagKeys the keys among those tags the token asks to set as transitive, from * either format, and empty when it asks for none + * @param claims the token's whole payload, for a claim a caller names itself: the source identity the + * generated table says a token carries */ public record WebIdentityToken(String issuer, String subject, List audiences, Map principalTags, - List transitiveTagKeys) { + List transitiveTagKeys, JsonNode claims) { public WebIdentityToken(String issuer, String subject, List audiences) { this(issuer, subject, audiences, Map.of(), List.of()); } + + public WebIdentityToken(String issuer, String subject, List audiences, + Map principalTags, List transitiveTagKeys) { + this(issuer, subject, audiences, principalTags, transitiveTagKeys, MissingNode.getInstance()); + } } 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 49345bfed6..132d4d96ff 100644 --- a/src/main/java/io/floci/aws/core/common/WebIdentityTokenVerifier.java +++ b/src/main/java/io/floci/aws/core/common/WebIdentityTokenVerifier.java @@ -155,7 +155,7 @@ public class WebIdentityTokenVerifier { } return new WebIdentityToken(issuer, subject, audiences, readPrincipalTags(claims), - readTransitiveTagKeys(claims)); + readTransitiveTagKeys(claims), claims); } private void verifyValidityWindow(JsonNode claims) throws InvalidTokenException { 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 78724465c0..07f1a6af2a 100644 --- a/src/main/java/io/floci/aws/services/iam/IamAuthorizedActions.java +++ b/src/main/java/io/floci/aws/services/iam/IamAuthorizedActions.java @@ -92,8 +92,15 @@ public final class IamAuthorizedActions { * whatever the resource's policy grants: "when you assume a role with another role, called role chaining, * permissions for sts:SetSourceIdentity are required in both the permissions policy of the principal who is * assuming the role and in the role trust policy of the target role". + * + *

An operation taking the value from an identity provider names the SAML {@code attribute} or the token + * {@code claim} carrying it instead of a member, and the {@code key} the value is present in the request as: + * an AssumeRoleWithSAML whose assertion carries {@code https://aws.amazon.com/SAML/Attributes/SourceIdentity} + * needs {@code sts:SetSourceIdentity} of the role's trust policy, read with it as {@code sts:SourceIdentity}. + * Each of {@code member}, {@code attribute}, {@code claim} and {@code key} is null where the file names none. */ - public record Companion(String action, String member, String carried, boolean callerPolicyWhenChained) { + public record Companion(String action, String member, String attribute, String claim, String key, + String carried, boolean callerPolicyWhenChained) { } /** @@ -208,14 +215,20 @@ public final class IamAuthorizedActions { namespaces.properties().forEach(namespace -> namespace.getValue().properties().forEach(operation -> { List needed = new ArrayList<>(); for (JsonNode companion : operation.getValue()) { - String member = companion.path("member").asText(""); + String member = companion.path("member").asText(null); + String attribute = companion.path("attribute").asText(null); + String claim = companion.path("claim").asText(null); + String key = companion.path("key").asText(null); String carried = companion.path("carried").asText(""); - if (member.isEmpty() || !carried.startsWith("aws:")) { + boolean fromMember = member != null && attribute == null && claim == null; + boolean fromProvider = member == null && key != null && (attribute == null) != (claim == null); + if (!(fromMember || fromProvider) || !carried.startsWith("aws:")) { throw new IllegalStateException(RESOURCE_NAME + " gives " + namespace.getKey() + ":" - + operation.getKey() + " a companion naming no member or no global key"); + + operation.getKey() + " a companion naming no source of its value or no global key"); } needed.add(new Companion(actionOf(namespace.getKey(), operation.getKey(), companion.path("action")), - member, carried, companion.path("callerPolicyWhenChained").asBoolean(false))); + member, attribute, claim, key, carried, + companion.path("callerPolicyWhenChained").asBoolean(false))); } found.put(namespace.getKey() + ":" + operation.getKey(), List.copyOf(needed)); })); 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 60235a2c8a..e8364c6fe6 100644 --- a/src/main/java/io/floci/aws/services/iam/SAMLAssertionVerifier.java +++ b/src/main/java/io/floci/aws/services/iam/SAMLAssertionVerifier.java @@ -73,11 +73,15 @@ final class SAMLAssertionVerifier { * {@code principalTags} is empty when it carries no session tags, and * {@code transitiveTagKeys} is empty when it asks for none to be transitive, which is AWS's * default for a session. {@code recipient} is the sign-in endpoint the bearer confirmation was - * accepted for, the endpoint a trust policy tests as {@code saml:aud}. + * accepted for, the endpoint a trust policy tests as {@code saml:aud}. {@code attributes} holds + * every attribute of the assertion's statement, by its name, with the values it carries in order, + * for an attribute a caller names itself: the source identity the generated table says an + * assertion carries. */ record Verified(String issuer, String subject, String subjectType, String nameQualifier, Instant expiration, List roles, String roleSessionName, - Map principalTags, List transitiveTagKeys, String recipient) {} + Map principalTags, List transitiveTagKeys, String recipient, + Map> attributes) {} record RolePair(String roleArn, String principalArn) {} static Verified verify(String encoded, SAMLProvider provider, Instant now) throws InvalidAssertionException { @@ -210,7 +214,8 @@ final class SAMLAssertionVerifier { String nameQualifier = Base64.getEncoder().encodeToString( Digests.sha1((issuer + provider.getArn()).getBytes(StandardCharsets.UTF_8))); return new Verified(issuer, name, subjectType, nameQualifier, notOnOrAfter, roles, - roleSessionName, principalTags(attributes), transitiveTagKeys(attributes), acceptedRecipient); + roleSessionName, principalTags(attributes), transitiveTagKeys(attributes), acceptedRecipient, + attributeValues(attributes)); } catch (InvalidAssertionException e) { throw e; } catch (Exception e) { @@ -299,6 +304,20 @@ final class SAMLAssertionVerifier { return keys; } + /** Each attribute's values, by the attribute's name, in the order the assertion gives them. */ + private static Map> attributeValues(NodeList attributes) { + Map> values = new LinkedHashMap<>(); + for (int i = 0; i < attributes.getLength(); i++) { + Element attribute = (Element) attributes.item(i); + List own = values.computeIfAbsent(attribute.getAttribute("Name"), ignored -> new ArrayList<>()); + NodeList attributeValues = attribute.getElementsByTagNameNS(SAML, "AttributeValue"); + for (int j = 0; j < attributeValues.getLength(); j++) { + own.add(attributeValues.item(j).getTextContent()); + } + } + return values; + } + /** What an attribute carrying no single value for its tag is refused with, Floci's wording. */ static String singleValueRequired(String key) { return "Session tag " + key + " must carry exactly one AttributeValue:" 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 25d6294297..5933669958 100644 --- a/src/main/java/io/floci/aws/services/iam/SAMLTrustPolicyEvaluator.java +++ b/src/main/java/io/floci/aws/services/iam/SAMLTrustPolicyEvaluator.java @@ -25,13 +25,26 @@ 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. {@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. + * ({@code aws:ResourceTag/}, {@code iam:ResourceTag/}), which a policy reads on it, + * beside the source identity the assertion sets, as {@code sts:SourceIdentity}. */ public boolean allows(String document, String providerArn, Map> claims, String roleSessionName, Map> roleTags) { return allows(SAML_ACTION, document, providerArn, claims, roleSessionName, roleTags); } + /** + * 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. + */ + public boolean allowsCompanion(String action, String document, String providerArn, + Map> claims, String roleSessionName, + Map> roleTags) { + 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. 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 8402542cef..7b766dcb23 100644 --- a/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java +++ b/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java @@ -1,5 +1,6 @@ package io.floci.aws.services.iam; +import com.fasterxml.jackson.databind.JsonNode; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AccountResolver; import io.floci.aws.core.common.AwsArnUtils; @@ -317,6 +318,66 @@ public class StsQueryHandler { .findFirst(); } + /** + * What the generated {@code iam-authorized-actions.json} gives a federated assume's source identity: the SAML + * attribute or the token claim carrying it, the key the trust policy reads it as, the action it needs of the trust + * policy and the key the session's requests carry it as. Empty were the file to give none. + */ + private static Optional federatedSourceIdentity(String operation) { + return IamAuthorizedActions.companions(operation).stream() + .filter(companion -> companion.attribute() != null || companion.claim() != null) + .findFirst(); + } + + /** + * 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 + * botocore's {@code sourceIdentityType}, the shape botocore gives these operations' response member as it does + * AssumeRole's request member. The two sentences are Floci's own: nothing published says what AWS answers. + */ + private static String federatedSourceIdentityValue(List values, String carrier) { + if (values.isEmpty()) { + return null; + } + if (values.size() > 1) { + throw new AwsException("InvalidIdentityToken", "The " + carrier + + " must carry exactly one value: a session takes a single source identity.", 400); + } + List violations = StsRequestShapes.valueViolations("AssumeRole", SOURCE_IDENTITY, values.getFirst()); + if (!violations.isEmpty()) { + throw new AwsException("InvalidIdentityToken", "The " + carrier + " is not a valid source identity: " + + String.join("; ", violations), 400); + } + return values.getFirst(); + } + + /** + * The trust policy's keys given in full, with the source identity under the key {@code key} gives it; the keys as + * they are where there is no source identity or the table gives none. + */ + private static Map> withSourceIdentity(Map> keys, + IamAuthorizedActions.Companion key, + String sourceIdentity) { + if (sourceIdentity == null || key == null) { + return keys; + } + Map> withIdentity = new LinkedHashMap<>(keys); + withIdentity.put(key.key(), List.of(sourceIdentity)); + return withIdentity; + } + + /** + * Records the source identity a federated session is minted with under the key {@code key} gives its requests, + * which a session assumed from it carries on: it "persists across chained role sessions". Nothing where there is + * no source identity or the table gives no key. + */ + private void recordSourceIdentity(String accessKeyId, IamAuthorizedActions.Companion key, + String sourceIdentity) { + if (sourceIdentity != null && key != null) { + iamService.recordCarriedKeys(accessKeyId, Map.of(key.carried(), sourceIdentity)); + } + } + /** * An AssumeRole naming a session tag key twice, in any case, is refused as AWS refuses it, with * {@code InvalidParameterValue} and "Duplicate tag keys found. Please note that Tag keys are case insensitive.", @@ -858,6 +919,9 @@ public class StsQueryHandler { // the keys to set as transitive arrive in the same namespace. iamService.recordSessionTags(accessKeyId, carriedTags, verified != null ? verified.transitiveTagKeys() : List.of()); + String sourceIdentity = verified != null ? verified.sourceIdentity() : null; + recordSourceIdentity(accessKeyId, federatedSourceIdentity("sts:AssumeRoleWithWebIdentity").orElse(null), + sourceIdentity); String result = new XmlBuilder() .raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration)) @@ -869,6 +933,7 @@ public class StsQueryHandler { .elem("Provider", provider) .elem("Audience", audience) .elem("SubjectFromWebIdentityToken", subject) + .elem(SOURCE_IDENTITY, sourceIdentity) .build(); return Response.ok(AwsQueryResponse.envelope("AssumeRoleWithWebIdentity", AwsNamespaces.STS, result)).build(); } @@ -895,7 +960,7 @@ public class StsQueryHandler { /** The claims of a token Floci issued and verified, used to fill the response accurately. */ private record VerifiedWebIdentity(String issuer, String subject, String audience, Map principalTags, - List transitiveTagKeys) {} + List transitiveTagKeys, String sourceIdentity) {} private record WebIdentityOutcome(VerifiedWebIdentity verified, IamRole role, Response denial) { @@ -983,7 +1048,23 @@ public class StsQueryHandler { "sub", List.of(claims.subject()), "aud", claims.audiences()); - Map> roleTags = roleTagKeys(role.get()); + // The source identity the token sets, which the generated table says it carries in a claim of its own: + // "include source identity in the https://aws.amazon.com/source_identity namespace in the token". The trust + // policy reads it as sts:SourceIdentity, beside the role's tags, and has to allow setting it: "trust policies + // for all roles connected to an identity provider (IdP) must have the sts:SetSourceIdentity permission". + IamAuthorizedActions.Companion sourceIdentityKey = federatedSourceIdentity("sts:AssumeRoleWithWebIdentity") + .orElse(null); + String sourceIdentity = sourceIdentityKey == null ? null + : tokenSourceIdentity(claims.claims().path(sourceIdentityKey.claim()), sourceIdentityKey.claim()); + Map> roleTags = withSourceIdentity(roleTagKeys(role.get()), sourceIdentityKey, + sourceIdentity); + if (sourceIdentity != null && !webIdentityTrustEvaluator.allowsCompanion(sourceIdentityKey.action(), + role.get().getAssumeRolePolicyDocument(), oidcProviderArn, issuerKeyPrefix, conditionClaims, + sessionName, roleTags)) { + LOG.debugv("Trust policy on role {0} does not permit setting the source identity of subject {1}", + roleArn, claims.subject()); + return WebIdentityOutcome.deny(accessDenied(sourceIdentityKey.action(), roleArn)); + } if (!webIdentityTrustEvaluator.allows(role.get().getAssumeRolePolicyDocument(), oidcProviderArn, issuerKeyPrefix, conditionClaims, sessionName, roleTags)) { LOG.debugv("Trust policy on role {0} denies web identity subject {1}", @@ -1004,7 +1085,23 @@ public class StsQueryHandler { .orElse(STS_AUDIENCE); return WebIdentityOutcome.allow( new VerifiedWebIdentity(claims.issuer(), claims.subject(), audience, - claims.principalTags(), claims.transitiveTagKeys()), role.get()); + claims.principalTags(), claims.transitiveTagKeys(), sourceIdentity), role.get()); + } + + /** + * The source identity a token's {@code claim} carries: none where the token has no such claim, its text where it + * is a string, and refused with InvalidIdentityToken, in Floci's own sentence, where it is anything else, a session + * taking a single value. + */ + private static String tokenSourceIdentity(JsonNode value, String claim) { + if (value.isMissingNode() || value.isNull()) { + return null; + } + if (!value.isTextual()) { + throw new AwsException("InvalidIdentityToken", "The token claim " + claim + + " must be a string: a session takes a single source identity.", 400); + } + return federatedSourceIdentityValue(List.of(value.asText()), "token claim " + claim); } /** @@ -1104,7 +1201,23 @@ public class StsQueryHandler { "iss", List.of(verified.issuer()), "sub", List.of(verified.subject()), "namequalifier", List.of(verified.nameQualifier())); - Map> roleTags = roleTagKeys(role); + // The source identity the assertion sets, which the generated table says it carries in an attribute of its + // own: "to set a SAML attribute for source identity, include the Attribute element with the Name attribute + // set to https://aws.amazon.com/SAML/Attributes/SourceIdentity". The trust policy reads it as + // sts:SourceIdentity, beside the role's tags, and has to allow setting it: "trust policies for all roles + // connected to an identity provider (IdP) must have the sts:SetSourceIdentity permission". + IamAuthorizedActions.Companion sourceIdentityKey = federatedSourceIdentity("sts:AssumeRoleWithSAML") + .orElse(null); + String sourceIdentity = sourceIdentityKey == null ? null : federatedSourceIdentityValue( + verified.attributes().getOrDefault(sourceIdentityKey.attribute(), List.of()), + "SAML attribute " + sourceIdentityKey.attribute()); + Map> roleTags = withSourceIdentity(roleTagKeys(role), sourceIdentityKey, sourceIdentity); + if (sourceIdentity != null && !samlTrustEvaluator.allowsCompanion(sourceIdentityKey.action(), + role.getAssumeRolePolicyDocument(), principalArn, assertionClaims, verified.roleSessionName(), + roleTags)) { + throw new AwsException("AccessDenied", "Not authorized to perform " + sourceIdentityKey.action() + + " on resource: " + roleArn, 403); + } if (!samlTrustEvaluator.allows(role.getAssumeRolePolicyDocument(), principalArn, assertionClaims, verified.roleSessionName(), roleTags)) { throw new AwsException("AccessDenied", "Not authorized to perform sts:AssumeRoleWithSAML on resource: " + roleArn, 403); @@ -1153,12 +1266,14 @@ public class StsQueryHandler { // keys to set as transitive arriving as an attribute of their own beside the tags. iamService.recordSessionTags(accessKeyId, verified.principalTags(), verified.transitiveTagKeys()); + recordSourceIdentity(accessKeyId, sourceIdentityKey, sourceIdentity); String result = new XmlBuilder() .raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration)) .start("AssumedRoleUser").elem("Arn", assumedRoleArn).elem("AssumedRoleId", assumedRoleId).end("AssumedRoleUser") .raw(sessionSizeXml("AssumeRoleWithSAML", session)).elem("Issuer", verified.issuer()) .elem("Audience", "urn:amazon:webservices") - .elem("NameQualifier", verified.nameQualifier()).elem("SubjectType", verified.subjectType()).elem("Subject", verified.subject()).build(); + .elem("NameQualifier", verified.nameQualifier()).elem("SubjectType", verified.subjectType()).elem("Subject", verified.subject()) + .elem(SOURCE_IDENTITY, sourceIdentity).build(); return Response.ok(AwsQueryResponse.envelope("AssumeRoleWithSAML", AwsNamespaces.STS, result)).build(); } diff --git a/src/main/java/io/floci/aws/services/iam/StsRequestShapes.java b/src/main/java/io/floci/aws/services/iam/StsRequestShapes.java index a647c15d5a..9c6d17aff7 100644 --- a/src/main/java/io/floci/aws/services/iam/StsRequestShapes.java +++ b/src/main/java/io/floci/aws/services/iam/StsRequestShapes.java @@ -46,6 +46,11 @@ final class StsRequestShapes { return CHECK.hasMember(action, member); } + /** Every constraint the model declares for {@code action}'s {@code member} that {@code value} breaks. */ + static List valueViolations(String action, String member, String value) { + return CHECK.valueViolations(action, member, value); + } + /** Every constraint the model declares for {@code action} that {@code params} breaks. */ static List violations(String action, MultivaluedMap params) { return CHECK.violations(action, params); 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 20e58b8efc..c687fcee47 100644 --- a/src/main/java/io/floci/aws/services/iam/TrustPolicyStatements.java +++ b/src/main/java/io/floci/aws/services/iam/TrustPolicyStatements.java @@ -37,9 +37,10 @@ final class TrustPolicyStatements { } /** - * 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. + * The values a condition key reads from the keys a federated assume gives in full: the role's tags, under the keys + * the generated table gives the role's type ({@code aws:ResourceTag/}, {@code iam:ResourceTag/}), and the + * source identity the assertion or the token sets, as {@code sts:SourceIdentity}, a key matched whatever its case, + * as AWS matches a tag key; empty for a key none of them gives a value under. */ static Optional> roleValues(String conditionKey, Map> roleTags) { if (conditionKey == null || roleTags == null) { 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 dd61eaff33..dc1f1df5c5 100644 --- a/src/main/java/io/floci/aws/services/iam/WebIdentityTrustPolicyEvaluator.java +++ b/src/main/java/io/floci/aws/services/iam/WebIdentityTrustPolicyEvaluator.java @@ -53,8 +53,9 @@ public class WebIdentityTrustPolicyEvaluator { * {@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. + * resource of the request, as AWS includes them when the resource already has tags, beside the + * source identity the token sets, as {@code sts:SourceIdentity}. 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, @@ -63,6 +64,19 @@ public class WebIdentityTrustPolicyEvaluator { roleSessionName, roleTags); } + /** + * 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. + */ + public boolean allowsCompanion(String action, String trustPolicyDocument, String oidcProviderArn, + String issuerKeyPrefix, Map> claims, String roleSessionName, + Map> roleTags) { + return allows(action, trustPolicyDocument, oidcProviderArn, issuerKeyPrefix, claims, roleSessionName, + 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. diff --git a/src/main/resources/aws/iam-authorized-actions.json b/src/main/resources/aws/iam-authorized-actions.json index 36670b9c87..485486e306 100644 --- a/src/main/resources/aws/iam-authorized-actions.json +++ b/src/main/resources/aws/iam-authorized-actions.json @@ -1811,6 +1811,24 @@ "carried": "aws:SourceIdentity", "callerPolicyWhenChained": true } + ], + "AssumeRoleWithSAML": [ + { + "action": "sts:SetSourceIdentity", + "attribute": "https://aws.amazon.com/SAML/Attributes/SourceIdentity", + "key": "sts:SourceIdentity", + "carried": "aws:SourceIdentity", + "callerPolicyWhenChained": false + } + ], + "AssumeRoleWithWebIdentity": [ + { + "action": "sts:SetSourceIdentity", + "claim": "https://aws.amazon.com/source_identity", + "key": "sts:SourceIdentity", + "carried": "aws:SourceIdentity", + "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 9d60e70b0b..db9a15099e 100644 --- a/src/test/java/io/floci/aws/services/iam/AssumeRoleWithSamlValidationIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/AssumeRoleWithSamlValidationIntegrationTest.java @@ -86,6 +86,8 @@ class AssumeRoleWithSamlValidationIntegrationTest { private static final String SAML_NS = "urn:oasis:names:tc:SAML:2.0:assertion"; private static final String COMMERCIAL_RECIPIENT = "https://signin.aws.amazon.com/saml"; private static final String EUSC_REGION = "eusc-de-east-1"; + /** The attribute the IAM user guide names for an assertion's source identity. */ + private static final String SOURCE_IDENTITY_ATTRIBUTE = "https://aws.amazon.com/SAML/Attributes/SourceIdentity"; @TestHTTPResource URI endpoint; @@ -795,6 +797,56 @@ class AssumeRoleWithSamlValidationIntegrationTest { equalTo(SAMLAssertionVerifier.singleValueRequired("Teams"))); } + /** + * The assertion's source identity is the session's: "to set a SAML attribute for source identity, include the + * Attribute element with the Name attribute set to https://aws.amazon.com/SAML/Attributes/SourceIdentity". The + * response returns it, the session's requests carry it as {@code aws:SourceIdentity}, and the trust policy reads + * it as {@code sts:SourceIdentity} and has to allow setting it: "trust policies for all roles connected to an + * identity provider (IdP) must have the sts:SetSourceIdentity permission". An assertion setting none needs no + * such permission. + */ + @Test + void theAssertionsSourceIdentityIsTheSessionsWhereTheTrustPolicyAllowsSettingIt() { + String permitting = createRole("saml-source-", "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":" + + "\"Allow\",\"Principal\":{\"Federated\":\"" + PROVIDER + "\"}," + + "\"Action\":[\"sts:AssumeRoleWithSAML\",\"sts:SetSourceIdentity\"]," + + "\"Condition\":{\"StringLike\":{\"sts:SourceIdentity\":[\"Saanvi\",\"Diego\"]}}}]}"); + String accessKeyId = assumeRequest(permitting, assertionCarryingAttributes(permitting, + Map.of(SOURCE_IDENTITY_ATTRIBUTE, List.of("Diego"))), PROVIDER) + .when().post("/").then().statusCode(200) + .body("AssumeRoleWithSAMLResponse.AssumeRoleWithSAMLResult.SourceIdentity", equalTo("Diego")) + .extract().path("AssumeRoleWithSAMLResponse.AssumeRoleWithSAMLResult.Credentials.AccessKeyId"); + assertEquals(Map.of("aws:SourceIdentity", "Diego"), iamService.callerCarriedKeys(accessKeyId)); + assume(permitting, assertionCarryingAttributes(permitting, Map.of(SOURCE_IDENTITY_ATTRIBUTE, + List.of("Mateo"))), PROVIDER).statusCode(403) + .body("ErrorResponse.Error.Message", containsString("sts:SetSourceIdentity")); + + String assumeOnly = createRole(true); + assume(assumeOnly, assertionCarryingAttributes(assumeOnly, Map.of(SOURCE_IDENTITY_ATTRIBUTE, + List.of("Diego"))), PROVIDER).statusCode(403) + .body("ErrorResponse.Error.Code", equalTo("AccessDenied")) + .body("ErrorResponse.Error.Message", equalTo("Not authorized to perform sts:SetSourceIdentity on " + + "resource: " + assumeOnly)); + assume(assumeOnly, assertionCarryingAttributes(assumeOnly, Map.of()), PROVIDER).statusCode(200); + } + + /** + * A session takes a single source identity of botocore's {@code sourceIdentityType}, so an attribute carrying + * several values, or one outside the type, is refused rather than read as one of them. + */ + @Test + void aSourceIdentityAttributeWithoutOneValidValueIsRefused() { + String role = createRole("saml-source-", "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":" + + "\"Allow\",\"Principal\":{\"Federated\":\"" + PROVIDER + "\"}," + + "\"Action\":[\"sts:AssumeRoleWithSAML\",\"sts:SetSourceIdentity\"]}]}"); + for (List values : List.of(List.of("Diego", "Saanvi"), List.of("bad identity"))) { + assume(role, assertionCarryingAttributes(role, Map.of(SOURCE_IDENTITY_ATTRIBUTE, values)), PROVIDER) + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("InvalidIdentityToken")) + .body("ErrorResponse.Error.Message", containsString("SAML attribute " + SOURCE_IDENTITY_ATTRIBUTE)); + } + } + /** And an attribute whose name ends at the colon names no tag key at all. */ @Test void aTagAttributeNamingNoKeyIsRefused() { @@ -977,7 +1029,13 @@ class AssumeRoleWithSamlValidationIntegrationTest { private static String assertionCarryingTags(String role, Map> tags, List transitiveTagKeys) { return assertion(role, PROVIDER, Instant.now().plusSeconds(300), AUDIENCE, ISSUER, true, false, - factory -> List.of(enveloped(factory)), null, tags, transitiveTagKeys); + factory -> List.of(enveloped(factory)), null, tags, transitiveTagKeys, Map.of()); + } + + /** A valid signed assertion for {@code role} carrying {@code attributes}, each value in its own AttributeValue. */ + private static String assertionCarryingAttributes(String role, Map> attributes) { + return assertion(role, PROVIDER, Instant.now().plusSeconds(300), AUDIENCE, ISSUER, true, false, + factory -> List.of(enveloped(factory)), null, Map.of(), List.of(), attributes); } /** One session tag, the shape every case that passes a well-formed one uses. */ @@ -990,29 +1048,30 @@ class AssumeRoleWithSamlValidationIntegrationTest { Function> transforms, String roleSessionName) { return assertion(role, provider, expiry, audience, issuer, sign, unrelatedConfirmation, transforms, - roleSessionName, Map.of(), List.of()); + roleSessionName, Map.of(), List.of(), Map.of()); } private static String assertion(String role, String provider, Instant expiry, String audience, String issuer, boolean sign, boolean unrelatedConfirmation, Function> transforms, String roleSessionName, Map> principalTags, - List transitiveTagKeys) { + List transitiveTagKeys, Map> otherAttributes) { return assertion(role, provider, expiry, audience, issuer, sign, unrelatedConfirmation, transforms, - roleSessionName, principalTags, transitiveTagKeys, COMMERCIAL_RECIPIENT); + roleSessionName, principalTags, transitiveTagKeys, otherAttributes, COMMERCIAL_RECIPIENT); } /** A valid signed assertion for {@code role} whose bearer confirmation names {@code recipient}. */ private static String assertionAddressedTo(String role, String provider, String recipient) { return assertion(role, provider, Instant.now().plusSeconds(300), AUDIENCE, ISSUER, true, false, - factory -> List.of(enveloped(factory)), null, Map.of(), List.of(), recipient); + factory -> List.of(enveloped(factory)), null, Map.of(), List.of(), Map.of(), recipient); } private static String assertion(String role, String provider, Instant expiry, String audience, String issuer, boolean sign, boolean unrelatedConfirmation, Function> transforms, String roleSessionName, Map> principalTags, - List transitiveTagKeys, String recipient) { + List transitiveTagKeys, Map> otherAttributes, + String recipient) { String sessionNameAttribute = roleSessionName == null ? "" : "" + roleSessionName + ""; @@ -1034,6 +1093,12 @@ class AssumeRoleWithSamlValidationIntegrationTest { .append("")); tagAttributes.append(""); } + otherAttributes.forEach((name, values) -> { + tagAttributes.append(""); + values.forEach(value -> tagAttributes.append("").append(value) + .append("")); + tagAttributes.append(""); + }); String id = "_" + UUID.randomUUID(); String extraConfirmation = unrelatedConfirmation ? "" 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 dae8b82c39..0d7b1f0c00 100644 --- a/src/test/java/io/floci/aws/services/iam/StsRegisteredOidcProviderIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/StsRegisteredOidcProviderIntegrationTest.java @@ -1,7 +1,9 @@ package io.floci.aws.services.iam; +import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.databind.node.TextNode; import io.floci.aws.core.common.Base64Url; import io.floci.aws.core.common.RequestScopes; import io.floci.aws.services.apigatewayv2.JwtSignatureVerifier; @@ -43,6 +45,7 @@ import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.when; /** @@ -242,6 +245,70 @@ class StsRegisteredOidcProviderIntegrationTest { } } + /** + * The token's source identity is the session's: "include source identity in the + * https://aws.amazon.com/source_identity namespace in the token". The response returns it, the session's requests + * carry it as {@code aws:SourceIdentity}, and the trust policy reads it as {@code sts:SourceIdentity} and has to + * allow setting it: "trust policies for all roles connected to an identity provider (IdP) must have the + * sts:SetSourceIdentity permission". The role of this class's other cases allows the assume alone. + */ + @Test + void aTokensSourceIdentityIsTheSessionsWhereTheTrustPolicyAllowsSettingIt() throws Exception { + StsException refused = assertThrows(StsException.class, () -> assume(token(issuer, "sts.amazonaws.com", + privateKey, KEY_ID, sourceIdentity(TextNode.valueOf("Admin"))))); + assertEquals(403, refused.statusCode()); + assertTrue(refused.awsErrorDetails().errorMessage().contains("sts:SetSourceIdentity"), refused.getMessage()); + + String host = issuer.substring("https://".length()); + String trust = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{" + + "\"Federated\":\"" + providerArn + "\"},\"Action\":[\"sts:AssumeRoleWithWebIdentity\"," + + "\"sts:SetSourceIdentity\"],\"Condition\":{\"StringEquals\":{\"" + host + ":sub\":\"" + SUBJECT + + "\"},\"StringLike\":{\"sts:SourceIdentity\":\"Admin\"}}}]}"; + Role permitting = iam.createRole(b -> b.roleName("web-source-" + UUID.randomUUID().toString().substring(0, 8)) + .assumeRolePolicyDocument(trust)).role(); + try { + AssumeRoleWithWebIdentityResponse response = assume(permitting, token(issuer, "sts.amazonaws.com", + privateKey, KEY_ID, sourceIdentity(TextNode.valueOf("Admin")))); + assertEquals("Admin", response.sourceIdentity()); + assertEquals(Map.of("aws:SourceIdentity", "Admin"), + iamService.callerCarriedKeys(response.credentials().accessKeyId())); + StsException other = assertThrows(StsException.class, () -> assume(permitting, token(issuer, + "sts.amazonaws.com", privateKey, KEY_ID, sourceIdentity(TextNode.valueOf("Other"))))); + assertEquals(403, other.statusCode()); + } finally { + iam.deleteRole(b -> b.roleName(permitting.roleName())); + } + } + + /** + * A session takes a single source identity of botocore's type, so a claim that is not one such string is + * refused. + */ + @Test + void aSourceIdentityClaimThatIsNotOneValidStringIsRefused() throws Exception { + for (JsonNode value : List.of(objectMapper.createArrayNode().add("Admin"), TextNode.valueOf("bad identity"))) { + StsException refused = assertThrows(StsException.class, () -> assume(token(issuer, "sts.amazonaws.com", + privateKey, KEY_ID, sourceIdentity(value)))); + assertEquals(400, refused.statusCode()); + assertEquals("InvalidIdentityToken", refused.awsErrorDetails().errorCode()); + assertTrue(refused.awsErrorDetails().errorMessage() + .contains("token claim https://aws.amazon.com/source_identity"), refused.getMessage()); + } + } + + private ObjectNode sourceIdentity(JsonNode value) { + ObjectNode claims = objectMapper.createObjectNode(); + claims.set("https://aws.amazon.com/source_identity", value); + return claims; + } + + private AssumeRoleWithWebIdentityResponse assume(Role target, String token) { + AssumeRoleWithWebIdentityResponse response = sts.assumeRoleWithWebIdentity(b -> b.roleArn(target.arn()) + .roleSessionName("registered").webIdentityToken(token)); + sessions.add(response.credentials().accessKeyId()); + return response; + } + private AssumeRoleWithWebIdentityResponse assume(String token) { AssumeRoleWithWebIdentityResponse response = sts.assumeRoleWithWebIdentity(b -> b.roleArn(role.arn()) .roleSessionName("registered").webIdentityToken(token)); @@ -256,6 +323,12 @@ class StsRegisteredOidcProviderIntegrationTest { private String token(String tokenIssuer, String audience, RSAPrivateKey signingKey, String keyId) throws GeneralSecurityException { + return token(tokenIssuer, audience, signingKey, keyId, objectMapper.createObjectNode()); + } + + /** A token as the others, its payload carrying {@code claims} beside the standard ones. */ + private String token(String tokenIssuer, String audience, RSAPrivateKey signingKey, String keyId, + ObjectNode claims) throws GeneralSecurityException { ObjectNode header = objectMapper.createObjectNode(); header.put("alg", "RS256"); header.put("typ", "JWT"); @@ -267,6 +340,7 @@ class StsRegisteredOidcProviderIntegrationTest { payload.put("sub", SUBJECT); payload.put("aud", audience); payload.put("exp", System.currentTimeMillis() / 1000 + 3600); + payload.setAll(claims); String signingInput = Base64Url.encode(header.toString().getBytes(StandardCharsets.UTF_8)) + "." + Base64Url.encode(payload.toString().getBytes(StandardCharsets.UTF_8)); Signature signature = Signature.getInstance("SHA256withRSA"); diff --git a/tools/aws/fetch_sts_source_identity.py b/tools/aws/fetch_sts_source_identity.py index a9103388e0..cdedadcae6 100644 --- a/tools/aws/fetch_sts_source_identity.py +++ b/tools/aws/fetch_sts_source_identity.py @@ -18,11 +18,21 @@ source identity does: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_monitor.html + To set a SAML attribute for source identity, include the Attribute element with the Name attribute set to + https://aws.amazon.com/SAML/Attributes/SourceIdentity. + + Include source identity in the https://aws.amazon.com/source_identity namespace in the token when you submit the + AssumeRoleWithWebIdentity request. + + Trust policies for all roles connected to an identity provider (IdP) must have the sts:SetSourceIdentity + permission. + This script copies those sentences as they stand, with what each names: the operation of each "Using source identity -with " section that names the API parameter carrying the value, the action setting a source identity needs, -the key a request setting one carries and the key the session's later requests carry, and the sentences saying the -value persists through a chain. A section naming no API parameter is not read here. Nothing in the output is written -by hand; regen_request_condition_keys.py and regen_iam_authorized_actions.py read it. +with " section that names the API parameter carrying the value (`keys`), or the SAML attribute or the token +claim carrying it (`federated`), the action setting a source identity needs, alone, when chaining and for a role an +identity provider is connected to, the key a request setting one carries and the key the session's later requests carry, +and the sentences saying the value persists through a chain. A section naming none of them is not read here. Nothing in +the output is written by hand; regen_request_condition_keys.py and regen_iam_authorized_actions.py read it. Run from anywhere in the repo: python3 tools/aws/fetch_sts_source_identity.py # rewrite the vendored file from the page @@ -54,6 +64,13 @@ CHAINING_RE = re.compile(r"\bWhen you assume a role with another role, called ro KEYS_RE = re.compile(r"\bWhen an identity sets a source identity, the (?Psts:[A-Za-z]+) key is present in the " r"request\. For subsequent actions taken during the role session, the " r"(?Paws:[A-Za-z]+) key is present in the request\.") +ATTRIBUTE_RE = re.compile(r"\bTo set a SAML attribute for source identity, include the Attribute element with the " + r"Name attribute set to (?Phttps://[^\s]+?)\.(?:\s|$)") +# The claim is read from the markup, where the page links the namespace's host inside the code element naming it. +CLAIM_RE = re.compile(r"\bInclude source identity in the ]*>(?P.*?)\s+namespace in the token", + re.S) +IDP_RE = re.compile(r"\bTrust policies for all roles connected to an identity provider \(IdP\) must have the " + r"(?Psts:[A-Za-z]+) permission\.") PERSISTS_RE = re.compile(r"\bThe value that is set persists when a role is used to assume another role[^.]*\. " r"The value that is set cannot be changed during the role session\.") CHAINED_KEYS_RE = re.compile(r"\bTherefore, both the (?Paws:[A-Za-z]+) and (?Psts:[A-Za-z]+) keys " @@ -73,9 +90,9 @@ def body(page: str) -> str: def sections(page: str) -> dict[str, str]: - """Each second-level section of the page as text, under its heading.""" + """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]): text(parts[i + 1]) for i in range(1, len(parts) - 1, 2)} + 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: @@ -89,14 +106,25 @@ def build(fetch) -> dict: page = fetch(PAGE) by_heading = sections(page) whole = text(body(page)) - keys = [] - for heading, section in by_heading.items(): + keys, federated = [], [] + for heading, markup in by_heading.items(): operation = OPERATION_HEADING_RE.match(heading) - member = MEMBER_RE.search(section) if operation else None - if member is None: + if operation is None: continue - keys.append({"operation": operation.group("operation"), "member": member.group("member"), - "row": member.group(0)}) + section = text(markup) + member = MEMBER_RE.search(section) + attribute = ATTRIBUTE_RE.search(section) + claim = CLAIM_RE.search(markup) + if member is not None: + keys.append({"operation": operation.group("operation"), "member": member.group("member"), + "row": member.group(0)}) + elif attribute is not None: + federated.append({"operation": operation.group("operation"), "attribute": attribute.group("attribute"), + "row": attribute.group(0).strip()}) + elif claim is not None: + named_claim = re.sub(r"<[^>]+>|\s+", "", claim.group("claim")) + federated.append({"operation": operation.group("operation"), "claim": named_claim, + "row": text(claim.group(0).replace(claim.group("claim"), named_claim))}) if not keys: raise ValueError(f"{PAGE} names no API parameter a source identity is passed in: its layout changed") permission = _sentence(PERMISSION_RE, whole, "which action specifying a source identity needs") @@ -109,7 +137,11 @@ def build(fetch) -> dict: if (chained.group("request"), chained.group("session")) != (named.group("request"), named.group("session")): raise ValueError(f"{PAGE} names other keys for a chained request than for one setting a source identity") persists = _sentence(PERSISTS_RE, whole, "that a source identity persists through a chain") - for entry in keys: + idp = _sentence(IDP_RE, whole, "which action a role an identity provider is connected to needs of its trust") + if idp.group("action") != permission.group("action"): + raise ValueError(f"{PAGE} names {permission.group('action')} for setting a source identity and " + f"{idp.group('action')} for a role an identity provider is connected to") + for entry in keys + federated: entry["key"] = named.group("request") return { "_source": { @@ -121,8 +153,9 @@ def build(fetch) -> dict: "chained form, the keys a request carries it as, and its persistence through a chain.", }, "keys": sorted(keys, key=lambda entry: entry["operation"]), + "federated": sorted(federated, key=lambda entry: entry["operation"]), "permission": {"action": permission.group("action"), "sentence": permission.group(0), - "chaining": chaining.group(0)}, + "chaining": chaining.group(0), "identityProvider": idp.group(0)}, "sessionKey": {"key": named.group("session"), "sentence": named.group(0), "chained": chained.group(0)}, "persists": persists.group(0), } diff --git a/tools/aws/regen_iam_authorized_actions.py b/tools/aws/regen_iam_authorized_actions.py index 4d31d305d9..b13eefe4d3 100644 --- a/tools/aws/regen_iam_authorized_actions.py +++ b/tools/aws/regen_iam_authorized_actions.py @@ -74,7 +74,11 @@ page names for the operation, `SourceIdentity`, a member of its request in botoc the key its session's later requests carry, `aws:SourceIdentity`. And "when you assume a role with another role, called role chaining, permissions for sts:SetSourceIdentity are required in both the permissions policy of the principal who is assuming the role and in the role trust policy of the target role", so a chained caller's own permissions must allow it -whatever the target's trust policy grants (`callerPolicyWhenChained`). +whatever the target's trust policy grants (`callerPolicyWhenChained`). AssumeRoleWithSAML and AssumeRoleWithWebIdentity, +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`. 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 @@ -584,7 +588,9 @@ def companions(documents: list[dict], page: dict | None, in, the action the page says setting one needs, where the reference lists it among the operation's actions, with the member and the key a chained caller carries the value as, and whether a chained caller's own permissions must 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).""" + 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.""" if not page: return {} action = page["permission"]["action"] @@ -608,6 +614,20 @@ def companions(documents: list[dict], page: dict | None, found.setdefault(namespace, {})[entry["operation"]] = [ {"action": action, "member": entry["member"], "carried": page["sessionKey"]["key"], "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 + # page says the value is present in the request as. Such a call carries no caller's credentials to chain. + actions = {reference.get("Name"): reference for reference in document.get("Actions") or []} + for entry in page.get("federated", []) if page["permission"].get("identityProvider") else []: + reference = actions.get(entry["operation"]) + if reference is None or entry["key"] not in (reference.get("ActionConditionKeys") or []) \ + 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"]] = [ + {"action": action, **source, "key": entry["key"], "carried": page["sessionKey"]["key"], + "callerPolicyWhenChained": False}] return {namespace: dict(sorted(operations.items())) for namespace, operations in sorted(found.items())} @@ -717,10 +737,8 @@ def _section_problems(document: dict) -> list[str]: for namespace, operations in (document.get("companions") or {}).items(): for operation, needed in (operations.items() if isinstance(operations, dict) else []): for companion in (needed if isinstance(needed, list) else [None]): - if not isinstance(companion, dict) \ - or set(companion) != {"action", "member", "carried", "callerPolicyWhenChained"} \ + if not isinstance(companion, dict) or not _companion_source_holds(namespace, companion) \ or not action_of(namespace, companion.get("action")) \ - or not NAME_RE.match(str(companion.get("member"))) \ or not CARRIED_KEY_RE.match(str(companion.get("carried"))) \ or not isinstance(companion.get("callerPolicyWhenChained"), bool): problems.append(f"companions {namespace}:{operation} is not an action of {namespace}, a request " @@ -728,6 +746,18 @@ def _section_problems(document: dict) -> list[str]: return problems +def _companion_source_holds(namespace: str, companion: dict) -> bool: + """Whether a companion names where its value comes from: a request member, or a SAML attribute or a token claim + with the namespace's key the value is present in the request as.""" + fields = set(companion) - {"action", "carried", "callerPolicyWhenChained"} + if fields == {"member"}: + return bool(NAME_RE.match(str(companion["member"]))) + 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 + ":") + + def _unscoped_problems(unscoped: object, routed: list[str]) -> list[str]: """Problems with the actions without resource types: one sorted list of usable names for each scope whose routes are read, and for no other.""" diff --git a/tools/aws/sources/sts-source-identity.json b/tools/aws/sources/sts-source-identity.json index 2cdaa7d2ce..a4c02bb6e9 100644 --- a/tools/aws/sources/sts-source-identity.json +++ b/tools/aws/sources/sts-source-identity.json @@ -2,7 +2,7 @@ "_source": { "page": "https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_monitor.html", "fetcher": "tools/aws/fetch_sts_source_identity.py", - "retrieved": "2026-11-28", + "retrieved": "2026-11-29", "note": "The page's sentences on setting a source identity, copied as they stand, with what each names: the API parameter each operation's section passes it in, the action setting one needs and its chained form, the keys a request carries it as, and its persistence through a chain." }, "keys": [ @@ -13,10 +13,25 @@ "key": "sts:SourceIdentity" } ], + "federated": [ + { + "operation": "AssumeRoleWithSAML", + "attribute": "https://aws.amazon.com/SAML/Attributes/SourceIdentity", + "row": "To set a SAML attribute for source identity, include the Attribute element with the Name attribute set to https://aws.amazon.com/SAML/Attributes/SourceIdentity.", + "key": "sts:SourceIdentity" + }, + { + "operation": "AssumeRoleWithWebIdentity", + "claim": "https://aws.amazon.com/source_identity", + "row": "Include source identity in the https://aws.amazon.com/source_identity namespace in the token", + "key": "sts:SourceIdentity" + } + ], "permission": { "action": "sts:SetSourceIdentity", "sentence": "To specify a source identity, principals (IAM users and roles) must have permissions to sts:SetSourceIdentity.", - "chaining": "When you assume a role with another role, called role chaining, permissions for sts:SetSourceIdentity are required in both the permissions policy of the principal who is assuming the role and in the role trust policy of the target role." + "chaining": "When you assume a role with another role, called role chaining, permissions for sts:SetSourceIdentity are required in both the permissions policy of the principal who is assuming the role and in the role trust policy of the target role.", + "identityProvider": "Trust policies for all roles connected to an identity provider (IdP) must have the sts:SetSourceIdentity permission." }, "sessionKey": { "key": "aws:SourceIdentity", diff --git a/tools/aws/test_fetch_sts_source_identity.py b/tools/aws/test_fetch_sts_source_identity.py index e6f35f3c64..74a728fad8 100644 --- a/tools/aws/test_fetch_sts_source_identity.py +++ b/tools/aws/test_fetch_sts_source_identity.py @@ -12,7 +12,9 @@ PERMISSIONS = ("

Permissions required to set source identity

  • T "role chaining, permissions for sts:SetSourceIdentity are required in both the " "permissions policy of the principal who is assuming the role and in the role trust policy of the " "target role. Otherwise, the assume role operation will fail.

") -THINGS = ("

Things to know about source identity

The value that is set persists when a role is used to " +THINGS = ("

Things to know about source identity

Trust policies for all roles connected to an identity " + "provider (IdP) must have the sts:SetSourceIdentity permission.

The value that is set " + "persists when a role is used to " "assume another role through the AWS CLI or AWS API, known as role chaining. The value that is set " "cannot be changed during the role session.

When an identity sets a source identity, the " "sts:SourceIdentity key is present in the request. For subsequent actions taken during the " @@ -20,20 +22,27 @@ THINGS = ("

Things to know about source identity

The value that is set ASSUME_ROLE = ("

Using source identity with AssumeRole

To pass source identity while assuming a role, use " "the -–source-identity AWS CLI option or the SourceIdentity AWS API " "parameter.

") -SAML = "

Using source identity with AssumeRoleWithSAML

Set a SAML attribute.

" +SAML = ("

Using source identity with AssumeRoleWithSAML

To set a SAML attribute for source identity, include " + "the Attribute element with the Name attribute set to " + "https://aws.amazon.com/SAML/Attributes/SourceIdentity. Use the AttributeValue " + "element.

") +WEB_IDENTITY = ("

Using source identity with AssumeRoleWithWebIdentity

Include source identity in the " + 'https://aws.amazon.com/' + "source_identity namespace in the token when you submit the request.

") +OTHER = "

Using source identity with AssumeRoot

Nothing to read here.

" CHAINED = ("

Control access using source identity information

Therefore, both the " "aws:SourceIdentity and sts:SourceIdentity keys are present in the request " "context.

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

Monitor

{"".join(sections)}
' def test_each_operation_naming_its_parameter_is_read_with_the_key_it_carries(): built = f.build(lambda url: page()) - # A section naming no API parameter, as the SAML one, is not read here. + # A section naming no API parameter, as the SAML one, gives no request member. assert built["keys"] == [{"operation": "AssumeRole", "member": "SourceIdentity", "key": "sts:SourceIdentity", "row": "To pass source identity while assuming a role, use the -–source-identity AWS " "CLI option or the SourceIdentity AWS API parameter."}] @@ -41,6 +50,18 @@ def test_each_operation_naming_its_parameter_is_read_with_the_key_it_carries(): assert built["permission"]["chaining"].startswith("When you assume a role with another role, called role chaining") assert built["sessionKey"]["key"] == "aws:SourceIdentity" assert built["persists"].endswith("The value that is set cannot be changed during the role session.") + assert built["permission"]["identityProvider"].startswith("Trust policies for all roles connected to an identity") + + +def test_a_federated_operation_is_read_with_the_attribute_or_claim_carrying_the_value(): + federated = {entry["operation"]: entry for entry in f.build(lambda url: page())["federated"]} + assert set(federated) == {"AssumeRoleWithSAML", "AssumeRoleWithWebIdentity"} + assert federated["AssumeRoleWithSAML"]["attribute"] == "https://aws.amazon.com/SAML/Attributes/SourceIdentity" + # The page links the claim's host inside its code element; the claim is the element's whole text. + assert federated["AssumeRoleWithWebIdentity"]["claim"] == "https://aws.amazon.com/source_identity" + assert federated["AssumeRoleWithWebIdentity"]["row"].startswith( + "Include source identity in the https://aws.amazon.com/source_identity namespace") + assert all(entry["key"] == "sts:SourceIdentity" for entry in federated.values()) def test_a_page_whose_layout_or_wording_changed_is_refused(): @@ -52,6 +73,10 @@ def test_a_page_whose_layout_or_wording_changed_is_refused(): f.build(lambda url: page(THINGS, PERMISSIONS.replace("permissions for sts:SetSourceIdentity", "permissions for sts:SetOther"), ASSUME_ROLE, CHAINED)) + with pytest.raises(ValueError, match="a role an identity provider is connected to"): + f.build(lambda url: page(THINGS.replace("must have the sts:SetSourceIdentity permission", + "must have the sts:Other permission"), + PERMISSIONS, ASSUME_ROLE, CHAINED)) with pytest.raises(ValueError, match="other keys for a chained request"): f.build(lambda url: page(THINGS, PERMISSIONS, ASSUME_ROLE, CHAINED.replace("aws:SourceIdentity", "aws:Other"))) diff --git a/tools/aws/test_regen_iam_authorized_actions.py b/tools/aws/test_regen_iam_authorized_actions.py index 161141ba06..185edbd2e5 100644 --- a/tools/aws/test_regen_iam_authorized_actions.py +++ b/tools/aws/test_regen_iam_authorized_actions.py @@ -776,3 +776,57 @@ def test_a_malformed_companion_is_rejected(companion): document = anchored() document["companions"] = {"sts": {"AssumeRole": [companion]}} assert any("companions sts:AssumeRole" in problem for problem in r.validate(document, [])) + + +FEDERATED_PAGE = {**SOURCE_IDENTITY, + "federated": [{"operation": "AssumeRoleWithSAML", "key": "sts:SourceIdentity", + "attribute": "https://aws.amazon.com/SAML/Attributes/SourceIdentity"}, + {"operation": "AssumeRoleWithWebIdentity", "key": "sts:SourceIdentity", + "claim": "https://aws.amazon.com/source_identity"}], + "permission": {**SOURCE_IDENTITY["permission"], + "identityProvider": "Trust policies for all roles connected to an identity provider"}} + + +def federated_sts(saml_keys: list[str]) -> dict: + document = service("sts", {"AssumeRole": ["sts:AssumeRole", "sts:SetSourceIdentity"], + "AssumeRoleWithSAML": [], "AssumeRoleWithWebIdentity": []}, + ["AssumeRole", "SetSourceIdentity"]) + document["Actions"] += [{"Name": "AssumeRoleWithSAML", "ActionConditionKeys": saml_keys}, + {"Name": "AssumeRoleWithWebIdentity", "ActionConditionKeys": ["sts:SourceIdentity"]}] + return document + + +def test_a_federated_operation_needs_the_action_of_its_assertions_or_tokens_value(): + found = r.companions([federated_sts(["sts:SourceIdentity"])], FEDERATED_PAGE, STS_REQUESTS)["sts"] + assert found["AssumeRoleWithSAML"] == [{ + "action": "sts:SetSourceIdentity", "attribute": "https://aws.amazon.com/SAML/Attributes/SourceIdentity", + "key": "sts:SourceIdentity", "carried": "aws:SourceIdentity", "callerPolicyWhenChained": False}] + assert found["AssumeRoleWithWebIdentity"][0]["claim"] == "https://aws.amazon.com/source_identity" + document = anchored() + document["companions"] = {"sts": found} + assert r.validate(document, []) == [] + + +def test_a_federated_operation_whose_action_takes_no_such_key_gives_no_companion(): + found = r.companions([federated_sts(["sts:RoleSessionName"])], FEDERATED_PAGE, STS_REQUESTS)["sts"] + assert "AssumeRoleWithSAML" not in found + assert "AssumeRoleWithWebIdentity" in found + no_idp_sentence = {**FEDERATED_PAGE, "permission": SOURCE_IDENTITY["permission"]} + assert set(r.companions([federated_sts(["sts:SourceIdentity"])], no_idp_sentence, STS_REQUESTS)["sts"]) \ + == {"AssumeRole"} + + +@pytest.mark.parametrize("companion", [ + {"action": "sts:SetSourceIdentity", "attribute": "SourceIdentity", "key": "sts:SourceIdentity", + "carried": "aws:SourceIdentity", "callerPolicyWhenChained": False}, + {"action": "sts:SetSourceIdentity", "claim": "https://aws.amazon.com/source_identity", + "carried": "aws:SourceIdentity", "callerPolicyWhenChained": False}, + {"action": "sts:SetSourceIdentity", "claim": "https://aws.amazon.com/source_identity", "key": "iam:Other", + "carried": "aws:SourceIdentity", "callerPolicyWhenChained": False}, + {"action": "sts:SetSourceIdentity", "member": "SourceIdentity", "claim": "https://aws.amazon.com/source_identity", + "key": "sts:SourceIdentity", "carried": "aws:SourceIdentity", "callerPolicyWhenChained": False}, +]) +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, []))