fix(cognito): keep the sign-in's auth_time across managed login sessions and refresh (#5157)

The tokens an authorization code redeems for were stamped with the time of
the redemption, so an authorize that a managed login session let skip the
form reported a fresh sign-in, and so did every refresh of those tokens.

The managed login session now records when the user signed in, the
authorization code carries that time (or the identity provider callback's
for federated sign-in), and the token endpoint mints with it. Refresh tokens
carry it too, so REFRESH_TOKEN_AUTH, GetTokensFromRefreshToken and the token
endpoint's refresh_token grant keep the original auth_time, as AWS
documents: "Refreshing a token doesn't reset the auth_time claim."

The sign-in time is a tagged auth_time= field after the family id, ahead of
the scope field. Refresh tokens minted before keep working and fall back to
the time they were issued.

A pre token generation trigger can no longer suppress or override auth_time,
which AWS lists among the claims a trigger cannot add, modify or suppress.
This commit is contained in:
jwoa95 authored and GitHub committed 2026-10-20 11:48:02 -04:00
1 parent 0ebcf84653
commit d1a2708634
14 files changed
+329 -98

No files matched your search

@@ -151,7 +151,7 @@ class CognitoFederationServiceTest {
}
@Test
void completeAuthorizationCarriesTheNonceAndCodeChallengeIntoTheCode() {
void completeAuthorizationCarriesTheNonceCodeChallengeAndSignInTimeIntoTheCode() {
createDefaultProvider();
String challenge = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM";
String redirect = federationService.beginAuthorization(
@@ -163,6 +163,7 @@ class CognitoFederationServiceTest {
CognitoAuthorizationCode storedCode = stateStore.consumeAuthorizationCode(authorizationCode).orElseThrow();
assertEquals("nonce-value", storedCode.nonce());
assertEquals(challenge, storedCode.codeChallenge());
assertEquals(CLOCK.instant(), storedCode.authTime(), "the user signed in when the provider sent them back");
assertFalse(redirect.contains(challenge), "the challenge stays with Cognito: " + redirect);
}
@@ -125,7 +125,7 @@ class CognitoFederationStateStoreTest {
@Test
void findSession_returnsStoredUnexpiredSessionUntilDeleted() {
CognitoFederationStateStore store = storeAt(NOW);
CognitoManagedLoginSession session = new CognitoManagedLoginSession("pool-id", "user", NOW.plusSeconds(60));
CognitoManagedLoginSession session = new CognitoManagedLoginSession("pool-id", "user", NOW, NOW.plusSeconds(60));
String sessionId = store.putSession(session);
@@ -139,7 +139,7 @@ class CognitoFederationStateStoreTest {
void findSession_expiredSessionReturnsEmptyAndIsRemoved() throws ReflectiveOperationException {
MutableClock clock = new MutableClock(NOW);
CognitoFederationStateStore store = new CognitoFederationStateStore(clock);
String sessionId = store.putSession(new CognitoManagedLoginSession("pool-id", "user", NOW.plusSeconds(60)));
String sessionId = store.putSession(new CognitoManagedLoginSession("pool-id", "user", NOW, NOW.plusSeconds(60)));
clock.set(NOW.plusSeconds(60));
@@ -159,7 +159,7 @@ class CognitoFederationStateStoreTest {
@Test
void putSession_idsAreOpaqueAndDistinct() {
CognitoFederationStateStore store = storeAt(NOW);
CognitoManagedLoginSession session = new CognitoManagedLoginSession("pool-id", "user", NOW.plusSeconds(60));
CognitoManagedLoginSession session = new CognitoManagedLoginSession("pool-id", "user", NOW, NOW.plusSeconds(60));
String first = store.putSession(session);
String second = store.putSession(session);
@@ -183,7 +183,7 @@ class CognitoFederationStateStoreTest {
private CognitoAuthorizationCode authorizationCode(Instant expiresAt) {
return new CognitoAuthorizationCode(
"pool-id", "client-id", "user-id", "https://example.com/callback", List.of("openid", "email"),
null, null, expiresAt
null, null, NOW, expiresAt
);
}
@@ -36,6 +36,7 @@ import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
@@ -1148,7 +1149,7 @@ class CognitoLambdaTriggersTest {
}
assertEquals("gold", claims.get("tier"), "claimsToAddOrOverride should add 'tier'");
assertEquals("override@example.com", claims.get("email"), "claimsToAddOrOverride should override 'email'");
assertNull(claims.get("auth_time"), "claimsToSuppress should drop 'auth_time'");
assertNotNull(claims.get("auth_time"), "a trigger cannot suppress 'auth_time'");
assertEquals(List.of("admins", "managers"), claims.get("cognito:groups"),
"groupOverrideDetails.groupsToOverride should replace cognito:groups");
}
@@ -1196,7 +1197,7 @@ class CognitoLambdaTriggersTest {
"claimsAndScopeOverrideDetails", Map.of(
"idTokenGeneration", Map.of(
"claimsToAddOrOverride", Map.of("id_only", "yes", "tier", "id-gold"),
"claimsToSuppress", List.of("auth_time")),
"claimsToSuppress", List.of("email")),
"accessTokenGeneration", Map.of(
"claimsToAddOrOverride", Map.of("access_only", "yes", "tier", "access-gold"))));
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token"), any(byte[].class), any()))
@@ -1218,12 +1219,11 @@ class CognitoLambdaTriggersTest {
assertEquals("yes", idClaims.get("id_only"));
assertEquals("id-gold", idClaims.get("tier"));
assertNull(idClaims.get("access_only"), "access-only override must not leak into id token");
assertNull(idClaims.get("auth_time"), "id-side claimsToSuppress should drop auth_time");
assertNull(idClaims.get("email"), "id-side claimsToSuppress should drop email");
assertEquals("yes", accessClaims.get("access_only"));
assertEquals("access-gold", accessClaims.get("tier"));
assertNull(accessClaims.get("id_only"), "id-only override must not leak into access token");
assertNotNull(accessClaims.get("auth_time"), "access-side did not suppress auth_time");
}
@Test
@@ -1384,7 +1384,7 @@ class CognitoLambdaTriggersTest {
"groupOverrideDetails", Map.of("groupsToOverride", List.of("admins"))))));
Map<String, Object> auth = service.generateAuthResultForHostedAuth(user, pool, client, null,
List.of("openid", "email"));
List.of("openid", "email"), Instant.now());
Map<String, Object> event;
Map<String, Object> idClaims;
@@ -1423,7 +1423,7 @@ class CognitoLambdaTriggersTest {
.thenReturn(ok(Map.of()));
service.generateAuthResultForHostedAuth(user, pool, client, null,
List.of("openid", "admin/superuser", "email"));
List.of("openid", "admin/superuser", "email"), Instant.now());
Map<String, Object> event;
try {
@@ -1445,7 +1445,7 @@ class CognitoLambdaTriggersTest {
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token"), payloadCap.capture(), any()))
.thenReturn(ok(Map.of()));
service.generateAuthResultForHostedAuth(user, pool, client, null, List.of("openid"));
service.generateAuthResultForHostedAuth(user, pool, client, null, List.of("openid"), Instant.now());
Map<String, Object> event;
try {
@@ -1470,7 +1470,7 @@ class CognitoLambdaTriggersTest {
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token"), payloadCap.capture(), any()))
.thenReturn(ok(Map.of()));
String refreshToken = (String) service.generateAuthResultForHostedAuth(user, pool, client, null,
List.of("openid", "email")).get("RefreshToken");
List.of("openid", "email"), Instant.now()).get("RefreshToken");
service.getTokensFromRefreshToken(client.getClientId(), refreshToken);
service.initiateAuth(client.getClientId(), "REFRESH_TOKEN_AUTH", Map.of("REFRESH_TOKEN", refreshToken));
@@ -1502,7 +1502,7 @@ class CognitoLambdaTriggersTest {
Map<String, Object> auth = service.generateAuthResultForHostedAuth(user, pool, client,
new CognitoService.ClaimsOverride(Map.of("nonce", "request-nonce"), null, null, null,
null, null, null, null, null), List.of("openid"));
null, null, null, null, null), List.of("openid"), Instant.now());
Map<String, Object> idClaims;
try {
@@ -1524,7 +1524,7 @@ class CognitoLambdaTriggersTest {
Map<String, Object> auth = service.generateAuthResultForHostedAuth(user, pool, client,
new CognitoService.ClaimsOverride(Map.of("nonce", "request-nonce"), null, null, null,
null, null, null, null, null), List.of("openid"));
null, null, null, null, null), List.of("openid"), Instant.now());
assertNotNull(auth.get("IdToken"));
assertNotNull(auth.get("AccessToken"));
@@ -1555,7 +1555,8 @@ class CognitoLambdaTriggersTest {
.thenReturn(ok(Map.of()));
List<String> granted = CognitoService.grantedScopes(client, List.of());
Map<String, Object> auth = service.generateAuthResultForHostedAuth(user, pool, client, null, granted);
Map<String, Object> auth = service.generateAuthResultForHostedAuth(user, pool, client, null, granted,
Instant.now());
assertEquals(List.of("openid", "email", "aws.cognito.signin.user.admin"), granted);
Map<String, Object> event;
@@ -1579,7 +1580,8 @@ class CognitoLambdaTriggersTest {
UserPoolClient client = createOAuthClient(pool, List.of("openid", "email"));
CognitoUser user = service.adminGetUser(pool.getId(), "alice");
Map<String, Object> auth = service.generateAuthResultForHostedAuth(user, pool, client, null, List.of());
Map<String, Object> auth = service.generateAuthResultForHostedAuth(user, pool, client, null, List.of(),
Instant.now());
Map<String, Object> accessClaims;
try {
@@ -1602,7 +1604,8 @@ class CognitoLambdaTriggersTest {
.thenReturn(ok(Map.of("claimsAndScopeOverrideDetails", Map.of(
"accessTokenGeneration", Map.of("scopesToSuppress", List.of("email"))))));
Map<String, Object> auth = service.generateAuthResultForHostedAuth(user, pool, client, null, List.of("email"));
Map<String, Object> auth = service.generateAuthResultForHostedAuth(user, pool, client, null, List.of("email"),
Instant.now());
Map<String, Object> accessClaims;
try {
@@ -1621,7 +1624,8 @@ class CognitoLambdaTriggersTest {
UserPoolClient client = createOAuthClient(pool, List.of("openid", "email"));
CognitoUser user = service.adminGetUser(pool.getId(), "alice");
Map<String, Object> auth = service.generateAuthResultForHostedAuth(user, pool, client, null, List.of("email"));
Map<String, Object> auth = service.generateAuthResultForHostedAuth(user, pool, client, null, List.of("email"),
Instant.now());
Map<String, Object> accessClaims;
try {
@@ -1648,7 +1652,7 @@ class CognitoLambdaTriggersTest {
"scopesToAdd", List.of("aws.cognito.signin.user.admin"))))));
Map<String, Object> auth = service.generateAuthResultForHostedAuth(user, pool, client, null,
List.of("openid", "email"));
List.of("openid", "email"), Instant.now());
Map<String, Object> accessClaims;
try {
@@ -4,12 +4,14 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import io.github.hectorvent.floci.testing.MutableClock;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.github.hectorvent.floci.testutil.SesMailbox;
import io.quarkus.test.InjectMock;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
@@ -17,6 +19,7 @@ import org.mockito.ArgumentCaptor;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Base64;
import java.util.HashSet;
import java.util.LinkedHashMap;
@@ -79,6 +82,9 @@ class CognitoManagedLoginIntegrationTest {
@InjectMock
LambdaService lambdaService;
@Inject
MutableClock clock;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
@@ -674,6 +680,50 @@ class CognitoManagedLoginIntegrationTest {
assertEquals(pool.username(), idToken.path("cognito:username").asText());
}
/**
* {@code auth_time} is when the user signed in, not when the tokens were issued: an authorize that
* the session lets skip the form ten minutes later gets new tokens with the sign-in's
* {@code auth_time}, and so does every refresh of them, as on AWS. The session takes its time from
* the clock, which the test moves on instead of waiting.
*/
@Test
void tokensFromTheSessionAndTheirRefreshKeepTheAuthTimeOfTheSignIn() throws Exception {
Pool pool = newPool();
long beforeSignIn = clock.instant().getEpochSecond();
Response signedIn = signIn(null, pool, authorizeRequest(pool.clientId()));
long afterSignIn = clock.instant().getEpochSecond();
JsonNode signInIdToken = jwtPayload(redeem(null, pool.clientId(), code(signedIn), VERIFIER)
.then().statusCode(200).extract().path("id_token"));
long authTime = signInIdToken.path("auth_time").asLong();
assertTrue(authTime >= beforeSignIn && authTime <= afterSignIn, "auth_time is the sign-in's: " + authTime);
clock.advance(Duration.ofMinutes(10));
Response again = browserGet(null, "/cognito-idp/oauth2/authorize", authorizeRequest(pool.clientId()),
signedIn.getCookie("cognito"));
Response tokens = redeem(null, pool.clientId(), code(again), VERIFIER);
tokens.then().statusCode(200);
JsonNode idToken = jwtPayload(tokens.path("id_token"));
assertNotEquals(signInIdToken.path("jti").asText(), idToken.path("jti").asText(), "new tokens were issued");
assertEquals(authTime, idToken.path("auth_time").asLong());
assertEquals(authTime, jwtPayload(tokens.path("access_token")).path("auth_time").asLong());
String refreshToken = tokens.path("refresh_token");
JsonNode viaInitiateAuth = cognitoJson("InitiateAuth", """
{"ClientId":"%s","AuthFlow":"REFRESH_TOKEN_AUTH","AuthParameters":{"REFRESH_TOKEN":"%s"}}
""".formatted(pool.clientId(), refreshToken)).path("AuthenticationResult");
JsonNode viaGetTokens = cognitoJson("GetTokensFromRefreshToken", """
{"ClientId":"%s","RefreshToken":"%s"}
""".formatted(pool.clientId(), refreshToken)).path("AuthenticationResult");
Response viaTokenEndpoint = refreshGrant(null, pool.clientId(), refreshToken);
viaTokenEndpoint.then().statusCode(200);
for (String token : List.of(viaInitiateAuth.path("IdToken").asText(),
viaInitiateAuth.path("AccessToken").asText(), viaGetTokens.path("IdToken").asText(),
viaGetTokens.path("AccessToken").asText(), viaTokenEndpoint.path("id_token"),
viaTokenEndpoint.path("access_token"))) {
assertEquals(authTime, jwtPayload(token).path("auth_time").asLong());
}
}
@Test
void sessionCookieOfAnotherPoolNeitherSignsInNorSignsOutThere() throws Exception {
Pool poolA = newPool();
@@ -243,7 +243,7 @@ class CognitoOAuthControllerTest {
void authorizeWithASessionBindsTheCodeToTheScopesGrantedThen() {
when(cognitoService.adminGetUser(POOL_ID, "session-user")).thenReturn(user("session-user"));
String sessionId = stateStore.putSession(new CognitoManagedLoginSession(POOL_ID, "session-user",
CLOCK.instant().plusSeconds(60)));
CLOCK.instant(), CLOCK.instant().plusSeconds(60)));
String withoutScope = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", null, null,
null, null, null, null, null, sessionId).getHeaderString("Location");
@@ -258,7 +258,7 @@ class CognitoOAuthControllerTest {
void authorizeWithASessionOfThePoolRedirectsWithACodeCarryingTheNonceAndChallenge() {
when(cognitoService.adminGetUser(POOL_ID, "session-user")).thenReturn(user("session-user"));
String sessionId = stateStore.putSession(new CognitoManagedLoginSession(POOL_ID, "session-user",
CLOCK.instant().plusSeconds(60)));
CLOCK.instant(), CLOCK.instant().plusSeconds(60)));
Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", "openid", "nonce",
null, "relying-party-state", RFC_7636_CHALLENGE, "S256", null, sessionId);
@@ -274,10 +274,24 @@ class CognitoOAuthControllerTest {
assertEquals(RFC_7636_CHALLENGE, storedCode.codeChallenge());
}
/** The code of an authorize that the session lets skip the form keeps when the user signed in. */
@Test
void authorizeWithASessionGivesTheCodeTheTimeTheUserSignedIn() {
when(cognitoService.adminGetUser(POOL_ID, "session-user")).thenReturn(user("session-user"));
Instant signedIn = CLOCK.instant().minusSeconds(600);
String sessionId = stateStore.putSession(new CognitoManagedLoginSession(POOL_ID, "session-user",
signedIn, signedIn.plusSeconds(3600)));
String location = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", null, null,
null, null, null, null, null, sessionId).getHeaderString("Location");
assertEquals(signedIn, storedCode(location).authTime());
}
@Test
void authorizeIgnoresASessionOfAnotherPool() {
String sessionId = stateStore.putSession(new CognitoManagedLoginSession("us-east-1_other", "session-user",
CLOCK.instant().plusSeconds(60)));
CLOCK.instant(), CLOCK.instant().plusSeconds(60)));
Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", null, null,
null, null, null, null, null, sessionId);
@@ -293,7 +307,7 @@ class CognitoOAuthControllerTest {
disabled.setEnabled(false);
when(cognitoService.adminGetUser(POOL_ID, "session-user")).thenReturn(disabled);
String sessionId = stateStore.putSession(new CognitoManagedLoginSession(POOL_ID, "session-user",
CLOCK.instant().plusSeconds(60)));
CLOCK.instant(), CLOCK.instant().plusSeconds(60)));
Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", null, null,
null, null, null, null, null, sessionId);
@@ -336,10 +350,10 @@ class CognitoOAuthControllerTest {
void tokenRedeemsAuthorizationCodeOnce() throws Exception {
String code = stateStore.putAuthorizationCode(new CognitoAuthorizationCode(
POOL_ID, CLIENT_ID, "federated-user", CALLBACK_URI, List.of("openid"), null, null,
CLOCK.instant().plusSeconds(60)));
CLOCK.instant(), CLOCK.instant().plusSeconds(60)));
when(cognitoService.describeUserPool(POOL_ID)).thenReturn(pool());
when(cognitoService.adminGetUser(POOL_ID, "federated-user")).thenReturn(user());
when(cognitoService.generateAuthResultForHostedAuth(any(CognitoUser.class), any(UserPool.class), eq(client), eq(null), any()))
when(cognitoService.generateAuthResultForHostedAuth(any(CognitoUser.class), any(UserPool.class), eq(client), eq(null), any(), any()))
.thenReturn(Map.of("AccessToken", "access-token", "IdToken", "id-token", "RefreshToken", "refresh-token",
"ExpiresIn", 3600, "TokenType", "Bearer"));
@@ -357,11 +371,30 @@ class CognitoOAuthControllerTest {
assertOAuthError(replay, "invalid_grant");
}
@Test
void tokenMintsTheTokensWithTheTimeTheCodesUserSignedIn() {
Instant signedIn = CLOCK.instant().minusSeconds(600);
String code = stateStore.putAuthorizationCode(new CognitoAuthorizationCode(
POOL_ID, CLIENT_ID, "federated-user", CALLBACK_URI, List.of("openid"), null, null,
signedIn, CLOCK.instant().plusSeconds(60)));
when(cognitoService.describeUserPool(POOL_ID)).thenReturn(pool());
when(cognitoService.adminGetUser(POOL_ID, "federated-user")).thenReturn(user());
when(cognitoService.generateAuthResultForHostedAuth(any(CognitoUser.class), any(UserPool.class), eq(client), eq(null), any(), any()))
.thenReturn(Map.of("AccessToken", "access-token", "RefreshToken", "refresh-token",
"ExpiresIn", 3600, "TokenType", "Bearer"));
Response response = controller.token(null, requestContext(null), validAuthorizationCodeForm(code));
assertEquals(200, response.getStatus());
verify(cognitoService).generateAuthResultForHostedAuth(any(CognitoUser.class), any(UserPool.class), eq(client),
eq(null), eq(List.of("openid")), eq(signedIn));
}
/** AWS leaves {@code id_token} out of the response, rather than sending it as null, without openid. */
@Test
void tokenLeavesTheIdTokenOutWhenNoneWasMinted() {
String code = putAuthorizationCode();
when(cognitoService.generateAuthResultForHostedAuth(any(CognitoUser.class), any(UserPool.class), eq(client), eq(null), any()))
when(cognitoService.generateAuthResultForHostedAuth(any(CognitoUser.class), any(UserPool.class), eq(client), eq(null), any(), any()))
.thenReturn(Map.of("AccessToken", "access-token", "RefreshToken", "refresh-token",
"ExpiresIn", 3600, "TokenType", "Bearer"));
@@ -376,7 +409,7 @@ class CognitoOAuthControllerTest {
void tokenRejectsAuthorizationCodeForAnotherClient() {
String code = stateStore.putAuthorizationCode(new CognitoAuthorizationCode(
POOL_ID, "other-client", "federated-user", CALLBACK_URI, List.of("openid"), null, null,
CLOCK.instant().plusSeconds(60)));
CLOCK.instant(), CLOCK.instant().plusSeconds(60)));
Response response = controller.token(null, requestContext(null), form("grant_type", "authorization_code",
"client_id", CLIENT_ID, "code", code, "redirect_uri", CALLBACK_URI));
@@ -506,7 +539,7 @@ class CognitoOAuthControllerTest {
void tokenPutsTheNonceInTheIdTokenOnly() {
String code = putAuthorizationCode("request-nonce", null);
ArgumentCaptor<CognitoService.ClaimsOverride> override = ArgumentCaptor.forClass(CognitoService.ClaimsOverride.class);
when(cognitoService.generateAuthResultForHostedAuth(any(CognitoUser.class), any(UserPool.class), eq(client), override.capture(), any()))
when(cognitoService.generateAuthResultForHostedAuth(any(CognitoUser.class), any(UserPool.class), eq(client), override.capture(), any(), any()))
.thenReturn(Map.of("AccessToken", "access-token", "IdToken", "id-token", "RefreshToken", "refresh-token",
"ExpiresIn", 3600, "TokenType", "Bearer"));
@@ -533,7 +566,7 @@ class CognitoOAuthControllerTest {
assertEquals(200, response.getStatus());
verify(cognitoService).generateAuthResultForHostedAuth(any(CognitoUser.class), any(UserPool.class), eq(client),
any(), scopes.capture());
any(), scopes.capture(), any());
assertEquals(List.of("openid"), scopes.getValue(), "the code's granted scopes reach the trigger");
verify(cognitoService, never()).generateAuthResult(any(CognitoUser.class), any(UserPool.class), any(), any());
}
@@ -879,10 +912,10 @@ class CognitoOAuthControllerTest {
private String putAuthorizationCode(String nonce, String codeChallenge) {
String code = stateStore.putAuthorizationCode(new CognitoAuthorizationCode(
POOL_ID, CLIENT_ID, "federated-user", CALLBACK_URI, List.of("openid"), nonce, codeChallenge,
CLOCK.instant().plusSeconds(60)));
CLOCK.instant(), CLOCK.instant().plusSeconds(60)));
when(cognitoService.describeUserPool(POOL_ID)).thenReturn(pool());
when(cognitoService.adminGetUser(POOL_ID, "federated-user")).thenReturn(user());
when(cognitoService.generateAuthResultForHostedAuth(any(CognitoUser.class), any(UserPool.class), eq(client), eq(null), any()))
when(cognitoService.generateAuthResultForHostedAuth(any(CognitoUser.class), any(UserPool.class), eq(client), eq(null), any(), any()))
.thenReturn(Map.of("AccessToken", "access-token", "IdToken", "id-token", "RefreshToken", "refresh-token",
"ExpiresIn", 3600, "TokenType", "Bearer"));
return code;
@@ -43,6 +43,7 @@ import java.lang.management.ThreadMXBean;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
@@ -631,6 +632,13 @@ class CognitoServiceTest {
null, null, List.of(), null, null);
}
/** A client of the authorization code grant, with the default explicit auth flows. */
private UserPoolClient codeGrantClient(UserPool pool) {
return service.createUserPoolClient(pool.getId(), "c", false, true, List.of("code"),
List.of("openid", "email", "aws.cognito.signin.user.admin"), null, List.of("https://app.example.test/cb"),
null, List.of(), null, null, List.of(), null, List.of(), null, null, null, List.of(), null, null);
}
@ParameterizedTest
@CsvSource({
"Short1!a",
@@ -4410,18 +4418,19 @@ class CognitoServiceTest {
}
@Test
void preTokenGenerationOverrideCannotSuppressOrReplaceIdentityClaims() {
void preTokenGenerationOverrideCannotSuppressOrReplaceProtectedClaims() {
UserPool pool = createPoolAndUser();
UserPoolClient client = service.createUserPoolClient(
pool.getId(), "c", false, false, List.of(), List.of());
CognitoUser user = service.adminGetUser(pool.getId(), "alice");
String sub = user.getAttributes().get("sub");
CognitoService.ClaimsOverride suppress = new CognitoService.ClaimsOverride(
null, List.of("sub", "cognito:username"), null, List.of("sub", "username"),
null, List.of("sub", "cognito:username", "auth_time"),
null, List.of("sub", "username", "auth_time"),
null, null, null, null, null);
CognitoService.ClaimsOverride replace = new CognitoService.ClaimsOverride(
Map.<String, Object>of("sub", "other", "cognito:username", "bob"), null,
Map.<String, Object>of("sub", "other", "username", "bob"), null,
Map.<String, Object>of("sub", "other", "cognito:username", "bob", "auth_time", 1L), null,
Map.<String, Object>of("sub", "other", "username", "bob", "auth_time", 1L), null,
null, null, null, null, null);
for (CognitoService.ClaimsOverride override : List.of(suppress, replace)) {
@@ -4434,6 +4443,8 @@ class CognitoServiceTest {
assertEquals("alice", access.get("username"));
assertEquals(sub, id.get("sub"));
assertEquals("alice", id.get("cognito:username"));
assertEquals(access.get("iat"), access.get("auth_time"));
assertEquals(id.get("iat"), id.get("auth_time"));
}
}
@@ -4724,15 +4735,17 @@ class CognitoServiceTest {
String refreshToken = (String) auth.get("RefreshToken");
assertNotNull(refreshToken);
// Should be parseable as base64 structured token: 5 payload fields + trailing HMAC signature
// Should be parseable as base64 structured token: 6 payload fields + trailing HMAC signature
String decoded = new String(Base64.getDecoder().decode(refreshToken), StandardCharsets.UTF_8);
String[] parts = decoded.split("\\|", 6);
assertEquals(6, parts.length, "Refresh token should encode 5 pipe-separated fields plus a signature");
String[] parts = decoded.split("\\|", 7);
assertEquals(7, parts.length, "Refresh token should encode 6 pipe-separated fields plus a signature");
assertEquals(pool.getId(), parts[0]);
assertEquals("alice", parts[1]);
assertEquals(client.getClientId(), parts[2]);
assertFalse(parts[3].isBlank(), "Refresh token should encode its issued-at timestamp");
assertFalse(parts[5].isBlank(), "Refresh token should encode a signature");
assertEquals("auth_time=" + Long.parseLong(parts[3]) / 1000L, parts[5],
"Refresh token should encode the user's auth_time, the issued-at second of an API sign-in");
assertFalse(parts[6].isBlank(), "Refresh token should encode a signature");
}
@Test
@@ -4763,6 +4776,84 @@ class CognitoServiceTest {
service.getTokensFromRefreshToken(client.getClientId(), "not-a-valid-refresh-token"));
}
// =========================================================================
// Issue #5146: refreshed tokens keep the auth_time of the sign-in
// =========================================================================
/**
* The tokens of an authorization code carry the time its user signed in, and AWS: "Refreshing a
* token doesn't reset the auth_time claim." Neither refresh operation does.
*/
@Test
@SuppressWarnings("unchecked")
void refreshedTokensKeepTheAuthTimeOfTheSignIn() throws Exception {
UserPool pool = createPoolAndUser();
UserPoolClient client = codeGrantClient(pool);
Instant signedIn = Instant.parse("2026-01-01T00:00:00Z");
Map<String, Object> redeemed = service.generateAuthResultForHostedAuth(service.adminGetUser(pool.getId(), "alice"),
pool, client, null, List.of("openid"), signedIn);
String refreshToken = (String) redeemed.get("RefreshToken");
Map<String, Object> viaInitiateAuth = (Map<String, Object>) service.initiateAuth(client.getClientId(),
"REFRESH_TOKEN_AUTH", Map.of("REFRESH_TOKEN", refreshToken)).get("AuthenticationResult");
Map<String, Object> viaGetTokens = (Map<String, Object>) service.getTokensFromRefreshToken(
client.getClientId(), refreshToken).get("AuthenticationResult");
for (Map<String, Object> tokens : List.of(redeemed, viaInitiateAuth, viaGetTokens)) {
assertEquals(signedIn.getEpochSecond(), authTime(tokens.get("IdToken")));
assertEquals(signedIn.getEpochSecond(), authTime(tokens.get("AccessToken")));
}
}
/**
* A code grant's refresh token minted before refresh tokens kept auth_time has the scope field
* alone, and refreshes with the time it was issued, as one of an API sign-in does.
*/
@Test
@SuppressWarnings("unchecked")
void aCodeGrantRefreshTokenWithoutAuthTimeRefreshesWithTheTimeItWasIssued() throws Exception {
UserPool pool = createPoolAndUser();
UserPoolClient client = codeGrantClient(pool);
long issuedAtMillis = System.currentTimeMillis() - 120_000L;
String scopeField = "scope=" + Base64.getUrlEncoder().withoutPadding()
.encodeToString("openid".getBytes(StandardCharsets.UTF_8));
String refreshToken = signRawRefreshToken(pool, pool.getId() + "|alice|" + client.getClientId() + "|"
+ issuedAtMillis + "|" + UUID.randomUUID() + "|" + scopeField);
for (Map<String, Object> response : List.of(
service.getTokensFromRefreshToken(client.getClientId(), refreshToken),
service.initiateAuth(client.getClientId(), "REFRESH_TOKEN_AUTH",
Map.of("REFRESH_TOKEN", refreshToken)))) {
Map<String, Object> refreshed = (Map<String, Object>) response.get("AuthenticationResult");
assertEquals(issuedAtMillis / 1000L, authTime(refreshed.get("IdToken")));
assertEquals(issuedAtMillis / 1000L, authTime(refreshed.get("AccessToken")));
}
}
/**
* Only the fields after the family id are tagged, so a username holding the auth_time tag stays a
* username, in a token with the field and in one minted before it.
*/
@Test
void aUsernameHoldingTheAuthTimeTagIsReadAsTheUsername() {
UserPool pool = createPoolAndUser();
String username = "alice|auth_time=1";
String[] withField = service.parseRefreshToken(service.buildRefreshToken(pool, username, "client-id",
1_790_000_000_123L, "family-id", null, 1_789_999_400L));
String[] withoutField = service.parseRefreshToken(signRawRefreshToken(pool,
pool.getId() + "|" + username + "|client-id|1790000000123|family-id"));
assertEquals(List.of(pool.getId(), username, "client-id", "1790000000123", "family-id", "1789999400"),
List.of(withField));
assertEquals(List.of(pool.getId(), username, "client-id", "1790000000123", "family-id", ""),
List.of(withoutField));
}
private static long authTime(Object token) throws Exception {
return MAPPER.readTree(jwtPayload((String) token)).path("auth_time").asLong();
}
// =========================================================================
// Issue #1306 — Refresh token expiry respects client token validity
// =========================================================================
@@ -4990,9 +5081,9 @@ class CognitoServiceTest {
UserPool pool = createPoolAndUser();
String[] parts = service.parseRefreshToken(service.buildRefreshToken(pool, "alice", "client-id",
1_790_000_000_123L, "family-id", List.of("openid", "notes/read|write")));
1_790_000_000_123L, "family-id", List.of("openid", "notes/read|write"), 1_789_999_400L));
assertEquals(List.of(pool.getId(), "alice", "client-id", "1790000000123", "family-id",
assertEquals(List.of(pool.getId(), "alice", "client-id", "1790000000123", "family-id", "1789999400",
"openid notes/read|write"), List.of(parts));
}
@@ -5000,21 +5091,22 @@ class CognitoServiceTest {
void refreshTokenOfACodeGrantWithoutScopesHasAnEmptyScopeField() {
UserPool pool = createPoolAndUser();
String[] parts = service.parseRefreshToken(
service.buildRefreshToken(pool, "alice", "client-id", 1_790_000_000_123L, "family-id", List.of()));
String[] parts = service.parseRefreshToken(service.buildRefreshToken(pool, "alice", "client-id",
1_790_000_000_123L, "family-id", List.of(), 1_789_999_400L));
assertEquals(6, parts.length);
assertEquals("", parts[5]);
assertEquals(7, parts.length);
assertEquals("", parts[6]);
}
@Test
void refreshTokenOfAnApiSignInHasNoScopeField() {
UserPool pool = createPoolAndUser();
String[] parts = service.parseRefreshToken(
service.buildRefreshToken(pool, "alice", "client-id", 1_790_000_000_123L, "family-id", null));
String[] parts = service.parseRefreshToken(service.buildRefreshToken(pool, "alice", "client-id",
1_790_000_000_123L, "family-id", null, 1_790_000_000L));
assertEquals(List.of(pool.getId(), "alice", "client-id", "1790000000123", "family-id"), List.of(parts));
assertEquals(List.of(pool.getId(), "alice", "client-id", "1790000000123", "family-id", "1790000000"),
List.of(parts));
}
/**
@@ -5036,23 +5128,21 @@ class CognitoServiceTest {
assertNotNull(service.getTokensFromRefreshToken(client.getClientId(), refreshToken).get("AuthenticationResult"));
assertNotNull(service.initiateAuth(client.getClientId(), "REFRESH_TOKEN_AUTH",
Map.of("REFRESH_TOKEN", refreshToken)).get("AuthenticationResult"));
assertEquals(List.of(pool.getId(), "pipe|user", "client-id", "1790000000123", "family-id", "openid"),
List.of(service.parseRefreshToken(service.buildRefreshToken(pool, "pipe|user", "client-id",
1_790_000_000_123L, "family-id", List.of("openid")))));
assertEquals(List.of(pool.getId(), "pipe|user", "client-id", "1790000000123", "family-id", "1789999400",
"openid"), List.of(service.parseRefreshToken(service.buildRefreshToken(pool, "pipe|user", "client-id",
1_790_000_000_123L, "family-id", List.of("openid"), 1_789_999_400L))));
}
@Test
@SuppressWarnings("unchecked")
void getTokensFromRefreshTokenOfACodeGrantKeepsItsScopesAndIssuesAnIdTokenOnlyWithOpenid() throws Exception {
UserPool pool = createPoolAndUser();
UserPoolClient client = service.createUserPoolClient(pool.getId(), "c", false, true, List.of("code"),
List.of("openid", "email", "aws.cognito.signin.user.admin"), null, List.of("https://app.example.test/cb"),
null, List.of(), null, null, List.of(), null, List.of(), null, null, null, List.of(), null, null);
UserPoolClient client = codeGrantClient(pool);
CognitoUser user = service.adminGetUser(pool.getId(), "alice");
for (List<String> granted : List.of(List.of("openid", "email"), List.of("email"))) {
String refreshToken = (String) service.generateAuthResultForHostedAuth(user, pool, client, null, granted)
.get("RefreshToken");
String refreshToken = (String) service.generateAuthResultForHostedAuth(user, pool, client, null, granted,
Instant.now()).get("RefreshToken");
Map<String, Object> refreshed = (Map<String, Object>) service
.getTokensFromRefreshToken(client.getClientId(), refreshToken).get("AuthenticationResult");
@@ -5071,8 +5161,8 @@ class CognitoServiceTest {
UserPool pool = createPoolAndUser();
UserPoolClient client = service.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());
CognitoUser user = service.adminGetUser(pool.getId(), "alice");
String refreshToken = (String) service.generateAuthResultForHostedAuth(user, pool, client, null, List.of())
.get("RefreshToken");
String refreshToken = (String) service.generateAuthResultForHostedAuth(user, pool, client, null, List.of(),
Instant.now()).get("RefreshToken");
Map<String, Object> refreshed = (Map<String, Object>) service
.getTokensFromRefreshToken(client.getClientId(), refreshToken).get("AuthenticationResult");