mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(sts): reject session-token requests from temporary callers (#5582)
* fix(sts): reject session-token requests from temporary callers * fix(sts): retain query callers with blank authorization headers
This commit is contained in:
1 parent
b8e628356c
commit
43eacd524c
5 files changed
+344
-2
No files matched your search
+91
@@ -0,0 +1,91 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
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.services.iam.IamClient;
|
||||
import software.amazon.awssdk.services.iam.model.AccessKey;
|
||||
import software.amazon.awssdk.services.sts.StsClient;
|
||||
import software.amazon.awssdk.services.sts.model.Credentials;
|
||||
import software.amazon.awssdk.services.sts.model.StsException;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
@DisplayName("STS session tokens require a long-term caller")
|
||||
class StsSessionTokenCallerTest {
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"session", "federation", "role"})
|
||||
void rejectsTemporaryCallersWhileTheirIdentityRemainsUsable(String kind) {
|
||||
List<Runnable> cleanup = new ArrayList<>();
|
||||
try (IamClient iam = TestFixtures.iamClient()) {
|
||||
try {
|
||||
String name = TestFixtures.uniqueName("token-caller");
|
||||
iam.createUser(r -> r.userName(name));
|
||||
cleanup.add(() -> iam.deleteUser(r -> r.userName(name)));
|
||||
AccessKey key = iam.createAccessKey(r -> r.userName(name)).accessKey();
|
||||
cleanup.add(() -> iam.deleteAccessKey(r -> r.userName(name).accessKeyId(key.accessKeyId())));
|
||||
String policy = "{\"Version\":\"2012-10-17\",\"Statement\":["
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":\"sts:*\",\"Resource\":\"*\"}]}";
|
||||
iam.putUserPolicy(r -> r.userName(name).policyName("sts").policyDocument(policy));
|
||||
cleanup.add(() -> iam.deleteUserPolicy(r -> r.userName(name).policyName("sts")));
|
||||
try (StsClient caller = client(AwsBasicCredentials.create(key.accessKeyId(), key.secretAccessKey()))) {
|
||||
Credentials issued;
|
||||
if ("role".equals(kind)) {
|
||||
String arn = iam.createRole(r -> r.roleName(name).assumeRolePolicyDocument(
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Principal\":{\"AWS\":\"*\"},\"Action\":\"sts:AssumeRole\"}]}"))
|
||||
.role().arn();
|
||||
cleanup.add(() -> iam.deleteRole(r -> r.roleName(name)));
|
||||
iam.putRolePolicy(r -> r.roleName(name).policyName("sts").policyDocument(policy));
|
||||
cleanup.add(() -> iam.deleteRolePolicy(r -> r.roleName(name).policyName("sts")));
|
||||
issued = caller.assumeRole(r -> r.roleArn(arn).roleSessionName("caller")).credentials();
|
||||
} else if ("federation".equals(kind)) {
|
||||
issued = caller.getFederationToken(r -> r.name(name).policy(policy)).credentials();
|
||||
} else {
|
||||
issued = caller.getSessionToken(r -> r.durationSeconds(900)).credentials();
|
||||
}
|
||||
assertThat(issued.accessKeyId()).startsWith("ASIA");
|
||||
try (StsClient temporary = client(AwsSessionCredentials.create(
|
||||
issued.accessKeyId(), issued.secretAccessKey(), issued.sessionToken()))) {
|
||||
String identity = temporary.getCallerIdentity().arn();
|
||||
assertThat(identity).isNotBlank();
|
||||
assertThatThrownBy(() -> temporary.getSessionToken(r -> r.durationSeconds(900)))
|
||||
.isInstanceOfSatisfying(StsException.class, error -> {
|
||||
assertThat(error.statusCode()).isEqualTo(403);
|
||||
assertThat(error.awsErrorDetails().errorCode()).isEqualTo("AccessDenied");
|
||||
});
|
||||
assertThat(temporary.getCallerIdentity().arn()).isEqualTo(identity);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
RuntimeException failure = null;
|
||||
for (int i = cleanup.size() - 1; i >= 0; i--) {
|
||||
try {
|
||||
cleanup.get(i).run();
|
||||
} catch (RuntimeException problem) {
|
||||
if (failure == null) {
|
||||
failure = new IllegalStateException("STS fixture cleanup failed");
|
||||
}
|
||||
failure.addSuppressed(problem);
|
||||
}
|
||||
}
|
||||
if (failure != null) {
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static StsClient client(AwsCredentials credentials) {
|
||||
return StsClient.builder().endpointOverride(TestFixtures.endpoint()).region(TestFixtures.region())
|
||||
.credentialsProvider(StaticCredentialsProvider.create(credentials)).build();
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,9 @@
|
||||
|
||||
## Session Token and Federation Token Permissions
|
||||
|
||||
`GetSessionToken` rejects temporary callers with `AccessDenied` before issuing credentials,
|
||||
including when IAM policy enforcement is disabled. Use a long-term IAM user or account key.
|
||||
|
||||
When `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED=true`, credentials from `GetSessionToken` and `GetFederationToken`
|
||||
are evaluated as the identity whose long-term key signed the call, as on AWS:
|
||||
|
||||
|
||||
@@ -246,6 +246,10 @@ public class StsQueryHandler {
|
||||
}
|
||||
|
||||
private Response handleGetSessionToken(MultivaluedMap<String, String> params) {
|
||||
if (IamService.isTemporaryAccessKey(callerAccessKeyId())) {
|
||||
return AwsQueryResponse.error("AccessDenied", "Cannot call GetSessionToken with session credentials",
|
||||
AwsNamespaces.STS, 403);
|
||||
}
|
||||
Response durationValidation = validateDurationSeconds(params, 900, 129600);
|
||||
if (durationValidation != null) {
|
||||
return durationValidation;
|
||||
@@ -523,8 +527,9 @@ public class StsQueryHandler {
|
||||
|
||||
/** The access key that signed this request, in the header or presigned in the query. */
|
||||
private String callerAccessKeyId() {
|
||||
String authorization = headers == null ? null : headers.getHeaderString("Authorization");
|
||||
String auth = IamEnforcementFilter.requestAuthorization(
|
||||
headers == null ? null : headers.getHeaderString("Authorization"),
|
||||
authorization == null || authorization.isBlank() ? null : authorization,
|
||||
uriInfo == null ? null : uriInfo.getQueryParameters());
|
||||
return auth == null ? null : accountResolver.extractAccessKeyId(auth);
|
||||
}
|
||||
|
||||
@@ -9,9 +9,11 @@ import io.github.hectorvent.floci.core.common.WebIdentityTokenVerifier;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamRole;
|
||||
import io.github.hectorvent.floci.testing.PartitionMatrix;
|
||||
import io.github.hectorvent.floci.testing.PartitionMatrix.PartitionCase;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.core.UriInfo;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
@@ -39,6 +41,7 @@ import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class StsQueryHandlerTest {
|
||||
@@ -87,7 +90,7 @@ class StsQueryHandlerTest {
|
||||
|
||||
return new StsQueryHandler(
|
||||
iamService,
|
||||
mock(AccountResolver.class),
|
||||
new AccountResolver("000000000000"),
|
||||
regionResolver,
|
||||
config,
|
||||
mock(AssumeRolePolicyEvaluator.class),
|
||||
@@ -99,6 +102,47 @@ class StsQueryHandlerTest {
|
||||
clock);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"ASIAtemporary, AKIAlongterm", "-, ASIAtemporary", "ASIAtemporary, -",
|
||||
"blank, ASIAtemporary", "space, ASIAtemporary"})
|
||||
void temporaryHeaderOrQueryCallerIsRejectedBeforeSessionRegistration(String headerKey, String queryKey) {
|
||||
IamService service = mock(IamService.class);
|
||||
StsQueryHandler handler = newHandler(service, new RegionResolver(REGION, "000000000000"));
|
||||
setCaller(handler, headerKey, queryKey);
|
||||
Response response = handler.handle("GetSessionToken", new MultivaluedHashMap<>());
|
||||
assertEquals(403, response.getStatus());
|
||||
assertTrue(response.getEntity().toString().contains("<Code>AccessDenied</Code>"));
|
||||
verifyNoInteractions(service);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"AKIAlongterm, ASIAtemporary", "-, AKIAlongterm", "-, -",
|
||||
"blank, AKIAlongterm", "space, AKIAlongterm", "blank, -", "space, -"})
|
||||
void longTermAndAnonymousCompatibilityCallsKeepExistingIssuance(String headerKey, String queryKey) {
|
||||
StsQueryHandler handler = newHandler();
|
||||
setCaller(handler, headerKey, queryKey);
|
||||
Response response = handler.handle("GetSessionToken", new MultivaluedHashMap<>());
|
||||
assertEquals(200, response.getStatus());
|
||||
}
|
||||
|
||||
private static void setCaller(StsQueryHandler handler, String headerKey, String queryKey) {
|
||||
handler.headers = mock(HttpHeaders.class);
|
||||
if (!"-".equals(headerKey)) {
|
||||
String authorization = switch (headerKey) {
|
||||
case "blank" -> "";
|
||||
case "space" -> " ";
|
||||
default -> "AWS4-HMAC-SHA256 Credential=" + headerKey + "/20261013/us-east-1/sts/aws4_request";
|
||||
};
|
||||
when(handler.headers.getHeaderString("Authorization")).thenReturn(authorization);
|
||||
}
|
||||
handler.uriInfo = mock(UriInfo.class);
|
||||
MultivaluedMap<String, String> query = new MultivaluedHashMap<>();
|
||||
if (!"-".equals(queryKey)) {
|
||||
query.putSingle("X-Amz-Credential", queryKey + "/20261013/us-east-1/sts/aws4_request");
|
||||
}
|
||||
when(handler.uriInfo.getQueryParameters()).thenReturn(query);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSessionTokenIssuesFortyCharSecretAndTwoHundredCharToken() {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.github.hectorvent.floci.testing.ValidateSignaturesProfile;
|
||||
import io.github.hectorvent.floci.testutil.AwsRequestSigner;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.RestAssured;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(ValidateSignaturesProfile.class)
|
||||
class StsSessionTokenCallerIntegrationTest {
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final Credentials ROOT = new Credentials("test", "test", null);
|
||||
private final List<String> sessions = new ArrayList<>();
|
||||
private final List<Runnable> cleanup = new ArrayList<>();
|
||||
|
||||
@Inject
|
||||
IamService iam;
|
||||
|
||||
@AfterEach
|
||||
void cleanup() {
|
||||
sessions.forEach(key -> iam.unregisterSession(ACCOUNT, key));
|
||||
AssertionError failures = null;
|
||||
for (int i = cleanup.size() - 1; i >= 0; i--) {
|
||||
try {
|
||||
cleanup.get(i).run();
|
||||
} catch (AssertionError failure) {
|
||||
if (failures == null) {
|
||||
failures = new AssertionError("Fixture cleanup failed");
|
||||
}
|
||||
failures.addSuppressed(failure);
|
||||
}
|
||||
}
|
||||
if (failures != null) {
|
||||
throw failures;
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"GetSessionToken, valid", "GetFederationToken, valid", "AssumeRole, valid",
|
||||
"GetSessionToken, missing", "GetFederationToken, missing", "AssumeRole, missing",
|
||||
"GetSessionToken, wrong", "GetFederationToken, wrong", "AssumeRole, wrong"
|
||||
})
|
||||
void temporaryCallerCannotMintAnotherSessionToken(String issuer, String tokenMode) throws Exception {
|
||||
Credentials user = createUser();
|
||||
Map<String, String> params = new LinkedHashMap<>();
|
||||
if ("GetFederationToken".equals(issuer)) {
|
||||
params.put("Name", "caller");
|
||||
} else if ("AssumeRole".equals(issuer)) {
|
||||
String role = "token-caller-" + UUID.randomUUID();
|
||||
Response created = request(ROOT, "iam", "CreateRole", Map.of("RoleName", role,
|
||||
"AssumeRolePolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[]}"));
|
||||
created.then().statusCode(200);
|
||||
String arn = created.xmlPath().getString("CreateRoleResponse.CreateRoleResult.Role.Arn");
|
||||
assertNotNull(arn);
|
||||
cleanup.add(() -> remove("DeleteRole", Map.of("RoleName", role)));
|
||||
params.put("RoleArn", arn);
|
||||
params.put("RoleSessionName", "caller");
|
||||
}
|
||||
Credentials issued = credentials(request(user, "sts", issuer, params), issuer);
|
||||
request(issued, "sts", "GetCallerIdentity", Map.of()).then().statusCode(200)
|
||||
.body("GetCallerIdentityResponse.GetCallerIdentityResult.Account", equalTo(ACCOUNT));
|
||||
Credentials caller = switch (tokenMode) {
|
||||
case "missing" -> new Credentials(issued.key(), issued.secret(), null);
|
||||
case "wrong" -> new Credentials(issued.key(), issued.secret(), "wrong-token");
|
||||
default -> issued;
|
||||
};
|
||||
Response result = request(caller, "sts", "GetSessionToken", Map.of());
|
||||
remember(result, "GetSessionToken");
|
||||
result.then().statusCode(403).body("ErrorResponse.Error.Code",
|
||||
equalTo("valid".equals(tokenMode) ? "AccessDenied" : "InvalidClientTokenId"));
|
||||
request(issued, "sts", "GetCallerIdentity", Map.of()).then().statusCode(200);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void longTermCallerCanMintSessionToken(boolean user) throws Exception {
|
||||
Credentials caller = user ? createUser() : ROOT;
|
||||
Credentials issued = credentials(request(caller, "sts", "GetSessionToken", Map.of()), "GetSessionToken");
|
||||
assertTrue(issued.key().startsWith("ASIA"));
|
||||
request(issued, "sts", "GetCallerIdentity", Map.of()).then().statusCode(200)
|
||||
.body("GetCallerIdentityResponse.GetCallerIdentityResult.Account", equalTo(ACCOUNT));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"", " ", "absent"})
|
||||
void blankAuthorizationDoesNotHideTemporaryQueryCredentials(String authorization) throws Exception {
|
||||
Credentials user = createUser();
|
||||
Credentials issued = credentials(request(user, "sts", "GetSessionToken", Map.of()), "GetSessionToken");
|
||||
Response result = querySessionRequest(authorization, issued).post("/");
|
||||
remember(result, "GetSessionToken");
|
||||
result.then().statusCode(403).body("ErrorResponse.Error.Code", equalTo("AccessDenied"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"", " "})
|
||||
void blankAuthorizationRetainsLongTermQueryIssuerIdentity(String authorization) throws Exception {
|
||||
Credentials user = createUser();
|
||||
String expected = request(user, "sts", "GetCallerIdentity", Map.of()).then().statusCode(200)
|
||||
.extract().path("GetCallerIdentityResponse.GetCallerIdentityResult.Arn");
|
||||
Credentials issued = credentials(querySessionRequest(authorization, user).post("/"), "GetSessionToken");
|
||||
request(issued, "sts", "GetCallerIdentity", Map.of()).then().statusCode(200)
|
||||
.body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn", equalTo(expected));
|
||||
}
|
||||
|
||||
private RequestSpecification querySessionRequest(String authorization, Credentials caller) {
|
||||
RequestSpecification request = given().queryParam("X-Amz-Algorithm", "AWS4-HMAC-SHA256")
|
||||
.queryParam("X-Amz-Credential", caller.key() + "/20261013/us-east-1/sts/aws4_request")
|
||||
.contentType("application/x-www-form-urlencoded").body("Action=GetSessionToken");
|
||||
if (caller.token() != null) {
|
||||
request.queryParam("X-Amz-Security-Token", caller.token());
|
||||
}
|
||||
if (!"absent".equals(authorization)) {
|
||||
request.header("Authorization", authorization);
|
||||
}
|
||||
return request;
|
||||
}
|
||||
|
||||
private Credentials createUser() throws Exception {
|
||||
String name = "token-user-" + UUID.randomUUID();
|
||||
request(ROOT, "iam", "CreateUser", Map.of("UserName", name)).then().statusCode(200);
|
||||
cleanup.add(() -> remove("DeleteUser", Map.of("UserName", name)));
|
||||
Response created = request(ROOT, "iam", "CreateAccessKey", Map.of("UserName", name));
|
||||
created.then().statusCode(200);
|
||||
String prefix = "CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.";
|
||||
String key = created.xmlPath().getString(prefix + "AccessKeyId");
|
||||
cleanup.add(() -> remove("DeleteAccessKey", Map.of("UserName", name, "AccessKeyId", key)));
|
||||
return new Credentials(key, created.xmlPath().getString(prefix + "SecretAccessKey"), null);
|
||||
}
|
||||
|
||||
private Credentials credentials(Response response, String action) {
|
||||
remember(response, action);
|
||||
response.then().statusCode(200);
|
||||
String prefix = action + "Response." + action + "Result.Credentials.";
|
||||
Credentials result = new Credentials(response.xmlPath().getString(prefix + "AccessKeyId"),
|
||||
response.xmlPath().getString(prefix + "SecretAccessKey"),
|
||||
response.xmlPath().getString(prefix + "SessionToken"));
|
||||
assertNotNull(result.key());
|
||||
assertNotNull(result.secret());
|
||||
assertNotNull(result.token());
|
||||
return result;
|
||||
}
|
||||
|
||||
private void remember(Response response, String action) {
|
||||
if (response.statusCode() == 200) {
|
||||
String key = response.xmlPath().getString(action + "Response." + action + "Result.Credentials.AccessKeyId");
|
||||
if (key != null && !key.isEmpty()) {
|
||||
sessions.add(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void remove(String action, Map<String, String> params) {
|
||||
try {
|
||||
request(ROOT, "iam", action, params).then().statusCode(200);
|
||||
} catch (Exception e) {
|
||||
throw new AssertionError("Failed cleanup " + action, e);
|
||||
}
|
||||
}
|
||||
|
||||
private Response request(Credentials caller, String service, String action, Map<String, String> params)
|
||||
throws Exception {
|
||||
StringBuilder body = new StringBuilder("Action=").append(action);
|
||||
params.forEach((name, value) -> body.append('&').append(name).append('=')
|
||||
.append(URLEncoder.encode(value, StandardCharsets.UTF_8)));
|
||||
URI uri = URI.create("http://localhost:" + RestAssured.port + "/");
|
||||
Map<String, String> extra = caller.token() == null ? Map.of()
|
||||
: Map.of("x-amz-security-token", caller.token());
|
||||
Map<String, String> headers = new LinkedHashMap<>(extra);
|
||||
headers.putAll(AwsRequestSigner.signedAs(caller.key(), caller.secret(), service)
|
||||
.headersFor("POST", uri, extra, body.toString().getBytes(StandardCharsets.UTF_8)));
|
||||
return given().headers(headers).contentType("application/x-www-form-urlencoded")
|
||||
.body(body.toString()).post("/");
|
||||
}
|
||||
|
||||
private record Credentials(String key, String secret, String token) {}
|
||||
}
|
||||
Reference in new issue
Block a user