Set/remove account recovery passwords alongside phone number recovery passwords

This commit is contained in:
Jon Chambers authored and Jon Chambers committed 2026-08-05 14:50:00 -04:00
1 parent c64aeec36a
commit 453222ba17
13 files changed
+141 -54

No files matched your search

@@ -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<Byte> deviceIds = updatedAccount.getDevices().stream().map(Device::getId).toList();
@@ -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<TransactWriteItem> 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
@@ -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());
}
@@ -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<TransactWriteItem> 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();
}
@@ -334,6 +334,8 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> 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<String, String> implemen
}
private void delete(final Account account) {
final List<TransactWriteItem> additionalWriteItems = account.getDevices().stream()
final List<TransactWriteItem> 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<String, String> implemen
profilesManager.deleteAll(account.getAccountIdentifier(), true))
.join();
phoneNumberRecoveryPasswordsManager.remove(account.getIdentifier(IdentityType.PNI));
accounts.delete(account.getAccountIdentifier(), additionalWriteItems);
redisDelete(account);
@@ -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();
@@ -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);
}
@@ -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());
}
@@ -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);
}
}
@@ -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<AccountsGrpcService, AccountsGrpc.AccountsBlockingStub> {
@@ -171,9 +172,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
final Account account = mock(Account.class);
when(account.getAccountIdentifier()).thenReturn(AUTHENTICATED_ACI);
when(account.getPhoneNumberIdentifier()).thenReturn(phoneNumberIdentifier);
when(account.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(phoneNumberIdentifier));
when(account.getNumber()).thenReturn(e164);
when(account.getNumberOptional()).thenReturn(Optional.of(e164));
when(account.getUsernameHash()).thenReturn(Optional.of(usernameHash));
when(account.getUsernameLinkHandle()).thenReturn(usernameLinkHandle);
@@ -286,7 +285,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
@Test
void reserveUsernameHash() throws UsernameHashNotAvailableException {
final Account account = mock(Account.class);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(AUTHENTICATED_ACI);
when(account.getAccountIdentifier()).thenReturn(AUTHENTICATED_ACI);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
@@ -547,7 +546,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
void setUsernameLink(final boolean keepLink) {
final Account account = mock(Account.class);
final UUID oldHandle = UUID.randomUUID();
when(account.getIdentifier(IdentityType.ACI)).thenReturn(AUTHENTICATED_ACI);
when(account.getAccountIdentifier()).thenReturn(AUTHENTICATED_ACI);
when(account.getUsernameHash()).thenReturn(Optional.of(new byte[AccountController.USERNAME_HASH_LENGTH]));
when(account.getUsernameLinkHandle()).thenReturn(oldHandle);
@@ -717,19 +716,24 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
final UUID phoneNumberIdentifier = UUID.randomUUID();
final Account account = mock(Account.class);
when(account.getIdentifier(IdentityType.PNI)).thenReturn(phoneNumberIdentifier);
when(account.getAccountIdentifier()).thenReturn(AUTHENTICATED_ACI);
when(account.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(phoneNumberIdentifier));
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
final byte[] registrationRecoveryPassword = TestRandomUtil.nextBytes(32);
when(phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForStorePassword(phoneNumberIdentifier, registrationRecoveryPassword))
.thenReturn(TransactWriteItem.builder().build());
assertDoesNotThrow(() ->
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<AccountsGrpcService, Ac
@ParameterizedTest
@ValueSource(booleans = {true, false})
void setZkCredentialKey(final boolean matchesCurrentZkCredentialKey) throws Exception {
void setZkCredentialKey(final boolean matchesCurrentZkCredentialKey) {
final ZkCredentialPublicKey publicKey = ZkCredentialKeyPair.generate().getPublicKey();
final long rotationId = ThreadLocalRandom.current().nextLong(1, Long.MAX_VALUE);
@@ -849,9 +853,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
final Account updatedAccount = mock(Account.class);
when(updatedAccount.getAccountIdentifier()).thenReturn(AUTHENTICATED_ACI);
when(updatedAccount.getNumber()).thenReturn(newNumber);
when(updatedAccount.getNumberOptional()).thenReturn(Optional.of(newNumber));
when(updatedAccount.getPhoneNumberIdentifier()).thenReturn(updatedPni);
when(updatedAccount.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(updatedPni));
when(updatedAccount.getUsernameHash()).thenReturn(Optional.empty());
@@ -51,6 +51,7 @@ import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient;
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
public class AccountCreationDeletionIntegrationTest {
@@ -67,7 +68,8 @@ public class AccountCreationDeletionIntegrationTest {
DynamoDbExtensionSchema.Tables.EC_KEYS,
DynamoDbExtensionSchema.Tables.PAGED_PQ_KEYS,
DynamoDbExtensionSchema.Tables.REPEATED_USE_EC_SIGNED_PRE_KEYS,
DynamoDbExtensionSchema.Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS);
DynamoDbExtensionSchema.Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS,
DynamoDbExtensionSchema.Tables.REGISTRATION_RECOVERY_PASSWORDS);
@RegisterExtension
static final RedisClusterExtension CACHE_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
@@ -81,6 +83,7 @@ public class AccountCreationDeletionIntegrationTest {
private AccountsManager accountsManager;
private KeysManager keysManager;
private PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager;
private DisconnectionRequestManager disconnectionRequestManager;
record DeliveryChannels(boolean fetchesMessages, String apnsToken, String fcmToken) {}
@@ -131,8 +134,13 @@ public class AccountCreationDeletionIntegrationTest {
final ProfilesManager profilesManager = mock(ProfilesManager.class);
when(profilesManager.deleteAll(any(), anyBoolean())).thenReturn(CompletableFuture.completedFuture(null));
final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager =
mock(PhoneNumberRecoveryPasswordsManager.class);
final PhoneNumberRecoveryPasswords phoneNumberRecoveryPasswords =
new PhoneNumberRecoveryPasswords(DynamoDbExtensionSchema.Tables.REGISTRATION_RECOVERY_PASSWORDS.tableName(),
Duration.ofDays(1),
DYNAMO_DB_EXTENSION.getDynamoDbClient(),
CLOCK);
phoneNumberRecoveryPasswordsManager = new PhoneNumberRecoveryPasswordsManager(phoneNumberRecoveryPasswords);
disconnectionRequestManager = mock(DisconnectionRequestManager.class);
when(disconnectionRequestManager.requestDisconnection(any())).thenReturn(CompletableFuture.completedFuture(null));
@@ -423,6 +431,8 @@ public class AccountCreationDeletionIntegrationTest {
true,
deviceCapabilities);
accountAttributes.setRecoveryPassword(TestRandomUtil.nextBytes(16));
final List<AccountBadge> 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))));
@@ -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,
@@ -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);