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

@@ -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()));