From 453222ba171a007acae43d08c92e07b78332c037 Mon Sep 17 00:00:00 2001 From: Jon Chambers Date: Mon, 3 Aug 2026 15:24:15 -0400 Subject: [PATCH] Set/remove account recovery passwords alongside phone number recovery passwords --- .../RegistrationLockVerificationManager.java | 4 +- .../controllers/AccountController.java | 37 ++++++++----------- .../controllers/VerificationController.java | 6 +++ .../grpc/AccountsGrpcService.java | 18 +++++++-- .../storage/AccountsManager.java | 13 +++++-- .../storage/PhoneNumberRecoveryPasswords.java | 31 ++++++++++++++-- .../PhoneNumberRecoveryPasswordsManager.java | 9 +++++ ...gistrationLockVerificationManagerTest.java | 5 +-- .../controllers/AccountControllerTest.java | 8 +++- .../grpc/AccountsGrpcServiceTest.java | 22 ++++++----- ...ccountCreationDeletionIntegrationTest.java | 20 ++++++++-- ...ntsManagerChangeNumberIntegrationTest.java | 12 +++++- .../tests/util/AccountsHelper.java | 10 +++++ 13 files changed, 141 insertions(+), 54 deletions(-) diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/auth/RegistrationLockVerificationManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/auth/RegistrationLockVerificationManager.java index 5920c5ac2..1755f6914 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/auth/RegistrationLockVerificationManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/auth/RegistrationLockVerificationManager.java @@ -20,7 +20,6 @@ import org.apache.commons.lang3.StringUtils; import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException; import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest; import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure; -import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.limits.RateLimiters; import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil; import org.whispersystems.textsecuregcm.push.NotPushRegisteredException; @@ -152,7 +151,8 @@ public class RegistrationLockVerificationManager { // This allows users to re-register via registration recovery password // instead of always being forced to fall back to SMS verification. if (!phoneVerificationType.equals(PhoneVerificationRequest.VerificationType.RECOVERY_PASSWORD) || clientRegistrationLock != null) { - phoneNumberRecoveryPasswordsManager.remove(updatedAccount.getIdentifier(IdentityType.PNI)); + phoneNumberRecoveryPasswordsManager.remove(updatedAccount.getPhoneNumberIdentifierOptional() + .orElseThrow(() -> new AssertionError("Account with a phone number did not have a phone number identifier"))); } final List deviceIds = updatedAccount.getDevices().stream().map(Device::getId).toList(); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/AccountController.java b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/AccountController.java index 31a3792e3..44262d393 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/AccountController.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/AccountController.java @@ -4,12 +4,7 @@ */ package org.whispersystems.textsecuregcm.controllers; -import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name; - import io.dropwizard.auth.Auth; -import io.micrometer.core.instrument.Metrics; -import io.micrometer.core.instrument.Tag; -import io.micrometer.core.instrument.Tags; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Schema; @@ -30,11 +25,13 @@ import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; import jakarta.ws.rs.QueryParam; import jakarta.ws.rs.WebApplicationException; -import jakarta.ws.rs.core.HttpHeaders; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.Response.Status; import java.util.Base64; +import java.util.Collection; +import java.util.Collections; +import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.UUID; @@ -62,7 +59,6 @@ import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.identity.ServiceIdentifier; import org.whispersystems.textsecuregcm.limits.RateLimitedByIp; import org.whispersystems.textsecuregcm.limits.RateLimiters; -import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil; import org.whispersystems.textsecuregcm.storage.Account; import org.whispersystems.textsecuregcm.storage.AccountsManager; import org.whispersystems.textsecuregcm.storage.Device; @@ -72,6 +68,7 @@ import org.whispersystems.textsecuregcm.storage.UsernameReservationNotFoundExcep import org.whispersystems.textsecuregcm.util.HeaderUtils; import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier; import org.whispersystems.textsecuregcm.util.Util; +import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem; @SuppressWarnings("OptionalUsedAsFieldOrParameterType") @Path("/v1/accounts") @@ -81,10 +78,6 @@ public class AccountController { public static final int USERNAME_HASH_LENGTH = 32; public static final int MAXIMUM_USERNAME_CIPHERTEXT_LENGTH = 128; - private static final String RECOVERY_PASSWORD_SET_COUNTER_NAME = - name(AccountController.class, "recoveryPasswordSet"); - - private final AccountsManager accounts; private final RateLimiters rateLimiters; private final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager; @@ -224,10 +217,18 @@ public class AccountController { @Produces(MediaType.APPLICATION_JSON) public void setAccountAttributes( @Auth AuthenticatedDevice auth, - @HeaderParam(HttpHeaders.USER_AGENT) String userAgent, @HeaderParam(HeaderUtils.X_SIGNAL_AGENT) String signalAgent, @NotNull @Valid AccountAttributes attributes) { + final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier()) + .orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED)); + + final Collection additionalWriteItems = + account.getPhoneNumberIdentifierOptional() + .flatMap(phoneNumberIdentifier -> attributes.recoveryPassword().map(recoveryPassword -> + List.of(phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForStorePassword(phoneNumberIdentifier, recoveryPassword)))) + .orElseGet(Collections::emptyList); + final Account updatedAccount = accounts.update(auth.accountIdentifier(), a -> { a.getDevice(auth.deviceId()).ifPresent(d -> { d.setFetchesMessages(attributes.getFetchesMessages()); @@ -243,17 +244,9 @@ public class AccountController { a.setUnidentifiedAccessKey(attributes.getUnidentifiedAccessKey()); a.setUnrestrictedUnidentifiedAccess(attributes.isUnrestrictedUnidentifiedAccess()); a.setDiscoverableByPhoneNumber(attributes.isDiscoverableByPhoneNumber()); - }); - // if registration recovery password was sent to us, store it (or refresh its expiration) - attributes.recoveryPassword().ifPresent(registrationRecoveryPassword -> { - final boolean rrpCreated = phoneNumberRecoveryPasswordsManager - .store(updatedAccount.getIdentifier(IdentityType.PNI), registrationRecoveryPassword); - Metrics.counter(RECOVERY_PASSWORD_SET_COUNTER_NAME, Tags.of( - UserAgentTagUtil.getPlatformTag(userAgent), - Tag.of("outcome", rrpCreated ? "created" : "updated"))) - .increment(); - }); + attributes.recoveryPassword().ifPresent(a::setAccountRecoveryPassword); + }, additionalWriteItems); } @GET diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/VerificationController.java b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/VerificationController.java index 100b496f5..6796ed45b 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/VerificationController.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/VerificationController.java @@ -749,6 +749,9 @@ public class VerificationController { // the RRP. It's possible the client will not actually be able to register (e.g. failed reglock challenge), and // so we will have removed the RRP unnecessarily. The impact of this is low, since the owner of the RRP // can always just fallback to session-based verification. + // + // Note that we do not remove the recovery password from the account itself because re-creation is imminent, and + // that process will overwrite the recovery password (along with the rest of the account record). existingRRP = phoneNumberRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join()); } @@ -824,6 +827,9 @@ public class VerificationController { // the RRP. It's possible the client will not actually be able to register (e.g. failed reglock challenge), and // so we will have removed the RRP unnecessarily. The impact of this is low, since the owner of the RRP // can always just fallback to session-based verification. + // + // Note that we do not remove the recovery password from the account itself because re-creation is imminent, and + // that process will overwrite the recovery password (along with the rest of the account record). phoneNumberRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join()); } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/AccountsGrpcService.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/AccountsGrpcService.java index ca5848c20..41f0a5693 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/AccountsGrpcService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/AccountsGrpcService.java @@ -12,6 +12,8 @@ import java.security.SecureRandom; import java.time.Clock; import java.time.Instant; import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.HexFormat; import java.util.List; import java.util.Map; @@ -83,7 +85,6 @@ import org.whispersystems.textsecuregcm.entities.IncomingMessage; import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey; import org.whispersystems.textsecuregcm.entities.MessageProtos; import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; -import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier; import org.whispersystems.textsecuregcm.limits.RateLimiters; import org.whispersystems.textsecuregcm.push.MessageTooLargeException; @@ -98,6 +99,7 @@ import org.whispersystems.textsecuregcm.util.RegistrationIdValidator; import org.whispersystems.textsecuregcm.util.SystemMapper; import org.whispersystems.textsecuregcm.util.UUIDUtil; import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier; +import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem; public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase { @@ -277,7 +279,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase { ? account.getUsernameLinkHandle() : UUID.randomUUID(); - accountsManager.update(account.getIdentifier(IdentityType.ACI), + accountsManager.update(account.getAccountIdentifier(), a -> a.setUsernameLinkDetails(linkHandle, request.getUsernameCiphertext().toByteArray())); return responseBuilder.setUsernameLinkHandle(UUIDUtil.toByteString(linkHandle)).build(); @@ -321,8 +323,16 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase { @Override public SetRegistrationRecoveryPasswordResponse setRegistrationRecoveryPassword(final SetRegistrationRecoveryPasswordRequest request) { - phoneNumberRecoveryPasswordsManager.store(getAuthenticatedAccount().getIdentifier(IdentityType.PNI), - request.getRegistrationRecoveryPassword().toByteArray()); + final Account account = getAuthenticatedAccount(); + final byte[] recoveryPassword = request.getRegistrationRecoveryPassword().toByteArray(); + + final Collection additionalWriteItems = account.getPhoneNumberIdentifierOptional() + .map(phoneNumberIdentifier -> + List.of(phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForStorePassword(phoneNumberIdentifier, recoveryPassword))) + .orElseGet(Collections::emptyList); + + // TODO Once we retire `AccountController`, replace this with a new `AccountsManager#setRecoveryPassword` method + accountsManager.update(account.getAccountIdentifier(), a -> a.setAccountRecoveryPassword(recoveryPassword), additionalWriteItems); return SetRegistrationRecoveryPasswordResponse.getDefaultInstance(); } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountsManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountsManager.java index 4e8e4201b..a08087a95 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountsManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountsManager.java @@ -334,6 +334,8 @@ public class AccountsManager extends RedisPubSubAdapter implemen account.setDiscoverableByPhoneNumber(accountAttributes.isDiscoverableByPhoneNumber()); account.setBadges(clock, accountBadges); + accountAttributes.recoveryPassword().ifPresent(account::setAccountRecoveryPassword); + String accountCreationType = maybeRecentlyDeletedAccountIdentifier.isPresent() ? "recently-deleted" : "new"; final String pushTokenType; @@ -1227,13 +1229,18 @@ public class AccountsManager extends RedisPubSubAdapter implemen } private void delete(final Account account) { - final List additionalWriteItems = account.getDevices().stream() + final List additionalWriteItems = new ArrayList<>(); + + account.getDevices().stream() .flatMap(device -> keysManager.buildWriteItemsForRemovedDevice( account.getIdentifier(IdentityType.ACI), account.getIdentifier(IdentityType.PNI), device.getId()) .stream()) - .toList(); + .forEach(additionalWriteItems::add); + + account.getPhoneNumberIdentifierOptional().ifPresent(phoneNumberIdentifier -> + additionalWriteItems.add(phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForRemovePassword(phoneNumberIdentifier))); CompletableFuture.allOf( secureStorageClient.deleteStoredData(account.getAccountIdentifier()), @@ -1244,8 +1251,6 @@ public class AccountsManager extends RedisPubSubAdapter implemen profilesManager.deleteAll(account.getAccountIdentifier(), true)) .join(); - phoneNumberRecoveryPasswordsManager.remove(account.getIdentifier(IdentityType.PNI)); - accounts.delete(account.getAccountIdentifier(), additionalWriteItems); redisDelete(account); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/PhoneNumberRecoveryPasswords.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/PhoneNumberRecoveryPasswords.java index 114d93fee..58eaf57a9 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/PhoneNumberRecoveryPasswords.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/PhoneNumberRecoveryPasswords.java @@ -17,13 +17,16 @@ import org.whispersystems.textsecuregcm.auth.SaltedTokenHash; import org.whispersystems.textsecuregcm.util.AttributeValues; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; +import software.amazon.awssdk.services.dynamodb.model.Delete; import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest; import software.amazon.awssdk.services.dynamodb.model.DeleteItemResponse; import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; +import software.amazon.awssdk.services.dynamodb.model.Put; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; import software.amazon.awssdk.services.dynamodb.model.PutItemResponse; import software.amazon.awssdk.services.dynamodb.model.ReturnValue; +import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem; public class PhoneNumberRecoveryPasswords { @@ -71,14 +74,12 @@ public class PhoneNumberRecoveryPasswords { /// @param data The salted registration recovery password /// @return true if a new mapping was added, false if an existing mapping was updated public boolean addOrReplace(final UUID phoneNumberIdentifier, final SaltedTokenHash data) { - final long expirationSeconds = expirationSeconds(); - final PutItemResponse response = dynamoDbClient.putItem(PutItemRequest.builder() .tableName(tableName) .returnValues(ReturnValue.ALL_OLD) .item(Map.of( KEY_PNI, AttributeValues.fromString(phoneNumberIdentifier.toString()), - ATTR_EXP, AttributeValues.fromLong(expirationSeconds), + ATTR_EXP, AttributeValues.fromLong(expirationSeconds()), ATTR_SALT, AttributeValues.fromString(data.salt()), ATTR_HASH, AttributeValues.fromString(data.hash()))) .build()); @@ -86,6 +87,21 @@ public class PhoneNumberRecoveryPasswords { return response.attributes() == null || response.attributes().isEmpty(); } + TransactWriteItem buildWriteItemForAddOrReplace(final UUID phoneNumberIdentifier, final SaltedTokenHash data) { + final long expirationSeconds = expirationSeconds(); + + return TransactWriteItem.builder() + .put(Put.builder() + .tableName(tableName) + .item(Map.of( + KEY_PNI, AttributeValues.fromString(phoneNumberIdentifier.toString()), + ATTR_EXP, AttributeValues.fromLong(expirationSeconds), + ATTR_SALT, AttributeValues.fromString(data.salt()), + ATTR_HASH, AttributeValues.fromString(data.hash()))) + .build()) + .build(); + } + /// Remove the entry associated with the provided PNI /// /// @return true if an entry was removed, false if no entry existed @@ -99,6 +115,15 @@ public class PhoneNumberRecoveryPasswords { return response.attributes() != null && !response.attributes().isEmpty(); } + TransactWriteItem buildWriteItemForRemove(final UUID phoneNumberIdentifier) { + return TransactWriteItem.builder() + .delete(Delete.builder() + .tableName(tableName) + .key(Map.of(KEY_PNI, AttributeValues.fromString(phoneNumberIdentifier.toString()))) + .build()) + .build(); + } + @VisibleForTesting long expirationSeconds() { return clock.instant().plus(expiration).getEpochSecond(); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/PhoneNumberRecoveryPasswordsManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/PhoneNumberRecoveryPasswordsManager.java index 16a10ed68..abc7c7c5c 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/PhoneNumberRecoveryPasswordsManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/PhoneNumberRecoveryPasswordsManager.java @@ -10,6 +10,7 @@ import static java.util.Objects.requireNonNull; import java.util.HexFormat; import java.util.UUID; import org.whispersystems.textsecuregcm.auth.SaltedTokenHash; +import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem; public class PhoneNumberRecoveryPasswordsManager { @@ -31,10 +32,18 @@ public class PhoneNumberRecoveryPasswordsManager { return phoneNumberRecoveryPasswords.addOrReplace(phoneNumberIdentifier, tokenHash); } + public TransactWriteItem buildTransactWriteItemForStorePassword(final UUID phoneNumberIdentifier, final byte[] password) { + return phoneNumberRecoveryPasswords.buildWriteItemForAddOrReplace(phoneNumberIdentifier, SaltedTokenHash.generateFor(bytesToString(password))); + } + public boolean remove(final UUID phoneNumberIdentifier) { return phoneNumberRecoveryPasswords.removeEntry(phoneNumberIdentifier); } + public TransactWriteItem buildTransactWriteItemForRemovePassword(final UUID phoneNumberIdentifier) { + return phoneNumberRecoveryPasswords.buildWriteItemForRemove(phoneNumberIdentifier); + } + private static String bytesToString(final byte[] bytes) { return HexFormat.of().formatHex(bytes); } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/auth/RegistrationLockVerificationManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/auth/RegistrationLockVerificationManagerTest.java index 85ed68537..5de41dc76 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/auth/RegistrationLockVerificationManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/auth/RegistrationLockVerificationManagerTest.java @@ -31,7 +31,6 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException; import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest; -import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.limits.RateLimiter; import org.whispersystems.textsecuregcm.limits.RateLimiters; import org.whispersystems.textsecuregcm.push.NotPushRegisteredException; @@ -77,8 +76,8 @@ class RegistrationLockVerificationManagerTest { account = mock(Account.class); final UUID accountIdentifier = UUID.randomUUID(); when(account.getAccountIdentifier()).thenReturn(accountIdentifier); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier); when(account.getNumberOptional()).thenReturn(Optional.of("+18005551212")); + when(account.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(UUID.randomUUID())); when(account.getDevices()).thenReturn(List.of(device)); AccountsHelper.setupMockGet(accountsManager, account); @@ -104,7 +103,7 @@ class RegistrationLockVerificationManagerTest { yield new Pair<>(RegistrationLockFailureException.class, e -> { if (e instanceof RegistrationLockFailureException) { if (!verificationType.equals(PhoneVerificationRequest.VerificationType.RECOVERY_PASSWORD) || clientRegistrationLock != null) { - verify(phoneNumberRecoveryPasswordsManager).remove(account.getIdentifier(IdentityType.PNI)); + verify(phoneNumberRecoveryPasswordsManager).remove(account.getPhoneNumberIdentifierOptional().orElseThrow()); } else { verify(phoneNumberRecoveryPasswordsManager, never()).remove(any()); } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AccountControllerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AccountControllerTest.java index a16e2fc2a..f5f015d52 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AccountControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AccountControllerTest.java @@ -12,6 +12,7 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyByte; import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; @@ -98,6 +99,7 @@ import org.whispersystems.textsecuregcm.util.SystemMapper; import org.whispersystems.textsecuregcm.util.TestRandomUtil; import org.whispersystems.textsecuregcm.util.TestRemoteAddressFilterProvider; import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier; +import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem; @ExtendWith(DropwizardExtensionsSupport.class) class AccountControllerTest { @@ -227,6 +229,9 @@ class AccountControllerTest { return null; }).when(usernameZkProofVerifier).verifyProof(any(), any()); + + when(PHONE_NUMBER_RECOVERY_PASSWORDS_MANAGER.buildTransactWriteItemForStorePassword(any(), any())) + .thenReturn(TransactWriteItem.builder().build()); } @AfterEach @@ -856,7 +861,8 @@ class AccountControllerTest { .setRecoveryPassword(recoveryPassword)))) { assertThat(response.getStatus()).isEqualTo(204); - verify(PHONE_NUMBER_RECOVERY_PASSWORDS_MANAGER).store(AuthHelper.UNDISCOVERABLE_PNI, recoveryPassword); + verify(accountsManager).update(eq(AuthHelper.UNDISCOVERABLE_UUID), any(), argThat(additionWriteItems -> additionWriteItems.size() == 1)); + verify(AuthHelper.UNDISCOVERABLE_ACCOUNT).setAccountRecoveryPassword(recoveryPassword); } } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/AccountsGrpcServiceTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/AccountsGrpcServiceTest.java index 5d85c3828..cca3233b6 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/AccountsGrpcServiceTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/AccountsGrpcServiceTest.java @@ -10,6 +10,7 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; @@ -99,7 +100,6 @@ import org.whispersystems.textsecuregcm.entities.ECSignedPreKey; import org.whispersystems.textsecuregcm.entities.EncryptedUsername; import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey; import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; -import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier; import org.whispersystems.textsecuregcm.limits.RateLimiter; import org.whispersystems.textsecuregcm.limits.RateLimiters; @@ -121,6 +121,7 @@ import org.whispersystems.textsecuregcm.util.TestClock; import org.whispersystems.textsecuregcm.util.TestRandomUtil; import org.whispersystems.textsecuregcm.util.UUIDUtil; import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier; +import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem; class AccountsGrpcServiceTest extends SimpleBaseGrpcTest { @@ -171,9 +172,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest authenticatedServiceStub().setRegistrationRecoveryPassword(SetRegistrationRecoveryPasswordRequest.newBuilder() .setRegistrationRecoveryPassword(ByteString.copyFrom(registrationRecoveryPassword)) .build())); - verify(phoneNumberRecoveryPasswordsManager).store(account.getIdentifier(IdentityType.PNI), registrationRecoveryPassword); + verify(account).setAccountRecoveryPassword(registrationRecoveryPassword); + verify(accountsManager).update(eq(AUTHENTICATED_ACI), any(), argThat(additionalWriteItems -> additionalWriteItems.size() == 1)); } @Test @@ -741,7 +745,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest badges = new ArrayList<>(List.of(new AccountBadge( RandomStringUtils.secure().nextAlphabetic(8), CLOCK.instant().plus(Duration.ofDays(7)), @@ -460,6 +470,8 @@ public class AccountCreationDeletionIntegrationTest { final UUID aci = account.getIdentifier(IdentityType.ACI); assertTrue(accountsManager.getByAccountIdentifier(aci).isPresent()); + assertTrue(phoneNumberRecoveryPasswordsManager.verify(account.getPhoneNumberIdentifierOptional().orElseThrow(), + accountAttributes.recoveryPassword().orElseThrow())); accountsManager.delete(account.getIdentifier(IdentityType.ACI), AccountsManager.DeletionReason.ADMIN_DELETED); @@ -468,6 +480,8 @@ public class AccountCreationDeletionIntegrationTest { assertFalse(keysManager.getEcSignedPreKey(account.getPhoneNumberIdentifier(), Device.PRIMARY_ID).join().isPresent()); assertFalse(keysManager.getLastResort(account.getAccountIdentifier(), Device.PRIMARY_ID).join().isPresent()); assertFalse(keysManager.getLastResort(account.getPhoneNumberIdentifier(), Device.PRIMARY_ID).join().isPresent()); + assertFalse(phoneNumberRecoveryPasswordsManager.verify(account.getPhoneNumberIdentifierOptional().orElseThrow(), + accountAttributes.recoveryPassword().orElseThrow())); verify(disconnectionRequestManager).requestDisconnection(argThat(disconnectedAccount -> disconnectedAccount.getIdentifier(IdentityType.ACI).equals(account.getIdentifier(IdentityType.ACI)))); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerChangeNumberIntegrationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerChangeNumberIntegrationTest.java index cf398ff44..d69a09532 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerChangeNumberIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerChangeNumberIntegrationTest.java @@ -17,6 +17,7 @@ import static org.mockito.Mockito.when; import java.nio.charset.StandardCharsets; import java.time.Clock; +import java.time.Duration; import java.util.Map; import java.util.Optional; import java.util.Set; @@ -60,7 +61,8 @@ class AccountsManagerChangeNumberIntegrationTest { Tables.EC_KEYS, Tables.PAGED_PQ_KEYS, Tables.REPEATED_USE_EC_SIGNED_PRE_KEYS, - Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS); + Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS, + Tables.REGISTRATION_RECOVERY_PASSWORDS); @RegisterExtension static final RedisClusterExtension CACHE_CLUSTER_EXTENSION = RedisClusterExtension.builder().build(); @@ -123,8 +125,14 @@ class AccountsManagerChangeNumberIntegrationTest { final ProfilesManager profilesManager = mock(ProfilesManager.class); when(profilesManager.deleteAll(any(), anyBoolean())).thenReturn(CompletableFuture.completedFuture(null)); + final PhoneNumberRecoveryPasswords phoneNumberRecoveryPasswords = + new PhoneNumberRecoveryPasswords(DynamoDbExtensionSchema.Tables.REGISTRATION_RECOVERY_PASSWORDS.tableName(), + Duration.ofDays(1), + DYNAMO_DB_EXTENSION.getDynamoDbClient(), + Clock.systemUTC()); + final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager = - mock(PhoneNumberRecoveryPasswordsManager.class); + new PhoneNumberRecoveryPasswordsManager(phoneNumberRecoveryPasswords); accountsManager = new AccountsManager( accounts, diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/tests/util/AccountsHelper.java b/service/src/test/java/org/whispersystems/textsecuregcm/tests/util/AccountsHelper.java index 317279b32..0dbe96872 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/tests/util/AccountsHelper.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/tests/util/AccountsHelper.java @@ -130,6 +130,15 @@ public class AccountsHelper { return account; }); + when(mockAccountsManager.update(any(UUID.class), any(), any())).thenAnswer(invocation -> { + final UUID accountIdentifier = invocation.getArgument(0, UUID.class); + final Account account = mockAccountsManager.getByAccountIdentifier(accountIdentifier).orElseThrow(); + + invocation.getArgument(1, Consumer.class).accept(account); + + return account; + }); + when(mockAccountsManager.update(any(Account.class), any())).thenAnswer(invocation -> { final Account account = invocation.getArgument(0); @@ -220,6 +229,7 @@ public class AccountsHelper { for (Stubbing stubbing : mockingDetails.getStubbings()) { switch (stubbing.getInvocation().getMethod().getName()) { case "getAccountIdentifier" -> when(updatedAccount.getAccountIdentifier()).thenAnswer(stubbing); + case "getPhoneNumberIdentifierOptional" -> when(updatedAccount.getPhoneNumberIdentifierOptional()).thenAnswer(stubbing); case "getPhoneNumberIdentifier" -> when(updatedAccount.getPhoneNumberIdentifier()).thenAnswer(stubbing); case "getIdentifier" -> when(updatedAccount.getIdentifier(stubbing.getInvocation().getArgument(0))).thenAnswer(stubbing); case "isIdentifiedBy" -> when(updatedAccount.isIdentifiedBy(stubbing.getInvocation().getArgument(0))).thenAnswer(stubbing);