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.
This commit is contained in:
jwoa95 authored and GitHub committed 2026-10-06 08:18:14 -04:00
1 parent 6e6ce61eea
commit 69b4d17c67
6 files changed
+471 -63

No files matched your search

@@ -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<byte[]> 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<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"));
AtomicReference<Throwable> 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<String> 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<CognitoUser> 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<String> 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<CognitoUser> 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<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.
*/
private static <T> T callFromFunction(Callable<T> 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
// =========================================================================