Light, fluffy, and always free - The AWS Local Emulator alternative
fix(cognito): expire auth challenge sessions (#4417)
Niels Kootstra8b9f441bb496
diff --git a/docs/services/cognito.md b/docs/services/cognito.mdindex ceaf1caeb7..424ecc4283 100644--- a/docs/services/cognito.md+++ b/docs/services/cognito.md@@ -214,6 +214,12 @@ challenge. It requires the user pool's tier to be Essentials or higher. `WEB_AUTAny other `AuthFlow` value is rejected with `InvalidParameterException` and no tokens are issued.+The challenge `Session` of a `USER_SRP_AUTH`, `CUSTOM_AUTH` or `USER_AUTH` sign-in is valid for 3 minutes+from when it was issued, the AWS default for the client's `AuthSessionValidity`. Answering the challenge with+an older session fails with `NotAuthorizedException` (`Invalid session for the user, session is expired.`)+and the sign-in has to start again. A per-client `AuthSessionValidity` is not supported yet, and the+`NEW_PASSWORD_REQUIRED` challenge does not check its session.+An app client only accepts the flows in its `ExplicitAuthFlows`: `ALLOW_USER_PASSWORD_AUTH`,`ALLOW_USER_SRP_AUTH`, `ALLOW_CUSTOM_AUTH`, `ALLOW_USER_AUTH`, `ALLOW_ADMIN_USER_PASSWORD_AUTH` and`ALLOW_REFRESH_TOKEN_AUTH`, or the legacy `USER_PASSWORD_AUTH`, `ADMIN_NO_SRP_AUTH` anddiff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.javaindex 15e9d54917..5483d127c7 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@@ -17,6 +17,9 @@ import org.jboss.logging.Logger;import java.nio.charset.StandardCharsets;import java.security.MessageDigest;+import java.time.Clock;+import java.time.Duration;+import java.time.Instant;import java.util.ArrayList;import java.util.Base64;import java.util.HashMap;@@ -25,6 +28,7 @@ import java.util.List;import java.util.Map;import java.util.UUID;import java.util.concurrent.ConcurrentHashMap;+import java.util.function.Function;/*** Owns Cognito authentication-flow protocol logic: USER_PASSWORD_AUTH,@@ -46,17 +50,26 @@ final class CognitoAuthFlowHandler {private static final String CUSTOM_MESSAGE_CODE_PARAMETER = "{####}";/** The message of a wrong password, which managed login also shows for an unknown user. */static final String INCORRECT_CREDENTIALS = "Incorrect username or password";+ /**+ * AWS default {@code AuthSessionValidity} (CreateUserPoolClient, valid range 3-15 minutes):+ * the lifetime of a challenge session token before InitiateAuth/RespondToAuthChallenge reject+ * it as expired. {@link UserPoolClient} does not yet store a per-client override, so every+ * client uses the AWS default until that field exists.+ */+ private static final Duration AUTH_SESSION_VALIDITY = Duration.ofMinutes(3);private final CognitoService service;private final LambdaService lambdaService;private final RegionResolver regionResolver;+ private final Clock clock;private final ConcurrentHashMap<String, SrpSession> srpSessions = new ConcurrentHashMap<>();- private final ConcurrentHashMap<String, CustomAuthSession> customAuthSessions = new ConcurrentHashMap<>();+ private final ConcurrentHashMap<String, CustomAuthToken> customAuthSessions = new ConcurrentHashMap<>();private final ConcurrentHashMap<String, UserAuthSession> userAuthSessions = new ConcurrentHashMap<>();private record SrpSession(String userPoolId, String username, String clientId,String aHex, String bHex, String bPublicHex,- String secretBlockBase64, Map<String, String> clientMetadata) {}+ String secretBlockBase64, Map<String, String> clientMetadata,+ Instant issuedAt) {}/*** Correlates a USER_AUTH challenge response back to the InitiateAuth/RespondToAuthChallenge@@ -65,7 +78,8 @@ final class CognitoAuthFlowHandler {* factor answer with no session at all, bypassing handleUserAuth's tier gate and letting a* caller trigger an OTP send without ever starting a flow.*/- private record UserAuthSession(String userPoolId, String username, String clientId, String challengeName) {}+ private record UserAuthSession(String userPoolId, String username, String clientId, String challengeName,+ Instant issuedAt) {}static final class CustomAuthSession {final String userPoolId;@@ -83,10 +97,42 @@ final class CognitoAuthFlowHandler {}}- CognitoAuthFlowHandler(CognitoService service, LambdaService lambdaService, RegionResolver regionResolver) {+ /**+ * One issued CUSTOM_AUTH session token. The flow state is shared across rounds, but each token+ * keeps the time it was minted, so issuing the next round's token never extends the old one.+ */+ private record CustomAuthToken(CustomAuthSession state, Instant issuedAt) {}++ CognitoAuthFlowHandler(CognitoService service, LambdaService lambdaService, RegionResolver regionResolver,+ Clock clock) {this.service = service;this.lambdaService = lambdaService;this.regionResolver = regionResolver;+ this.clock = clock;+ }++ /**+ * True once {@code issuedAt} is older than {@link #AUTH_SESSION_VALIDITY}, matching the+ * NotAuthorizedException AWS returns for an expired InitiateAuth/RespondToAuthChallenge session.+ */+ private boolean sessionExpired(Instant issuedAt) {+ return clock.instant().isAfter(issuedAt.plus(AUTH_SESSION_VALIDITY));+ }++ private static AwsException sessionExpiredException() {+ return new AwsException("NotAuthorizedException",+ "Invalid session for the user, session is expired.", 400);+ }++ /** Stores a newly minted CUSTOM_AUTH token, stamped now, after dropping expired ones. */+ private void issueCustomAuthToken(String sessionToken, CustomAuthSession state) {+ purgeExpired(customAuthSessions, CustomAuthToken::issuedAt);+ customAuthSessions.put(sessionToken, new CustomAuthToken(state, clock.instant()));+ }++ /** Drops already-expired entries so an abandoned challenge session doesn't linger forever. */+ private <V> void purgeExpired(ConcurrentHashMap<String, V> sessions, Function<V, Instant> issuedAtOf) {+ sessions.entrySet().removeIf(entry -> sessionExpired(issuedAtOf.apply(entry.getValue())));}// ──────────────────────────── Public entry points ────────────────────────────@@ -493,10 +539,11 @@ final class CognitoAuthFlowHandler {new java.security.SecureRandom().nextBytes(secretBlock);String secretBlockBase64 = Base64.getEncoder().encodeToString(secretBlock);+ purgeExpired(srpSessions, SrpSession::issuedAt);srpSessions.put(sessionToken, new SrpSession(pool.getId(), user.getUsername(), client.getClientId(),aHex, bHex, bPublicHex, secretBlockBase64,- clientMetadata == null ? Map.of() : clientMetadata));+ clientMetadata == null ? Map.of() : clientMetadata, clock.instant()));Map<String, Object> result = new HashMap<>();result.put("ChallengeName", "PASSWORD_VERIFIER");@@ -514,14 +561,23 @@ final class CognitoAuthFlowHandler {private Map<String, Object> handlePasswordVerifierChallenge(UserPool pool, UserPoolClient client,String session, Map<String, String> responses,Map<String, String> clientMetadata) {- CustomAuthSession customState =+ CustomAuthToken customToken =session == null ? null : customAuthSessions.get(session);- if (customState != null) {- return verifyPasswordWithinCustomAuth(pool, client, session, customState, responses, clientMetadata);+ if (customToken != null) {+ if (sessionExpired(customToken.issuedAt())) {+ customAuthSessions.remove(session);+ throw sessionExpiredException();+ }+ return verifyPasswordWithinCustomAuth(pool, client, session, customToken.state(), responses,+ clientMetadata);}SrpSession srp = srpSessions.get(session);if (srp == null) throw new AwsException("NotAuthorizedException", "Session not found", 400);+ if (sessionExpired(srp.issuedAt())) {+ srpSessions.remove(session);+ throw sessionExpiredException();+ }String username = responses.get("USERNAME");String claimSignature = responses.get("PASSWORD_CLAIM_SIGNATURE");@@ -704,8 +760,10 @@ final class CognitoAuthFlowHandler {String challengeName, List<String> available,Map<String, String> challengeParameters) {String session = buildSessionToken(pool.getId(), user.getUsername(), client.getClientId());+ purgeExpired(userAuthSessions, UserAuthSession::issuedAt);userAuthSessions.put(session,- new UserAuthSession(pool.getId(), user.getUsername(), client.getClientId(), challengeName));+ new UserAuthSession(pool.getId(), user.getUsername(), client.getClientId(), challengeName,+ clock.instant()));Map<String, Object> result = new HashMap<>();result.put("ChallengeName", challengeName);result.put("Session", session);@@ -727,6 +785,9 @@ final class CognitoAuthFlowHandler {if (state == null || !expectedChallenge.equals(state.challengeName())) {throw new AwsException("NotAuthorizedException", "Session not found", 400);}+ if (sessionExpired(state.issuedAt())) {+ throw sessionExpiredException();+ }if (!state.userPoolId().equals(pool.getId()) || !state.clientId().equals(client.getClientId())) {throw new AwsException("NotAuthorizedException", "Session does not match client", 400);}@@ -810,7 +871,7 @@ final class CognitoAuthFlowHandler {createAuthChallenge(pool, client, user, state, challengeName), publicParams);String sessionToken = buildSessionToken(pool.getId(), user.getUsername(), client.getClientId());- customAuthSessions.put(sessionToken, state);+ issueCustomAuthToken(sessionToken, state);Map<String, Object> result = new HashMap<>();result.put("ChallengeName", challengeName);@@ -823,8 +884,15 @@ final class CognitoAuthFlowHandler {String session, Map<String, String> responses,Map<String, String> clientMetadata) {if (session == null) throw new AwsException("InvalidParameterException", "Session is required", 400);- CustomAuthSession state = customAuthSessions.get(session);- if (state == null) throw new AwsException("NotAuthorizedException", "Session not found", 400);+ CustomAuthToken token = customAuthSessions.get(session);+ if (token == null) {+ throw new AwsException("NotAuthorizedException", "Session not found", 400);+ }+ if (sessionExpired(token.issuedAt())) {+ customAuthSessions.remove(session);+ throw sessionExpiredException();+ }+ CustomAuthSession state = token.state();if (!state.userPoolId.equals(pool.getId()) || !state.clientId.equals(client.getClientId())) {throw new AwsException("NotAuthorizedException", "Session does not match client", 400);}@@ -873,7 +941,7 @@ final class CognitoAuthFlowHandler {String newSession = buildSessionToken(pool.getId(), state.username, client.getClientId());customAuthSessions.remove(session);- customAuthSessions.put(newSession, state);+ issueCustomAuthToken(newSession, state);Map<String, Object> result = new HashMap<>();result.put("ChallengeName", nextChallenge);@@ -933,7 +1001,7 @@ final class CognitoAuthFlowHandler {String newSession = buildSessionToken(pool.getId(), state.username, client.getClientId());customAuthSessions.remove(session);- customAuthSessions.put(newSession, state);+ issueCustomAuthToken(newSession, state);Map<String, Object> result = new HashMap<>();result.put("ChallengeName", nextChallenge);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.javaindex d6d0869eef..42af56913c 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@@ -189,7 +189,8 @@ public class CognitoService implements ResourceProvider {acmService,new VerificationCodeService(storageFactory, clock),new CognitoMessageDispatcher(sesService, snsService),- certificateManager+ certificateManager,+ clock);}@@ -255,6 +256,32 @@ public class CognitoService implements ResourceProvider {VerificationCodeService verificationCodeService,CognitoMessageDispatcher messageDispatcher,TlsCertificateManager certificateManager) {+ this(poolStore, clientStore, resourceServerStore, domainStore, identityProviderStore, userStore,+ groupStore, revokedTokenStore, baseUrl, cloudFrontDomainSuffix, regionResolver, lambdaService,+ acmService, verificationCodeService, messageDispatcher, certificateManager, Clock.systemUTC());+ }++ /**+ * Full constructor accepting the {@link Clock} used to time-bound Cognito auth challenge+ * sessions (see {@link CognitoAuthFlowHandler}). Production code reaches this through the+ * {@code @Inject} constructor above with the CDI-managed clock; every other constructor here+ * defaults to {@link Clock#systemUTC()} so existing call sites are unaffected.+ */+ CognitoService(StorageBackend<String, UserPool> poolStore,+ StorageBackend<String, UserPoolClient> clientStore,+ StorageBackend<String, ResourceServer> resourceServerStore,+ StorageBackend<String, UserPoolDomain> domainStore,+ StorageBackend<String, IdentityProvider> identityProviderStore,+ StorageBackend<String, CognitoUser> userStore,+ StorageBackend<String, CognitoGroup> groupStore,+ StorageBackend<String, RevokedTokenInfo> revokedTokenStore,+ String baseUrl,+ String cloudFrontDomainSuffix,+ RegionResolver regionResolver, LambdaService lambdaService, AcmService acmService,+ VerificationCodeService verificationCodeService,+ CognitoMessageDispatcher messageDispatcher,+ TlsCertificateManager certificateManager,+ Clock clock) {this.poolStore = poolStore;this.clientStore = clientStore;this.resourceServerStore = resourceServerStore;@@ -271,7 +298,7 @@ public class CognitoService implements ResourceProvider {this.verificationCodeService = verificationCodeService;this.messageDispatcher = messageDispatcher;this.certificateManager = certificateManager;- this.authFlowHandler = new CognitoAuthFlowHandler(this, lambdaService, regionResolver);+ this.authFlowHandler = new CognitoAuthFlowHandler(this, lambdaService, regionResolver, clock);}// ──────────────────────────── User Pools ────────────────────────────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.javaindex 977355f347..f967c8cdb7 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@@ -18,6 +18,7 @@ import io.github.hectorvent.floci.services.lambda.model.InvocationType;import io.github.hectorvent.floci.services.lambda.model.InvokeResult;import io.github.hectorvent.floci.services.ses.SesService;import io.github.hectorvent.floci.services.sns.SnsService;+import io.github.hectorvent.floci.testing.MutableClock;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import org.junit.jupiter.params.ParameterizedTest;@@ -28,6 +29,7 @@ import org.mockito.ArgumentCaptor;import javax.crypto.Mac;import javax.crypto.spec.SecretKeySpec;import java.nio.charset.StandardCharsets;+import java.time.Duration;import java.util.Base64;import java.util.HashMap;import java.util.List;@@ -879,6 +881,82 @@ class CognitoLambdaTriggersTest {verify(lambdaService).invoke(anyString(), eq("arn:aws:lambda:::verify"), any(byte[].class), any());}+ private CognitoService serviceWithClock(MutableClock clock) {+ return new CognitoService(+ new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),+ new InMemoryStorage<>(), new InMemoryStorage<>(),+ new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),+ "http://localhost:4566", "cloudfront.net", regionResolver, lambdaService, mock(AcmService.class),+ null, null, mock(TlsCertificateManager.class), clock);+ }++ private UserPoolClient customAuthClient(CognitoService clockedService) {+ Map<String, Object> req = new HashMap<>();+ req.put("PoolName", "trigger-pool");+ req.put("LambdaConfig", Map.of(+ "DefineAuthChallenge", "arn:aws:lambda:::define",+ "CreateAuthChallenge", "arn:aws:lambda:::create",+ "VerifyAuthChallengeResponse", "arn:aws:lambda:::verify"));+ UserPool pool = clockedService.createUserPool(req, "us-east-1");+ clockedService.adminCreateUser(pool.getId(), "alice", Map.of("email", "[email protected]"), null);+ clockedService.adminSetUserPassword(pool.getId(), "alice", "Perm1234!", true);+ return clockedService.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of(),+ null, List.of(), null, AUTH_FLOWS, null, null, List.of(), null, List.of(), null,+ null, null, List.of(), null, null);+ }++ @Test+ @SuppressWarnings("unchecked")+ void customAuthSessionValidityStartsWhenTheSessionIsIssued() {+ MutableClock clock = new MutableClock();+ CognitoService clockedService = serviceWithClock(clock);+ UserPoolClient client = customAuthClient(clockedService);++ when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::define"), any(byte[].class), any()))+ .thenReturn(ok(Map.of("challengeName", "CUSTOM_CHALLENGE")))+ .thenReturn(ok(Map.of("issueTokens", true)));+ // A slow CreateAuthChallenge trigger: two minutes pass before the session is handed out.+ when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::create"), any(byte[].class), any()))+ .thenAnswer(invocation -> {+ clock.advance(Duration.ofMinutes(2));+ return ok(Map.of("privateChallengeParameters", Map.of("answer", "blue")));+ });+ when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::verify"), any(byte[].class), any()))+ .thenReturn(ok(Map.of("answerCorrect", true)));++ String session = (String) clockedService.initiateAuth(client.getClientId(), "CUSTOM_AUTH",+ Map.of("USERNAME", "alice")).get("Session");+ clock.advance(Duration.ofMinutes(2));++ Map<String, Object> tokens = clockedService.respondToAuthChallenge(client.getClientId(),+ "CUSTOM_CHALLENGE", session, Map.of("USERNAME", "alice", "ANSWER", "blue"));++ assertNotNull(((Map<String, Object>) tokens.get("AuthenticationResult")).get("AccessToken"));+ }++ @Test+ void customAuthSessionExpiresThreeMinutesAfterItIsIssued() {+ MutableClock clock = new MutableClock();+ CognitoService clockedService = serviceWithClock(clock);+ UserPoolClient client = customAuthClient(clockedService);++ when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::define"), any(byte[].class), any()))+ .thenReturn(ok(Map.of("challengeName", "CUSTOM_CHALLENGE")));+ when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::create"), any(byte[].class), any()))+ .thenReturn(ok(Map.of("privateChallengeParameters", Map.of("answer", "blue"))));++ String session = (String) clockedService.initiateAuth(client.getClientId(), "CUSTOM_AUTH",+ Map.of("USERNAME", "alice")).get("Session");+ clock.advance(Duration.ofMinutes(3).plusSeconds(1));++ AwsException ex = assertThrows(AwsException.class, () ->+ clockedService.respondToAuthChallenge(client.getClientId(), "CUSTOM_CHALLENGE", session,+ Map.of("USERNAME", "alice", "ANSWER", "blue")));+ assertEquals("NotAuthorizedException", ex.getErrorCode());+ assertEquals("Invalid session for the user, session is expired.", ex.getMessage());+ verify(lambdaService, never()).invoke(anyString(), eq("arn:aws:lambda:::verify"), any(byte[].class), any());+ }+@Testvoid customAuthDoesNotIssueTokensWhenVerifyAuthChallengeTriggerErrors() {UserPool pool = createPoolWithLambdaConfig(Map.of("DefineAuthChallenge",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.javaindex 3dd8e09710..b3515c4bb9 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@@ -24,6 +24,7 @@ import io.github.hectorvent.floci.services.cognito.verification.CognitoMessageDiimport io.github.hectorvent.floci.services.cognito.verification.VerificationCode;import io.github.hectorvent.floci.services.cognito.verification.VerificationCodeException;import io.github.hectorvent.floci.services.cognito.verification.VerificationCodeService;+import io.github.hectorvent.floci.testing.MutableClock;import org.mockito.ArgumentCaptor;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Nested;@@ -32,6 +33,8 @@ import org.junit.jupiter.params.ParameterizedTest;import org.junit.jupiter.params.provider.CsvSource;import java.nio.charset.StandardCharsets;+import java.time.Clock;+import java.time.Duration;import java.util.ArrayList;import java.util.Base64;import java.util.HashMap;@@ -2376,6 +2379,111 @@ class CognitoServiceTest {assertEquals("NotAuthorizedException", ex.getErrorCode());}+ // =========================================================================+ // Auth challenge session expiry+ // =========================================================================++ private CognitoService serviceWithClock(Clock clock) {+ return new CognitoService(+ new InMemoryStorage<>(),+ new InMemoryStorage<>(),+ new InMemoryStorage<>(),+ new InMemoryStorage<>(),+ new InMemoryStorage<>(),+ new InMemoryStorage<>(),+ new InMemoryStorage<>(),+ new InMemoryStorage<>(),+ "http://localhost:4566",+ "cloudfront.net",+ regionResolver,+ null,+ acmService,+ null,+ null,+ null,+ clock+ );+ }++ @Test+ void respondToAuthChallengeAfterSrpSessionExpiryRejects() {+ MutableClock clock = new MutableClock();+ CognitoService clockedService = serviceWithClock(clock);+ String password = "Password123!";+ UserPool pool = clockedService.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");+ clockedService.adminCreateUser(pool.getId(), "bob", Map.of("email", "[email protected]"), null);+ clockedService.adminSetUserPassword(pool.getId(), "bob", password, true);+ UserPoolClient client =+ clockedService.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());++ Map<String, Object> initResult = clockedService.initiateAuth(client.getClientId(), "USER_SRP_AUTH",+ Map.of("USERNAME", "bob", "SRP_A", "ABCDEF1234567890"));+ String session = (String) initResult.get("Session");++ clock.advance(Duration.ofMinutes(3).plusSeconds(1));++ AwsException ex = assertThrows(AwsException.class, () ->+ clockedService.respondToAuthChallenge(client.getClientId(), "PASSWORD_VERIFIER", session,+ Map.of(+ "USERNAME", "bob",+ "PASSWORD_CLAIM_SIGNATURE", "any-sig",+ "TIMESTAMP", "Wed Apr 8 12:00:00 UTC 2026"+ )));+ assertEquals("NotAuthorizedException", ex.getErrorCode());+ assertEquals("Invalid session for the user, session is expired.", ex.getMessage());+ }++ @Test+ void respondToAuthChallengeBeforeSrpSessionExpiryStillWorks() {+ MutableClock clock = new MutableClock();+ CognitoService clockedService = serviceWithClock(clock);+ String password = "Password123!";+ UserPool pool = clockedService.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");+ clockedService.adminCreateUser(pool.getId(), "bob", Map.of("email", "[email protected]"), null);+ clockedService.adminSetUserPassword(pool.getId(), "bob", password, true);+ UserPoolClient client =+ clockedService.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());++ Map<String, Object> initResult = clockedService.initiateAuth(client.getClientId(), "USER_SRP_AUTH",+ Map.of("USERNAME", "bob", "SRP_A", "ABCDEF1234567890"));+ String session = (String) initResult.get("Session");++ clock.advance(Duration.ofMinutes(2));++ AwsException ex = assertThrows(AwsException.class, () ->+ clockedService.respondToAuthChallenge(client.getClientId(), "PASSWORD_VERIFIER", session,+ Map.of(+ "USERNAME", "bob",+ "PASSWORD_CLAIM_SIGNATURE", "invalid-sig",+ "TIMESTAMP", "Wed Apr 8 12:00:00 UTC 2026"+ )));+ assertEquals("NotAuthorizedException", ex.getErrorCode());+ assertNotEquals("Invalid session for the user, session is expired.", ex.getMessage(),+ "a session still within AuthSessionValidity should fail signature checking, not expiry");+ }++ @Test+ void respondToAuthChallengeAfterUserAuthPasswordSessionExpiryRejects() {+ MutableClock clock = new MutableClock();+ CognitoService clockedService = serviceWithClock(clock);+ UserPool pool = clockedService.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");+ clockedService.adminCreateUser(pool.getId(), "alice", Map.of("email", "[email protected]"), "TempPass1!");+ clockedService.adminSetUserPassword(pool.getId(), "alice", "Perm1234!", true);+ UserPoolClient client = openClient(clockedService, pool.getId(), "c", false);++ Map<String, Object> initResult = clockedService.initiateAuth(client.getClientId(), "USER_AUTH",+ Map.of("USERNAME", "alice", "PREFERRED_CHALLENGE", "PASSWORD"));+ String session = (String) initResult.get("Session");++ clock.advance(Duration.ofMinutes(3).plusSeconds(1));++ AwsException ex = assertThrows(AwsException.class, () ->+ clockedService.respondToAuthChallenge(client.getClientId(), "PASSWORD", session,+ Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")));+ assertEquals("NotAuthorizedException", ex.getErrorCode());+ assertEquals("Invalid session for the user, session is expired.", ex.getMessage());+ }+// =========================================================================// USER_AUTH (choice-based) flow// =========================================================================