From 2dd46b3b85f276940390c4a0f6fafbc3044aeb70 Mon Sep 17 00:00:00 2001 From: Jon Chambers Date: Tue, 4 Aug 2026 16:51:59 -0400 Subject: [PATCH] Add temporary plumbing and a command to migrate account recovery passwords --- .../textsecuregcm/WhisperServerService.java | 3 + .../textsecuregcm/storage/Account.java | 11 +- .../storage/AccountsManager.java | 29 +++ .../storage/PhoneNumberRecoveryPasswords.java | 18 ++ .../PhoneNumberRecoveryPasswordsManager.java | 9 + ...pulateAccountRecoveryPasswordsCommand.java | 81 ++++++++ ...igrateRecoveryPasswordIntegrationTest.java | 174 ++++++++++++++++++ .../PhoneNumberRecoveryPasswordsTest.java | 76 ++++++++ 8 files changed, 397 insertions(+), 4 deletions(-) create mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/workers/PopulateAccountRecoveryPasswordsCommand.java create mode 100644 service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerMigrateRecoveryPasswordIntegrationTest.java create mode 100644 service/src/test/java/org/whispersystems/textsecuregcm/storage/PhoneNumberRecoveryPasswordsTest.java diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java index 3d65c9d4e..60615e0f2 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java @@ -329,6 +329,7 @@ import org.whispersystems.textsecuregcm.workers.DeleteUserCommand; import org.whispersystems.textsecuregcm.workers.IdleDeviceNotificationSchedulerFactory; import org.whispersystems.textsecuregcm.workers.MessagePersisterServiceCommand; import org.whispersystems.textsecuregcm.workers.NotifyIdleDevicesCommand; +import org.whispersystems.textsecuregcm.workers.PopulateAccountRecoveryPasswordsCommand; import org.whispersystems.textsecuregcm.workers.ProcessScheduledJobsServiceCommand; import org.whispersystems.textsecuregcm.workers.RegenerateSecondaryDynamoDbTableDataCommand; import org.whispersystems.textsecuregcm.workers.RemoveExpiredAccountsCommand; @@ -408,6 +409,8 @@ public class WhisperServerService extends Application implemen throw new AssertionError("Every implementation of the Java platform is required to support the SHA-256 MessageDigest algorithm", e); } } + + public void migrateAccountRecoveryPassword(final Account account) { + accountLockManager.withSingleAccountLock(account, () -> { + migrateAccountRecoveryPassword(account.getAccountIdentifier(), MAX_UPDATE_ATTEMPTS); + return null; + }, accountLockExecutor); + } + + private void migrateAccountRecoveryPassword(final UUID accountIdentifier, final int retries) { + try { + final Account account = accounts.getByAccountIdentifier(accountIdentifier) + .orElseThrow(ContestedOptimisticLockException::new); + + account.getPhoneNumberIdentifierOptional() + .flatMap(phoneNumberRecoveryPasswordsManager::getPasswordAndWriteItemForMigration) + .ifPresent(passwordAndWriteItem -> { + account.setAccountRecoveryPassword(passwordAndWriteItem.first()); + accounts.updateTransactionally(account, List.of(passwordAndWriteItem.second())); + + redisDelete(account); + }); + } catch (final ContestedOptimisticLockException | TransactionCanceledException e) { + if (retries > 0) { + migrateAccountRecoveryPassword(accountIdentifier, retries - 1); + } + + throw e; + } + } } 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 58eaf57a9..ca528771b 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/PhoneNumberRecoveryPasswords.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/PhoneNumberRecoveryPasswords.java @@ -27,6 +27,7 @@ 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; +import software.amazon.awssdk.services.dynamodb.model.Update; public class PhoneNumberRecoveryPasswords { @@ -132,4 +133,21 @@ public class PhoneNumberRecoveryPasswords { private static SaltedTokenHash saltedTokenHashFromItem(final Map item) { return new SaltedTokenHash(item.get(ATTR_HASH).s(), item.get(ATTR_SALT).s()); } + + TransactWriteItem buildWriteItemForMigration(final UUID phoneNumberIdentifier, final SaltedTokenHash expectedPassword) { + return TransactWriteItem.builder() + .update(Update.builder() + .tableName(tableName) + .key(Map.of(KEY_PNI, AttributeValues.fromString(phoneNumberIdentifier.toString()))) + .conditionExpression("attribute_exists(#pni) AND #salt = :salt AND #hash = :hash") + .expressionAttributeNames(Map.of( + "#pni", KEY_PNI, + "#salt", ATTR_SALT, + "#hash", ATTR_HASH)) + .expressionAttributeValues(Map.of( + ":salt", AttributeValues.fromString(expectedPassword.salt()), + ":hash", AttributeValues.fromString(expectedPassword.hash()))) + .build()) + .build(); + } } 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 abc7c7c5c..195dc3d04 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/PhoneNumberRecoveryPasswordsManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/PhoneNumberRecoveryPasswordsManager.java @@ -8,8 +8,10 @@ package org.whispersystems.textsecuregcm.storage; import static java.util.Objects.requireNonNull; import java.util.HexFormat; +import java.util.Optional; import java.util.UUID; import org.whispersystems.textsecuregcm.auth.SaltedTokenHash; +import org.whispersystems.textsecuregcm.util.Pair; import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem; public class PhoneNumberRecoveryPasswordsManager { @@ -47,4 +49,11 @@ public class PhoneNumberRecoveryPasswordsManager { private static String bytesToString(final byte[] bytes) { return HexFormat.of().formatHex(bytes); } + + Optional> getPasswordAndWriteItemForMigration(final UUID phoneNumberIdentifier) { + final Optional maybeExistingPassword = phoneNumberRecoveryPasswords.lookup(phoneNumberIdentifier); + + return maybeExistingPassword.map(existingPassword -> + new Pair<>(existingPassword, phoneNumberRecoveryPasswords.buildWriteItemForMigration(phoneNumberIdentifier, existingPassword))); + } } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/PopulateAccountRecoveryPasswordsCommand.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/PopulateAccountRecoveryPasswordsCommand.java new file mode 100644 index 000000000..f6e166cb8 --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/PopulateAccountRecoveryPasswordsCommand.java @@ -0,0 +1,81 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ + +package org.whispersystems.textsecuregcm.workers; + +import com.google.common.annotations.VisibleForTesting; +import io.micrometer.core.instrument.Counter; +import io.micrometer.core.instrument.Metrics; +import net.sourceforge.argparse4j.inf.Subparser; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.whispersystems.textsecuregcm.metrics.MetricsUtil; +import org.whispersystems.textsecuregcm.storage.Account; +import org.whispersystems.textsecuregcm.storage.AccountsManager; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; + +public class PopulateAccountRecoveryPasswordsCommand extends AbstractSinglePassCrawlAccountsCommand { + + @VisibleForTesting + static final String DRY_RUN_ARGUMENT = "dry-run"; + + @VisibleForTesting + static final String MAX_CONCURRENCY_ARGUMENT = "max-concurrency"; + + private static final String ACCOUNTS_MIGRATED_COUNTER_NAME = + MetricsUtil.name(PopulateAccountRecoveryPasswordsCommand.class, "accountsMigrated"); + + private static final Logger logger = LoggerFactory.getLogger(PopulateAccountRecoveryPasswordsCommand.class); + + public PopulateAccountRecoveryPasswordsCommand() { + super("populate-account-recovery-passwords", "Copies phone number recovery passwords as account recovery passwords"); + } + + @Override + public void configure(final Subparser subparser) { + super.configure(subparser); + + subparser.addArgument("--dry-run") + .type(Boolean.class) + .dest(DRY_RUN_ARGUMENT) + .required(false) + .setDefault(true) + .help("If true, don't actually migrate any passwords"); + + subparser.addArgument("--max-concurrency") + .type(Integer.class) + .dest(MAX_CONCURRENCY_ARGUMENT) + .required(false) + .setDefault(64) + .help("Max concurrency for migration operations"); + } + + @Override + protected void crawlAccounts(final Flux accounts) { + final AccountsManager accountsManager = getCommandDependencies().accountsManager(); + + final boolean dryRun = getNamespace().getBoolean(DRY_RUN_ARGUMENT); + final int maxConcurrency = getNamespace().getInt(MAX_CONCURRENCY_ARGUMENT); + + final Counter accountsMigratedCounter = + Metrics.counter(ACCOUNTS_MIGRATED_COUNTER_NAME, "dryRun", String.valueOf(dryRun)); + + accounts.flatMap(account -> (dryRun + ? Mono.empty() + : Mono.fromRunnable(() -> accountsManager.migrateAccountRecoveryPassword(account))) + .onErrorResume(throwable -> { + logger.warn("Failed to migrate account recovery password for account {}", + account.getAccountIdentifier(), throwable); + + return Mono.empty(); + }) + .subscribeOn(Schedulers.boundedElastic()) + .doOnSuccess(_ -> accountsMigratedCounter.increment()), maxConcurrency) + .then() + .block(); + } +} diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerMigrateRecoveryPasswordIntegrationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerMigrateRecoveryPasswordIntegrationTest.java new file mode 100644 index 000000000..f864a0840 --- /dev/null +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerMigrateRecoveryPasswordIntegrationTest.java @@ -0,0 +1,174 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ + +package org.whispersystems.textsecuregcm.storage; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.i18n.phonenumbers.PhoneNumberUtil; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Duration; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager; +import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient; +import org.whispersystems.textsecuregcm.redis.RedisClusterExtension; +import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient; +import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient; +import org.whispersystems.textsecuregcm.tests.util.AccountsHelper; +import org.whispersystems.textsecuregcm.util.TestRandomUtil; +import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; + +public class AccountsManagerMigrateRecoveryPasswordIntegrationTest { + @RegisterExtension + static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension( + DynamoDbExtensionSchema.Tables.ACCOUNTS, + DynamoDbExtensionSchema.Tables.DELETED_ACCOUNTS, + DynamoDbExtensionSchema.Tables.DELETED_ACCOUNTS_LOCK, + DynamoDbExtensionSchema.Tables.NUMBERS, + DynamoDbExtensionSchema.Tables.PNI, + DynamoDbExtensionSchema.Tables.PNI_ASSIGNMENTS, + DynamoDbExtensionSchema.Tables.USERNAMES, + 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.REGISTRATION_RECOVERY_PASSWORDS); + + @RegisterExtension + static final RedisClusterExtension CACHE_CLUSTER_EXTENSION = RedisClusterExtension.builder().build(); + + @RegisterExtension + static final S3LocalStackExtension S3_EXTENSION = new S3LocalStackExtension("testbucket"); + + private PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager; + private ScheduledExecutorService executor; + + private AccountsManager accountsManager; + + @BeforeEach + void setup() throws InterruptedException { + + { + final DynamoDbAsyncClient dynamoDbAsyncClient = DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(); + final KeysManager keysManager = new KeysManager( + new SingleUseECPreKeyStore(dynamoDbAsyncClient, DynamoDbExtensionSchema.Tables.EC_KEYS.tableName()), + new PagedSingleUseKEMPreKeyStore(dynamoDbAsyncClient, + S3_EXTENSION.getS3Client(), + DynamoDbExtensionSchema.Tables.PAGED_PQ_KEYS.tableName(), + S3_EXTENSION.getBucketName()), + new RepeatedUseECSignedPreKeyStore(dynamoDbAsyncClient, + DynamoDbExtensionSchema.Tables.REPEATED_USE_EC_SIGNED_PRE_KEYS.tableName()), + new RepeatedUseKEMSignedPreKeyStore(dynamoDbAsyncClient, + DynamoDbExtensionSchema.Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS.tableName())); + + final Accounts accounts = new Accounts( + Clock.systemUTC(), + DYNAMO_DB_EXTENSION.getDynamoDbClient(), + DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), + DynamoDbExtensionSchema.Tables.ACCOUNTS.tableName(), + DynamoDbExtensionSchema.Tables.NUMBERS.tableName(), + DynamoDbExtensionSchema.Tables.PNI_ASSIGNMENTS.tableName(), + DynamoDbExtensionSchema.Tables.USERNAMES.tableName(), + DynamoDbExtensionSchema.Tables.DELETED_ACCOUNTS.tableName(), + DynamoDbExtensionSchema.Tables.USED_LINK_DEVICE_TOKENS.tableName()); + + executor = Executors.newSingleThreadScheduledExecutor(); + + final AccountLockManager accountLockManager = new AccountLockManager(DYNAMO_DB_EXTENSION.getDynamoDbClient(), + DynamoDbExtensionSchema.Tables.DELETED_ACCOUNTS_LOCK.tableName()); + + final SecureStorageClient secureStorageClient = mock(SecureStorageClient.class); + when(secureStorageClient.deleteStoredData(any())).thenReturn(CompletableFuture.completedFuture(null)); + + final SecureValueRecoveryClient svr2Client = mock(SecureValueRecoveryClient.class); + when(svr2Client.removeData(any(UUID.class))).thenReturn(CompletableFuture.completedFuture(null)); + + final DisconnectionRequestManager disconnectionRequestManager = mock(DisconnectionRequestManager.class); + + final PhoneNumberIdentifiers phoneNumberIdentifiers = + new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), DynamoDbExtensionSchema.Tables.PNI.tableName()); + + final MessagesManager messagesManager = mock(MessagesManager.class); + when(messagesManager.clear(any())).thenReturn(CompletableFuture.completedFuture(null)); + + 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()); + + phoneNumberRecoveryPasswordsManager = new PhoneNumberRecoveryPasswordsManager(phoneNumberRecoveryPasswords); + + accountsManager = new AccountsManager( + accounts, + phoneNumberIdentifiers, + CACHE_CLUSTER_EXTENSION.getRedisCluster(), + mock(FaultTolerantRedisClient.class), + accountLockManager, + keysManager, + messagesManager, + profilesManager, + mock(ChangeNumberWaitingPeriodManager.class), + secureStorageClient, + svr2Client, + disconnectionRequestManager, + phoneNumberRecoveryPasswordsManager, + executor, + executor, + executor, + mock(Clock.class), + "link-device-secret".getBytes(StandardCharsets.UTF_8)); + } + } + + @AfterEach + void tearDown() throws InterruptedException { + executor.shutdown(); + + //noinspection ResultOfMethodCallIgnored + executor.awaitTermination(1, TimeUnit.SECONDS); + } + + @Test + void migrateAccountRecoveryPassword() throws InterruptedException { + final String phoneNumber = PhoneNumberUtil.getInstance().format( + PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164); + + final Account account = AccountsHelper.createAccount(accountsManager, phoneNumber); + final UUID phoneNumberIdentifier = account.getPhoneNumberIdentifierOptional().orElseThrow(); + final byte[] recoveryPassword = TestRandomUtil.nextBytes(16); + + phoneNumberRecoveryPasswordsManager.store(phoneNumberIdentifier, recoveryPassword); + + assertFalse(accountsManager.getByAccountIdentifier(account.getAccountIdentifier()) + .orElseThrow() + .getAccountRecoveryPassword() + .isPresent()); + + accountsManager.migrateAccountRecoveryPassword(account); + + assertTrue(accountsManager.getByAccountIdentifier(account.getAccountIdentifier()) + .orElseThrow() + .getAccountRecoveryPassword() + .isPresent()); + } +} diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/PhoneNumberRecoveryPasswordsTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/PhoneNumberRecoveryPasswordsTest.java new file mode 100644 index 000000000..2c4dbd1c7 --- /dev/null +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/PhoneNumberRecoveryPasswordsTest.java @@ -0,0 +1,76 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ + +package org.whispersystems.textsecuregcm.storage; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.time.Clock; +import java.time.Duration; +import java.util.UUID; +import org.apache.commons.lang3.RandomStringUtils; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.whispersystems.textsecuregcm.auth.SaltedTokenHash; +import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem; +import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsRequest; +import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledException; + +class PhoneNumberRecoveryPasswordsTest { + + @RegisterExtension + static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension( + DynamoDbExtensionSchema.Tables.REGISTRATION_RECOVERY_PASSWORDS + ); + + private PhoneNumberRecoveryPasswords phoneNumberRecoveryPasswords; + + @BeforeEach + void setUp() { + phoneNumberRecoveryPasswords = new PhoneNumberRecoveryPasswords( + DynamoDbExtensionSchema.Tables.REGISTRATION_RECOVERY_PASSWORDS.tableName(), + Duration.ofDays(1), + DYNAMO_DB_EXTENSION.getDynamoDbClient(), + Clock.systemUTC()); + } + + @Test + void buildWriteItemForMigration() { + final UUID phoneNumberIdentifier = UUID.randomUUID(); + + final SaltedTokenHash originalPassword = + SaltedTokenHash.generateFor(RandomStringUtils.insecure().nextAlphanumeric(16)); + + phoneNumberRecoveryPasswords.addOrReplace(phoneNumberIdentifier, originalPassword); + + final TransactWriteItem transactWriteItem = + phoneNumberRecoveryPasswords.buildWriteItemForMigration(phoneNumberIdentifier, originalPassword); + + assertDoesNotThrow(() -> DYNAMO_DB_EXTENSION.getDynamoDbClient().transactWriteItems(TransactWriteItemsRequest.builder() + .transactItems(transactWriteItem) + .build())); + + final SaltedTokenHash changedPassword = + new SaltedTokenHash(originalPassword.salt() + "-different", originalPassword.hash() + "-different"); + + phoneNumberRecoveryPasswords.addOrReplace(phoneNumberIdentifier, changedPassword); + + assertThrows(TransactionCanceledException.class, () -> + DYNAMO_DB_EXTENSION.getDynamoDbClient().transactWriteItems(TransactWriteItemsRequest.builder() + .transactItems(transactWriteItem) + .build()), + "Transaction should not proceed if password has changed"); + + phoneNumberRecoveryPasswords.removeEntry(phoneNumberIdentifier); + + assertThrows(TransactionCanceledException.class, () -> + DYNAMO_DB_EXTENSION.getDynamoDbClient().transactWriteItems(TransactWriteItemsRequest.builder() + .transactItems(transactWriteItem) + .build()), + "Transaction should not proceed if password has been removed"); + } +}