mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
9c8d2ba58d
commit
b90b671c21
13 files changed
+607
-85
No files matched your search
+109
@@ -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());
|
||||
}
|
||||
}
|
||||
+21
-16
@@ -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();
|
||||
|
||||
+82
-9
@@ -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
|
||||
|
||||
+15
-6
@@ -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<>(),
|
||||
|
||||
+13
-3
@@ -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 {
|
||||
|
||||
+174
-2
@@ -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));
|
||||
}
|
||||
|
||||
+42
@@ -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",
|
||||
|
||||
Reference in new issue
Block a user