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

+1 -1
View File
@@ -1054,7 +1054,7 @@ When `sts:AssumeRoleWithWebIdentity` receives a token whose `iss` names an issue
- `iss` matches the cluster's issuer exactly
- `aud` contains `sts.amazonaws.com`
- `exp` / `nbf`, with 60s of clock-skew tolerance
- the role's trust policy: `Principal.Federated` and the `Condition` block, comparing `oidc:sub` / `oidc:aud` with exact, case-sensitive equality
- the role's trust policy: `Principal.Federated` and the `Condition` block, comparing `oidc:sub` / `oidc:aud` / `sts:RoleSessionName` with exact, case-sensitive equality
The response then carries the token's real claims in `SubjectFromWebIdentityToken`, `Provider`, and `Audience`. Failures return `InvalidIdentityToken` (400) for a bad token, `ExpiredTokenException` (400) for an expired one, or `AccessDenied` (403) when the trust policy does not permit the subject.
+9 -1
View File
@@ -98,6 +98,14 @@ trade-in token, and the model is what is in hand, so the blank is read as the va
SAML role sessions reject `DurationSeconds` above the target role maximum. Accepted requests retain the shorter assertion expiration.
A SAML role session is named after the assertion's `https://aws.amazon.com/SAML/Attributes/RoleSessionName`
attribute, which is also the `sts:RoleSessionName` the role's trust policy reads. A value outside
`[a-zA-Z_0-9+=,.@-]{2,64}` is refused with `InvalidIdentityToken` and the message
`RoleSessionName in AuthnResponse must match [a-zA-Z_0-9+=,.@-]{2,64}`. AWS refuses an assertion
without the attribute; Floci accepts it, names the session after the assertion's subject, and leaves
`sts:RoleSessionName` out of the request context, so a trust policy that requires a session name
refuses it.
## Privileged Root Sessions
`AssumeRoot` returns "short term credentials you can use to perform privileged tasks on a member
@@ -459,7 +467,7 @@ When the token's `iss` names a known Floci issuer, all of the following are enfo
- `iss` matches that issuer exactly
- `aud` contains `sts.amazonaws.com`
- `exp` / `nbf`, with 60s of clock-skew tolerance
- the role's trust policy: `Principal.Federated` plus the `Condition` block, comparing `<oidcProvider>:sub` and `<oidcProvider>:aud` with exact, **case-sensitive** equality (`StringEquals`, `StringNotEquals`, `StringLike`, and `StringNotLike` are supported)
- the role's trust policy: `Principal.Federated` plus the `Condition` block, comparing `<oidcProvider>:sub`, `<oidcProvider>:aud` and `sts:RoleSessionName` (the request's `RoleSessionName`) with exact, **case-sensitive** equality (`StringEquals`, `StringNotEquals`, `StringLike`, and `StringNotLike` are supported)
The response carries the token's real claims in `SubjectFromWebIdentityToken`, `Provider`, and `Audience`. A bad token returns `InvalidIdentityToken` (400), an expired one returns `ExpiredTokenException` (400), and a role that does not exist or a trust policy that does not permit the subject returns `AccessDenied` (403).
@@ -25,6 +25,7 @@ import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
/** Verifies the specific SAML assertion contract consumed by STS. */
final class SAMLAssertionVerifier {
@@ -33,14 +34,19 @@ final class SAMLAssertionVerifier {
private static final String AUDIENCE = "urn:amazon:webservices";
static final String ASSERTION_INVALID = "The SAML assertion is invalid.";
static final String SIGNATURE_INVALID = "Response signature invalid";
private static final String ROLE_SESSION_NAME = "https://aws.amazon.com/SAML/Attributes/RoleSessionName";
// 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}");
// SAML 2.0 core 5.4.4. AWS rejects any other reference transform as an invalid signature.
private static final Set<String> ALLOWED_TRANSFORMS = Set.of(
Transform.ENVELOPED, CanonicalizationMethod.EXCLUSIVE, CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS);
private SAMLAssertionVerifier() {}
/** {@code roleSessionName} is null when the assertion carries no RoleSessionName attribute. */
record Verified(String issuer, String subject, String subjectType, String nameQualifier,
Instant expiration, List<RolePair> roles) {}
Instant expiration, List<RolePair> roles, String roleSessionName) {}
record RolePair(String roleArn, String principalArn) {}
static Verified verify(String encoded, SAMLProvider provider, Instant now) throws InvalidAssertionException {
@@ -169,9 +175,10 @@ final class SAMLAssertionVerifier {
if (roles.isEmpty()) {
throw invalid("role pair missing");
}
String roleSessionName = roleSessionName(attributes);
String nameQualifier = Base64.getEncoder().encodeToString(
Digests.sha1((issuer + provider.getArn()).getBytes(StandardCharsets.UTF_8)));
return new Verified(issuer, name, subjectType, nameQualifier, notOnOrAfter, roles);
return new Verified(issuer, name, subjectType, nameQualifier, notOnOrAfter, roles, roleSessionName);
} catch (InvalidAssertionException e) {
throw e;
} catch (Exception e) {
@@ -179,6 +186,26 @@ final class SAMLAssertionVerifier {
}
}
/**
* The value of the RoleSessionName attribute, whose name is case-sensitive and which "contains
* one AttributeValue element", or null when the assertion has no such attribute.
*/
private static String roleSessionName(NodeList attributes) throws InvalidAssertionException {
for (int i = 0; i < attributes.getLength(); i++) {
Element attribute = (Element) attributes.item(i);
if (!ROLE_SESSION_NAME.equals(attribute.getAttribute("Name"))) {
continue;
}
Element value = first(attribute, SAML, "AttributeValue");
String sessionName = value == null ? "" : value.getTextContent();
if (!ROLE_SESSION_NAME_PATTERN.matcher(sessionName).matches()) {
throw new InvalidAssertionException("role session name", ROLE_SESSION_NAME_INVALID);
}
return sessionName;
}
return null;
}
private static X509Certificate certificate(String encoded) throws Exception {
byte[] der = Base64.getDecoder().decode(encoded.replaceAll("\\s+", ""));
return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(der));
@@ -13,13 +13,19 @@ import java.util.stream.StreamSupport;
/** Evaluates the federated principal and SAML action in a role trust policy. */
@ApplicationScoped
public class SAMLTrustPolicyEvaluator {
private static final String ROLE_SESSION_NAME_KEY = "sts:RoleSessionName";
private final ObjectMapper mapper;
@Inject
public SAMLTrustPolicyEvaluator(ObjectMapper mapper) {
this.mapper = mapper;
}
public boolean allows(String document, String providerArn, Map<String, List<String>> claims) {
/**
* {@code roleSessionName} is the assertion's {@code RoleSessionName} attribute, which a policy
* reads as {@code sts:RoleSessionName}, or null when the assertion carries none.
*/
public boolean allows(String document, String providerArn, Map<String, List<String>> claims,
String roleSessionName) {
try {
JsonNode statements = mapper.readTree(document).path("Statement");
if (!TrustPolicyStatements.wellFormed(statements)) {
@@ -28,7 +34,7 @@ public class SAMLTrustPolicyEvaluator {
if (statements.isArray()) {
boolean allowed = false;
for (JsonNode statement : statements) {
int result = evaluate(statement, providerArn, claims);
int result = evaluate(statement, providerArn, claims, roleSessionName);
if (result < 0) {
return false;
}
@@ -38,21 +44,23 @@ public class SAMLTrustPolicyEvaluator {
}
return allowed;
}
return statements.isObject() && evaluate(statements, providerArn, claims) > 0;
return statements.isObject() && evaluate(statements, providerArn, claims, roleSessionName) > 0;
} catch (Exception e) {
return false;
}
}
private int evaluate(JsonNode statement, String providerArn, Map<String, List<String>> claims) {
private int evaluate(JsonNode statement, String providerArn, Map<String, List<String>> claims,
String roleSessionName) {
if (!actionApplies(statement) || !principal(statement.path("Principal"), providerArn)
|| !conditionsSatisfied(statement.get("Condition"), claims)) {
|| !conditionsSatisfied(statement.get("Condition"), claims, roleSessionName)) {
return 0;
}
return TrustPolicyStatements.denies(statement) ? -1 : 1;
}
private boolean conditionsSatisfied(JsonNode condition, Map<String, List<String>> claims) {
private boolean conditionsSatisfied(JsonNode condition, Map<String, List<String>> claims,
String roleSessionName) {
if (condition == null || condition.isNull()) {
return true;
}
@@ -68,10 +76,7 @@ public class SAMLTrustPolicyEvaluator {
Iterator<Map.Entry<String, JsonNode>> entries = operator.getValue().fields();
while (entries.hasNext()) {
Map.Entry<String, JsonNode> entry = entries.next();
String key = entry.getKey();
int colon = key.indexOf(':');
String claimName = colon < 0 ? key : key.substring(colon + 1);
List<String> actual = claims.getOrDefault(claimName, List.of());
List<String> actual = conditionValues(entry.getKey(), claims, roleSessionName);
List<String> expected = entry.getValue().isArray()
? StreamSupport.stream(entry.getValue().spliterator(), false)
.filter(JsonNode::isTextual).map(JsonNode::asText).toList()
@@ -87,6 +92,16 @@ public class SAMLTrustPolicyEvaluator {
return true;
}
private static List<String> conditionValues(String key, Map<String, List<String>> claims,
String roleSessionName) {
if (ROLE_SESSION_NAME_KEY.equalsIgnoreCase(key)) {
return roleSessionName == null ? List.of() : List.of(roleSessionName);
}
int colon = key.indexOf(':');
String claimName = colon < 0 ? key : key.substring(colon + 1);
return claims.getOrDefault(claimName, List.of());
}
private boolean operatorMatches(String operator, List<String> actual, List<String> expected) {
if ("StringEquals".equals(operator)) {
return actual.stream().anyMatch(value -> expected.contains(value));
@@ -579,7 +579,8 @@ public class StsQueryHandler {
String callerAccountId = regionResolver.getAccountId();
String accountId = AwsArnUtils.accountOrDefault(roleArn, callerAccountId);
WebIdentityOutcome outcome = verifyWebIdentityToken(webIdentityToken, roleName, accountId, roleArn);
WebIdentityOutcome outcome = verifyWebIdentityToken(webIdentityToken, roleName, accountId, roleArn,
sessionName);
if (outcome.denial() != null) {
return outcome.denial();
}
@@ -666,9 +667,12 @@ public class StsQueryHandler {
}
}
/** Inspects {@code token} and decides whether it may assume {@code roleArn}. */
/**
* Inspects {@code token} and decides whether it may assume {@code roleArn} as the session
* {@code sessionName}, which the trust policy reads as {@code sts:RoleSessionName}.
*/
private WebIdentityOutcome verifyWebIdentityToken(String token, String roleName, String roleAccountId,
String roleArn) {
String roleArn, String sessionName) {
Optional<String> issuer = tokenVerifier.peekIssuer(token);
if (issuer.isEmpty()) {
return config.services().iam().enforcementEnabled()
@@ -714,7 +718,7 @@ public class StsQueryHandler {
"aud", claims.audiences());
if (!webIdentityTrustEvaluator.allows(role.get().getAssumeRolePolicyDocument(),
oidcProviderArn, issuerKeyPrefix, conditionClaims)) {
oidcProviderArn, issuerKeyPrefix, conditionClaims, sessionName)) {
LOG.debugv("Trust policy on role {0} denies web identity subject {1}",
roleArn, claims.subject());
return WebIdentityOutcome.deny(accessDenied(roleArn));
@@ -793,7 +797,7 @@ public class StsQueryHandler {
"aud", List.of(STS_AUDIENCE),
"iss", List.of(verified.issuer()),
"sub", List.of(verified.subject()),
"namequalifier", List.of(verified.nameQualifier())))) {
"namequalifier", List.of(verified.nameQualifier())), verified.roleSessionName())) {
throw new AwsException("AccessDenied", "Not authorized to perform sts:AssumeRoleWithSAML on resource: " + roleArn, 403);
}
@@ -802,9 +806,14 @@ public class StsQueryHandler {
return roleDurationError;
}
String sessionName = verified.subject().replaceAll("[^A-Za-z0-9+=,.@_-]", "_");
if (sessionName.length() > 64) {
sessionName = sessionName.substring(0, 64);
String sessionName = verified.roleSessionName();
// AWS refuses an assertion without the attribute; Floci has always accepted one, naming the
// session after its subject, and keeps doing so.
if (sessionName == null) {
sessionName = verified.subject().replaceAll("[^A-Za-z0-9+=,.@_-]", "_");
if (sessionName.length() > 64) {
sessionName = sessionName.substring(0, 64);
}
}
Instant requestedExpiration = clock.instant().plusSeconds(durationSeconds);
Instant expiration = verified.expiration().isBefore(requestedExpiration) ? verified.expiration() : requestedExpiration;
@@ -15,7 +15,7 @@ import java.util.stream.StreamSupport;
/**
* Evaluates a role's trust policy for {@code sts:AssumeRoleWithWebIdentity}, matching the
* {@code Federated} principal and the {@code Condition} block that pins an OIDC subject and
* audience.
* audience, and the session name the request passes.
*
* <p>Separate from {@link AssumeRolePolicyEvaluator} on purpose. That evaluator serves the
* {@code sts:AssumeRole} path, hardcodes that action, reads only {@code Principal.AWS}, and ignores
@@ -32,6 +32,7 @@ public class WebIdentityTrustPolicyEvaluator {
private static final Logger LOG = Logger.getLogger(WebIdentityTrustPolicyEvaluator.class);
private static final String WEB_IDENTITY_ACTION = "sts:assumerolewithwebidentity";
private static final String ROLE_SESSION_NAME_KEY = "sts:RoleSessionName";
private final ObjectMapper objectMapper;
@@ -46,11 +47,12 @@ public class WebIdentityTrustPolicyEvaluator {
*
* <p>{@code claims} holds the OIDC condition context keyed <em>without</em> the provider
* prefix — {@code sub}, {@code aud} — which this evaluator resolves against policy keys of the
* form {@code <provider-host-and-path>:sub}. An explicit {@code Deny} wins over any
* {@code Allow}, per AWS precedence.
* form {@code <provider-host-and-path>:sub}. {@code roleSessionName} is the request's
* {@code RoleSessionName}, which a policy reads as {@code sts:RoleSessionName}. An explicit
* {@code Deny} wins over any {@code Allow}, per AWS precedence.
*/
public boolean allows(String trustPolicyDocument, String oidcProviderArn, String issuerKeyPrefix,
Map<String, List<String>> claims) {
Map<String, List<String>> claims, String roleSessionName) {
if (trustPolicyDocument == null || trustPolicyDocument.isBlank()) {
return false;
}
@@ -68,7 +70,7 @@ public class WebIdentityTrustPolicyEvaluator {
boolean allow = false;
if (statements.isArray()) {
for (JsonNode stmt : statements) {
switch (evaluate(stmt, oidcProviderArn, issuerKeyPrefix, claims)) {
switch (evaluate(stmt, oidcProviderArn, issuerKeyPrefix, claims, roleSessionName)) {
case DENY -> { return false; }
case ALLOW -> allow = true;
case NO_MATCH -> { }
@@ -77,7 +79,7 @@ public class WebIdentityTrustPolicyEvaluator {
return allow;
}
if (statements.isObject()) {
return evaluate(statements, oidcProviderArn, issuerKeyPrefix, claims) == Match.ALLOW;
return evaluate(statements, oidcProviderArn, issuerKeyPrefix, claims, roleSessionName) == Match.ALLOW;
}
return false;
}
@@ -85,14 +87,14 @@ public class WebIdentityTrustPolicyEvaluator {
private enum Match { ALLOW, DENY, NO_MATCH }
private Match evaluate(JsonNode stmt, String oidcProviderArn, String issuerKeyPrefix,
Map<String, List<String>> claims) {
Map<String, List<String>> claims, String roleSessionName) {
if (!actionApplies(stmt)) {
return Match.NO_MATCH;
}
if (!matchesFederatedPrincipal(stmt.get("Principal"), oidcProviderArn)) {
return Match.NO_MATCH;
}
if (!conditionsSatisfied(stmt.get("Condition"), issuerKeyPrefix, claims)) {
if (!conditionsSatisfied(stmt.get("Condition"), issuerKeyPrefix, claims, roleSessionName)) {
return Match.NO_MATCH;
}
return TrustPolicyStatements.denies(stmt) ? Match.DENY : Match.ALLOW;
@@ -170,7 +172,7 @@ public class WebIdentityTrustPolicyEvaluator {
* using anything else does not match, which fails closed.
*/
private boolean conditionsSatisfied(JsonNode conditionNode, String issuerKeyPrefix,
Map<String, List<String>> claims) {
Map<String, List<String>> claims, String roleSessionName) {
if (conditionNode == null || conditionNode.isNull()) {
// No condition constraints — the federated principal alone is enough.
return true;
@@ -191,7 +193,7 @@ public class WebIdentityTrustPolicyEvaluator {
while (keyIterator.hasNext()) {
Map.Entry<String, JsonNode> keyEntry = keyIterator.next();
if (!keySatisfied(operator, keyEntry.getKey(), keyEntry.getValue(),
issuerKeyPrefix, claims)) {
issuerKeyPrefix, claims, roleSessionName)) {
return false;
}
}
@@ -200,8 +202,11 @@ public class WebIdentityTrustPolicyEvaluator {
}
private boolean keySatisfied(String operator, String conditionKey, JsonNode expected,
String issuerKeyPrefix, Map<String, List<String>> claims) {
List<String> actual = resolveClaim(conditionKey, issuerKeyPrefix, claims);
String issuerKeyPrefix, Map<String, List<String>> claims,
String roleSessionName) {
List<String> actual = ROLE_SESSION_NAME_KEY.equalsIgnoreCase(conditionKey)
? (roleSessionName == null ? List.of() : List.of(roleSessionName))
: resolveClaim(conditionKey, issuerKeyPrefix, claims);
List<String> expectedValues = textValues(expected);
if (expectedValues.isEmpty()) {
return false;
@@ -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")));
}
}