mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cognito): validate email attributes before storing users (#5460)
* fix(cognito): validate email attributes before storing users * fix(cognito): reject escaped and quoted email separators * fix(cognito): preserve blank attribute deletion on updates * test(cognito): use inline mocks for final verification services
This commit is contained in:
1 parent
15fb050d91
commit
3ad8c25a4f
4 files changed
+275
-8
No files matched your search
+115
@@ -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<Map<String, String>> attributes = List.of(Map.of("Name", "email", "Value", email));
|
||||
Map<String, Object> 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<Map<String, String>> 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<Map<String, String>> attributes = List.of(Map.of("Name", "name", "Value", "must-not-be-saved"),
|
||||
Map.of("Name", "email", "Value", email));
|
||||
Map<String, Map<String, Object>> 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<String, Map<String, Object>> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<String, Object> auth = service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH",
|
||||
Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!"));
|
||||
String token = (String) ((Map<String, Object>) auth.get("AuthenticationResult")).get("AccessToken");
|
||||
Map<String, String> attributes = Map.of("email", email, "name", "must-not-be-saved");
|
||||
for (Runnable operation : List.<Runnable>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<String, Object> auth = (Map<String, Object>) 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<String, Object> auth = (Map<String, Object>) 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());
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user