fix(sts): give web identity and SAML trust policies the sts:RoleSessionName key (#8920)

This commit is contained in:
Jeremy Chapeau authored and GitHub committed 2026-11-20 20:14:00 -04:00
1 parent 91ed539910
commit 7b88a31956
12 files changed
+448 -41

No files matched your search

@@ -65,6 +65,7 @@ import java.util.function.Function;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -236,6 +237,64 @@ class AssumeRoleWithSamlValidationIntegrationTest {
.statusCode(403).body(containsString("AccessDenied"));
}
/**
* "You can use an Attribute element with the Name attribute set to
* https://aws.amazon.com/SAML/Attributes/RoleSessionName. This element contains one
* AttributeValue element that provides an identifier for the temporary credentials that are
* issued when the role is assumed." It names the session, and it is the {@code sts:RoleSessionName}
* a trust policy reads, which the Service Authorization Reference lists for
* {@code sts:AssumeRoleWithSAML}.
*/
@Test
void trustPolicyRequiringTheSessionNameAllowsTheAssertionThatCarriesIt() {
String role = createRoleWithCondition("{\"StringEquals\":{\"sts:RoleSessionName\":\"alice@example.test\"}}");
assume(role, assertionNamingSession(role, "alice@example.test"), PROVIDER)
.statusCode(200)
.body("AssumeRoleWithSAMLResponse.AssumeRoleWithSAMLResult.AssumedRoleUser.Arn",
equalTo("arn:aws:sts::" + ACCOUNT + ":assumed-role/" + role.substring(role.lastIndexOf('/') + 1)
+ "/alice@example.test"))
.body("AssumeRoleWithSAMLResponse.AssumeRoleWithSAMLResult.AssumedRoleUser.AssumedRoleId",
endsWith(":alice@example.test"));
}
@Test
void trustPolicyRequiringTheSessionNameRefusesAnotherName() {
String role = createRoleWithCondition("{\"StringEquals\":{\"sts:RoleSessionName\":\"alice@example.test\"}}");
assume(role, assertionNamingSession(role, "mallory"), PROVIDER)
.statusCode(403).body(containsString("AccessDenied"));
}
@Test
void trustPolicyRequiringTheSessionNameRefusesAnAssertionWithoutOne() {
String role = createRoleWithCondition("{\"StringEquals\":{\"sts:RoleSessionName\":\"alice@example.test\"}}");
assume(role, assertion(role, PROVIDER, Instant.now().plusSeconds(300), AUDIENCE, ISSUER, true), PROVIDER)
.statusCode(403).body(containsString("AccessDenied"));
}
@Test
void theSessionNameAttributeNamesTheSessionWithoutACondition() {
String role = createRole(true);
assume(role, assertionNamingSession(role, "bob"), PROVIDER)
.statusCode(200)
.body("AssumeRoleWithSAMLResponse.AssumeRoleWithSAMLResult.AssumedRoleUser.Arn", endsWith("/bob"));
}
/**
* "Error: RoleSessionName in AuthnResponse must match [a-zA-Z_0-9+=,.@-]{2,64} (service:
* AWSSecurityTokenService; status code: 400; error code: InvalidIdentityToken)".
*/
@Test
void aSessionNameAttributeOutsideItsPatternIsRejected() {
String role = createRole(true);
assume(role, assertionNamingSession(role, "has space"), PROVIDER)
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidIdentityToken"))
.body("ErrorResponse.Error.Message",
equalTo("RoleSessionName in AuthnResponse must match [a-zA-Z_0-9+=,.@-]{2,64}"));
assume(role, assertionNamingSession(role, "a".repeat(65)), PROVIDER)
.statusCode(400).body("ErrorResponse.Error.Code", equalTo("InvalidIdentityToken"));
}
@Test
void duplicateProviderCreationIsRejected() {
String metadata = SamlMetadata.forEntity(ISSUER, certificateBase64);
@@ -508,6 +567,18 @@ class AssumeRoleWithSamlValidationIntegrationTest {
return "arn:aws:iam::" + ACCOUNT + ":role/" + role;
}
private static String createRoleWithCondition(String condition) {
String role = "saml-session-" + UUID.randomUUID().toString().replace("-", "").substring(0, 12);
String trust = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Federated\":\""
+ PROVIDER + "\"},\"Action\":\"sts:AssumeRoleWithSAML\",\"Condition\":" + condition + "}]}";
given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateRole").formParam("RoleName", role)
.formParam("AssumeRolePolicyDocument", trust)
.header("Authorization", auth("iam")).when().post("/").then().statusCode(200);
ensureProviderRegistered();
return "arn:aws:iam::" + ACCOUNT + ":role/" + role;
}
private static void ensureProviderRegistered() {
if (!providerRegistered) {
registerProvider();
@@ -546,6 +617,22 @@ class AssumeRoleWithSamlValidationIntegrationTest {
private static String assertion(String role, String provider, Instant expiry, String audience,
String issuer, boolean sign, boolean unrelatedConfirmation,
Function<XMLSignatureFactory, List<Transform>> transforms) {
return assertion(role, provider, expiry, audience, issuer, sign, unrelatedConfirmation, transforms, null);
}
/** A valid signed assertion for {@code role} that names its session {@code roleSessionName}. */
private static String assertionNamingSession(String role, String roleSessionName) {
return assertion(role, PROVIDER, Instant.now().plusSeconds(300), AUDIENCE, ISSUER, true, false,
factory -> List.of(enveloped(factory)), roleSessionName);
}
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) {
String sessionNameAttribute = roleSessionName == null ? ""
: "<saml:Attribute Name=\"https://aws.amazon.com/SAML/Attributes/RoleSessionName\"><saml:AttributeValue>"
+ roleSessionName + "</saml:AttributeValue></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>"
@@ -554,7 +641,8 @@ class AssumeRoleWithSamlValidationIntegrationTest {
+ Instant.now() + "\"><saml:Issuer>" + issuer + "</saml:Issuer><saml:Subject><saml:NameID Format=\"persistent\">saml-subject</saml:NameID>"
+ extraConfirmation + "<saml:SubjectConfirmation Method=\"urn:oasis:names:tc:SAML:2.0:cm:bearer\"><saml:SubjectConfirmationData Recipient=\"https://signin.aws.amazon.com/saml\" NotOnOrAfter=\"" + expiry + "\"/></saml:SubjectConfirmation></saml:Subject>"
+ "<saml:Conditions NotBefore=\"" + Instant.now().minusSeconds(30) + "\" NotOnOrAfter=\"" + expiry + "\"><saml:AudienceRestriction><saml:Audience>" + audience + "</saml:Audience></saml:AudienceRestriction></saml:Conditions>"
+ "<saml:AttributeStatement><saml:Attribute Name=\"https://aws.amazon.com/SAML/Attributes/Role\"><saml:AttributeValue>" + role + "," + provider + "</saml:AttributeValue></saml:Attribute></saml:AttributeStatement></saml:Assertion>";
+ "<saml:AttributeStatement><saml:Attribute Name=\"https://aws.amazon.com/SAML/Attributes/Role\"><saml:AttributeValue>" + role + "," + provider + "</saml:AttributeValue></saml:Attribute>" + sessionNameAttribute
+ "</saml:AttributeStatement></saml:Assertion>";
try {
Document document = XmlParser.parseDocument(xml);
if (!sign) {
@@ -0,0 +1,73 @@
package io.floci.aws.services.iam;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The {@code sts:RoleSessionName} key of an {@code AssumeRoleWithSAML} trust policy, which holds
* the value of the assertion's {@code https://aws.amazon.com/SAML/Attributes/RoleSessionName}
* attribute, and is absent when the assertion carries none.
*/
class SAMLTrustPolicyEvaluatorTest {
private static final String PROVIDER = "arn:aws:iam::000000000000:saml-provider/corp-idp";
private static final Map<String, List<String>> CLAIMS = Map.of(
"aud", List.of("https://signin.aws.amazon.com/saml"),
"iss", List.of("https://idp.example.test/saml"),
"sub", List.of("saml-subject"));
private final SAMLTrustPolicyEvaluator evaluator = new SAMLTrustPolicyEvaluator(new ObjectMapper());
private static String policy(String condition) {
return """
{"Statement":[{"Effect":"Allow","Principal":{"Federated":"%s"},
"Action":"sts:AssumeRoleWithSAML"%s}]}""".formatted(PROVIDER,
condition == null ? "" : ",\"Condition\":" + condition);
}
private boolean allows(String policy, String roleSessionName) {
return evaluator.allows(policy, PROVIDER, CLAIMS, roleSessionName);
}
@Test
void allowsTheRoleSessionNameThePolicyRequires() {
assertTrue(allows(policy("{\"StringEquals\":{\"sts:RoleSessionName\":\"alice\"}}"), "alice"));
assertTrue(allows(policy("{\"StringLike\":{\"sts:RoleSessionName\":\"al*\"}}"), "alice"));
}
@Test
void deniesAnotherRoleSessionName() {
assertFalse(allows(policy("{\"StringEquals\":{\"sts:RoleSessionName\":\"alice\"}}"), "mallory"));
assertFalse(allows(policy("{\"StringNotEquals\":{\"sts:RoleSessionName\":\"alice\"}}"), "alice"));
}
@Test
void deniesWhenTheAssertionCarriesNoRoleSessionName() {
assertFalse(allows(policy("{\"StringEquals\":{\"sts:RoleSessionName\":\"alice\"}}"), null));
}
@Test
void roleSessionNameKeyIsCaseInsensitiveButItsValueIsNot() {
assertTrue(allows(policy("{\"StringEquals\":{\"STS:rolesessionname\":\"alice\"}}"), "alice"));
assertFalse(allows(policy("{\"StringEquals\":{\"sts:RoleSessionName\":\"Alice\"}}"), "alice"));
}
@Test
void roleSessionNameAndSubjectConditionsMustBothHold() {
String policy = policy("{\"StringEquals\":{\"saml:sub\":\"saml-subject\",\"sts:RoleSessionName\":\"alice\"}}");
assertTrue(allows(policy, "alice"));
assertFalse(allows(policy, "mallory"));
}
@Test
void aPolicyWithoutConditionIgnoresTheRoleSessionName() {
assertTrue(allows(policy(null), "alice"));
assertTrue(allows(policy(null), null));
}
}
@@ -965,7 +965,7 @@ class StsQueryHandlerTest {
OidcIssuerKeyLookup keys = mock(OidcIssuerKeyLookup.class);
when(keys.findVerificationKey(issuer)).thenReturn(Optional.of(mock(RSAPublicKey.class)));
WebIdentityTrustPolicyEvaluator trust = mock(WebIdentityTrustPolicyEvaluator.class);
when(trust.allows(eq("{}"), eq(providerArn), eq("oidc.example.com/id/ABC"), anyMap())).thenReturn(true);
when(trust.allows(eq("{}"), eq(providerArn), eq("oidc.example.com/id/ABC"), anyMap(), eq("app"))).thenReturn(true);
StsQueryHandler handler = new StsQueryHandler(iamService, mock(AccountResolver.class),
new RegionResolver(REGION, "000000000000"), config, mock(AssumeRolePolicyEvaluator.class),
@@ -980,7 +980,7 @@ class StsQueryHandlerTest {
Response response = handler.handle("AssumeRoleWithWebIdentity", params);
assertEquals(200, response.getStatus(), (String) response.getEntity());
verify(trust).allows(eq("{}"), eq(providerArn), eq("oidc.example.com/id/ABC"), anyMap());
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()));
}
@@ -55,8 +55,8 @@ class TrustPolicyStatementsTest {
String document = "{\"Version\":\"2012-10-17\",\"Statement\":[" + String.join(",", statements) + "]}";
return switch (path) {
case ASSUME_ROLE -> assumeRole.allows(document, new IamService.CallerArns(USER, USER), ACCOUNT, Map.of());
case WEB_IDENTITY -> webIdentity.allows(document, OIDC_PROVIDER, OIDC_PREFIX, Map.of());
case SAML -> saml.allows(document, SAML_PROVIDER, Map.of());
case WEB_IDENTITY -> webIdentity.allows(document, OIDC_PROVIDER, OIDC_PREFIX, Map.of(), "session");
case SAML -> saml.allows(document, SAML_PROVIDER, Map.of(), "session");
};
}
@@ -0,0 +1,139 @@
package io.floci.aws.services.iam;
import io.floci.aws.services.eks.EksOidcService;
import io.floci.aws.testing.AwsTestClients;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.Role;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.model.AssumeRoleWithWebIdentityResponse;
import software.amazon.awssdk.services.sts.model.StsException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@code sts:RoleSessionName} in an {@code AssumeRoleWithWebIdentity} trust policy, which the
* Service Authorization Reference lists for the action and which holds the {@code RoleSessionName}
* the request passes: "Your administrator might require that you specify your user name as the
* session name when you assume the role. For more information, see sts:RoleSessionName."
*/
@QuarkusTest
class WebIdentityRoleSessionNameIntegrationTest {
private static final String ACCOUNT = "000000000000";
private static final String SUBJECT = "system:serviceaccount:default:app";
@TestHTTPResource("/")
URI endpoint;
@Inject
IamService iamService;
@Inject
EksOidcService oidc;
private final List<String> sessions = new ArrayList<>();
private final List<String> roles = new ArrayList<>();
private String keyName;
private String issuer;
private String providerArn;
private IamClient iam;
private StsClient sts;
@BeforeEach
void createIssuer() {
keyName = "web-session-name-" + UUID.randomUUID();
issuer = oidc.newIssuerUrl("us-east-1");
providerArn = "arn:aws:iam::" + ACCOUNT + ":oidc-provider/" + issuer.substring("https://".length());
iam = AwsTestClients.create(IamClient.builder(), ACCOUNT, Region.US_EAST_1, endpoint);
sts = StsClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
.credentialsProvider(AnonymousCredentialsProvider.create()).build();
}
@AfterEach
void cleanUp() {
try {
for (String session : sessions) {
iamService.unregisterSession(ACCOUNT, session);
}
for (String role : roles) {
iam.deleteRole(b -> b.roleName(role));
}
oidc.deleteKey(keyName);
} finally {
try {
sts.close();
} finally {
iam.close();
}
}
}
private Role role(String condition) {
String name = "web-session-name-" + UUID.randomUUID().toString().substring(0, 8);
String trust = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Federated\":\""
+ providerArn + "\"},\"Action\":\"sts:AssumeRoleWithWebIdentity\""
+ (condition == null ? "" : ",\"Condition\":" + condition) + "}]}";
Role role = iam.createRole(b -> b.roleName(name).assumeRolePolicyDocument(trust)
.tags(tag -> tag.key("team").value("federated"))).role();
roles.add(name);
return role;
}
private AssumeRoleWithWebIdentityResponse assume(Role role, String sessionName) {
String token = oidc.mintServiceAccountToken(keyName, issuer, "default", "app", "sts.amazonaws.com", 3600);
AssumeRoleWithWebIdentityResponse response = sts.assumeRoleWithWebIdentity(b -> b.roleArn(role.arn())
.roleSessionName(sessionName).webIdentityToken(token));
sessions.add(response.credentials().accessKeyId());
return response;
}
private String sessionNameCondition(String sessionName) {
return "{\"StringEquals\":{\"" + issuer.substring("https://".length()) + ":sub\":\"" + SUBJECT
+ "\",\"sts:RoleSessionName\":\"" + sessionName + "\"}}";
}
@Test
void trustPolicyRequiringTheSessionNameAllowsTheRequestThatPassesIt() {
Role role = role(sessionNameCondition("deploy-42"));
AssumeRoleWithWebIdentityResponse response = assume(role, "deploy-42");
assertTrue(response.assumedRoleUser().arn().endsWith("/" + role.roleName() + "/deploy-42"),
response.assumedRoleUser().arn());
FederatedSessionAssertions.assertIdentity(endpoint, iamService, role, "deploy-42", response);
}
@Test
void trustPolicyRequiringTheSessionNameRefusesAnotherName() {
Role role = role(sessionNameCondition("deploy-42"));
StsException error = assertThrows(StsException.class, () -> assume(role, "deploy-43"));
assertEquals("AccessDenied", error.awsErrorDetails().errorCode());
assertEquals(403, error.statusCode());
}
@Test
void trustPolicyWithoutTheConditionAcceptsAnySessionName() {
Role role = role(null);
AssumeRoleWithWebIdentityResponse response = assume(role, "anything-goes");
FederatedSessionAssertions.assertIdentity(endpoint, iamService, role, "anything-goes", response);
}
}
@@ -17,6 +17,7 @@ class WebIdentityTrustPolicyEvaluatorTest {
private static final String NAMESPACE = "my-namespace";
private static final String SERVICE_ACCOUNT = "my-service-account";
private static final String SUBJECT = "system:serviceaccount:" + NAMESPACE + ":" + SERVICE_ACCOUNT;
private static final String SESSION_NAME = "build-42";
private final WebIdentityTrustPolicyEvaluator evaluator =
new WebIdentityTrustPolicyEvaluator(new ObjectMapper());
@@ -45,7 +46,7 @@ class WebIdentityTrustPolicyEvaluatorTest {
}
private boolean allows(String policy, Map<String, List<String>> claims) {
return evaluator.allows(policy, PROVIDER_ARN, PREFIX, claims);
return evaluator.allows(policy, PROVIDER_ARN, PREFIX, claims, SESSION_NAME);
}
@Test
@@ -87,7 +88,7 @@ class WebIdentityTrustPolicyEvaluatorTest {
String policy = irsaTrustPolicy(SUBJECT);
assertFalse(evaluator.allows(policy,
"arn:aws:iam::000000000000:oidc-provider/oidc.eks.us-east-1.amazonaws.com/id/OTHER",
PREFIX, claims(SUBJECT)));
PREFIX, claims(SUBJECT), SESSION_NAME));
}
@Test
@@ -241,4 +242,46 @@ class WebIdentityTrustPolicyEvaluatorTest {
"%s:SUB":"%s"}}}]}""".formatted(PROVIDER_ARN, PREFIX.toUpperCase(), SUBJECT);
assertTrue(allows(policy, claims(SUBJECT)));
}
/** A trust policy that pins the session name the caller passes in {@code RoleSessionName}. */
private String sessionNamePolicy(String operator, String sessionName) {
return """
{"Statement":[{"Effect":"Allow","Principal":{"Federated":"%s"},
"Action":"sts:AssumeRoleWithWebIdentity","Condition":{"%s":{
"sts:RoleSessionName":"%s"}}}]}""".formatted(PROVIDER_ARN, operator, sessionName);
}
@Test
void allowsTheRoleSessionNameThePolicyRequires() {
assertTrue(allows(sessionNamePolicy("StringEquals", SESSION_NAME), claims(SUBJECT)));
assertTrue(allows(sessionNamePolicy("StringLike", "build-*"), claims(SUBJECT)));
}
@Test
void deniesAnotherRoleSessionName() {
assertFalse(allows(sessionNamePolicy("StringEquals", "deploy-1"), claims(SUBJECT)));
assertFalse(allows(sessionNamePolicy("StringNotEquals", SESSION_NAME), claims(SUBJECT)));
}
@Test
void roleSessionNameKeyIsCaseInsensitiveButItsValueIsNot() {
String policy = """
{"Statement":[{"Effect":"Allow","Principal":{"Federated":"%s"},
"Action":"sts:AssumeRoleWithWebIdentity","Condition":{"StringEquals":{
"STS:rolesessionname":"%s"}}}]}""".formatted(PROVIDER_ARN, SESSION_NAME);
assertTrue(allows(policy, claims(SUBJECT)));
assertFalse(allows(sessionNamePolicy("StringEquals", SESSION_NAME.toUpperCase()), claims(SUBJECT)));
}
@Test
void roleSessionNameAndSubjectConditionsMustBothHold() {
String policy = """
{"Statement":[{"Effect":"Allow","Principal":{"Federated":"%s"},
"Action":"sts:AssumeRoleWithWebIdentity","Condition":{"StringEquals":{
"%s:sub":"%s","sts:RoleSessionName":"%s"}}}]}"""
.formatted(PROVIDER_ARN, PREFIX, SUBJECT, SESSION_NAME);
assertTrue(allows(policy, claims(SUBJECT)));
assertFalse(evaluator.allows(policy, PROVIDER_ARN, PREFIX, claims(SUBJECT), "other-session"));
assertFalse(allows(policy, claims("system:serviceaccount:my-namespace:other")));
}
}