From d1a2708634c1f187a45ab99e08561a11b74bb2bb Mon Sep 17 00:00:00 2001 From: jwoa95 <88512616+jwoa95@users.noreply.github.com> Date: Tue, 20 Oct 2026 16:48:02 +0100 Subject: [PATCH] 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. --- docs/services/cognito.md | 14 +- .../cognito/CognitoAuthFlowHandler.java | 2 +- .../cognito/CognitoFederationService.java | 3 +- .../cognito/CognitoManagedLoginService.java | 10 +- .../cognito/CognitoOAuthController.java | 2 +- .../services/cognito/CognitoService.java | 90 +++++++---- .../model/CognitoAuthorizationCode.java | 5 +- .../model/CognitoManagedLoginSession.java | 5 +- .../cognito/CognitoFederationServiceTest.java | 3 +- .../CognitoFederationStateStoreTest.java | 8 +- .../cognito/CognitoLambdaTriggersTest.java | 34 +++-- .../CognitoManagedLoginIntegrationTest.java | 50 ++++++ .../cognito/CognitoOAuthControllerTest.java | 57 +++++-- .../services/cognito/CognitoServiceTest.java | 144 ++++++++++++++---- 14 files changed, 329 insertions(+), 98 deletions(-) diff --git a/docs/services/cognito.md b/docs/services/cognito.md index 42964dc13c..4ad06befa6 100644 --- a/docs/services/cognito.md +++ b/docs/services/cognito.md @@ -713,7 +713,8 @@ the callback in `CallbackURLs`. No domain is needed; on a custom domain the same 1. `GET /cognito-idp/oauth2/authorize` redirects to `/cognito-idp/login` with the request's parameters, `login_hint` included. If the browser already has a managed login session in the - pool, it skips the form and redirects straight to the callback with a code, as AWS does. A + pool, it skips the form and redirects straight to the callback with a code, as AWS does; the + code's tokens carry the `auth_time` of the session's sign-in, not of this request. A `scope` the client's `AllowedOAuthScopes` does not include is refused first, as on AWS, with a redirect to the callback carrying `error=invalid_request`, `error_description=invalid_scope` and the `state`. @@ -878,9 +879,16 @@ Floci mirrors AWS's access-token / ID-token split: - **ID token:** `sub`, `cognito:username`, `aud`, and readable user attributes (`email`, `email_verified`, `phone_number`, `custom:*`, ...). Attribute claims are filtered by the app client's `ReadAttributes` (an unset/empty list means all attributes are readable). +- **Both tokens:** `auth_time` is when the user signed in, as on AWS. Tokens from an authorization + code carry the time the user signed in at the login page or the identity provider, also when a + managed login session skipped the form, and tokens from `REFRESH_TOKEN_AUTH`, + `GetTokensFromRefreshToken` or the token endpoint's `refresh_token` grant keep the `auth_time` of + the sign-in that issued the refresh token. A + refresh token issued by an older Floci does not carry its sign-in time, so its tokens get the time + it was issued. -As on AWS, a pre token generation trigger cannot suppress or override `sub`, the access token's -`username` or the ID token's `cognito:username`; Floci ignores those entries in its response. +As on AWS, a pre token generation trigger cannot suppress or override `sub`, `auth_time`, the access +token's `username` or the ID token's `cognito:username`; Floci ignores those entries in its response. Not-found errors (`ResourceNotFoundException`, `UserNotFoundException`) return HTTP `400`, matching the Cognito JSON protocol. diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java index 2da7c8b604..11516a1a7f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java @@ -712,7 +712,7 @@ final class CognitoAuthFlowHandler { clientMetadata, "TokenGeneration_RefreshTokens", scopes); Map result = new HashMap<>(); result.put("AuthenticationResult", service.accessAndIdTokens(user, pool, client, override, refreshTokenUuid, - scopes, iat / 1000L)); + scopes, CognitoService.refreshTokenAuthTime(parts, iat))); return result; } diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoFederationService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoFederationService.java index 2b7782577f..0961c80eb2 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoFederationService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoFederationService.java @@ -95,10 +95,11 @@ public class CognitoFederationService { String issuer = optionalText(claims, "iss"); CognitoUser user = cognitoService.provisionFederatedUser(transaction.userPoolId(), provider, subject, issuer, mapAttributes(provider, claims)); + Instant signedInAt = clock.instant(); CognitoAuthorizationCode authorizationCode = new CognitoAuthorizationCode( transaction.userPoolId(), transaction.clientId(), user.getUsername(), transaction.redirectUri(), transaction.scopes(), transaction.nonce(), transaction.codeChallenge(), - clock.instant().plus(AUTHORIZATION_CODE_LIFETIME)); + signedInAt, signedInAt.plus(AUTHORIZATION_CODE_LIFETIME)); return stateStore.putAuthorizationCode(authorizationCode); } diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginService.java index 65de449199..3ba8828fcd 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginService.java @@ -11,6 +11,7 @@ import org.jboss.logging.Logger; import java.time.Clock; import java.time.Duration; +import java.time.Instant; import java.util.List; import java.util.Optional; @@ -92,14 +93,17 @@ public class CognitoManagedLoginService { } private String openSession(UserPoolClient client, CognitoUser user) { + Instant signedInAt = clock.instant(); return stateStore.putSession(new CognitoManagedLoginSession( - client.getUserPoolId(), user.getUsername(), clock.instant().plus(SESSION_LIFETIME))); + client.getUserPoolId(), user.getUsername(), signedInAt, signedInAt.plus(SESSION_LIFETIME))); } /** * Issues an authorization code to the user of the browser's session, or nothing when there is * no session for the client's pool. Every pool's session travels in the same cookie on Floci's - * own host, so a session of one pool must never sign its user in to another. + * own host, so a session of one pool must never sign its user in to another. The code keeps the + * session's sign-in time, so its tokens carry the {@code auth_time} of the sign-in, not of this + * request. * * @param grantedScopes the scopes the authorization request was granted, which the code keeps */ @@ -116,7 +120,7 @@ public class CognitoManagedLoginService { } CognitoAuthorizationCode code = new CognitoAuthorizationCode(client.getUserPoolId(), client.getClientId(), session.get().username(), redirectUri, grantedScopes, nonce, codeChallenge, - clock.instant().plus(AUTHORIZATION_CODE_LIFETIME)); + session.get().authTime(), clock.instant().plus(AUTHORIZATION_CODE_LIFETIME)); return Optional.of(stateStore.putAuthorizationCode(code)); } diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthController.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthController.java index c59a108c5a..e407e6e6d5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthController.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthController.java @@ -619,7 +619,7 @@ public class CognitoOAuthController { UserPool pool = cognitoService.describeUserPool(consumedCode.userPoolId()); CognitoUser user = cognitoService.adminGetUser(consumedCode.userPoolId(), consumedCode.userId()); Map authentication = cognitoService.generateAuthResultForHostedAuth(user, pool, client, - nonceClaim(consumedCode.nonce()), consumedCode.scopes()); + nonceClaim(consumedCode.nonce()), consumedCode.scopes(), consumedCode.authTime()); return tokenResponse(authentication); } catch (AwsException e) { LOG.error("Failed to redeem Cognito authorization code", e); diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java index c18ed5e7bb..f1b3b60980 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java @@ -137,6 +137,11 @@ public class CognitoService implements ResourceProvider { * starts with it, so a token whose username holds a pipe is never read as one with scopes. */ private static final String REFRESH_TOKEN_SCOPE_FIELD = "scope="; + /** + * Starts the refresh token field that holds when the user signed in, in epoch seconds. A family id + * never starts with it either, so a token minted before the field existed is never read as one with it. + */ + private static final String REFRESH_TOKEN_AUTH_TIME_FIELD = "auth_time="; private static final String IDENTITIES_ATTRIBUTE = "identities"; @@ -4433,7 +4438,7 @@ public class CognitoService implements ResourceProvider { // Use refresh token UUID as origin_jti for derived tokens Map result = new HashMap<>(); result.put("AuthenticationResult", accessAndIdTokens(user, pool, client, override, refreshTokenUuid, - scopes, issuedAt / 1000L)); + scopes, refreshTokenAuthTime(parts, issuedAt))); return result; } @@ -4533,13 +4538,17 @@ public class CognitoService implements ResourceProvider { * allows, rather than the {@code aws.cognito.signin.user.admin} of an API sign-in, and the ID * token is minted only when they include {@code openid}, as on AWS. The trigger is told the same * scopes, and a V2 trigger's scope changes apply on top of them. + * + *

{@code authTime} is when the user signed in, which the code kept: the tokens carry it as + * {@code auth_time}, and so does every token refreshed from them. */ Map generateAuthResultForHostedAuth(CognitoUser user, UserPool pool, UserPoolClient client, - ClaimsOverride protocolClaims, List grantedScopes) { + ClaimsOverride protocolClaims, List grantedScopes, + Instant authTime) { List scopes = scopesStillAllowed(client, grantedScopes); ClaimsOverride trigger = authFlowHandler.preTokenGenerationForHostedAuth(pool, client, user, scopes); return generateAuthResult(user, pool, client, mergeUnderProtocolClaims(trigger, protocolClaims), - UUID.randomUUID().toString(), scopes); + UUID.randomUUID().toString(), scopes, authTime.getEpochSecond()); } /** @@ -4612,22 +4621,25 @@ public class CognitoService implements ResourceProvider { } Map generateAuthResult(CognitoUser user, UserPool pool, UserPoolClient client, ClaimsOverride override, String originJti) { - return generateAuthResult(user, pool, client, override, originJti, null); + return generateAuthResult(user, pool, client, override, originJti, null, null); } /** * @param grantedScopes the scopes of the OAuth grant the tokens are minted for, or null for a * sign-in through the API. The refresh token keeps them, so that a refresh * mints the same kind of tokens. + * @param authTime when the user signed in, epoch seconds, which the refresh token keeps too; + * null for a sign-in through the API, which the user completes with this request */ private Map generateAuthResult(CognitoUser user, UserPool pool, UserPoolClient client, ClaimsOverride override, String originJti, - List grantedScopes) { + List grantedScopes, Long authTime) { long issuedAt = System.currentTimeMillis(); + long signedInAt = authTime != null ? authTime : issuedAt / 1000L; Map auth = accessAndIdTokens(user, pool, client, override, originJti, grantedScopes, - issuedAt / 1000L); + signedInAt); auth.put("RefreshToken", buildRefreshToken(pool, user.getUsername(), client.getClientId(), issuedAt, - originJti, grantedScopes)); + originJti, grantedScopes, signedInAt)); return auth; } @@ -4761,12 +4773,12 @@ public class CognitoService implements ResourceProvider { Map addOrOverride = isAccess ? override.accessClaimsToAddOrOverride() : override.idClaimsToAddOrOverride(); if (suppress != null) { suppress.stream() - .filter(claim -> !isTriggerProtectedIdentityClaim(claim, isAccess)) + .filter(claim -> !isTriggerProtectedClaim(claim, isAccess)) .forEach(claims::remove); } if (addOrOverride != null) { addOrOverride.forEach((claim, value) -> { - if (!isTriggerProtectedIdentityClaim(claim, isAccess)) { + if (!isTriggerProtectedClaim(claim, isAccess)) { claims.put(claim, value); } }); @@ -4802,10 +4814,12 @@ public class CognitoService implements ResourceProvider { /** * AWS lets no pre token generation trigger add, modify or suppress the claims that identify * the user: {@code sub} in either token, {@code username} in the access token and - * {@code cognito:username} in the ID token. + * {@code cognito:username} in the ID token. Nor {@code auth_time}, when the user signed in, in + * either token. */ - private static boolean isTriggerProtectedIdentityClaim(String claim, boolean isAccess) { - return "sub".equals(claim) || (isAccess ? "username" : "cognito:username").equals(claim); + private static boolean isTriggerProtectedClaim(String claim, boolean isAccess) { + return "sub".equals(claim) || "auth_time".equals(claim) + || (isAccess ? "username" : "cognito:username").equals(claim); } private String encodeJwtHeader(UserPool pool) { @@ -5492,17 +5506,20 @@ public class CognitoService implements ResourceProvider { } /** - * A signed {@code poolId|username|clientId|issuedAt|familyId} token. An OAuth grant's token adds a - * field holding its scopes, base64url-encoded because a scope may contain the pipe that separates - * the fields; a sign-in through the API, {@code grantedScopes} null, has none. + * A signed {@code poolId|username|clientId|issuedAt|familyId|authTime} token, {@code authTime} being + * when the user signed in, which a managed login session can put well before the token is issued. + * An OAuth grant's token adds a field holding its scopes, base64url-encoded because a scope may + * contain the pipe that separates the fields; a sign-in through the API, {@code grantedScopes} + * null, has none. */ String buildRefreshToken(UserPool pool, String username, String clientId, long issuedAt, String originJti, - List grantedScopes) { + List grantedScopes, long authTime) { if (ensureRefreshTokenSecret(pool)) { poolStore.put(pool.getId(), pool); } String familyId = originJti != null ? originJti : UUID.randomUUID().toString(); - String raw = pool.getId() + "|" + username + "|" + clientId + "|" + issuedAt + "|" + familyId; + String raw = pool.getId() + "|" + username + "|" + clientId + "|" + issuedAt + "|" + familyId + + "|" + REFRESH_TOKEN_AUTH_TIME_FIELD + authTime; if (grantedScopes != null) { raw += "|" + REFRESH_TOKEN_SCOPE_FIELD + Base64Url.encode(String.join(" ", grantedScopes)); } @@ -5522,8 +5539,9 @@ public class CognitoService implements ResourceProvider { /** * The fields of a refresh token whose signature verifies: {@code [poolId, username, clientId, - * issuedAt, familyId]}, and for an OAuth grant's token a sixth, its scopes separated by spaces. - * Only the username can hold a pipe, so the fields after it are read from the end of the token. + * issuedAt, familyId, authTime]}, {@code authTime} empty for a token minted before refresh tokens + * kept it, and for an OAuth grant's token a seventh, its scopes separated by spaces. Only the + * username can hold a pipe, so the fields after it are read from the end of the token. */ String[] parseRefreshToken(String refreshToken) { try { @@ -5532,9 +5550,16 @@ public class CognitoService implements ResourceProvider { int signatureAt = raw.lastIndexOf('|'); String payload = raw.substring(0, signatureAt); String[] parts = payload.split("\\|", -1); - boolean hasScopes = parts[parts.length - 1].startsWith(REFRESH_TOKEN_SCOPE_FIELD); - int trailing = hasScopes ? 4 : 3; - if (parts.length < 2 + trailing) { + int end = parts.length; + boolean hasScopes = parts[end - 1].startsWith(REFRESH_TOKEN_SCOPE_FIELD); + if (hasScopes) { + end--; + } + boolean hasAuthTime = end > 0 && parts[end - 1].startsWith(REFRESH_TOKEN_AUTH_TIME_FIELD); + if (hasAuthTime) { + end--; + } + if (end < 5) { return null; } UserPool pool = poolStore.get(parts[0]).orElse(null); @@ -5546,13 +5571,14 @@ public class CognitoService implements ResourceProvider { if (!MessageDigest.isEqual(expectedSignature, actualSignature)) { return null; } - int usernameEnd = parts.length - trailing; - String[] fields = new String[hasScopes ? 6 : 5]; + int usernameEnd = end - 3; + String[] fields = new String[hasScopes ? 7 : 6]; fields[0] = parts[0]; fields[1] = String.join("|", Arrays.copyOfRange(parts, 1, usernameEnd)); System.arraycopy(parts, usernameEnd, fields, 2, 3); + fields[5] = hasAuthTime ? parts[end].substring(REFRESH_TOKEN_AUTH_TIME_FIELD.length()) : ""; if (hasScopes) { - fields[5] = new String(Base64.getUrlDecoder().decode( + fields[6] = new String(Base64.getUrlDecoder().decode( parts[parts.length - 1].substring(REFRESH_TOKEN_SCOPE_FIELD.length())), StandardCharsets.UTF_8); } return fields; @@ -5562,10 +5588,20 @@ public class CognitoService implements ResourceProvider { /** The scopes of the OAuth grant a parsed refresh token belongs to, or null for a sign-in through the API. */ static List refreshTokenScopes(String[] parts) { - if (parts.length < 6) { + if (parts.length < 7) { return null; } - return parts[5].isEmpty() ? List.of() : List.of(parts[5].split(" ")); + return parts[6].isEmpty() ? List.of() : List.of(parts[6].split(" ")); + } + + /** + * When the user signed in to get a parsed refresh token, in epoch seconds: every token refreshed + * from it keeps that as its {@code auth_time}, since "Refreshing a token doesn't reset the + * {@code auth_time} claim" on AWS. A token minted before refresh tokens kept it falls back to when + * it was issued, {@code issuedAtMillis}. + */ + static long refreshTokenAuthTime(String[] parts, long issuedAtMillis) { + return parts[5].isEmpty() ? issuedAtMillis / 1000L : Long.parseLong(parts[5]); } record VerifiedAccessToken(String username, String poolId, String subject, String clientId) {} diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoAuthorizationCode.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoAuthorizationCode.java index 5500a7d406..296b93bedf 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoAuthorizationCode.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoAuthorizationCode.java @@ -8,7 +8,9 @@ import java.util.List; * when the code was issued, which redemption narrows to the client's current AllowedOAuthScopes but * never widens. {@code nonce} and {@code codeChallenge} are the authorization request's values, or * null when it sent none; the token endpoint puts the nonce in the ID token and requires a matching - * {@code code_verifier} when there is a challenge. + * {@code code_verifier} when there is a challenge. {@code authTime} is when the user signed in, which + * can be well before the code was issued when a managed login session skipped the sign-in form; the + * tokens the code redeems for carry it as {@code auth_time}. */ public record CognitoAuthorizationCode( String userPoolId, @@ -18,6 +20,7 @@ public record CognitoAuthorizationCode( List scopes, String nonce, String codeChallenge, + Instant authTime, Instant expiresAt) { public CognitoAuthorizationCode { diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoManagedLoginSession.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoManagedLoginSession.java index 9c70d3b03f..8c802818a0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoManagedLoginSession.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoManagedLoginSession.java @@ -4,7 +4,8 @@ import java.time.Instant; /** * A browser's managed login session, which lets {@code /oauth2/authorize} skip the sign-in form. - * {@code username} is the user's canonical username, not the alias they typed. + * {@code username} is the user's canonical username, not the alias they typed. {@code authTime} is + * when the user signed in, which every token issued through the session carries as {@code auth_time}. */ -public record CognitoManagedLoginSession(String userPoolId, String username, Instant expiresAt) { +public record CognitoManagedLoginSession(String userPoolId, String username, Instant authTime, Instant expiresAt) { } diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoFederationServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoFederationServiceTest.java index 20a5cab395..c2927d4d2d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoFederationServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoFederationServiceTest.java @@ -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); } diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoFederationStateStoreTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoFederationStateStoreTest.java index 064efb000b..b3bca40bfd 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoFederationStateStoreTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoFederationStateStoreTest.java @@ -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 ); } diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java index 0cb685be59..69bcc77f36 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java @@ -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 auth = service.generateAuthResultForHostedAuth(user, pool, client, null, - List.of("openid", "email")); + List.of("openid", "email"), Instant.now()); Map event; Map 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 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 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 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 idClaims; try { @@ -1524,7 +1524,7 @@ class CognitoLambdaTriggersTest { Map 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 granted = CognitoService.grantedScopes(client, List.of()); - Map auth = service.generateAuthResultForHostedAuth(user, pool, client, null, granted); + Map auth = service.generateAuthResultForHostedAuth(user, pool, client, null, granted, + Instant.now()); assertEquals(List.of("openid", "email", "aws.cognito.signin.user.admin"), granted); Map event; @@ -1579,7 +1580,8 @@ class CognitoLambdaTriggersTest { UserPoolClient client = createOAuthClient(pool, List.of("openid", "email")); CognitoUser user = service.adminGetUser(pool.getId(), "alice"); - Map auth = service.generateAuthResultForHostedAuth(user, pool, client, null, List.of()); + Map auth = service.generateAuthResultForHostedAuth(user, pool, client, null, List.of(), + Instant.now()); Map accessClaims; try { @@ -1602,7 +1604,8 @@ class CognitoLambdaTriggersTest { .thenReturn(ok(Map.of("claimsAndScopeOverrideDetails", Map.of( "accessTokenGeneration", Map.of("scopesToSuppress", List.of("email")))))); - Map auth = service.generateAuthResultForHostedAuth(user, pool, client, null, List.of("email")); + Map auth = service.generateAuthResultForHostedAuth(user, pool, client, null, List.of("email"), + Instant.now()); Map accessClaims; try { @@ -1621,7 +1624,8 @@ class CognitoLambdaTriggersTest { UserPoolClient client = createOAuthClient(pool, List.of("openid", "email")); CognitoUser user = service.adminGetUser(pool.getId(), "alice"); - Map auth = service.generateAuthResultForHostedAuth(user, pool, client, null, List.of("email")); + Map auth = service.generateAuthResultForHostedAuth(user, pool, client, null, List.of("email"), + Instant.now()); Map accessClaims; try { @@ -1648,7 +1652,7 @@ class CognitoLambdaTriggersTest { "scopesToAdd", List.of("aws.cognito.signin.user.admin")))))); Map auth = service.generateAuthResultForHostedAuth(user, pool, client, null, - List.of("openid", "email")); + List.of("openid", "email"), Instant.now()); Map accessClaims; try { diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginIntegrationTest.java index 93d3916ac9..e83d99bd94 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginIntegrationTest.java @@ -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(); diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthControllerTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthControllerTest.java index e059c7d046..bb2a6096fd 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthControllerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthControllerTest.java @@ -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 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; diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java index e83c9ca41e..d052dfc056 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java @@ -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.of("sub", "other", "cognito:username", "bob"), null, - Map.of("sub", "other", "username", "bob"), null, + Map.of("sub", "other", "cognito:username", "bob", "auth_time", 1L), null, + Map.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 redeemed = service.generateAuthResultForHostedAuth(service.adminGetUser(pool.getId(), "alice"), + pool, client, null, List.of("openid"), signedIn); + String refreshToken = (String) redeemed.get("RefreshToken"); + + Map viaInitiateAuth = (Map) service.initiateAuth(client.getClientId(), + "REFRESH_TOKEN_AUTH", Map.of("REFRESH_TOKEN", refreshToken)).get("AuthenticationResult"); + Map viaGetTokens = (Map) service.getTokensFromRefreshToken( + client.getClientId(), refreshToken).get("AuthenticationResult"); + + for (Map 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 response : List.of( + service.getTokensFromRefreshToken(client.getClientId(), refreshToken), + service.initiateAuth(client.getClientId(), "REFRESH_TOKEN_AUTH", + Map.of("REFRESH_TOKEN", refreshToken)))) { + Map refreshed = (Map) 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 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 refreshed = (Map) 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 refreshed = (Map) service .getTokensFromRefreshToken(client.getClientId(), refreshToken).get("AuthenticationResult");