mirror of
https://github.com/floci-io/floci.git
synced 2026-11-26 07:11:11 -05:00
fix(cognito): answer UsernameExistsException when AdminCreateUser's username is taken in a UsernameAttributes pool (#9286)
This commit is contained in:
1 parent
5807e901a4
commit
374b5f5c8e
4 files changed
+55
-190
No files matched your search
@@ -321,9 +321,9 @@ further divergences, both deliberate:
|
||||
- **`SUPPRESS`** sends nothing. **`RESEND`** sets the request's `TemporaryPassword`, or a
|
||||
generated one, and sends the invitation again.
|
||||
- **Delivery failure** returns `CodeDeliveryFailureException`, as `SignUp` does. The invitation is
|
||||
sent before anything is stored, so a failed one creates no user, leaves a resent user's previous
|
||||
temporary password working, and leaves a `ForceAliasCreation` alias with its holder. When one
|
||||
medium fails and another delivers, the request succeeds.
|
||||
sent before anything is stored, so a failed one creates no user and leaves a resent user's
|
||||
previous temporary password working. When one medium fails and another delivers, the request
|
||||
succeeds.
|
||||
- **CloudFormation:** `AWS::Cognito::UserPoolUser` has no `TemporaryPassword`, so its user gets a
|
||||
generated one, and the template's `DesiredDeliveryMediums`, `ValidationData` and `ClientMetadata`
|
||||
are passed on.
|
||||
@@ -977,9 +977,9 @@ Floci follows real Cognito semantics for pools created with `UsernameAttributes`
|
||||
verifier, which has to use the `USER_ID_FOR_SRP` of the challenge, as AWS documents.
|
||||
- `AdminUpdateUserAttributes` can change the email; afterwards sign-in works with the new email and
|
||||
fails with the old one, while `Username`/`sub` stay fixed.
|
||||
- Duplicate email/phone on `AdminCreateUser`: `UsernameExistsException` when the incoming alias is
|
||||
unverified, `AliasExistsException` when it is verified (`email_verified=true`); pass
|
||||
`ForceAliasCreation=true` to migrate a verified alias off the previous owner. On
|
||||
- Duplicate email/phone on `AdminCreateUser`: `UsernameExistsException` ("User account already
|
||||
exists"), as on AWS, whether or not either address is verified. `ForceAliasCreation=true` does not
|
||||
move the address off the previous owner, because it is that user's username. On
|
||||
`AdminUpdateUserAttributes`, changing to an in-use alias throws `AliasExistsException`.
|
||||
|
||||
Pools **without** `UsernameAttributes` (classic pools, and pools using `AliasAttributes`) keep the
|
||||
|
||||
@@ -2366,22 +2366,20 @@ public class CognitoService implements ResourceProvider, StoredResourceArns {
|
||||
// again. That includes a function calling back for the username it was given.
|
||||
String inFlightKey = regionResolver.getAccountId() + "::" + userKey(userPoolId, signInKey(pool, username));
|
||||
if (!userCreatesInFlight.add(inFlightKey)) {
|
||||
throw new AwsException("UsernameExistsException", "User already exists", 400);
|
||||
throw new AwsException("UsernameExistsException", "User account already exists", 400);
|
||||
}
|
||||
try {
|
||||
aliasHolderToMove(pool, username, forceAliasCreation);
|
||||
requireUsernameAvailable(pool, username);
|
||||
String password = initialPassword(pool, temporaryPassword);
|
||||
CognitoUser user = newAdminCreatedUser(pool, username, attributes, password);
|
||||
|
||||
// Before anything is stored, so a trigger that refuses the user leaves the pool unchanged,
|
||||
// including the alias a ForceAliasCreation request would move.
|
||||
// Before anything is stored, so a trigger that refuses the user leaves the pool unchanged.
|
||||
authFlowHandler.firePreSignUpForAdminCreateUser(pool, user, validationData, clientMetadata);
|
||||
Invitation invitation = "SUPPRESS".equals(messageAction) ? null : new Invitation(password,
|
||||
deliveryMediums, invitationCustomMessage(pool, user, deliveryMediums, clientMetadata));
|
||||
|
||||
synchronized (lock) {
|
||||
return storeAdminCreatedUserUnderUserLock(userPoolId, username, forceAliasCreation, user,
|
||||
invitation);
|
||||
return storeAdminCreatedUserUnderUserLock(userPoolId, username, user, invitation);
|
||||
}
|
||||
} finally {
|
||||
userCreatesInFlight.remove(inFlightKey);
|
||||
@@ -2463,31 +2461,19 @@ public class CognitoService implements ResourceProvider, StoredResourceArns {
|
||||
}
|
||||
|
||||
/**
|
||||
* The user whose verified alias an AdminCreateUser for {@code username} moves to the new user,
|
||||
* or null when no user has that username or alias. Throws when one does and the request
|
||||
* cannot take it: {@code UsernameExistsException} for a username or an unverified alias, and
|
||||
* {@code AliasExistsException} for a verified alias without ForceAliasCreation.
|
||||
* Refuses an AdminCreateUser for {@code username} when a user already has it as their username
|
||||
* or, in a {@code UsernameAttributes} pool, as their sign-in email or phone number. AWS answers
|
||||
* {@code UsernameExistsException} there whether or not the address is verified, and
|
||||
* ForceAliasCreation does not move it to the new user.
|
||||
*/
|
||||
private CognitoUser aliasHolderToMove(UserPool pool, String username, boolean forceAliasCreation) {
|
||||
private void requireUsernameAvailable(UserPool pool, String username) {
|
||||
CognitoUser existing = findUserByUsername(pool, username);
|
||||
String aliasAttribute = null;
|
||||
if (usesAliasUsernames(pool) && existing == null) {
|
||||
aliasAttribute = aliasAttributeForValue(pool, username);
|
||||
existing = findUserByAlias(pool.getId(), aliasAttribute, username);
|
||||
existing = findUserByAlias(pool.getId(), aliasAttributeForValue(pool, username), username);
|
||||
}
|
||||
if (existing == null) {
|
||||
return null;
|
||||
if (existing != null) {
|
||||
throw new AwsException("UsernameExistsException", "User account already exists", 400);
|
||||
}
|
||||
boolean existingAliasVerified = aliasAttribute != null
|
||||
&& "true".equalsIgnoreCase(existing.getAttributes().get(aliasAttribute + "_verified"));
|
||||
if (!existingAliasVerified) {
|
||||
throw new AwsException("UsernameExistsException", "User already exists", 400);
|
||||
}
|
||||
if (!forceAliasCreation) {
|
||||
throw new AwsException("AliasExistsException",
|
||||
"An account with the given " + aliasAttribute + " already exists.", 400);
|
||||
}
|
||||
return existing;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2635,26 +2621,15 @@ public class CognitoService implements ResourceProvider, StoredResourceArns {
|
||||
}
|
||||
}
|
||||
|
||||
private CognitoUser storeAdminCreatedUserUnderUserLock(String userPoolId, String username,
|
||||
boolean forceAliasCreation, CognitoUser user,
|
||||
private CognitoUser storeAdminCreatedUserUnderUserLock(String userPoolId, String username, CognitoUser user,
|
||||
Invitation invitation) {
|
||||
// Read again under the lock rather than reused from before the triggers: while they ran, the
|
||||
// pool may have been deleted, another request may have taken the username or alias, and
|
||||
// the alias holder may have been updated or deleted, which writing back an earlier read
|
||||
// would undo.
|
||||
// pool may have been deleted or another request may have taken the username.
|
||||
UserPool pool = describeUserPool(userPoolId);
|
||||
CognitoUser aliasHolder = aliasHolderToMove(pool, username, forceAliasCreation);
|
||||
requireUsernameAvailable(pool, username);
|
||||
// Sent once nothing else can refuse the request and before anything is stored, so a failed
|
||||
// delivery leaves no user behind and the alias where it was.
|
||||
// delivery leaves no user behind.
|
||||
deliverInvitation(pool, user, invitation);
|
||||
if (aliasHolder != null) {
|
||||
String aliasAttribute = aliasAttributeForValue(pool, username);
|
||||
aliasHolder.getAttributes().remove(aliasAttribute);
|
||||
aliasHolder.getAttributes().put(aliasAttribute + "_verified", "false");
|
||||
aliasHolder.setLastModifiedDate(System.currentTimeMillis() / 1000L);
|
||||
userStore.put(userKey(userPoolId, aliasHolder.getUsername()), aliasHolder);
|
||||
}
|
||||
|
||||
userStore.put(userKey(userPoolId, user.getUsername()), user);
|
||||
LOG.infov("Created user {0} in pool {1}", user.getUsername(), userPoolId);
|
||||
return user;
|
||||
|
||||
@@ -831,30 +831,6 @@ class CognitoLambdaTriggersTest {
|
||||
assertNull(user.getAttributes().get("phone_number_verified"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void preSignUpLambdaErrorOnForcedAliasCreationKeepsTheExistingAlias() {
|
||||
Map<String, Object> poolRequest = new HashMap<>();
|
||||
poolRequest.put("PoolName", "alias-trigger-pool");
|
||||
poolRequest.put("UsernameAttributes", List.of("email"));
|
||||
poolRequest.put("LambdaConfig", Map.of("PreSignUp", "arn:aws:lambda:::pre-signup"));
|
||||
UserPool pool = service.createUserPool(poolRequest, "us-east-1");
|
||||
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-signup"),
|
||||
any(byte[].class), any()))
|
||||
.thenReturn(ok(Map.of()))
|
||||
.thenReturn(lambdaError("Unhandled", "Refused"));
|
||||
CognitoUser holder = service.adminCreateUser(pool.getId(), "alice@example.com",
|
||||
Map.of("email_verified", "true"), null, "SUPPRESS");
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
service.adminCreateUser(pool.getId(), "alice@example.com",
|
||||
Map.of("email_verified", "true"), null, "SUPPRESS", true));
|
||||
assertEquals("UserLambdaValidationException", ex.getErrorCode());
|
||||
|
||||
CognitoUser after = service.adminGetUser(pool.getId(), holder.getUsername());
|
||||
assertEquals("alice@example.com", after.getAttributes().get("email"));
|
||||
assertEquals("true", after.getAttributes().get("email_verified"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void preSignUpFunctionCallingBackForTheSameUsernameIsNotBlocked() {
|
||||
UserPool pool = createPoolWithLambdaConfig(Map.of("PreSignUp", "arn:aws:lambda:::pre-signup"));
|
||||
@@ -914,7 +890,7 @@ class CognitoLambdaTriggersTest {
|
||||
AwsException second = assertThrows(AwsException.class, () -> service.adminCreateUser(pool.getId(),
|
||||
"alice", Map.of("name", "second"), null, "SUPPRESS"));
|
||||
assertEquals("UsernameExistsException", second.getErrorCode());
|
||||
assertEquals("User already exists", second.getMessage());
|
||||
assertEquals("User account already exists", second.getMessage());
|
||||
|
||||
releaseFirst.countDown();
|
||||
assertEquals("alice", first.get(10, TimeUnit.SECONDS).getUsername());
|
||||
@@ -973,66 +949,6 @@ class CognitoLambdaTriggersTest {
|
||||
assertEquals("retry", service.adminGetUser(pool.getId(), "alice").getAttributes().get("name"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void forcedAliasCreationDoesNotRestoreAHolderThePreSignUpFunctionDeleted() {
|
||||
UserPool pool = createEmailUsernamePoolWithPreSignUp();
|
||||
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-signup"),
|
||||
any(byte[].class), any()))
|
||||
.thenReturn(ok(Map.of()))
|
||||
.thenAnswer(invocation -> {
|
||||
callFromFunction(() -> {
|
||||
service.adminDeleteUser(pool.getId(), "alice@example.com");
|
||||
return null;
|
||||
});
|
||||
return ok(Map.of());
|
||||
});
|
||||
CognitoUser holder = service.adminCreateUser(pool.getId(), "alice@example.com",
|
||||
Map.of("email_verified", "true"), null, "SUPPRESS");
|
||||
|
||||
CognitoUser created = service.adminCreateUser(pool.getId(), "alice@example.com",
|
||||
Map.of("email_verified", "true"), null, "SUPPRESS", true);
|
||||
|
||||
AwsException lookup = assertThrows(AwsException.class, () ->
|
||||
service.adminGetUser(pool.getId(), holder.getUsername()));
|
||||
assertEquals("UserNotFoundException", lookup.getErrorCode());
|
||||
assertEquals(created.getUsername(),
|
||||
service.adminGetUser(pool.getId(), "alice@example.com").getUsername());
|
||||
}
|
||||
|
||||
@Test
|
||||
void forcedAliasCreationKeepsTheEmailThePreSignUpFunctionGaveTheHolder() {
|
||||
UserPool pool = createEmailUsernamePoolWithPreSignUp();
|
||||
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-signup"),
|
||||
any(byte[].class), any()))
|
||||
.thenReturn(ok(Map.of()))
|
||||
.thenAnswer(invocation -> {
|
||||
callFromFunction(() -> {
|
||||
service.adminUpdateUserAttributes(pool.getId(), "alice@example.com",
|
||||
Map.of("email", "alice.new@example.com"));
|
||||
return null;
|
||||
});
|
||||
return ok(Map.of());
|
||||
});
|
||||
CognitoUser holder = service.adminCreateUser(pool.getId(), "alice@example.com",
|
||||
Map.of("email_verified", "true"), null, "SUPPRESS");
|
||||
|
||||
CognitoUser created = service.adminCreateUser(pool.getId(), "alice@example.com",
|
||||
Map.of("email_verified", "true"), null, "SUPPRESS", true);
|
||||
|
||||
assertEquals("alice.new@example.com",
|
||||
service.adminGetUser(pool.getId(), holder.getUsername()).getAttributes().get("email"));
|
||||
assertEquals(created.getUsername(),
|
||||
service.adminGetUser(pool.getId(), "alice@example.com").getUsername());
|
||||
}
|
||||
|
||||
private UserPool createEmailUsernamePoolWithPreSignUp() {
|
||||
Map<String, Object> poolRequest = new HashMap<>();
|
||||
poolRequest.put("PoolName", "alias-trigger-pool");
|
||||
poolRequest.put("UsernameAttributes", List.of("email"));
|
||||
poolRequest.put("LambdaConfig", Map.of("PreSignUp", "arn:aws:lambda:::pre-signup"));
|
||||
return service.createUserPool(poolRequest, "us-east-1");
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes {@code call} the way a trigger function's SDK call reaches Floci: from another thread,
|
||||
* while the request that invoked the function waits for it to return.
|
||||
|
||||
@@ -6229,7 +6229,7 @@ class CognitoServiceTest {
|
||||
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());
|
||||
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@Example.com", "Valid-password123!", Map.of(), Map.of(), Map.of()));
|
||||
@@ -6641,7 +6641,7 @@ class CognitoServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void emailAliasPoolVerifiedDuplicateThrowsAliasExists() {
|
||||
void emailAliasPoolVerifiedDuplicateWithVerifiedFlagThrowsUsernameExists() {
|
||||
UserPool pool = createEmailAliasPool();
|
||||
service.adminCreateUser(pool.getId(), "dupe@b.com",
|
||||
new HashMap<>(Map.of("email", "dupe@b.com", "email_verified", "true")), null);
|
||||
@@ -6649,33 +6649,46 @@ class CognitoServiceTest {
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> service.adminCreateUser(pool.getId(), "dupe@b.com",
|
||||
new HashMap<>(Map.of("email", "dupe@b.com", "email_verified", "true")), null));
|
||||
assertEquals("AliasExistsException", ex.getErrorCode());
|
||||
assertEquals("UsernameExistsException", ex.getErrorCode());
|
||||
assertEquals("User account already exists", ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void emailAliasPoolAliasExistsUsesExistingVerificationNotIncoming() {
|
||||
void emailAliasPoolVerifiedDuplicateWithoutVerifiedFlagThrowsUsernameExists() {
|
||||
UserPool pool = createEmailAliasPool();
|
||||
// Existing owner holds a *verified* alias.
|
||||
service.adminCreateUser(pool.getId(), "owner@b.com",
|
||||
new HashMap<>(Map.of("email", "owner@b.com", "email_verified", "true")), null);
|
||||
|
||||
// The second create omits email_verified from its own payload. The exception
|
||||
// type must be driven by the existing owner's verified alias -> AliasExistsException.
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> service.adminCreateUser(pool.getId(), "owner@b.com",
|
||||
new HashMap<>(Map.of("email", "owner@b.com")), null));
|
||||
assertEquals("AliasExistsException", ex.getErrorCode());
|
||||
assertEquals("UsernameExistsException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void emailAliasPoolIncomingVerifiedFlagCannotForceAliasExists() {
|
||||
void emailAliasPoolForceAliasCreationDoesNotTakeAVerifiedUsername() {
|
||||
UserPool pool = createEmailAliasPool();
|
||||
CognitoUser first = service.adminCreateUser(pool.getId(), "move@b.com",
|
||||
new HashMap<>(Map.of("email", "move@b.com", "email_verified", "true")), null);
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> service.adminCreateUser(pool.getId(), "move@b.com",
|
||||
new HashMap<>(Map.of("email", "move@b.com", "email_verified", "true")), null, null, true));
|
||||
assertEquals("UsernameExistsException", ex.getErrorCode());
|
||||
|
||||
List<CognitoUser> users = service.listUsers(pool.getId(), null);
|
||||
assertEquals(1, users.size());
|
||||
assertEquals(first.getUsername(), users.get(0).getUsername());
|
||||
assertEquals("move@b.com", users.get(0).getAttributes().get("email"));
|
||||
assertEquals("true", users.get(0).getAttributes().get("email_verified"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void emailAliasPoolUnverifiedDuplicateWithVerifiedFlagThrowsUsernameExists() {
|
||||
UserPool pool = createEmailAliasPool();
|
||||
// Existing owner's alias is *unverified*, so the alias is not reserved.
|
||||
service.adminCreateUser(pool.getId(), "unv@b.com",
|
||||
new HashMap<>(Map.of("email", "unv@b.com")), null);
|
||||
|
||||
// A caller-supplied email_verified=true must not upgrade the decision:
|
||||
// the existing owner is unverified -> UsernameExistsException, not AliasExistsException.
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> service.adminCreateUser(pool.getId(), "unv@b.com",
|
||||
new HashMap<>(Map.of("email", "unv@b.com", "email_verified", "true")), null));
|
||||
@@ -6683,34 +6696,15 @@ class CognitoServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void emailAliasPoolForceAliasCreationReclaimsWithoutIncomingVerifiedFlag() {
|
||||
void emailAliasPoolUnverifiedDuplicateWithoutVerifiedFlagThrowsUsernameExists() {
|
||||
UserPool pool = createEmailAliasPool();
|
||||
CognitoUser first = service.adminCreateUser(pool.getId(), "reclaim@b.com",
|
||||
new HashMap<>(Map.of("email", "reclaim@b.com", "email_verified", "true")), null);
|
||||
service.adminCreateUser(pool.getId(), "unv@b.com",
|
||||
new HashMap<>(Map.of("email", "unv@b.com")), null);
|
||||
|
||||
// ForceAliasCreation reclaim keys off the existing owner's verified alias and
|
||||
// must not require the caller to re-send email_verified in the new payload.
|
||||
CognitoUser second = service.adminCreateUser(pool.getId(), "reclaim@b.com",
|
||||
new HashMap<>(Map.of("email", "reclaim@b.com")), null, null, true);
|
||||
|
||||
assertNotEquals(first.getUsername(), second.getUsername());
|
||||
assertEquals(second.getUsername(), service.adminGetUser(pool.getId(), "reclaim@b.com").getUsername());
|
||||
assertNull(service.adminGetUser(pool.getId(), first.getUsername()).getAttributes().get("email"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void emailAliasPoolForceAliasCreationMigratesVerifiedAlias() {
|
||||
UserPool pool = createEmailAliasPool();
|
||||
CognitoUser first = service.adminCreateUser(pool.getId(), "move@b.com",
|
||||
new HashMap<>(Map.of("email", "move@b.com", "email_verified", "true")), null);
|
||||
|
||||
CognitoUser second = service.adminCreateUser(pool.getId(), "move@b.com",
|
||||
new HashMap<>(Map.of("email", "move@b.com", "email_verified", "true")), null, null, true);
|
||||
|
||||
assertNotEquals(first.getUsername(), second.getUsername());
|
||||
// The alias now resolves to the new user; the previous user lost it.
|
||||
assertEquals(second.getUsername(), service.adminGetUser(pool.getId(), "move@b.com").getUsername());
|
||||
assertNull(service.adminGetUser(pool.getId(), first.getUsername()).getAttributes().get("email"));
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> service.adminCreateUser(pool.getId(), "unv@b.com",
|
||||
new HashMap<>(Map.of("email", "unv@b.com")), null));
|
||||
assertEquals("UsernameExistsException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -7473,26 +7467,6 @@ class CognitoServiceTest {
|
||||
AwsException lookup = assertThrows(AwsException.class, () -> svc.adminGetUser(pool.getId(), "alice"));
|
||||
assertEquals("UserNotFoundException", lookup.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedInvitationDelivery_withForceAliasCreation_leavesTheAliasWithItsHolder() {
|
||||
Map<String, Object> poolRequest = Map.of("PoolName", "AliasInvitePool",
|
||||
"UsernameAttributes", List.of("email"));
|
||||
UserPool pool = svc.createUserPool(poolRequest, "us-east-1");
|
||||
CognitoUser holder = create(pool, "alice@example.com", Map.of("email_verified", "true"), "Temp1234!",
|
||||
"SUPPRESS", List.of("EMAIL"));
|
||||
failDelivery();
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () -> svc.adminCreateUser(pool.getId(),
|
||||
"alice@example.com", Map.of("email_verified", "true"), null, null, true, List.of("EMAIL"),
|
||||
Map.of(), Map.of()));
|
||||
|
||||
assertEquals("CodeDeliveryFailureException", failure.getErrorCode());
|
||||
CognitoUser after = svc.adminGetUser(pool.getId(), holder.getUsername());
|
||||
assertEquals("alice@example.com", after.getAttributes().get("email"));
|
||||
assertEquals("true", after.getAttributes().get("email_verified"));
|
||||
assertEquals(holder.getUsername(), svc.adminGetUser(pool.getId(), "alice@example.com").getUsername());
|
||||
}
|
||||
}
|
||||
|
||||
// --- replaceGroupDescription: a service method that does not exist on main ---
|
||||
|
||||
Reference in new issue
Block a user