fix(sts): preserve assumed role session identity (#4403)

* fix(sts): preserve assumed role session identity

* test(sts): cover federated caller identity round trips
This commit is contained in:
Aniket Shukla authored and GitHub committed 2026-09-25 20:29:14 -04:00
1 parent 4b15ca8950
commit cd9843f5bd
8 files changed
+186 -24

No files matched your search

+2
View File
@@ -74,5 +74,7 @@ aws sts get-session-token --endpoint-url $AWS_ENDPOINT_URL
```
`GetCallerIdentity` is commonly used in CI pipelines and integration tests as a quick connectivity check before running more complex tests.
For temporary credentials returned by an assumed-role action, its `Arn` and `UserId` match
the `AssumedRoleUser.Arn` and `AssumedRoleUser.AssumedRoleId` returned when the session was created.
When `FLOCI_SERVICES_IAM_SEED_DEPLOYER_PRINCIPAL=true`, requests signed with the seeded `floci` access key return `arn:aws:iam::000000000000:user/floci-deployer`. Other unknown local credentials continue to return the account root ARN for backward compatibility.
@@ -2181,14 +2181,14 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
/**
* Stores an assumed-role session so the enforcement filter can resolve its policies.
*/
public void registerSession(String sessionAccessKeyId, String roleArn, java.time.Instant expiration) {
public void registerSession(String sessionAccessKeyId, String roleArn, Instant expiration) {
sessions.put(sessionAccessKeyId, new SessionCredential(sessionAccessKeyId, roleArn, expiration));
}
/**
* Stores an assumed-role session with an optional inline session policy document.
*/
public void registerSession(String sessionAccessKeyId, String roleArn, java.time.Instant expiration,
public void registerSession(String sessionAccessKeyId, String roleArn, Instant expiration,
String sessionPolicyDocument) {
sessions.put(sessionAccessKeyId,
new SessionCredential(sessionAccessKeyId, roleArn, expiration, sessionPolicyDocument));
@@ -2199,13 +2199,13 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
* authentication paths use the overload that also records the session token.
*/
public void registerSession(String sessionAccessKeyId, String secretAccessKey, String roleArn,
java.time.Instant expiration, String sessionPolicyDocument) {
Instant expiration, String sessionPolicyDocument) {
registerSession(sessionAccessKeyId, secretAccessKey, null, roleArn, expiration, sessionPolicyDocument);
}
/** Stores a temporary credential including the session token required for authentication. */
public void registerSession(String sessionAccessKeyId, String secretAccessKey, String sessionToken,
String roleArn, java.time.Instant expiration, String sessionPolicyDocument) {
String roleArn, Instant expiration, String sessionPolicyDocument) {
sessions.put(sessionAccessKeyId,
new SessionCredential(sessionAccessKeyId, secretAccessKey, sessionToken, roleArn,
expiration, sessionPolicyDocument));
@@ -2217,7 +2217,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
* credentials that carry no role ARN (e.g. GetSessionToken) back to the caller's account.
*/
public void registerSession(String sessionAccessKeyId, String secretAccessKey, String roleArn,
java.time.Instant expiration, String sessionPolicyDocument,
Instant expiration, String sessionPolicyDocument,
String originAccountId) {
registerSession(sessionAccessKeyId, secretAccessKey, null, roleArn, expiration, sessionPolicyDocument,
originAccountId);
@@ -2225,16 +2225,26 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
/** Stores a temporary credential and its origin account. */
public void registerSession(String sessionAccessKeyId, String secretAccessKey, String sessionToken,
String roleArn, java.time.Instant expiration, String sessionPolicyDocument,
String roleArn, Instant expiration, String sessionPolicyDocument,
String originAccountId) {
sessions.put(sessionAccessKeyId,
new SessionCredential(sessionAccessKeyId, secretAccessKey, sessionToken, roleArn, expiration,
sessionPolicyDocument, originAccountId));
registerSession(sessionAccessKeyId, secretAccessKey, sessionToken, roleArn, expiration,
sessionPolicyDocument, originAccountId, null, null);
}
/** Stores the identity returned to the caller when STS creates an assumed-role session. */
public void registerSession(String sessionAccessKeyId, String secretAccessKey, String sessionToken,
String roleArn, Instant expiration, String sessionPolicyDocument,
String originAccountId, String roleSessionName, String assumedRoleId) {
SessionCredential session = new SessionCredential(sessionAccessKeyId, secretAccessKey, sessionToken,
roleArn, expiration, sessionPolicyDocument, originAccountId);
session.setRoleSessionName(roleSessionName);
session.setAssumedRoleId(assumedRoleId);
sessions.put(sessionAccessKeyId, session);
}
/** Stores a temporary session in an explicit account namespace. */
public void registerSessionForAccount(String accountId, String sessionAccessKeyId, String secretAccessKey,
String roleArn, java.time.Instant expiration,
String roleArn, Instant expiration,
String sessionPolicyDocument) {
registerSessionForAccount(accountId, sessionAccessKeyId, secretAccessKey, null, roleArn, expiration,
sessionPolicyDocument);
@@ -2242,7 +2252,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
/** Stores a temporary credential in an explicit account namespace. */
public void registerSessionForAccount(String accountId, String sessionAccessKeyId, String secretAccessKey,
String sessionToken, String roleArn, java.time.Instant expiration,
String sessionToken, String roleArn, Instant expiration,
String sessionPolicyDocument) {
if (accountId == null || accountId.isBlank()) {
throw new IllegalArgumentException("Session account ID must not be blank");
@@ -2439,7 +2449,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
Optional<SessionCredential> sessionOpt = findSessionForCallerContext(accessKeyId);
if (sessionOpt.isPresent()) {
SessionCredential session = sessionOpt.get();
if (session.getExpiration() != null && session.getExpiration().isBefore(java.time.Instant.now())) {
if (session.getExpiration() != null && session.getExpiration().isBefore(Instant.now())) {
deleteSession(accessKeyId, session);
return null; // expired — unknown key → bypass
}
@@ -2522,7 +2532,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
Optional<SessionCredential> sessionOpt = findSessionForCallerContext(accessKeyId);
if (sessionOpt.isPresent()) {
SessionCredential session = sessionOpt.get();
if (session.getExpiration() != null && session.getExpiration().isBefore(java.time.Instant.now())) {
if (session.getExpiration() != null && session.getExpiration().isBefore(Instant.now())) {
deleteSession(accessKeyId, session);
return Optional.empty();
}
@@ -2532,13 +2542,31 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : "UnknownRole";
String accountId = AwsArnUtils.accountOrDefault(roleArn, regionResolver.getAccountId());
String sessionName = session.getRoleSessionName();
if (sessionName == null) {
sessionName = session.getEc2InstanceId() != null
? session.getEc2InstanceId() : "floci-session";
}
return Optional.of(AwsArnUtils.Arn.of("sts", "", accountId, "assumed-role/" + roleName + "/"
+ (session.getEc2InstanceId() != null ? session.getEc2InstanceId() : "floci-session")).toString());
+ sessionName).toString());
}
return Optional.empty();
}
public Optional<String> resolveCallerUserId(String accessKeyId) {
Optional<SessionCredential> sessionOpt = findSessionForCallerContext(accessKeyId);
if (sessionOpt.isEmpty()) {
return Optional.empty();
}
SessionCredential session = sessionOpt.get();
if (session.getExpiration() != null && session.getExpiration().isBefore(Instant.now())) {
deleteSession(accessKeyId, session);
return Optional.empty();
}
return Optional.ofNullable(session.getAssumedRoleId());
}
/** Temporary credentials are the ones STS mints, distinguished by the {@code ASIA} prefix. */
public static boolean isTemporaryAccessKey(String accessKeyId) {
return accessKeyId != null && accessKeyId.startsWith(TEMPORARY_ACCESS_KEY_PREFIX);
@@ -132,7 +132,8 @@ public class StsQueryHandler {
// these temporary credentials to the assumed role's account.
String sessionPolicy = getParam(params, "Policy");
iamService.registerSession(
accessKeyId, secretKey, sessionToken, roleArn, expiration, sessionPolicy, callerAccountId);
accessKeyId, secretKey, sessionToken, roleArn, expiration, sessionPolicy, callerAccountId,
sessionName, assumedRoleId);
String result = new XmlBuilder()
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
@@ -177,8 +178,9 @@ public class StsQueryHandler {
String accessKeyId = authorization == null ? null : accountResolver.extractAccessKeyId(authorization);
String arn = iamService.resolveCallerArn(accessKeyId)
.orElse(AwsArnUtils.Arn.of("iam", "", accountId, "root").toString());
String userId = iamService.resolveCallerUserId(accessKeyId).orElse(accountId);
String result = new XmlBuilder()
.elem("UserId", accountId)
.elem("UserId", userId)
.elem("Account", accountId)
.elem("Arn", arn)
.build();
@@ -243,7 +245,8 @@ public class StsQueryHandler {
String sessionPolicy = getParam(params, "Policy");
iamService.registerSession(
accessKeyId, secretKey, sessionToken, roleArn, expiration, sessionPolicy, callerAccountId);
accessKeyId, secretKey, sessionToken, roleArn, expiration, sessionPolicy, callerAccountId,
sessionName, assumedRoleId);
String result = new XmlBuilder()
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
@@ -405,7 +408,8 @@ public class StsQueryHandler {
String assumedRoleArn = AwsArnUtils.Arn.of("sts", "", accountId, "assumed-role/" + roleName + "/" + sessionName).toString();
String assumedRoleId = "AROA" + randomId(16) + ":" + sessionName;
iamService.registerSession(accessKeyId, secretKey, sessionToken, roleArn, expiration, null, callerAccountId);
iamService.registerSession(accessKeyId, secretKey, sessionToken, roleArn, expiration, null,
callerAccountId, sessionName, assumedRoleId);
String result = new XmlBuilder()
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
.start("AssumedRoleUser").elem("Arn", assumedRoleArn).elem("AssumedRoleId", assumedRoleId).end("AssumedRoleUser")
@@ -13,6 +13,8 @@ public class SessionCredential {
private String secretAccessKey;
private String sessionToken;
private String roleArn;
private String roleSessionName;
private String assumedRoleId;
private Instant expiration;
/** Inline session policy passed to AssumeRole/GetFederationToken — further restricts role policies. */
private String sessionPolicyDocument;
@@ -86,6 +88,12 @@ public class SessionCredential {
public String getRoleArn() { return roleArn; }
public void setRoleArn(String roleArn) { this.roleArn = roleArn; }
public String getRoleSessionName() { return roleSessionName; }
public void setRoleSessionName(String roleSessionName) { this.roleSessionName = roleSessionName; }
public String getAssumedRoleId() { return assumedRoleId; }
public void setAssumedRoleId(String assumedRoleId) { this.assumedRoleId = assumedRoleId; }
public Instant getExpiration() { return expiration; }
public void setExpiration(Instant expiration) { this.expiration = expiration; }
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.eks;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
@@ -134,11 +135,10 @@ class EksIrsaEndToEndIntegrationTest {
@Test
@Order(3)
void mintedTokenAssumesRoleAndReturnsRealClaims() {
void mintedTokenAssumesRoleAndPreservesCallerIdentity() {
String token = mintToken(NAMESPACE, SERVICE_ACCOUNT, null);
assumeRole(token)
.then()
ValidatableResponse assumed = assumeRole(token).then()
.statusCode(200)
.body(containsString("<AccessKeyId>ASIA"))
.body(containsString("<SecretAccessKey>"))
@@ -148,6 +148,21 @@ class EksIrsaEndToEndIntegrationTest {
+ NAMESPACE + ":" + SERVICE_ACCOUNT + "</SubjectFromWebIdentityToken>"))
.body(containsString("<Provider>" + issuer + "</Provider>"))
.body(containsString("<Audience>sts.amazonaws.com</Audience>"));
String prefix = "AssumeRoleWithWebIdentityResponse.AssumeRoleWithWebIdentityResult.";
String accessKeyId = assumed.extract().path(prefix + "Credentials.AccessKeyId");
String sessionToken = assumed.extract().path(prefix + "Credentials.SessionToken");
String assumedRoleArn = assumed.extract().path(prefix + "AssumedRoleUser.Arn");
String assumedRoleId = assumed.extract().path(prefix + "AssumedRoleUser.AssumedRoleId");
given()
.contentType(FORM)
.formParam("Action", "GetCallerIdentity")
.header("Authorization", "AWS4-HMAC-SHA256 Credential=" + accessKeyId
+ "/20260926/us-east-1/sts/aws4_request")
.header("X-Amz-Security-Token", sessionToken)
.when().post("/").then().statusCode(200)
.body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn", equalTo(assumedRoleArn))
.body("GetCallerIdentityResponse.GetCallerIdentityResult.UserId", equalTo(assumedRoleId));
}
@Test
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
@@ -224,14 +225,29 @@ class AssumeRoleWithSamlValidationIntegrationTest {
}
@Test
void validSignedAssertionReturnsCredentialsAndSamlFields() {
void validSignedAssertionPreservesCallerIdentity() {
String role = createRole(true);
assume(role, assertion(role, PROVIDER, Instant.now().plusSeconds(300), AUDIENCE, ISSUER, true), PROVIDER)
ValidatableResponse assumed = assume(role,
assertion(role, PROVIDER, Instant.now().plusSeconds(300), AUDIENCE, ISSUER, true), PROVIDER)
.statusCode(200)
.body("AssumeRoleWithSAMLResponse.AssumeRoleWithSAMLResult.Credentials.AccessKeyId", startsWith("ASIA"))
.body("AssumeRoleWithSAMLResponse.AssumeRoleWithSAMLResult.Issuer", containsString(ISSUER))
.body("AssumeRoleWithSAMLResponse.AssumeRoleWithSAMLResult.Audience", containsString(AUDIENCE))
.body("AssumeRoleWithSAMLResponse.AssumeRoleWithSAMLResult.Subject", containsString("saml-subject"));
String prefix = "AssumeRoleWithSAMLResponse.AssumeRoleWithSAMLResult.";
String accessKeyId = assumed.extract().path(prefix + "Credentials.AccessKeyId");
String sessionToken = assumed.extract().path(prefix + "Credentials.SessionToken");
String assumedRoleArn = assumed.extract().path(prefix + "AssumedRoleUser.Arn");
String assumedRoleId = assumed.extract().path(prefix + "AssumedRoleUser.AssumedRoleId");
given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetCallerIdentity")
.header("Authorization", "AWS4-HMAC-SHA256 Credential=" + accessKeyId
+ "/20260926/us-east-1/sts/aws4_request")
.header("X-Amz-Security-Token", sessionToken)
.when().post("/").then().statusCode(200)
.body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn", equalTo(assumedRoleArn))
.body("GetCallerIdentityResponse.GetCallerIdentityResult.UserId", equalTo(assumedRoleId));
}
private static void assertSignatureInvalid(Function<XMLSignatureFactory, List<Transform>> transforms) {
@@ -255,7 +271,7 @@ class AssumeRoleWithSamlValidationIntegrationTest {
}
}
private static io.restassured.response.ValidatableResponse assume(String role, String assertion, String provider) {
private static ValidatableResponse assume(String role, String assertion, String provider) {
return given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "AssumeRoleWithSAML")
.formParam("RoleArn", role)
@@ -88,6 +88,27 @@ class IamServiceTest {
assertTrue(iamService.findSecretKey("ASIAOTHER", "other-token").isPresent());
}
@Test
void assumedRoleSessionIdentitySurvivesPersistence() throws Exception {
String accessKeyId = "ASIAASSUMEDROLESESSION";
InMemoryStorage<String, SessionCredential> sessions = new InMemoryStorage<>();
IamService service = iamService(false, new InMemoryStorage<>(), sessions);
service.registerSession(accessKeyId, "secret", "token",
"arn:aws:iam::123456789012:role/TestRole", Instant.now().plusSeconds(3600),
null, "123456789012", "my-custom-session-name",
"AROATESTROLEID:my-custom-session-name");
SessionCredential stored = sessions.get(accessKeyId).orElseThrow();
ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();
SessionCredential restored = mapper.readValue(mapper.writeValueAsBytes(stored), SessionCredential.class);
assertEquals("my-custom-session-name", restored.getRoleSessionName());
assertEquals("AROATESTROLEID:my-custom-session-name", restored.getAssumedRoleId());
sessions.put(accessKeyId, restored);
assertEquals("arn:aws:sts::123456789012:assumed-role/TestRole/my-custom-session-name",
service.resolveCallerArn(accessKeyId).orElseThrow());
assertEquals(restored.getAssumedRoleId(), service.resolveCallerUserId(accessKeyId).orElseThrow());
}
@Test
void ec2SessionMarkerSurvivesPersistenceAndExpiredCredentialsCannotAuthenticate() throws Exception {
SessionCredential expired = new SessionCredential("ASIAEXPIREDEC2", "secret", "token",
@@ -0,0 +1,68 @@
package io.github.hectorvent.floci.services.iam;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
@QuarkusTest
class StsSessionIdentityIntegrationTest {
private static final String ROLE_NAME = "sts-session-identity-role";
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/" + ROLE_NAME;
private static final String SESSION_NAME = "my-custom-session-name";
private static final String AUTHORIZATION =
"AWS4-HMAC-SHA256 Credential=test/20260925/us-east-1/iam/aws4_request";
private static final String STS_AUTHORIZATION =
"AWS4-HMAC-SHA256 Credential=test/20260925/us-east-1/sts/aws4_request";
@AfterEach
void deleteRole() {
given()
.formParam("Action", "DeleteRole")
.formParam("RoleName", ROLE_NAME)
.header("Authorization", AUTHORIZATION)
.when().post("/");
}
@Test
void callerIdentityMatchesTheAssumedRoleSession() {
given()
.formParam("Action", "CreateRole")
.formParam("RoleName", ROLE_NAME)
.formParam("AssumeRolePolicyDocument",
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Principal\":{\"AWS\":\"arn:aws:iam::000000000000:root\"},"
+ "\"Action\":\"sts:AssumeRole\"}]}")
.header("Authorization", AUTHORIZATION)
.when().post("/").then().statusCode(200);
ValidatableResponse assumed = given()
.formParam("Action", "AssumeRole")
.formParam("RoleArn", ROLE_ARN)
.formParam("RoleSessionName", SESSION_NAME)
.header("Authorization", STS_AUTHORIZATION)
.when().post("/").then().statusCode(200);
String accessKeyId = assumed.extract().path(
"AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId");
String sessionToken = assumed.extract().path(
"AssumeRoleResponse.AssumeRoleResult.Credentials.SessionToken");
String assumedRoleArn = assumed.extract().path(
"AssumeRoleResponse.AssumeRoleResult.AssumedRoleUser.Arn");
String assumedRoleId = assumed.extract().path(
"AssumeRoleResponse.AssumeRoleResult.AssumedRoleUser.AssumedRoleId");
given()
.formParam("Action", "GetCallerIdentity")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=" + accessKeyId
+ "/20260925/us-east-1/sts/aws4_request")
.header("X-Amz-Security-Token", sessionToken)
.when().post("/").then().statusCode(200)
.body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn", equalTo(assumedRoleArn))
.body("GetCallerIdentityResponse.GetCallerIdentityResult.UserId", equalTo(assumedRoleId));
}
}