fix(cognito): verify admin contact attribute updates (#6474)

* fix(cognito): verify admin contact attribute updates

* fix(cognito): roll back failed admin contact updates

* fix(cognito): preserve verification during overlapping callbacks

* fix(cognito): scope verification cleanup to issued codes

* fix(cognito): retry undelivered admin attribute codes

* test(cognito): update tracked code fixtures

* fix(cognito): share contact updates after sender failures
This commit is contained in:
Jimmy Liu Jia authored and GitHub committed 2026-10-25 08:59:27 -04:00
1 parent 9c8d2ba58d
commit b90b671c21
13 files changed
+607 -85

No files matched your search

+4
View File
@@ -599,6 +599,10 @@ verification code can be requested after the sender is working again.
Codes issued for earlier destinations of changed contacts are also withdrawn,
including when the replacement is pending. Codes for unchanged contacts that
the failed delivery did not reach remain usable.
`AdminUpdateUserAttributes` uses the same contact update and failed-sender handling.
It skips verification delivery when the request sets the matching `*_verified`
attribute to `true`. Otherwise, retrying an identical admin update sends a new
code if the previous delivery failed and left no usable code.
A verification code is still sent to the replacement value, but Cognito no
longer retains or exposes the old value. For alias attributes, the old alias is
removed immediately and the replacement becomes usable for sign-in only after
@@ -1964,7 +1964,8 @@ final class CognitoAuthFlowHandler {
byte[] payload;
try {
payload = MAPPER.writeValueAsBytes(
triggerEvent(pool, clientId, user, "CustomEmailSender", triggerSource, req));
triggerEvent(pool, clientId == null ? CLIENT_ID_NOT_APPLICABLE : clientId,
user, "CustomEmailSender", triggerSource, req));
} catch (JsonProcessingException e) {
throw new IllegalStateException("Cannot serialize the CustomEmailSender event", e);
}
@@ -723,7 +723,8 @@ public class CognitoJsonHandler {
service.adminUpdateUserAttributes(
request.path("UserPoolId").asText(),
request.path("Username").asText(),
attrs
attrs,
clientMetadata(request)
);
return Response.ok(objectMapper.createObjectNode()).build();
}
@@ -2676,45 +2676,95 @@ public class CognitoService implements ResourceProvider {
}
public void adminUpdateUserAttributes(String userPoolId, String username, Map<String, String> attributes) {
adminUpdateUserAttributes(userPoolId, username, attributes, Map.of());
}
public void adminUpdateUserAttributes(String userPoolId, String username, Map<String, String> attributes,
Map<String, String> clientMetadata) {
CognitoUser resolvedUser = adminGetUser(userPoolId, username);
List<AttributeCodeMessage> messages = new ArrayList<>();
AttributeCodeSending sending;
synchronized (userLock(userPoolId, resolvedUser.getUsername())) {
adminUpdateUserAttributesUnderUserLock(
userPoolId, resolvedUser.getUsername(), attributes);
userPoolId, resolvedUser.getUsername(), attributes, clientMetadata, messages);
sending = attributeCodeSending(userPoolId, resolvedUser.getUsername(), null);
}
sendAttributeCodeMessages(sending, "CustomMessage_UpdateUserAttribute", clientMetadata, messages);
}
private void adminUpdateUserAttributesUnderUserLock(
String userPoolId, String username, Map<String, String> attributes) {
CognitoUser user = adminGetUser(userPoolId, username);
String userPoolId, String username, Map<String, String> attributes,
Map<String, String> clientMetadata, List<AttributeCodeMessage> messages) {
CognitoUser currentUser = adminGetUser(userPoolId, username);
UserPool pool = describeUserPool(userPoolId);
boolean stagesContactUpdate = attributes.entrySet().stream()
.anyMatch(attribute -> isVerifiableContactAttribute(attribute.getKey())
&& shouldVerifyAttribute(pool, attribute.getKey())
&& !isExplicitlyVerified(attributes, attribute.getKey())
&& blankToNull(attribute.getValue()) != null);
CognitoUser updatedUser = stagesContactUpdate
? MAPPER.convertValue(currentUser, CognitoUser.class) : currentUser;
validateEmailAttribute(attributes, true);
if (usesAliasUsernames(pool)) {
for (String aliasAttribute : pool.getUsernameAttributes()) {
String newValue = attributes.get(aliasAttribute);
if (blankToNull(newValue) == null || newValue.equals(user.getAttributes().get(aliasAttribute))) {
if (blankToNull(newValue) == null || newValue.equals(currentUser.getAttributes().get(aliasAttribute))) {
continue;
}
CognitoUser other = findUserByAlias(userPoolId, aliasAttribute, newValue);
if (other != null && !other.getUsername().equals(user.getUsername())) {
if (other != null && !other.getUsername().equals(currentUser.getUsername())) {
throw new AwsException("AliasExistsException",
"An account with the given " + aliasAttribute + " already exists.", 400);
}
}
}
attributes.keySet().forEach(attributeName ->
clearPendingAttributeVerification(userPoolId, user, attributeName));
Map<String, String> contacts = new LinkedHashMap<>();
for (Map.Entry<String, String> attribute : attributes.entrySet()) {
String attributeName = attribute.getKey();
String value = attribute.getValue();
boolean contact = isVerifiableContactAttribute(attributeName);
if (blankToNull(value) == null) {
user.getAttributes().remove(attributeName);
user.getAttributes().remove(attributeName + "_verified");
updatedUser.getAttributes().remove(attributeName);
updatedUser.getAttributes().remove(attributeName + "_verified");
clearPendingAttributeVerification(userPoolId, updatedUser, attributeName);
} else if (contact && shouldVerifyAttribute(pool, attributeName)
&& !isExplicitlyVerified(attributes, attributeName)) {
String pending = updatedUser.getPendingAttributes().get(attributeName);
boolean sameCurrent = value.equals(updatedUser.getAttributes().get(attributeName));
if (sameCurrent && "true".equalsIgnoreCase(
updatedUser.getAttributes().get(attributeName + "_verified"))) {
continue;
}
if (value.equals(pending) || sameCurrent) {
ensureVerificationWiring();
if (verificationCodeService.hasUsableCode(
userPoolId, updatedUser.getUsername(), verificationPurpose(attributeName))) {
continue;
}
}
clearPendingAttributeVerification(userPoolId, updatedUser, attributeName);
stageContactAttributeUpdate(pool, updatedUser, attributeName, value);
contacts.put(attributeName, value);
} else {
user.getAttributes().put(attributeName, value);
clearPendingAttributeVerification(userPoolId, updatedUser, attributeName);
updatedUser.getAttributes().put(attributeName, value);
if (contact && isExplicitlyVerified(attributes, attributeName)) {
updatedUser.getAttributes().put(attributeName + "_verified", "true");
updatedUser.getPendingAttributes().remove(attributeName);
}
}
}
user.setLastModifiedDate(System.currentTimeMillis() / 1000L);
userStore.put(userKey(userPoolId, user.getUsername()), user);
completeContactAttributeUpdate(pool, null, currentUser, updatedUser, contacts,
"CustomEmailSender_AdminUpdateUserAttribute", clientMetadata, messages);
}
private boolean isExplicitlyVerified(Map<String, String> attributes, String attributeName) {
return "true".equalsIgnoreCase(attributes.get(attributeName + "_verified"));
}
private boolean shouldVerifyAttribute(UserPool pool, String attributeName) {
return pool.getAutoVerifiedAttributes() != null
&& pool.getAutoVerifiedAttributes().contains(attributeName);
}
public void adminDeleteUserAttributes(String userPoolId, String username, List<String> attributeNames) {
@@ -4118,7 +4168,7 @@ public class CognitoService implements ResourceProvider {
: VerificationCode.Purpose.PHONE_ATTRIBUTE_VERIFICATION;
ensureVerificationWiring();
try {
String code = verificationCodeService.issue(poolId, user.getUsername(),
VerificationCodeService.IssuedCode code = verificationCodeService.issueTracked(poolId, user.getUsername(),
purpose, Duration.ofHours(24));
dispatchAttributeVerificationCode(pool, clientId, user, attributeName, destination, purpose, code,
"CustomEmailSender_VerifyUserAttribute", clientMetadata, messages);
@@ -4244,9 +4294,7 @@ public class CognitoService implements ResourceProvider {
}
CognitoUser updatedUser = MAPPER.convertValue(currentUser, CognitoUser.class);
List<Map<String, Object>> deliveryDetails = new ArrayList<>();
Map<String, String> contacts = new LinkedHashMap<>();
for (Map.Entry<String, String> attribute : attributes.entrySet()) {
String attributeName = attribute.getKey();
String value = attribute.getValue();
@@ -4257,17 +4305,30 @@ public class CognitoService implements ResourceProvider {
} else if (!isVerifiableContactAttribute(attributeName)) {
updatedUser.getAttributes().put(attributeName, value);
} else {
stageContactAttributeUpdate(pool, updatedUser, attributeName, value);
contacts.put(attributeName, value);
if (requiresVerificationBeforeUpdate(pool, attributeName)) {
updatedUser.getPendingAttributes().put(attributeName, value);
} else {
updatedUser.getAttributes().put(attributeName, value);
updatedUser.getAttributes().put(attributeName + "_verified", "false");
updatedUser.getPendingAttributes().remove(attributeName);
}
}
}
return completeContactAttributeUpdate(pool, clientId, currentUser, updatedUser, contacts,
"CustomEmailSender_UpdateUserAttribute", clientMetadata, messages);
}
private void stageContactAttributeUpdate(UserPool pool, CognitoUser user, String attributeName, String value) {
if (requiresVerificationBeforeUpdate(pool, attributeName)) {
user.getPendingAttributes().put(attributeName, value);
} else {
user.getAttributes().put(attributeName, value);
user.getAttributes().put(attributeName + "_verified", "false");
user.getPendingAttributes().remove(attributeName);
}
}
private List<Map<String, Object>> completeContactAttributeUpdate(
UserPool pool, String clientId, CognitoUser currentUser, CognitoUser updatedUser,
Map<String, String> contacts, String customEmailSenderSource,
Map<String, String> clientMetadata, List<AttributeCodeMessage> messages) {
String poolId = pool.getId();
List<Map<String, Object>> deliveryDetails = new ArrayList<>();
boolean issued = false;
try {
for (Map.Entry<String, String> attribute : contacts.entrySet()) {
@@ -4275,10 +4336,10 @@ public class CognitoService implements ResourceProvider {
String value = attribute.getValue();
VerificationCode.Purpose purpose = verificationPurpose(attributeName);
ensureVerificationWiring();
String verificationCode = verificationCodeService.issue(
VerificationCodeService.IssuedCode verificationCode = verificationCodeService.issueTracked(
poolId, currentUser.getUsername(), purpose, Duration.ofHours(24));
dispatchAttributeVerificationCode(pool, clientId, currentUser, attributeName, value,
purpose, verificationCode, "CustomEmailSender_UpdateUserAttribute", clientMetadata, messages);
purpose, verificationCode, customEmailSenderSource, clientMetadata, messages);
Map<String, Object> detail = new LinkedHashMap<>();
detail.put("AttributeName", attributeName);
@@ -4290,10 +4351,9 @@ public class CognitoService implements ResourceProvider {
} catch (VerificationCodeException e) {
throw mapVerificationCodeException(e);
} catch (CustomEmailSenderException e) {
for (String attributeName : attributes.keySet()) {
if (isVerifiableContactAttribute(attributeName)
&& !Objects.equals(attributeVerificationDestination(currentUser, attributeName),
attributeVerificationDestination(updatedUser, attributeName))) {
for (String attributeName : List.of("email", "phone_number")) {
if (!Objects.equals(attributeVerificationDestination(currentUser, attributeName),
attributeVerificationDestination(updatedUser, attributeName))) {
verificationCodeService.invalidatePrevious(
poolId, currentUser.getUsername(), verificationPurpose(attributeName));
}
@@ -4308,8 +4368,8 @@ public class CognitoService implements ResourceProvider {
} finally {
if (!issued) {
// A failed sender hand-over must not leave earlier queued codes live but unsent.
messages.forEach(message -> verificationCodeService.invalidatePrevious(
poolId, currentUser.getUsername(), message.purpose()));
messages.forEach(message -> verificationCodeService.invalidateIfCurrent(
poolId, currentUser.getUsername(), message.purpose(), message.issued()));
}
}
@@ -6055,20 +6115,22 @@ public class CognitoService implements ResourceProvider {
*/
private void dispatchAttributeVerificationCode(UserPool pool, String clientId, CognitoUser user,
String attributeName, String destination,
VerificationCode.Purpose purpose, String code,
VerificationCode.Purpose purpose,
VerificationCodeService.IssuedCode issued,
String customEmailSenderSource,
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)) {
messages.add(new AttributeCodeMessage(deliveryUser, purpose, code, deliveryMedium(attributeName)));
customEmailSenderSource, purpose, issued.code(), clientMetadata)) {
messages.add(new AttributeCodeMessage(deliveryUser, purpose, issued, 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,
private record AttributeCodeMessage(CognitoUser deliveryUser, VerificationCode.Purpose purpose,
VerificationCodeService.IssuedCode issued,
String deliveryMedium) {
}
@@ -6101,13 +6163,14 @@ public class CognitoService implements ResourceProvider {
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(),
messageDispatcher.dispatch(sending.pool(), message.deliveryUser(), message.purpose(),
message.issued().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());
verificationCodeService.invalidateIfCurrent(
sending.pool().getId(), sending.user().getUsername(), message.purpose(), message.issued());
if (failure == null) {
failure = e;
}
@@ -70,14 +70,23 @@ public final class VerificationCodeService {
*/
public String issue(String userPoolId, String username,
VerificationCode.Purpose purpose, Duration ttl) {
return issueTracked(userPoolId, username, purpose, ttl).code();
}
public record IssuedCode(String code, String hash) {
}
/** Issue a code with an identity that can safely withdraw only this issuance. */
public IssuedCode issueTracked(String userPoolId, String username,
VerificationCode.Purpose purpose, Duration ttl) {
String key = VerificationCode.storageKey(userPoolId, username, purpose);
synchronized (lockFor(key)) {
return issueUnderLock(key, userPoolId, username, purpose, ttl);
}
}
private String issueUnderLock(String key, String userPoolId, String username,
VerificationCode.Purpose purpose, Duration ttl) {
private IssuedCode issueUnderLock(String key, String userPoolId, String username,
VerificationCode.Purpose purpose, Duration ttl) {
Optional<VerificationCode> existing = store.get(key);
if (existing.isPresent() && !existing.get().isConsumed()) {
Duration since = Duration.between(existing.get().getIssuedAt(), clock.instant());
@@ -101,7 +110,7 @@ public final class VerificationCodeService {
userPoolId, username, purpose, hash, salt, now, now.plus(ttl), MAX_ATTEMPTS
);
store.put(key, vc);
return code;
return new IssuedCode(code, hash);
}
/**
@@ -184,6 +193,27 @@ public final class VerificationCodeService {
invalidate(VerificationCode.storageKey(userPoolId, username, purpose));
}
public boolean hasUsableCode(String userPoolId, String username,
VerificationCode.Purpose purpose) {
String key = VerificationCode.storageKey(userPoolId, username, purpose);
synchronized (lockFor(key)) {
return store.get(key).map(code -> !code.isConsumed()
&& !code.isExpired(clock.instant())
&& code.getAttemptsRemaining() > 0).orElse(false);
}
}
/** Withdraw only the code issued by the caller, preserving a newer replacement. */
public void invalidateIfCurrent(String userPoolId, String username,
VerificationCode.Purpose purpose, IssuedCode issued) {
String key = VerificationCode.storageKey(userPoolId, username, purpose);
synchronized (lockFor(key)) {
if (store.get(key).map(current -> current.getCodeHash().equals(issued.hash())).orElse(false)) {
store.delete(key);
}
}
}
/**
* Removes every code issued for a pool, for DeleteUserPool. Pool ids are caller-chosen via
* floci:override-id and may contain a colon, so the key prefix alone also matches a distinct
@@ -0,0 +1,109 @@
package io.github.hectorvent.floci.services.cognito;
import io.github.hectorvent.floci.config.TlsCertificateManager;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.acm.AcmService;
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.verification.CognitoMessageDispatcher;
import io.github.hectorvent.floci.services.cognito.verification.VerificationCode;
import io.github.hectorvent.floci.services.cognito.verification.VerificationCodeService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import static io.github.hectorvent.floci.testing.InlineMocks.inlineMock;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
class CognitoAdminAttributeVerificationTest {
private CognitoService service;
private VerificationCodeService codes;
private CognitoMessageDispatcher dispatcher;
private UserPool pool;
@BeforeEach
void setUp() {
codes = inlineMock(VerificationCodeService.class);
dispatcher = inlineMock(CognitoMessageDispatcher.class);
when(codes.issueTracked(anyString(), anyString(), any(), any(Duration.class)))
.thenReturn(new VerificationCodeService.IssuedCode("123456", "test-hash"));
service = new CognitoService(
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(),
"http://localhost:4566", new RegionResolver("us-east-1", "000000000000"),
null, mock(AcmService.class), codes, dispatcher, mock(TlsCertificateManager.class));
pool = service.createUserPool(Map.of("PoolName", "AdminAttributeVerification",
"AutoVerifiedAttributes", List.of("email")), "us-east-1");
service.adminCreateUser(pool.getId(), "alice", Map.of(
"email", "old@example.com", "email_verified", "true"), "TempPass1!");
clearInvocations(codes, dispatcher);
}
@Test
void changingEmailClearsItsVerifiedFlag() {
service.adminUpdateUserAttributes(pool.getId(), "alice", Map.of("email", "new@example.com"));
CognitoUser updated = service.adminGetUser(pool.getId(), "alice");
assertEquals("new@example.com", updated.getAttributes().get("email"));
assertEquals("false", updated.getAttributes().get("email_verified"));
}
@Test
void changingEmailSendsItsVerificationCode() {
service.adminUpdateUserAttributes(pool.getId(), "alice", Map.of("email", "new@example.com"));
verify(codes).issueTracked(eq(pool.getId()), eq("alice"),
eq(VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION), any(Duration.class));
verify(dispatcher).dispatch(eq(pool), any(), eq(VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION),
eq("123456"), eq(List.of("EMAIL")), any());
}
@Test
void explicitlyVerifiedEmailSkipsTheVerificationMessage() {
service.adminUpdateUserAttributes(pool.getId(), "alice", Map.of(
"email", "trusted@example.com", "email_verified", "true"));
CognitoUser updated = service.adminGetUser(pool.getId(), "alice");
assertEquals("trusted@example.com", updated.getAttributes().get("email"));
assertEquals("true", updated.getAttributes().get("email_verified"));
verifyNoInteractions(dispatcher);
}
@Test
void requiringVerificationBeforeUpdatePreservesCurrentEmailUntilVerified() {
UserPool pendingPool = service.createUserPool(Map.of(
"PoolName", "AdminPendingAttributeVerification",
"AutoVerifiedAttributes", List.of("email"),
"UserAttributeUpdateSettings", Map.of(
"AttributesRequireVerificationBeforeUpdate", List.of("email"))), "us-east-1");
service.adminCreateUser(pendingPool.getId(), "bob", Map.of(
"email", "old@example.com", "email_verified", "true"), "TempPass1!");
clearInvocations(codes, dispatcher);
service.adminUpdateUserAttributes(pendingPool.getId(), "bob", Map.of("email", "new@example.com"));
CognitoUser updated = service.adminGetUser(pendingPool.getId(), "bob");
assertEquals("old@example.com", updated.getAttributes().get("email"));
assertEquals("true", updated.getAttributes().get("email_verified"));
assertEquals("new@example.com", updated.getPendingAttributes().get("email"));
verify(codes).issueTracked(eq(pendingPool.getId()), eq("bob"),
eq(VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION), any(Duration.class));
verify(dispatcher).dispatch(eq(pendingPool), any(),
eq(VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION), eq("123456"),
eq(List.of("EMAIL")), any());
}
}
@@ -58,7 +58,7 @@ class CognitoAttributeVerificationConcurrencyTest {
CountDownLatch releaseFirstIssue = new CountDownLatch(1);
CountDownLatch secondStarted = new CountDownLatch(1);
when(codes.issue(anyString(), anyString(), any(), any(Duration.class)))
when(codes.issueTracked(anyString(), anyString(), any(), any(Duration.class)))
.thenAnswer(invocation -> {
int issue = issues.incrementAndGet();
if (issue == 1) {
@@ -67,7 +67,7 @@ class CognitoAttributeVerificationConcurrencyTest {
}
String code = issue == 1 ? FIRST_CODE : SECOND_CODE;
latestCode.set(code);
return code;
return new VerificationCodeService.IssuedCode(code, "test-hash-" + issue);
});
doAnswer(invocation -> {
CognitoUser deliveryUser = invocation.getArgument(1);
@@ -118,7 +118,7 @@ class CognitoAttributeVerificationConcurrencyTest {
CountDownLatch releaseResendIssue = new CountDownLatch(1);
CountDownLatch updateStarted = new CountDownLatch(1);
when(codes.issue(anyString(), anyString(), any(), any(Duration.class)))
when(codes.issueTracked(anyString(), anyString(), any(), any(Duration.class)))
.thenAnswer(invocation -> {
int issue = issues.incrementAndGet();
if (issue == 2) {
@@ -127,7 +127,7 @@ class CognitoAttributeVerificationConcurrencyTest {
}
String code = issue == 1 ? FIRST_CODE : issue == 2 ? SECOND_CODE : "333333";
latestCode.set(code);
return code;
return new VerificationCodeService.IssuedCode(code, "test-hash-" + issue);
});
acceptOnlyLatestCode(codes, latestCode);
@@ -173,8 +173,12 @@ class CognitoAttributeVerificationConcurrencyTest {
CountDownLatch releaseConsume = new CountDownLatch(1);
CountDownLatch updateStarted = new CountDownLatch(1);
when(codes.issue(anyString(), anyString(), any(), any(Duration.class)))
.thenAnswer(invocation -> issues.incrementAndGet() == 1 ? FIRST_CODE : SECOND_CODE);
when(codes.issueTracked(anyString(), anyString(), any(), any(Duration.class)))
.thenAnswer(invocation -> {
int issue = issues.incrementAndGet();
return new VerificationCodeService.IssuedCode(
issue == 1 ? FIRST_CODE : SECOND_CODE, "test-hash-" + issue);
});
doAnswer(invocation -> {
assertEquals(FIRST_CODE, invocation.getArgument(3));
consumeEntered.countDown();
@@ -220,8 +224,8 @@ class CognitoAttributeVerificationConcurrencyTest {
CountDownLatch releaseConsume = new CountDownLatch(1);
CountDownLatch adminStarted = new CountDownLatch(1);
when(codes.issue(anyString(), anyString(), any(), any(Duration.class)))
.thenReturn(FIRST_CODE);
when(codes.issueTracked(anyString(), anyString(), any(), any(Duration.class)))
.thenReturn(new VerificationCodeService.IssuedCode(FIRST_CODE, "test-hash"));
doAnswer(invocation -> {
assertEquals(FIRST_CODE, invocation.getArgument(3));
consumeEntered.countDown();
@@ -250,9 +254,10 @@ class CognitoAttributeVerificationConcurrencyTest {
verify.get(5, TimeUnit.SECONDS);
adminUpdate.get(5, TimeUnit.SECONDS);
assertEquals(ADMIN_EMAIL, harness.user().getAttributes().get("email"),
assertEquals(FIRST_EMAIL, harness.user().getAttributes().get("email"),
"verification finishing later must not overwrite a completed admin update");
assertNull(harness.user().getPendingAttributes().get("email"));
assertEquals(ADMIN_EMAIL, harness.user().getPendingAttributes().get("email"),
"the completed admin update remains pending until its new value is verified");
} finally {
releaseConsume.countDown();
executor.shutdownNow();
@@ -268,8 +273,8 @@ class CognitoAttributeVerificationConcurrencyTest {
CountDownLatch releaseConsume = new CountDownLatch(1);
CountDownLatch adminStarted = new CountDownLatch(1);
when(codes.issue(anyString(), anyString(), any(), any(Duration.class)))
.thenReturn(FIRST_CODE);
when(codes.issueTracked(anyString(), anyString(), any(), any(Duration.class)))
.thenReturn(new VerificationCodeService.IssuedCode(FIRST_CODE, "test-hash"));
doAnswer(invocation -> {
assertEquals(FIRST_CODE, invocation.getArgument(3));
consumeEntered.countDown();
@@ -316,8 +321,8 @@ class CognitoAttributeVerificationConcurrencyTest {
CountDownLatch releaseConsume = new CountDownLatch(1);
CountDownLatch adminStarted = new CountDownLatch(1);
when(codes.issue(anyString(), anyString(), any(), any(Duration.class)))
.thenReturn(FIRST_CODE);
when(codes.issueTracked(anyString(), anyString(), any(), any(Duration.class)))
.thenReturn(new VerificationCodeService.IssuedCode(FIRST_CODE, "test-hash"));
doAnswer(invocation -> {
assertEquals(FIRST_CODE, invocation.getArgument(3));
consumeEntered.countDown();
@@ -368,8 +373,8 @@ class CognitoAttributeVerificationConcurrencyTest {
CountDownLatch releaseConsume = new CountDownLatch(1);
CountDownLatch changeStarted = new CountDownLatch(1);
when(codes.issue(anyString(), anyString(), any(), any(Duration.class)))
.thenReturn(FIRST_CODE);
when(codes.issueTracked(anyString(), anyString(), any(), any(Duration.class)))
.thenReturn(new VerificationCodeService.IssuedCode(FIRST_CODE, "test-hash"));
doAnswer(invocation -> {
assertEquals(FIRST_CODE, invocation.getArgument(3));
consumeEntered.countDown();
@@ -9,10 +9,12 @@ import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.acm.AcmService;
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.CustomSenderCodeEncryptor;
import io.github.hectorvent.floci.services.cognito.verification.VerificationCode;
import io.github.hectorvent.floci.services.cognito.verification.VerificationCodeService;
import io.github.hectorvent.floci.services.kms.KmsService;
import io.github.hectorvent.floci.services.lambda.LambdaService;
@@ -86,6 +88,7 @@ class CognitoCustomEmailSenderTest {
private SesService ses;
private SnsService sns;
private CognitoService service;
private VerificationCodeService codes;
@BeforeEach
void setUp() {
@@ -96,16 +99,68 @@ class CognitoCustomEmailSenderTest {
lambda = mock(LambdaService.class);
ses = mock(SesService.class);
sns = mock(SnsService.class);
codes = new VerificationCodeService(storageFactory, Clock.systemUTC());
service = new CognitoService(
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
"http://localhost:4566", "cloudfront.net", regionResolver, lambda, mock(AcmService.class),
new VerificationCodeService(storageFactory, Clock.systemUTC()),
codes,
new CognitoMessageDispatcher(ses, sns, REGION), mock(TlsCertificateManager.class),
Clock.systemUTC(), true, new CustomSenderCodeEncryptor(kms));
}
@ParameterizedTest
@CsvSource({"false, false, false", "true, false, false", "false, true, false", "true, true, false",
"false, false, true", "true, false, true", "false, true, true", "true, true, true"})
void failedAdminSenderKeepsTheWholeUpdate(boolean emailFirst, boolean pending, boolean invocationFailure) {
UserPool pool = pool(Map.of("KMSKeyID", keyArn, "CustomEmailSender", sender()),
List.of("email", "phone_number"));
service.adminCreateUser(pool.getId(), "alice", Map.of(
"email", "old@example.com", "email_verified", "true",
"phone_number", "+12025550100", "phone_number_verified", "true", "name", "Original"), null);
service.adminSetUserPassword(pool.getId(), "alice", "Passw0rd!", true);
if (pending) {
service.updateUserPool(Map.of("UserPoolId", pool.getId(), "UserAttributeUpdateSettings",
Map.of("AttributesRequireVerificationBeforeUpdate", List.of("email", "phone_number"))), REGION);
}
if (invocationFailure) {
when(lambda.invoke(eq(REGION), eq(SENDER), any(byte[].class), any()))
.thenThrow(new AwsException("AccessDeniedException", "Sender unavailable", 400));
} else {
kms.disableKey(keyArn, REGION);
}
Map<String, String> attributes = new LinkedHashMap<>();
if (emailFirst) {
attributes.put("email", "new@example.com");
}
attributes.put("phone_number", "+12025550101");
attributes.put("name", "Renamed");
if (!emailFirst) {
attributes.put("email", "new@example.com");
}
AwsException failure = assertThrows(AwsException.class,
() -> service.adminUpdateUserAttributes(pool.getId(), "alice", attributes));
assertEquals(invocationFailure ? "UnexpectedLambdaException" : "CodeDeliveryFailureException",
failure.getErrorCode());
CognitoUser stored = service.adminGetUser(pool.getId(), "alice");
assertEquals("Renamed", stored.getAttributes().get("name"));
assertEquals(pending ? "old@example.com" : "new@example.com", stored.getAttributes().get("email"));
assertEquals(pending ? "+12025550100" : "+12025550101", stored.getAttributes().get("phone_number"));
assertEquals(pending ? "true" : "false", stored.getAttributes().get("email_verified"));
assertEquals(pending ? "true" : "false", stored.getAttributes().get("phone_number_verified"));
if (pending) {
assertEquals(Map.of("email", "new@example.com", "phone_number", "+12025550101"),
stored.getPendingAttributes());
} else {
assertTrue(stored.getPendingAttributes().isEmpty());
}
assertFalse(codes.hasUsableCode(pool.getId(), "alice", VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION));
assertFalse(codes.hasUsableCode(pool.getId(), "alice", VerificationCode.Purpose.PHONE_ATTRIBUTE_VERIFICATION));
}
@Test
@SuppressWarnings("unchecked")
void signUpHandsTheEncryptedCodeToTheFunctionInsteadOfSendingEmail() throws Exception {
@@ -373,8 +428,9 @@ class CognitoCustomEmailSenderTest {
() -> assertEquals("Renamed", stored.get("name")));
}
@Test
void anUndeliveredAttributeUpdateCodeCanBeRequestedAgain() throws Exception {
@ParameterizedTest
@ValueSource(booleans = {false, true})
void anUndeliveredAttributeUpdateCodeCanBeRequestedAgain(boolean admin) throws Exception {
UserPool pool = pool(Map.of("KMSKeyID", keyArn, "CustomEmailSender", sender()), List.of("email"));
UserPoolClient client = client(pool);
service.adminCreateUser(pool.getId(), "alice",
@@ -383,13 +439,20 @@ class CognitoCustomEmailSenderTest {
String token = signIn(client, "alice", "Passw0rd!");
kms.disableKey(keyArn, REGION);
assertThrows(AwsException.class,
() -> service.updateUserAttributes(token, Map.of("email", "alice@example.org")));
() -> updateAttributes(admin, pool, token, Map.of("email", "alice@example.org")));
kms.enableKey(keyArn, REGION);
service.getUserAttributeVerificationCode(token, "email");
if (admin) {
service.adminUpdateUserAttributes(pool.getId(), "alice", Map.of("email", "alice@example.org"));
} else {
service.getUserAttributeVerificationCode(token, "email");
}
Map<String, Object> verification = senderEvent();
assertEquals("CustomEmailSender_VerifyUserAttribute", verification.get("triggerSource"));
assertEquals(admin ? "CustomEmailSender_AdminUpdateUserAttribute" : "CustomEmailSender_VerifyUserAttribute",
verification.get("triggerSource"));
assertEquals(admin ? "CLIENT_ID_NOT_APPLICABLE" : client.getClientId(),
((Map<?, ?>) verification.get("callerContext")).get("clientId"));
assertEquals("alice@example.org",
((Map<?, ?>) request(verification).get("userAttributes")).get("email"));
service.verifyUserAttribute(token, "email", decrypt(request(verification)).plaintext());
@@ -397,8 +460,10 @@ class CognitoCustomEmailSenderTest {
}
@ParameterizedTest
@CsvSource({"OMIT, false", "SAME, false", "REPLACE, false", "REPLACE, true"})
void anEmailSenderFailureOnlyWithdrawsCodesForChangedDestinations(String phoneUpdate, boolean requiresVerification) {
@CsvSource({"OMIT, false, false", "SAME, false, false", "REPLACE, false, false", "REPLACE, true, false",
"OMIT, false, true", "SAME, false, true", "REPLACE, false, true", "REPLACE, true, true"})
void anEmailSenderFailureOnlyWithdrawsCodesForChangedDestinations(
String phoneUpdate, boolean requiresVerification, boolean admin) {
UserPool pool = pool(Map.of("KMSKeyID", keyArn, "CustomEmailSender", sender()),
List.of("email", "phone_number"));
if (requiresVerification) {
@@ -429,7 +494,7 @@ class CognitoCustomEmailSenderTest {
}
AwsException delivery = assertThrows(AwsException.class,
() -> service.updateUserAttributes(token, attributes));
() -> updateAttributes(admin, pool, token, attributes));
assertEquals("CodeDeliveryFailureException", delivery.getErrorCode());
if (!replacePhone) {
@@ -460,6 +525,14 @@ class CognitoCustomEmailSenderTest {
assertFalse(service.adminGetUser(pool.getId(), "alice").getPendingAttributes().containsKey("phone_number"));
}
private void updateAttributes(boolean admin, UserPool pool, String token, Map<String, String> attributes) {
if (admin) {
service.adminUpdateUserAttributes(pool.getId(), "alice", attributes);
} else {
service.updateUserAttributes(token, attributes);
}
}
/**
* Measured (eu-west-1, 2026-10-20): Cognito hands out a code again at once, on a healthy pool
* and once a key that could not encrypt is enabled again. The code a failed delivery issued is
@@ -2330,6 +2330,8 @@ class CognitoLambdaTriggersTest {
VerificationCodeService verificationCodeService = inlineMock(VerificationCodeService.class);
if (purpose != null) {
when(verificationCodeService.issue(any(), any(), eq(purpose), any())).thenReturn(code);
when(verificationCodeService.issueTracked(any(), any(), eq(purpose), any()))
.thenReturn(new VerificationCodeService.IssuedCode(code, "test-hash"));
}
return createServiceWithMessaging(ses, mock(SnsService.class), verificationCodeService);
}
@@ -2364,8 +2366,12 @@ class CognitoLambdaTriggersTest {
VerificationCodeService codes = inlineMock(VerificationCodeService.class);
when(codes.issue(any(), any(), eq(VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION), any()))
.thenReturn("777888");
when(codes.issueTracked(any(), any(), eq(VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION), any()))
.thenReturn(new VerificationCodeService.IssuedCode("777888", "email-hash"));
when(codes.issue(any(), any(), eq(VerificationCode.Purpose.PHONE_ATTRIBUTE_VERIFICATION), any()))
.thenReturn("555666");
when(codes.issueTracked(any(), any(), eq(VerificationCode.Purpose.PHONE_ATTRIBUTE_VERIFICATION), any()))
.thenReturn(new VerificationCodeService.IssuedCode("555666", "phone-hash"));
return codes;
}
@@ -2651,7 +2657,7 @@ class CognitoLambdaTriggersTest {
void anUpdateThatCannotIssueALaterCodeWithdrawsTheCodesBeforeIt() {
SesService ses = mock(SesService.class);
VerificationCodeService codes = attributeCodes();
when(codes.issue(any(), any(), eq(VerificationCode.Purpose.PHONE_ATTRIBUTE_VERIFICATION), any()))
when(codes.issueTracked(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);
@@ -2664,7 +2670,8 @@ class CognitoLambdaTriggersTest {
() -> svc.updateUserAttributes(accessToken, newEmailAndPhoneNumber(), Map.of()));
assertEquals("LimitExceededException", refused.getErrorCode());
verify(codes).invalidatePrevious(pool.getId(), "spike", VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION);
verify(codes).invalidateIfCurrent(eq(pool.getId()), eq("spike"),
eq(VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION), any());
verify(ses, never()).sendServiceEmail(any());
assertEquals("spike@example.com", svc.adminGetUser(pool.getId(), "spike").getAttributes().get("email"));
}
@@ -2687,9 +2694,10 @@ class CognitoLambdaTriggersTest {
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);
verify(codes).invalidateIfCurrent(eq(pool.getId()), eq("spike"),
eq(VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION), any());
verify(codes, never()).invalidateIfCurrent(eq(pool.getId()), eq("spike"),
eq(VerificationCode.Purpose.PHONE_ATTRIBUTE_VERIFICATION), any());
}
@Test
@@ -2707,7 +2715,8 @@ class CognitoLambdaTriggersTest {
() -> svc.getUserAttributeVerificationCode(accessToken, "email", Map.of()));
assertEquals("CodeDeliveryFailureException", failure.getErrorCode());
verify(codes).invalidatePrevious(pool.getId(), "spike", VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION);
verify(codes).invalidateIfCurrent(eq(pool.getId()), eq("spike"),
eq(VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION), any());
}
/** What the message goes out with is read before the update is stored: a client deleted after does not stop it. */
@@ -2470,9 +2470,9 @@ class CognitoServiceTest {
void expiredPendingEmailCodeLeavesActiveAttributeAndVerifiedFlagUnchanged() {
VerificationCodeService verificationCodeService = inlineMock(VerificationCodeService.class);
CognitoMessageDispatcher messageDispatcher = inlineMock(CognitoMessageDispatcher.class);
when(verificationCodeService.issue(any(), any(),
when(verificationCodeService.issueTracked(any(), any(),
eq(VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION), any()))
.thenReturn("123456");
.thenReturn(new VerificationCodeService.IssuedCode("123456", "test-hash"));
CognitoService serviceWithVerification = new CognitoService(
new InMemoryStorage<>(),
@@ -2534,9 +2534,9 @@ class CognitoServiceTest {
void verificationCodeForRequiredEmailUpdateUsesPendingDestination() {
VerificationCodeService verificationCodeService = inlineMock(VerificationCodeService.class);
CognitoMessageDispatcher messageDispatcher = inlineMock(CognitoMessageDispatcher.class);
when(verificationCodeService.issue(any(), any(),
when(verificationCodeService.issueTracked(any(), any(),
eq(VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION), any()))
.thenReturn("123456");
.thenReturn(new VerificationCodeService.IssuedCode("123456", "test-hash"));
CognitoService serviceWithVerification = new CognitoService(
new InMemoryStorage<>(),
@@ -2606,11 +2606,11 @@ class CognitoServiceTest {
"email", "admin@example.com"));
CognitoUser updated = fixture.service().adminGetUser(fixture.pool().getId(), "alice");
assertEquals("admin@example.com", updated.getAttributes().get("email"));
assertEquals("old@example.com", updated.getAttributes().get("email"));
assertEquals("admin@example.com", updated.getPendingAttributes().get("email"));
assertEquals("updated", updated.getAttributes().get("custom:note"));
assertFalse(updated.getPendingAttributes().containsKey("email"));
assertEquals("+12025550101", updated.getPendingAttributes().get("phone_number"));
verify(verificationCodeService, times(2)).invalidatePrevious(
verify(verificationCodeService).invalidatePrevious(
fixture.pool().getId(), "alice",
VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION);
verify(verificationCodeService, never()).invalidatePrevious(
@@ -2676,6 +2676,9 @@ class CognitoServiceTest {
VerificationCodeService verificationCodeService,
CognitoMessageDispatcher messageDispatcher) {
when(verificationCodeService.issue(any(), any(), any(), any())).thenReturn("123456");
when(verificationCodeService.issueTracked(any(), any(), any(), any()))
.thenReturn(new VerificationCodeService.IssuedCode("123456", "test-hash"));
when(verificationCodeService.hasUsableCode(any(), any(), any())).thenReturn(true);
CognitoService serviceWithVerification = new CognitoService(
new InMemoryStorage<>(),
new InMemoryStorage<>(),
@@ -68,7 +68,15 @@ class CognitoSignUpTriggerIntegrationTest {
Future<?> callback = null;
try {
JsonNode event = MAPPER.readTree((byte[]) invocation.getArgument(2));
assertEquals("CustomMessage_SignUp", event.path("triggerSource").asText());
if (!"CustomMessage_SignUp".equals(event.path("triggerSource").asText())) {
assertEquals("CustomMessage_UpdateUserAttribute",
event.path("triggerSource").asText());
assertEquals("CLIENT_ID_NOT_APPLICABLE",
event.path("callerContext").path("clientId").asText());
assertEquals("admin", event.path("request").path("clientMetadata")
.path("source").asText());
return response(Map.of());
}
assertEquals(username, event.path("userName").asText());
assertEquals(email, event.path("request").path("userAttributes").path("email").asText());
callback = callbackExecutor.submit(() -> {
@@ -77,7 +85,8 @@ class CognitoSignUpTriggerIntegrationTest {
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)))))
List.of(Map.of("Name", "email", "Value", changedEmail)),
"ClientMetadata", Map.of("source", "admin"))))
.then().statusCode(200);
return null;
});
@@ -104,7 +113,8 @@ class CognitoSignUpTriggerIntegrationTest {
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");
assertEquals(1, SesMailbox.messagesTo(changedEmail).size(),
"the admin update must send the new email its verification code");
assertTrue(signUp.path("UserConfirmed").asBoolean(),
"SignUp must report confirmation completed by its synchronous CustomMessage callback");
} finally {
@@ -40,6 +40,7 @@ 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.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.awaitility.Awaitility.await;
@@ -232,6 +233,171 @@ class CognitoSignUpTriggerReentrancyTest {
assertTrue(sns.getSentMessages().getFirst().getMessage().matches("Use code \\d{6}"));
}
@Test
void overlappingCustomMessageDoesNotBypassAdminContactVerification() throws Exception {
UserPool pool = service.createUserPool(Map.of(
"PoolName", "overlapping-admin-updates",
"AutoVerifiedAttributes", List.of("phone_number"),
"UserAttributeUpdateSettings", Map.of(
"AttributesRequireVerificationBeforeUpdate", List.of("phone_number")),
"LambdaConfig", Map.of("CustomMessage", FUNCTION)), "us-east-1");
service.adminCreateUser(pool.getId(), "alice", Map.of(
"phone_number", PHONE, "phone_number_verified", "true"), "TempPass1!", "SUPPRESS");
CountDownLatch firstMessageEntered = new CountDownLatch(1);
CountDownLatch releaseFirstMessage = new CountDownLatch(1);
AtomicInteger invocations = new AtomicInteger();
when(lambdaService.invoke(anyString(), eq(FUNCTION), any(byte[].class),
eq(InvocationType.RequestResponse))).thenAnswer(invocation -> {
if (invocations.incrementAndGet() == 1) {
firstMessageEntered.countDown();
assertTrue(releaseFirstMessage.await(5, TimeUnit.SECONDS));
}
return response(Map.of());
});
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
Future<?> first = executor.submit(() -> service.adminUpdateUserAttributes(
pool.getId(), "alice", Map.of("phone_number", "+12025550124")));
assertTrue(firstMessageEntered.await(5, TimeUnit.SECONDS));
service.adminUpdateUserAttributes(pool.getId(), "alice",
Map.of("phone_number", "+12025550125"));
CognitoUser updated = service.adminGetUser(pool.getId(), "alice");
assertEquals(PHONE, updated.getAttributes().get("phone_number"));
assertEquals("true", updated.getAttributes().get("phone_number_verified"));
assertEquals("+12025550125", updated.getPendingAttributes().get("phone_number"));
releaseFirstMessage.countDown();
first.get(5, TimeUnit.SECONDS);
} finally {
releaseFirstMessage.countDown();
executor.shutdownNow();
assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
}
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void customMessageCallbackDoesNotReissueAnUnchangedContact(boolean writesCurrentContact) throws Exception {
UserPool pool = service.createUserPool(Map.of(
"PoolName", "same-contact-callback",
"AutoVerifiedAttributes", List.of("phone_number"),
"UserAttributeUpdateSettings", Map.of(
"AttributesRequireVerificationBeforeUpdate", List.of("phone_number")),
"LambdaConfig", Map.of("CustomMessage", FUNCTION)), "us-east-1");
service.adminCreateUser(pool.getId(), "alice", Map.of(
"phone_number", PHONE, "phone_number_verified", "true"), "TempPass1!", "SUPPRESS");
String replacement = "+12025550124";
AtomicInteger invocations = new AtomicInteger();
when(lambdaService.invoke(anyString(), eq(FUNCTION), any(byte[].class),
eq(InvocationType.RequestResponse))).thenAnswer(invocation -> {
if (invocations.incrementAndGet() == 1) {
service.adminUpdateUserAttributes(pool.getId(), "alice",
Map.of("phone_number", writesCurrentContact ? PHONE : replacement));
}
return response(Map.of());
});
service.adminUpdateUserAttributes(pool.getId(), "alice", Map.of("phone_number", replacement));
assertEquals(1, invocations.get());
assertEquals(1, sns.getSentMessages().size());
assertEquals(replacement, service.adminGetUser(pool.getId(), "alice")
.getPendingAttributes().get("phone_number"));
}
@Test
void failedOlderSendDoesNotDeleteNewerAttributeCode() throws Exception {
SnsService selectiveSms = mock(SnsService.class);
AtomicReference<String> newerCode = new AtomicReference<>();
String firstPhone = "+12025550124";
String secondPhone = "+12025550125";
when(selectiveSms.publish(any(), any(), any(), any(), any(), any(), any()))
.thenAnswer(invocation -> {
if (firstPhone.equals(invocation.getArgument(2))) {
throw new IllegalStateException("first SMS unavailable");
}
newerCode.set(((String) invocation.getArgument(3)).replaceAll("\\D", ""));
return "sent";
});
service = serviceWithSns(selectiveSms);
UserPool pool = service.createUserPool(Map.of(
"PoolName", "overlapping-code-cleanup",
"AutoVerifiedAttributes", List.of("phone_number"),
"UserAttributeUpdateSettings", Map.of(
"AttributesRequireVerificationBeforeUpdate", List.of("phone_number")),
"LambdaConfig", Map.of("CustomMessage", FUNCTION)), "us-east-1");
service.adminCreateUser(pool.getId(), "alice", Map.of(
"phone_number", PHONE, "phone_number_verified", "true"), "TempPass1!", "SUPPRESS");
CountDownLatch firstMessageEntered = new CountDownLatch(1);
CountDownLatch releaseFirstMessage = new CountDownLatch(1);
AtomicInteger invocations = new AtomicInteger();
when(lambdaService.invoke(anyString(), eq(FUNCTION), any(byte[].class),
eq(InvocationType.RequestResponse))).thenAnswer(invocation -> {
if (invocations.incrementAndGet() == 1) {
firstMessageEntered.countDown();
assertTrue(releaseFirstMessage.await(5, TimeUnit.SECONDS));
}
return response(Map.of());
});
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
Future<?> first = executor.submit(() -> service.adminUpdateUserAttributes(
pool.getId(), "alice", Map.of("phone_number", firstPhone)));
assertTrue(firstMessageEntered.await(5, TimeUnit.SECONDS));
service.adminUpdateUserAttributes(pool.getId(), "alice", Map.of("phone_number", secondPhone));
assertNotNull(newerCode.get());
releaseFirstMessage.countDown();
ExecutionException failure = assertThrows(ExecutionException.class,
() -> first.get(5, TimeUnit.SECONDS));
assertEquals("CodeDeliveryFailureException", ((AwsException) failure.getCause()).getErrorCode());
codes.consume(pool.getId(), "alice", VerificationCode.Purpose.PHONE_ATTRIBUTE_VERIFICATION,
newerCode.get());
} finally {
releaseFirstMessage.countDown();
executor.shutdownNow();
assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
}
}
@Test
void failedAttributeDeliveryCanBeRetriedWithTheSameContact() {
SnsService selectiveSms = mock(SnsService.class);
AtomicInteger attempts = new AtomicInteger();
AtomicReference<String> deliveredCode = new AtomicReference<>();
when(selectiveSms.publish(any(), any(), any(), any(), any(), any(), any()))
.thenAnswer(invocation -> {
if (attempts.incrementAndGet() == 1) {
throw new IllegalStateException("SMS unavailable");
}
deliveredCode.set(((String) invocation.getArgument(3)).replaceAll("\\D", ""));
return "sent";
});
service = serviceWithSns(selectiveSms);
UserPool pool = service.createUserPool(Map.of(
"PoolName", "retry-attribute-code",
"AutoVerifiedAttributes", List.of("phone_number"),
"UserAttributeUpdateSettings", Map.of(
"AttributesRequireVerificationBeforeUpdate", List.of("phone_number"))), "us-east-1");
service.adminCreateUser(pool.getId(), "alice", Map.of(
"phone_number", PHONE, "phone_number_verified", "true"), "TempPass1!", "SUPPRESS");
String replacement = "+12025550124";
AwsException firstFailure = assertThrows(AwsException.class,
() -> service.adminUpdateUserAttributes(pool.getId(), "alice",
Map.of("phone_number", replacement)));
assertEquals("CodeDeliveryFailureException", firstFailure.getErrorCode());
service.adminUpdateUserAttributes(pool.getId(), "alice", Map.of("phone_number", replacement));
assertEquals(2, attempts.get());
assertNotNull(deliveredCode.get());
codes.consume(pool.getId(), "alice", VerificationCode.Purpose.PHONE_ATTRIBUTE_VERIFICATION,
deliveredCode.get());
}
@Test
void preSignUpRejectsSameUsernameAdminCreationWithoutBlockingTheTrigger() throws Exception {
UserPool pool = pool(Map.of("PreSignUp", FUNCTION));
@@ -291,6 +457,11 @@ class CognitoSignUpTriggerReentrancyTest {
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));
if (!"CustomMessage_SignUp".equals(event.path("triggerSource").asText())) {
assertEquals("CustomMessage_UpdateUserAttribute", event.path("triggerSource").asText());
return response(Map.of());
}
callback(() -> {
if (deletePhone) {
service.adminDeleteUserAttributes(pool.getId(), "alice", List.of("phone_number"));
@@ -305,8 +476,9 @@ class CognitoSignUpTriggerReentrancyTest {
CognitoUser result = service.signUp(client.getClientId(), "alice", "Perm1234!", Map.of("phone_number", PHONE), Map.of(), Map.of());
assertNull(callbackFailure.get());
assertEquals(1, sns.getSentMessages().size());
assertEquals(PHONE, sns.getSentMessages().getFirst().getPhoneNumber());
assertEquals(deletePhone ? 1 : 2, sns.getSentMessages().size());
assertEquals(1, sns.getSentMessages().stream()
.filter(message -> PHONE.equals(message.getPhoneNumber())).count());
assertEquals(Map.of("AttributeName", "phone_number", "DeliveryMedium", "SMS", "Destination", "+*******0123"),
service.signUpCodeDeliveryDetails(result));
}
@@ -177,6 +177,48 @@ class VerificationCodeServiceTest {
VerificationCode.Purpose.SIGNUP_CONFIRMATION, Duration.ofHours(24)));
}
@Test
void hasUsableCode_excludesWithdrawnAndExpiredCodes() {
VerificationCode.Purpose purpose = VerificationCode.Purpose.PHONE_ATTRIBUTE_VERIFICATION;
assertEquals(false, service.hasUsableCode("pool", "alice", purpose));
VerificationCodeService.IssuedCode issued = service.issueTracked(
"pool", "alice", purpose, Duration.ofMinutes(15));
assertTrue(service.hasUsableCode("pool", "alice", purpose));
service.invalidateIfCurrent("pool", "alice", purpose, issued);
assertEquals(false, service.hasUsableCode("pool", "alice", purpose));
service.issueTracked("pool", "alice", purpose, Duration.ofMinutes(15));
clock.advance(Duration.ofMinutes(16));
assertEquals(false, service.hasUsableCode("pool", "alice", purpose));
}
@Test
void invalidateIfCurrent_preservesNewerCode() {
VerificationCode.Purpose purpose = VerificationCode.Purpose.PHONE_ATTRIBUTE_VERIFICATION;
VerificationCodeService.IssuedCode first = service.issueTracked(
"pool", "alice", purpose, Duration.ofHours(24));
service.invalidatePrevious("pool", "alice", purpose);
VerificationCodeService.IssuedCode newer = service.issueTracked(
"pool", "alice", purpose, Duration.ofHours(24));
service.invalidateIfCurrent("pool", "alice", purpose, first);
assertDoesNotThrow(() -> service.consume("pool", "alice", purpose, newer.code()));
}
@Test
void invalidateIfCurrent_withdrawsMatchingCode() {
VerificationCode.Purpose purpose = VerificationCode.Purpose.PHONE_ATTRIBUTE_VERIFICATION;
VerificationCodeService.IssuedCode issued = service.issueTracked(
"pool", "alice", purpose, Duration.ofHours(24));
service.invalidateIfCurrent("pool", "alice", purpose, issued);
VerificationCodeException failure = assertThrows(VerificationCodeException.class,
() -> service.consume("pool", "alice", purpose, issued.code()));
assertEquals(VerificationCodeException.Kind.NOT_FOUND, failure.getKind());
}
@Test
void issue_twiceWithin30s_throwsRateLimit() {
service.issue("pool", "alice",