diff --git a/docs/services/cognito.md b/docs/services/cognito.md index a772d6ff95..eb1ae1dfb5 100644 --- a/docs/services/cognito.md +++ b/docs/services/cognito.md @@ -464,6 +464,8 @@ the stored or returned value. A client that signs in with `USER_PASSWORD_AUTH`, ## User Attribute Update Verification +`UpdateUserAttributes` and `AdminUpdateUserAttributes` delete attributes submitted with a blank value, including whitespace-only values. Deleting an email or phone number also removes its verified flag and pending value. Admin updates invalidate the matching pending verification code. + `CreateUserPool`, `UpdateUserPool`, and `DescribeUserPool` support `UserAttributeUpdateSettings.AttributesRequireVerificationBeforeUpdate` for `email` and `phone_number`. diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java index 4ca8e5f0ee..2b2b1dc088 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 @@ -112,6 +112,10 @@ public class CognitoService implements ResourceProvider { private static final List DELIVERY_MEDIUMS = List.of("SMS", "EMAIL"); // JVM-local stripes bound lock memory without retaining one lock for every user key. private static final int USER_LOCK_STRIPES = 512; + // A Cognito email attribute is one address, not an SES display-name or recipient list. + private static final Pattern EMAIL_ATTRIBUTE_PATTERN = + Pattern.compile("[^\\s\\p{Cntrl}@<>,;]+@[^\\s\\p{Cntrl}@<>,;]+"); + private static final int EMAIL_ATTRIBUTE_MAX_LENGTH = 2048; /** * No configured CloudFront suffix, for the test constructors: the suffix then follows the * request's partition. CDI wires {@code floci.services.cloudfront.domain-suffix}. @@ -2328,6 +2332,8 @@ public class CognitoService implements ResourceProvider { resolvedAttributes.put("sub", canonicalUsername); } + validateEmailAttribute(resolvedAttributes, false); + CognitoUser user = new CognitoUser(); user.setUsername(canonicalUsername); user.setUserPoolId(pool.getId()); @@ -2628,10 +2634,11 @@ public class CognitoService implements ResourceProvider { String userPoolId, String username, Map attributes) { CognitoUser user = adminGetUser(userPoolId, username); UserPool pool = describeUserPool(userPoolId); + validateEmailAttribute(attributes, true); if (usesAliasUsernames(pool)) { for (String aliasAttribute : pool.getUsernameAttributes()) { String newValue = attributes.get(aliasAttribute); - if (newValue == null || newValue.equals(user.getAttributes().get(aliasAttribute))) { + if (blankToNull(newValue) == null || newValue.equals(user.getAttributes().get(aliasAttribute))) { continue; } CognitoUser other = findUserByAlias(userPoolId, aliasAttribute, newValue); @@ -2643,7 +2650,16 @@ public class CognitoService implements ResourceProvider { } attributes.keySet().forEach(attributeName -> clearPendingAttributeVerification(userPoolId, user, attributeName)); - user.getAttributes().putAll(attributes); + for (Map.Entry attribute : attributes.entrySet()) { + String attributeName = attribute.getKey(); + String value = attribute.getValue(); + if (blankToNull(value) == null) { + user.getAttributes().remove(attributeName); + user.getAttributes().remove(attributeName + "_verified"); + } else { + user.getAttributes().put(attributeName, value); + } + } user.setLastModifiedDate(System.currentTimeMillis() / 1000L); userStore.put(userKey(userPoolId, user.getUsername()), user); } @@ -3262,6 +3278,8 @@ public class CognitoService implements ResourceProvider { throw new AwsException("UsernameExistsException", "User already exists", 400); } + validateEmailAttribute(resolvedAttributes, false); + String key = userKey(userPoolId, canonicalUsername); CognitoUser user = new CognitoUser(); @@ -4043,6 +4061,7 @@ public class CognitoService implements ResourceProvider { String poolId, String username, Map attributes) { UserPool pool = describeUserPool(poolId); CognitoUser currentUser = adminGetUser(poolId, username); + validateEmailAttribute(attributes, true); // Validate every entry (alias availability) before mutating the user or issuing any // verification code. Otherwise a later entry failing leaves an earlier entry's code @@ -4113,6 +4132,36 @@ public class CognitoService implements ResourceProvider { return deliveryDetails; } + private static void validateEmailAttribute(Map attributes, boolean allowDeletion) { + if (attributes == null || !attributes.containsKey("email")) { + return; + } + String email = attributes.get("email"); + if (allowDeletion && email != null && email.isBlank()) { + return; + } + // Use Cognito's 2048-character attribute limit, not SES's envelope-address limit. + if (email == null || email.length() > EMAIL_ATTRIBUTE_MAX_LENGTH + || !EMAIL_ATTRIBUTE_PATTERN.matcher(email).matches() || !hasEmailSeparator(email)) { + throw new AwsException("InvalidParameterException", "Invalid email address format.", 400); + } + } + + private static boolean hasEmailSeparator(String email) { + boolean quoted = false; + for (int i = 0; i < email.length(); i++) { + char character = email.charAt(i); + if (character == '\\') { + i++; + } else if (character == '"') { + quoted = !quoted; + } else if (character == '@' && !quoted) { + return true; + } + } + return false; + } + public void deleteUserAttributes(String accessToken, List attributeNames) { VerifiedAccessToken token = verifyAccessToken(accessToken); requireScope(accessToken, USER_ADMIN_SCOPE); diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoEmailValidationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoEmailValidationIntegrationTest.java new file mode 100644 index 0000000000..91f99428cf --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoEmailValidationIntegrationTest.java @@ -0,0 +1,115 @@ +package io.github.hectorvent.floci.services.cognito; + +import com.fasterxml.jackson.core.json.JsonWriteFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.json.JsonMapper; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction; +import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson; +import static org.hamcrest.Matchers.equalTo; + +@QuarkusTest +class CognitoEmailValidationIntegrationTest { + private static final ObjectMapper JSON = JsonMapper.builder().enable(JsonWriteFeature.ESCAPE_NON_ASCII).build(); + + @BeforeAll + static void setUpJson() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @ParameterizedTest + @ValueSource(strings = {"", " ", "\t\r\n", "\u2003"}) + void bothUpdateApisDeleteBlankEmailsButCreationStillRejectsThem(String email) throws Exception { + String poolId = cognitoJson("CreateUserPool", JSON.writeValueAsString(Map.of( + "PoolName", "blank-email-" + UUID.randomUUID()))).path("UserPool").path("Id").asText(); + try { + String clientId = cognitoJson("CreateUserPoolClient", JSON.writeValueAsString(Map.of( + "UserPoolId", poolId, "ClientName", "email-client", + "ExplicitAuthFlows", List.of("ALLOW_USER_PASSWORD_AUTH")))) + .path("UserPoolClient").path("ClientId").asText(); + for (String operation : List.of("AdminUpdateUserAttributes", "UpdateUserAttributes")) { + cognitoAction("AdminCreateUser", JSON.writeValueAsString(Map.of("UserPoolId", poolId, + "Username", operation, "MessageAction", "SUPPRESS", "UserAttributes", List.of( + Map.of("Name", "email", "Value", "alice@example.com"), + Map.of("Name", "email_verified", "Value", "true"))))) + .then().statusCode(200); + cognitoAction("AdminSetUserPassword", JSON.writeValueAsString(Map.of("UserPoolId", poolId, + "Username", operation, "Password", "Passw0rd!x", "Permanent", true))) + .then().statusCode(200); + String token = cognitoJson("InitiateAuth", JSON.writeValueAsString(Map.of("ClientId", clientId, + "AuthFlow", "USER_PASSWORD_AUTH", "AuthParameters", + Map.of("USERNAME", operation, "PASSWORD", "Passw0rd!x")))) + .path("AuthenticationResult").path("AccessToken").asText(); + List> attributes = List.of(Map.of("Name", "email", "Value", email)); + Map request = operation.equals("AdminUpdateUserAttributes") + ? Map.of("UserPoolId", poolId, "Username", operation, "UserAttributes", attributes) + : Map.of("AccessToken", token, "UserAttributes", attributes); + cognitoAction(operation, JSON.writeValueAsString(request)).then().statusCode(200); + cognitoAction("AdminGetUser", JSON.writeValueAsString(Map.of("UserPoolId", poolId, + "Username", operation))).then().statusCode(200) + .body("UserAttributes.findAll { it.Name == 'email' || it.Name == 'email_verified' }.size()", + equalTo(0)); + } + List> attributes = List.of(Map.of("Name", "email", "Value", email)); + cognitoAction("AdminCreateUser", JSON.writeValueAsString(Map.of("UserPoolId", poolId, + "Username", "bad-admin", "MessageAction", "SUPPRESS", "UserAttributes", attributes))) + .then().statusCode(400).body("__type", equalTo("InvalidParameterException")); + cognitoAction("SignUp", JSON.writeValueAsString(Map.of("ClientId", clientId, + "Username", "bad-signup", "Password", "Passw0rd!x", "UserAttributes", attributes))) + .then().statusCode(400).body("__type", equalTo("InvalidParameterException")); + } finally { + cognitoAction("DeleteUserPool", JSON.writeValueAsString(Map.of("UserPoolId", poolId))) + .then().statusCode(200); + } + } + + @ParameterizedTest + @ValueSource(strings = {"alice smith@example.com", "alice\\@example.com", "\"alice@example.com\""}) + void allFourApisReturnCognitoValidationErrorsAndPreserveExistingAttributes(String email) throws Exception { + String poolId = cognitoJson("CreateUserPool", JSON.writeValueAsString(Map.of( + "PoolName", "email-validation-" + UUID.randomUUID()))).path("UserPool").path("Id").asText(); + try { + String clientId = cognitoJson("CreateUserPoolClient", JSON.writeValueAsString(Map.of( + "UserPoolId", poolId, "ClientName", "email-client", + "ExplicitAuthFlows", List.of("ALLOW_USER_PASSWORD_AUTH")))) + .path("UserPoolClient").path("ClientId").asText(); + cognitoAction("AdminCreateUser", JSON.writeValueAsString(Map.of("UserPoolId", poolId, + "Username", "alice", "MessageAction", "SUPPRESS", "UserAttributes", + List.of(Map.of("Name", "email", "Value", "alice@example.com"))))) + .then().statusCode(200); + cognitoAction("AdminSetUserPassword", JSON.writeValueAsString(Map.of("UserPoolId", poolId, + "Username", "alice", "Password", "Passw0rd!x", "Permanent", true))).then().statusCode(200); + String token = cognitoJson("InitiateAuth", JSON.writeValueAsString(Map.of("ClientId", clientId, + "AuthFlow", "USER_PASSWORD_AUTH", "AuthParameters", Map.of("USERNAME", "alice", "PASSWORD", "Passw0rd!x")))) + .path("AuthenticationResult").path("AccessToken").asText(); + List> attributes = List.of(Map.of("Name", "name", "Value", "must-not-be-saved"), + Map.of("Name", "email", "Value", email)); + Map> requests = Map.of( + "AdminCreateUser", Map.of("UserPoolId", poolId, "Username", "bad-admin", "MessageAction", "SUPPRESS", "UserAttributes", attributes), + "SignUp", Map.of("ClientId", clientId, "Username", "bad-signup", "Password", "Passw0rd!x", "UserAttributes", attributes), + "AdminUpdateUserAttributes", Map.of("UserPoolId", poolId, "Username", "alice", "UserAttributes", attributes), + "UpdateUserAttributes", Map.of("AccessToken", token, "UserAttributes", attributes)); + for (Map.Entry> request : requests.entrySet()) { + cognitoAction(request.getKey(), JSON.writeValueAsString(request.getValue())).then().statusCode(400) + .body("__type", equalTo("InvalidParameterException")); + } + cognitoAction("AdminGetUser", JSON.writeValueAsString(Map.of("UserPoolId", poolId, "Username", "alice"))) + .then().statusCode(200) + .body("UserAttributes.find { it.Name == 'email' }.Value", equalTo("alice@example.com")) + .body("UserAttributes.findAll { it.Name == 'name' }.size()", equalTo(0)); + cognitoAction("ListUsers", JSON.writeValueAsString(Map.of("UserPoolId", poolId))) + .then().statusCode(200).body("Users.size()", equalTo(1)); + } finally { + cognitoAction("DeleteUserPool", JSON.writeValueAsString(Map.of("UserPoolId", poolId))).then().statusCode(200); + } + } +} 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 3f9fe5766e..a4c2133a2a 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 @@ -34,6 +34,7 @@ import org.junit.jupiter.api.Nested; 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 org.mockito.ArgumentCaptor; import java.lang.management.ManagementFactory; @@ -242,6 +243,79 @@ class CognitoServiceTest { return pool; } + @ParameterizedTest + @ValueSource(strings = {"alice smith@example.com", "alice", "alice@", "@example.com", + "alice@@example.com", "alice@example.com\n", "alice@example.com\u0000", "alice@exa mple.com", + "alice\\@example.com", "\"alice@example.com\""}) + @SuppressWarnings("unchecked") + void malformedEmailsAreRejectedBeforeAnyUserOrAttributeIsStored(String email) { + UserPool pool = createPoolAndUser(); + UserPoolClient client = openClient(service, pool.getId(), "email-client", false); + Map auth = service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH", + Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")); + String token = (String) ((Map) auth.get("AuthenticationResult")).get("AccessToken"); + Map attributes = Map.of("email", email, "name", "must-not-be-saved"); + for (Runnable operation : List.of( + () -> service.adminCreateUser(pool.getId(), "invalid-admin", attributes, "TempPass1!"), + () -> service.signUp(client.getClientId(), "invalid-signup", "Pass1234!", attributes), + () -> service.adminUpdateUserAttributes(pool.getId(), "alice", attributes), + () -> service.updateUserAttributes(token, attributes))) { + AwsException error = assertThrows(AwsException.class, operation::run); + assertEquals("InvalidParameterException", error.getErrorCode()); + assertEquals(400, error.getHttpStatus()); + } + assertEquals(1, userStore.keys().size()); + CognitoUser unchanged = service.adminGetUser(pool.getId(), "alice"); + assertEquals("alice@example.com", unchanged.getAttributes().get("email")); + assertFalse(unchanged.getAttributes().containsKey("name")); + assertTrue(unchanged.getPendingAttributes().isEmpty()); + } + + @Test + void emailLengthUsesCognitoLimitAndBlankSelfServiceUpdateStillDeletes() { + UserPool pool = createPoolAndUser(); + String validLongEmail = "a".repeat(2036) + "@example.com"; + assertEquals(2048, validLongEmail.length()); + service.adminUpdateUserAttributes(pool.getId(), "alice", Map.of("email", validLongEmail)); + assertEquals(validLongEmail, service.adminGetUser(pool.getId(), "alice").getAttributes().get("email")); + assertEquals("InvalidParameterException", assertThrows(AwsException.class, + () -> service.adminUpdateUserAttributes(pool.getId(), "alice", Map.of("email", "a" + validLongEmail))) + .getErrorCode()); + UserPoolClient client = openClient(service, pool.getId(), "email-client", false); + @SuppressWarnings("unchecked") + Map auth = (Map) service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH", + Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")).get("AuthenticationResult"); + service.updateUserAttributes((String) auth.get("AccessToken"), Map.of("email", "")); + assertNull(service.adminGetUser(pool.getId(), "alice").getAttributes().get("email")); + } + + @ParameterizedTest + @ValueSource(strings = {"", " ", "\t\r\n", "\u2003"}) + @SuppressWarnings("unchecked") + void blankSelfServiceEmailUpdateDeletesAttributeAndVerifiedFlag(String email) { + UserPool pool = createPoolAndUser(); + service.adminUpdateUserAttributes(pool.getId(), "alice", Map.of("email_verified", "true")); + UserPoolClient client = openClient(service, pool.getId(), "blank-email-client", false); + Map auth = (Map) service.initiateAuth( + client.getClientId(), "USER_PASSWORD_AUTH", + Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")).get("AuthenticationResult"); + + assertTrue(service.updateUserAttributes((String) auth.get("AccessToken"), Map.of("email", email)).isEmpty()); + + CognitoUser updated = service.adminGetUser(pool.getId(), "alice"); + assertFalse(updated.getAttributes().containsKey("email")); + assertFalse(updated.getAttributes().containsKey("email_verified")); + } + + @Test + void emailSeparatorAfterAQuotedLocalPartOrEscapedBackslashRemainsValid() { + UserPool pool = createPoolAndUser(); + for (String email : List.of("\"alice\\\\name\"@example.com", "alice\\\\@example.com")) { + service.adminUpdateUserAttributes(pool.getId(), "alice", Map.of("email", email)); + assertEquals(email, service.adminGetUser(pool.getId(), "alice").getAttributes().get("email")); + } + } + private UserPool createPoolWithStrictPasswordPolicy() { return service.createUserPool(Map.of( "PoolName", "StrictPasswordPool", @@ -2535,6 +2609,33 @@ class CognitoServiceTest { VerificationCode.Purpose.PHONE_ATTRIBUTE_VERIFICATION); } + @ParameterizedTest + @ValueSource(strings = {"", " ", "\t\r\n", "\u2003"}) + void blankAdminEmailUpdateDeletesAttributesAndClearsOnlyMatchingVerification(String email) { + VerificationCodeService verificationCodeService = inlineMock(VerificationCodeService.class); + CognitoMessageDispatcher messageDispatcher = inlineMock(CognitoMessageDispatcher.class); + PendingContactFixture fixture = createPendingContactFixture(verificationCodeService, messageDispatcher); + clearInvocations(verificationCodeService, messageDispatcher); + + fixture.service().adminUpdateUserAttributes(fixture.pool().getId(), "alice", Map.of( + "email", email, "custom:note", email, "name", "updated")); + + CognitoUser updated = fixture.service().adminGetUser(fixture.pool().getId(), "alice"); + assertFalse(updated.getAttributes().containsKey("email")); + assertFalse(updated.getAttributes().containsKey("email_verified")); + assertFalse(updated.getAttributes().containsKey("custom:note")); + assertEquals("updated", updated.getAttributes().get("name")); + assertFalse(updated.getPendingAttributes().containsKey("email")); + assertEquals("+12025550100", updated.getAttributes().get("phone_number")); + assertEquals("true", updated.getAttributes().get("phone_number_verified")); + assertEquals("+12025550101", updated.getPendingAttributes().get("phone_number")); + verify(verificationCodeService).invalidatePrevious(fixture.pool().getId(), "alice", + VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION); + verify(verificationCodeService, never()).invalidatePrevious(any(), any(), + eq(VerificationCode.Purpose.PHONE_ATTRIBUTE_VERIFICATION)); + verifyNoInteractions(messageDispatcher); + } + @Test void adminContactDeleteClearsOnlyMatchingPendingValueAndVerificationCode() { VerificationCodeService verificationCodeService = inlineMock(VerificationCodeService.class); @@ -4478,12 +4579,12 @@ class CognitoServiceTest { Map.of("PoolName", "TestPool", "AliasAttributes", List.of("email")), "us-east-1" ); - service.adminCreateUser(pool.getId(), "shared-lookup", Map.of("email", "owner@example.com"), null); + service.adminCreateUser(pool.getId(), "shared-lookup@example.com", Map.of("email", "owner@example.com"), null); service.adminCreateUser(pool.getId(), "alice", - Map.of("email", "shared-lookup", "email_verified", "true"), null); + Map.of("email", "shared-lookup@example.com", "email_verified", "true"), null); AwsException ex = assertThrows(AwsException.class, - () -> service.adminGetUser(pool.getId(), "shared-lookup")); + () -> service.adminGetUser(pool.getId(), "shared-lookup@example.com")); assertEquals("InvalidParameterException", ex.getErrorCode()); assertEquals(400, ex.getHttpStatus()); } @@ -4494,13 +4595,13 @@ class CognitoServiceTest { Map.of("PoolName", "TestPool", "AliasAttributes", List.of("email")), "us-east-1" ); - service.adminCreateUser(pool.getId(), "shared-lookup", Map.of("email", "owner@example.com"), null); + service.adminCreateUser(pool.getId(), "shared-lookup@example.com", Map.of("email", "owner@example.com"), null); service.adminCreateUser(pool.getId(), "alice", Map.of("email", "alice@example.com"), null); service.adminUpdateUserAttributes(pool.getId(), "alice", - Map.of("email", "shared-lookup", "email_verified", "true")); + Map.of("email", "shared-lookup@example.com", "email_verified", "true")); AwsException ex = assertThrows(AwsException.class, - () -> service.adminGetUser(pool.getId(), "shared-lookup")); + () -> service.adminGetUser(pool.getId(), "shared-lookup@example.com")); assertEquals("InvalidParameterException", ex.getErrorCode()); assertEquals(400, ex.getHttpStatus()); }