From faf9c4e64d2ff2cbcdc2a9d238e14230bcd39528 Mon Sep 17 00:00:00 2001 From: James McMahon Date: Tue, 10 Nov 2026 01:13:31 +0000 Subject: [PATCH] fix(cognito): honour case-insensitive sign-in configuration (#7831) --- .../com/floci/test/CognitoEmailCaseTest.java | 74 ++++++ docs/services/cognito.md | 7 + .../cognito/CognitoAuthFlowHandler.java | 11 +- .../aws/services/cognito/CognitoService.java | 60 ++++- .../CognitoEmailCaseIntegrationTest.java | 85 +++++++ .../CognitoMessageMfaIntegrationTest.java | 41 ++++ .../services/cognito/CognitoServiceTest.java | 224 ++++++++++++++++++ .../CognitoSignUpTriggerReentrancyTest.java | 10 +- .../services/cognito/CognitoTotpMfaTest.java | 40 ++++ 9 files changed, 531 insertions(+), 21 deletions(-) create mode 100644 compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoEmailCaseTest.java create mode 100644 src/test/java/io/floci/aws/services/cognito/CognitoEmailCaseIntegrationTest.java diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoEmailCaseTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoEmailCaseTest.java new file mode 100644 index 0000000000..cc9ae6ea64 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoEmailCaseTest.java @@ -0,0 +1,74 @@ +package com.floci.test; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient; +import software.amazon.awssdk.services.cognitoidentityprovider.model.AttributeType; +import software.amazon.awssdk.services.cognitoidentityprovider.model.AuthFlowType; +import software.amazon.awssdk.services.cognitoidentityprovider.model.ExplicitAuthFlowsType; +import software.amazon.awssdk.services.cognitoidentityprovider.model.InitiateAuthResponse; +import software.amazon.awssdk.services.cognitoidentityprovider.model.MessageActionType; +import software.amazon.awssdk.services.cognitoidentityprovider.model.UserNotFoundException; +import software.amazon.awssdk.services.cognitoidentityprovider.model.UsernameAttributeType; + +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@DisplayName("Cognito email sign-in case sensitivity (issue #7828)") +class CognitoEmailCaseTest { + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + @DisplayName("Email sign-in respects the pool's CaseSensitive setting") + void emailSignInRespectsCaseSensitivity(boolean caseSensitive) { + try (CognitoIdentityProviderClient cognito = TestFixtures.cognitoClient()) { + String poolId = cognito.createUserPool(b -> b + .poolName(TestFixtures.uniqueName("email-case")) + .usernameAttributes(UsernameAttributeType.EMAIL) + .usernameConfiguration(c -> c.caseSensitive(caseSensitive))) + .userPool().id(); + try { + String clientId = cognito.createUserPoolClient(b -> b + .userPoolId(poolId) + .clientName("email-case-client") + .explicitAuthFlows(ExplicitAuthFlowsType.ALLOW_USER_PASSWORD_AUTH)) + .userPoolClient().clientId(); + String username = cognito.adminCreateUser(b -> b + .userPoolId(poolId) + .username("fixture@example.com") + .messageAction(MessageActionType.SUPPRESS) + .userAttributes( + AttributeType.builder().name("email").value("fixture@example.com").build(), + AttributeType.builder().name("email_verified").value("true").build())) + .user().username(); + cognito.adminSetUserPassword(b -> b.userPoolId(poolId).username(username) + .password("Valid-password123!").permanent(true)); + + InitiateAuthResponse lowercase = cognito.initiateAuth(b -> b.clientId(clientId) + .authFlow(AuthFlowType.USER_PASSWORD_AUTH) + .authParameters(Map.of("USERNAME", "fixture@example.com", "PASSWORD", "Valid-password123!"))); + assertThat(lowercase.authenticationResult().accessToken()).isNotBlank(); + + if (caseSensitive) { + assertThatThrownBy(() -> cognito.initiateAuth(b -> b.clientId(clientId) + .authFlow(AuthFlowType.USER_PASSWORD_AUTH) + .authParameters(Map.of("USERNAME", "Fixture@Example.com", "PASSWORD", "Valid-password123!")))) + .isInstanceOf(UserNotFoundException.class); + } else { + InitiateAuthResponse mixedCase = cognito.initiateAuth(b -> b.clientId(clientId) + .authFlow(AuthFlowType.USER_PASSWORD_AUTH) + .authParameters(Map.of("USERNAME", "Fixture@Example.com", "PASSWORD", "Valid-password123!"))); + assertThat(mixedCase.authenticationResult().accessToken()).isNotBlank(); + assertThat(mixedCase.authenticationResult().idToken()).isNotBlank(); + assertThat(cognito.adminGetUser(b -> b.userPoolId(poolId).username("Fixture@Example.com")) + .username()).isEqualTo(username); + } + } finally { + cognito.deleteUserPool(b -> b.userPoolId(poolId)); + } + } + } +} diff --git a/docs/services/cognito.md b/docs/services/cognito.md index 7ac230c518..f076ef2144 100644 --- a/docs/services/cognito.md +++ b/docs/services/cognito.md @@ -914,6 +914,13 @@ Floci follows real Cognito semantics for pools created with `UsernameAttributes` Pools **without** `UsernameAttributes` (classic pools, and pools using `AliasAttributes`) keep the literal `Username` you supply, unchanged. +With `UsernameConfiguration.CaseSensitive=false`, username, email and `preferred_username` +lookups and duplicate checks ignore case. An omitted setting or `CaseSensitive=true` keeps +exact matching. Email sign-in still resolves to the same canonical UUID, and `SECRET_HASH` +uses the exact `USERNAME` sent in each request. Challenge responses follow the pool's case-sensitivity +setting too. Floci preserves stored casing in returned usernames, email addresses and +`preferred_username` values. AWS lowercases these values in case-insensitive pools. + ### Token claims Floci mirrors AWS's access-token / ID-token split: diff --git a/src/main/java/io/floci/aws/services/cognito/CognitoAuthFlowHandler.java b/src/main/java/io/floci/aws/services/cognito/CognitoAuthFlowHandler.java index d900c7f71a..51aa85370e 100644 --- a/src/main/java/io/floci/aws/services/cognito/CognitoAuthFlowHandler.java +++ b/src/main/java/io/floci/aws/services/cognito/CognitoAuthFlowHandler.java @@ -443,7 +443,7 @@ final class CognitoAuthFlowHandler { throw new AwsException("NotAuthorizedException", "Session does not match client", 400); } String username = responses.get("USERNAME"); - if (username == null || !username.equals(state.username())) { + if (username == null || !service.signInKey(pool, username).equals(service.signInKey(pool, state.username()))) { throw new AwsException("NotAuthorizedException", "Session does not match user", 400); } validateSecretHash(client, responses, username); @@ -543,13 +543,14 @@ final class CognitoAuthFlowHandler { CognitoUser user = applyNewPasswordAttributes(pool, responses); return continueCustomSrpAuth(pool, client, user, session, state, clientMetadata); } + String username = responses.get("USERNAME"); PasswordChangeSession pending = session == null ? null : passwordChangeSessions.get(session); if (pending == null || sessionExpired(pending.expiresAt()) || !pool.getId().equals(pending.userPoolId()) || !client.getClientId().equals(pending.clientId()) - || !pending.username().equals(responses.get("USERNAME"))) { + || !service.signInKey(pool, pending.username()).equals(service.signInKey(pool, username))) { throw new AwsException("NotAuthorizedException", "Invalid session for the user.", 400); } - validateSecretHash(client, responses, pending.username()); + validateSecretHash(client, responses, username); synchronized (pending) { if (passwordChangeSessions.get(session) != pending || sessionExpired(pending.expiresAt())) { throw new AwsException("NotAuthorizedException", "Session not found", 400); @@ -1002,7 +1003,7 @@ final class CognitoAuthFlowHandler { throw new AwsException("InvalidParameterException", "USERNAME, PASSWORD_CLAIM_SIGNATURE and TIMESTAMP are required", 400); } - if (!username.equals(srp.username())) { + if (!service.signInKey(pool, username).equals(service.signInKey(pool, srp.username()))) { throw new AwsException("NotAuthorizedException", "Session does not match user", 400); } validateSecretHash(client, responses, username); @@ -2529,7 +2530,7 @@ final class CognitoAuthFlowHandler { throw new AwsException("NotAuthorizedException", "Session does not match client", 400); } String username = responses.get("USERNAME"); - if (username == null || !username.equals(state.username())) { + if (username == null || !service.signInKey(pool, username).equals(service.signInKey(pool, state.username()))) { throw new AwsException("NotAuthorizedException", "Session does not match user", 400); } validateSecretHash(client, responses, username); diff --git a/src/main/java/io/floci/aws/services/cognito/CognitoService.java b/src/main/java/io/floci/aws/services/cognito/CognitoService.java index b3600650d0..ed906b1293 100644 --- a/src/main/java/io/floci/aws/services/cognito/CognitoService.java +++ b/src/main/java/io/floci/aws/services/cognito/CognitoService.java @@ -216,7 +216,8 @@ public class CognitoService implements ResourceProvider { } private Object userLock(String poolId, String username) { - String key = userKey(poolId, username); + UserPool pool = poolStore.get(poolId).orElse(null); + String key = userKey(poolId, pool == null ? username : signInKey(pool, username)); return userLocks[Math.floorMod(key.hashCode(), USER_LOCK_STRIPES)]; } @@ -2318,7 +2319,7 @@ public class CognitoService implements ResourceProvider { // Claimed before the username is checked, so an overlapping request for it is refused here // rather than passing the check while this one is in its trigger and invoking the trigger // again. That includes a function calling back for the username it was given. - String inFlightKey = regionResolver.getAccountId() + "::" + userKey(userPoolId, username); + String inFlightKey = regionResolver.getAccountId() + "::" + userKey(userPoolId, signInKey(pool, username)); if (!userCreatesInFlight.add(inFlightKey)) { throw new AwsException("UsernameExistsException", "User already exists", 400); } @@ -2400,7 +2401,7 @@ public class CognitoService implements ResourceProvider { /** The user a RESEND for {@code username} names, refused unless it awaits its first sign-in. */ private CognitoUser resendTarget(UserPool pool, String username) { - CognitoUser existing = userStore.get(userKey(pool.getId(), username)).orElse(null); + CognitoUser existing = findUserByUsername(pool, username); if (usesAliasUsernames(pool) && existing == null) { existing = findUserByAlias(pool.getId(), aliasAttributeForValue(pool, username), username); } @@ -2423,7 +2424,7 @@ public class CognitoService implements ResourceProvider { * {@code AliasExistsException} for a verified alias without ForceAliasCreation. */ private CognitoUser aliasHolderToMove(UserPool pool, String username, boolean forceAliasCreation) { - CognitoUser existing = userStore.get(userKey(pool.getId(), username)).orElse(null); + CognitoUser existing = findUserByUsername(pool, username); String aliasAttribute = null; if (usesAliasUsernames(pool) && existing == null) { aliasAttribute = aliasAttributeForValue(pool, username); @@ -2637,8 +2638,8 @@ public class CognitoService implements ResourceProvider { canonicalUsername = existing != null ? existing.getUsername() : UUID.randomUUID().toString(); resolvedAttributes.put("sub", canonicalUsername); } else { - canonicalUsername = username; - existing = userStore.get(userKey(userPoolId, username)).orElse(null); + existing = findUserByUsername(pool, username); + canonicalUsername = existing == null ? username : existing.getUsername(); } String key = userKey(userPoolId, canonicalUsername); @@ -3510,7 +3511,8 @@ public class CognitoService implements ResourceProvider { .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 400)); String userPoolId = client.getUserPoolId(); - String inFlightKey = regionResolver.getAccountId() + "::" + userKey(userPoolId, username); + UserPool pool = describeUserPool(userPoolId); + String inFlightKey = regionResolver.getAccountId() + "::" + userKey(userPoolId, signInKey(pool, username)); if (!userCreatesInFlight.add(inFlightKey)) { throw new AwsException("UsernameExistsException", "User already exists", 400); } @@ -3632,7 +3634,7 @@ public class CognitoService implements ResourceProvider { private void requireAvailableSignUpUsername(UserPool pool, String username) { boolean exists = usesAliasUsernames(pool) ? findUserByAlias(pool.getId(), aliasAttributeForValue(pool, username), username) != null - : userStore.get(userKey(pool.getId(), username)).isPresent(); + : findUserByUsername(pool, username) != null; if (exists) { throw new AwsException("UsernameExistsException", "User already exists", 400); } @@ -6578,7 +6580,8 @@ public class CognitoService implements ResourceProvider { String prefix = pool.getId() + "::"; boolean conflict = userStore.scan(key -> key.startsWith(prefix)).stream() .filter(candidate -> !candidate.getUsername().equals(currentUser.getUsername())) - .filter(candidate -> value.equals(candidate.getAttributes().get(attributeName))) + .filter(candidate -> matchesSignInAttribute(pool, attributeName, value, + candidate.getAttributes().get(attributeName))) .anyMatch(candidate -> !aliasAttribute || isActiveAliasAttribute(candidate, attributeName)); if (conflict) { @@ -6735,19 +6738,21 @@ public class CognitoService implements ResourceProvider { private boolean matchesAliasOrUsernameAttribute(UserPool pool, CognitoUser user, String username) { - if (username.equals(user.getAttributes().get("sub"))) { + if ((!usesAliasUsernames(pool) + && signInKey(pool, username).equals(signInKey(pool, user.getUsername()))) + || username.equals(user.getAttributes().get("sub"))) { return true; } for (String attribute : pool.getAliasAttributes()) { - if (username.equals(user.getAttributes().get(attribute)) + if (matchesSignInAttribute(pool, attribute, username, user.getAttributes().get(attribute)) && isActiveAliasAttribute(user, attribute)) { return true; } } for (String attribute : pool.getUsernameAttributes()) { - if (username.equals(user.getAttributes().get(attribute))) { + if (matchesSignInAttribute(pool, attribute, username, user.getAttributes().get(attribute))) { return true; } } @@ -6805,11 +6810,40 @@ public class CognitoService implements ResourceProvider { throw new AwsException("InvalidParameterException", expected, 400); } + private boolean isCaseInsensitive(UserPool pool) { + return pool.getUsernameConfiguration() != null + && Boolean.FALSE.equals(pool.getUsernameConfiguration().get("CaseSensitive")); + } + + String signInKey(UserPool pool, String value) { + return value != null && isCaseInsensitive(pool) ? value.toLowerCase(Locale.ROOT) : value; + } + + private boolean matchesSignInAttribute(UserPool pool, String attribute, String supplied, String stored) { + return switch (attribute) { + case "email", "preferred_username" -> signInKey(pool, supplied).equals(signInKey(pool, stored)); + default -> supplied.equals(stored); + }; + } + + private CognitoUser findUserByUsername(UserPool pool, String username) { + CognitoUser exact = userStore.get(userKey(pool.getId(), username)).orElse(null); + if (exact != null || usesAliasUsernames(pool) || !isCaseInsensitive(pool)) { + return exact; + } + String prefix = pool.getId() + "::"; + String key = signInKey(pool, username); + return userStore.scan(k -> k.startsWith(prefix)).stream() + .filter(user -> key.equals(signInKey(pool, user.getUsername()))) + .findFirst().orElse(null); + } + /** Finds the single user in a pool whose {@code aliasAttr} equals {@code aliasValue}, or null. */ private CognitoUser findUserByAlias(String poolId, String aliasAttr, String aliasValue) { + UserPool pool = describeUserPool(poolId); String prefix = poolId + "::"; return userStore.scan(k -> k.startsWith(prefix)).stream() - .filter(u -> aliasValue.equals(u.getAttributes().get(aliasAttr))) + .filter(u -> matchesSignInAttribute(pool, aliasAttr, aliasValue, u.getAttributes().get(aliasAttr))) .findFirst() .orElse(null); } diff --git a/src/test/java/io/floci/aws/services/cognito/CognitoEmailCaseIntegrationTest.java b/src/test/java/io/floci/aws/services/cognito/CognitoEmailCaseIntegrationTest.java new file mode 100644 index 0000000000..862cf565ab --- /dev/null +++ b/src/test/java/io/floci/aws/services/cognito/CognitoEmailCaseIntegrationTest.java @@ -0,0 +1,85 @@ +package io.floci.aws.services.cognito; + +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.UUID; + +import static io.floci.aws.services.cognito.CognitoRestAssuredUtils.cognitoAction; +import static io.floci.aws.services.cognito.CognitoRestAssuredUtils.cognitoJson; +import static org.hamcrest.Matchers.emptyOrNullString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; + +@QuarkusTest +class CognitoEmailCaseIntegrationTest { + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void initiateAuth_caseInsensitiveEmailPool_acceptsMixedCaseEmail() throws Exception { + String poolId = cognitoJson("CreateUserPool", """ + { + "PoolName": "email-case-%s", + "UsernameAttributes": ["email"], + "UsernameConfiguration": { "CaseSensitive": false } + } + """.formatted(UUID.randomUUID())).path("UserPool").path("Id").asText(); + try { + String clientId = cognitoJson("CreateUserPoolClient", """ + { + "UserPoolId": "%s", + "ClientName": "email-case-client", + "ExplicitAuthFlows": ["ALLOW_USER_PASSWORD_AUTH"] + } + """.formatted(poolId)).path("UserPoolClient").path("ClientId").asText(); + String username = cognitoJson("AdminCreateUser", """ + { + "UserPoolId": "%s", + "Username": "fixture@example.com", + "TemporaryPassword": "Temporary-password123!", + "MessageAction": "SUPPRESS", + "UserAttributes": [ + { "Name": "email", "Value": "fixture@example.com" }, + { "Name": "email_verified", "Value": "true" } + ] + } + """.formatted(poolId)).path("User").path("Username").asText(); + cognitoAction("AdminSetUserPassword", """ + { + "UserPoolId": "%s", + "Username": "%s", + "Password": "Valid-password123!", + "Permanent": true + } + """.formatted(poolId, username)).then().statusCode(200); + + for (String email : List.of("fixture@example.com", "Fixture@Example.com")) { + cognitoAction("InitiateAuth", """ + { + "ClientId": "%s", + "AuthFlow": "USER_PASSWORD_AUTH", + "AuthParameters": { + "USERNAME": "%s", + "PASSWORD": "Valid-password123!" + } + } + """.formatted(clientId, email)) + .then().statusCode(200) + .body("AuthenticationResult.ExpiresIn", equalTo(3600)) + .body("AuthenticationResult.AccessToken", not(emptyOrNullString())) + .body("AuthenticationResult.IdToken", not(emptyOrNullString())); + } + } finally { + cognitoAction("DeleteUserPool", """ + { "UserPoolId": "%s" } + """.formatted(poolId)).then().statusCode(200); + } + } +} diff --git a/src/test/java/io/floci/aws/services/cognito/CognitoMessageMfaIntegrationTest.java b/src/test/java/io/floci/aws/services/cognito/CognitoMessageMfaIntegrationTest.java index 478f7d67f9..0994669a97 100644 --- a/src/test/java/io/floci/aws/services/cognito/CognitoMessageMfaIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cognito/CognitoMessageMfaIntegrationTest.java @@ -6,7 +6,10 @@ import io.floci.aws.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import java.util.Locale; import java.util.UUID; import java.util.concurrent.ThreadLocalRandom; @@ -37,6 +40,44 @@ class CognitoMessageMfaIntegrationTest { RestAssuredJsonUtils.configureAwsContentTypes(); } + @ParameterizedTest + @ValueSource(strings = {"false", "true", "default"}) + void smsChallengeRespectsUsernameCaseSensitivity(String setting) throws Exception { + String configuration = "default".equals(setting) ? "" + : ",\"UsernameConfiguration\":{\"CaseSensitive\":" + setting + "}"; + String poolId = cognitoJson("CreateUserPool", "{\"PoolName\":\"MfaCasePool\"" + configuration + "}") + .path("UserPool").path("Id").asText(); + try { + cognitoJson("SetUserPoolMfaConfig", """ + {"UserPoolId":"%s","MfaConfiguration":"ON",%s} + """.formatted(poolId, SMS_CONFIG)); + String clientId = createClient(poolId); + User user = createUser(poolId); + User variant = new User(user.username().toUpperCase(Locale.ROOT), user.phone(), user.email()); + JsonNode challenge = passwordLogin(clientId, "false".equals(setting) ? variant : user); + assertEquals("SMS_MFA", challenge.path("ChallengeName").asText()); + String code = CognitoCodes.sixDigitCode(latestSms(user.phone())); + cognitoAction("RespondToAuthChallenge", """ + {"ClientId":"%s","ChallengeName":"SMS_MFA","Session":"%s", + "ChallengeResponses":{"SMS_MFA_CODE":"%s"}} + """.formatted(clientId, challenge.path("Session").asText(), code)) + .then().statusCode(400).body("__type", equalTo("NotAuthorizedException")); + cognitoAction("RespondToAuthChallenge", respond(clientId, "SMS_MFA", challenge, + new User("other", user.phone(), user.email()), "SMS_MFA_CODE", code)) + .then().statusCode(400).body("__type", equalTo("NotAuthorizedException")); + if (!"false".equals(setting)) { + cognitoAction("RespondToAuthChallenge", respond(clientId, "SMS_MFA", challenge, variant, + "SMS_MFA_CODE", code)).then().statusCode(400) + .body("__type", equalTo("NotAuthorizedException")); + } + JsonNode result = cognitoJson("RespondToAuthChallenge", respond(clientId, "SMS_MFA", challenge, + "false".equals(setting) ? variant : user, "SMS_MFA_CODE", code)); + assertFalse(result.path("AuthenticationResult").path("AccessToken").asText().isEmpty()); + } finally { + cognitoAction("DeleteUserPool", "{\"UserPoolId\":\"" + poolId + "\"}").then().statusCode(200); + } + } + @Test void optionalSmsMfaChallengesOnceTurnedOnAndVerifiesThePhone() throws Exception { String poolId = createPool("OPTIONAL", SMS_CONFIG); diff --git a/src/test/java/io/floci/aws/services/cognito/CognitoServiceTest.java b/src/test/java/io/floci/aws/services/cognito/CognitoServiceTest.java index bdd3633a96..24feca91ca 100644 --- a/src/test/java/io/floci/aws/services/cognito/CognitoServiceTest.java +++ b/src/test/java/io/floci/aws/services/cognito/CognitoServiceTest.java @@ -5977,6 +5977,230 @@ class CognitoServiceTest { return service.createUserPool(req, "us-east-1"); } + @Nested + class CaseInsensitiveSignIn { + private UserPool pool() { + return service.createUserPool(Map.of("PoolName", "case-insensitive", + "UsernameAttributes", List.of("email"), + "UsernameConfiguration", Map.of("CaseSensitive", false)), "us-east-1"); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void emailLookupRespectsExplicitCaseSensitivity(boolean caseSensitive) { + UserPool pool = pool(); + pool.setUsernameConfiguration(Map.of("CaseSensitive", caseSensitive)); + CognitoUser user = service.adminCreateUser(pool.getId(), "Fixture@Example.com", Map.of(), null); + assertEquals(user.getUsername(), service.adminGetUser(pool.getId(), "Fixture@Example.com").getUsername()); + if (caseSensitive) { + AwsException error = assertThrows(AwsException.class, + () -> service.adminGetUser(pool.getId(), "fixture@example.com")); + assertEquals("UserNotFoundException", error.getErrorCode()); + } else { + assertEquals(user.getUsername(), service.adminGetUser(pool.getId(), "fixture@example.com").getUsername()); + } + } + + @Test + void omittedCaseSensitivityKeepsExactEmailMatching() { + UserPool pool = createEmailAliasPool(); + service.adminCreateUser(pool.getId(), "fixture@example.com", Map.of(), null); + AwsException error = assertThrows(AwsException.class, + () -> service.adminGetUser(pool.getId(), "Fixture@Example.com")); + assertEquals("UserNotFoundException", error.getErrorCode()); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void passwordAndSrpAuthKeepCanonicalIdentity(boolean admin) throws Exception { + UserPool pool = pool(); + String password = "Valid-password123!"; + CognitoUser user = service.adminCreateUser(pool.getId(), "fixture@example.com", Map.of(), null); + service.adminSetUserPassword(pool.getId(), user.getUsername(), password, true); + UserPoolClient client = service.createUserPoolClient(pool.getId(), "client", true, false, List.of(), List.of()); + client.setExplicitAuthFlows(List.of("ALLOW_USER_PASSWORD_AUTH", "ALLOW_ADMIN_USER_PASSWORD_AUTH", + "ALLOW_USER_SRP_AUTH")); + String supplied = "Fixture@Example.com"; + String secretHash = secretHash(client, supplied); + Map params = Map.of("USERNAME", supplied, "PASSWORD", password, "SECRET_HASH", secretHash); + Map authenticated = initiateAuth(admin, pool, client, "USER_PASSWORD_AUTH", params); + Map tokens = (Map) authenticated.get("AuthenticationResult"); + String accessToken = (String) tokens.get("AccessToken"); + JsonNode claims = new ObjectMapper().readTree(Base64.getUrlDecoder().decode(accessToken.split("\\.")[1])); + assertEquals(user.getUsername(), claims.path("sub").asText()); + assertEquals(user.getUsername(), claims.path("username").asText()); + + Map srpParams = Map.of("USERNAME", supplied, + "SRP_A", CognitoSrpTestClient.publicA(), "SECRET_HASH", secretHash); + Map started = initiateAuth(admin, pool, client, "USER_SRP_AUTH", srpParams); + Map challenge = (Map) started.get("ChallengeParameters"); + assertEquals(user.getUsername(), challenge.get("USER_ID_FOR_SRP")); + Map proof = new HashMap<>(CognitoSrpTestClient.proof( + pool.getId(), user.getUsername(), password, challenge)); + proof.put("SECRET_HASH", secretHash(client, user.getUsername())); + Map completed = respondToChallenge(admin, pool, client, "PASSWORD_VERIFIER", (String) started.get("Session"), proof); + assertNotNull(completed.get("AuthenticationResult")); + } + + private Map initiateAuth(boolean admin, UserPool pool, UserPoolClient client, + String flow, Map params) { + return admin ? service.adminInitiateAuth(pool.getId(), client.getClientId(), + "USER_PASSWORD_AUTH".equals(flow) ? "ADMIN_USER_PASSWORD_AUTH" : flow, params) + : service.initiateAuth(client.getClientId(), flow, params); + } + + private Map respondToChallenge(boolean admin, UserPool pool, UserPoolClient client, + String challenge, String session, Map responses) { + return admin ? service.adminRespondToAuthChallenge(pool.getId(), client.getClientId(), + challenge, session, responses) + : service.respondToAuthChallenge(client.getClientId(), challenge, session, responses); + } + + private String secretHash(UserPoolClient client, String username) throws Exception { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(client.getClientSecret().getBytes(StandardCharsets.UTF_8), "HmacSHA256")); + return Base64.getEncoder().encodeToString( + mac.doFinal((username + client.getClientId()).getBytes(StandardCharsets.UTF_8))); + } + + @ParameterizedTest + @CsvSource({"false,false", "true,false", "false,true", "true,true", "false,default", "true,default"}) + void srpChallengeRespectsUsernameCaseSensitivity(boolean admin, String setting) throws Exception { + UserPool pool = service.createUserPool(Map.of("PoolName", "classic-srp-case"), "us-east-1"); + if (!"default".equals(setting)) { + pool.setUsernameConfiguration(Map.of("CaseSensitive", Boolean.parseBoolean(setting))); + } + String password = "Valid-password123!"; + CognitoUser user = service.adminCreateUser(pool.getId(), "Fixture", Map.of(), null); + service.adminSetUserPassword(pool.getId(), user.getUsername(), password, true); + UserPoolClient client = service.createUserPoolClient(pool.getId(), "client", true, false, List.of(), List.of()); + client.setExplicitAuthFlows(List.of("ALLOW_USER_SRP_AUTH")); + String supplied = "false".equals(setting) ? "fixture" : user.getUsername(); + Map started = initiateAuth(admin, pool, client, "USER_SRP_AUTH", + Map.of("USERNAME", supplied, "SRP_A", CognitoSrpTestClient.publicA(), + "SECRET_HASH", secretHash(client, supplied))); + Map challenge = (Map) started.get("ChallengeParameters"); + assertEquals("Fixture", challenge.get("USER_ID_FOR_SRP")); + String session = (String) started.get("Session"); + Map proof = new HashMap<>(CognitoSrpTestClient.proof( + pool.getId(), user.getUsername(), password, challenge)); + proof.remove("USERNAME"); + assertEquals("InvalidParameterException", assertThrows(AwsException.class, + () -> respondToChallenge(admin, pool, client, "PASSWORD_VERIFIER", session, proof)).getErrorCode()); + proof.put("USERNAME", "other"); + proof.put("SECRET_HASH", secretHash(client, "other")); + assertEquals("NotAuthorizedException", assertThrows(AwsException.class, + () -> respondToChallenge(admin, pool, client, "PASSWORD_VERIFIER", session, proof)).getErrorCode()); + proof.put("USERNAME", "fixture"); + proof.put("SECRET_HASH", secretHash(client, "fixture")); + if (!"false".equals(setting)) { + assertEquals("NotAuthorizedException", assertThrows(AwsException.class, + () -> respondToChallenge(admin, pool, client, "PASSWORD_VERIFIER", session, proof)).getErrorCode()); + proof.put("USERNAME", user.getUsername()); + proof.put("SECRET_HASH", secretHash(client, user.getUsername())); + } + Map tokens = (Map) respondToChallenge(admin, pool, client, "PASSWORD_VERIFIER", session, proof).get("AuthenticationResult"); + String accessToken = (String) tokens.get("AccessToken"); + JsonNode claims = new ObjectMapper().readTree(Base64.getUrlDecoder().decode(accessToken.split("\\.")[1])); + assertEquals("Fixture", claims.path("username").asText()); + assertEquals(user.getAttributes().get("sub"), claims.path("sub").asText()); + } + + @ParameterizedTest + @CsvSource({"false,false", "true,false", "false,true", "true,true", "false,default", "true,default"}) + void newPasswordChallengeRespectsUsernameCaseSensitivity(boolean admin, String setting) throws Exception { + UserPool pool = service.createUserPool(Map.of("PoolName", "classic-password-case"), "us-east-1"); + if (!"default".equals(setting)) { + pool.setUsernameConfiguration(Map.of("CaseSensitive", Boolean.parseBoolean(setting))); + } + String temporaryPassword = "Temporary-password123!"; + CognitoUser user = service.adminCreateUser(pool.getId(), "Fixture", Map.of(), temporaryPassword); + UserPoolClient client = service.createUserPoolClient(pool.getId(), "client", true, false, List.of(), List.of()); + client.setExplicitAuthFlows(List.of("ALLOW_USER_PASSWORD_AUTH", "ALLOW_ADMIN_USER_PASSWORD_AUTH")); + String supplied = "false".equals(setting) ? "fixture" : user.getUsername(); + Map started = initiateAuth(admin, pool, client, "USER_PASSWORD_AUTH", + Map.of("USERNAME", supplied, "PASSWORD", temporaryPassword, + "SECRET_HASH", secretHash(client, supplied))); + assertEquals("NEW_PASSWORD_REQUIRED", started.get("ChallengeName")); + String session = (String) started.get("Session"); + String newPassword = "Permanent-password123!"; + Map responses = new HashMap<>(Map.of("NEW_PASSWORD", newPassword)); + assertEquals("NotAuthorizedException", assertThrows(AwsException.class, + () -> respondToChallenge(admin, pool, client, "NEW_PASSWORD_REQUIRED", session, responses)) + .getErrorCode()); + responses.put("USERNAME", "other"); + responses.put("SECRET_HASH", secretHash(client, "other")); + assertEquals("NotAuthorizedException", assertThrows(AwsException.class, + () -> respondToChallenge(admin, pool, client, "NEW_PASSWORD_REQUIRED", session, responses)) + .getErrorCode()); + responses.put("USERNAME", "fixture"); + responses.put("SECRET_HASH", secretHash(client, "fixture")); + if (!"false".equals(setting)) { + assertEquals("NotAuthorizedException", assertThrows(AwsException.class, + () -> respondToChallenge(admin, pool, client, "NEW_PASSWORD_REQUIRED", session, responses)) + .getErrorCode()); + responses.put("USERNAME", user.getUsername()); + responses.put("SECRET_HASH", secretHash(client, user.getUsername())); + } + Map tokens = (Map) respondToChallenge(admin, pool, client, "NEW_PASSWORD_REQUIRED", + session, responses).get("AuthenticationResult"); + assertNotNull(tokens.get("AccessToken")); + assertEquals("Fixture", service.adminGetUser(pool.getId(), supplied).getUsername()); + assertNotNull(initiateAuth(admin, pool, client, "USER_PASSWORD_AUTH", + Map.of("USERNAME", supplied, "PASSWORD", newPassword, "SECRET_HASH", secretHash(client, supplied))) + .get("AuthenticationResult")); + } + + @Test + void duplicateEmailCreationAndUpdatesUseTheSameComparison() { + UserPool pool = pool(); + CognitoUser user = service.adminCreateUser(pool.getId(), "fixture@example.com", + Map.of("email_verified", "true"), null); + AwsException duplicate = assertThrows(AwsException.class, + () -> service.adminCreateUser(pool.getId(), "Fixture@Example.com", Map.of(), null)); + assertEquals("AliasExistsException", duplicate.getErrorCode()); + UserPoolClient client = service.createUserPoolClient(pool.getId(), "client", false, false, List.of(), List.of()); + AwsException signup = assertThrows(AwsException.class, () -> service.signUp(client.getClientId(), + "Fixture@Example.com", "Valid-password123!", Map.of(), Map.of(), Map.of())); + assertEquals("UsernameExistsException", signup.getErrorCode()); + + CognitoUser other = service.adminCreateUser(pool.getId(), "other@example.com", Map.of(), null); + AwsException update = assertThrows(AwsException.class, () -> service.adminUpdateUserAttributes( + pool.getId(), other.getUsername(), Map.of("email", "Fixture@Example.com"))); + assertEquals("AliasExistsException", update.getErrorCode()); + service.adminSetUserPassword(pool.getId(), other.getUsername(), "Valid-password123!", true); + client.setExplicitAuthFlows(List.of("ALLOW_USER_PASSWORD_AUTH")); + Map tokens = (Map) service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH", + Map.of("USERNAME", other.getUsername(), "PASSWORD", "Valid-password123!")) + .get("AuthenticationResult"); + AwsException selfUpdate = assertThrows(AwsException.class, () -> service.updateUserAttributes( + (String) tokens.get("AccessToken"), Map.of("email", "Fixture@Example.com"))); + assertEquals("AliasExistsException", selfUpdate.getErrorCode()); + service.adminUpdateUserAttributes(pool.getId(), user.getUsername(), Map.of("email", "Changed@Example.com")); + assertEquals(user.getUsername(), service.adminGetUser(pool.getId(), "changed@example.com").getUsername()); + assertThrows(AwsException.class, () -> service.adminGetUser(pool.getId(), "fixture@example.com")); + assertEquals(user.getUsername(), service.adminGetUser(pool.getId(), user.getUsername()).getAttributes().get("sub")); + } + + @Test + void classicUsernameAndPreferredUsernameAliasRespectTheSetting() { + UserPool pool = service.createUserPool(Map.of("PoolName", "classic-case-insensitive", + "AliasAttributes", List.of("preferred_username"), + "UsernameConfiguration", Map.of("CaseSensitive", false)), "us-east-1"); + CognitoUser user = service.adminCreateUser(pool.getId(), "Fixture", + Map.of("preferred_username", "Nickname"), null); + assertEquals(user.getUsername(), service.adminGetUser(pool.getId(), "fixture").getUsername()); + assertEquals(user.getUsername(), service.adminGetUser(pool.getId(), "NICKNAME").getUsername()); + AwsException duplicate = assertThrows(AwsException.class, + () -> service.adminCreateUser(pool.getId(), "FIXTURE", Map.of(), null)); + assertEquals("UsernameExistsException", duplicate.getErrorCode()); + UserPoolClient client = service.createUserPoolClient(pool.getId(), "client", false, false, List.of(), List.of()); + AwsException signup = assertThrows(AwsException.class, () -> service.signUp(client.getClientId(), + "FIXTURE", "Valid-password123!", Map.of(), Map.of(), Map.of())); + assertEquals("UsernameExistsException", signup.getErrorCode()); + } + } + private static boolean isUuid(String value) { try { UUID.fromString(value); diff --git a/src/test/java/io/floci/aws/services/cognito/CognitoSignUpTriggerReentrancyTest.java b/src/test/java/io/floci/aws/services/cognito/CognitoSignUpTriggerReentrancyTest.java index 239eca81f5..3b17fb51e3 100644 --- a/src/test/java/io/floci/aws/services/cognito/CognitoSignUpTriggerReentrancyTest.java +++ b/src/test/java/io/floci/aws/services/cognito/CognitoSignUpTriggerReentrancyTest.java @@ -24,6 +24,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; import java.time.Clock; @@ -398,9 +399,12 @@ class CognitoSignUpTriggerReentrancyTest { deliveredCode.get()); } - @Test - void preSignUpRejectsSameUsernameAdminCreationWithoutBlockingTheTrigger() throws Exception { + @ParameterizedTest + @CsvSource({"true, alice", "false, alice", "false, ALICE"}) + void preSignUpRejectsSameUsernameAdminCreationWithoutBlockingTheTrigger( + boolean caseSensitive, String overlappingUsername) throws Exception { UserPool pool = pool(Map.of("PreSignUp", FUNCTION)); + pool.setUsernameConfiguration(Map.of("CaseSensitive", caseSensitive)); UserPoolClient client = client(pool); AtomicReference callbackFailure = new AtomicReference<>(); AtomicReference duplicateFailure = new AtomicReference<>(); @@ -410,7 +414,7 @@ class CognitoSignUpTriggerReentrancyTest { if ("PreSignUp_SignUp".equals(event.path("triggerSource").asText())) { callback(() -> { AwsException duplicate = assertThrows(AwsException.class, - () -> service.adminCreateUser(pool.getId(), "alice", + () -> service.adminCreateUser(pool.getId(), overlappingUsername, Map.of("name", "created by trigger"), null, "SUPPRESS")); assertEquals("UsernameExistsException", duplicate.getErrorCode()); duplicateFailure.set(duplicate); diff --git a/src/test/java/io/floci/aws/services/cognito/CognitoTotpMfaTest.java b/src/test/java/io/floci/aws/services/cognito/CognitoTotpMfaTest.java index 2d50512682..a05afdfb0d 100644 --- a/src/test/java/io/floci/aws/services/cognito/CognitoTotpMfaTest.java +++ b/src/test/java/io/floci/aws/services/cognito/CognitoTotpMfaTest.java @@ -12,6 +12,8 @@ import io.floci.aws.services.cognito.model.UserPoolClient; import io.floci.aws.testing.MutableClock; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; @@ -21,6 +23,7 @@ import java.security.MessageDigest; import java.time.Duration; import java.util.Arrays; import java.util.Base64; +import java.util.HashMap; import java.util.List; import java.util.Map; @@ -108,6 +111,43 @@ class CognitoTotpMfaTest { assertNotNull(((Map) completed.get("AuthenticationResult")).get("AccessToken")); } + @ParameterizedTest + @ValueSource(strings = {"false", "true", "default"}) + void totpChallengesRespectUsernameCaseSensitivity(String setting) { + if (!"default".equals(setting)) { + pool.setUsernameConfiguration(Map.of("CaseSensitive", Boolean.parseBoolean(setting))); + } + String supplied = "false".equals(setting) ? "ALICE" : USERNAME; + String session = (String) service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH", + Map.of("USERNAME", supplied, "PASSWORD", PASSWORD)).get("Session"); + Map association = service.associateSoftwareToken(null, session); + String secret = (String) association.get("SecretCode"); + String code = CognitoTotp.code(secret, clock.instant()); + String verified = (String) service.verifySoftwareToken(null, (String) association.get("Session"), code) + .get("Session"); + assertTotpUsernameMatching(setting, "MFA_SETUP", verified, Map.of()); + String later = (String) passwordLogin().get("Session"); + assertTotpUsernameMatching(setting, "SOFTWARE_TOKEN_MFA", later, Map.of("SOFTWARE_TOKEN_MFA_CODE", code)); + } + + private void assertTotpUsernameMatching(String setting, String challenge, String session, + Map fields) { + Map responses = new HashMap<>(fields); + assertEquals("NotAuthorizedException", assertThrows(AwsException.class, + () -> service.respondToAuthChallenge(client.getClientId(), challenge, session, responses)).getErrorCode()); + responses.put("USERNAME", "other"); + assertEquals("NotAuthorizedException", assertThrows(AwsException.class, + () -> service.respondToAuthChallenge(client.getClientId(), challenge, session, responses)).getErrorCode()); + responses.put("USERNAME", "ALICE"); + if (!"false".equals(setting)) { + assertEquals("NotAuthorizedException", assertThrows(AwsException.class, + () -> service.respondToAuthChallenge(client.getClientId(), challenge, session, responses)).getErrorCode()); + responses.put("USERNAME", USERNAME); + } + assertNotNull(service.respondToAuthChallenge(client.getClientId(), challenge, session, responses) + .get("AuthenticationResult")); + } + @Test void disabledUserCannotCompleteMfaSetupChallenge() { String loginSession = (String) passwordLogin().get("Session");