feat(sts): pass transitive session tags into a chained role session (#9308)

A session tag never reached the session assumed from it, so the opt-in AWS
publishes for role chaining was missing: "if you set a tag key as transitive,
the corresponding key and value passes to subsequent sessions in a role chain".
All three operations that mint a tagged session now read the keys where AWS
publishes them, the request's TransitiveTagKeys member, the assertion's
multivalued TransitiveTagKeys attribute and the token's transitive_tag_keys
claim in either published format, and GetFederationToken declares none because
its credentials cannot assume a role at all.

A session assumed from one carrying transitive tags takes those tags as its own,
under the ones its own request passes, and keeps their keys transitive so the
next link inherits them too. A role's own tags never pass down. A session tag
whose key the calling session passes down is refused, which AWS publishes as the
operation failing without saying what it answers, so the code is the one this
operation already gives the other rule that turns on the caller being a session
and the sentence is this package's own. The inherited tags count against the
session token size like any other state the session carries, while the keys cost
nothing.

sts:TransitiveTagKeys now reaches the role's trust policy with the keys the
request names, beside sts:RoleSessionName and sts:ExternalId there. It stays out
of the caller's identity-policy context, which is filled from the generated
request-condition-keys.json, and that file does not list the key for the action.

One rule of the chain is left and the docs say why: a transitive tag replaces the
assumed role's matching ResourceTag value, and Floci publishes no
aws:ResourceTag for the role in either evaluation, so there is nothing yet for it
to replace.

An inherited tag needs the role's tagging permission as much as a passed one
does, so the trust policy is read for sts:TagSession when the calling session
passes any tag down, with the request carrying none: the guide lists "incoming
transitive session tags" among the tags a principal carries, and where a base
role's own tags are passed on by STS "the trust policy must also allow
sts:TagSession". The caller's own policy is read for a request that carries
Tags, which the generated tagging table keys on, so a chain of inherited tags
alone is held to the role's permission and not to the calling session's, where
AWS reads both; the docs say so.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-23 22:29:02 -04:00
1 parent 014256293c
commit adb5b9edc0
13 files changed
+732 -58

No files matched your search

+6 -2
View File
@@ -3864,7 +3864,8 @@ floci populates:
federated user carries the tags of the user whose key minted it. An account-root principal has
no stored tags and no way to pass one. A session tag replaces the identity's tag of that key
whatever its case; [STS](sts.md#session-tags) has where each operation takes its session tags
from, and the transitive inheritance that is not implemented.
from, and [Transitive tags](sts.md#transitive-tags) how a chained session inherits the ones the
calling session passes down, which are its own tags from then on.
- `aws:PrincipalType` and `aws:userid`: resolved from the same lookup as `aws:PrincipalArn`, so
they always describe the same credential. The values follow the user guide's principal key
values list: `Account` with the account id for the account-root principal and for a session
@@ -3997,7 +3998,10 @@ floci populates:
The actions and request members come from the same `request-condition-keys.json`.
`AssumeRoleWithWebIdentity` and `AssumeRoleWithSAML` are not signed, so no identity-based policy is
evaluated for them. `sts:SourceIdentity`, `sts:TransitiveTagKeys`, `aws:RequestTag/<key>` and `aws:TagKeys`
are not populated for `AssumeRole`: Floci does not model source identity or session tags.
are not populated for `AssumeRole`: source identity is not modelled, and the three tag keys are not in
this file for the action, which is what fills the context here. A session's own tags are modelled, and
reach a policy as `aws:PrincipalTag/<key>`; `sts:TransitiveTagKeys` reaches the role's trust policy,
which the STS handler reads with a context of its own (see [STS](sts.md#transitive-tags)).
**Any other condition key is absent from the request context.** A positive scalar operator
without `IfExists` on an absent key makes the whole statement *not apply*: it neither matches nor
+78 -11
View File
@@ -524,21 +524,88 @@ message rather than from a request member, that is measured once the assertion o
been verified, which is the first point the tags exist, rather than before the operation runs where
the declared members are read.
Two published pieces of this are not here yet. The transitive tag keys an assertion or a token
carries beside the tags are not read, so a tag never passes into a chained session: that is AWS's
default, "by default, AWS STS does not pass tags to subsequent role sessions", and the opt-in is
missing. And the plaintext limits a session tag is held to, 50 tags with keys of 128 characters and
values of 256, are read where the model declares the members that carry them, which leaves the
number and the length of the tags inside an assertion or a token unchecked, nothing published
saying what AWS answers when those break; what does hold them is the token size above.
One published piece of this is not here yet: the plaintext limits a session tag is held to, 50 tags
with keys of 128 characters and values of 256, are read where the model declares the members that
carry them, which leaves the number and the length of the tags inside an assertion or a token
unchecked, nothing published saying what AWS answers when those break; what does hold them is the
token size above.
#### Transitive tags
A session tag is the current session's alone unless its key is named transitive, and then "the
corresponding key and value passes to subsequent sessions in a role chain". Nothing passes by
default: "if you choose not to specify a transitive tag key, then no tags are passed from this
session to any subsequent sessions." Each operation that can carry them names them the way AWS
publishes for it, and the one that cannot says why:
| Operation | Where a transitive key comes from |
|-----------|-----------------------------------|
| `AssumeRole` | the request's `TransitiveTagKeys` member |
| `AssumeRoleWithSAML` | the assertion's `https://aws.amazon.com/SAML/Attributes/TransitiveTagKeys` attribute, which is multivalued |
| `AssumeRoleWithWebIdentity` | the token's `transitive_tag_keys`, nested in the tag namespace or as the flattened claim of that name |
| `GetFederationToken` | nowhere: it declares no such member, because "you can't use the temporary credentials" it returns to assume a role |
A key naming no tag of that session selects nothing, there being no tag of that key to carry, and
nothing published says AWS refuses it. The keys are matched against the tags without regard to case,
as a tag key is compared anywhere else, and the spellings kept are the ones the request, the
assertion or the token sent. A token's claim is read as the array both published examples write, a
lone string being read as the one key it names, and a claim of any other shape is refused with
`The web identity token's transitive tag keys do not read as an array of strings`, which is Floci's
own sentence for the same reason the malformed-tag refusals above are.
When a session with transitive tags assumes a role, those tags become the new session's own, under
the tags that request passes: "the new session inherits any transitive session tags from the calling
session". They stay transitive there, so the link after it inherits them too, which is what the
guide's own chain shows, its second session's inherited tags continuing "to be transitive" without
the second request naming them again. A role's own tags never pass down, however they are tagged:
"you cannot set role tags as transitive."
The role being assumed has to permit the tagging for an inherited tag as much as for a passed one,
and answers `AccessDenied` naming `sts:TagSession` when it does not. Inherited tags are session tags
of the session being minted, the guide listing "incoming transitive session tags" among the tags a
principal carries, and where a base role's own tags are passed on by STS "the trust policy must also
allow sts:TagSession", with the refusal reading "not authorized to perform: sts:TagSession". The
caller's own policy is read for a request that carries `Tags`, which the generated tagging table
keys on, so a chain carrying only inherited tags is held to the role's permission and not to the
calling session's, where AWS reads both.
An inherited tag cannot be overridden: "if you pass a session tag with the same key as an inherited
tag, the operation fails." Here that is `ValidationError` 400 with
`Session tag <key> cannot be passed because the calling session carries it as a transitive tag.`,
the key as the request spelled it. That it fails is published and what AWS answers is not, so the
sentence is Floci's own and the code is the one this operation already gives the other rule that
turns on the caller being a session, the one-hour cap on a chained assume. The refusal is read after
the trust policy has allowed the assume and beside that cap, which is an order nothing published
settles either.
The inherited tags are state the new session carries, so they count against the
[4,096-byte limit](iam.md#what-a-sessions-token-costs-and-when-it-is-refused) exactly as tags passed
by the request do. The keys themselves cost nothing: "the transitive status of a session tag does not
impact its packed binary size."
`sts:TransitiveTagKeys` is in the request context the role's trust policy is read with, carrying the
keys the request names rather than the ones it inherits, since the key "compares the transitive
session tag keys in the request with those specified in the policy". A request naming none leaves it
absent, which is what the guide's own example policy tests with a `Null` condition on it. It is not
in the context of the caller's own identity-based policies, which is read from the generated
`request-condition-keys.json`, and that file does not list the key for `sts:AssumeRole`.
One rule of the chain is not implemented. Transitive tags "replace matching ResourceTag values after
the evaluation of the role trust policy", so a chained session's tag shadows the assumed role's tag
of that key. Floci publishes no `aws:ResourceTag/<key>` for the role in either evaluation, so there
is no value for a transitive tag to replace: what has to come first is the role's own tags reaching
those contexts. The guide's example also says a session tag naming the role tag of an earlier link
fails, which does not follow from the published rule, that tag being nothing the earlier session
passed down, so what is built here is the rule the API Reference states.
### Known limitations
- **The tag and source-identity condition keys are not in the request context.**
`aws:RequestTag/*`, `aws:TagKeys`, `sts:TransitiveTagKeys` and `sts:SourceIdentity` are not
populated, so a condition on them does not match. A trust policy keyed on one of them therefore
reads as unsatisfied, including on the `sts:TagSession` permission a tagged assume needs, and
`sts:SetSourceIdentity` is not checked at all.
`aws:RequestTag/*`, `aws:TagKeys` and `sts:SourceIdentity` are not populated, so a condition on
them does not match. A trust policy keyed on one of them therefore reads as unsatisfied, including
on the `sts:TagSession` permission a tagged assume needs, and `sts:SetSourceIdentity` is not
checked at all. `sts:TransitiveTagKeys` is populated for the trust policy and not for the caller's
own identity-based policies, as [Transitive tags](#transitive-tags) says.
## Web Identity Validation (IRSA)
@@ -11,11 +11,14 @@ import java.util.Map;
* @param audiences the {@code aud} claim, normalized to a list (JWT allows string or array)
* @param principalTags the session tags the token passes, from either of the two claim formats
* 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
*/
public record WebIdentityToken(String issuer, String subject, List<String> audiences,
Map<String, String> principalTags) {
Map<String, String> principalTags,
List<String> transitiveTagKeys) {
public WebIdentityToken(String issuer, String subject, List<String> audiences) {
this(issuer, subject, audiences, Map.of());
this(issuer, subject, audiences, Map.of(), List.of());
}
}
@@ -41,6 +41,12 @@ public class WebIdentityTokenVerifier {
/** The namespace AWS publishes a token's session tags under, whichever format they take. */
private static final String TAGS_CLAIM = "https://aws.amazon.com/tags";
private static final String FLATTENED_TAG_CLAIM = TAGS_CLAIM + "/principal_tags/";
/** The nested member, and the flattened claim, naming the keys to set as transitive. */
private static final String TRANSITIVE_KEYS = "transitive_tag_keys";
private static final String FLATTENED_TRANSITIVE_CLAIM = TAGS_CLAIM + "/" + TRANSITIVE_KEYS;
/** What a transitive tag key claim of any other shape is refused with, Floci's own wording. */
static final String TRANSITIVE_KEYS_MALFORMED =
"The web identity token's transitive tag keys do not read as an array of strings";
private final ObjectMapper objectMapper;
@@ -126,7 +132,8 @@ public class WebIdentityTokenVerifier {
throw new InvalidTokenException("The web identity token has no subject claim");
}
return new WebIdentityToken(issuer, subject, audiences, readPrincipalTags(claims));
return new WebIdentityToken(issuer, subject, audiences, readPrincipalTags(claims),
readTransitiveTagKeys(claims));
}
private void verifyValidityWindow(JsonNode claims) throws InvalidTokenException {
@@ -172,9 +179,7 @@ public class WebIdentityTokenVerifier {
* published nested example writes each as an array holding that one value, so a single-element
* array is read as the value it holds. Anything else is a multi-valued session tag, which "AWS
* STS does not support", and the token is refused rather than verified with that tag dropped:
* a tag a policy would have been evaluated with cannot go missing quietly. The transitive tag
* keys the same namespace carries are not read: nothing here passes a tag into a later session
* yet, and a key stored unread would say otherwise.
* a tag a policy would have been evaluated with cannot go missing quietly.
*/
private Map<String, String> readPrincipalTags(JsonNode claims) throws InvalidTokenException {
Map<String, String> tags = new LinkedHashMap<>();
@@ -194,6 +199,46 @@ public class WebIdentityTokenVerifier {
return tags;
}
/**
* The keys the token asks to set as transitive, in the order the claim lists them, read in
* both formats as the tags are: nested, where "transitive tag keys are represented in an array
* under the transitive_tag_keys key" of the same namespace, and flattened, "in a single claim
* as an array of strings with the prefix https://aws.amazon.com/tags/transitive_tag_keys".
*
* <p>Both published examples write an array, and a lone string is read as the one key it names
* rather than refused, which is the same reading {@link #singleValue} gives a tag written
* without its array. A claim of any other shape, or one holding something that is not a
* string, is refused rather than read past: a key dropped quietly would leave a chained
* session short of a tag whose absence a policy can turn on. Which keys select a tag is the
* session's business, not this one's.
*/
private static List<String> readTransitiveTagKeys(JsonNode claims) throws InvalidTokenException {
List<String> keys = new ArrayList<>();
readTransitiveKeysInto(claims.path(TAGS_CLAIM).path(TRANSITIVE_KEYS), keys);
readTransitiveKeysInto(claims.path(FLATTENED_TRANSITIVE_CLAIM), keys);
return keys;
}
private static void readTransitiveKeysInto(JsonNode claim, List<String> keys)
throws InvalidTokenException {
if (claim.isMissingNode() || claim.isNull()) {
return;
}
if (claim.isTextual()) {
keys.add(claim.asText());
return;
}
if (!claim.isArray()) {
throw new InvalidTokenException(TRANSITIVE_KEYS_MALFORMED);
}
for (JsonNode key : claim) {
if (!key.isTextual()) {
throw new InvalidTokenException(TRANSITIVE_KEYS_MALFORMED);
}
keys.add(key.asText());
}
}
/** The one value a tag claim carries, written as a string or as an array holding it alone. */
private static String singleValue(String key, JsonNode value) throws InvalidTokenException {
if (value.isTextual()) {
@@ -5198,8 +5198,18 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
* tag keys", and a second such tag "replaces the first tag. A second tag is not added." Stored
* as two they would reach a policy as one key with the other's value dropped, and a Deny keyed
* on that value would stop matching.
*
* <p>{@code transitiveTagKeys} are the keys among them the request asked to set as transitive,
* which is what {@link #callerTransitiveSessionTags} then carries into a session assumed from
* this one. Only a key naming one of these tags selects anything: a key naming none carries no
* tag onward, there being no tag of that key in the session to carry, and the keys are matched
* against the tags the same way a tag key is compared anywhere else here, without regard to
* case. The spellings kept are the ones the request sent, as the tag keys themselves are, and a
* key named twice, which a chained request can do by naming one it already inherits, is one
* key.
*/
public void recordSessionTags(String sessionAccessKeyId, Map<String, String> tags) {
public void recordSessionTags(String sessionAccessKeyId, Map<String, String> tags,
List<String> transitiveTagKeys) {
if (sessionAccessKeyId == null || tags == null || tags.isEmpty()) {
return;
}
@@ -5208,12 +5218,55 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
oneTagPerKey.keySet().removeIf(stored -> stored.equalsIgnoreCase(key));
oneTagPerKey.put(key, value);
});
List<String> transitive = new ArrayList<>();
if (transitiveTagKeys != null) {
for (String key : transitiveTagKeys) {
if (oneTagPerKey.keySet().stream().anyMatch(key::equalsIgnoreCase)
&& transitive.stream().noneMatch(key::equalsIgnoreCase)) {
transitive.add(key);
}
}
}
sessions.get(sessionAccessKeyId).ifPresent(session -> {
session.setSessionTags(oneTagPerKey);
session.setTransitiveTagKeys(transitive);
sessions.put(sessionAccessKeyId, session);
});
}
/**
* The transitive session tags the credentials {@code accessKeyId} carry, which a session
* assumed from them inherits: "if you used temporary credentials to perform this operation,
* the new session inherits any transitive session tags from the calling session".
*
* <p>Only session tags are ever in it. A role's own tags are never transitive, which the guide
* states outright, "you cannot set role tags as transitive", and shows: the second session of
* its chain inherits the first session's two transitive tags and not the tag attached to the
* role it assumed. A long-term key carries none, there being no session behind it, and so does
* a session that named no transitive key.
*/
public Map<String, String> callerTransitiveSessionTags(String accessKeyId) {
return findSessionForCallerContext(accessKeyId)
.map(IamService::transitiveSessionTags)
.orElseGet(Map::of);
}
private static Map<String, String> transitiveSessionTags(SessionCredential session) {
if (session.getTransitiveTagKeys().isEmpty()) {
return Map.of();
}
Set<String> transitive = session.getTransitiveTagKeys().stream()
.map(key -> key.toLowerCase(Locale.ROOT))
.collect(Collectors.toSet());
Map<String, String> tags = new LinkedHashMap<>();
session.getSessionTags().forEach((key, value) -> {
if (transitive.contains(key.toLowerCase(Locale.ROOT))) {
tags.put(key, value);
}
});
return tags;
}
/**
* When the credentials {@code accessKeyId} names last authenticated with an MFA device, empty
* for a session minted without one and for every long-term key. A session assumed from such a
@@ -42,6 +42,14 @@ final class SAMLAssertionVerifier {
/** What a session tag attribute naming no key is refused with, this package's own wording. */
static final String TAG_KEY_MISSING =
"A PrincipalTag attribute must name the tag key after the colon.";
/**
* What an attribute naming the keys to set as transitive is named: "include another Attribute
* element with the Name attribute set to
* https://aws.amazon.com/SAML/Attributes/TransitiveTagKeys", which unlike a tag attribute "is
* an optional multivalued attribute", so each of its values is one key.
*/
private static final String TRANSITIVE_TAG_KEYS =
"https://aws.amazon.com/SAML/Attributes/TransitiveTagKeys";
// The pattern AWS names in its error for a RoleSessionName attribute outside it.
static final String ROLE_SESSION_NAME_INVALID = "RoleSessionName in AuthnResponse must match [a-zA-Z_0-9+=,.@-]{2,64}";
private static final Pattern ROLE_SESSION_NAME_PATTERN = Pattern.compile("[a-zA-Z_0-9+=,.@-]{2,64}");
@@ -52,12 +60,14 @@ final class SAMLAssertionVerifier {
private SAMLAssertionVerifier() {}
/**
* {@code roleSessionName} is null when the assertion carries no RoleSessionName attribute, and
* {@code principalTags} is empty when it carries no session tags.
* {@code roleSessionName} is null when the assertion carries no RoleSessionName attribute,
* {@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.
*/
record Verified(String issuer, String subject, String subjectType, String nameQualifier,
Instant expiration, List<RolePair> roles, String roleSessionName,
Map<String, String> principalTags) {}
Map<String, String> principalTags, List<String> transitiveTagKeys) {}
record RolePair(String roleArn, String principalArn) {}
static Verified verify(String encoded, SAMLProvider provider, Instant now) throws InvalidAssertionException {
@@ -190,7 +200,7 @@ 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));
roleSessionName, principalTags(attributes), transitiveTagKeys(attributes));
} catch (InvalidAssertionException e) {
throw e;
} catch (Exception e) {
@@ -255,6 +265,30 @@ final class SAMLAssertionVerifier {
return tags;
}
/**
* The keys the assertion asks to set as transitive, in the order its values read.
*
* <p>This attribute is the one AWS publishes as multivalued, each value naming one key, so
* several values are read rather than refused as a session tag's would be, and an attribute
* carrying none asks for nothing. The value is taken as the assertion signed it, as a tag key
* attribute's is. Which of them select a tag is the session's business, not this one's: a key
* naming no session tag carries no tag onward, and nothing published says AWS refuses it.
*/
private static List<String> transitiveTagKeys(NodeList attributes) {
List<String> keys = new ArrayList<>();
for (int i = 0; i < attributes.getLength(); i++) {
Element attribute = (Element) attributes.item(i);
if (!TRANSITIVE_TAG_KEYS.equals(attribute.getAttribute("Name"))) {
continue;
}
NodeList values = attribute.getElementsByTagNameNS(SAML, "AttributeValue");
for (int j = 0; j < values.getLength(); j++) {
keys.add(values.item(j).getTextContent());
}
}
return keys;
}
/** 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:"
@@ -42,6 +42,7 @@ import java.time.Duration;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -147,7 +148,8 @@ public class StsQueryHandler {
// A session whose token will not fit is refused before anything is minted, on every
// operation that carries state into the token it mints.
if (PACKED_SESSION_OPERATIONS.contains(action)) {
AssembledSession session = assembledSession(action, params);
AssembledSession session = assembledSession(action, params,
inheritedTransitiveTags(action));
if (session.tooLarge()) {
return session.refusal();
}
@@ -198,8 +200,13 @@ public class StsQueryHandler {
String callerAccountId = regionResolver.getAccountId();
String accountId = AwsArnUtils.accountOrDefault(roleArn, callerAccountId);
// What the calling session passes down to this one, which is nothing unless it was itself
// minted with transitive tags. It is read before the trust policy, which has to permit
// tagging the session for these as well as for the tags the request passes.
Map<String, String> inheritedTags = inheritedTransitiveTags("AssumeRole");
IamRole role = iamService.findRole(accountId, roleName).orElse(null);
Response trustDenied = enforceTrustPolicy(roleArn, role, accountId, params, mfa);
Response trustDenied = enforceTrustPolicy(roleArn, role, accountId, params, mfa, inheritedTags);
if (trustDenied != null) {
return trustDenied;
}
@@ -215,6 +222,14 @@ public class StsQueryHandler {
AwsNamespaces.STS, 400);
}
// The collision is read beside the other rule that turns on the caller being a session,
// the chaining cap above, and after the role has allowed the assume: nothing published
// says which of the two refusals AWS reaches first.
Response collision = refuseInheritedTagCollision(inheritedTags, params);
if (collision != null) {
return collision;
}
String sessionRoleArn = canonicalRoleArn(role, accountId, roleName);
String assumedRoleArn = assumedRoleArn(sessionRoleArn, accountId, roleName, sessionName);
String assumedRoleId = assumedRoleId(role, sessionName);
@@ -228,7 +243,15 @@ public class StsQueryHandler {
iamService.registerSession(
accessKeyId, secretKey, sessionToken, sessionRoleArn, expiration, sessionPolicy, callerAccountId,
sessionName, assumedRoleId);
iamService.recordSessionTags(accessKeyId, requestTags(params));
// The tags inherited from the calling session are this session's own from here on, under
// the ones the request passes, and the keys they came in under stay transitive so the next
// session in the chain inherits them too: in the guide's chain the second session's
// inherited tags "continue to be transitive" without the second request naming them.
Map<String, String> sessionTags = new LinkedHashMap<>(inheritedTags);
sessionTags.putAll(requestTags(params));
List<String> transitiveKeys = new ArrayList<>(inheritedTags.keySet());
transitiveKeys.addAll(transitiveTagKeys(params));
iamService.recordSessionTags(accessKeyId, sessionTags, transitiveKeys);
String result = new XmlBuilder()
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
@@ -236,7 +259,7 @@ public class StsQueryHandler {
.elem("Arn", assumedRoleArn)
.elem("AssumedRoleId", assumedRoleId)
.end("AssumedRoleUser")
.raw(sessionSizeXml("AssumeRole", params))
.raw(sessionSizeXml("AssumeRole", assembledSession("AssumeRole", params, inheritedTags)))
.build();
return Response.ok(AwsQueryResponse.envelope("AssumeRole", AwsNamespaces.STS, result)).build();
}
@@ -321,10 +344,12 @@ public class StsQueryHandler {
* the two operations that mint a session out of the caller's own credentials declare no state
* at all, so a parameter STS would ignore cannot be made to cost a caller anything.
*
* <p>{@code carriedTags} is for the tags an operation takes from its message instead: they are
* state the session carries like any other, "session policies and session tags add to the
* session token size", and they are known only once the assertion or the token they arrived in
* has been verified, which is where those two operations read this.
* <p>{@code carriedTags} is for the tags that reach a session other than as a member of its
* own request: they are state it carries like any other, "session policies and session tags
* add to the session token size". For the two operations that take their tags from a message
* they are known only once the assertion or the token has been verified, which is where those
* read this; for a chained assume they are the tags inherited from the calling session, which
* the new session carries as its own and so pays for in the same way.
*/
private AssembledSession assembledSession(String action, MultivaluedMap<String, String> params) {
return assembledSession(action, params, Map.of());
@@ -484,7 +509,8 @@ public class StsQueryHandler {
* principal does wherever else Floci builds it.
*/
private Response enforceTrustPolicy(String roleArn, IamRole role, String roleAccountId,
MultivaluedMap<String, String> params, MfaOutcome mfa) {
MultivaluedMap<String, String> params, MfaOutcome mfa,
Map<String, String> inheritedTags) {
String callerAccount = regionResolver.getAccountId();
IamService.CallerArns caller = iamService.resolveCallerArns(callerAccessKeyId())
.orElseGet(() -> IamService.CallerArns.accountRoot(
@@ -518,15 +544,27 @@ public class StsQueryHandler {
if (externalId != null) {
trustContext.put("sts:ExternalId", List.of(externalId));
}
// "Compares the transitive session tag keys in the request with those specified in the
// policy", so it is the keys this request names rather than the ones it inherits, and a
// request naming none leaves the key absent, which is what the guide's own policy example
// tests with a Null condition on it.
List<String> requestedTransitiveKeys = transitiveTagKeys(params);
if (!requestedTransitiveKeys.isEmpty()) {
trustContext.put("sts:TransitiveTagKeys", requestedTransitiveKeys);
}
if (!trustPolicyEvaluator.allows(role.getAssumeRolePolicyDocument(), caller, callerAccount,
trustContext)) {
return AwsQueryResponse.error("AccessDenied",
"User: " + callerArn + " is not authorized to perform: sts:AssumeRole on resource: " + roleArn,
AwsNamespaces.STS, 403);
}
// A request that carries session tags needs the trust policy's permission to carry them:
// "for roles without this permission in the trust policy, the AssumeRole operation fails".
if (!requestTags(params).isEmpty()
// A session the request tags needs the trust policy's permission to carry them: "for roles
// without this permission in the trust policy, the AssumeRole operation fails". The tags
// the calling session passes down count as much, being session tags of the session this
// mints: the guide lists "incoming transitive session tags" among the tags a principal
// carries, and where a base role's tags are passed on by STS "the trust policy must also
// allow sts:TagSession", the refusal naming that action as this one does.
if ((!requestTags(params).isEmpty() || !inheritedTags.isEmpty())
&& !trustPolicyEvaluator.allowsTagging(role.getAssumeRolePolicyDocument(), caller,
callerAccount, trustContext)) {
return AwsQueryResponse.error("AccessDenied", "User: " + callerArn
@@ -707,8 +745,10 @@ public class StsQueryHandler {
accessKeyId, secretKey, sessionToken, sessionRoleArn, expiration, sessionPolicy, callerAccountId,
sessionName, assumedRoleId);
// The token's own claims, this operation declaring no Tags member: a session tag reaches it
// "in the JSON Web Token (JWT) when you submit the AssumeRoleWithWebIdentity request".
iamService.recordSessionTags(accessKeyId, carriedTags);
// "in the JSON Web Token (JWT) when you submit the AssumeRoleWithWebIdentity request", and
// the keys to set as transitive arrive in the same namespace.
iamService.recordSessionTags(accessKeyId, carriedTags,
verified != null ? verified.transitiveTagKeys() : List.of());
String result = new XmlBuilder()
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
@@ -745,7 +785,8 @@ 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) {}
Map<String, String> principalTags,
List<String> transitiveTagKeys) {}
private record WebIdentityOutcome(VerifiedWebIdentity verified, IamRole role, Response denial) {
@@ -829,7 +870,7 @@ public class StsQueryHandler {
// verify() already required the audience list to contain STS_AUDIENCE.
return WebIdentityOutcome.allow(
new VerifiedWebIdentity(claims.issuer(), claims.subject(), STS_AUDIENCE,
claims.principalTags()), role.get());
claims.principalTags(), claims.transitiveTagKeys()), role.get());
}
private static String assumedRoleId(IamRole role, String sessionName) {
@@ -950,8 +991,10 @@ public class StsQueryHandler {
iamService.registerSession(accessKeyId, secretKey, sessionToken, sessionRoleArn, expiration, null,
callerAccountId, sessionName, assumedRoleId);
// The assertion's own attributes, this operation declaring no Tags member either.
iamService.recordSessionTags(accessKeyId, verified.principalTags());
// The assertion's own attributes, this operation declaring no Tags member either, the
// keys to set as transitive arriving as an attribute of their own beside the tags.
iamService.recordSessionTags(accessKeyId, verified.principalTags(),
verified.transitiveTagKeys());
String result = new XmlBuilder()
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
.start("AssumedRoleUser").elem("Arn", assumedRoleArn).elem("AssumedRoleId", assumedRoleId).end("AssumedRoleUser")
@@ -1005,7 +1048,11 @@ public class StsQueryHandler {
// minted it, so the caller is recorded with it.
iamService.registerIssuedSession(accessKeyId, secretKey, sessionToken, federatedUserArn, expiration,
sessionPolicy, accountId, callerAccessKeyId());
iamService.recordSessionTags(accessKeyId, requestTags(params));
// None of them is transitive: this operation declares no TransitiveTagKeys member, and the
// guide says why, that "you can't set session tags as transitive when you use
// GetFederationToken, because you can't use the temporary credentials" it returns to
// assume a role.
iamService.recordSessionTags(accessKeyId, requestTags(params), List.of());
String result = new XmlBuilder()
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
@@ -1427,6 +1474,66 @@ public class StsQueryHandler {
return claims;
}
/**
* The keys the request's own {@code TransitiveTagKeys} member names, in the order their
* indexes read, each as it was sent: the model holds every one of them to a minimum length of
* 1, so by here none is absent, and holds the list to 50 members of 128 characters apiece.
*
* <p>A key naming no tag of this request selects nothing, there being no tag of that key for a
* later session to inherit, and nothing published says AWS refuses it.
*/
private static List<String> transitiveTagKeys(MultivaluedMap<String, String> params) {
return AwsQueryLists.members(params, "TransitiveTagKeys", null).stream()
.map(member -> params.getFirst(member.prefix()))
.filter(Objects::nonNull)
.toList();
}
/**
* The transitive session tags the caller passes down to the session this request mints: "if
* you used temporary credentials to perform this operation, the new session inherits any
* transitive session tags from the calling session". A long-term key carries none, and neither
* does a session that set none transitive, which is AWS's default.
*
* <p>Only the operation that declares {@code TransitiveTagKeys} chains them, which is the
* generated request shapes answering which one that is rather than this naming it: the rule is
* published on that operation's own {@code Tags} member, and the other operation taking a
* {@code Tags} member mints a session that "can't" be used to assume a role at all.
*/
private Map<String, String> inheritedTransitiveTags(String action) {
if (!StsRequestShapes.hasMember(action, "TransitiveTagKeys")) {
return Map.of();
}
return iamService.callerTransitiveSessionTags(callerAccessKeyId());
}
/**
* The refusal for a session tag whose key the calling session already passes down: "if you
* pass a session tag with the same key as an inherited tag, the operation fails". The key is
* matched without regard to case, as a tag key is everywhere else here, so a request passing
* {@code department} cannot sidestep an inherited {@code Department} either.
*
* <p>That it fails is published; what AWS answers is not. The code is the one this operation
* already gives the other rule that turns on the caller being a session, the chaining cap, and
* the sentence is this package's own, naming the key as the request spelled it. Taking the
* request's tag instead would have let a chain quietly drop a tag a policy turns on, which the
* inheritance exists to carry.
*/
private static Response refuseInheritedTagCollision(Map<String, String> inheritedTags,
MultivaluedMap<String, String> params) {
if (inheritedTags.isEmpty()) {
return null;
}
for (String key : requestTags(params).keySet()) {
if (inheritedTags.keySet().stream().anyMatch(inherited -> inherited.equalsIgnoreCase(key))) {
return AwsQueryResponse.error("ValidationError", "Session tag " + key
+ " cannot be passed because the calling session carries it as a transitive"
+ " tag.", AwsNamespaces.STS, 400);
}
}
return null;
}
/**
* {@code jwtAlgorithmType} publishes a fixed length of 5 and no enum, and the reference names
* the two values that length is for, so the value set is documented where the length is
@@ -89,6 +89,15 @@ public class SessionCredential {
* Floci recorded them.
*/
private Map<String, String> sessionTags = new LinkedHashMap<>();
/**
* The keys among those session tags the session was asked to set as transitive, in the order
* the request named them: "if you set a tag key as transitive, the corresponding key and value
* passes to subsequent sessions in a role chain". A session assumed from this one inherits
* those tags and keeps their keys transitive, so a chain carries them all the way down. Empty
* for a session that named none, which is AWS's default: "if you choose not to specify a
* transitive tag key, then no tags are passed from this session to any subsequent sessions".
*/
private List<String> transitiveTagKeys = new ArrayList<>();
public SessionCredential() {}
@@ -220,4 +229,13 @@ public class SessionCredential {
public void setSessionTags(Map<String, String> sessionTags) {
this.sessionTags = sessionTags == null ? new LinkedHashMap<>() : new LinkedHashMap<>(sessionTags);
}
public List<String> getTransitiveTagKeys() {
return transitiveTagKeys;
}
public void setTransitiveTagKeys(List<String> transitiveTagKeys) {
this.transitiveTagKeys = transitiveTagKeys == null
? new ArrayList<>() : new ArrayList<>(transitiveTagKeys);
}
}
@@ -17,6 +17,7 @@ import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.interfaces.RSAPublicKey;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -194,8 +195,8 @@ class WebIdentityTokenVerifierTest {
* The session tags a token passes in the nested format, "a structure within the
* https://aws.amazon.com/tags namespace", where the tags sit "under the principal_tags key".
* The published example writes each value as an array holding one string while the prose calls
* each tag "a single string value", so both forms are read. The transitive keys beside them are
* not read.
* each tag "a single string value", so both forms are read. The keys to set as transitive sit
* in the same namespace, "in an array under the transitive_tag_keys key".
*/
@Test
void readsTheSessionTagsOfTheNestedClaimFormat() throws Exception {
@@ -209,6 +210,7 @@ class WebIdentityTokenVerifierTest {
EksOidcService.STS_AUDIENCE);
assertEquals(Map.of("Project", "Automation", "CostCenter", "987654"), verified.principalTags());
assertEquals(List.of("Project"), verified.transitiveTagKeys());
}
/**
@@ -242,8 +244,8 @@ class WebIdentityTokenVerifierTest {
/**
* And in the flattened format, "compatible with identity providers that don't support nested
* objects in JWT claims", where each tag is "a separate claim with the prefix
* https://aws.amazon.com/tags/principal_tags/" and the transitive keys are one claim of their
* own, which is not a tag.
* https://aws.amazon.com/tags/principal_tags/" and the transitive keys are "a single claim as
* an array of strings" of their own, which is not a tag.
*/
@Test
void readsTheSessionTagsOfTheFlattenedClaimFormat() throws Exception {
@@ -258,6 +260,45 @@ class WebIdentityTokenVerifierTest {
assertEquals(Map.of("Project", "Automation", "Department", "Engineering"),
verified.principalTags());
assertEquals(List.of("Project"), verified.transitiveTagKeys());
}
/**
* A transitive key claim of a shape neither published example writes. A lone string is read as
* the one key it names, the same reading a tag written without its array gets, and anything
* else is refused rather than read past: a key dropped quietly would leave a chained session
* short of a tag whose absence a policy can turn on.
*/
@Test
void readsALoneTransitiveKeyAndRefusesAClaimThatIsNeitherStringNorStringArray() throws Exception {
KeyPair keyPair = newKeyPair();
String lone = signRs256(keyPair.getPrivate(), claims(
"\"https://aws.amazon.com/tags\":{\"principal_tags\":{\"Project\":\"Automation\"},"
+ "\"transitive_tag_keys\":\"Project\"}"));
assertEquals(List.of("Project"), verifier.verify(lone, (RSAPublicKey) keyPair.getPublic(),
ISSUER, EksOidcService.STS_AUDIENCE).transitiveTagKeys());
for (String claim : List.of("{\"Project\":true}", "[\"Project\",7]")) {
String malformed = signRs256(keyPair.getPrivate(), claims(
"\"https://aws.amazon.com/tags/transitive_tag_keys\":" + claim));
assertEquals(WebIdentityTokenVerifier.TRANSITIVE_KEYS_MALFORMED,
assertThrows(WebIdentityTokenVerifier.InvalidTokenException.class,
() -> verifier.verify(malformed, (RSAPublicKey) keyPair.getPublic(),
ISSUER, EksOidcService.STS_AUDIENCE)).getMessage());
}
}
/** A token passing tags but naming no transitive key passes none of them down, AWS's default. */
@Test
void aTokenNamingNoTransitiveKeyPassesNothingDown() throws Exception {
KeyPair keyPair = newKeyPair();
String token = signRs256(keyPair.getPrivate(), claims(
"\"https://aws.amazon.com/tags/principal_tags/Project\":\"Automation\""));
assertTrue(verifier.verify(token, (RSAPublicKey) keyPair.getPublic(), ISSUER,
EksOidcService.STS_AUDIENCE).transitiveTagKeys().isEmpty());
}
/** A token passing no tags carries none, which is every token this emulator mints itself. */
@@ -269,6 +310,7 @@ class WebIdentityTokenVerifierTest {
EksOidcService.STS_AUDIENCE);
assertTrue(verified.principalTags().isEmpty());
assertTrue(verified.transitiveTagKeys().isEmpty());
}
/** A valid claim set carrying {@code extra} beside the three claims every token needs. */
@@ -563,6 +563,37 @@ class AssumeRoleWithSamlValidationIntegrationTest {
iamService.resolveCallerArns(accessKeyId).orElseThrow().principalTags());
}
/**
* The keys the assertion asks to set as transitive pass down to a session assumed from this
* one: the attribute naming them "is an optional multivalued attribute that sets your session
* tags as transitive", so several values are read rather than refused as a tag attribute's
* would be. A tag the assertion carries but does not name there stays with this session, which
* is AWS's default.
*/
@Test
void theAssertionsTransitiveKeysAreWhatPassesDownFromTheSession() {
String role = createRoleAllowingTags();
Map<String, List<String>> tags = new LinkedHashMap<>();
tags.put("Project", List.of("Automation"));
tags.put("CostCenter", List.of("12345"));
String accessKeyId = assumeRequest(role,
assertionCarryingTags(role, tags, List.of("Project", "Absent")), PROVIDER)
.when().post("/").then().statusCode(200)
.extract().path("AssumeRoleWithSAMLResponse.AssumeRoleWithSAMLResult.Credentials.AccessKeyId");
assertEquals(Map.of("Project", "Automation"),
iamService.callerTransitiveSessionTags(accessKeyId),
"only the tag named transitive passes down, and a key naming none selects nothing");
String noneNamed = assumeRequest(role, assertionCarryingTags(role, tags), PROVIDER)
.when().post("/").then().statusCode(200)
.extract().path("AssumeRoleWithSAMLResponse.AssumeRoleWithSAMLResult.Credentials.AccessKeyId");
assertTrue(iamService.callerTransitiveSessionTags(noneNamed).isEmpty(),
"an assertion naming no transitive key passes nothing down");
}
/**
* The value is the one the assertion signed, spaces and all: a tag value may carry them, and
* trimming it would hand a policy a value the provider never asserted.
@@ -763,8 +794,14 @@ class AssumeRoleWithSamlValidationIntegrationTest {
* pass a tag with no value or with several.
*/
private static String assertionCarryingTags(String role, Map<String, List<String>> tags) {
return assertionCarryingTags(role, tags, List.of());
}
/** The same, asking for {@code transitiveTagKeys} to be set as transitive beside the tags. */
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);
factory -> List.of(enveloped(factory)), null, tags, transitiveTagKeys);
}
/** One session tag, the shape every case that passes a well-formed one uses. */
@@ -777,13 +814,14 @@ class AssumeRoleWithSamlValidationIntegrationTest {
Function<XMLSignatureFactory, List<Transform>> transforms,
String roleSessionName) {
return assertion(role, provider, expiry, audience, issuer, sign, unrelatedConfirmation, transforms,
roleSessionName, Map.of());
roleSessionName, Map.of(), List.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) {
String roleSessionName, Map<String, List<String>> principalTags,
List<String> transitiveTagKeys) {
String sessionNameAttribute = roleSessionName == null ? ""
: "<saml:Attribute Name=\"https://aws.amazon.com/SAML/Attributes/RoleSessionName\"><saml:AttributeValue>"
+ roleSessionName + "</saml:AttributeValue></saml:Attribute>";
@@ -795,6 +833,16 @@ class AssumeRoleWithSamlValidationIntegrationTest {
.append("</saml:AttributeValue>"));
tagAttributes.append("</saml:Attribute>");
});
if (!transitiveTagKeys.isEmpty()) {
// One multivalued attribute, which is how the guide writes this one: "include another
// Attribute element with the Name attribute set to
// https://aws.amazon.com/SAML/Attributes/TransitiveTagKeys".
tagAttributes.append("<saml:Attribute Name=\"https://aws.amazon.com/SAML/Attributes/")
.append("TransitiveTagKeys\">");
transitiveTagKeys.forEach(key -> tagAttributes.append("<saml:AttributeValue>").append(key)
.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>"
@@ -590,7 +590,8 @@ class IamServiceTest {
role.setTags(Map.of("Team", "role-team", "Owner", "platform"));
iamService.registerSession("ASIASESSIONTAGS", "secret", "token", role.getArn(),
Instant.now().plusSeconds(3600), null, "000000000000", "tagged", "AROATAGGED:tagged");
iamService.recordSessionTags("ASIASESSIONTAGS", Map.of("Team", "session-team", "Project", "atlas"));
iamService.recordSessionTags("ASIASESSIONTAGS", Map.of("Team", "session-team", "Project", "atlas"),
List.of());
Map<String, List<String>> context = new LinkedHashMap<>();
iamService.resolveCallerArns("ASIASESSIONTAGS").orElseThrow().putPrincipalKeys(context);
@@ -611,7 +612,7 @@ class IamServiceTest {
role.setTags(Map.of("department", "finance"));
iamService.registerSession("ASIACASETAGS", "secret", "token", role.getArn(),
Instant.now().plusSeconds(3600), null, "000000000000", "cased", "AROACASED:cased");
iamService.recordSessionTags("ASIACASETAGS", Map.of("Department", "engineering"));
iamService.recordSessionTags("ASIACASETAGS", Map.of("Department", "engineering"), List.of());
Map<String, List<String>> context = new LinkedHashMap<>();
iamService.resolveCallerArns("ASIACASETAGS").orElseThrow().putPrincipalKeys(context);
@@ -633,7 +634,7 @@ class IamServiceTest {
Map<String, String> sent = new LinkedHashMap<>();
sent.put("Team", "first");
sent.put("team", "second");
iamService.recordSessionTags("ASIAONETAG", sent);
iamService.recordSessionTags("ASIAONETAG", sent, List.of());
Map<String, List<String>> context = new LinkedHashMap<>();
iamService.resolveCallerArns("ASIAONETAG").orElseThrow().putPrincipalKeys(context);
@@ -642,6 +643,36 @@ class IamServiceTest {
assertFalse(context.containsKey("aws:PrincipalTag/Team"));
}
/**
* Only the tags whose keys a session set as transitive pass down to a session assumed from it:
* "if you set a tag key as transitive, the corresponding key and value passes to subsequent
* sessions in a role chain", and by default none does. A key naming no tag of the session
* selects nothing, there being no tag of that key to carry, and the keys are matched against
* the tags without regard to case, as a tag key is everywhere else here.
*/
@Test
void onlyTheTagsNamedTransitivePassDownFromASession() {
IamRole role = iamService.createRole("Chained", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
iamService.registerSession("ASIATRANSITIVE", "secret", "token", role.getArn(),
Instant.now().plusSeconds(3600), null, "000000000000", "chain", "AROACHAIN:chain");
Map<String, String> tags = new LinkedHashMap<>();
tags.put("Team", "platform");
tags.put("Scratch", "local");
iamService.recordSessionTags("ASIATRANSITIVE", tags, List.of("team", "Absent"));
assertEquals(Map.of("Team", "platform"),
iamService.callerTransitiveSessionTags("ASIATRANSITIVE"));
iamService.registerSession("ASIAUNTRANSITIVE", "secret", "token", role.getArn(),
Instant.now().plusSeconds(3600), null, "000000000000", "none", "AROANONE:none");
iamService.recordSessionTags("ASIAUNTRANSITIVE", tags, List.of());
assertTrue(iamService.callerTransitiveSessionTags("ASIAUNTRANSITIVE").isEmpty(),
"no transitive key named means nothing passes down");
assertTrue(iamService.callerTransitiveSessionTags("AKIALONGTERMKEY").isEmpty(),
"a long-term key has no session behind it to pass anything down");
}
/** A federated user's session tags join the tags of the user whose key minted the session. */
@Test
void federatedSessionTagsJoinTheIssuingUsersTags() {
@@ -651,7 +682,7 @@ class IamServiceTest {
iamService.registerIssuedSession("ASIAFEDTAGS", "secret", "token",
"arn:aws:sts::000000000000:federated-user/federated-tagged",
Instant.now().plusSeconds(3600), null, "000000000000", key);
iamService.recordSessionTags("ASIAFEDTAGS", Map.of("Project", "atlas"));
iamService.recordSessionTags("ASIAFEDTAGS", Map.of("Project", "atlas"), List.of());
Map<String, List<String>> context = new LinkedHashMap<>();
iamService.resolveCallerArns("ASIAFEDTAGS").orElseThrow().putPrincipalKeys(context);
@@ -49,6 +49,17 @@ class PrincipalTagEnforcementIntegrationTest {
private static final String ALLOW_ASSUME = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole","Resource":"*"}]}""";
/**
* What a role in a chain needs: the assume and the tagging for the next link, the tag-keyed
* Allow the probe turns on, and a Deny keyed on a tag that must not have come across.
*/
private static final String CHAINED_POLICY = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["sts:AssumeRole","sts:TagSession"],"Resource":"*"},
{"Effect":"Allow","Action":"iam:ListUsers","Resource":"*",
"Condition":{"StringEquals":{"aws:PrincipalTag/Team":"platform"}}},
{"Effect":"Deny","Action":"iam:ListUsers","Resource":"*",
"Condition":{"StringEquals":{"aws:PrincipalTag/Scratch":"local"}}}]}""";
private static final String TAG_POLICY = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"iam:ListUsers","Resource":"*",
@@ -268,6 +279,150 @@ class PrincipalTagEnforcementIntegrationTest {
}
}
/**
* A transitive session tag passes into the session assumed from it and stays transitive, so it
* reaches every later link: "if you set a tag key as transitive, the corresponding key and
* value passes to subsequent sessions in a role chain", and in the guide's own chain the
* second session's inherited tags "continue to be transitive" without the second request
* naming them again.
*
* <p>The two controls are what make it a test of the opt-in rather than of tags leaking. The
* tag that is not named transitive does not come across, which the Deny in the role's policy
* would have turned on, and a session that named no transitive key at all passes nothing,
* which is AWS's default: "by default, AWS STS does not pass tags to subsequent role sessions".
* The role assumed in the chain carries no tag of its own, so an inherited tag is the only way
* the Allow can match.
*/
@Test
void aTransitiveTagPassesIntoEveryLaterSessionOfTheChain() {
String first = "principal-chain-one-" + suffix();
String second = "principal-chain-two-" + suffix();
String source = "principal-chainer-" + suffix();
UserCredentials keys = user(ACCOUNT, source, ALLOW_ASSUME);
policy(source, "tagging", ALLOW_TAGGING);
try (IamClient admin = admin(ACCOUNT);
StsClient sts = AwsTestClients.create(StsClient.builder(), keys.accessKeyId(), keys.secretAccessKey(),
Region.US_EAST_1)) {
String one = role(admin, ACCOUNT, first, trustAllowingTags(), CHAINED_POLICY);
// The role assumed in the chain permits tagging too, which an inherited tag needs of it
// as much as a passed one does.
String two = role(admin, ACCOUNT, second, trustAllowingTags(), CHAINED_POLICY);
Credentials passed = sts.assumeRole(r -> r.roleArn(one).roleSessionName("chain-one")
.tags(sessionTag("Team", "platform"), sessionTag("Scratch", "local"))
.transitiveTagKeys("Team")).credentials();
try (StsClient chained = AwsTestClients.create(StsClient.builder(), sessionCredentials(passed),
Region.US_EAST_1, baseUri)) {
Credentials inherited = chained.assumeRole(r -> r.roleArn(two)
.roleSessionName("chain-two")).credentials();
try (IamClient caller = sessionClient(inherited)) {
caller.listUsers();
}
try (StsClient onwards = AwsTestClients.create(StsClient.builder(),
sessionCredentials(inherited), Region.US_EAST_1, baseUri)) {
Credentials third = onwards.assumeRole(r -> r.roleArn(two)
.roleSessionName("chain-three")).credentials();
try (IamClient caller = sessionClient(third)) {
caller.listUsers();
}
}
}
Credentials kept = sts.assumeRole(r -> r.roleArn(one).roleSessionName("chain-kept")
.tags(sessionTag("Team", "platform"))).credentials();
try (StsClient chained = AwsTestClients.create(StsClient.builder(), sessionCredentials(kept),
Region.US_EAST_1, baseUri)) {
Credentials nothing = chained.assumeRole(r -> r.roleArn(two)
.roleSessionName("chain-default")).credentials();
try (IamClient caller = sessionClient(nothing)) {
denied(caller::listUsers);
}
}
}
}
/**
* A chained assume is held to the role's tagging permission for the tags it inherits, not only
* for the tags its own request passes. The guide lists "incoming transitive session tags" among
* the tags a principal carries, and where a base role's own tags are passed on by STS "the
* trust policy must also allow sts:TagSession", the refusal naming that action. The same role
* takes an assume from a session that passes nothing down, so what is refused here is the
* tagging rather than the assume.
*/
@Test
void aChainedAssumeNeedsTheRolesTaggingPermissionForTheTagsItInherits() {
String first = "principal-inherit-one-" + suffix();
String second = "principal-inherit-two-" + suffix();
String source = "principal-inheritor-" + suffix();
UserCredentials keys = user(ACCOUNT, source, ALLOW_ASSUME);
policy(source, "tagging", ALLOW_TAGGING);
try (IamClient admin = admin(ACCOUNT);
StsClient sts = AwsTestClients.create(StsClient.builder(), keys.accessKeyId(), keys.secretAccessKey(),
Region.US_EAST_1)) {
String one = role(admin, ACCOUNT, first, trustAllowingTags(), CHAINED_POLICY);
String untagged = role(admin, ACCOUNT, second, trust(null), CHAINED_POLICY);
Credentials passing = sts.assumeRole(r -> r.roleArn(one).roleSessionName("inherit-one")
.tags(sessionTag("Team", "platform")).transitiveTagKeys("Team")).credentials();
try (StsClient chained = AwsTestClients.create(StsClient.builder(), sessionCredentials(passing),
Region.US_EAST_1, baseUri)) {
AwsServiceException refused = assertThrows(AwsServiceException.class,
() -> chained.assumeRole(r -> r.roleArn(untagged).roleSessionName("inherit-two")));
assertEquals(403, refused.statusCode());
assertTrue(refused.awsErrorDetails().errorMessage()
.endsWith("is not authorized to perform: sts:TagSession on resource: " + untagged),
refused.awsErrorDetails().errorMessage());
}
Credentials passingNothing = sts.assumeRole(r -> r.roleArn(one).roleSessionName("inherit-none")
.tags(sessionTag("Team", "platform"))).credentials();
try (StsClient chained = AwsTestClients.create(StsClient.builder(),
sessionCredentials(passingNothing), Region.US_EAST_1, baseUri)) {
chained.assumeRole(r -> r.roleArn(untagged).roleSessionName("inherit-plain"));
}
}
}
/**
* A session tag whose key the calling session already passes down is refused: "if you pass a
* session tag with the same key as an inherited tag, the operation fails". The key is matched
* without regard to case, as a tag key is anywhere else, so the lowercase spelling here is the
* same tag. What AWS answers is not published, so the code and the sentence are Floci's, and
* the role being assumed permits tagging, which is how this refusal is told apart from the
* tagging permission's.
*/
@Test
void aSessionTagCollidingWithAnInheritedTransitiveTagIsRefused() {
String first = "principal-collide-one-" + suffix();
String second = "principal-collide-two-" + suffix();
String source = "principal-collider-" + suffix();
UserCredentials keys = user(ACCOUNT, source, ALLOW_ASSUME);
policy(source, "tagging", ALLOW_TAGGING);
try (IamClient admin = admin(ACCOUNT);
StsClient sts = AwsTestClients.create(StsClient.builder(), keys.accessKeyId(), keys.secretAccessKey(),
Region.US_EAST_1)) {
String one = role(admin, ACCOUNT, first, trustAllowingTags(), CHAINED_POLICY);
String two = role(admin, ACCOUNT, second, trustAllowingTags(), CHAINED_POLICY);
Credentials passed = sts.assumeRole(r -> r.roleArn(one).roleSessionName("collide-one")
.tags(sessionTag("Team", "platform")).transitiveTagKeys("Team")).credentials();
try (StsClient chained = AwsTestClients.create(StsClient.builder(), sessionCredentials(passed),
Region.US_EAST_1, baseUri)) {
AwsServiceException refused = assertThrows(AwsServiceException.class,
() -> chained.assumeRole(r -> r.roleArn(two).roleSessionName("collide-two")
.tags(sessionTag("team", "other"))));
assertEquals(400, refused.statusCode());
assertEquals("ValidationError", refused.awsErrorDetails().errorCode());
assertTrue(refused.awsErrorDetails().errorMessage().contains("Session tag team"),
refused.awsErrorDetails().errorMessage());
// A key the calling session does not pass down is not held to it.
chained.assumeRole(r -> r.roleArn(two).roleSessionName("collide-other")
.tags(sessionTag("Scratch", "local")));
}
}
}
@Test
void sameNamedUsersInDifferentAccountsKeepTheirOwnTags() {
String name = "principal-account-" + suffix();
@@ -447,6 +447,13 @@ class StsQueryHandlerTest {
assertFalse(StsRequestShapes.hasMember("GetSessionToken", "Tags"));
assertFalse(StsRequestShapes.hasMember("AssumeRoot", "Policy"));
assertFalse(StsRequestShapes.hasMember("AssumeRoot", "Tags"));
// The one operation that chains tags is the one declaring the keys to chain them under,
// which is what the inheritance reads rather than naming the operation itself.
assertTrue(StsRequestShapes.hasMember("AssumeRole", "TransitiveTagKeys"));
assertFalse(StsRequestShapes.hasMember("GetFederationToken", "TransitiveTagKeys"));
assertFalse(StsRequestShapes.hasMember("AssumeRoleWithSAML", "TransitiveTagKeys"));
assertFalse(StsRequestShapes.hasMember("AssumeRoleWithWebIdentity", "TransitiveTagKeys"));
}
/**
@@ -470,7 +477,7 @@ class StsQueryHandlerTest {
.handle("AssumeRole", params);
assertEquals(200, response.getStatus(), (String) response.getEntity());
verify(assumed).recordSessionTags(anyString(), eq(Map.of("Project", "atlas")));
verify(assumed).recordSessionTags(anyString(), eq(Map.of("Project", "atlas")), eq(List.of()));
IamService longTerm = mock(IamService.class);
MultivaluedMap<String, String> untagged = sessionRequest("GetSessionToken");
@@ -481,7 +488,63 @@ class StsQueryHandlerTest {
.handle("GetSessionToken", untagged);
assertEquals(200, longTermResponse.getStatus(), (String) longTermResponse.getEntity());
verify(longTerm, never()).recordSessionTags(anyString(), anyMap());
verify(longTerm, never()).recordSessionTags(anyString(), anyMap(), anyList());
}
/**
* What the calling session passes down joins the tags of the session being minted, and the
* keys it came in under stay transitive so the next link inherits them too. The request's own
* transitive keys are added to them, and a request that names one is still measured by the
* tags it carries rather than by the keys: "the transitive status of a session tag does not
* impact its packed binary size".
*/
@Test
void aChainedSessionCarriesTheTagsTheCallingSessionPassesDown() {
IamRole role = new IamRole();
role.setRoleName("TestRole");
role.setArn("arn:aws:iam::000000000000:role/TestRole");
IamService chained = mock(IamService.class);
when(chained.findRole(anyString(), anyString())).thenReturn(Optional.of(role));
when(chained.callerTransitiveSessionTags(any())).thenReturn(Map.of("Star", "1"));
MultivaluedMap<String, String> params = sessionRequest("AssumeRole");
params.putSingle("Tags.member.1.Key", "Sun");
params.putSingle("Tags.member.1.Value", "2");
params.putSingle("TransitiveTagKeys.member.1", "Sun");
Response response = newHandler(chained, new RegionResolver(REGION, "000000000000"))
.handle("AssumeRole", params);
assertEquals(200, response.getStatus(), (String) response.getEntity());
verify(chained).recordSessionTags(anyString(), eq(Map.of("Star", "1", "Sun", "2")),
eq(List.of("Star", "Sun")));
}
/**
* A session tag whose key the calling session already passes down is refused: "if you pass a
* session tag with the same key as an inherited tag, the operation fails". Nothing is minted
* for it, and the key is matched without regard to case.
*/
@Test
void aSessionTagCollidingWithAnInheritedTransitiveTagIsRefused() {
IamRole role = new IamRole();
role.setRoleName("TestRole");
role.setArn("arn:aws:iam::000000000000:role/TestRole");
IamService chained = mock(IamService.class);
when(chained.findRole(anyString(), anyString())).thenReturn(Optional.of(role));
when(chained.callerTransitiveSessionTags(any())).thenReturn(Map.of("Star", "1"));
MultivaluedMap<String, String> params = sessionRequest("AssumeRole");
params.putSingle("Tags.member.1.Key", "star");
params.putSingle("Tags.member.1.Value", "9");
Response response = newHandler(chained, new RegionResolver(REGION, "000000000000"))
.handle("AssumeRole", params);
assertEquals(400, response.getStatus(), (String) response.getEntity());
String body = (String) response.getEntity();
assertTrue(body.contains("ValidationError"), body);
assertTrue(body.contains("Session tag star"), body);
verify(chained, never()).registerSession(anyString(), anyString(), anyString(), anyString(),
any(), any(), anyString(), anyString(), anyString());
}
/** The least a request needs to reach issuance on an operation that models a token size. */
@@ -1070,7 +1133,8 @@ class StsQueryHandlerTest {
when(verifier.peekIssuer("jwt0")).thenReturn(Optional.of(issuer));
when(verifier.verify(eq("jwt0"), any(), eq(issuer), anyString()))
.thenReturn(new WebIdentityToken(issuer, "system:serviceaccount:default:app",
List.of("sts.amazonaws.com"), Map.of("Project", "atlas")));
List.of("sts.amazonaws.com"), Map.of("Project", "atlas"),
List.of("Project")));
OidcIssuerKeyLookup keys = mock(OidcIssuerKeyLookup.class);
when(keys.findVerificationKey(issuer)).thenReturn(Optional.of(mock(RSAPublicKey.class)));
WebIdentityTrustPolicyEvaluator trust = mock(WebIdentityTrustPolicyEvaluator.class);
@@ -1095,7 +1159,10 @@ class StsQueryHandlerTest {
verify(trust).allows(eq("{}"), eq(providerArn), eq("oidc.example.com/id/ABC"), anyMap(), eq("app"));
assertEquals("arn:aws-cn:sts::000000000000:assumed-role/web-role/app",
extract(ARN, (String) response.getEntity()));
verify(iamService).recordSessionTags(anyString(), eq(Map.of("Project", "atlas")));
// The token's own transitive key is recorded with its tags, so a session assumed from this
// one inherits the tag.
verify(iamService).recordSessionTags(anyString(), eq(Map.of("Project", "atlas")),
eq(List.of("Project")));
// The token's tags are state its session carries, so they count with the token itself.
assertEquals(Integer.toString(200 + "Project".length() + "atlas".length()),
extract(SESSION_TOKEN_SIZE, (String) response.getEntity()));