Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(cognito): hide unknown users in USER_AUTH (#4478)

XuJian9c93e6ab7b52
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 042f4c4da2..626b71fdf0 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
@@ -23,11 +23,13 @@ import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
+import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Function;
/**
@@ -50,13 +52,7 @@ 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);
+ static final int MAX_USER_AUTH_SESSIONS_PER_PARTITION = 4_096;
private final CognitoService service;
private final LambdaService lambdaService;
@@ -64,12 +60,14 @@ final class CognitoAuthFlowHandler {
private final Clock clock;
private final ConcurrentHashMap<String, SrpSession> srpSessions = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, CustomAuthToken> customAuthSessions = new ConcurrentHashMap<>();
- private final ConcurrentHashMap<String, UserAuthSession> userAuthSessions = new ConcurrentHashMap<>();
+ private final Object userAuthSessionLock = new Object();
+ private final LinkedHashMap<String, UserAuthSession> userAuthSessions = new LinkedHashMap<>();
+ private final LinkedHashMap<String, UserAuthSession> simulatedUserAuthSessions = new LinkedHashMap<>();
private record SrpSession(String userPoolId, String username, String clientId,
String aHex, String bHex, String bPublicHex,
String secretBlockBase64, Map<String, String> clientMetadata,
- Instant issuedAt) {}
+ Instant expiresAt) {}
/**
* Correlates a USER_AUTH challenge response back to the InitiateAuth/RespondToAuthChallenge
@@ -79,7 +77,7 @@ final class CognitoAuthFlowHandler {
* caller trigger an OTP send without ever starting a flow.
*/
private record UserAuthSession(String userPoolId, String username, String clientId, String challengeName,
- Instant issuedAt) {}
+ Instant expiresAt, boolean userExists) {}
static final class CustomAuthSession {
final String userPoolId;
@@ -101,7 +99,7 @@ final class CognitoAuthFlowHandler {
* 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) {}
+ private record CustomAuthToken(CustomAuthSession state, Instant expiresAt) {}
CognitoAuthFlowHandler(CognitoService service, LambdaService lambdaService, RegionResolver regionResolver,
Clock clock) {
@@ -112,11 +110,19 @@ final class CognitoAuthFlowHandler {
}
/**
- * True once {@code issuedAt} is older than {@link #AUTH_SESSION_VALIDITY}, matching the
- * NotAuthorizedException AWS returns for an expired InitiateAuth/RespondToAuthChallenge session.
+ * Each token retains the issuing client's validity, so purging one client's sessions cannot
+ * expire another client's longer-lived challenge.
*/
- private boolean sessionExpired(Instant issuedAt) {
- return clock.instant().isAfter(issuedAt.plus(AUTH_SESSION_VALIDITY));
+ private static Instant sessionExpiry(UserPoolClient client, Instant issuedAt) {
+ return issuedAt.plus(Duration.ofMinutes(client.getAuthSessionValidity()));
+ }
+
+ private boolean sessionExpired(Instant expiresAt) {
+ return sessionExpired(expiresAt, clock.instant());
+ }
+
+ private static boolean sessionExpired(Instant expiresAt, Instant now) {
+ return now.isAfter(expiresAt);
}
private static AwsException sessionExpiredException() {
@@ -125,14 +131,14 @@ final class CognitoAuthFlowHandler {
}
/** 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()));
+ private void issueCustomAuthToken(String sessionToken, CustomAuthSession state, UserPoolClient client) {
+ purgeExpired(customAuthSessions, CustomAuthToken::expiresAt);
+ customAuthSessions.put(sessionToken, new CustomAuthToken(state, sessionExpiry(client, 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())));
+ private <V> void purgeExpired(ConcurrentHashMap<String, V> sessions, Function<V, Instant> expiresAtOf) {
+ sessions.entrySet().removeIf(entry -> sessionExpired(expiresAtOf.apply(entry.getValue())));
}
// ──────────────────────────── Public entry points ────────────────────────────
@@ -286,15 +292,15 @@ final class CognitoAuthFlowHandler {
return handleSelectChallenge(pool, client, session, responses, clientMetadata);
}
if ("PASSWORD".equals(challengeName)) {
- consumeUserAuthSession(pool, client, session, "PASSWORD");
+ rejectSimulatedUser(consumeUserAuthSession(pool, client, session, "PASSWORD"));
return authenticateWithPassword(pool, client, responses, clientMetadata);
}
if ("PASSWORD_SRP".equals(challengeName)) {
- consumeUserAuthSession(pool, client, session, "PASSWORD_SRP");
+ rejectSimulatedUser(consumeUserAuthSession(pool, client, session, "PASSWORD_SRP"));
return handleUserSrpAuth(pool, client, responses, clientMetadata);
}
if ("EMAIL_OTP".equals(challengeName) || "SMS_OTP".equals(challengeName)) {
- consumeUserAuthSession(pool, client, session, challengeName);
+ rejectSimulatedUser(consumeUserAuthSession(pool, client, session, challengeName));
return handleOtpChallengeResponse(pool, client, challengeName, responses, clientMetadata);
}
if ("NEW_PASSWORD_REQUIRED".equals(challengeName)) {
@@ -539,11 +545,11 @@ final class CognitoAuthFlowHandler {
new java.security.SecureRandom().nextBytes(secretBlock);
String secretBlockBase64 = Base64.getEncoder().encodeToString(secretBlock);
- purgeExpired(srpSessions, SrpSession::issuedAt);
+ purgeExpired(srpSessions, SrpSession::expiresAt);
srpSessions.put(sessionToken, new SrpSession(
pool.getId(), user.getUsername(), client.getClientId(),
aHex, bHex, bPublicHex, secretBlockBase64,
- clientMetadata == null ? Map.of() : clientMetadata, clock.instant()));
+ clientMetadata == null ? Map.of() : clientMetadata, sessionExpiry(client, clock.instant())));
Map<String, Object> result = new HashMap<>();
result.put("ChallengeName", "PASSWORD_VERIFIER");
@@ -564,7 +570,7 @@ final class CognitoAuthFlowHandler {
CustomAuthToken customToken =
session == null ? null : customAuthSessions.get(session);
if (customToken != null) {
- if (sessionExpired(customToken.issuedAt())) {
+ if (sessionExpired(customToken.expiresAt())) {
customAuthSessions.remove(session);
throw sessionExpiredException();
}
@@ -574,7 +580,7 @@ final class CognitoAuthFlowHandler {
SrpSession srp = srpSessions.get(session);
if (srp == null) throw new AwsException("NotAuthorizedException", "Session not found", 400);
- if (sessionExpired(srp.issuedAt())) {
+ if (sessionExpired(srp.expiresAt())) {
srpSessions.remove(session);
throw sessionExpiredException();
}
@@ -642,7 +648,16 @@ final class CognitoAuthFlowHandler {
throw new AwsException("InvalidParameterException", "USERNAME is required", 400);
}
validateSecretHash(client, params, username);
- CognitoUser user = service.adminGetUser(pool.getId(), username);
+ CognitoUser user;
+ try {
+ user = service.adminGetUser(pool.getId(), username);
+ } catch (AwsException exception) {
+ if (!"UserNotFoundException".equals(exception.getErrorCode())
+ || !"ENABLED".equals(client.getPreventUserExistenceErrors())) {
+ throw exception;
+ }
+ return simulatedUserAuthChallenge(pool, client, username);
+ }
requireSignInEligible(user);
List<String> available = availableUserAuthChallenges(user);
@@ -667,7 +682,7 @@ final class CognitoAuthFlowHandler {
private Map<String, Object> handleSelectChallenge(UserPool pool, UserPoolClient client, String session,
Map<String, String> responses,
Map<String, String> clientMetadata) {
- consumeUserAuthSession(pool, client, session, "SELECT_CHALLENGE");
+ rejectSimulatedUser(consumeUserAuthSession(pool, client, session, "SELECT_CHALLENGE"));
String username = responses.get("USERNAME");
String answer = responses.get("ANSWER");
if (username == null || answer == null) {
@@ -759,11 +774,30 @@ final class CognitoAuthFlowHandler {
private Map<String, Object> userAuthChallengeResponse(UserPool pool, UserPoolClient client, CognitoUser user,
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,
- clock.instant()));
+ return userAuthChallengeResponse(pool, client, user.getUsername(), challengeName, available,
+ challengeParameters, true);
+ }
+
+ private Map<String, Object> userAuthChallengeResponse(UserPool pool, UserPoolClient client, String username,
+ String challengeName, List<String> available,
+ Map<String, String> challengeParameters,
+ boolean userExists) {
+ String session = buildSessionToken(pool.getId(), username, client.getClientId());
+ synchronized (userAuthSessionLock) {
+ Instant issuedAt = clock.instant();
+ // Each entry uses its own client's lifetime, even after a clock rollback.
+ userAuthSessions.values().removeIf(state -> sessionExpired(state.expiresAt(), issuedAt));
+ simulatedUserAuthSessions.values().removeIf(state -> sessionExpired(state.expiresAt(), issuedAt));
+ LinkedHashMap<String, UserAuthSession> store = userExists
+ ? userAuthSessions : simulatedUserAuthSessions;
+ if (store.size() >= MAX_USER_AUTH_SESSIONS_PER_PARTITION) {
+ Iterator<String> tokens = store.keySet().iterator();
+ tokens.next();
+ tokens.remove();
+ }
+ store.put(session, new UserAuthSession(pool.getId(), username, client.getClientId(),
+ challengeName, sessionExpiry(client, issuedAt), userExists));
+ }
Map<String, Object> result = new HashMap<>();
result.put("ChallengeName", challengeName);
result.put("Session", session);
@@ -779,18 +813,62 @@ final class CognitoAuthFlowHandler {
* {@code expectedChallenge} against this same pool and client, and consumes it so it cannot
* be replayed against a second RespondToAuthChallenge call.
*/
- private void consumeUserAuthSession(UserPool pool, UserPoolClient client, String session,
- String expectedChallenge) {
- UserAuthSession state = session == null ? null : userAuthSessions.remove(session);
+ private UserAuthSession consumeUserAuthSession(UserPool pool, UserPoolClient client, String session,
+ String expectedChallenge) {
+ UserAuthSession state;
+ synchronized (userAuthSessionLock) {
+ state = session == null ? null : userAuthSessions.remove(session);
+ if (state == null && session != null) {
+ state = simulatedUserAuthSessions.remove(session);
+ }
+ }
if (state == null || !expectedChallenge.equals(state.challengeName())) {
throw new AwsException("NotAuthorizedException", "Session not found", 400);
}
- if (sessionExpired(state.issuedAt())) {
+ if (sessionExpired(state.expiresAt())) {
throw sessionExpiredException();
}
if (!state.userPoolId().equals(pool.getId()) || !state.clientId().equals(client.getClientId())) {
throw new AwsException("NotAuthorizedException", "Session does not match client", 400);
}
+ return state;
+ }
+
+ private void rejectSimulatedUser(UserAuthSession session) {
+ if (!session.userExists()) {
+ throw new AwsException("NotAuthorizedException", INCORRECT_CREDENTIALS, 400);
+ }
+ }
+
+ private Map<String, Object> simulatedUserAuthChallenge(UserPool pool, UserPoolClient client, String username) {
+ List<String> available = configuredUserAuthChallenges(pool);
+ if (available.isEmpty()) {
+ throw new AwsException("NotAuthorizedException", INCORRECT_CREDENTIALS, 400);
+ }
+ String challenge = available.get(ThreadLocalRandom.current().nextInt(available.size()));
+ return userAuthChallengeResponse(pool, client, username, challenge, available,
+ Map.of("USERNAME", username), false);
+ }
+
+ private List<String> configuredUserAuthChallenges(UserPool pool) {
+ Map<String, Object> policies = pool.getPolicies();
+ if (policies == null || !(policies.get("SignInPolicy") instanceof Map<?, ?> signInPolicy)) {
+ return List.of("PASSWORD");
+ }
+ Object configuredFactors = signInPolicy.get("AllowedFirstAuthFactors");
+ if (!(configuredFactors instanceof List<?> factors) || factors.isEmpty()) {
+ return List.of("PASSWORD");
+ }
+
+ List<String> supported = new ArrayList<>();
+ for (Object factor : factors) {
+ if (factor instanceof String name
+ && ("PASSWORD".equals(name) || "EMAIL_OTP".equals(name) || "SMS_OTP".equals(name))
+ && !supported.contains(name)) {
+ supported.add(name);
+ }
+ }
+ return supported;
}
/** The set of USER_AUTH challenges this user currently qualifies for. */
@@ -871,7 +949,7 @@ final class CognitoAuthFlowHandler {
createAuthChallenge(pool, client, user, state, challengeName), publicParams);
String sessionToken = buildSessionToken(pool.getId(), user.getUsername(), client.getClientId());
- issueCustomAuthToken(sessionToken, state);
+ issueCustomAuthToken(sessionToken, state, client);
Map<String, Object> result = new HashMap<>();
result.put("ChallengeName", challengeName);
@@ -888,7 +966,7 @@ final class CognitoAuthFlowHandler {
if (token == null) {
throw new AwsException("NotAuthorizedException", "Session not found", 400);
}
- if (sessionExpired(token.issuedAt())) {
+ if (sessionExpired(token.expiresAt())) {
customAuthSessions.remove(session);
throw sessionExpiredException();
}
@@ -941,7 +1019,7 @@ final class CognitoAuthFlowHandler {
String newSession = buildSessionToken(pool.getId(), state.username, client.getClientId());
customAuthSessions.remove(session);
- issueCustomAuthToken(newSession, state);
+ issueCustomAuthToken(newSession, state, client);
Map<String, Object> result = new HashMap<>();
result.put("ChallengeName", nextChallenge);
@@ -1001,7 +1079,7 @@ final class CognitoAuthFlowHandler {
String newSession = buildSessionToken(pool.getId(), state.username, client.getClientId());
customAuthSessions.remove(session);
- issueCustomAuthToken(newSession, state);
+ issueCustomAuthToken(newSession, state, client);
Map<String, Object> result = new HashMap<>();
result.put("ChallengeName", nextChallenge);
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java
index e23ab98b5d..c586ec9d05 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java
@@ -2967,6 +2967,62 @@ class CognitoIntegrationTest {
.body("__type", equalTo("InvalidParameterException"));
}
+ @Test
+ @Order(111)
+ void preventUserExistenceErrorsHidesUnknownUserAuthUsersOverTheWire() throws Exception {
+ String userAuthPoolId = cognitoJson("CreateUserPool", """
+ {
+ "PoolName": "HiddenUserAuthWirePool",
+ "UsernameAttributes": ["phone_number"],
+ "Policies": {
+ "SignInPolicy": { "AllowedFirstAuthFactors": ["PASSWORD", "SMS_OTP"] }
+ }
+ }
+ """).path("UserPool").path("Id").asText();
+ String userAuthClientId = cognitoJson("CreateUserPoolClient", """
+ {
+ "UserPoolId": "%s",
+ "ClientName": "hidden-user-auth-client",
+ "ExplicitAuthFlows": ["ALLOW_USER_AUTH"],
+ "PreventUserExistenceErrors": "ENABLED"
+ }
+ """.formatted(userAuthPoolId)).path("UserPoolClient").path("ClientId").asText();
+
+ JsonNode challengeResult = cognitoJson("InitiateAuth", """
+ {
+ "ClientId": "%s",
+ "AuthFlow": "USER_AUTH",
+ "AuthParameters": {
+ "USERNAME": "+5511900000000",
+ "PREFERRED_CHALLENGE": "SMS_OTP"
+ }
+ }
+ """.formatted(userAuthClientId));
+
+ String challenge = challengeResult.path("ChallengeName").asText();
+ assertTrue(List.of("PASSWORD", "SMS_OTP").contains(challenge),
+ "the simulated challenge must come from the configured first factors: " + challengeResult);
+ assertFalse(challengeResult.path("Session").asText().isBlank());
+ assertEquals(List.of("PASSWORD", "SMS_OTP"), textValues(challengeResult.path("AvailableChallenges")));
+
+ String answerName = "SMS_OTP".equals(challenge) ? "SMS_OTP_CODE" : "PASSWORD";
+ cognitoAction("RespondToAuthChallenge", """
+ {
+ "ClientId": "%s",
+ "ChallengeName": "%s",
+ "Session": "%s",
+ "ChallengeResponses": {
+ "USERNAME": "+5511900000000",
+ "%s": "invalid"
+ }
+ }
+ """.formatted(userAuthClientId, challenge, challengeResult.path("Session").asText(), answerName))
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("NotAuthorizedException"))
+ .body("message", equalTo("Incorrect username or password"));
+ }
+
private static List<String> textValues(JsonNode array) {
List<String> values = new ArrayList<>();
for (JsonNode value : array) {
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 5bee31439b..7fb0cdecb8 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
@@ -1101,7 +1101,7 @@ class CognitoLambdaTriggersTest {
String session = (String) clockedService.initiateAuth(client.getClientId(), "CUSTOM_AUTH",
Map.of("USERNAME", "alice")).get("Session");
- clock.advance(Duration.ofMinutes(3).plusSeconds(1));
+ clock.advance(Duration.ofMinutes(client.getAuthSessionValidity()).plusSeconds(1));
AwsException ex = assertThrows(AwsException.class, () ->
clockedService.respondToAuthChallenge(client.getClientId(), "CUSTOM_CHALLENGE", session,
@@ -1111,6 +1111,45 @@ class CognitoLambdaTriggersTest {
verify(lambdaService, never()).invoke(anyString(), eq("arn:aws:lambda:::verify"), any(byte[].class), any());
}
+ @Test
+ void customAuthSessionUsesConfiguredClientValidityAcrossOtherClientInitiation() {
+ MutableClock clock = new MutableClock();
+ CognitoService clockedService = serviceWithClock(clock);
+ UserPoolClient longClient = customAuthClient(clockedService);
+ longClient.setAuthSessionValidity(10);
+ UserPoolClient shortClient = clockedService.createUserPoolClient(
+ longClient.getUserPoolId(), "short", 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);
+
+ when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::define"), any(byte[].class), any()))
+ .thenReturn(ok(Map.of("challengeName", "CUSTOM_CHALLENGE")))
+ .thenReturn(ok(Map.of("challengeName", "CUSTOM_CHALLENGE")))
+ .thenReturn(ok(Map.of("issueTokens", true)))
+ .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"))));
+ when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::verify"), any(byte[].class), any()))
+ .thenReturn(ok(Map.of("answerCorrect", true)));
+
+ String longSession = (String) clockedService.initiateAuth(longClient.getClientId(), "CUSTOM_AUTH",
+ Map.of("USERNAME", "alice")).get("Session");
+ clock.advance(Duration.ofMinutes(4));
+ clockedService.initiateAuth(shortClient.getClientId(), "CUSTOM_AUTH", Map.of("USERNAME", "alice"));
+
+ Map<String, Object> result = clockedService.respondToAuthChallenge(longClient.getClientId(),
+ "CUSTOM_CHALLENGE", longSession, Map.of("USERNAME", "alice", "ANSWER", "blue"));
+ assertNotNull(result.get("AuthenticationResult"));
+
+ String expiringSession = (String) clockedService.initiateAuth(longClient.getClientId(), "CUSTOM_AUTH",
+ Map.of("USERNAME", "alice")).get("Session");
+ clock.advance(Duration.ofMinutes(longClient.getAuthSessionValidity()).plusSeconds(1));
+ AwsException expired = assertThrows(AwsException.class, () -> clockedService.respondToAuthChallenge(
+ longClient.getClientId(), "CUSTOM_CHALLENGE", expiringSession,
+ Map.of("USERNAME", "alice", "ANSWER", "blue")));
+ assertEquals("Invalid session for the user, session is expired.", expired.getMessage());
+ }
+
@Test
void 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.java
index 5fe9f6d0fa..3786ff1cdd 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
@@ -2431,7 +2431,7 @@ class CognitoServiceTest {
Map.of("USERNAME", "bob", "SRP_A", "ABCDEF1234567890"));
String session = (String) initResult.get("Session");
- clock.advance(Duration.ofMinutes(3).plusSeconds(1));
+ clock.advance(Duration.ofMinutes(client.getAuthSessionValidity()).plusSeconds(1));
AwsException ex = assertThrows(AwsException.class, () ->
clockedService.respondToAuthChallenge(client.getClientId(), "PASSWORD_VERIFIER", session,
@@ -2473,6 +2473,34 @@ class CognitoServiceTest {
"a session still within AuthSessionValidity should fail signature checking, not expiry");
}
+ @Test
+ void srpSessionUsesConfiguredClientValidity() {
+ MutableClock clock = new MutableClock();
+ CognitoService clockedService = serviceWithClock(clock);
+ 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", "Password123!", true);
+ UserPoolClient client = clockedService.createUserPoolClient(
+ pool.getId(), "c", false, false, List.of(), List.of());
+ client.setAuthSessionValidity(15);
+
+ String session = (String) clockedService.initiateAuth(client.getClientId(), "USER_SRP_AUTH",
+ Map.of("USERNAME", "bob", "SRP_A", "ABCDEF1234567890")).get("Session");
+ Map<String, String> invalidSignature = Map.of("USERNAME", "bob",
+ "PASSWORD_CLAIM_SIGNATURE", "invalid-sig", "TIMESTAMP", "Wed Apr 8 12:00:00 UTC 2026");
+
+ clock.advance(Duration.ofMinutes(4));
+ AwsException beforeExpiry = assertThrows(AwsException.class, () -> clockedService.respondToAuthChallenge(
+ client.getClientId(), "PASSWORD_VERIFIER", session, invalidSignature));
+ assertEquals("NotAuthorizedException", beforeExpiry.getErrorCode());
+ assertNotEquals("Invalid session for the user, session is expired.", beforeExpiry.getMessage());
+
+ clock.advance(Duration.ofMinutes(client.getAuthSessionValidity() - 4).plusSeconds(1));
+ AwsException afterExpiry = assertThrows(AwsException.class, () -> clockedService.respondToAuthChallenge(
+ client.getClientId(), "PASSWORD_VERIFIER", session, invalidSignature));
+ assertEquals("Invalid session for the user, session is expired.", afterExpiry.getMessage());
+ }
+
@Test
void respondToAuthChallengeAfterUserAuthPasswordSessionExpiryRejects() {
MutableClock clock = new MutableClock();
@@ -2486,7 +2514,7 @@ class CognitoServiceTest {
Map.of("USERNAME", "alice", "PREFERRED_CHALLENGE", "PASSWORD"));
String session = (String) initResult.get("Session");
- clock.advance(Duration.ofMinutes(3).plusSeconds(1));
+ clock.advance(Duration.ofMinutes(client.getAuthSessionValidity()).plusSeconds(1));
AwsException ex = assertThrows(AwsException.class, () ->
clockedService.respondToAuthChallenge(client.getClientId(), "PASSWORD", session,
@@ -2495,6 +2523,62 @@ class CognitoServiceTest {
assertEquals("Invalid session for the user, session is expired.", ex.getMessage());
}
+ @Test
+ void userAuthSessionKeepsItsOwnValidityWhenAnotherClientPurgesSessions() {
+ 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(), "Temp1234!");
+ clockedService.adminSetUserPassword(pool.getId(), "alice", "Perm1234!", true);
+ UserPoolClient longClient = openClient(clockedService, pool.getId(), "long", false);
+ longClient.setAuthSessionValidity(10);
+ UserPoolClient shortClient = openClient(clockedService, pool.getId(), "short", false);
+
+ String longSession = (String) clockedService.initiateAuth(longClient.getClientId(), "USER_AUTH",
+ Map.of("USERNAME", "alice", "PREFERRED_CHALLENGE", "PASSWORD")).get("Session");
+ clock.advance(Duration.ofMinutes(4));
+ clockedService.initiateAuth(shortClient.getClientId(), "USER_AUTH",
+ Map.of("USERNAME", "alice", "PREFERRED_CHALLENGE", "PASSWORD"));
+
+ Map<String, Object> result = clockedService.respondToAuthChallenge(longClient.getClientId(),
+ "PASSWORD", longSession, Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!"));
+ assertNotNull(result.get("AuthenticationResult"));
+
+ String expiringSession = (String) clockedService.initiateAuth(longClient.getClientId(), "USER_AUTH",
+ Map.of("USERNAME", "alice", "PREFERRED_CHALLENGE", "PASSWORD")).get("Session");
+ clock.advance(Duration.ofMinutes(longClient.getAuthSessionValidity()).plusSeconds(1));
+ AwsException expired = assertThrows(AwsException.class, () -> clockedService.respondToAuthChallenge(
+ longClient.getClientId(), "PASSWORD", expiringSession,
+ Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")));
+ assertEquals("Invalid session for the user, session is expired.", expired.getMessage());
+ }
+
+ @Test
+ void simulatedUserAuthSessionUsesConfiguredClientValidity() {
+ MutableClock clock = new MutableClock();
+ CognitoService clockedService = serviceWithClock(clock);
+ UserPool pool = clockedService.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");
+ UserPoolClient client = openClient(clockedService, pool.getId(), "c", false);
+ client.setAuthSessionValidity(10);
+ client.setPreventUserExistenceErrors("ENABLED");
+
+ String liveSession = (String) clockedService.initiateAuth(client.getClientId(), "USER_AUTH",
+ Map.of("USERNAME", "missing-1")).get("Session");
+ clock.advance(Duration.ofMinutes(4));
+ AwsException live = assertThrows(AwsException.class, () -> clockedService.respondToAuthChallenge(
+ client.getClientId(), "PASSWORD", liveSession,
+ Map.of("USERNAME", "missing-1", "PASSWORD", "anything")));
+ assertEquals("Incorrect username or password", live.getMessage());
+
+ String expiredSession = (String) clockedService.initiateAuth(client.getClientId(), "USER_AUTH",
+ Map.of("USERNAME", "missing-2")).get("Session");
+ clock.advance(Duration.ofMinutes(client.getAuthSessionValidity()).plusSeconds(1));
+ AwsException expired = assertThrows(AwsException.class, () -> clockedService.respondToAuthChallenge(
+ client.getClientId(), "PASSWORD", expiredSession,
+ Map.of("USERNAME", "missing-2", "PASSWORD", "anything")));
+ assertEquals("Invalid session for the user, session is expired.", expired.getMessage());
+ }
+
// =========================================================================
// USER_AUTH (choice-based) flow
// =========================================================================
@@ -2552,6 +2636,216 @@ class CognitoServiceTest {
assertEquals("InvalidParameterException", ex.getErrorCode());
}
+ @Test
+ void initiateAuthWithUserAuthHidesAnUnknownUserWhenPreventionIsEnabled() {
+ UserPool pool = service.createUserPool(Map.of(
+ "PoolName", "TestPool",
+ "Policies", Map.of("SignInPolicy", Map.of(
+ "AllowedFirstAuthFactors", List.of("PASSWORD", "SMS_OTP")))), "us-east-1");
+ UserPoolClient client = openClient(service, pool.getId(), "c", false);
+ service.describeUserPoolClient(client.getClientId()).setPreventUserExistenceErrors("ENABLED");
+
+ Map<String, Object> result = service.initiateAuth(client.getClientId(), "USER_AUTH", Map.of(
+ "USERNAME", "+5511900000000",
+ "PREFERRED_CHALLENGE", "SMS_OTP"));
+
+ String challenge = (String) result.get("ChallengeName");
+ assertTrue(List.of("PASSWORD", "SMS_OTP").contains(challenge),
+ "the simulated challenge must come from the pool's allowed factors: " + challenge);
+ assertEquals(List.of("PASSWORD", "SMS_OTP"), result.get("AvailableChallenges"));
+ String session = (String) result.get("Session");
+ assertNotNull(session);
+
+ Map<String, String> response = "SMS_OTP".equals(challenge)
+ ? Map.of("USERNAME", "+5511900000000", "SMS_OTP_CODE", "123456")
+ : Map.of("USERNAME", "+5511900000000", "PASSWORD", "anything");
+ AwsException exception = assertThrows(AwsException.class, () -> service.respondToAuthChallenge(
+ client.getClientId(), challenge, session, response));
+ assertEquals("NotAuthorizedException", exception.getErrorCode());
+ assertEquals("Incorrect username or password", exception.getMessage());
+ }
+
+ @Test
+ void initiateAuthWithUserAuthDefaultsAnUnknownUserToPasswordWithoutASignInPolicy() {
+ UserPool pool = service.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");
+ UserPoolClient client = openClient(service, pool.getId(), "c", false);
+ service.describeUserPoolClient(client.getClientId()).setPreventUserExistenceErrors("ENABLED");
+
+ Map<String, Object> result = service.initiateAuth(client.getClientId(), "USER_AUTH",
+ Map.of("USERNAME", "missing"));
+
+ assertEquals("PASSWORD", result.get("ChallengeName"));
+ assertEquals(List.of("PASSWORD"), result.get("AvailableChallenges"));
+ }
+
+ @Test
+ void initiateAuthWithUserAuthKeepsUserNotFoundForLegacyClients() {
+ UserPool pool = service.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");
+ UserPoolClient client = openClient(service, pool.getId(), "c", false);
+ service.describeUserPoolClient(client.getClientId()).setPreventUserExistenceErrors("LEGACY");
+
+ AwsException exception = assertThrows(AwsException.class, () -> service.initiateAuth(
+ client.getClientId(), "USER_AUTH", Map.of("USERNAME", "missing")));
+
+ assertEquals("UserNotFoundException", exception.getErrorCode());
+ }
+
+ @Test
+ void respondToAuthChallengeRejectsASimulatedUserSessionAfterExpiry() {
+ MutableClock clock = new MutableClock();
+ CognitoService clockedService = serviceWithClock(clock);
+ UserPool pool = clockedService.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");
+ UserPoolClient client = openClient(clockedService, pool.getId(), "c", false);
+ clockedService.describeUserPoolClient(client.getClientId()).setPreventUserExistenceErrors("ENABLED");
+
+ Map<String, Object> initResult = clockedService.initiateAuth(client.getClientId(), "USER_AUTH",
+ Map.of("USERNAME", "missing"));
+ String session = (String) initResult.get("Session");
+ clock.advance(Duration.ofMinutes(client.getAuthSessionValidity()).plusSeconds(1));
+
+ AwsException exception = assertThrows(AwsException.class, () -> clockedService.respondToAuthChallenge(
+ client.getClientId(), "PASSWORD", session,
+ Map.of("USERNAME", "missing", "PASSWORD", "anything")));
+
+ assertEquals("NotAuthorizedException", exception.getErrorCode());
+ assertEquals("Invalid session for the user, session is expired.", exception.getMessage());
+ }
+
+ @Test
+ void initiateAuthWithUserAuthPurgesExpiredSimulatedSessions() {
+ MutableClock clock = new MutableClock();
+ CognitoService clockedService = serviceWithClock(clock);
+ UserPool pool = clockedService.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");
+ UserPoolClient client = openClient(clockedService, pool.getId(), "c", false);
+ clockedService.describeUserPoolClient(client.getClientId()).setPreventUserExistenceErrors("ENABLED");
+
+ Map<String, Object> oldResult = clockedService.initiateAuth(client.getClientId(), "USER_AUTH",
+ Map.of("USERNAME", "missing-old"));
+ String oldSession = (String) oldResult.get("Session");
+ clock.advance(Duration.ofMinutes(client.getAuthSessionValidity()).plusSeconds(1));
+
+ Map<String, Object> newResult = clockedService.initiateAuth(client.getClientId(), "USER_AUTH",
+ Map.of("USERNAME", "missing-new"));
+
+ AwsException oldException = assertThrows(AwsException.class, () -> clockedService.respondToAuthChallenge(
+ client.getClientId(), "PASSWORD", oldSession,
+ Map.of("USERNAME", "missing-old", "PASSWORD", "anything")));
+ assertEquals("Session not found", oldException.getMessage());
+
+ String newSession = (String) newResult.get("Session");
+ AwsException newException = assertThrows(AwsException.class, () -> clockedService.respondToAuthChallenge(
+ client.getClientId(), "PASSWORD", newSession,
+ Map.of("USERNAME", "missing-new", "PASSWORD", "anything")));
+ assertEquals("Incorrect username or password", newException.getMessage());
+ }
+
+ @Test
+ void initiateAuthWithUserAuthPurgesExpiredSessionsAfterClockRollback() {
+ MutableClock clock = new MutableClock();
+ CognitoService clockedService = serviceWithClock(clock);
+ UserPool pool = clockedService.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");
+ UserPoolClient client = openClient(clockedService, pool.getId(), "c", false);
+ clockedService.adminCreateUser(pool.getId(), "alice", Map.of(), "Temp1234!");
+ clockedService.adminSetUserPassword(pool.getId(), "alice", "Perm1234!", true);
+
+ Map<String, Object> firstResult = clockedService.initiateAuth(client.getClientId(), "USER_AUTH",
+ Map.of("USERNAME", "alice", "PREFERRED_CHALLENGE", "PASSWORD"));
+ String firstSession = (String) firstResult.get("Session");
+ clock.advance(Duration.ofMinutes(-10));
+
+ Map<String, Object> rolledBackResult = clockedService.initiateAuth(client.getClientId(), "USER_AUTH",
+ Map.of("USERNAME", "alice", "PREFERRED_CHALLENGE", "PASSWORD"));
+ String rolledBackSession = (String) rolledBackResult.get("Session");
+ clock.advance(Duration.ofMinutes(7));
+
+ clockedService.initiateAuth(client.getClientId(), "USER_AUTH",
+ Map.of("USERNAME", "alice", "PREFERRED_CHALLENGE", "PASSWORD"));
+
+ AwsException expiredException = assertThrows(AwsException.class, () ->
+ clockedService.respondToAuthChallenge(client.getClientId(), "PASSWORD", rolledBackSession,
+ Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")));
+ assertEquals("Session not found", expiredException.getMessage());
+
+ Map<String, Object> authResult = clockedService.respondToAuthChallenge(
+ client.getClientId(), "PASSWORD", firstSession,
+ Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!"));
+ assertNotNull(authResult.get("AuthenticationResult"));
+ }
+
+ @Test
+ void initiateAuthWithUserAuthCapsSimulatedSessionsWithoutEvictingRealSessions() {
+ MutableClock clock = new MutableClock();
+ CognitoService clockedService = serviceWithClock(clock);
+ UserPool pool = clockedService.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");
+ UserPoolClient client = openClient(clockedService, pool.getId(), "c", false);
+ clockedService.describeUserPoolClient(client.getClientId()).setPreventUserExistenceErrors("ENABLED");
+ clockedService.adminCreateUser(pool.getId(), "alice", Map.of(), "Temp1234!");
+ clockedService.adminSetUserPassword(pool.getId(), "alice", "Perm1234!", true);
+
+ Map<String, Object> realResult = clockedService.initiateAuth(client.getClientId(), "USER_AUTH",
+ Map.of("USERNAME", "alice", "PREFERRED_CHALLENGE", "PASSWORD"));
+ String realSession = (String) realResult.get("Session");
+
+ Map<String, Object> firstResult = clockedService.initiateAuth(client.getClientId(), "USER_AUTH",
+ Map.of("USERNAME", "missing-0"));
+ String firstSession = (String) firstResult.get("Session");
+ for (int index = 1; index < CognitoAuthFlowHandler.MAX_USER_AUTH_SESSIONS_PER_PARTITION; index++) {
+ clockedService.initiateAuth(client.getClientId(), "USER_AUTH",
+ Map.of("USERNAME", "missing-" + index));
+ }
+
+ Map<String, Object> newestResult = clockedService.initiateAuth(client.getClientId(), "USER_AUTH",
+ Map.of("USERNAME", "missing-overflow"));
+
+ AwsException firstException = assertThrows(AwsException.class, () -> clockedService.respondToAuthChallenge(
+ client.getClientId(), "PASSWORD", firstSession,
+ Map.of("USERNAME", "missing-0", "PASSWORD", "anything")));
+ assertEquals("Session not found", firstException.getMessage());
+
+ String newestSession = (String) newestResult.get("Session");
+ AwsException newestException = assertThrows(AwsException.class, () -> clockedService.respondToAuthChallenge(
+ client.getClientId(), "PASSWORD", newestSession,
+ Map.of("USERNAME", "missing-overflow", "PASSWORD", "anything")));
+ assertEquals("Incorrect username or password", newestException.getMessage());
+
+ Map<String, Object> authResult = clockedService.respondToAuthChallenge(
+ client.getClientId(), "PASSWORD", realSession,
+ Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!"));
+ assertNotNull(authResult.get("AuthenticationResult"));
+ }
+
+ @Test
+ void initiateAuthWithUserAuthCapsRealSessionsWithinTheirPartition() {
+ MutableClock clock = new MutableClock();
+ CognitoService clockedService = serviceWithClock(clock);
+ UserPool pool = clockedService.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");
+ UserPoolClient client = openClient(clockedService, pool.getId(), "c", false);
+ clockedService.adminCreateUser(pool.getId(), "alice", Map.of(), "Temp1234!");
+ clockedService.adminSetUserPassword(pool.getId(), "alice", "Perm1234!", true);
+
+ Map<String, Object> firstResult = clockedService.initiateAuth(client.getClientId(), "USER_AUTH",
+ Map.of("USERNAME", "alice", "PREFERRED_CHALLENGE", "PASSWORD"));
+ String firstSession = (String) firstResult.get("Session");
+ for (int index = 1; index < CognitoAuthFlowHandler.MAX_USER_AUTH_SESSIONS_PER_PARTITION; index++) {
+ clockedService.initiateAuth(client.getClientId(), "USER_AUTH",
+ Map.of("USERNAME", "alice", "PREFERRED_CHALLENGE", "PASSWORD"));
+ }
+
+ Map<String, Object> newestResult = clockedService.initiateAuth(client.getClientId(), "USER_AUTH",
+ Map.of("USERNAME", "alice", "PREFERRED_CHALLENGE", "PASSWORD"));
+
+ AwsException firstException = assertThrows(AwsException.class, () -> clockedService.respondToAuthChallenge(
+ client.getClientId(), "PASSWORD", firstSession,
+ Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")));
+ assertEquals("Session not found", firstException.getMessage());
+
+ String newestSession = (String) newestResult.get("Session");
+ Map<String, Object> authResult = clockedService.respondToAuthChallenge(
+ client.getClientId(), "PASSWORD", newestSession,
+ Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!"));
+ assertNotNull(authResult.get("AuthenticationResult"));
+ }
+
@Test
void initiateAuthWithUserAuthPreferredChallengePasswordThenRespondCompletesAuth() {
UserPool pool = createPoolAndUser();