Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(cognito): run signup triggers outside user locks (#5783)

Aniket Shukla4776bfb899f8
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 fe3752f812..8b00f7fd85 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
@@ -180,10 +180,8 @@ public class CognitoService implements ResourceProvider {
private final TlsCertificateManager certificateManager;
private final boolean enforceTokenValidityLimits;
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<String> adminCreatesInFlight = ConcurrentHashMap.newKeySet();
+ // Reserve names per account through registration callbacks, without blocking their admin requests.
+ private final Set<String> userCreatesInFlight = ConcurrentHashMap.newKeySet();
// Keyed by session token; contains SRP ephemeral state (bPrivate, B, A, secretBlock)
private final CognitoAuthFlowHandler authFlowHandler;
@@ -2187,8 +2185,8 @@ public class CognitoService implements ResourceProvider {
// Claimed before the username is checked, so an overlapping request for it is refused here
// rather than passing the check while this one is in its trigger and invoking the trigger
// again. That includes a function calling back for the username it was given.
- String inFlightKey = userKey(userPoolId, username);
- if (!adminCreatesInFlight.add(inFlightKey)) {
+ String inFlightKey = regionResolver.getAccountId() + "::" + userKey(userPoolId, username);
+ if (!userCreatesInFlight.add(inFlightKey)) {
throw new AwsException("UsernameExistsException", "User already exists", 400);
}
try {
@@ -2207,7 +2205,7 @@ public class CognitoService implements ResourceProvider {
invitation);
}
} finally {
- adminCreatesInFlight.remove(inFlightKey);
+ userCreatesInFlight.remove(inFlightKey);
}
}
@@ -2628,6 +2626,10 @@ public class CognitoService implements ResourceProvider {
private void adminDeleteUserUnderUserLock(String userPoolId, String username) {
CognitoUser user = adminGetUser(userPoolId, username);
+ deleteUserRecordAndGroups(userPoolId, user);
+ }
+
+ private void deleteUserRecordAndGroups(String userPoolId, CognitoUser user) {
for (String groupName : new ArrayList<>(user.getGroupNames())) {
groupStore.get(groupKey(userPoolId, groupName)).ifPresent(group -> {
group.removeUserName(user.getUsername());
@@ -3285,16 +3287,21 @@ public class CognitoService implements ResourceProvider {
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found",
400));
String userPoolId = client.getUserPoolId();
- // Locked on the requested username/alias, same reasoning as adminCreateUser: an alias
- // pool has no canonical id to lock on until creation succeeds.
- synchronized (userLock(userPoolId, username)) {
- return signUpUnderUserLock(client, userPoolId, username, password, attributes);
+ String inFlightKey = regionResolver.getAccountId() + "::" + userKey(userPoolId, username);
+ if (!userCreatesInFlight.add(inFlightKey)) {
+ throw new AwsException("UsernameExistsException", "User already exists", 400);
+ }
+ try {
+ return signUpWithReservedUsername(client, userPoolId, username, password, attributes);
+ } finally {
+ userCreatesInFlight.remove(inFlightKey);
}
}
- private CognitoUser signUpUnderUserLock(UserPoolClient client, String userPoolId,
+ private CognitoUser signUpWithReservedUsername(UserPoolClient client, String userPoolId,
String username, String password, Map<String, String> attributes) {
UserPool pool = describeUserPool(userPoolId);
+ requireAvailableSignUpUsername(pool, username);
boolean aliasPool = usesAliasUsernames(pool);
Map<String, String> resolvedAttributes = attributes == null
@@ -3302,14 +3309,9 @@ public class CognitoService implements ResourceProvider {
String canonicalUsername = username;
if (aliasPool) {
String aliasAttribute = aliasAttributeForValue(pool, username);
- if (findUserByAlias(userPoolId, aliasAttribute, username) != null) {
- throw new AwsException("UsernameExistsException", "User already exists", 400);
- }
resolvedAttributes.put(aliasAttribute, username);
canonicalUsername = UUID.randomUUID().toString();
resolvedAttributes.put("sub", canonicalUsername);
- } else if (userStore.get(userKey(userPoolId, username)).isPresent()) {
- throw new AwsException("UsernameExistsException", "User already exists", 400);
}
validateEmailAttribute(resolvedAttributes, false);
@@ -3328,7 +3330,7 @@ public class CognitoService implements ResourceProvider {
user.getAttributes().put("sub", UUID.randomUUID().toString());
}
- // Fire PreSignUp BEFORE persisting — allows the trigger to block signup
+ // Fire PreSignUp BEFORE persisting: allows the trigger to block signup
// (via lambda error) or auto-confirm/auto-verify the user (via response).
CognitoAuthFlowHandler.PreSignUpResponse preSignUp = authFlowHandler.firePreSignUp(
pool, client, user, Map.of(), Map.of(), "PreSignUp_SignUp");
@@ -3354,7 +3356,16 @@ public class CognitoService implements ResourceProvider {
}
}
- userStore.put(key, user);
+ // Capture trigger data before publishing the live, mutable user to admin requests.
+ CognitoUser triggerUser = MAPPER.convertValue(user, CognitoUser.class);
+ synchronized (userLock(userPoolId, username)) {
+ UserPool currentPool = describeUserPool(userPoolId);
+ if (clientStore.get(client.getClientId()).isEmpty()) {
+ throw new AwsException("ResourceNotFoundException", "Client not found", 400);
+ }
+ requireAvailableSignUpUsername(currentPool, username);
+ userStore.put(key, user);
+ }
LOG.infov("Signed up user {0} in pool {1} (status={2})",
username, userPoolId, user.getUserStatus());
@@ -3363,14 +3374,14 @@ public class CognitoService implements ResourceProvider {
String code = verificationCodeService.issue(pool.getId(), user.getUsername(),
VerificationCode.Purpose.SIGNUP_CONFIRMATION, Duration.ofHours(24));
Map<String, Object> customMessage = authFlowHandler.fireCustomMessage(
- pool, client, user, "CustomMessage_SignUp");
- messageDispatcher.dispatch(pool, user, VerificationCode.Purpose.SIGNUP_CONFIRMATION,
+ pool, client, triggerUser, "CustomMessage_SignUp");
+ messageDispatcher.dispatch(pool, triggerUser, VerificationCode.Purpose.SIGNUP_CONFIRMATION,
code, List.of(deliveryTarget.deliveryMedium()), customMessage);
} catch (VerificationCodeException e) {
- rollbackSignUpConfirmationArtifacts(pool.getId(), user.getUsername(), key);
+ rollbackSignUpConfirmationArtifacts(user);
throw mapVerificationCodeException(e);
} catch (RuntimeException e) {
- rollbackSignUpConfirmationArtifacts(pool.getId(), user.getUsername(), key);
+ rollbackSignUpConfirmationArtifacts(user);
throw new AwsException("CodeDeliveryFailureException",
"Failed to deliver the message.", 400);
}
@@ -3379,9 +3390,21 @@ public class CognitoService implements ResourceProvider {
// When PreSignUp auto-confirms, AWS Cognito also fires PostConfirmation.
// See: docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-sign-up.html
if (preSignUp.autoConfirmUser()) {
- authFlowHandler.firePostConfirmation(pool, client, user, Map.of(), "PostConfirmation_ConfirmSignUp");
+ authFlowHandler.firePostConfirmation(pool, client, triggerUser, Map.of(), "PostConfirmation_ConfirmSignUp");
+ }
+ synchronized (userLock(userPoolId, user.getUsername())) {
+ triggerUser.setUserStatus(user.getUserStatus());
+ }
+ return triggerUser;
+ }
+
+ private void requireAvailableSignUpUsername(UserPool pool, String username) {
+ boolean exists = usesAliasUsernames(pool)
+ ? findUserByAlias(pool.getId(), aliasAttributeForValue(pool, username), username) != null
+ : userStore.get(userKey(pool.getId(), username)).isPresent();
+ if (exists) {
+ throw new AwsException("UsernameExistsException", "User already exists", 400);
}
- return user;
}
public void confirmSignUp(String clientId, String username) {
@@ -3398,15 +3421,19 @@ public class CognitoService implements ResourceProvider {
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found",
400));
String userPoolId = client.getUserPoolId();
- synchronized (userLock(userPoolId, username)) {
- confirmSignUpUnderUserLock(client, userPoolId, username, confirmationCode, clientMetadata);
+ CognitoUser resolvedUser = adminGetUser(userPoolId, username);
+ UserPool pool;
+ CognitoUser triggerUser;
+ synchronized (userLock(userPoolId, resolvedUser.getUsername())) {
+ pool = poolStore.get(userPoolId).orElseThrow(() -> userPoolNotFound(userPoolId));
+ triggerUser = confirmSignUpUnderUserLock(client, pool, resolvedUser.getUsername(), confirmationCode);
}
+ authFlowHandler.firePostConfirmation(pool, client, triggerUser,
+ clientMetadata, "PostConfirmation_ConfirmSignUp");
}
- private void confirmSignUpUnderUserLock(UserPoolClient client, String userPoolId, String username,
- String confirmationCode, Map<String, String> clientMetadata) {
- UserPool pool = poolStore.get(userPoolId)
- .orElseThrow(() -> userPoolNotFound(userPoolId));
+ private CognitoUser confirmSignUpUnderUserLock(UserPoolClient client, UserPool pool, String username,
+ String confirmationCode) {
CognitoUser user = adminGetUser(client.getUserPoolId(), username);
if (verificationCodeService != null && isSignUpConfirmationEnabled(pool)) {
try {
@@ -3430,7 +3457,7 @@ public class CognitoService implements ResourceProvider {
user.setUserStatus("CONFIRMED");
user.setLastModifiedDate(System.currentTimeMillis() / 1000L);
userStore.put(userKey(client.getUserPoolId(), user.getUsername()), user);
- authFlowHandler.firePostConfirmation(pool, client, user, clientMetadata, "PostConfirmation_ConfirmSignUp");
+ return MAPPER.convertValue(user, CognitoUser.class);
}
Map<String, String> signUpCodeDeliveryDetails(CognitoUser user) {
@@ -5958,12 +5985,22 @@ public class CognitoService implements ResourceProvider {
return null;
}
- private void rollbackSignUpConfirmationArtifacts(String userPoolId, String username,
- String userKey) {
- userStore.delete(userKey);
- if (verificationCodeService != null) {
- verificationCodeService.invalidatePrevious(userPoolId, username,
- VerificationCode.Purpose.SIGNUP_CONFIRMATION);
+ private void rollbackSignUpConfirmationArtifacts(CognitoUser expectedUser) {
+ String poolId = expectedUser.getUserPoolId();
+ String username = expectedUser.getUsername();
+ synchronized (userLock(poolId, username)) {
+ CognitoUser current = userStore.get(userKey(poolId, username)).orElse(null);
+ // Admin callbacks can edit sub, so only the stored instance identifies this signup.
+ if (current != null && current != expectedUser) {
+ return;
+ }
+ if (current != null) {
+ deleteUserRecordAndGroups(poolId, current);
+ }
+ if (verificationCodeService != null) {
+ verificationCodeService.invalidatePrevious(poolId, username,
+ VerificationCode.Purpose.SIGNUP_CONFIRMATION);
+ }
}
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoSignUpCreationScopeTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoSignUpCreationScopeTest.java
new file mode 100644
index 0000000000..115b98e695
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoSignUpCreationScopeTest.java
@@ -0,0 +1,162 @@
+package io.github.hectorvent.floci.services.cognito;
+
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.common.RequestContext;
+import io.github.hectorvent.floci.core.common.ReservedTags;
+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
+import io.github.hectorvent.floci.core.storage.InMemoryStorage;
+import io.github.hectorvent.floci.services.cognito.model.CognitoUser;
+import io.github.hectorvent.floci.services.cognito.model.UserPool;
+import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;
+import io.github.hectorvent.floci.services.lambda.LambdaService;
+import io.github.hectorvent.floci.services.lambda.model.InvocationType;
+import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
+import jakarta.enterprise.inject.Instance;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+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 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.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+class CognitoSignUpCreationScopeTest {
+ private static final String FIRST_ACCOUNT = "111111111111";
+ private static final String SECOND_ACCOUNT = "222222222222";
+ private static final String POOL_ID = "us-east-1_sharedpool";
+ private static final String FUNCTION = "pre-signup";
+
+ private final ThreadLocal<RequestContext> requestContext = ThreadLocal.withInitial(() -> {
+ RequestContext context = new RequestContext();
+ context.setAccountId(FIRST_ACCOUNT);
+ return context;
+ });
+
+ @ParameterizedTest
+ @CsvSource({"false, false", "true, false", "false, true", "true, true"})
+ void overlappingSignUpReservesOnlyTheSameAccountAndUsername(
+ boolean firstRequestIsAdmin, boolean differentAccount) throws Exception {
+ Instance<RequestContext> contexts = mock(Instance.class);
+ when(contexts.get()).thenAnswer(invocation -> requestContext.get());
+ RegionResolver regionResolver = new RegionResolver("us-east-1", FIRST_ACCOUNT) {
+ @Override
+ public String getAccountId() {
+ return requestContext.get().getAccountId();
+ }
+ };
+ LambdaService lambdaService = mock(LambdaService.class);
+ CognitoService service = new CognitoService(
+ store(contexts), store(contexts), store(contexts), store(contexts),
+ store(contexts), store(contexts), store(contexts), store(contexts),
+ "http://localhost:4566", regionResolver, lambdaService, null, null, null, null);
+ UserPoolClient firstClient = inAccount(FIRST_ACCOUNT, () -> createClient(service));
+ String overlappingAccount = differentAccount ? SECOND_ACCOUNT : FIRST_ACCOUNT;
+ UserPoolClient overlappingClient = differentAccount
+ ? inAccount(SECOND_ACCOUNT, () -> createClient(service)) : firstClient;
+ CountDownLatch firstTriggerEntered = new CountDownLatch(1);
+ CountDownLatch releaseFirstTrigger = new CountDownLatch(1);
+ List<String> invokedAccounts = new CopyOnWriteArrayList<>();
+ when(lambdaService.invoke(anyString(), eq(FUNCTION), any(byte[].class),
+ eq(InvocationType.RequestResponse))).thenAnswer(invocation -> {
+ String account = requestContext.get().getAccountId();
+ invokedAccounts.add(account);
+ if (FIRST_ACCOUNT.equals(account) && firstTriggerEntered.getCount() != 0) {
+ firstTriggerEntered.countDown();
+ assertTrue(releaseFirstTrigger.await(30, TimeUnit.SECONDS),
+ "first account's trigger must be released by the test");
+ }
+ return new InvokeResult(200, null,
+ "{\"response\":{}}".getBytes(StandardCharsets.UTF_8), null, "request");
+ });
+
+ ExecutorService requests = Executors.newFixedThreadPool(2);
+ List<Future<?>> pending = new ArrayList<>();
+ try {
+ Future<CognitoUser> first = requests.submit(() -> inAccount(FIRST_ACCOUNT, () ->
+ firstRequestIsAdmin
+ ? service.adminCreateUser(POOL_ID, "alice", Map.of("name", "first"),
+ "Perm1234!", "SUPPRESS")
+ : service.signUp(firstClient.getClientId(), "alice", "Perm1234!",
+ Map.of("name", "first"))));
+ pending.add(first);
+ assertTrue(firstTriggerEntered.await(5, TimeUnit.SECONDS), "first request must enter PreSignUp");
+
+ Future<CognitoUser> overlapping = requests.submit(() -> inAccount(overlappingAccount, () ->
+ service.signUp(overlappingClient.getClientId(), "alice", "Perm1234!",
+ Map.of("name", "overlapping"))));
+ pending.add(overlapping);
+ if (differentAccount) {
+ assertEquals("overlapping", overlapping.get(5, TimeUnit.SECONDS).getAttributes().get("name"));
+ assertEquals("overlapping", inAccount(SECOND_ACCOUNT, () ->
+ service.adminGetUser(POOL_ID, "alice").getAttributes().get("name")));
+ } else {
+ ExecutionException failure = assertThrows(ExecutionException.class,
+ () -> overlapping.get(5, TimeUnit.SECONDS));
+ AwsException duplicate = assertInstanceOf(AwsException.class, failure.getCause());
+ assertEquals("UsernameExistsException", duplicate.getErrorCode());
+ }
+ assertEquals(1L, releaseFirstTrigger.getCount(), "overlap must finish while first trigger is paused");
+ assertFalse(first.isDone(), "first request must still be waiting for its trigger");
+ assertEquals(1, Collections.frequency(invokedAccounts, FIRST_ACCOUNT));
+ assertEquals(differentAccount ? 1 : 0, Collections.frequency(invokedAccounts, SECOND_ACCOUNT));
+
+ releaseFirstTrigger.countDown();
+ assertEquals("first", first.get(5, TimeUnit.SECONDS).getAttributes().get("name"));
+ assertEquals("first", inAccount(FIRST_ACCOUNT, () ->
+ service.adminGetUser(POOL_ID, "alice").getAttributes().get("name")));
+ if (differentAccount) {
+ assertEquals("overlapping", inAccount(SECOND_ACCOUNT, () ->
+ service.adminGetUser(POOL_ID, "alice").getAttributes().get("name")));
+ }
+ } finally {
+ releaseFirstTrigger.countDown();
+ pending.forEach(task -> task.cancel(true));
+ requests.shutdownNow();
+ requestContext.remove();
+ assertTrue(requests.awaitTermination(5, TimeUnit.SECONDS), "request executor must terminate");
+ }
+ }
+
+ private static <V> AccountAwareStorageBackend<V> store(Instance<RequestContext> contexts) {
+ return new AccountAwareStorageBackend<>(new InMemoryStorage<>(), contexts, FIRST_ACCOUNT);
+ }
+
+ private static UserPoolClient createClient(CognitoService service) {
+ UserPool pool = service.createUserPool(Map.of("PoolName", "creation-scope",
+ "UserPoolTags", Map.of(ReservedTags.OVERRIDE_ID_KEY, POOL_ID),
+ "LambdaConfig", Map.of("PreSignUp", FUNCTION)), "us-east-1");
+ assertEquals(POOL_ID, pool.getId());
+ return service.createUserPoolClient(pool.getId(), "client", false, false, List.of(), List.of());
+ }
+
+ private <T> T inAccount(String accountId, Callable<T> action) throws Exception {
+ String previous = requestContext.get().getAccountId();
+ requestContext.get().setAccountId(accountId);
+ try {
+ return action.call();
+ } finally {
+ requestContext.get().setAccountId(previous);
+ }
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoSignUpTriggerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoSignUpTriggerIntegrationTest.java
new file mode 100644
index 0000000000..7769b234e1
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoSignUpTriggerIntegrationTest.java
@@ -0,0 +1,214 @@
+package io.github.hectorvent.floci.services.cognito;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.services.lambda.LambdaService;
+import io.github.hectorvent.floci.services.lambda.model.InvocationType;
+import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.github.hectorvent.floci.testutil.SesMailbox;
+import io.quarkus.test.InjectMock;
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+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 java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+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;
+import static org.hamcrest.Matchers.hasItem;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.when;
+
+@QuarkusTest
+class CognitoSignUpTriggerIntegrationTest {
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ @InjectMock
+ LambdaService lambdaService;
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @Test
+ void customMessageAdminConfirmationIsReflectedInSignUpResponseOverHttp() throws Exception {
+ String id = UUID.randomUUID().toString();
+ String username = "trigger-" + id;
+ String email = "original-" + id + "@example.com";
+ String changedEmail = "changed-" + id + "@example.com";
+ String function = "arn:aws:lambda:us-east-1:000000000000:function:custom-message-" + id;
+ String poolId = cognitoJson("CreateUserPool", MAPPER.writeValueAsString(Map.of(
+ "PoolName", "signup-message-trigger-" + id, "AutoVerifiedAttributes", List.of("email"),
+ "LambdaConfig", Map.of("CustomMessage", function)))).path("UserPool").path("Id").asText();
+ ExecutorService callbackExecutor = Executors.newSingleThreadExecutor();
+ AtomicReference<Throwable> callbackFailure = new AtomicReference<>();
+ try {
+ String clientId = cognitoJson("CreateUserPoolClient", MAPPER.writeValueAsString(Map.of(
+ "UserPoolId", poolId, "ClientName", "app")))
+ .path("UserPoolClient").path("ClientId").asText();
+ when(lambdaService.invoke(anyString(), eq(function), any(byte[].class),
+ eq(InvocationType.RequestResponse))).thenAnswer(invocation -> {
+ Future<?> callback = null;
+ try {
+ JsonNode event = MAPPER.readTree((byte[]) invocation.getArgument(2));
+ assertEquals("CustomMessage_SignUp", event.path("triggerSource").asText());
+ assertEquals(username, event.path("userName").asText());
+ assertEquals(email, event.path("request").path("userAttributes").path("email").asText());
+ callback = callbackExecutor.submit(() -> {
+ String userRequest = MAPPER.writeValueAsString(Map.of(
+ "UserPoolId", poolId, "Username", username));
+ cognitoAction("AdminConfirmSignUp", userRequest).then().statusCode(200);
+ cognitoAction("AdminUpdateUserAttributes", MAPPER.writeValueAsString(Map.of(
+ "UserPoolId", poolId, "Username", username, "UserAttributes",
+ List.of(Map.of("Name", "email", "Value", changedEmail)))))
+ .then().statusCode(200);
+ return null;
+ });
+ callback.get(5, TimeUnit.SECONDS);
+ } catch (InterruptedException failure) {
+ Thread.currentThread().interrupt();
+ callbackFailure.set(failure);
+ } catch (Exception | AssertionError failure) {
+ callbackFailure.set(failure);
+ } finally {
+ if (callback != null) {
+ callback.cancel(true);
+ }
+ }
+ return response(Map.of());
+ });
+
+ JsonNode signUp = cognitoJson("SignUp", MAPPER.writeValueAsString(Map.of("ClientId", clientId,
+ "Username", username, "Password", "Perm1234!", "UserAttributes",
+ List.of(Map.of("Name", "email", "Value", email)))));
+
+ assertNull(callbackFailure.get(), () -> "CustomMessage HTTP callback failed before Lambda returned: "
+ + callbackFailure.get());
+ cognitoAction("AdminGetUser", MAPPER.writeValueAsString(Map.of("UserPoolId", poolId,
+ "Username", username))).then().statusCode(200).body("UserStatus", equalTo("CONFIRMED"));
+ assertEquals(1, SesMailbox.messagesTo(email).size(), "signup must send to the captured email address");
+ assertTrue(SesMailbox.messagesTo(changedEmail).isEmpty(), "the callback's new email must not receive the code");
+ assertTrue(signUp.path("UserConfirmed").asBoolean(),
+ "SignUp must report confirmation completed by its synchronous CustomMessage callback");
+ } finally {
+ callbackExecutor.shutdownNow();
+ try {
+ assertTrue(callbackExecutor.awaitTermination(5, TimeUnit.SECONDS), "HTTP callback executor must stop");
+ } finally {
+ cognitoAction("DeleteUserPool", MAPPER.writeValueAsString(Map.of("UserPoolId", poolId)))
+ .then().statusCode(200);
+ }
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void postConfirmationCanAddTheConfirmedUserToAGroupOverHttp(boolean autoConfirm) throws Exception {
+ String id = UUID.randomUUID().toString();
+ String username = "trigger-" + id;
+ String email = username + "@example.com";
+ String groupName = "confirmed-" + id;
+ String postFunction = "arn:aws:lambda:us-east-1:000000000000:function:post-confirm-" + id;
+ String preFunction = "arn:aws:lambda:us-east-1:000000000000:function:pre-signup-" + id;
+ Map<String, String> triggers = autoConfirm
+ ? Map.of("PreSignUp", preFunction, "PostConfirmation", postFunction)
+ : Map.of("PostConfirmation", postFunction);
+ String poolId = cognitoJson("CreateUserPool", MAPPER.writeValueAsString(Map.of(
+ "PoolName", "signup-trigger-" + id, "AutoVerifiedAttributes", List.of("email"),
+ "LambdaConfig", triggers))).path("UserPool").path("Id").asText();
+ ExecutorService callbackExecutor = Executors.newSingleThreadExecutor();
+ AtomicReference<Throwable> callbackFailure = new AtomicReference<>();
+ try {
+ String clientId = cognitoJson("CreateUserPoolClient", MAPPER.writeValueAsString(Map.of(
+ "UserPoolId", poolId, "ClientName", "app")))
+ .path("UserPoolClient").path("ClientId").asText();
+ cognitoAction("CreateGroup", MAPPER.writeValueAsString(Map.of(
+ "UserPoolId", poolId, "GroupName", groupName))).then().statusCode(200);
+ if (autoConfirm) {
+ when(lambdaService.invoke(anyString(), eq(preFunction), any(byte[].class),
+ eq(InvocationType.RequestResponse)))
+ .thenReturn(response(Map.of("autoConfirmUser", true)));
+ }
+ when(lambdaService.invoke(anyString(), eq(postFunction), any(byte[].class),
+ eq(InvocationType.RequestResponse))).thenAnswer(invocation -> {
+ Future<Integer> callback = null;
+ try {
+ JsonNode event = MAPPER.readTree((byte[]) invocation.getArgument(2));
+ assertEquals("PostConfirmation_ConfirmSignUp", event.path("triggerSource").asText());
+ assertEquals(username, event.path("userName").asText());
+ assertEquals(poolId, event.path("userPoolId").asText());
+ if (!autoConfirm) {
+ assertEquals("http-confirm", event.path("request").path("clientMetadata")
+ .path("source").asText());
+ }
+ callback = callbackExecutor.submit(() -> cognitoAction("AdminAddUserToGroup",
+ MAPPER.writeValueAsString(Map.of("UserPoolId", poolId,
+ "Username", username, "GroupName", groupName))).statusCode());
+ assertEquals(200, callback.get(5, TimeUnit.SECONDS));
+ } catch (InterruptedException failure) {
+ Thread.currentThread().interrupt();
+ callbackFailure.set(failure);
+ } catch (Exception | AssertionError failure) {
+ callbackFailure.set(failure);
+ } finally {
+ if (callback != null) {
+ callback.cancel(true);
+ }
+ }
+ return response(Map.of());
+ });
+
+ cognitoAction("SignUp", MAPPER.writeValueAsString(Map.of("ClientId", clientId,
+ "Username", username, "Password", "Perm1234!", "UserAttributes",
+ List.of(Map.of("Name", "email", "Value", email))))).then().statusCode(200);
+ if (!autoConfirm) {
+ JsonNode messages = SesMailbox.messagesTo(email);
+ assertEquals(1, messages.size());
+ Matcher code = Pattern.compile("\\b(\\d{6})\\b")
+ .matcher(messages.get(0).path("Body").path("text_part").asText());
+ assertTrue(code.find(), "signup email must contain the confirmation code");
+ cognitoAction("ConfirmSignUp", MAPPER.writeValueAsString(Map.of("ClientId", clientId,
+ "Username", username, "ConfirmationCode", code.group(1),
+ "ClientMetadata", Map.of("source", "http-confirm")))).then().statusCode(200);
+ }
+ assertNull(callbackFailure.get(), () -> "PostConfirmation HTTP callback failed before Lambda returned: "
+ + callbackFailure.get());
+ String userRequest = MAPPER.writeValueAsString(Map.of("UserPoolId", poolId, "Username", username));
+ cognitoAction("AdminGetUser", userRequest).then().statusCode(200)
+ .body("UserStatus", equalTo("CONFIRMED"));
+ cognitoAction("AdminListGroupsForUser", userRequest).then().statusCode(200)
+ .body("Groups.GroupName", hasItem(groupName));
+ } finally {
+ callbackExecutor.shutdownNow();
+ try {
+ assertTrue(callbackExecutor.awaitTermination(5, TimeUnit.SECONDS), "HTTP callback executor must stop");
+ } finally {
+ cognitoAction("DeleteUserPool", MAPPER.writeValueAsString(Map.of("UserPoolId", poolId)))
+ .then().statusCode(200);
+ }
+ }
+ }
+
+ private static InvokeResult response(Map<String, Object> response) throws Exception {
+ return new InvokeResult(200, null, MAPPER.writeValueAsBytes(Map.of("response", response)), null, "request");
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoSignUpTriggerReentrancyTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoSignUpTriggerReentrancyTest.java
new file mode 100644
index 0000000000..0da854b219
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoSignUpTriggerReentrancyTest.java
@@ -0,0 +1,461 @@
+package io.github.hectorvent.floci.services.cognito;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.storage.InMemoryStorage;
+import io.github.hectorvent.floci.services.cognito.model.CognitoUser;
+import io.github.hectorvent.floci.services.cognito.model.UserPool;
+import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;
+import io.github.hectorvent.floci.services.cognito.verification.CognitoMessageDispatcher;
+import io.github.hectorvent.floci.services.cognito.verification.VerificationCode;
+import io.github.hectorvent.floci.services.cognito.verification.VerificationCodeException;
+import io.github.hectorvent.floci.services.cognito.verification.VerificationCodeService;
+import io.github.hectorvent.floci.services.lambda.LambdaService;
+import io.github.hectorvent.floci.services.lambda.model.InvocationType;
+import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
+import io.github.hectorvent.floci.services.sns.SnsService;
+import io.github.hectorvent.floci.testing.InMemoryStorageFactory;
+import io.smallrye.config.SmallRyeConfigBuilder;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.time.Clock;
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+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.TimeoutException;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+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.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+class CognitoSignUpTriggerReentrancyTest {
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private static final String FUNCTION = "signup-trigger";
+ private static final String PHONE = "+12025550123";
+
+ private LambdaService lambdaService;
+ private RegionResolver regionResolver;
+ private CognitoService service;
+ private VerificationCodeService codes;
+ private SnsService sns;
+ private ExecutorService callbackExecutor;
+
+ @BeforeEach
+ void setUp() {
+ lambdaService = mock(LambdaService.class);
+ regionResolver = new RegionResolver("us-east-1", "000000000000");
+ InMemoryStorageFactory storageFactory = new InMemoryStorageFactory("000000000000");
+ EmulatorConfig config = new SmallRyeConfigBuilder().withMapping(EmulatorConfig.class)
+ .build().getConfigMapping(EmulatorConfig.class);
+ sns = new SnsService(storageFactory, config, regionResolver, null, null, null, MAPPER, null);
+ codes = new VerificationCodeService(storageFactory, Clock.systemUTC());
+ service = serviceWithSns(sns);
+ callbackExecutor = Executors.newSingleThreadExecutor();
+ }
+
+ private CognitoService serviceWithSns(SnsService smsService) {
+ return new CognitoService(
+ new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
+ new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
+ new InMemoryStorage<>(), new InMemoryStorage<>(), "http://localhost:4566",
+ regionResolver, lambdaService, null, codes,
+ new CognitoMessageDispatcher(null, smsService, "us-east-1"), null);
+ }
+
+ @AfterEach
+ void stopCallbackExecutor() throws InterruptedException {
+ if (callbackExecutor != null) {
+ callbackExecutor.shutdownNow();
+ assertTrue(callbackExecutor.awaitTermination(5, TimeUnit.SECONDS),
+ "trigger callback executor must terminate after the request releases its locks");
+ }
+ }
+
+ @Test
+ void confirmSignUpPostConfirmationCanUpdateTheSameUserBeforeReturning() throws Exception {
+ UserPool pool = pool(Map.of("PostConfirmation", FUNCTION));
+ UserPoolClient client = client(pool);
+ CognitoUser user = service.signUp(client.getClientId(), "alice", "Perm1234!",
+ Map.of("phone_number", PHONE));
+ String code = sns.getSentMessages().getFirst().getMessage().replaceAll("\\D", "");
+ AtomicReference<Throwable> callbackFailure = new AtomicReference<>();
+ when(lambdaService.invoke(anyString(), eq(FUNCTION), any(byte[].class),
+ eq(InvocationType.RequestResponse))).thenAnswer(invocation -> {
+ JsonNode event = MAPPER.readTree((byte[]) invocation.getArgument(2));
+ assertEquals("PostConfirmation_ConfirmSignUp", event.path("triggerSource").asText());
+ assertEquals("confirm", event.path("request").path("clientMetadata").path("source").asText());
+ callback(() -> service.adminUpdateUserAttributes(pool.getId(), user.getUsername(),
+ Map.of("name", "updated by confirmation trigger")), callbackFailure);
+ return response(Map.of());
+ });
+
+ service.confirmSignUp(client.getClientId(), "alice", code, Map.of("source", "confirm"));
+
+ assertNull(callbackFailure.get(), () -> "PostConfirmation callback failed before returning: "
+ + callbackFailure.get());
+ CognitoUser confirmed = service.adminGetUser(pool.getId(), "alice");
+ assertEquals("CONFIRMED", confirmed.getUserStatus());
+ assertEquals("true", confirmed.getAttributes().get("phone_number_verified"));
+ assertEquals("updated by confirmation trigger", confirmed.getAttributes().get("name"));
+ VerificationCodeException consumed = assertThrows(VerificationCodeException.class,
+ () -> codes.consume(pool.getId(), "alice", VerificationCode.Purpose.SIGNUP_CONFIRMATION, code));
+ assertEquals(VerificationCodeException.Kind.NOT_FOUND, consumed.getKind());
+ }
+
+ @Test
+ void confirmationStillDispatchesPostConfirmationWhenThePersistedUsersPoolIsDeleted() throws Exception {
+ AtomicReference<String> confirmationCode = new AtomicReference<>();
+ AtomicBoolean poolDeleted = new AtomicBoolean();
+ InMemoryStorage<String, CognitoUser> userStore = new InMemoryStorage<>() {
+ @Override
+ public void put(String key, CognitoUser user) {
+ super.put(key, user);
+ if ("CONFIRMED".equals(user.getUserStatus())) {
+ assertEquals("CONFIRMED", get(key).orElseThrow().getUserStatus());
+ assertEquals("true", user.getAttributes().get("phone_number_verified"));
+ VerificationCodeException consumed = assertThrows(VerificationCodeException.class,
+ () -> codes.consume(user.getUserPoolId(), user.getUsername(),
+ VerificationCode.Purpose.SIGNUP_CONFIRMATION, confirmationCode.get()));
+ assertEquals(VerificationCodeException.Kind.NOT_FOUND, consumed.getKind());
+ service.deleteUserPool(user.getUserPoolId());
+ assertEquals("ResourceNotFoundException", assertThrows(AwsException.class,
+ () -> service.describeUserPool(user.getUserPoolId())).getErrorCode());
+ poolDeleted.set(true);
+ }
+ }
+ };
+ service = new CognitoService(
+ new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
+ new InMemoryStorage<>(), new InMemoryStorage<>(), userStore,
+ new InMemoryStorage<>(), new InMemoryStorage<>(), "http://localhost:4566",
+ regionResolver, lambdaService, null, codes,
+ new CognitoMessageDispatcher(null, sns, "us-east-1"), null);
+ UserPool pool = pool(Map.of("PostConfirmation", FUNCTION));
+ UserPoolClient client = client(pool);
+ service.signUp(client.getClientId(), "alice", "Perm1234!", Map.of("phone_number", PHONE));
+ confirmationCode.set(sns.getSentMessages().getFirst().getMessage().replaceAll("\\D", ""));
+ AtomicReference<JsonNode> event = new AtomicReference<>();
+ when(lambdaService.invoke(anyString(), eq(FUNCTION), any(byte[].class),
+ eq(InvocationType.RequestResponse))).thenAnswer(invocation -> {
+ assertTrue(poolDeleted.get(), "the pool must already be deleted when the trigger is dispatched");
+ event.set(MAPPER.readTree((byte[]) invocation.getArgument(2)));
+ return response(Map.of());
+ });
+
+ service.confirmSignUp(client.getClientId(), "alice", confirmationCode.get(), Map.of("source", "confirm"));
+
+ assertTrue(poolDeleted.get());
+ assertNotNull(event.get(), "persisted confirmation must still invoke its captured PostConfirmation trigger");
+ assertEquals("PostConfirmation_ConfirmSignUp", event.get().path("triggerSource").asText());
+ assertEquals(pool.getId(), event.get().path("userPoolId").asText());
+ assertEquals("alice", event.get().path("userName").asText());
+ assertEquals("true", event.get().path("request").path("userAttributes").path("phone_number_verified").asText());
+ assertEquals("confirm", event.get().path("request").path("clientMetadata").path("source").asText());
+ }
+
+ @Test
+ void autoConfirmedSignUpPostConfirmationCanUpdateTheSameUserBeforeReturning() throws Exception {
+ UserPool pool = pool(Map.of("PreSignUp", "auto-confirm", "PostConfirmation", FUNCTION));
+ UserPoolClient client = client(pool);
+ when(lambdaService.invoke(anyString(), eq("auto-confirm"), any(byte[].class),
+ eq(InvocationType.RequestResponse))).thenReturn(response(Map.of("autoConfirmUser", true)));
+ AtomicReference<Throwable> callbackFailure = new AtomicReference<>();
+ when(lambdaService.invoke(anyString(), eq(FUNCTION), any(byte[].class),
+ eq(InvocationType.RequestResponse))).thenAnswer(invocation -> {
+ JsonNode event = MAPPER.readTree((byte[]) invocation.getArgument(2));
+ assertEquals("PostConfirmation_ConfirmSignUp", event.path("triggerSource").asText());
+ callback(() -> service.adminUpdateUserAttributes(pool.getId(), event.path("userName").asText(),
+ Map.of("name", "updated by auto-confirm trigger")), callbackFailure);
+ return response(Map.of());
+ });
+
+ CognitoUser user = service.signUp(client.getClientId(), "alice", "Perm1234!",
+ Map.of("phone_number", PHONE));
+
+ assertNull(callbackFailure.get(), () -> "auto-confirm PostConfirmation callback failed before returning: "
+ + callbackFailure.get());
+ assertEquals("CONFIRMED", user.getUserStatus());
+ assertEquals("updated by auto-confirm trigger",
+ service.adminGetUser(pool.getId(), user.getUsername()).getAttributes().get("name"));
+ assertTrue(sns.getSentMessages().isEmpty());
+ }
+
+ @Test
+ void customMessageSignUpCanUpdateTheSameUserBeforeReturning() throws Exception {
+ UserPool pool = pool(Map.of("CustomMessage", FUNCTION));
+ UserPoolClient client = client(pool);
+ AtomicReference<Throwable> callbackFailure = new AtomicReference<>();
+ when(lambdaService.invoke(anyString(), eq(FUNCTION), any(byte[].class),
+ eq(InvocationType.RequestResponse))).thenAnswer(invocation -> {
+ JsonNode event = MAPPER.readTree((byte[]) invocation.getArgument(2));
+ assertEquals("CustomMessage_SignUp", event.path("triggerSource").asText());
+ callback(() -> service.adminUpdateUserAttributes(pool.getId(), event.path("userName").asText(),
+ Map.of("name", "updated by message trigger")), callbackFailure);
+ return response(Map.of("smsMessage", "Use code {####}"));
+ });
+
+ CognitoUser user = service.signUp(client.getClientId(), "alice", "Perm1234!",
+ Map.of("phone_number", PHONE));
+
+ assertNull(callbackFailure.get(), () -> "CustomMessage callback failed before returning: "
+ + callbackFailure.get());
+ assertEquals("UNCONFIRMED", user.getUserStatus());
+ assertEquals("updated by message trigger",
+ service.adminGetUser(pool.getId(), user.getUsername()).getAttributes().get("name"));
+ assertEquals(1, sns.getSentMessages().size());
+ assertTrue(sns.getSentMessages().getFirst().getMessage().matches("Use code \\d{6}"));
+ }
+
+ @Test
+ void preSignUpRejectsSameUsernameAdminCreationWithoutBlockingTheTrigger() throws Exception {
+ UserPool pool = pool(Map.of("PreSignUp", FUNCTION));
+ UserPoolClient client = client(pool);
+ AtomicReference<Throwable> callbackFailure = new AtomicReference<>();
+ AtomicReference<AwsException> duplicateFailure = new AtomicReference<>();
+ when(lambdaService.invoke(anyString(), eq(FUNCTION), any(byte[].class),
+ eq(InvocationType.RequestResponse))).thenAnswer(invocation -> {
+ JsonNode event = MAPPER.readTree((byte[]) invocation.getArgument(2));
+ if ("PreSignUp_SignUp".equals(event.path("triggerSource").asText())) {
+ callback(() -> {
+ AwsException duplicate = assertThrows(AwsException.class,
+ () -> service.adminCreateUser(pool.getId(), "alice",
+ Map.of("name", "created by trigger"), null, "SUPPRESS"));
+ assertEquals("UsernameExistsException", duplicate.getErrorCode());
+ duplicateFailure.set(duplicate);
+ }, callbackFailure);
+ }
+ return response(Map.of());
+ });
+
+ service.signUp(client.getClientId(), "alice", "Perm1234!",
+ Map.of("phone_number", PHONE, "name", "created by signup"));
+
+ assertNull(callbackFailure.get(), () -> "PreSignUp callback failed before returning: "
+ + callbackFailure.get());
+ assertNotNull(duplicateFailure.get(), "the PreSignUp trigger must complete its same-username callback");
+ assertEquals("created by signup", service.adminGetUser(pool.getId(), "alice").getAttributes().get("name"));
+ }
+
+ @Test
+ void preSignUpCanUpdateAnExistingUserOnTheSameLockStripe() throws Exception {
+ UserPool pool = pool(Map.of());
+ UserPoolClient client = client(pool);
+ service.adminCreateUser(pool.getId(), "BB", Map.of(), "Perm1234!", "SUPPRESS");
+ pool.setLambdaConfig(Map.of("PreSignUp", FUNCTION));
+ assertEquals((pool.getId() + "::Aa").hashCode(), (pool.getId() + "::BB").hashCode());
+ AtomicReference<Throwable> callbackFailure = new AtomicReference<>();
+ when(lambdaService.invoke(anyString(), eq(FUNCTION), any(byte[].class),
+ eq(InvocationType.RequestResponse))).thenAnswer(invocation -> {
+ callback(() -> service.adminUpdateUserAttributes(pool.getId(), "BB",
+ Map.of("name", "updated by PreSignUp")), callbackFailure);
+ return response(Map.of());
+ });
+
+ service.signUp(client.getClientId(), "Aa", "Perm1234!", Map.of("phone_number", PHONE));
+
+ assertNull(callbackFailure.get());
+ assertEquals("updated by PreSignUp", service.adminGetUser(pool.getId(), "BB").getAttributes().get("name"));
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void signUpDeliveryDetailsDescribeTheSentMessageDespiteCallbackMutation(boolean deletePhone) throws Exception {
+ UserPool pool = pool(Map.of("CustomMessage", FUNCTION));
+ UserPoolClient client = client(pool);
+ AtomicReference<Throwable> callbackFailure = new AtomicReference<>();
+ when(lambdaService.invoke(anyString(), eq(FUNCTION), any(byte[].class),
+ eq(InvocationType.RequestResponse))).thenAnswer(invocation -> {
+ callback(() -> {
+ if (deletePhone) {
+ service.adminDeleteUserAttributes(pool.getId(), "alice", List.of("phone_number"));
+ } else {
+ service.adminUpdateUserAttributes(pool.getId(), "alice",
+ Map.of("phone_number", "+12025550999"));
+ }
+ }, callbackFailure);
+ return response(Map.of());
+ });
+
+ CognitoUser result = service.signUp(client.getClientId(), "alice", "Perm1234!", Map.of("phone_number", PHONE));
+
+ assertNull(callbackFailure.get());
+ assertEquals(1, sns.getSentMessages().size());
+ assertEquals(PHONE, sns.getSentMessages().getFirst().getPhoneNumber());
+ assertEquals(Map.of("AttributeName", "phone_number", "DeliveryMedium", "SMS", "Destination", "+*******0123"),
+ service.signUpCodeDeliveryDetails(result));
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void deliveryFailureRollsBackOriginalUserEvenWhenCallbackChangesSub(boolean deleteSub) throws Exception {
+ service = serviceWithSns(failingSms());
+ UserPool pool = pool(Map.of("CustomMessage", FUNCTION));
+ UserPoolClient client = client(pool);
+ service.createGroup(pool.getId(), "members", null, null, null);
+ AtomicReference<Throwable> callbackFailure = new AtomicReference<>();
+ when(lambdaService.invoke(anyString(), eq(FUNCTION), any(byte[].class),
+ eq(InvocationType.RequestResponse))).thenAnswer(invocation -> {
+ callback(() -> {
+ service.adminAddUserToGroup(pool.getId(), "members", "alice");
+ if (deleteSub) {
+ service.adminDeleteUserAttributes(pool.getId(), "alice", List.of("sub"));
+ } else {
+ service.adminUpdateUserAttributes(pool.getId(), "alice", Map.of("sub", "changed"));
+ }
+ }, callbackFailure);
+ return response(Map.of());
+ });
+
+ AwsException failure = assertThrows(AwsException.class, () -> service.signUp(client.getClientId(),
+ "alice", "Perm1234!", Map.of("phone_number", PHONE)));
+
+ assertEquals("CodeDeliveryFailureException", failure.getErrorCode());
+ assertNull(callbackFailure.get());
+ assertEquals("UserNotFoundException", assertThrows(AwsException.class,
+ () -> service.adminGetUser(pool.getId(), "alice")).getErrorCode());
+ assertTrue(service.getGroup(pool.getId(), "members").getUserNames().isEmpty());
+ assertEquals(VerificationCodeException.Kind.NOT_FOUND, assertThrows(VerificationCodeException.class,
+ () -> codes.consume(pool.getId(), "alice", VerificationCode.Purpose.SIGNUP_CONFIRMATION,
+ "123456")).getKind());
+ }
+
+ @Test
+ void failedDeliveryDoesNotDeleteACallbackReplacementOrItsConfirmationCode() throws Exception {
+ service = serviceWithSns(failingSms());
+ UserPool pool = pool(Map.of("CustomMessage", FUNCTION));
+ UserPoolClient client = client(pool);
+ AtomicReference<String> replacementCode = new AtomicReference<>();
+ AtomicReference<Throwable> callbackFailure = new AtomicReference<>();
+ when(lambdaService.invoke(anyString(), eq(FUNCTION), any(byte[].class),
+ eq(InvocationType.RequestResponse))).thenAnswer(invocation -> {
+ callback(() -> {
+ service.adminDeleteUser(pool.getId(), "alice");
+ service.adminCreateMigratedUser(pool.getId(), "alice", "Replacement123!",
+ Map.of("phone_number", PHONE, "name", "replacement"), "UNCONFIRMED");
+ codes.invalidatePrevious(pool.getId(), "alice", VerificationCode.Purpose.SIGNUP_CONFIRMATION);
+ replacementCode.set(codes.issue(pool.getId(), "alice",
+ VerificationCode.Purpose.SIGNUP_CONFIRMATION, Duration.ofHours(24)));
+ }, callbackFailure);
+ return response(Map.of());
+ });
+
+ AwsException failure = assertThrows(AwsException.class, () -> service.signUp(client.getClientId(),
+ "alice", "Perm1234!", Map.of("phone_number", PHONE)));
+
+ assertEquals("CodeDeliveryFailureException", failure.getErrorCode());
+ assertNull(callbackFailure.get());
+ assertEquals("replacement", service.adminGetUser(pool.getId(), "alice").getAttributes().get("name"));
+ service.confirmSignUp(client.getClientId(), "alice", replacementCode.get());
+ assertEquals("CONFIRMED", service.adminGetUser(pool.getId(), "alice").getUserStatus());
+ }
+
+ @Test
+ void confirmationCapturesTriggerAttributesBeforeConcurrentAdminMutation() throws Exception {
+ UserPool pool = pool(Map.of("PostConfirmation", FUNCTION));
+ UserPoolClient client = client(pool);
+ service.signUp(client.getClientId(), "alice", "Perm1234!",
+ Map.of("phone_number", PHONE, "name", "at confirmation"));
+ CognitoUser user = service.adminGetUser(pool.getId(), "alice");
+ String code = sns.getSentMessages().getFirst().getMessage().replaceAll("\\D", "");
+ AtomicBoolean captureStarted = new AtomicBoolean();
+ CountDownLatch mutationStarted = new CountDownLatch(1);
+ AtomicReference<Thread> mutationThread = new AtomicReference<>();
+ AtomicReference<Future<?>> mutation = new AtomicReference<>();
+ user.setAttributes(new HashMap<>(user.getAttributes()) {
+ @Override
+ public Set<Map.Entry<String, String>> entrySet() {
+ if (captureStarted.compareAndSet(false, true)) {
+ mutation.set(callbackExecutor.submit(() -> {
+ mutationThread.set(Thread.currentThread());
+ mutationStarted.countDown();
+ service.adminUpdateUserAttributes(pool.getId(), "alice", Map.of("name", "after confirmation"));
+ }));
+ try {
+ assertTrue(mutationStarted.await(5, TimeUnit.SECONDS));
+ } catch (InterruptedException exception) {
+ Thread.currentThread().interrupt();
+ throw new AssertionError("interrupted while coordinating snapshot", exception);
+ }
+ await().pollInterval(Duration.ofMillis(10)).atMost(Duration.ofSeconds(1))
+ .until(() -> mutation.get().isDone()
+ || mutationThread.get().getState() == Thread.State.BLOCKED);
+ }
+ return super.entrySet();
+ }
+ });
+ AtomicReference<JsonNode> event = new AtomicReference<>();
+ when(lambdaService.invoke(anyString(), eq(FUNCTION), any(byte[].class),
+ eq(InvocationType.RequestResponse))).thenAnswer(invocation -> {
+ event.set(MAPPER.readTree((byte[]) invocation.getArgument(2)));
+ return response(Map.of());
+ });
+
+ service.confirmSignUp(client.getClientId(), "alice", code);
+ mutation.get().get(5, TimeUnit.SECONDS);
+
+ assertEquals("at confirmation", event.get().path("request").path("userAttributes").path("name").asText());
+ assertEquals("after confirmation", service.adminGetUser(pool.getId(), "alice").getAttributes().get("name"));
+ }
+
+ private SnsService failingSms() {
+ SnsService failing = mock(SnsService.class);
+ when(failing.publish(any(), any(), any(), any(), any(), any(), any()))
+ .thenThrow(new IllegalStateException("SMS unavailable"));
+ return failing;
+ }
+
+ private UserPool pool(Map<String, Object> lambdaConfig) {
+ return service.createUserPool(Map.of("PoolName", "signup-reentrancy",
+ "AutoVerifiedAttributes", List.of("phone_number"), "LambdaConfig", lambdaConfig), "us-east-1");
+ }
+
+ private UserPoolClient client(UserPool pool) {
+ return service.createUserPoolClient(pool.getId(), "client", false, false, List.of(), List.of());
+ }
+
+ private void callback(Runnable action, AtomicReference<Throwable> failure) {
+ Future<?> task = callbackExecutor.submit(action);
+ try {
+ task.get(5, TimeUnit.SECONDS);
+ } catch (ExecutionException exception) {
+ failure.set(exception.getCause());
+ } catch (TimeoutException exception) {
+ failure.set(exception);
+ } catch (InterruptedException exception) {
+ Thread.currentThread().interrupt();
+ failure.set(exception);
+ } finally {
+ task.cancel(true);
+ }
+ }
+
+ private static InvokeResult response(Map<String, Object> response) throws JsonProcessingException {
+ return new InvokeResult(200, null, MAPPER.writeValueAsBytes(Map.of("response", response)), null, "request");
+ }
+}