mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(iam): read a federated assume's source identity from its assertion or token (#9708)
Under enforcement a role whose trust policy conditions AssumeRoleWithSAML or AssumeRoleWithWebIdentity on sts:SourceIdentity refused every assume, and one that withheld sts:SetSourceIdentity was never consulted: neither operation read the source identity its identity provider sets, so the session carried none, the response returned none and its requests carried no aws:SourceIdentity. The Service Reference gives both actions sts:SourceIdentity but lists no authorized actions for either operation, and botocore models the value only in the response. The IAM user guide's page on source identity, which tools/aws/fetch_sts_source_identity.py already vendors, says where each carries 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", and what it needs, "trust policies for all roles connected to an identity provider (IdP) must have the sts:SetSourceIdentity permission". The fetcher now copies those sentences too, and regen_iam_authorized_actions.py gives each operation a companion naming the attribute or the claim and the key it is read as, where the reference's action of the operation's name takes sts:SourceIdentity. STS reads the value the table names, holds it to botocore's sourceIdentityType (the shape botocore gives the response's SourceIdentity, as it does AssumeRole's member), and refuses several values or one outside it with InvalidIdentityToken. The trust policy reads it as sts:SourceIdentity, through the keys the federated trust evaluators already read in full, and is checked for sts:SetSourceIdentity before the assume, as for AssumeRole. The session records it under aws:SourceIdentity, which a session assumed from it carries on, and the response returns it. Part of #6640.
This commit is contained in:
1 parent
f33de37d7b
commit
7d3049d218
21 files changed
+603
-62
No files matched your search
@@ -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
|
||||
|
||||
+21
-7
@@ -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: <role>`. 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/<key>` and `aws:TagKeys`, which the Service Authorization Reference
|
||||
|
||||
@@ -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<String, List<String>> context) {
|
||||
Map<String, List<String>> carried = context;
|
||||
for (Companion companion : companions) {
|
||||
List<String> value = carried == null ? null : carried.get(companion.carried());
|
||||
List<String> 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(),
|
||||
|
||||
@@ -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<String> 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<String, String> 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
|
||||
|
||||
@@ -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<String> audiences,
|
||||
Map<String, String> principalTags,
|
||||
List<String> transitiveTagKeys) {
|
||||
List<String> transitiveTagKeys, JsonNode claims) {
|
||||
|
||||
public WebIdentityToken(String issuer, String subject, List<String> audiences) {
|
||||
this(issuer, subject, audiences, Map.of(), List.of());
|
||||
}
|
||||
|
||||
public WebIdentityToken(String issuer, String subject, List<String> audiences,
|
||||
Map<String, String> principalTags, List<String> transitiveTagKeys) {
|
||||
this(issuer, subject, audiences, principalTags, transitiveTagKeys, MissingNode.getInstance());
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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".
|
||||
*
|
||||
* <p>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<Companion> 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));
|
||||
}));
|
||||
|
||||
@@ -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<RolePair> roles, String roleSessionName,
|
||||
Map<String, String> principalTags, List<String> transitiveTagKeys, String recipient) {}
|
||||
Map<String, String> principalTags, List<String> transitiveTagKeys, String recipient,
|
||||
Map<String, List<String>> 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<String, List<String>> attributeValues(NodeList attributes) {
|
||||
Map<String, List<String>> values = new LinkedHashMap<>();
|
||||
for (int i = 0; i < attributes.getLength(); i++) {
|
||||
Element attribute = (Element) attributes.item(i);
|
||||
List<String> 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:"
|
||||
|
||||
@@ -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/<key>}, {@code iam:ResourceTag/<key>}), which a policy reads on it.
|
||||
* ({@code aws:ResourceTag/<key>}, {@code iam:ResourceTag/<key>}), 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<String, List<String>> claims,
|
||||
String roleSessionName, Map<String, List<String>> 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<String, List<String>> claims, String roleSessionName,
|
||||
Map<String, List<String>> 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.
|
||||
|
||||
@@ -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<IamAuthorizedActions.Companion> 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<String> 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<String> 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<String, List<String>> withSourceIdentity(Map<String, List<String>> keys,
|
||||
IamAuthorizedActions.Companion key,
|
||||
String sourceIdentity) {
|
||||
if (sourceIdentity == null || key == null) {
|
||||
return keys;
|
||||
}
|
||||
Map<String, List<String>> 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<String, String> principalTags,
|
||||
List<String> transitiveTagKeys) {}
|
||||
List<String> 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<String, List<String>> 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<String, List<String>> 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<String, List<String>> 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<String, List<String>> 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();
|
||||
}
|
||||
|
||||
|
||||
@@ -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<String> 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<String> violations(String action, MultivaluedMap<String, String> params) {
|
||||
return CHECK.violations(action, params);
|
||||
|
||||
@@ -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/<key>}, {@code iam:ResourceTag/<key>}), a key matched whatever its
|
||||
* case, as AWS matches a tag key; empty for a key the role gives no value under.
|
||||
* 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/<key>}, {@code iam:ResourceTag/<key>}), 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<List<String>> roleValues(String conditionKey, Map<String, List<String>> roleTags) {
|
||||
if (conditionKey == null || roleTags == null) {
|
||||
|
||||
@@ -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/<key>}, {@code iam:ResourceTag/<key>}), which a policy reads on it as on the
|
||||
* resource of the request, as AWS includes them when the resource already has tags. An explicit
|
||||
* {@code Deny} wins over any {@code Allow}, per AWS precedence.
|
||||
* 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<String, List<String>> 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<String, List<String>> claims, String roleSessionName,
|
||||
Map<String, List<String>> 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.
|
||||
|
||||
@@ -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
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
+71
-6
@@ -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<String> 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<String, List<String>> tags,
|
||||
List<String> 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<String, List<String>> 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<XMLSignatureFactory, List<Transform>> 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<XMLSignatureFactory, List<Transform>> transforms,
|
||||
String roleSessionName, Map<String, List<String>> principalTags,
|
||||
List<String> transitiveTagKeys) {
|
||||
List<String> transitiveTagKeys, Map<String, List<String>> 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<XMLSignatureFactory, List<Transform>> transforms,
|
||||
String roleSessionName, Map<String, List<String>> principalTags,
|
||||
List<String> transitiveTagKeys, String recipient) {
|
||||
List<String> transitiveTagKeys, Map<String, List<String>> otherAttributes,
|
||||
String recipient) {
|
||||
String sessionNameAttribute = roleSessionName == null ? ""
|
||||
: "<saml:Attribute Name=\"https://aws.amazon.com/SAML/Attributes/RoleSessionName\"><saml:AttributeValue>"
|
||||
+ roleSessionName + "</saml:AttributeValue></saml:Attribute>";
|
||||
@@ -1034,6 +1093,12 @@ class AssumeRoleWithSamlValidationIntegrationTest {
|
||||
.append("</saml:AttributeValue>"));
|
||||
tagAttributes.append("</saml:Attribute>");
|
||||
}
|
||||
otherAttributes.forEach((name, values) -> {
|
||||
tagAttributes.append("<saml:Attribute Name=\"").append(name).append("\">");
|
||||
values.forEach(value -> tagAttributes.append("<saml:AttributeValue>").append(value)
|
||||
.append("</saml:AttributeValue>"));
|
||||
tagAttributes.append("</saml:Attribute>");
|
||||
});
|
||||
String id = "_" + UUID.randomUUID();
|
||||
String extraConfirmation = unrelatedConfirmation
|
||||
? "<saml:SubjectConfirmation Method=\"urn:oasis:names:tc:SAML:2.0:cm:sender-vouches\"><saml:SubjectConfirmationData Recipient=\"https://unrelated.example.test\" NotOnOrAfter=\"" + Instant.now().minusSeconds(1) + "\"/></saml:SubjectConfirmation>"
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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 <Operation>" 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 <Operation>" 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 (?P<request>sts:[A-Za-z]+) key is present in the "
|
||||
r"request\. For subsequent actions taken during the role session, the "
|
||||
r"(?P<session>aws:[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 (?P<attribute>https://[^\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 <code[^>]*>(?P<claim>.*?)</code>\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"(?P<action>sts:[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 (?P<session>aws:[A-Za-z]+) and (?P<request>sts:[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"<h2[^>]*>(.*?)</h2>", 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),
|
||||
}
|
||||
|
||||
@@ -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."""
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -12,7 +12,9 @@ PERMISSIONS = ("<h2>Permissions required to set source identity</h2><ul><li><p>T
|
||||
"<a>role chaining</a>, permissions for <code>sts:SetSourceIdentity</code> 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.</p></li></ul>")
|
||||
THINGS = ("<h2>Things to know about source identity</h2><p>The value that is set persists when a role is used to "
|
||||
THINGS = ("<h2>Things to know about source identity</h2><p>Trust policies for all roles connected to an identity "
|
||||
"provider (IdP) must have the <code>sts:SetSourceIdentity</code> permission.</p><p>The value that is set "
|
||||
"persists when a role is used to "
|
||||
"assume another role through the AWS CLI or AWS API, known as <a>role chaining</a>. The value that is set "
|
||||
"cannot be changed during the role session.</p><p>When an identity sets a source identity, the "
|
||||
"<code>sts:SourceIdentity</code> key is present in the request. For subsequent actions taken during the "
|
||||
@@ -20,20 +22,27 @@ THINGS = ("<h2>Things to know about source identity</h2><p>The value that is set
|
||||
ASSUME_ROLE = ("<h2>Using source identity with AssumeRole</h2><p>To pass source identity while assuming a role, use "
|
||||
"the <code>-–source-identity</code> AWS CLI option or the <code>SourceIdentity</code> AWS API "
|
||||
"parameter.</p>")
|
||||
SAML = "<h2>Using source identity with AssumeRoleWithSAML</h2><p>Set a SAML attribute.</p>"
|
||||
SAML = ("<h2>Using source identity with AssumeRoleWithSAML</h2><p>To set a SAML attribute for source identity, include "
|
||||
"the <code>Attribute</code> element with the <code>Name</code> attribute set to "
|
||||
"<code>https://aws.amazon.com/SAML/Attributes/SourceIdentity</code>. Use the <code>AttributeValue</code> "
|
||||
"element.</p>")
|
||||
WEB_IDENTITY = ("<h2>Using source identity with AssumeRoleWithWebIdentity</h2><p>Include source identity in the "
|
||||
'<code class="code"><a href="https://aws.amazon.com/"><span>https://aws.amazon.com/</span></a>'
|
||||
"source_identity</code> namespace in the token when you submit the request.</p>")
|
||||
OTHER = "<h2>Using source identity with AssumeRoot</h2><p>Nothing to read here.</p>"
|
||||
CHAINED = ("<h2>Control access using source identity information</h2><p>Therefore, both the "
|
||||
"<code>aws:SourceIdentity</code> and <code>sts:SourceIdentity</code> keys are present in the request "
|
||||
"context.</p>")
|
||||
|
||||
|
||||
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'<div id="main-col-body"><h1>Monitor</h1>{"".join(sections)}</div><div class="prev-next"></div>'
|
||||
|
||||
|
||||
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 <code>sts:SetSourceIdentity",
|
||||
"permissions for <code>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 <code>sts:SetSourceIdentity</code> permission",
|
||||
"must have the <code>sts:Other</code> 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("<code>aws:SourceIdentity", "<code>aws:Other")))
|
||||
|
||||
@@ -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, []))
|
||||
Reference in new issue
Block a user