From 69b4d17c678f6a2b568274b4e206bb11db5cd6c8 Mon Sep 17 00:00:00 2001 From: jwoa95 <88512616+jwoa95@users.noreply.github.com> Date: Tue, 6 Oct 2026 13:18:14 +0100 Subject: [PATCH] fix(cognito): run the PreSignUp trigger on AdminCreateUser (#5149) * fix(cognito): run the PreSignUp trigger on AdminCreateUser AWS invokes the pre sign-up trigger when AdminCreateUser creates a user, with triggerSource PreSignUp_AdminCreateUser, the request's ValidationData and ClientMetadata, and ignores the response's autoConfirmUser, autoVerifyEmail and autoVerifyPhone. A trigger error refuses the user. The trigger runs before anything is stored, so a refused ForceAliasCreation request no longer moves the alias off the existing user. * fix(cognito): invoke PreSignUp outside the user lock on AdminCreateUser AdminCreateUser held the lock stripe of the requested username while the pre sign-up trigger ran. A function that called back into the pool for an identifier on the same stripe, such as AdminCreateUser for the same username, waited for that lock until the invocation timed out. The trigger now runs with no lock held. A taken username or alias is still refused before the trigger is invoked, and the checks run again under the lock once it accepts, so a user created while the trigger ran still fails the request with UsernameExistsException. With ForceAliasCreation, the alias holder was read before the trigger and written back after it, which could undo a change made to the holder in the meantime or restore a deleted holder. The holder is now looked up under the lock after the trigger, just before its alias is moved. * fix(cognito): run PreSignUp once per in-flight AdminCreateUser username With the pre sign-up trigger running outside the user lock, two overlapping AdminCreateUser requests for the same free username could both pass the existence check and both invoke the trigger. The later one was then refused under the lock after its function had already run, or failed with the function's own error instead of UsernameExistsException. AdminCreateUser now claims the username before checking it and gives the claim up once the user is stored or the request fails. An overlapping request for the same username, including one the function makes for the username it was given, is refused with UsernameExistsException before it invokes the trigger. --- docs/services/cognito.md | 2 +- .../CognitoUserPoolUserCfnProvisioner.java | 6 +- .../cognito/CognitoAuthFlowHandler.java | 26 +- .../services/cognito/CognitoJsonHandler.java | 8 +- .../services/cognito/CognitoService.java | 183 +++++++---- .../cognito/CognitoLambdaTriggersTest.java | 309 ++++++++++++++++++ 6 files changed, 471 insertions(+), 63 deletions(-) diff --git a/docs/services/cognito.md b/docs/services/cognito.md index adebb5e6c9..5a4fe53743 100644 --- a/docs/services/cognito.md +++ b/docs/services/cognito.md @@ -181,7 +181,7 @@ further divergences, both deliberate: | Action | Description | |--------|-------------| -| AdminCreateUser | Creates or resends setup for a user in a user pool. | +| AdminCreateUser | Creates or resends setup for a user in a user pool. Creating a user invokes the pre sign-up trigger with triggerSource `PreSignUp_AdminCreateUser`, the request's `ValidationData` and `ClientMetadata`, and `callerContext.clientId` `CLIENT_ID_NOT_APPLICABLE`. A trigger error refuses the user with `UserLambdaValidationException`, and its `autoConfirmUser`, `autoVerifyEmail` and `autoVerifyPhone` are ignored, as on AWS. | | AdminGetUser | Returns a user's stored attributes and status. | | AdminDeleteUser | Deletes a user from a user pool. An API Gateway Cognito authorizer rejects the user's existing tokens afterwards. | | AdminSetUserPassword | Sets a user's password and permanent-password status. | diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoUserPoolUserCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoUserPoolUserCfnProvisioner.java index 8e65a63ba1..56ca8bec78 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoUserPoolUserCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoUserPoolUserCfnProvisioner.java @@ -76,9 +76,9 @@ public class CognitoUserPoolUserCfnProvisioner implements CfnResourceProvisioner for (JsonNode attribute : resolved.path("UserAttributes")) { userAttributes.put(attribute.path("Name").asText(), attribute.path("Value").asText()); } - // DesiredDeliveryMediums, ValidationData and ClientMetadata only reach a message transport - // or a Lambda trigger, neither of which AdminCreateUser drives here, so they only take part - // in the createOnly record. + // DesiredDeliveryMediums only reaches a message transport, which AdminCreateUser does not + // drive here. ValidationData and ClientMetadata are not passed to the PreSignUp trigger, + // which sees empty maps. All three only take part in the createOnly record. String name = customNamed ? username : ctx.generatePhysicalName(r.getLogicalId(), 128, false); String messageAction = text(resolved, "MessageAction"); if ("RESEND".equalsIgnoreCase(messageAction)) { diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java index 0a53da69a7..4d632ef257 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java @@ -52,6 +52,8 @@ final class CognitoAuthFlowHandler { private static final Logger LOG = Logger.getLogger(CognitoAuthFlowHandler.class); private static final ObjectMapper MAPPER = new ObjectMapper(); private static final String CUSTOM_MESSAGE_CODE_PARAMETER = "{####}"; + /** The {@code callerContext.clientId} AWS sends for an admin action, which names no app client. */ + private static final String CLIENT_ID_NOT_APPLICABLE = "CLIENT_ID_NOT_APPLICABLE"; /** The message of a wrong password, which managed login also shows for an unknown user. */ static final String INCORRECT_CREDENTIALS = "Incorrect username or password"; static final int MAX_USER_AUTH_SESSIONS_PER_PARTITION = 4_096; @@ -1538,7 +1540,7 @@ final class CognitoAuthFlowHandler { event.put("userName", user == null ? null : user.getUsername()); event.put("callerContext", Map.of( "awsSdkVersion", "floci", - "clientId", client.getClientId())); + "clientId", client == null ? CLIENT_ID_NOT_APPLICABLE : client.getClientId())); event.put("triggerSource", triggerSource); Map req = new HashMap<>(request); if (user != null) { @@ -1703,6 +1705,28 @@ final class CognitoAuthFlowHandler { Boolean.TRUE.equals(resp.get("autoVerifyPhone"))); } + /** + * Fires PreSignUp with triggerSource {@code PreSignUp_AdminCreateUser}. AWS ignores + * {@code autoConfirmUser}, {@code autoVerifyEmail} and {@code autoVerifyPhone} for this + * source, so the response is discarded and only a failure changes the outcome. + */ + void firePreSignUpForAdminCreateUser(UserPool pool, CognitoUser user, + Map validationData, + Map clientMetadata) { + Map req = new HashMap<>(); + req.put("validationData", validationData == null ? Map.of() : validationData); + req.put("clientMetadata", clientMetadata == null ? Map.of() : clientMetadata); + TriggerResult result = invokeTrigger(pool, null, user, "PreSignUp", "PreSignUp_AdminCreateUser", req); + if (!result.errored()) { + return; + } + if (result.errorKind() == TriggerErrorKind.USER_VALIDATION) { + throw new AwsException("UserLambdaValidationException", + "PreSignUp failed with error " + result.errorMessage() + ".", 400); + } + throw triggerFailure(result, "PreSignUp"); + } + /** * Fires the CustomMessage trigger, if configured, so the function can override the * subject/body Cognito would otherwise deliver. Non-blocking: an unconfigured or diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java index 2f162518fc..b05ac041c3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java @@ -611,6 +611,10 @@ public class CognitoJsonHandler { : request.path("TemporaryPassword").asText(null); String messageAction = request.path("MessageAction").isMissingNode() ? null : request.path("MessageAction").asText(null); + Map validationData = new HashMap<>(); + request.path("ValidationData").forEach(a -> validationData.put(a.path("Name").asText(), a.path("Value").asText())); + Map clientMetadata = new HashMap<>(); + request.path("ClientMetadata").fields().forEachRemaining(e -> clientMetadata.put(e.getKey(), e.getValue().asText())); CognitoUser user = service.adminCreateUser( request.path("UserPoolId").asText(), @@ -618,7 +622,9 @@ public class CognitoJsonHandler { attrs, tempPassword, messageAction, - request.path("ForceAliasCreation").asBoolean(false) + request.path("ForceAliasCreation").asBoolean(false), + validationData, + clientMetadata ); ObjectNode response = objectMapper.createObjectNode(); response.set("User", userToNode(user)); 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 1b10d799d5..5c3696c716 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 @@ -79,6 +79,7 @@ import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Pattern; import static io.github.hectorvent.floci.core.common.ReservedTags.rejectUnknownReservedTags; @@ -148,6 +149,10 @@ public class CognitoService implements ResourceProvider { private final CognitoMessageDispatcher messageDispatcher; private final TlsCertificateManager certificateManager; private final Object[] userLocks = newUserLockStripes(); + // The userKey of each username an AdminCreateUser is creating, from before its existence check + // until it stores the user or fails, so an overlapping request for the same username is refused + // instead of invoking the PreSignUp trigger again. Only the request that adds a key removes it. + private final Set adminCreatesInFlight = ConcurrentHashMap.newKeySet(); // Keyed by session token; contains SRP ephemeral state (bPrivate, B, A, secretBlock) private final CognitoAuthFlowHandler authFlowHandler; @@ -2022,78 +2027,124 @@ public class CognitoService implements ResourceProvider { String temporaryPassword, String messageAction, boolean forceAliasCreation) { - // Locked on the requested username/alias (not yet resolved to a canonical id, since - // an alias pool doesn't have one until creation), so two concurrent requests for the - // same identifier can't both pass the existence/alias check and create duplicates. - synchronized (userLock(userPoolId, username)) { - return adminCreateUserUnderUserLock(userPoolId, username, attributes, - temporaryPassword, messageAction, forceAliasCreation); - } + return adminCreateUser(userPoolId, username, attributes, temporaryPassword, messageAction, + forceAliasCreation, Map.of(), Map.of()); } - private CognitoUser adminCreateUserUnderUserLock(String userPoolId, + /** + * AdminCreateUser with the request's {@code ValidationData} and {@code ClientMetadata}, which + * reach only the PreSignUp trigger and are never stored. + */ + public CognitoUser adminCreateUser(String userPoolId, String username, Map attributes, String temporaryPassword, String messageAction, - boolean forceAliasCreation) { - UserPool pool = describeUserPool(userPoolId); - boolean resend = "RESEND".equalsIgnoreCase(messageAction); - boolean aliasPool = usesAliasUsernames(pool); + boolean forceAliasCreation, + Map validationData, + Map clientMetadata) { + // Locked on the requested username/alias (not yet resolved to a canonical id, since + // an alias pool doesn't have one until creation), so two concurrent requests for the + // same identifier can't both pass the existence/alias check and create duplicates. + Object lock = userLock(userPoolId, username); + if ("RESEND".equalsIgnoreCase(messageAction)) { + synchronized (lock) { + return resendInvitationUnderUserLock(userPoolId, username); + } + } + // The PreSignUp trigger runs with no lock held: its function can call back into the pool, + // and a call that needs the same lock stripe would wait until the invocation timed out. + // A taken username or alias is refused before the trigger sees the request, and checked + // again under the lock once the trigger accepts, since users can change while it runs. + UserPool pool = describeUserPool(userPoolId); + // 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 = userKey(userPoolId, username); + if (!adminCreatesInFlight.add(inFlightKey)) { + throw new AwsException("UsernameExistsException", "User already exists", 400); + } + try { + aliasHolderToMove(pool, username, forceAliasCreation); + CognitoUser user = newAdminCreatedUser(pool, username, attributes, temporaryPassword); + + // Before anything is stored, so a trigger that refuses the user leaves the pool unchanged, + // including the alias a ForceAliasCreation request would move. + authFlowHandler.firePreSignUpForAdminCreateUser(pool, user, validationData, clientMetadata); + + synchronized (lock) { + return storeAdminCreatedUserUnderUserLock(userPoolId, username, forceAliasCreation, user); + } + } finally { + adminCreatesInFlight.remove(inFlightKey); + } + } + + private CognitoUser resendInvitationUnderUserLock(String userPoolId, String username) { + UserPool pool = describeUserPool(userPoolId); + CognitoUser existing = userStore.get(userKey(userPoolId, username)).orElse(null); + if (usesAliasUsernames(pool) && existing == null) { + existing = findUserByAlias(userPoolId, aliasAttributeForValue(pool, username), username); + } + if (existing == null) { + throw new AwsException("UserNotFoundException", "User not found", 400); + } + if (!"FORCE_CHANGE_PASSWORD".equals(existing.getUserStatus())) { + final String userStateExceptionMessage = """ + User is in %s state and cannot be resent an invitation. + """.formatted(existing.getUserStatus()); + throw new AwsException("UnsupportedUserStateException", userStateExceptionMessage, 400); + } + existing.setLastModifiedDate(System.currentTimeMillis() / 1000L); + userStore.put(userKey(userPoolId, existing.getUsername()), existing); + LOG.infov("Resent invitation for user {0} in pool {1}", existing.getUsername(), userPoolId); + return existing; + } + + /** + * 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. + */ + private CognitoUser aliasHolderToMove(UserPool pool, String username, boolean forceAliasCreation) { + CognitoUser existing = userStore.get(userKey(pool.getId(), username)).orElse(null); + String aliasAttribute = null; + if (usesAliasUsernames(pool) && existing == null) { + aliasAttribute = aliasAttributeForValue(pool, username); + existing = findUserByAlias(pool.getId(), aliasAttribute, username); + } + if (existing == null) { + return null; + } + 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; + } + + private CognitoUser newAdminCreatedUser(UserPool pool, String username, Map attributes, + String temporaryPassword) { Map resolvedAttributes = attributes == null ? new HashMap<>() : new HashMap<>(attributes); - CognitoUser existing = userStore.get(userKey(userPoolId, username)).orElse(null); - String aliasAttribute = null; - if (aliasPool && existing == null) { - aliasAttribute = aliasAttributeForValue(pool, username); - existing = findUserByAlias(userPoolId, aliasAttribute, username); - } - - if (resend) { - if (existing == null) { - throw new AwsException("UserNotFoundException", "User not found", 400); - } - if (!"FORCE_CHANGE_PASSWORD".equals(existing.getUserStatus())) { - final String userStateExceptionMessage = """ - User is in %s state and cannot be resent an invitation. - """.formatted(existing.getUserStatus()); - throw new AwsException("UnsupportedUserStateException", userStateExceptionMessage, 400); - } - existing.setLastModifiedDate(System.currentTimeMillis() / 1000L); - userStore.put(userKey(userPoolId, existing.getUsername()), existing); - LOG.infov("Resent invitation for user {0} in pool {1}", existing.getUsername(), userPoolId); - return existing; - } - - if (existing != null) { - boolean existingAliasVerified = aliasAttribute != null - && "true".equalsIgnoreCase(existing.getAttributes().get(aliasAttribute + "_verified")); - if (existingAliasVerified) { - if (!forceAliasCreation) { - throw new AwsException("AliasExistsException", - "An account with the given " + aliasAttribute + " already exists.", 400); - } - existing.getAttributes().remove(aliasAttribute); - existing.getAttributes().put(aliasAttribute + "_verified", "false"); - existing.setLastModifiedDate(System.currentTimeMillis() / 1000L); - userStore.put(userKey(userPoolId, existing.getUsername()), existing); - } else { - throw new AwsException("UsernameExistsException", "User already exists", 400); - } - } - String canonicalUsername = username; - if (aliasPool) { - resolvedAttributes.put(aliasAttribute, username); + if (usesAliasUsernames(pool)) { + resolvedAttributes.put(aliasAttributeForValue(pool, username), username); canonicalUsername = UUID.randomUUID().toString(); resolvedAttributes.put("sub", canonicalUsername); } CognitoUser user = new CognitoUser(); user.setUsername(canonicalUsername); - user.setUserPoolId(userPoolId); + user.setUserPoolId(pool.getId()); user.getAttributes().putAll(resolvedAttributes); // Ensure sub attribute is present @@ -2106,9 +2157,27 @@ public class CognitoService implements ResourceProvider { user.setTemporaryPassword(true); user.setUserStatus("FORCE_CHANGE_PASSWORD"); } + return user; + } - userStore.put(userKey(userPoolId, canonicalUsername), user); - LOG.infov("Created user {0} in pool {1}", canonicalUsername, userPoolId); + private CognitoUser storeAdminCreatedUserUnderUserLock(String userPoolId, String username, + boolean forceAliasCreation, CognitoUser user) { + // Read again under the lock rather than reused from before the trigger: while it 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. + UserPool pool = describeUserPool(userPoolId); + CognitoUser aliasHolder = aliasHolderToMove(pool, username, forceAliasCreation); + 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; } diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java index b8e64ea0ee..782758b10f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java @@ -1,7 +1,9 @@ package io.github.hectorvent.floci.services.cognito; import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.config.TlsCertificateManager; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; @@ -27,7 +29,9 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.NullAndEmptySource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; +import org.mockito.invocation.InvocationOnMock; +import java.io.IOException; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.Base64; @@ -35,15 +39,26 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.concurrent.Callable; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; @@ -485,6 +500,300 @@ class CognitoLambdaTriggersTest { .invoke(anyString(), anyString(), any(byte[].class), any()); } + @Test + void preSignUpFiresOnAdminCreateUserWithValidationDataAndClientMetadata() throws Exception { + UserPool pool = createPoolWithLambdaConfig(Map.of("PreSignUp", "arn:aws:lambda:::pre-signup")); + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-signup"), + any(byte[].class), eq(InvocationType.RequestResponse))) + .thenReturn(ok(Map.of())); + + ObjectNode request = MAPPER.createObjectNode(); + request.put("UserPoolId", pool.getId()); + request.put("Username", "alice"); + request.put("MessageAction", "SUPPRESS"); + request.putArray("UserAttributes").addObject().put("Name", "email").put("Value", "alice@example.com"); + request.putArray("ValidationData").addObject().put("Name", "inviteCode").put("Value", "abc123"); + request.putObject("ClientMetadata").put("source", "admin-console"); + new CognitoJsonHandler(service, MAPPER).handle("AdminCreateUser", request, "us-east-1"); + + ArgumentCaptor payloadCaptor = ArgumentCaptor.forClass(byte[].class); + verify(lambdaService).invoke(anyString(), eq("arn:aws:lambda:::pre-signup"), + payloadCaptor.capture(), eq(InvocationType.RequestResponse)); + JsonNode event = MAPPER.readTree(payloadCaptor.getValue()); + assertEquals("PreSignUp_AdminCreateUser", event.path("triggerSource").asText()); + assertEquals("CLIENT_ID_NOT_APPLICABLE", event.path("callerContext").path("clientId").asText()); + assertEquals("alice", event.path("userName").asText()); + assertEquals("alice@example.com", event.path("request").path("userAttributes").path("email").asText()); + assertEquals("abc123", event.path("request").path("validationData").path("inviteCode").asText()); + assertEquals("admin-console", event.path("request").path("clientMetadata").path("source").asText()); + assertFalse(service.adminGetUser(pool.getId(), "alice").getAttributes().containsKey("inviteCode"), + "ValidationData must not be stored as a user attribute"); + } + + @Test + void preSignUpLambdaErrorBlocksAdminCreateUser() { + UserPool pool = createPoolWithLambdaConfig(Map.of("PreSignUp", "arn:aws:lambda:::pre-signup")); + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-signup"), + any(byte[].class), any())) + .thenReturn(lambdaError("Unhandled", "Invitations are closed")); + + AwsException ex = assertThrows(AwsException.class, () -> + service.adminCreateUser(pool.getId(), "alice", + Map.of("email", "alice@example.com"), null, "SUPPRESS")); + assertEquals("UserLambdaValidationException", ex.getErrorCode()); + assertEquals("PreSignUp failed with error Invitations are closed.", ex.getMessage()); + + AwsException lookup = assertThrows(AwsException.class, () -> + service.adminGetUser(pool.getId(), "alice")); + assertEquals("UserNotFoundException", lookup.getErrorCode()); + } + + @Test + void preSignUpAutoConfirmAndVerifyResponseIsIgnoredOnAdminCreateUser() { + // AWS ignores autoConfirmUser, autoVerifyEmail and autoVerifyPhone for PreSignUp_AdminCreateUser. + UserPool pool = createPoolWithLambdaConfig(Map.of("PreSignUp", "arn:aws:lambda:::pre-signup")); + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-signup"), + any(byte[].class), any())) + .thenReturn(ok(Map.of( + "autoConfirmUser", true, + "autoVerifyEmail", true, + "autoVerifyPhone", true))); + + CognitoUser user = service.adminCreateUser(pool.getId(), "alice", + Map.of("email", "alice@example.com", "phone_number", "+15551234567"), + "Temp1234!", "SUPPRESS"); + + verify(lambdaService).invoke(anyString(), eq("arn:aws:lambda:::pre-signup"), + any(byte[].class), eq(InvocationType.RequestResponse)); + assertEquals("FORCE_CHANGE_PASSWORD", user.getUserStatus()); + assertNull(user.getAttributes().get("email_verified")); + assertNull(user.getAttributes().get("phone_number_verified")); + } + + @Test + void preSignUpLambdaErrorOnForcedAliasCreationKeepsTheExistingAlias() { + Map 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")); + AtomicReference callbackFailure = new AtomicReference<>(); + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-signup"), + any(byte[].class), eq(InvocationType.RequestResponse))) + .thenAnswer(invocation -> { + try { + callFromFunction(() -> service.adminCreateUser(pool.getId(), "alice", + Map.of("name", "created by the function"), null, "SUPPRESS")); + } catch (ExecutionException e) { + callbackFailure.set(e.getCause()); + } + return ok(Map.of()); + }) + .thenReturn(ok(Map.of())); + + // The function's call is for the username the request is creating. It would wait out the + // invocation if the request held that username's lock stripe while the function ran, and + // it is refused rather than invoking the trigger a second time for the same username. + assertTimeoutPreemptively(Duration.ofSeconds(10), () -> service.adminCreateUser(pool.getId(), "alice", + Map.of("name", "created by the request"), null, "SUPPRESS")); + + assertEquals("UsernameExistsException", + assertInstanceOf(AwsException.class, callbackFailure.get()).getErrorCode()); + assertEquals("created by the request", + service.adminGetUser(pool.getId(), "alice").getAttributes().get("name")); + verify(lambdaService).invoke(anyString(), eq("arn:aws:lambda:::pre-signup"), + any(byte[].class), eq(InvocationType.RequestResponse)); + } + + @Test + void overlappingAdminCreateUserForTheSameUsernameInvokesPreSignUpOnce() throws Exception { + UserPool pool = createPoolWithLambdaConfig(Map.of("PreSignUp", "arn:aws:lambda:::pre-signup")); + List invokedFor = new CopyOnWriteArrayList<>(); + CountDownLatch firstInTrigger = new CountDownLatch(1); + CountDownLatch releaseFirst = new CountDownLatch(1); + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-signup"), + any(byte[].class), eq(InvocationType.RequestResponse))) + .thenAnswer(invocation -> { + String request = nameAttributeOf(invocation); + invokedFor.add(request); + if ("first".equals(request)) { + firstInTrigger.countDown(); + assertTrue(releaseFirst.await(10, TimeUnit.SECONDS)); + } + return ok(Map.of()); + }); + + ExecutorService firstRequest = Executors.newSingleThreadExecutor(); + try { + Future first = firstRequest.submit(() -> service.adminCreateUser(pool.getId(), "alice", + Map.of("name", "first"), null, "SUPPRESS")); + assertTrue(firstInTrigger.await(10, TimeUnit.SECONDS)); + + // The first request is still in its trigger, so no user named alice is stored yet. + 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()); + + releaseFirst.countDown(); + assertEquals("alice", first.get(10, TimeUnit.SECONDS).getUsername()); + } finally { + releaseFirst.countDown(); + firstRequest.shutdownNow(); + } + + assertEquals(List.of("first"), invokedFor); + assertEquals("first", service.adminGetUser(pool.getId(), "alice").getAttributes().get("name")); + } + + @Test + void adminCreateUserOverlappingAFailingPreSignUpIsRefusedAndTheUsernameIsFreedAfterwards() throws Exception { + UserPool pool = createPoolWithLambdaConfig(Map.of("PreSignUp", "arn:aws:lambda:::pre-signup")); + List invokedFor = new CopyOnWriteArrayList<>(); + CountDownLatch firstInTrigger = new CountDownLatch(1); + CountDownLatch releaseFirst = new CountDownLatch(1); + // The function refuses every user but the retried one, so a second request that reached it + // would fail with the function's error instead of UsernameExistsException. + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-signup"), + any(byte[].class), eq(InvocationType.RequestResponse))) + .thenAnswer(invocation -> { + String request = nameAttributeOf(invocation); + invokedFor.add(request); + if ("first".equals(request)) { + firstInTrigger.countDown(); + assertTrue(releaseFirst.await(10, TimeUnit.SECONDS)); + } + return "retry".equals(request) ? ok(Map.of()) : lambdaError("Unhandled", "Refused"); + }); + + ExecutorService firstRequest = Executors.newSingleThreadExecutor(); + try { + Future first = firstRequest.submit(() -> service.adminCreateUser(pool.getId(), "alice", + Map.of("name", "first"), null, "SUPPRESS")); + assertTrue(firstInTrigger.await(10, TimeUnit.SECONDS)); + + AwsException second = assertThrows(AwsException.class, () -> service.adminCreateUser(pool.getId(), + "alice", Map.of("name", "second"), null, "SUPPRESS")); + assertEquals("UsernameExistsException", second.getErrorCode()); + + releaseFirst.countDown(); + ExecutionException firstFailure = assertThrows(ExecutionException.class, + () -> first.get(10, TimeUnit.SECONDS)); + assertEquals("UserLambdaValidationException", + assertInstanceOf(AwsException.class, firstFailure.getCause()).getErrorCode()); + } finally { + releaseFirst.countDown(); + firstRequest.shutdownNow(); + } + + service.adminCreateUser(pool.getId(), "alice", Map.of("name", "retry"), null, "SUPPRESS"); + + assertEquals(List.of("first", "retry"), invokedFor); + 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 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. + */ + private static T callFromFunction(Callable call) throws Exception { + ExecutorService functionThread = Executors.newSingleThreadExecutor(); + try { + return functionThread.submit(call).get(30, TimeUnit.SECONDS); + } finally { + functionThread.shutdownNow(); + } + } + + /** + * The {@code name} attribute of the user a trigger invocation is for, which tells the tests' + * requests apart. + */ + private static String nameAttributeOf(InvocationOnMock invocation) throws IOException { + byte[] event = invocation.getArgument(2); + return MAPPER.readTree(event).path("request").path("userAttributes").path("name").asText(); + } + // ========================================================================= // PreTokenGeneration // =========================================================================