fix(cognito): fire the CustomMessage trigger for UpdateUserAttributes and GetUserAttributeVerificationCode (#6205)

* fix(cognito): fire the CustomMessage trigger for UpdateUserAttributes and GetUserAttributeVerificationCode

Both sent their verification codes without the CustomMessage trigger, so a
pool's function never shaped those messages and never saw the request's
ClientMetadata. They now fire it with CustomMessage_UpdateUserAttribute and
CustomMessage_VerifyUserAttribute.

Measured on Cognito, the event carries the user as stored once the request is
done: the whole update applied, and an email that must be verified before it
changes still the old one while the code goes to the new address. The message
is therefore sent once the update is stored and the user lock is released. The
trigger is synchronous, so holding the lock would also block a function that
calls the pool back for the same user until its invocation timed out, which
SignUp already avoids. Cognito keeps an update whose code it cannot deliver
and answers CodeDeliveryFailureException, and a message that cannot be sent
now does the same.

* fix(cognito): leave nothing behind when an attribute code's message is not sent

Sending an attribute code's message after the user lock opened four ways to
leave a code live that no message carried, or to fail an update already
stored. Each message is now sent on its own: one that cannot be sent has its
code withdrawn, so another can be asked for at once as on Cognito, and the
others still go out. An update that stops before it is stored withdraws the
codes it already issued. The pool, the client and a copy of the stored user
are read while the lock is held, as SignUp captures its trigger's user, so
nothing is looked up once the update is stored.
This commit is contained in:
Alessandro Lattao authored and GitHub committed 2026-10-22 06:44:54 -04:00
1 parent 5beb8d47b9
commit 2c5415186a
7 files changed
+495 -19

No files matched your search

@@ -4,8 +4,10 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;
import software.amazon.awssdk.services.cognitoidentityprovider.model.AliasAttributeType;
import software.amazon.awssdk.services.cognitoidentityprovider.model.AttributeType;
@@ -18,6 +20,8 @@ import software.amazon.awssdk.services.cognitoidentityprovider.model.MessageActi
import software.amazon.awssdk.services.cognitoidentityprovider.model.UpdateUserAttributesResponse;
import software.amazon.awssdk.services.cognitoidentityprovider.model.UserNotFoundException;
import software.amazon.awssdk.services.cognitoidentityprovider.model.VerifiedAttributeType;
import software.amazon.awssdk.services.lambda.LambdaClient;
import software.amazon.awssdk.services.lambda.model.Runtime;
import java.net.URI;
import java.net.URLEncoder;
@@ -45,12 +49,14 @@ class CognitoVerifyUserAttributeTest {
private static final String PASSWORD = "Verify1234!";
private static CognitoIdentityProviderClient cognito;
private static LambdaClient lambda;
private String poolId;
@BeforeAll
static void setUpClient() {
cognito = TestFixtures.cognitoClient();
lambda = TestFixtures.lambdaClient();
}
@AfterAll
@@ -58,6 +64,9 @@ class CognitoVerifyUserAttributeTest {
if (cognito != null) {
cognito.close();
}
if (lambda != null) {
lambda.close();
}
}
@AfterEach
@@ -258,6 +267,80 @@ class CognitoVerifyUserAttributeTest {
assertThat(authenticate(clientId, newPhone)).isNotBlank();
}
/**
* Measured on Cognito (eu-west-1, 2026-10-21 and 2026-10-22): both calls hand their code to the
* CustomMessage trigger with the request's ClientMetadata and the user as stored, whose email
* stays the verified one until the new one is verified, and the function's message is the one
* delivered. Each code is used before the next is asked for.
*/
@Test
void customMessageShapesTheCodesOfAnEmailUpdate() throws Exception {
Assumptions.assumeTrue(TestFixtures.isLambdaDispatchAvailable(),
"skipping: Lambda dispatch (Docker) not available in this environment");
String functionName = TestFixtures.uniqueName("compat-custom-message");
String functionArn = lambda.createFunction(b -> b
.functionName(functionName)
.runtime(Runtime.NODEJS20_X)
.role("arn:aws:iam::000000000000:role/lambda-role")
.handler("index.handler")
.timeout(10)
.code(c -> c.zipFile(SdkBytes.fromByteArray(LambdaUtils.cognitoCustomMessageZip()))))
.functionArn();
try {
poolId = cognito.createUserPool(b -> b
.poolName("custom-message-update-" + UUID.randomUUID())
.autoVerifiedAttributes(VerifiedAttributeType.EMAIL)
.userAttributeUpdateSettings(s -> s
.attributesRequireVerificationBeforeUpdate(VerifiedAttributeType.EMAIL))
.lambdaConfig(l -> l.customMessage(functionArn)))
.userPool()
.id();
String clientId = createClient();
String username = "custom-message-" + UUID.randomUUID();
String oldEmail = "old+" + UUID.randomUUID() + "@example.com";
String newEmail = "new+" + UUID.randomUUID() + "@example.com";
createConfirmedUser(username,
AttributeType.builder().name("email").value(oldEmail).build(),
AttributeType.builder().name("email_verified").value("true").build(),
AttributeType.builder().name("name").value("Original").build());
String accessToken = authenticate(clientId, username);
clearInspectionEndpoint("/_aws/ses");
cognito.getUserAttributeVerificationCode(b -> b
.accessToken(accessToken)
.attributeName("email")
.clientMetadata(Map.of("source", "settings")));
JsonNode verify = latestSesMessageTo(oldEmail);
assertThat(verify.path("Subject").asText()).isEqualTo("CustomMessage_VerifyUserAttribute");
String verifyText = verify.path("Body").path("text_part").asText();
assertThat(verifyText).matches("\\d{6} for " + Pattern.quote(oldEmail) + ", Original, from settings");
cognito.verifyUserAttribute(b -> b
.accessToken(accessToken)
.attributeName("email")
.code(extractVerificationCode(verifyText)));
clearInspectionEndpoint("/_aws/ses");
cognito.updateUserAttributes(b -> b
.accessToken(accessToken)
.userAttributes(AttributeType.builder().name("email").value(newEmail).build(),
AttributeType.builder().name("name").value("Renamed").build())
.clientMetadata(Map.of("source", "profile")));
JsonNode update = latestSesMessageTo(newEmail);
assertThat(update.path("Subject").asText()).isEqualTo("CustomMessage_UpdateUserAttribute");
String updateText = update.path("Body").path("text_part").asText();
assertThat(updateText).matches("\\d{6} for " + Pattern.quote(oldEmail) + ", Renamed, from profile");
assertThat(userAttribute(username, "email")).isEqualTo(oldEmail);
cognito.verifyUserAttribute(b -> b
.accessToken(accessToken)
.attributeName("email")
.code(extractVerificationCode(updateText)));
assertThat(userAttribute(username, "email")).isEqualTo(newEmail);
} finally {
lambda.deleteFunction(b -> b.functionName(functionName));
}
}
private String createClient() {
return cognito.createUserPoolClient(b -> b
.userPoolId(poolId)
@@ -316,13 +399,17 @@ class CognitoVerifyUserAttributeTest {
}
private static String fetchLatestSesVerificationCode(String recipient) throws Exception {
return extractVerificationCode(latestSesMessageTo(recipient).path("Body").path("text_part").asText());
}
private static JsonNode latestSesMessageTo(String recipient) throws Exception {
// The mailbox's email parameter filters by message source, so the message sent to the
// recipient is picked out of the full list.
JsonNode messages = getInspectionMessages(TestFixtures.endpoint().resolve("/_aws/ses"));
for (JsonNode message : messages) {
for (JsonNode to : message.path("Destination").path("ToAddresses")) {
if (recipient.equals(to.asText())) {
return extractVerificationCode(message.path("Body").path("text_part").asText());
return message;
}
}
}
@@ -359,6 +359,25 @@ public final class LambdaUtils {
return createZip("index.js", code);
}
/**
* ZIP containing a Node.js Cognito CustomMessage handler that writes what its event carried into
* the email: the trigger source as the subject, and the code parameter, the user's email and
* name and the request's {@code source} metadata as the message.
*/
public static byte[] cognitoCustomMessageZip() {
String code = """
exports.handler = async (event) => {
const attributes = event.request.userAttributes;
const metadata = event.request.clientMetadata || {};
event.response.emailSubject = event.triggerSource;
event.response.emailMessage = `${event.request.codeParameter} for ${attributes.email}, `
+ `${attributes.name}, from ${metadata.source}`;
return event;
};
""";
return createZip("index.js", code);
}
private static byte[] createZip(String filename, String content) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
+2 -2
View File
@@ -315,9 +315,9 @@ passwordless pool generates a password. `TemporaryPasswordValidityDays` is not e
| ResendConfirmationCode | Issues a new sign-up confirmation code to an unconfirmed user, replacing the previous one, and returns where it was sent. |
| GetUser | Returns attributes for the authenticated access-token user, and the MFA settings (`UserMFASettingList`, `PreferredMfaSetting`) once any is turned on. |
| GetUserAuthFactors | Returns the authenticated access-token user's sign-in factors: `PASSWORD` when the user has a password, `EMAIL_OTP` and `SMS_OTP` when the email or phone number is verified, whatever the pool's `AllowedFirstAuthFactors` allows, as on AWS, `WEB_AUTHN` once the user has registered a passkey, and `SOFTWARE_TOKEN` once `VerifySoftwareToken` has confirmed an authenticator. The access token must carry the `aws.cognito.signin.user.admin` scope. `UserMFASettingList` and `PreferredMfaSetting` report the SMS, email and software-token MFA preferences set with `SetUserMFAPreference`. |
| GetUserAttributeVerificationCode | Issues a verification code for the authenticated user's email or phone_number attribute. |
| GetUserAttributeVerificationCode | Issues a verification code for the authenticated user's email or phone_number attribute. The CustomMessage trigger shapes its message, with triggerSource `CustomMessage_VerifyUserAttribute` and the request's `ClientMetadata`. |
| VerifyUserAttribute | Verifies an email or phone_number attribute with its issued verification code. |
| UpdateUserAttributes | Updates attributes for the authenticated access-token user. |
| UpdateUserAttributes | Updates attributes for the authenticated access-token user. A changed email or phone_number gets a verification code once the update is stored. The CustomMessage trigger shapes its message, with triggerSource `CustomMessage_UpdateUserAttribute`, the request's `ClientMetadata` and the user as stored. A message that cannot be sent fails the request with `CodeDeliveryFailureException` and leaves the update in place, as on AWS. |
| DeleteUserAttributes | Deletes the named attributes from the authenticated access-token user. |
| DeleteUser | Deletes the authenticated access-token user and removes them from their groups. An API Gateway Cognito authorizer rejects the user's existing tokens afterwards. |
| ChangePassword | Changes the authenticated user's password. |
@@ -4080,14 +4080,22 @@ public class CognitoService implements ResourceProvider {
String username = token.username();
String poolId = token.poolId();
List<AttributeCodeMessage> messages = new ArrayList<>();
Map<String, Object> response;
AttributeCodeSending sending;
synchronized (userLock(poolId, username)) {
return getUserAttributeVerificationCodeUnderUserLock(poolId, username, token.clientId(), attributeName,
clientMetadata);
UserPoolClient client = describeUserPoolClient(token.clientId());
response = getUserAttributeVerificationCodeUnderUserLock(poolId, username, token.clientId(), attributeName,
clientMetadata, messages);
sending = attributeCodeSending(poolId, username, client);
}
sendAttributeCodeMessages(sending, "CustomMessage_VerifyUserAttribute", clientMetadata, messages);
return response;
}
private Map<String, Object> getUserAttributeVerificationCodeUnderUserLock(
String poolId, String username, String clientId, String attributeName, Map<String, String> clientMetadata) {
String poolId, String username, String clientId, String attributeName, Map<String, String> clientMetadata,
List<AttributeCodeMessage> messages) {
if (!"email".equals(attributeName) && !"phone_number".equals(attributeName)) {
throw new AwsException("InvalidParameterException",
"Invalid attribute name. Only phone_number and email can be verified.", 400);
@@ -4113,7 +4121,7 @@ public class CognitoService implements ResourceProvider {
String code = verificationCodeService.issue(poolId, user.getUsername(),
purpose, Duration.ofHours(24));
dispatchAttributeVerificationCode(pool, clientId, user, attributeName, destination, purpose, code,
"CustomEmailSender_VerifyUserAttribute", clientMetadata);
"CustomEmailSender_VerifyUserAttribute", clientMetadata, messages);
} catch (VerificationCodeException e) {
throw mapVerificationCodeException(e);
}
@@ -4203,14 +4211,22 @@ public class CognitoService implements ResourceProvider {
400);
}
List<AttributeCodeMessage> messages = new ArrayList<>();
List<Map<String, Object>> deliveryDetails;
AttributeCodeSending sending;
synchronized (userLock(poolId, username)) {
return updateUserAttributesUnderUserLock(poolId, username, token.clientId(), attributes, clientMetadata);
UserPoolClient client = describeUserPoolClient(token.clientId());
deliveryDetails = updateUserAttributesUnderUserLock(poolId, username, token.clientId(), attributes,
clientMetadata, messages);
sending = attributeCodeSending(poolId, username, client);
}
sendAttributeCodeMessages(sending, "CustomMessage_UpdateUserAttribute", clientMetadata, messages);
return deliveryDetails;
}
private List<Map<String, Object>> updateUserAttributesUnderUserLock(
String poolId, String username, String clientId, Map<String, String> attributes,
Map<String, String> clientMetadata) {
Map<String, String> clientMetadata, List<AttributeCodeMessage> messages) {
UserPool pool = describeUserPool(poolId);
CognitoUser currentUser = adminGetUser(poolId, username);
validateEmailAttribute(attributes, true);
@@ -4230,6 +4246,7 @@ public class CognitoService implements ResourceProvider {
CognitoUser updatedUser = MAPPER.convertValue(currentUser, CognitoUser.class);
List<Map<String, Object>> deliveryDetails = new ArrayList<>();
boolean issued = false;
try {
for (Map.Entry<String, String> attribute : attributes.entrySet()) {
String attributeName = attribute.getKey();
@@ -4254,7 +4271,7 @@ public class CognitoService implements ResourceProvider {
String verificationCode = verificationCodeService.issue(
poolId, currentUser.getUsername(), purpose, Duration.ofHours(24));
dispatchAttributeVerificationCode(pool, clientId, currentUser, attributeName, value,
purpose, verificationCode, "CustomEmailSender_UpdateUserAttribute", clientMetadata);
purpose, verificationCode, "CustomEmailSender_UpdateUserAttribute", clientMetadata, messages);
if (requiresVerificationBeforeUpdate(pool, attributeName)) {
updatedUser.getPendingAttributes().put(attributeName, value);
@@ -4270,13 +4287,19 @@ public class CognitoService implements ResourceProvider {
detail.put("Destination", maskAttributeDestination(attributeName, value));
deliveryDetails.add(detail);
}
issued = true;
} catch (VerificationCodeException e) {
throw mapVerificationCodeException(e);
} catch (AwsException e) {
throw e;
} catch (RuntimeException e) {
throw new AwsException("CodeDeliveryFailureException",
"Failed to deliver verification code", 400);
throw codeDeliveryFailure();
} finally {
if (!issued) {
// Nothing is stored, so the codes already issued for messages still to send go with it.
messages.forEach(message -> verificationCodeService.invalidatePrevious(
poolId, currentUser.getUsername(), message.purpose()));
}
}
updatedUser.setLastModifiedDate(System.currentTimeMillis() / 1000L);
@@ -6016,20 +6039,79 @@ public class CognitoService implements ResourceProvider {
return configured instanceof List<?> attributes && attributes.contains(attributeName);
}
/**
* Hands {@code code} to the pool's CustomEmailSender when it takes the code, and otherwise adds
* the message that sends it to {@code messages}, for {@link #sendAttributeCodeMessages}.
*/
private void dispatchAttributeVerificationCode(UserPool pool, String clientId, CognitoUser user,
String attributeName, String destination,
VerificationCode.Purpose purpose, String code,
String customEmailSenderSource,
Map<String, String> clientMetadata) {
Map<String, String> clientMetadata,
List<AttributeCodeMessage> messages) {
CognitoUser deliveryUser = MAPPER.convertValue(user, CognitoUser.class);
deliveryUser.getAttributes().put(attributeName, destination);
if (!sendThroughCustomEmailSender(pool, clientId, deliveryUser, deliveryMedium(attributeName),
customEmailSenderSource, purpose, code, clientMetadata)) {
messageDispatcher.dispatch(pool, deliveryUser, purpose, code,
List.of(deliveryMedium(attributeName)));
messages.add(new AttributeCodeMessage(deliveryUser, purpose, code, deliveryMedium(attributeName)));
}
}
/** An attribute's code, to send as Cognito's own message to the address on {@code deliveryUser}. */
private record AttributeCodeMessage(CognitoUser deliveryUser, VerificationCode.Purpose purpose, String code,
String deliveryMedium) {
}
/** What the messages of a request's attribute codes are sent with, read under the user lock. */
private record AttributeCodeSending(UserPool pool, UserPoolClient client, CognitoUser user) {
}
/**
* Reads, while the user lock is held, what the codes' messages go out with once it is released:
* the pool, the client, and a copy of the user as stored, which another request may change under
* its own lock in the meantime.
*/
private AttributeCodeSending attributeCodeSending(String poolId, String username, UserPoolClient client) {
return new AttributeCodeSending(describeUserPool(poolId), client,
MAPPER.convertValue(adminGetUser(poolId, username), CognitoUser.class));
}
/**
* Sends each code as Cognito's message, which the CustomMessage trigger shapes. It runs once the
* user lock is released, since the trigger's function may call the pool back for this user, and
* hands the trigger the user as stored, which keeps an email that must be verified before it
* changes (measured, eu-west-1, 2026-10-21 and 2026-10-22). A code that cannot be sent is
* withdrawn, so a new one can be asked for at once, as Cognito hands one out (measured); the
* others are still sent, and the request then fails.
*/
private void sendAttributeCodeMessages(AttributeCodeSending sending, String triggerSource,
Map<String, String> clientMetadata, List<AttributeCodeMessage> messages) {
RuntimeException failure = null;
for (AttributeCodeMessage message : messages) {
try {
Map<String, Object> customMessage = authFlowHandler.fireCustomMessage(
sending.pool(), sending.client(), sending.user(), triggerSource, clientMetadata);
messageDispatcher.dispatch(sending.pool(), message.deliveryUser(), message.purpose(), message.code(),
List.of(message.deliveryMedium()), customMessage);
} catch (RuntimeException e) {
LOG.warnv("Cannot send a {0} code for pool {1}: {2}",
message.purpose(), sending.pool().getId(), e.getMessage());
verificationCodeService.invalidatePrevious(
sending.pool().getId(), sending.user().getUsername(), message.purpose());
if (failure == null) {
failure = e;
}
}
}
if (failure != null) {
throw failure instanceof AwsException aws ? aws : codeDeliveryFailure();
}
}
private static AwsException codeDeliveryFailure() {
return new AwsException("CodeDeliveryFailureException", "Failed to deliver verification code", 400);
}
/**
* Hands {@code code} to the pool's CustomEmailSender function when the pool has one and the
* code goes by email, in place of the message Cognito would send and of the CustomMessage
@@ -74,7 +74,7 @@ class CognitoAttributeVerificationConcurrencyTest {
String code = invocation.getArgument(3);
destinationByCode.put(code, deliveryUser.getAttributes().get("email"));
return null;
}).when(dispatcher).dispatch(any(), any(), any(), anyString(), any());
}).when(dispatcher).dispatch(any(), any(), any(), anyString(), any(), any());
acceptOnlyLatestCode(codes, latestCode);
ExecutorService executor = Executors.newFixedThreadPool(2);
@@ -14,6 +14,7 @@ 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;
@@ -39,6 +40,7 @@ import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -64,8 +66,10 @@ 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;
import static org.mockito.ArgumentMatchers.contains;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
@@ -105,10 +109,17 @@ class CognitoLambdaTriggersTest {
*/
private CognitoService createServiceWithMessaging(SesService ses, SnsService sns,
VerificationCodeService verificationCodeService) {
return createServiceWithMessaging(ses, sns, verificationCodeService, new InMemoryStorage<>());
}
/** The same, keeping its users in {@code users}. */
private CognitoService createServiceWithMessaging(SesService ses, SnsService sns,
VerificationCodeService verificationCodeService,
InMemoryStorage<String, CognitoUser> users) {
return new CognitoService(
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
users, new InMemoryStorage<>(), new InMemoryStorage<>(),
"http://localhost:4566", regionResolver, lambdaService, mock(AcmService.class),
verificationCodeService, new CognitoMessageDispatcher(ses, sns, "us-east-1"),
mock(TlsCertificateManager.class));
@@ -2229,7 +2240,46 @@ class CognitoLambdaTriggersTest {
}
private static UserPoolClient customMessageClient(CognitoService svc, UserPool pool) {
return svc.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());
return svc.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of(),
null, List.of(), null, AUTH_FLOWS, null, null, List.of(), null, List.of(), null,
null, null, List.of(), null, null);
}
/** Signs in a confirmed user {@code spike} with a verified email and a name; returns the access token. */
@SuppressWarnings("unchecked")
private static String customMessageUser(CognitoService svc, UserPool pool, UserPoolClient client) {
svc.adminCreateUser(pool.getId(), "spike",
Map.of("email", "spike@example.com", "email_verified", "true", "name", "Spike"), null);
svc.adminSetUserPassword(pool.getId(), "spike", "Spike@Test1", true);
Map<String, Object> result = svc.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH",
Map.of("USERNAME", "spike", "PASSWORD", "Spike@Test1"));
return (String) ((Map<String, Object>) result.get("AuthenticationResult")).get("AccessToken");
}
/** Issues 777888 for an email's verification and 555666 for a phone number's. */
private static VerificationCodeService attributeCodes() {
VerificationCodeService codes = inlineMock(VerificationCodeService.class);
when(codes.issue(any(), any(), eq(VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION), any()))
.thenReturn("777888");
when(codes.issue(any(), any(), eq(VerificationCode.Purpose.PHONE_ATTRIBUTE_VERIFICATION), any()))
.thenReturn("555666");
return codes;
}
/** A new email, then a phone number: two codes, the email's issued first. */
private static Map<String, String> newEmailAndPhoneNumber() {
Map<String, String> attributes = new LinkedHashMap<>();
attributes.put("email", "spike@example.org");
attributes.put("phone_number", "+12025550123");
return attributes;
}
/** The email first, so a code sent as soon as the email is read would miss the name. */
private static Map<String, String> newEmailAndName() {
Map<String, String> attributes = new LinkedHashMap<>();
attributes.put("email", "spike@example.org");
attributes.put("name", "Renamed");
return attributes;
}
/** Answers the CustomMessage function with {@code response} and captures the events it is sent. */
@@ -2357,6 +2407,243 @@ class CognitoLambdaTriggersTest {
assertEquals(Map.of("source", "forgot"), ((Map<String, Object>) event.get("request")).get("clientMetadata"));
}
/** Measured (eu-west-1, 2026-10-21): the event carries the user as the whole update leaves them. */
@Test
void customMessageFiresWithUpdateUserAttributeTriggerSourceOnUpdateUserAttributes() throws Exception {
SesService ses = mock(SesService.class);
CognitoService svc = customMessageService(ses, VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION, "777888");
UserPool pool = customMessagePool(svc, Map.of("AutoVerifiedAttributes", List.of("email")));
UserPoolClient client = customMessageClient(svc, pool);
String accessToken = customMessageUser(svc, pool, client);
ArgumentCaptor<byte[]> events = customMessageAnswers(Map.of(
"emailSubject", "Confirm your address",
"emailMessage", "Your code is {####}"));
svc.updateUserAttributes(accessToken, newEmailAndName(), Map.of("source", "profile"));
JsonNode event = MAPPER.readTree(events.getValue());
assertEquals("CustomMessage_UpdateUserAttribute", event.path("triggerSource").asText());
assertEquals(client.getClientId(), event.path("callerContext").path("clientId").asText());
JsonNode request = event.path("request");
assertEquals("{####}", request.path("codeParameter").asText());
assertEquals("profile", request.path("clientMetadata").path("source").asText());
assertEquals("spike@example.org", request.path("userAttributes").path("email").asText());
assertEquals("false", request.path("userAttributes").path("email_verified").asText());
assertEquals("Renamed", request.path("userAttributes").path("name").asText());
assertVerificationEmail(ses, "spike@example.org", "Confirm your address", "Your code is 777888");
}
@Test
void customMessageFiresWithVerifyUserAttributeTriggerSourceOnGetUserAttributeVerificationCode() throws Exception {
SesService ses = mock(SesService.class);
CognitoService svc = customMessageService(ses, VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION, "777888");
UserPool pool = customMessagePool(svc, Map.of("AutoVerifiedAttributes", List.of("email")));
UserPoolClient client = customMessageClient(svc, pool);
String accessToken = customMessageUser(svc, pool, client);
ArgumentCaptor<byte[]> events = customMessageAnswers(Map.of(
"emailSubject", "Verify your address",
"emailMessage", "Your code is {####}"));
svc.getUserAttributeVerificationCode(accessToken, "email", Map.of("source", "settings"));
JsonNode event = MAPPER.readTree(events.getValue());
assertEquals("CustomMessage_VerifyUserAttribute", event.path("triggerSource").asText());
assertEquals(client.getClientId(), event.path("callerContext").path("clientId").asText());
JsonNode request = event.path("request");
assertEquals("{####}", request.path("codeParameter").asText());
assertEquals("settings", request.path("clientMetadata").path("source").asText());
assertEquals("spike@example.com", request.path("userAttributes").path("email").asText());
assertVerificationEmail(ses, "spike@example.com", "Verify your address", "Your code is 777888");
}
/**
* Measured (eu-west-1, 2026-10-21 and 2026-10-22): with an email that must be verified before it
* changes, both events carry the address still in place, and both codes go to the new one; a
* request without ClientMetadata leaves the key out.
*/
@Test
void customMessageForAnEmailAwaitingVerificationCarriesTheAddressStillInPlace() throws Exception {
SesService ses = mock(SesService.class);
CognitoService svc = customMessageService(ses, VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION, "777888");
UserPool pool = customMessagePool(svc, Map.of(
"AutoVerifiedAttributes", List.of("email"),
"UserAttributeUpdateSettings", Map.of("AttributesRequireVerificationBeforeUpdate", List.of("email"))));
UserPoolClient client = customMessageClient(svc, pool);
String accessToken = customMessageUser(svc, pool, client);
ArgumentCaptor<byte[]> events = customMessageAnswers(Map.of());
svc.updateUserAttributes(accessToken, newEmailAndName(), Map.of());
svc.getUserAttributeVerificationCode(accessToken, "email", Map.of());
List<byte[]> sent = events.getAllValues();
assertEquals(2, sent.size());
for (byte[] payload : sent) {
JsonNode request = MAPPER.readTree(payload).path("request");
assertFalse(request.has("clientMetadata"));
JsonNode userAttributes = request.path("userAttributes");
assertEquals("spike@example.com", userAttributes.path("email").asText());
assertEquals("true", userAttributes.path("email_verified").asText());
assertEquals("Renamed", userAttributes.path("name").asText());
}
ArgumentCaptor<SendEmailRequest> emails = ArgumentCaptor.forClass(SendEmailRequest.class);
verify(ses, times(2)).sendServiceEmail(emails.capture());
assertEquals(List.of(List.of("spike@example.org"), List.of("spike@example.org")),
emails.getAllValues().stream().map(SendEmailRequest::toAddresses).toList());
}
/**
* Measured (eu-west-1, 2026-10-22): Cognito keeps an update whose code it cannot deliver, and
* answers CodeDeliveryFailureException.
*/
@Test
void anUpdateWhoseCodeCannotBeSentIsKept() {
SesService ses = mock(SesService.class);
when(ses.sendServiceEmail(any())).thenThrow(new IllegalStateException("SES unavailable"));
CognitoService svc = customMessageService(ses, VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION, "777888");
UserPool pool = customMessagePool(svc, Map.of("AutoVerifiedAttributes", List.of("email")));
UserPoolClient client = customMessageClient(svc, pool);
String accessToken = customMessageUser(svc, pool, client);
customMessageAnswers(Map.of());
AwsException failure = assertThrows(AwsException.class,
() -> svc.updateUserAttributes(accessToken, newEmailAndName(), Map.of()));
assertEquals("CodeDeliveryFailureException", failure.getErrorCode());
Map<String, String> attributes = svc.adminGetUser(pool.getId(), "spike").getAttributes();
assertEquals("spike@example.org", attributes.get("email"));
assertEquals("false", attributes.get("email_verified"));
assertEquals("Renamed", attributes.get("name"));
}
/**
* An update that cannot issue a later attribute's code stores nothing, and withdraws the codes it
* issued before it, which no message carried, so they can be asked for again at once.
*/
@Test
void anUpdateThatCannotIssueALaterCodeWithdrawsTheCodesBeforeIt() {
SesService ses = mock(SesService.class);
VerificationCodeService codes = attributeCodes();
when(codes.issue(any(), any(), eq(VerificationCode.Purpose.PHONE_ATTRIBUTE_VERIFICATION), any()))
.thenThrow(new VerificationCodeException(VerificationCodeException.Kind.RATE_LIMIT,
"Attempt limit exceeded, please try again later"));
CognitoService svc = createServiceWithMessaging(ses, mock(SnsService.class), codes);
UserPool pool = customMessagePool(svc, Map.of("AutoVerifiedAttributes", List.of("email")));
String accessToken = customMessageUser(svc, pool, customMessageClient(svc, pool));
customMessageAnswers(Map.of());
clearInvocations(codes);
AwsException refused = assertThrows(AwsException.class,
() -> svc.updateUserAttributes(accessToken, newEmailAndPhoneNumber(), Map.of()));
assertEquals("LimitExceededException", refused.getErrorCode());
verify(codes).invalidatePrevious(pool.getId(), "spike", VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION);
verify(ses, never()).sendServiceEmail(any());
assertEquals("spike@example.com", svc.adminGetUser(pool.getId(), "spike").getAttributes().get("email"));
}
/** One message that cannot be sent holds back no other code of the update, and its own is withdrawn. */
@Test
void aCodeThatCannotBeSentHoldsBackNoOther() {
SesService ses = mock(SesService.class);
when(ses.sendServiceEmail(any())).thenThrow(new IllegalStateException("SES unavailable"));
SnsService sns = mock(SnsService.class);
VerificationCodeService codes = attributeCodes();
CognitoService svc = createServiceWithMessaging(ses, sns, codes);
UserPool pool = customMessagePool(svc, Map.of("AutoVerifiedAttributes", List.of("email")));
String accessToken = customMessageUser(svc, pool, customMessageClient(svc, pool));
customMessageAnswers(Map.of());
clearInvocations(codes);
AwsException failure = assertThrows(AwsException.class,
() -> svc.updateUserAttributes(accessToken, newEmailAndPhoneNumber(), Map.of()));
assertEquals("CodeDeliveryFailureException", failure.getErrorCode());
verify(sns).publish(any(), any(), eq("+12025550123"), contains("555666"), any(), any(), any());
verify(codes).invalidatePrevious(pool.getId(), "spike", VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION);
verify(codes, never()).invalidatePrevious(pool.getId(), "spike",
VerificationCode.Purpose.PHONE_ATTRIBUTE_VERIFICATION);
}
@Test
void aVerificationCodeThatCannotBeSentIsWithdrawn() {
SesService ses = mock(SesService.class);
when(ses.sendServiceEmail(any())).thenThrow(new IllegalStateException("SES unavailable"));
VerificationCodeService codes = attributeCodes();
CognitoService svc = createServiceWithMessaging(ses, mock(SnsService.class), codes);
UserPool pool = customMessagePool(svc, Map.of("AutoVerifiedAttributes", List.of("email")));
String accessToken = customMessageUser(svc, pool, customMessageClient(svc, pool));
customMessageAnswers(Map.of());
clearInvocations(codes);
AwsException failure = assertThrows(AwsException.class,
() -> svc.getUserAttributeVerificationCode(accessToken, "email", Map.of()));
assertEquals("CodeDeliveryFailureException", failure.getErrorCode());
verify(codes).invalidatePrevious(pool.getId(), "spike", VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION);
}
/** What the message goes out with is read before the update is stored: a client deleted after does not stop it. */
@Test
void anUpdatesCodeGoesOutThoughItsClientIsDeletedOnceTheUpdateIsStored() throws Exception {
SesService ses = mock(SesService.class);
AtomicReference<CognitoService> service = new AtomicReference<>();
AtomicReference<String> clientId = new AtomicReference<>();
InMemoryStorage<String, CognitoUser> users = new InMemoryStorage<>() {
@Override
public void put(String key, CognitoUser user) {
super.put(key, user);
if ("spike@example.org".equals(user.getAttributes().get("email"))) {
service.get().deleteUserPoolClient(user.getUserPoolId(), clientId.get());
}
}
};
CognitoService svc = createServiceWithMessaging(ses, mock(SnsService.class), attributeCodes(), users);
service.set(svc);
UserPool pool = customMessagePool(svc, Map.of("AutoVerifiedAttributes", List.of("email")));
UserPoolClient client = customMessageClient(svc, pool);
clientId.set(client.getClientId());
String accessToken = customMessageUser(svc, pool, client);
ArgumentCaptor<byte[]> events = customMessageAnswers(Map.of(
"emailSubject", "Confirm your address",
"emailMessage", "Your code is {####}"));
svc.updateUserAttributes(accessToken, Map.of("email", "spike@example.org"), Map.of());
assertEquals(client.getClientId(),
MAPPER.readTree(events.getValue()).path("callerContext").path("clientId").asText());
assertVerificationEmail(ses, "spike@example.org", "Confirm your address", "Your code is 777888");
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void customMessageFunctionCallingBackForTheUserOfAnAttributeCodeIsNotBlocked(boolean update) {
CognitoService svc = customMessageService(mock(SesService.class),
VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION, "777888");
UserPool pool = customMessagePool(svc, Map.of("AutoVerifiedAttributes", List.of("email")));
UserPoolClient client = customMessageClient(svc, pool);
String accessToken = customMessageUser(svc, pool, client);
when(lambdaService.invoke(anyString(), eq(CUSTOM_MESSAGE), any(byte[].class),
eq(InvocationType.RequestResponse))).thenAnswer(invocation -> {
callFromFunction(() -> {
svc.adminUpdateUserAttributes(pool.getId(), "spike", Map.of("name", "Set by the function"));
return null;
});
return ok(Map.of());
});
// The function's call is for the user the request sends a code to. It would wait out the
// invocation if the request held that user's lock stripe while the function ran.
assertTimeoutPreemptively(Duration.ofSeconds(10), () -> {
if (update) {
svc.updateUserAttributes(accessToken, Map.of("email", "spike@example.org"), Map.of());
} else {
svc.getUserAttributeVerificationCode(accessToken, "email", Map.of());
}
});
assertEquals("Set by the function", svc.adminGetUser(pool.getId(), "spike").getAttributes().get("name"));
}
/** Measured (eu-west-1, 2026-10-21): no ClientMetadata omits the key, including an empty map. */
@Test
void customMessageSignUpOmitsMissingOrEmptyClientMetadata() throws Exception {
@@ -68,6 +68,7 @@ import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.*;
class CognitoServiceTest {
@@ -2584,7 +2585,7 @@ class CognitoServiceTest {
verify(messageDispatcher).dispatch(
eq(pool), deliveryUser.capture(),
eq(VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION),
eq("123456"), eq(List.of("EMAIL")));
eq("123456"), eq(List.of("EMAIL")), isNull());
assertEquals("new@example.com", deliveryUser.getValue().getAttributes().get("email"));
assertEquals("old@example.com",
serviceWithVerification.adminGetUser(pool.getId(), "alice").getAttributes().get("email"));