fix(sts): apply role session duration limit to AssumeRole (#7131)

This commit is contained in:
Andre Kurait authored and GitHub committed 2026-10-31 17:36:45 -04:00
1 parent 2d68edc4b7
commit cbb563f24c
4 files changed
+148 -1

No files matched your search

+5
View File
@@ -258,6 +258,11 @@ as the account root, as the key itself does.
`AssumeRole` and `AssumeRoleWithWebIdentity` require the target role to exist in IAM, returning `AccessDenied` (403)
if it does not.
`AssumeRole` rejects a `DurationSeconds` above the role's `MaxSessionDuration` with
`ValidationError` (400), after trust validation and before registering credentials. The exact
role limit is accepted; an omitted duration defaults to 3600 seconds. This role setting is
checked even when IAM policy enforcement is disabled.
When `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED=true`, `AssumeRole` also evaluates the target role's trust policy
(`AssumeRolePolicyDocument`) against the caller and returns `AccessDenied` if it is not permitted. AWS principal
forms are matched: `"*"`, an account id, an account-root ARN (`arn:aws:iam::<acct>:root`), and exact principal ARNs;
@@ -179,6 +179,11 @@ public class StsQueryHandler {
return trustDenied;
}
Response roleDurationError = validateMaxSessionDuration(durationSeconds, role);
if (roleDurationError != null) {
return roleDurationError;
}
String sessionRoleArn = canonicalRoleArn(role, accountId, roleName);
String assumedRoleArn = assumedRoleArn(sessionRoleArn, accountId, roleName, sessionName);
String roleId = (role != null && role.getRoleId() != null) ? role.getRoleId() : ("AROA" + randomId(16));
@@ -0,0 +1,83 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.testing.ValidateSignaturesProfile;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.model.AssumeRoleResponse;
import software.amazon.awssdk.services.sts.model.StsException;
import java.net.URI;
import java.time.Instant;
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.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
@QuarkusTest
@TestProfile(ValidateSignaturesProfile.class)
class StsAssumeRoleDurationIntegrationTest {
@TestHTTPResource
URI endpoint;
@Inject
IamService service;
@Test
void roleLimitUpdatesApplyToNewSessionsWithoutChangingIssuedCredentials() {
StaticCredentialsProvider credentials = StaticCredentialsProvider.create(
AwsBasicCredentials.create("test", "test"));
String name = "duration-" + UUID.randomUUID();
List<String> sessions = new ArrayList<>();
try (IamClient iam = IamClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
.credentialsProvider(credentials).build();
StsClient sts = StsClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
.credentialsProvider(credentials).build()) {
String arn = iam.createRole(request -> request.roleName(name).maxSessionDuration(7200)
.assumeRolePolicyDocument("{\"Version\":\"2012-10-17\",\"Statement\":[]}"))
.role().arn();
try {
assertRejected(sts, arn, 7201);
Instant before = Instant.now();
AssumeRoleResponse allowed = sts.assumeRole(request -> request.roleArn(arn)
.roleSessionName("boundary").durationSeconds(7200));
sessions.add(allowed.credentials().accessKeyId());
Instant after = Instant.now();
assertFalse(allowed.credentials().expiration().isBefore(before.plusSeconds(7200).minusMillis(1)));
assertFalse(allowed.credentials().expiration().isAfter(after.plusSeconds(7200).plusMillis(1)));
Instant storedExpiration = service.findSessionExpiration(
allowed.credentials().accessKeyId()).orElseThrow();
iam.updateRole(request -> request.roleName(name).maxSessionDuration(3600));
assertRejected(sts, arn, 3601);
assertEquals(storedExpiration, service.findSessionExpiration(
allowed.credentials().accessKeyId()).orElseThrow());
AssumeRoleResponse defaulted = sts.assumeRole(request -> request.roleArn(arn)
.roleSessionName("defaulted"));
sessions.add(defaulted.credentials().accessKeyId());
assertEquals(3600, iam.getRole(request -> request.roleName(name)).role().maxSessionDuration());
} finally {
sessions.forEach(key -> service.unregisterSession("000000000000", key));
iam.deleteRole(request -> request.roleName(name));
}
}
}
private static void assertRejected(StsClient sts, String arn, int duration) {
StsException error = assertThrows(StsException.class, () -> sts.assumeRole(request -> request
.roleArn(arn).roleSessionName("rejected").durationSeconds(duration)));
assertEquals(400, error.statusCode());
assertEquals("ValidationError", error.awsErrorDetails().errorCode());
assertEquals("The requested DurationSeconds exceeds the MaxSessionDuration set for this role.",
error.awsErrorDetails().errorMessage());
}
}
@@ -469,7 +469,11 @@ class StsQueryHandlerTest {
params.putSingle("RoleSessionName", "test-session");
params.putSingle("DurationSeconds", durationSeconds);
Response response = newHandler().handle("AssumeRole", params);
IamRole role = new IamRole();
role.setRoleName("TestRole");
role.setArn(params.getFirst("RoleArn"));
role.setMaxSessionDuration(43200);
Response response = newHandler(role).handle("AssumeRole", params);
assertEquals(200, response.getStatus(), (String) response.getEntity());
}
@@ -497,6 +501,56 @@ class StsQueryHandlerTest {
assertEquals(200, response.getStatus(), (String) response.getEntity());
}
@ParameterizedTest
@CsvSource({"3600,3601,400", "7200,7201,400", "3600,3600,200", "7200,7200,200",
"3600,900,200", "43200,43200,200", "3600,0,200"})
void assumeRoleDurationUsesTheRoleLimitBeforeRegistering(int maximum, int requested, int status) {
IamRole role = new IamRole();
role.setRoleName("TestRole");
role.setArn("arn:aws:iam::000000000000:role/TestRole");
role.setMaxSessionDuration(maximum);
IamService service = mock(IamService.class);
when(service.findRole(anyString(), anyString())).thenReturn(Optional.of(role));
Instant now = Instant.parse("2026-01-01T00:00:00Z");
StsQueryHandler handler = newHandler(service, new RegionResolver(REGION, "000000000000"),
Clock.fixed(now, ZoneOffset.UTC));
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("RoleArn", role.getArn());
params.putSingle("RoleSessionName", "duration");
if (requested != 0) {
params.putSingle("DurationSeconds", Integer.toString(requested));
}
Response response = handler.handle("AssumeRole", params);
String body = (String) response.getEntity();
assertEquals(status, response.getStatus(), body);
if (status == 400) {
assertTrue(body.contains("<Code>ValidationError</Code>"), body);
assertTrue(body.contains("The requested DurationSeconds exceeds the MaxSessionDuration set for this role."), body);
verify(service, never()).registerSession(anyString(), anyString(), anyString(), anyString(),
any(), any(), anyString(), anyString(), anyString());
} else {
Instant expiry = now.plusSeconds(requested == 0 ? 3600 : requested);
assertEquals(expiry.toString(), extract(EXPIRATION, body));
verify(service).registerSession(anyString(), anyString(), anyString(), eq(role.getArn()),
eq(expiry), isNull(), eq("000000000000"), eq("duration"), anyString());
}
}
@Test
void missingRoleIsDeniedBeforeItsDurationIsChecked() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("RoleArn", "arn:aws:iam::000000000000:role/MissingRole");
params.putSingle("RoleSessionName", "duration");
params.putSingle("DurationSeconds", "43200");
IamService service = mock(IamService.class);
Response response = newHandler(service, new RegionResolver(REGION, "000000000000"))
.handle("AssumeRole", params);
assertEquals(403, response.getStatus());
assertTrue(response.getEntity().toString().contains("<Code>AccessDenied</Code>"));
verify(service, never()).registerSession(anyString(), anyString(), anyString(), anyString(),
any(), any(), anyString(), anyString(), anyString());
}
@Test
void assumeRoleRejectsDurationSecondsBelowMinimum() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();