fix(sts): require long-term callers for federation tokens (#5586)

* fix(sts): require long-term callers for federation tokens

* fix(sts): preserve temporary federation caller refusals

* fix(sts): refuse temporary federation callers before dispatch
This commit is contained in:
David Phillips authored and GitHub committed 2026-10-13 18:31:06 -04:00
1 parent 5e48cbb80b
commit c907eec9d2
10 files changed
+292 -49

No files matched your search

@@ -19,7 +19,7 @@ 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")
@DisplayName("STS session and federation tokens require a long-term caller")
class StsSessionTokenCallerTest {
@ParameterizedTest
@ValueSource(strings = {"session", "federation", "role"})
@@ -62,6 +62,13 @@ class StsSessionTokenCallerTest {
assertThat(error.statusCode()).isEqualTo(403);
assertThat(error.awsErrorDetails().errorCode()).isEqualTo("AccessDenied");
});
assertThatThrownBy(() -> temporary.getFederationToken(r -> r.name("another-caller").policy(policy)))
.isInstanceOfSatisfying(StsException.class, error -> {
assertThat(error.statusCode()).isEqualTo(403);
assertThat(error.awsErrorDetails().errorCode()).isEqualTo("AccessDenied");
assertThat(error.awsErrorDetails().errorMessage())
.isEqualTo("Cannot call GetFederationToken with session credentials");
});
assertThat(temporary.getCallerIdentity().arn()).isEqualTo(identity);
}
}
+3 -1
View File
@@ -22,8 +22,10 @@
## Session Token and Federation Token Permissions
`GetSessionToken` rejects temporary callers with `AccessDenied` before issuing credentials,
`GetSessionToken` and `GetFederationToken` reject temporary callers with `AccessDenied` before issuing credentials,
including when IAM policy enforcement is disabled. Use a long-term IAM user or account key.
For an authenticated temporary caller, `GetFederationToken` returns
`Cannot call GetFederationToken with session credentials` with either enforcement setting.
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:
@@ -63,6 +63,9 @@ import java.util.regex.Pattern;
* key itself is still checked.</li>
* </ul>
*
* <p>Authenticated temporary callers of {@code sts:GetFederationToken} are refused here with
* the same operation-specific error as the handler, before policy evaluation.
*
* <p>Evaluates the caller's identity policies, optional session policy, and optional
* permissions boundary, as well as applicable resource policies via {@link ResourcePolicyProvider}.
*
@@ -365,6 +368,11 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
return; // AWS returns caller identity even when an identity policy explicitly denies it
}
if ("sts:GetFederationToken".equals(action) && IamService.isTemporaryAccessKey(akid)) {
ctx.abortWith(queryXmlAccessDenied(IamService.FEDERATION_TOKEN_SESSION_MESSAGE));
return;
}
// Service control policies from the caller's organization, when the Organizations
// service is present and SCP enforcement is enabled. Resolved lazily via Instance
// to avoid a hard IAM → Organizations dependency.
@@ -101,6 +101,9 @@ import java.util.stream.Stream;
@ApplicationScoped
public class IamService implements SessionAccountLookup, ResourceProvider {
public static final String FEDERATION_TOKEN_SESSION_MESSAGE =
"Cannot call GetFederationToken with session credentials";
private static final int ROLE_INLINE_POLICY_SIZE_LIMIT = 10_240;
private static final Logger LOG = Logger.getLogger(IamService.class);
private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
@@ -537,6 +537,10 @@ public class StsQueryHandler {
}
private Response handleGetFederationToken(MultivaluedMap<String, String> params) {
if (IamService.isTemporaryAccessKey(callerAccessKeyId())) {
return AwsQueryResponse.error("AccessDenied", IamService.FEDERATION_TOKEN_SESSION_MESSAGE,
AwsNamespaces.STS, 403);
}
Response validation = validateRequired(params, "Name");
if (validation != null) {
return validation;
@@ -1130,6 +1130,29 @@ class IamEnforcementFilterTest {
verify(containerRequest).abortWith(any());
}
@Test
void temporaryFederationCallerIsRefusedWithoutReachingTheHandler() {
ContainerRequestContext request = mock(ContainerRequestContext.class);
String auth = "AWS4-HMAC-SHA256 Credential=ASIASESSION/20261013/us-east-1/sts/aws4_request, "
+ "SignedHeaders=host, Signature=abc";
requestContext.setAccountId("000000000000");
when(accountResolver.extractAccessKeyId(auth)).thenReturn("ASIASESSION");
when(request.getHeaderString("Authorization")).thenReturn(auth);
when(request.getMediaType()).thenReturn(MediaType.APPLICATION_FORM_URLENCODED_TYPE);
when(actionRegistry.resolve("sts", request)).thenReturn("sts:GetFederationToken");
when(iamService.isKnownAccessKey("ASIASESSION")).thenReturn(true);
newFilter().filter(request);
ArgumentCaptor<Response> response = ArgumentCaptor.captor();
verify(request).abortWith(response.capture());
assertEquals(403, response.getValue().getStatus());
assertTrue(entityString(response.getValue()).contains("<Code>AccessDenied</Code>"));
assertTrue(entityString(response.getValue()).contains(
"<Message>Cannot call GetFederationToken with session credentials</Message>"));
verifyNoInteractions(evaluator);
}
@Test
void getCallerIdentityBypassesPolicyEnforcement() {
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
@@ -0,0 +1,147 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.services.iam.model.AccessKey;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.github.hectorvent.floci.testutil.StsRequests;
import io.github.hectorvent.floci.testutil.StsRequests.Credentials;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.Response;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@QuarkusTest
@TestProfile(StsFederationCallerEnforcementIntegrationTest.SignedEnforcement.class)
class StsFederationCallerEnforcementIntegrationTest {
private static final String ACCOUNT = "000000000000";
private static final String ALLOW_STS = "{\"Version\":\"2012-10-17\",\"Statement\":["
+ "{\"Effect\":\"Allow\",\"Action\":\"sts:*\",\"Resource\":\"*\"}]}";
@Inject IamService iam;
@RegisterExtension final PartitionCleanup cleanup = new PartitionCleanup();
public static class SignedEnforcement implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.auth.validate-signatures", "true", "floci.services.iam.enforcement-enabled", "true");
}
}
@ParameterizedTest
@ValueSource(strings = {"GetFederationToken", "GetSessionToken", "AssumeRole"})
void issuedTemporaryCallerKeepsExactRefusal(String issuer) throws Exception {
Credentials issued = issue(issuer);
String identity = request(issued, "GetCallerIdentity", Map.of()).then().statusCode(200)
.extract().path("GetCallerIdentityResponse.GetCallerIdentityResult.Arn");
// Even missing required fields must reach the temporary-caller refusal before parsing.
request(issued, "GetFederationToken", Map.of()).then().statusCode(403)
.body("ErrorResponse.Error.Code", equalTo("AccessDenied"))
.body("ErrorResponse.Error.Message", equalTo("Cannot call GetFederationToken with session credentials"));
request(issued, "GetCallerIdentity", Map.of()).then().statusCode(200)
.body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn", equalTo(identity));
}
@ParameterizedTest
@ValueSource(strings = {"missing", "wrong", "forged", "unknown", "expired"})
void authenticationStillPrecedesTheCallerRestriction(String mode) throws Exception {
Credentials issued = issue("GetFederationToken");
Credentials caller = switch (mode) {
case "missing" -> new Credentials(issued.key(), issued.secret(), null);
case "wrong" -> new Credentials(issued.key(), issued.secret(), "wrong");
case "forged" -> new Credentials(issued.key(), "wrong", issued.token());
case "unknown" -> new Credentials("ASIAUNKNOWN", "unknown", "unknown");
case "expired" -> {
String key = "ASIA" + UUID.randomUUID().toString().replace("-", "");
iam.registerSession(key, "expired", "token", null, Instant.EPOCH, null);
cleanup.register(() -> iam.unregisterSession(ACCOUNT, key));
yield new Credentials(key, "expired", "token");
}
default -> throw new IllegalArgumentException(mode);
};
request(caller, "GetFederationToken", Map.of("Name", "refused")).then().statusCode(403)
.body("ErrorResponse.Error.Code", equalTo("forged".equals(mode)
? "SignatureDoesNotMatch" : "InvalidClientTokenId"));
request(issued, "GetCallerIdentity", Map.of()).then().statusCode(200);
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void longTermPoliciesStillDecideIssuance(boolean allowed) throws Exception {
Credentials user = user(allowed);
Response result = request(user, "GetFederationToken", Map.of("Name", "longterm"));
if (allowed) {
remember(result, "GetFederationToken");
} else {
result.then().statusCode(403).body("ErrorResponse.Error.Code", equalTo("AccessDenied"))
.body("ErrorResponse.Error.Message", equalTo("User is not authorized to perform: sts:GetFederationToken"));
}
}
@Test
void federationSessionKeepsOtherIamAndStsRestrictions() throws Exception {
Credentials issued = issue("GetFederationToken");
request(issued, "ListUsers", Map.of()).then().statusCode(403)
.body("ErrorResponse.Error.Code", equalTo("AccessDenied"));
request(issued, "GetSessionToken", Map.of()).then().statusCode(403)
.body("ErrorResponse.Error.Code", equalTo("AccessDenied"));
request(issued, "GetCallerIdentity", Map.of()).then().statusCode(200);
}
private Credentials issue(String action) throws Exception {
Credentials user = user(true);
Map<String, String> parameters = new LinkedHashMap<>();
if ("GetFederationToken".equals(action)) {
parameters.put("Name", "federated");
parameters.put("Policy", ALLOW_STS);
} else if ("AssumeRole".equals(action)) {
String name = "fed-caller-role-" + UUID.randomUUID();
String arn = iam.createRole(name, "/", "{\"Version\":\"2012-10-17\",\"Statement\":["
+ "{\"Effect\":\"Allow\",\"Principal\":\"*\",\"Action\":\"sts:AssumeRole\"}]}", null, 3600, null).getArn();
cleanup.register(() -> iam.deleteRole(name));
parameters.put("RoleArn", arn);
parameters.put("RoleSessionName", "caller");
}
return remember(request(user, action, parameters), action);
}
private Credentials user(boolean allowed) {
String name = "fed-enforced-" + UUID.randomUUID();
iam.createUser(name, "/");
cleanup.register(() -> iam.deleteUser(name));
AccessKey key = iam.createAccessKey(name);
cleanup.register(() -> iam.deleteAccessKey(name, key.getAccessKeyId()));
if (allowed) {
iam.putUserPolicy(name, "sts", ALLOW_STS);
cleanup.register(() -> iam.deleteUserPolicy(name, "sts"));
}
return new Credentials(key.getAccessKeyId(), key.getSecretAccessKey(), null);
}
private Credentials remember(Response result, String action) {
String prefix = action + "Response." + action + "Result.Credentials.";
String key = result.xmlPath().getString(prefix + "AccessKeyId");
if (key != null) {
cleanup.register(() -> iam.unregisterSession(ACCOUNT, key));
}
result.then().statusCode(200);
assertNotNull(key);
return new Credentials(key, result.xmlPath().getString(prefix + "SecretAccessKey"),
result.xmlPath().getString(prefix + "SessionToken"));
}
private Response request(Credentials caller, String action, Map<String, String> parameters) throws Exception {
return StsRequests.request(caller, "ListUsers".equals(action) ? "iam" : "sts", action, parameters);
}
}
@@ -106,23 +106,32 @@ class StsQueryHandlerTest {
@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);
for (String action : new String[]{"GetSessionToken", "GetFederationToken"}) {
IamService service = mock(IamService.class);
StsQueryHandler handler = newHandler(service, new RegionResolver(REGION, "000000000000"));
setCaller(handler, headerKey, queryKey);
Response response = handler.handle(action, new MultivaluedHashMap<>());
assertEquals(403, response.getStatus());
assertTrue(response.getEntity().toString().contains("<Code>AccessDenied</Code>"));
assertTrue(response.getEntity().toString().contains("Cannot call " + action + " with session credentials"));
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());
for (String action : new String[]{"GetSessionToken", "GetFederationToken"}) {
StsQueryHandler handler = newHandler();
setCaller(handler, headerKey, queryKey);
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
if ("GetFederationToken".equals(action)) {
params.putSingle("Name", "caller");
}
Response response = handler.handle(action, params);
assertEquals(200, response.getStatus());
}
}
private static void setCaller(StsQueryHandler handler, String headerKey, String queryKey) {
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.testing.ValidateSignaturesProfile;
import io.github.hectorvent.floci.testutil.AwsRequestSigner;
import io.github.hectorvent.floci.testutil.StsRequests.Credentials;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.RestAssured;
@@ -14,7 +15,6 @@ 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;
@@ -22,6 +22,7 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.github.hectorvent.floci.testutil.StsRequests.request;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -63,7 +64,7 @@ class StsSessionTokenCallerIntegrationTest {
"GetSessionToken, missing", "GetFederationToken, missing", "AssumeRole, missing",
"GetSessionToken, wrong", "GetFederationToken, wrong", "AssumeRole, wrong"
})
void temporaryCallerCannotMintAnotherSessionToken(String issuer, String tokenMode) throws Exception {
void temporaryCallerCannotMintLongTermOnlyTokens(String issuer, String tokenMode) throws Exception {
Credentials user = createUser();
Map<String, String> params = new LinkedHashMap<>();
if ("GetFederationToken".equals(issuer)) {
@@ -87,21 +88,29 @@ class StsSessionTokenCallerIntegrationTest {
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);
for (String action : new String[]{"GetSessionToken", "GetFederationToken"}) {
Response result = request(caller, "sts", action, issuanceParams(action));
remember(result, action);
result.then().statusCode(403).body("ErrorResponse.Error.Code",
equalTo("valid".equals(tokenMode) ? "AccessDenied" : "InvalidClientTokenId"));
if ("valid".equals(tokenMode)) {
result.then().body("ErrorResponse.Error.Message",
equalTo("Cannot call " + action + " with session credentials"));
}
request(issued, "sts", "GetCallerIdentity", Map.of()).then().statusCode(200);
}
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void longTermCallerCanMintSessionToken(boolean user) throws Exception {
void longTermCallerCanMintBothTokenTypes(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));
for (String action : new String[]{"GetSessionToken", "GetFederationToken"}) {
Credentials issued = credentials(request(caller, "sts", action, issuanceParams(action)), action);
assertTrue(issued.key().startsWith("ASIA"));
request(issued, "sts", "GetCallerIdentity", Map.of()).then().statusCode(200)
.body("GetCallerIdentityResponse.GetCallerIdentityResult.Account", equalTo(ACCOUNT));
}
}
@ParameterizedTest
@@ -109,9 +118,13 @@ class StsSessionTokenCallerIntegrationTest {
void blankAuthorizationDoesNotHideTemporaryQueryCredentials(String authorization) throws Exception {
Credentials user = createUser();
Credentials issued = credentials(request(user, "sts", "GetSessionToken", Map.of()), "GetSessionToken");
Response result = querySessionRequest(authorization, issued);
remember(result, "GetSessionToken");
result.then().statusCode(403).body("ErrorResponse.Error.Code", equalTo("AccessDenied"));
for (String action : new String[]{"GetSessionToken", "GetFederationToken"}) {
Response result = querySessionRequest(authorization, issued, action);
remember(result, action);
result.then().statusCode(403).body("ErrorResponse.Error.Code", equalTo("AccessDenied"))
.body("ErrorResponse.Error.Message",
equalTo("Cannot call " + action + " with session credentials"));
}
}
@ParameterizedTest
@@ -120,13 +133,22 @@ class StsSessionTokenCallerIntegrationTest {
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), "GetSessionToken");
request(issued, "sts", "GetCallerIdentity", Map.of()).then().statusCode(200)
.body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn", equalTo(expected));
for (String action : new String[]{"GetSessionToken", "GetFederationToken"}) {
Credentials issued = credentials(querySessionRequest(authorization, user, action), action);
String expectedArn = "GetFederationToken".equals(action)
? "arn:aws:sts::" + ACCOUNT + ":federated-user/federated-caller" : expected;
request(issued, "sts", "GetCallerIdentity", Map.of()).then().statusCode(200)
.body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn", equalTo(expectedArn));
}
}
private Response querySessionRequest(String authorization, Credentials caller) throws Exception {
String body = "Action=GetSessionToken";
private static Map<String, String> issuanceParams(String action) {
return "GetFederationToken".equals(action) ? Map.of("Name", "federated-caller") : Map.of();
}
private Response querySessionRequest(String authorization, Credentials caller, String action) throws Exception {
String body = "Action=" + action
+ ("GetFederationToken".equals(action) ? "&Name=federated-caller" : "");
URI endpoint = URI.create("http://localhost:" + RestAssured.port + "/");
Map<String, String> query = caller.token() == null ? Map.of()
: Map.of("X-Amz-Security-Token", caller.token());
@@ -182,20 +204,4 @@ class StsSessionTokenCallerIntegrationTest {
}
}
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) {}
}
@@ -0,0 +1,34 @@
package io.github.hectorvent.floci.testutil;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
import static io.restassured.RestAssured.given;
public final class StsRequests {
private StsRequests() {}
public record Credentials(String key, String secret, String token) {}
public static 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 endpoint = 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", endpoint, extra, body.toString().getBytes(StandardCharsets.UTF_8)));
return given().headers(headers).contentType("application/x-www-form-urlencoded")
.body(body.toString()).post(endpoint);
}
}