mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(sts): cap chained AssumeRole sessions at one hour (#7142)
This commit is contained in:
1 parent
a74e252379
commit
42d5793d3b
6 files changed
+220
-7
No files matched your search
@@ -342,3 +342,8 @@ execution. Nonblank Authorization headers retain priority. See [signature checks
|
||||
AssumeRoleWithWebIdentity rejects a requested duration above the target role's
|
||||
`MaxSessionDuration` before issuing credentials. The default remains 3,600 seconds;
|
||||
existing token and trust-policy errors take precedence over this role-specific check.
|
||||
|
||||
Role chaining limits `AssumeRole` to one hour, including when the target role permits a longer
|
||||
session. A live role credential must carry its matching session token. `GetSessionToken` user
|
||||
credentials are not role chaining. The cap is checked after trust and role-maximum validation,
|
||||
before registering the new session.
|
||||
@@ -4480,6 +4480,17 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
.isPresent();
|
||||
}
|
||||
|
||||
/** Role chaining requires a live role credential with this request's matching issued token. */
|
||||
public boolean isRoleSession(String accessKeyId, String sessionToken) {
|
||||
return currentSession(accessKeyId)
|
||||
.filter(session -> hasMatchingSessionToken(session, sessionToken))
|
||||
.map(SessionCredential::getRoleArn)
|
||||
.filter(AwsArnUtils::isArn)
|
||||
.map(AwsArnUtils::parse)
|
||||
.filter(arn -> "iam".equals(arn.service()) && arn.resource().startsWith("role/"))
|
||||
.isPresent();
|
||||
}
|
||||
|
||||
/**
|
||||
* The session token issued alongside a temporary credential, for callers that must tell a
|
||||
* missing token apart from one that does not match.
|
||||
|
||||
@@ -184,6 +184,12 @@ public class StsQueryHandler {
|
||||
return roleDurationError;
|
||||
}
|
||||
|
||||
if (durationSeconds > 3600 && iamService.isRoleSession(callerAccessKeyId(), callerSessionToken(params))) {
|
||||
return AwsQueryResponse.error("ValidationError",
|
||||
"The requested DurationSeconds exceeds the 1 hour session limit for roles assumed by role chaining.",
|
||||
AwsNamespaces.STS, 400);
|
||||
}
|
||||
|
||||
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));
|
||||
@@ -267,16 +273,21 @@ public class StsQueryHandler {
|
||||
"role" + IamService.normalizePath(role.getPath()) + roleName);
|
||||
}
|
||||
|
||||
private String callerSessionToken(MultivaluedMap<String, String> params) {
|
||||
String token = headers == null ? null : headers.getHeaderString("X-Amz-Security-Token");
|
||||
if (token == null && params != null) {
|
||||
token = getParam(params, "X-Amz-Security-Token");
|
||||
}
|
||||
if (token == null && uriInfo != null) {
|
||||
token = uriInfo.getQueryParameters().getFirst("X-Amz-Security-Token");
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
private Response handleGetCallerIdentity(MultivaluedMap<String, String> params) {
|
||||
String accountId = regionResolver.getAccountId();
|
||||
String accessKeyId = callerAccessKeyId();
|
||||
String sessionToken = headers == null ? null : headers.getHeaderString("X-Amz-Security-Token");
|
||||
if (sessionToken == null && params != null) {
|
||||
sessionToken = getParam(params, "X-Amz-Security-Token");
|
||||
}
|
||||
if (sessionToken == null && uriInfo != null) {
|
||||
sessionToken = uriInfo.getQueryParameters().getFirst("X-Amz-Security-Token");
|
||||
}
|
||||
String sessionToken = callerSessionToken(params);
|
||||
String arn = iamService.resolveCallerArn(accessKeyId)
|
||||
.orElse(regionResolver.buildGlobalArn("iam", accountId, "root"));
|
||||
String userId = iamService.resolveCallerUserId(accessKeyId, sessionToken).orElse(accountId);
|
||||
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.github.hectorvent.floci.testing.SignedIamEnforcementProfile;
|
||||
import io.github.hectorvent.floci.testing.SignedIamUsers;
|
||||
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.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.AwsCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
|
||||
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.iam.model.Role;
|
||||
import software.amazon.awssdk.services.sts.StsClient;
|
||||
import software.amazon.awssdk.services.sts.model.AssumeRoleRequest;
|
||||
import software.amazon.awssdk.services.sts.model.Credentials;
|
||||
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.*;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(SignedIamEnforcementProfile.class)
|
||||
class AssumeRoleDurationIntegrationTest {
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
@TestHTTPResource("/")
|
||||
URI endpoint;
|
||||
@Inject
|
||||
IamService iam;
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"user,3600,7200,false", "user,7200,7200,true", "role,7200,3600,true",
|
||||
"role,7200,3601,false", "user,3600,0,true", "token,7200,7200,true",
|
||||
"user,43200,43201,false", "user,3600,900,true", "role,7200,0,true"})
|
||||
void signedDurationLimits(String callerKind, int maximum, int requested, boolean allowed) throws Exception {
|
||||
String policy = "{\"Statement\":{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"}}";
|
||||
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "duration-", "admin", policy);
|
||||
IamClient admin = IamClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
|
||||
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(
|
||||
user.accessKeyId(), user.secretAccessKey()))).build();
|
||||
StsClient issuer = client(AwsBasicCredentials.create(user.accessKeyId(), user.secretAccessKey()))) {
|
||||
Role role = admin.createRole(b -> b.roleName("duration-" + UUID.randomUUID()).path("/teams/duration/")
|
||||
.maxSessionDuration(maximum).assumeRolePolicyDocument("{\"Statement\":{\"Effect\":\"Allow\","
|
||||
+ "\"Principal\":{\"AWS\":\"" + ACCOUNT + "\"},\"Action\":\"sts:AssumeRole\"}}")).role();
|
||||
List<Credentials> sessions = new ArrayList<>();
|
||||
boolean rolePolicyCreated = false;
|
||||
try {
|
||||
admin.putRolePolicy(b -> b.roleName(role.roleName()).policyName("assume").policyDocument(policy));
|
||||
rolePolicyCreated = true;
|
||||
AwsCredentials caller = AwsBasicCredentials.create(user.accessKeyId(), user.secretAccessKey());
|
||||
if (!"user".equals(callerKind)) {
|
||||
Credentials source = "role".equals(callerKind)
|
||||
? issuer.assumeRole(b -> b.roleArn(role.arn()).roleSessionName("first")
|
||||
.durationSeconds(3600)).credentials()
|
||||
: issuer.getSessionToken(b -> b.durationSeconds(3600)).credentials();
|
||||
sessions.add(source);
|
||||
caller = AwsSessionCredentials.create(source.accessKeyId(), source.secretAccessKey(),
|
||||
source.sessionToken());
|
||||
}
|
||||
try (StsClient sts = client(caller)) {
|
||||
AssumeRoleRequest.Builder request = AssumeRoleRequest.builder().roleArn(role.arn())
|
||||
.roleSessionName("duration-check");
|
||||
if (requested != 0) {
|
||||
request.durationSeconds(requested);
|
||||
}
|
||||
Instant before = Instant.now();
|
||||
if (allowed) {
|
||||
Credentials issued = sts.assumeRole(request.build()).credentials();
|
||||
sessions.add(issued);
|
||||
int seconds = requested == 0 ? 3600 : requested;
|
||||
assertFalse(issued.expiration().isBefore(before.plusSeconds(seconds - 1)));
|
||||
assertFalse(issued.expiration().isAfter(Instant.now().plusSeconds(seconds)));
|
||||
} else {
|
||||
StsException error = assertThrows(StsException.class, () -> {
|
||||
sessions.add(sts.assumeRole(request.build()).credentials());
|
||||
});
|
||||
assertEquals("ValidationError", error.awsErrorDetails().errorCode());
|
||||
assertEquals(400, error.statusCode());
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
for (Credentials session : sessions.reversed()) {
|
||||
iam.unregisterSession(ACCOUNT, session.accessKeyId());
|
||||
assertTrue(iam.resolveCallerArns(session.accessKeyId()).isEmpty());
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
if (rolePolicyCreated) {
|
||||
admin.deleteRolePolicy(b -> b.roleName(role.roleName()).policyName("assume"));
|
||||
}
|
||||
} finally {
|
||||
admin.deleteRole(b -> b.roleName(role.roleName()));
|
||||
assertTrue(iam.findRole(ACCOUNT, role.roleName()).isEmpty());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private StsClient client(AwsCredentials credentials) {
|
||||
return StsClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
|
||||
.credentialsProvider(StaticCredentialsProvider.create(credentials)).build();
|
||||
}
|
||||
}
|
||||
@@ -92,6 +92,30 @@ class IamServiceTest {
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void roleChainingRequiresALiveTokenMatchedRoleSession() {
|
||||
MutableClock clock = new MutableClock();
|
||||
IamService service = new IamService(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new RegionResolver("cn-north-1", "000000000000"), false, clock);
|
||||
IamRole role = service.createRole("ChainRole", "/teams/chain/", "{}", null, 7200, null);
|
||||
service.registerSession("ASIACHAIN", "secret", "token", role.getArn(), clock.instant().plusSeconds(60),
|
||||
null, "000000000000");
|
||||
service.registerSession("ASIAUSER", "secret", "user-token", null, clock.instant().plusSeconds(60),
|
||||
null, "000000000000");
|
||||
service.registerSession("ASIAFEDERATED", "secret", "federated-token",
|
||||
"arn:aws-cn:sts::000000000000:federated-user/example", clock.instant().plusSeconds(60),
|
||||
null, "000000000000");
|
||||
assertTrue(service.isRoleSession("ASIACHAIN", "token"));
|
||||
assertFalse(service.isRoleSession("ASIACHAIN", "wrong"));
|
||||
assertFalse(service.isRoleSession("ASIACHAIN", null));
|
||||
assertFalse(service.isRoleSession("ASIAUSER", "user-token"));
|
||||
assertFalse(service.isRoleSession("ASIAFEDERATED", "federated-token"));
|
||||
assertFalse(service.isRoleSession("ASIAUNKNOWN", "token"));
|
||||
clock.advance(Duration.ofSeconds(60));
|
||||
assertFalse(service.isRoleSession("ASIACHAIN", "token"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPrincipalArnNamesTheRootOrTheRoleOrUserIamHoldsAtItsOwnPath() {
|
||||
iamService.createRole("reader", "/team/", "{}", null, 3600, null);
|
||||
|
||||
@@ -999,6 +999,54 @@ class StsQueryHandlerTest {
|
||||
assertEquals(expiration, sessionExpiration.getValue());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"header,3601,400", "form,3601,400", "query,3601,400",
|
||||
"empty-header,3601,200", "header,3600,200"})
|
||||
void roleChainingUsesCallerTokenPrecedenceBeforeRegistration(String tokenSource, int duration, int status) {
|
||||
IamRole role = new IamRole();
|
||||
role.setRoleName("TestRole");
|
||||
role.setArn("arn:aws:iam::000000000000:role/TestRole");
|
||||
role.setMaxSessionDuration(7200);
|
||||
IamService service = mock(IamService.class);
|
||||
when(service.findRole(anyString(), anyString())).thenReturn(Optional.of(role));
|
||||
when(service.isRoleSession("ASIACHAIN", "issued-token")).thenReturn(true);
|
||||
StsQueryHandler handler = newHandler(service, new RegionResolver(REGION, "000000000000"));
|
||||
handler.headers = mock(HttpHeaders.class);
|
||||
when(handler.headers.getHeaderString("Authorization")).thenReturn(
|
||||
"AWS4-HMAC-SHA256 Credential=ASIACHAIN/20261031/us-east-1/sts/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=unused-in-unit-test");
|
||||
handler.uriInfo = mock(UriInfo.class);
|
||||
MultivaluedMap<String, String> query = new MultivaluedHashMap<>();
|
||||
query.putSingle("X-Amz-Security-Token", "issued-token");
|
||||
when(handler.uriInfo.getQueryParameters()).thenReturn(query);
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("RoleArn", role.getArn());
|
||||
params.putSingle("RoleSessionName", "chained");
|
||||
params.putSingle("DurationSeconds", Integer.toString(duration));
|
||||
if ("header".equals(tokenSource)) {
|
||||
when(handler.headers.getHeaderString("X-Amz-Security-Token")).thenReturn("issued-token");
|
||||
params.putSingle("X-Amz-Security-Token", "wrong-form-token");
|
||||
} else if ("empty-header".equals(tokenSource)) {
|
||||
when(handler.headers.getHeaderString("X-Amz-Security-Token")).thenReturn("");
|
||||
params.putSingle("X-Amz-Security-Token", "issued-token");
|
||||
} else if ("form".equals(tokenSource)) {
|
||||
params.putSingle("X-Amz-Security-Token", "issued-token");
|
||||
query.putSingle("X-Amz-Security-Token", "wrong-query-token");
|
||||
}
|
||||
|
||||
Response response = handler.handle("AssumeRole", params);
|
||||
|
||||
assertEquals(status, response.getStatus(), response.getEntity().toString());
|
||||
if (status == 400) {
|
||||
assertTrue(response.getEntity().toString().contains("role chaining"));
|
||||
verify(service, never()).registerSession(anyString(), anyString(), anyString(), anyString(), any(),
|
||||
any(), anyString(), anyString(), anyString());
|
||||
} else {
|
||||
verify(service).registerSession(anyString(), anyString(), anyString(), eq(role.getArn()), any(),
|
||||
isNull(), eq("000000000000"), eq("chained"), anyString());
|
||||
}
|
||||
}
|
||||
|
||||
private static String extract(Pattern pattern, String body) {
|
||||
Matcher matcher = pattern.matcher(body);
|
||||
assertTrue(matcher.find(), "expected " + pattern + " in " + body);
|
||||
|
||||
Reference in new issue
Block a user