From 1366fbba8aeeaf4a8adaf61f27ad8bb4a79a2ce7 Mon Sep 17 00:00:00 2001 From: Jon Chambers <63609320+jon-signal@users.noreply.github.com> Date: Tue, 18 Aug 2026 11:08:10 -0400 Subject: [PATCH] Allow account recovery with ACI and recovery password --- .../RegistrationLockVerificationManager.java | 24 +- .../controllers/RegistrationController.java | 161 ++++++++- .../entities/RegistrationRequest.java | 22 +- .../textsecuregcm/storage/Account.java | 7 + .../textsecuregcm/storage/Accounts.java | 7 +- .../storage/AccountsManager.java | 268 +++++++++++---- ...gistrationLockVerificationManagerTest.java | 14 +- .../controllers/AccountControllerTest.java | 2 +- .../RegistrationControllerTest.java | 307 ++++++++++++++++++ .../entities/RegistrationRequestTest.java | 179 ++++++++++ ...ccountCreationDeletionIntegrationTest.java | 138 ++++++++ .../storage/AccountsManagerTest.java | 194 +++++++++++ .../textsecuregcm/storage/AccountsTest.java | 32 ++ 13 files changed, 1258 insertions(+), 97 deletions(-) create mode 100644 service/src/test/java/org/whispersystems/textsecuregcm/entities/RegistrationRequestTest.java 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 1755f6914..70173be58 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/auth/RegistrationLockVerificationManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/auth/RegistrationLockVerificationManager.java @@ -14,6 +14,7 @@ import io.micrometer.core.instrument.Tag; import io.micrometer.core.instrument.Tags; import java.time.Duration; import java.time.Instant; +import java.util.Collections; import java.util.List; import javax.annotation.Nullable; import org.apache.commons.lang3.StringUtils; @@ -28,6 +29,7 @@ import org.whispersystems.textsecuregcm.storage.Account; import org.whispersystems.textsecuregcm.storage.AccountsManager; import org.whispersystems.textsecuregcm.storage.Device; import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager; +import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem; public class RegistrationLockVerificationManager { public enum Flow { @@ -137,12 +139,8 @@ public class RegistrationLockVerificationManager { // Freezing the existing account credentials will definitively start the reglock timeout. // Until the timeout, the current reglock can still be supplied, // along with phone number verification, to restore access. - final Account updatedAccount; - if (!alreadyLocked) { - updatedAccount = accounts.update(account, Account::lockAuthTokenHash); - } else { - updatedAccount = account; - } + + final List additionalWriteItems; // The client often sends an empty registration lock token on the first request // and sends an actual token if the server returns a 423 indicating that one is required. @@ -151,10 +149,20 @@ 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.getPhoneNumberIdentifierOptional() - .orElseThrow(() -> new AssertionError("Account with a phone number did not have a phone number identifier"))); + additionalWriteItems = List.of(phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForRemovePassword(account.getPhoneNumberIdentifierOptional() + .orElseThrow(() -> new AssertionError("Account with a phone number did not have a phone number identifier")))); + } else { + additionalWriteItems = Collections.emptyList(); } + final Account updatedAccount = accounts.update(account.getAccountIdentifier(), a -> { + if (!a.hasLockedCredentials()) { + a.lockAuthTokenHash(); + } + + a.clearAccountRecoveryPassword(); + }, additionalWriteItems); + final List deviceIds = updatedAccount.getDevices().stream().map(Device::getId).toList(); disconnectionRequestManager.requestDisconnection(updatedAccount.getAccountIdentifier(), deviceIds); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/RegistrationController.java b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/RegistrationController.java index 763ebaa23..b80bcd3c5 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/RegistrationController.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/RegistrationController.java @@ -41,6 +41,9 @@ import java.time.Duration; import java.time.Instant; import java.util.Collections; import java.util.Optional; +import java.util.UUID; +import javax.annotation.Nullable; +import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.signal.libsignal.zkgroup.InvalidInputException; import org.signal.libsignal.zkgroup.VerificationFailedException; @@ -71,6 +74,7 @@ import org.whispersystems.textsecuregcm.storage.DeviceCapability; import org.whispersystems.textsecuregcm.storage.DeviceIdentityInfo; import org.whispersystems.textsecuregcm.storage.DeviceSpec; import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager; +import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager; import org.whispersystems.textsecuregcm.storage.ReceiptAlreadyRedeemedException; import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory; import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel; @@ -151,10 +155,12 @@ public class RegistrationController { in = ParameterIn.HEADER, name = HttpHeaders.AUTHORIZATION, description = """ - The basic auth header. For accounts with a phone number, the username must be the e164-formatted number that is being registered. - For accounts without a phone number, the username is ignored on a fresh registration (it must be present, however, so an arbitrary - string is acceptable). For account recovery (re-registration) by ACI, it must be set to the ACI of the account being recovered. - In all cases, the password is the password to be used for primary device authentication. + The basic auth header. For accounts with a phone number, the username must be the e164-formatted number that + is being registered. For accounts without a phone number, the username is ignored on a fresh registration + (it must be present, however, so any string that can't be parsed as an e164-formatted phone number or UUID + is acceptable; "__no_number__" is recommended). For account recovery (re-registration) by ACI, it must be + set to the ACI of the account being recovered. In all cases, the password is the password to be used for + primary device authentication. """, required = true, schema = @Schema(type = "string") @@ -166,9 +172,6 @@ public class RegistrationController { @Context final ContainerRequestContext requestContext) throws RateLimitExceededException, InterruptedException, RegistrationLockFailureException { - final String number = authorizationHeader.getUsername(); - final String password = authorizationHeader.getPassword(); - if (!registrationRequest.isEverySignedKeyValid(userAgent)) { throw new WebApplicationException("Invalid signature", 422); } @@ -181,10 +184,28 @@ public class RegistrationController { } final AccountCreationResponse response; - if (registrationRequest.pniIdentityKey() != null) { - response = registerAccountWithNumber(number, password, registrationRequest, requestContext, userAgent, signalAgent); + + if (registrationRequest.receiptCredentialPresentation() != null && registrationRequest.receiptCredentialPresentation().length > 0) { + // A receipt credential presentation will only be present if the caller is trying to register a new account + // without a phone number, in which case we can (and must) ignore the "username" in the authentication header. + response = registerAccountWithoutNumber(authorizationHeader.getPassword(), registrationRequest, userAgent, signalAgent); } else { - response = registerAccountWithoutNumber(password, registrationRequest, userAgent, signalAgent); + // The caller is either trying to register a new account with a phone number or recover an account by ACI. Either + // way, the "username" from the auth header is meaningful. + @Nullable UUID recoveredAccountIdentifier; + + try { + recoveredAccountIdentifier = UUID.fromString(authorizationHeader.getUsername()); + } catch (final IllegalArgumentException _) { + // The provided username is either a phone number or a nonsense string (for registration without a phone number) + recoveredAccountIdentifier = null; + } + + if (recoveredAccountIdentifier != null) { + response = recoverAccount(recoveredAccountIdentifier, authorizationHeader.getPassword(), registrationRequest, userAgent, signalAgent); + } else { + response = registerAccountWithNumber(authorizationHeader.getUsername(), authorizationHeader.getPassword(), registrationRequest, requestContext, userAgent, signalAgent); + } } return response; @@ -199,8 +220,9 @@ public class RegistrationController { final String signalAgent) throws RateLimitExceededException, InterruptedException, RegistrationLockFailureException { - if (registrationRequest.accountAttributes().getPhoneNumberIdentityRegistrationId().isEmpty()) { - throw new WebApplicationException("PNI registration ID must be provided", 422); + if (registrationRequest.pniIdentityKey() == null) { + // RegistrationRequest checks that either all phone number-associated information is present or all is absent + throw new WebApplicationException("PNI keys and registration ID must be provided", 422); } rateLimiters.getRegistrationLimiter().validate(number); @@ -365,4 +387,119 @@ public class RegistrationController { } } + private AccountCreationResponse recoverAccount(final UUID accountIdentifier, + final String password, + final RegistrationRequest registrationRequest, + final String userAgent, + final String signalAgent) throws RegistrationLockFailureException, RateLimitExceededException { + + if (!dynamicConfigurationManager.getConfiguration().getLoginPurchaseConfiguration().enabled()) { + throw new BadRequestException("login purchases are not enabled"); + } + + if (ArrayUtils.isEmpty(registrationRequest.recoveryPassword())) { + throw new BadRequestException("Recovery password required for authentication when recovering an account by identifier"); + } + + if (registrationRequest.accountAttributes().recoveryPassword().isEmpty()) { + throw new BadRequestException("Recovery password required for for storage when recovering an account by identifier"); + } + + if (registrationRequest.pniIdentityKey() == null) { + throw new BadRequestException("Must specify a PNI-associated identity key when recovering an account by identifier"); + } + + final Account existingAccount = accounts.getByAccountIdentifier(accountIdentifier) + .orElseThrow(ForbiddenException::new); + + final boolean passwordVerified = existingAccount.getAccountRecoveryPassword() + .map(saltedRecoveryPasswordHash -> PhoneNumberRecoveryPasswordsManager.verify(saltedRecoveryPasswordHash, registrationRequest.recoveryPassword())) + .orElse(false); + + if (!passwordVerified) { + throw new ForbiddenException(); + } + + if (!registrationRequest.skipDeviceTransfer() && existingAccount.hasCapability(DeviceCapability.TRANSFER)) { + // If a device transfer is possible, clients must explicitly opt out of a transfer (i.e. after prompting the user) + // before we'll let them recover an account and start "from scratch" + throw new WebApplicationException(Response.status(409, "device transfer available").build()); + } + + final Account reclaimedAccount = existingAccount.getNumberOptional().isPresent() + ? recoverAccountWithPhoneNumber(existingAccount, registrationRequest, password, userAgent, signalAgent) + : recoverAccountWithoutPhoneNumber(existingAccount, registrationRequest, password, userAgent, signalAgent); + + Metrics.counter(ACCOUNT_CREATED_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent), + Tag.of(VERIFICATION_TYPE_TAG_NAME, registrationRequest.verificationType().name()))) + .increment(); + + return new AccountCreationResponse(new AccountIdentityResponseBuilder(reclaimedAccount) + .storageCapable(existingAccount.hasCapability(DeviceCapability.STORAGE)) + .build(), true); + } + + private Account recoverAccountWithoutPhoneNumber(final Account existingAccount, + final RegistrationRequest registrationRequest, + final String password, + final String userAgent, + final String signalAgent) { + + return accounts.recover(existingAccount, + registrationRequest.accountAttributes(), + registrationRequest.aciIdentityKey(), + Optional.empty(), + new DeviceSpec( + registrationRequest.accountAttributes().getName(), + password, + signalAgent, + registrationRequest.accountAttributes().getCapabilities(), + new DeviceIdentityInfo( + registrationRequest.accountAttributes().getRegistrationId(), + registrationRequest.deviceActivationRequest().aciSignedPreKey(), + registrationRequest.deviceActivationRequest().aciPqLastResortPreKey()), + Optional.empty(), + registrationRequest.accountAttributes().getFetchesMessages(), + registrationRequest.deviceActivationRequest().apnToken(), + registrationRequest.deviceActivationRequest().gcmToken()), + userAgent); + } + + private Account recoverAccountWithPhoneNumber(final Account existingAccount, + final RegistrationRequest registrationRequest, + final String password, + final String userAgent, + final String signalAgent) throws RegistrationLockFailureException, RateLimitExceededException { + + registrationLockVerificationManager.verifyRegistrationLock(existingAccount, + registrationRequest.accountAttributes().getRegistrationLock(), + userAgent, + RegistrationLockVerificationManager.Flow.REGISTRATION, + PhoneVerificationRequest.VerificationType.RECOVERY_PASSWORD); + + assert registrationRequest.pniIdentityKey() != null; + + return accounts.recover(existingAccount, + registrationRequest.accountAttributes(), + registrationRequest.aciIdentityKey(), + Optional.of(registrationRequest.pniIdentityKey()), + new DeviceSpec( + registrationRequest.accountAttributes().getName(), + password, + signalAgent, + registrationRequest.accountAttributes().getCapabilities(), + new DeviceIdentityInfo( + registrationRequest.accountAttributes().getRegistrationId(), + registrationRequest.deviceActivationRequest().aciSignedPreKey(), + registrationRequest.deviceActivationRequest().aciPqLastResortPreKey()), + Optional.of(new DeviceIdentityInfo( + registrationRequest.accountAttributes().getPhoneNumberIdentityRegistrationId().get(), + // We've already validated the presence of PNI keys by this point + registrationRequest.deviceActivationRequest().pniSignedPreKey().orElseThrow(), + registrationRequest.deviceActivationRequest().pniPqLastResortPreKey().orElseThrow())), + registrationRequest.accountAttributes().getFetchesMessages(), + registrationRequest.deviceActivationRequest().apnToken(), + registrationRequest.deviceActivationRequest().gcmToken()), + userAgent); + } } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/entities/RegistrationRequest.java b/service/src/main/java/org/whispersystems/textsecuregcm/entities/RegistrationRequest.java index 49a834962..ed2a2172e 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/entities/RegistrationRequest.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/entities/RegistrationRequest.java @@ -15,6 +15,7 @@ import jakarta.validation.Valid; import jakarta.validation.constraints.AssertTrue; import jakarta.validation.constraints.NotNull; import java.util.List; +import java.util.stream.Stream; import javax.annotation.Nullable; import org.signal.libsignal.protocol.IdentityKey; import org.whispersystems.textsecuregcm.util.ByteArrayAdapter; @@ -33,7 +34,8 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT @Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """ A base64-encoded registration recovery password. Must be provided if `sessionId` and `receiptCredentialPresentation` are not provided; must not be provided if `sessionId` - or `receiptCredentialPresentation` is provided. + or `receiptCredentialPresentation` is provided. Registration recovery passwords must + be specified when reclaiming an account by account identifier. """) @Nullable byte[] recoveryPassword, @@ -74,7 +76,10 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT @Valid @Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """ The PNI-associated identity key for the account, encoded as a base64 string. - Must be provided for an account with a phone number. + Must be provided for an account with a phone number or when recovering an account by + ID (even if the recovered account does not have a phone number, in which case + PNI-associated key material will be ignored). Must be absent when registering an + account without a phone number. """) @JsonSerialize(using = IdentityKeyAdapter.Serializer.class) @JsonDeserialize(using = IdentityKeyAdapter.Deserializer.class) @@ -116,4 +121,17 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT return deviceActivationRequest().apnToken().isPresent() ^ deviceActivationRequest().gcmToken().isPresent(); } } + + @VisibleForTesting + @AssertTrue + @Schema(hidden = true) + boolean isAllOrNoPhoneNumberInformationProvided() { + final boolean expectPresence = pniIdentityKey != null; + + return Stream.of(pniIdentityKey != null, + accountAttributes().getPhoneNumberIdentityRegistrationId().isPresent(), + deviceActivationRequest().pniSignedPreKey().isPresent(), + deviceActivationRequest().pniPqLastResortPreKey().isPresent()) + .allMatch(present -> present == expectPresence); + } } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/Account.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/Account.java index 4051c4c43..68acb120a 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/Account.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/Account.java @@ -714,6 +714,13 @@ public class Account { this.accountRecoveryPasswordHash = saltedAccountRecoveryPasswordHash.hash(); } + public void clearAccountRecoveryPassword() { + requireNotStale(); + + this.accountRecoveryPasswordSalt = null; + this.accountRecoveryPasswordHash = null; + } + public Optional getAuthCredentialSalt() { requireNotStale(); return Optional.ofNullable(authCredentialSalt); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/Accounts.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/Accounts.java index a5a93f8a2..bea45d7f2 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/Accounts.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/Accounts.java @@ -341,8 +341,10 @@ public class Accounts { // If the account recovery password in the request matches the existing account, this is likely a client retry, // and we continue to allow for idempotency, otherwise this is an attempt to double-redeem a receipt - final boolean isRetry = existingAccount.getAccountRecoveryPassword().map(arp -> - PhoneNumberRecoveryPasswordsManager.verify(arp, accountRecoveryPasswordInRequest)).orElse(false); + final boolean isRetry = existingAccount.getAccountRecoveryPassword() + .map(arp -> PhoneNumberRecoveryPasswordsManager.verify(arp, accountRecoveryPasswordInRequest)) + .orElse(false); + if (!isRetry) { throw new ReceiptAlreadyRedeemedException(); } @@ -383,6 +385,7 @@ public class Accounts { log.error("Reclaimed accounts must match. Old account {}:{}:{}, New account {}:{}:{}", existingAccount.getAccountIdentifier(), existingAccount.getNumberOptional().map(Accounts::redactPhoneNumber), existingAccount.getPhoneNumberIdentifierOptional(), accountToCreate.getAccountIdentifier(), accountToCreate.getNumberOptional().map(Accounts::redactPhoneNumber), accountToCreate.getPhoneNumberIdentifierOptional()); + throw new IllegalArgumentException("reclaimed accounts must match"); } 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 e36fadf1c..7e23a774d 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountsManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountsManager.java @@ -207,6 +207,58 @@ public class AccountsManager extends RedisPubSubAdapter implemen } } + private enum AccountCreationType { + NEW("new"), + RECENTLY_DELETED("recently-deleted"), + RE_REGISTRATION("re-registration"); + + private final String tagValue; + + AccountCreationType(final String tagValue) { + this.tagValue = tagValue; + } + + public String getTagValue() { + return tagValue; + } + } + + private enum PushTokenType { + APNS("apns"), + FCM("fcm"), + NONE("none"); + + private final String tagValue; + + PushTokenType(final String tagValue) { + this.tagValue = tagValue; + } + + public String getTagValue() { + return tagValue; + } + + public static PushTokenType fromDeviceSpec(final DeviceSpec deviceSpec) { + if (deviceSpec.apnRegistrationId().isPresent()) { + return PushTokenType.APNS; + } else if (deviceSpec.gcmRegistrationId().isPresent()) { + return PushTokenType.FCM; + } else { + return PushTokenType.NONE; + } + } + + public static PushTokenType fromDevice(final Device device) { + if (StringUtils.isNotBlank(device.getApnId())) { + return PushTokenType.APNS; + } else if (StringUtils.isNotBlank(device.getGcmId())) { + return PushTokenType.FCM; + } else { + return PushTokenType.NONE; + } + } + } + private record DeviceIdentifier(UUID accountIdentifier, byte deviceId, int registrationId) { } @@ -399,19 +451,13 @@ public class AccountsManager extends RedisPubSubAdapter implemen accountAttributes.recoveryPassword().ifPresent(account::setAccountRecoveryPassword); - String accountCreationType = maybeRecentlyDeletedAccountIdentifier.isPresent() ? "recently-deleted" : "new"; + AccountCreationType accountCreationType = maybeRecentlyDeletedAccountIdentifier.isPresent() + ? AccountCreationType.RECENTLY_DELETED + : AccountCreationType.NEW; - final String pushTokenType; + final PushTokenType pushTokenType = PushTokenType.fromDeviceSpec(primaryDeviceSpec); - if (primaryDeviceSpec.apnRegistrationId().isPresent()) { - pushTokenType = "apns"; - } else if (primaryDeviceSpec.gcmRegistrationId().isPresent()) { - pushTokenType = "fcm"; - } else { - pushTokenType = "none"; - } - - String previousPushTokenType = null; + @Nullable PushTokenType previousPushTokenType = null; try { final List additionalWriteItems = new ArrayList<>(keysManager.buildWriteItemsForNewDevice(account.getAccountIdentifier(), @@ -436,81 +482,169 @@ public class AccountsManager extends RedisPubSubAdapter implemen additionalWriteItems); } } catch (final AccountAlreadyExistsException e) { - accountCreationType = "re-registration"; + accountCreationType = AccountCreationType.RE_REGISTRATION; + previousPushTokenType = PushTokenType.fromDevice(e.getExistingAccount().getPrimaryDevice()); - if (StringUtils.isNotBlank(e.getExistingAccount().getPrimaryDevice().getApnId())) { - previousPushTokenType = "apns"; - } else if (StringUtils.isNotBlank(e.getExistingAccount().getPrimaryDevice().getGcmId())) { - previousPushTokenType = "fcm"; + reclaimAccount(account, e.getExistingAccount(), primaryDeviceSpec, accountAttributes); + } + + handleAccountCreated(account, + accountCreationType, + pushTokenType, + previousPushTokenType, + accountAttributes.recoveryPassword().isPresent(), + userAgent); + + return account; + } + + /// Recovers (re-registers) an account with a specific identifier. Callers are responsible for checking that the end + /// user has permission to recover the account (i.e. via an account recovery password). + /// + /// @param existingAccount the account to recover + /// @param accountAttributes a new set of attributes for the recovered account + /// @param aciIdentityKey a new identity key for the recovered account + /// @param maybePniIdentityKey a new PNI-associated identity for the recovered account; must be present if + /// `existingAccount` has a phone number + /// @param primaryDeviceSpec a new device spec for the account's primary device + /// @param userAgent the User-Agent string of the client requesting account reclamation + /// + /// @return the recovered [Account] + /// + /// @throws IllegalArgumentException if `maybePniIdentityKey` is set but the `existingAccount` does not have a phone + /// number or vice versa + @SuppressWarnings("OptionalUsedAsFieldOrParameterType") + public Account recover(final Account existingAccount, + final AccountAttributes accountAttributes, + final IdentityKey aciIdentityKey, + final Optional maybePniIdentityKey, + final DeviceSpec primaryDeviceSpec, + @Nullable final String userAgent) { + + final Account recoveredAccount = accountLockManager.withSingleAccountLock(existingAccount, () -> { + final Account account = new Account(); + account.setAccountIdentifier(existingAccount.getAccountIdentifier()); + + if (existingAccount.getNumberOptional().isPresent()) { + account.setNumber(existingAccount.getNumberOptional().get(), + existingAccount.getPhoneNumberIdentifierOptional() + .orElseThrow(() -> new AssertionError("Accounts that have a phone number must also have a PNI"))); + + account.setPhoneNumberIdentityKey(maybePniIdentityKey + .orElseThrow(() -> new IllegalArgumentException("PNI identity key must be provided if existing account has a phone number"))); + + account.setRegistrationLockFromAttributes(accountAttributes); + account.setDiscoverableByPhoneNumber(accountAttributes.isDiscoverableByPhoneNumber()); } else { - previousPushTokenType = "none"; + if (maybePniIdentityKey.isPresent()) { + throw new IllegalArgumentException("PNI identity key must not be provided if existing account does not have a phone number"); + } + + final byte[] authCredentialSalt = new byte[AUTH_CREDENTIAL_SALT_SIZE]; + SECURE_RANDOM.nextBytes(authCredentialSalt); + + account.setAuthCredentialSalt(authCredentialSalt); } - final UUID aci = e.getExistingAccount().getAccountIdentifier(); - account.setAccountIdentifier(aci); + account.setIdentityKey(aciIdentityKey); + account.addDevice(primaryDeviceSpec.toDevice(Device.PRIMARY_ID, clock, aciIdentityKey)); + account.setUnidentifiedAccessKey(accountAttributes.getUnidentifiedAccessKey()); + account.setUnrestrictedUnidentifiedAccess(accountAttributes.isUnrestrictedUnidentifiedAccess()); + account.setAccountRecoveryPassword(accountAttributes.recoveryPassword().orElseThrow(() -> + new IllegalArgumentException("Must specify a recovery password when reclaiming an existing account"))); - final List additionalWriteItems = new ArrayList<>(keysManager.buildWriteItemsForNewDevice(account.getAccountIdentifier(), - account.getPhoneNumberIdentifierOptional(), - Device.PRIMARY_ID, - primaryDeviceSpec.aciInfo().signedPreKey(), - primaryDeviceSpec.pniInfo().map(DeviceIdentityInfo::signedPreKey), - primaryDeviceSpec.aciInfo().pqLastResortPreKey(), - primaryDeviceSpec.pniInfo().map(DeviceIdentityInfo::pqLastResortPreKey))); + reclaimAccount(account, existingAccount, primaryDeviceSpec, accountAttributes); - e.getExistingAccount().getDevices() - .stream() - .map(Device::getId) - // No need to clear the keys for the primary device since we'll just overwrite them in the same - // transaction anyhow - .filter(existingDeviceId -> existingDeviceId != Device.PRIMARY_ID) - .map(existingDeviceId -> - keysManager.buildWriteItemsForRemovedDevice(aci, account.getPhoneNumberIdentifierOptional(), existingDeviceId)) - .forEach(additionalWriteItems::addAll); + return account; + }, accountLockExecutor); - maybePni.ifPresent(phoneNumberIdentifier -> - accountAttributes.recoveryPassword().ifPresent(phoneNumberRecoveryPassword -> - additionalWriteItems.add(phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForStorePassword(phoneNumberIdentifier, phoneNumberRecoveryPassword)))); + final PushTokenType pushTokenType = PushTokenType.fromDeviceSpec(primaryDeviceSpec); + final PushTokenType previousPushTokenType = PushTokenType.fromDevice(existingAccount.getPrimaryDevice()); - CompletableFuture.allOf( - keysManager.deleteSingleUsePreKeys(aci), + handleAccountCreated(recoveredAccount, + AccountCreationType.RE_REGISTRATION, + pushTokenType, + previousPushTokenType, + true, + userAgent); + + return recoveredAccount; + } + + private void reclaimAccount(final Account account, + final Account existingAccount, + final DeviceSpec primaryDeviceSpec, + final AccountAttributes accountAttributes) { + + final UUID aci = existingAccount.getAccountIdentifier(); + account.setAccountIdentifier(aci); + + final List additionalWriteItems = new ArrayList<>(keysManager.buildWriteItemsForNewDevice(account.getAccountIdentifier(), + account.getPhoneNumberIdentifierOptional(), + Device.PRIMARY_ID, + primaryDeviceSpec.aciInfo().signedPreKey(), + primaryDeviceSpec.pniInfo().map(DeviceIdentityInfo::signedPreKey), + primaryDeviceSpec.aciInfo().pqLastResortPreKey(), + primaryDeviceSpec.pniInfo().map(DeviceIdentityInfo::pqLastResortPreKey))); + + existingAccount.getDevices() + .stream() + .map(Device::getId) + // No need to clear the keys for the primary device since we'll just overwrite them in the same + // transaction anyhow + .filter(existingDeviceId -> existingDeviceId != Device.PRIMARY_ID) + .map(existingDeviceId -> + keysManager.buildWriteItemsForRemovedDevice(aci, account.getPhoneNumberIdentifierOptional(), existingDeviceId)) + .forEach(additionalWriteItems::addAll); + + account.getPhoneNumberIdentifierOptional().ifPresent(phoneNumberIdentifier -> + accountAttributes.recoveryPassword().ifPresent(phoneNumberRecoveryPassword -> + additionalWriteItems.add(phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForStorePassword(phoneNumberIdentifier, phoneNumberRecoveryPassword)))); + + CompletableFuture.allOf( + keysManager.deleteSingleUsePreKeys(aci), + account.getPhoneNumberIdentifierOptional().map(keysManager::deleteSingleUsePreKeys).orElse(CompletableFuture.completedFuture(null)), + messagesManager.clear(aci), + profilesManager.deleteAll(aci, false)) + .thenCompose(ignored -> disconnectionRequestManager.requestDisconnection(existingAccount)) + .thenCompose(ignored -> accounts.reclaimAccount(existingAccount, account, additionalWriteItems)) + .thenCompose(ignored -> { + // We should have cleared all messages before overwriting the old account, but more may have arrived + // while we were working. Similarly, the old account holder could have added keys or profiles. We'll + // largely repeat the cleanup process after creating the account to make sure we really REALLY got + // everything. + // + // We exclude the primary device's repeated-use keys from deletion because new keys were provided as + // part of the account creation process, and we don't want to delete the keys that just got added. + return CompletableFuture.allOf(keysManager.deleteSingleUsePreKeys(aci), account.getPhoneNumberIdentifierOptional().map(keysManager::deleteSingleUsePreKeys).orElse(CompletableFuture.completedFuture(null)), messagesManager.clear(aci), - profilesManager.deleteAll(aci, false)) - .thenCompose(ignored -> disconnectionRequestManager.requestDisconnection(e.getExistingAccount())) - .thenCompose(ignored -> accounts.reclaimAccount(e.getExistingAccount(), account, additionalWriteItems)) - .thenCompose(ignored -> { - // We should have cleared all messages before overwriting the old account, but more may have arrived - // while we were working. Similarly, the old account holder could have added keys or profiles. We'll - // largely repeat the cleanup process after creating the account to make sure we really REALLY got - // everything. - // - // We exclude the primary device's repeated-use keys from deletion because new keys were provided as - // part of the account creation process, and we don't want to delete the keys that just got added. - return CompletableFuture.allOf(keysManager.deleteSingleUsePreKeys(aci), - account.getPhoneNumberIdentifierOptional().map(keysManager::deleteSingleUsePreKeys).orElse(CompletableFuture.completedFuture(null)), - messagesManager.clear(aci), - profilesManager.deleteAll(aci, false)); - }) - .join(); - } + profilesManager.deleteAll(aci, false)); + }) + .join(); + } + + private void handleAccountCreated(final Account account, + final AccountCreationType accountCreationType, + final PushTokenType pushTokenType, + @Nullable final PushTokenType previousPushTokenType, + final boolean hasRecoveryPassword, + @Nullable final String userAgent) { redisSet(account); changeNumberWaitingPeriodManager.handleAccountCreated(account.getAccountIdentifier(), clock.instant()); Tags tags = Tags.of(UserAgentTagUtil.getPlatformTag(userAgent), - Tag.of("type", accountCreationType), - Tag.of("hasPushToken", String.valueOf( - primaryDeviceSpec.apnRegistrationId().isPresent() || primaryDeviceSpec.gcmRegistrationId() - .isPresent())), - Tag.of("pushTokenType", pushTokenType), - Tag.of("hasRecoveryPassword", String.valueOf(accountAttributes.recoveryPassword().isPresent()))); + Tag.of("type", accountCreationType.getTagValue()), + Tag.of("pushTokenType", pushTokenType.getTagValue()), + Tag.of("hasRecoveryPassword", String.valueOf(hasRecoveryPassword))); - if (StringUtils.isNotBlank(previousPushTokenType)) { - tags = tags.and(Tag.of("previousPushTokenType", previousPushTokenType)); + if (previousPushTokenType != null) { + tags = tags.and(Tag.of("previousPushTokenType", previousPushTokenType.getTagValue())); } + Metrics.counter(CREATE_COUNTER_NAME, tags).increment(); - return account; } public Pair addDevice(final UUID accountIdentifier, final DeviceSpec deviceSpec, final String linkDeviceToken) 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 5de41dc76..bbcdfb842 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/auth/RegistrationLockVerificationManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/auth/RegistrationLockVerificationManagerTest.java @@ -41,15 +41,16 @@ import org.whispersystems.textsecuregcm.storage.Device; import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager; import org.whispersystems.textsecuregcm.tests.util.AccountsHelper; import org.whispersystems.textsecuregcm.util.Pair; +import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem; class RegistrationLockVerificationManagerTest { private final AccountsManager accountsManager = mock(AccountsManager.class); private final DisconnectionRequestManager disconnectionRequestManager = mock(DisconnectionRequestManager.class); - private final ExternalServiceCredentialsGenerator svr2CredentialsGenerator = mock( - ExternalServiceCredentialsGenerator.class); - private final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager = mock( - PhoneNumberRecoveryPasswordsManager.class); + private final ExternalServiceCredentialsGenerator svr2CredentialsGenerator = + mock(ExternalServiceCredentialsGenerator.class); + private final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager = + mock(PhoneNumberRecoveryPasswordsManager.class); private final PushNotificationManager pushNotificationManager = mock(PushNotificationManager.class); private final RateLimiters rateLimiters = mock(RateLimiters.class); private final RegistrationLockVerificationManager registrationLockVerificationManager = new RegistrationLockVerificationManager( @@ -84,6 +85,9 @@ class RegistrationLockVerificationManagerTest { existingRegistrationLock = mock(StoredRegistrationLock.class); when(account.getRegistrationLock()).thenReturn(existingRegistrationLock); + + when(phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForRemovePassword(any())) + .thenReturn(TransactWriteItem.builder().build()); } @ParameterizedTest @@ -103,7 +107,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.getPhoneNumberIdentifierOptional().orElseThrow()); + verify(phoneNumberRecoveryPasswordsManager).buildTransactWriteItemForRemovePassword(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 db16d9c87..3c4da9f15 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AccountControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AccountControllerTest.java @@ -230,7 +230,7 @@ class AccountControllerTest { return null; }).when(usernameZkProofVerifier).verifyProof(any(), any()); - when(PHONE_NUMBER_RECOVERY_PASSWORDS_MANAGER.buildTransactWriteItemForStorePassword(any(), any())) + when(PHONE_NUMBER_RECOVERY_PASSWORDS_MANAGER.buildTransactWriteItemForStorePassword(any(), any(byte[].class))) .thenReturn(TransactWriteItem.builder().build()); } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/RegistrationControllerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/RegistrationControllerTest.java index ac064bba0..c903a7fc3 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/RegistrationControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/RegistrationControllerTest.java @@ -8,11 +8,13 @@ package org.whispersystems.textsecuregcm.controllers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; +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; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -1124,6 +1126,311 @@ class RegistrationControllerTest { } } + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void recoverAccount(final boolean existingAccountHasPhoneNumber) { + final IdentityKey aciIdentityKey; + final IdentityKey pniIdentityKey; + final ECSignedPreKey aciSignedPreKey; + final ECSignedPreKey pniSignedPreKey; + final KEMSignedPreKey aciPqLastResortPreKey; + final KEMSignedPreKey pniPqLastResortPreKey; + { + final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate(); + final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate(); + + aciIdentityKey = new IdentityKey(aciIdentityKeyPair.getPublicKey()); + pniIdentityKey = new IdentityKey(pniIdentityKeyPair.getPublicKey()); + aciSignedPreKey = KeysHelper.signedECPreKey(1, aciIdentityKeyPair); + pniSignedPreKey = KeysHelper.signedECPreKey(2, pniIdentityKeyPair); + aciPqLastResortPreKey = KeysHelper.signedKEMPreKey(3, aciIdentityKeyPair); + pniPqLastResortPreKey = KeysHelper.signedKEMPreKey(4, pniIdentityKeyPair); + } + + final byte[] deviceName = "test".getBytes(StandardCharsets.UTF_8); + final int registrationId = 1; + final int pniRegistrationId = 2; + + final byte[] newRecoveryPassword = TestRandomUtil.nextBytes(32); + + final Set deviceCapabilities = DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES; + + final AccountAttributes accountAttributes = + new AccountAttributes(true, registrationId, pniRegistrationId, deviceName, null, false, deviceCapabilities, newRecoveryPassword) + .setUnidentifiedAccessKey(TestRandomUtil.nextBytes(16)); + + final byte[] existingRecoveryPassword = TestRandomUtil.nextBytes(32); + + final Account existingAccount = new Account(); + existingAccount.setAccountIdentifier(UUID.randomUUID()); + existingAccount.setAccountRecoveryPassword(existingRecoveryPassword); + + if (existingAccountHasPhoneNumber) { + existingAccount.setNumber(PhoneNumberUtil.getInstance().format( + PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164), + UUID.randomUUID()); + + existingAccount.setPhoneNumberIdentityKey(pniIdentityKey); + } + + when(accountsManager.getByAccountIdentifier(existingAccount.getAccountIdentifier())) + .thenReturn(Optional.of(existingAccount)); + + when(accountsManager.recover(any(), any(), any(), any(), any(), any())) + .thenReturn(mock(Account.class)); + + final RegistrationRequest registrationRequest = new RegistrationRequest(null, + existingRecoveryPassword, + null, + accountAttributes, + true, + aciIdentityKey, + pniIdentityKey, + new DeviceActivationRequest(aciSignedPreKey, + Optional.of(pniSignedPreKey), + aciPqLastResortPreKey, + Optional.of(pniPqLastResortPreKey), + Optional.empty(), + Optional.empty())); + + final Invocation.Builder request = resources.getJerseyTest() + .target("/v1/registration") + .request() + .header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(existingAccount.getAccountIdentifier().toString(), PASSWORD)); + + try (final Response response = request.post(Entity.json(requestToJson(registrationRequest)))) { + assertEquals(200, response.getStatus()); + + final AccountCreationResponse creationResponse = response.readEntity(AccountCreationResponse.class); + assertTrue(creationResponse.reregistration()); + } + + verify(accountsManager).recover( + eq(existingAccount), + argThat(attributes -> accountAttributesEqual(attributes, accountAttributes)), + eq(aciIdentityKey), + eq(existingAccountHasPhoneNumber ? Optional.of(pniIdentityKey) : Optional.empty()), + eq(new DeviceSpec( + deviceName, + PASSWORD, + null, + deviceCapabilities, + new DeviceIdentityInfo(registrationId, aciSignedPreKey, aciPqLastResortPreKey), + existingAccountHasPhoneNumber + ? Optional.of(new DeviceIdentityInfo(pniRegistrationId, pniSignedPreKey, pniPqLastResortPreKey)) + : Optional.empty(), + true, + Optional.empty(), + Optional.empty())), + any() + ); + + verifyNoInteractions(phoneVerificationTokenManager); + } + + @ParameterizedTest + @MethodSource + void recoverAccountBadRequest(final Account existingAccount, + final UUID accountIdentifier, + final RegistrationRequest registrationRequest, + final int expectedStatus) { + + when(accountsManager.getByAccountIdentifier(any())) + .thenReturn(Optional.empty()); + + when(accountsManager.getByAccountIdentifier(existingAccount.getAccountIdentifier())) + .thenReturn(Optional.of(existingAccount)); + + final Invocation.Builder request = resources.getJerseyTest() + .target("/v1/registration") + .request() + .header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(accountIdentifier.toString(), PASSWORD)); + + try (final Response response = request.post(Entity.json(requestToJson(registrationRequest)))) { + assertEquals(expectedStatus, response.getStatus()); + } + + verify(accountsManager, never()).recover(any(), any(), any(), any(), any(), any()); + verifyNoInteractions(phoneVerificationTokenManager); + } + + private static List recoverAccountBadRequest() { + final IdentityKey aciIdentityKey; + final IdentityKey pniIdentityKey; + final ECSignedPreKey aciSignedPreKey; + final ECSignedPreKey pniSignedPreKey; + final KEMSignedPreKey aciPqLastResortPreKey; + final KEMSignedPreKey pniPqLastResortPreKey; + { + final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate(); + final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate(); + + aciIdentityKey = new IdentityKey(aciIdentityKeyPair.getPublicKey()); + pniIdentityKey = new IdentityKey(pniIdentityKeyPair.getPublicKey()); + aciSignedPreKey = KeysHelper.signedECPreKey(1, aciIdentityKeyPair); + pniSignedPreKey = KeysHelper.signedECPreKey(2, pniIdentityKeyPair); + aciPqLastResortPreKey = KeysHelper.signedKEMPreKey(3, aciIdentityKeyPair); + pniPqLastResortPreKey = KeysHelper.signedKEMPreKey(4, pniIdentityKeyPair); + } + + final byte[] deviceName = "test".getBytes(StandardCharsets.UTF_8); + final int registrationId = 1; + final int pniRegistrationId = 2; + + final byte[] newRecoveryPassword = TestRandomUtil.nextBytes(32); + + final Set deviceCapabilities = DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES; + + final AccountAttributes accountAttributes = + new AccountAttributes(true, registrationId, pniRegistrationId, deviceName, null, false, deviceCapabilities, newRecoveryPassword) + .setUnidentifiedAccessKey(TestRandomUtil.nextBytes(16)); + + final byte[] existingRecoveryPassword = TestRandomUtil.nextBytes(32); + + final Account existingAccount = new Account(); + existingAccount.setAccountIdentifier(UUID.randomUUID()); + existingAccount.setAccountRecoveryPassword(existingRecoveryPassword); + existingAccount.setNumber(PhoneNumberUtil.getInstance().format( + PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164), + UUID.randomUUID()); + + existingAccount.setPhoneNumberIdentityKey(pniIdentityKey); + + final Device primaryDevice = new Device(); + primaryDevice.setId(Device.PRIMARY_ID); + primaryDevice.setCapabilities(Set.of(DeviceCapability.TRANSFER)); + + existingAccount.addDevice(primaryDevice); + + return List.of( + Arguments.argumentSet("Missing recovery password", + existingAccount, + existingAccount.getAccountIdentifier(), + new RegistrationRequest(null, + null, + null, + accountAttributes, + true, + aciIdentityKey, + pniIdentityKey, + new DeviceActivationRequest(aciSignedPreKey, + Optional.of(pniSignedPreKey), + aciPqLastResortPreKey, + Optional.of(pniPqLastResortPreKey), + Optional.empty(), + Optional.empty())), + 422), + + Arguments.argumentSet("Session ID instead of recovery password", + existingAccount, + existingAccount.getAccountIdentifier(), + new RegistrationRequest("session-id", + null, + null, + accountAttributes, + true, + aciIdentityKey, + pniIdentityKey, + new DeviceActivationRequest(aciSignedPreKey, + Optional.of(pniSignedPreKey), + aciPqLastResortPreKey, + Optional.of(pniPqLastResortPreKey), + Optional.empty(), + Optional.empty())), + 400), + + Arguments.argumentSet("Receipt credential presentation instead of recovery password", + existingAccount, + existingAccount.getAccountIdentifier(), + new RegistrationRequest(null, + null, + TestRandomUtil.nextBytes(16), + accountAttributes, + true, + aciIdentityKey, + pniIdentityKey, + new DeviceActivationRequest(aciSignedPreKey, + Optional.of(pniSignedPreKey), + aciPqLastResortPreKey, + Optional.of(pniPqLastResortPreKey), + Optional.empty(), + Optional.empty())), + 400), + + Arguments.argumentSet("Missing PNI identity key", + existingAccount, + existingAccount.getAccountIdentifier(), + new RegistrationRequest(null, + existingRecoveryPassword, + null, + accountAttributes, + true, + aciIdentityKey, + null, + new DeviceActivationRequest(aciSignedPreKey, + Optional.of(pniSignedPreKey), + aciPqLastResortPreKey, + Optional.of(pniPqLastResortPreKey), + Optional.empty(), + Optional.empty())), + 422), + + Arguments.argumentSet("Account not found", + existingAccount, + UUID.randomUUID(), + new RegistrationRequest(null, + existingRecoveryPassword, + null, + accountAttributes, + true, + aciIdentityKey, + pniIdentityKey, + new DeviceActivationRequest(aciSignedPreKey, + Optional.of(pniSignedPreKey), + aciPqLastResortPreKey, + Optional.of(pniPqLastResortPreKey), + Optional.empty(), + Optional.empty())), + 403), + + Arguments.argumentSet("Incorrect password", + existingAccount, + existingAccount.getAccountIdentifier(), + new RegistrationRequest(null, + TestRandomUtil.nextBytes(32), + null, + accountAttributes, + true, + aciIdentityKey, + pniIdentityKey, + new DeviceActivationRequest(aciSignedPreKey, + Optional.of(pniSignedPreKey), + aciPqLastResortPreKey, + Optional.of(pniPqLastResortPreKey), + Optional.empty(), + Optional.empty())), + 403), + + Arguments.argumentSet("Device transfer opt-out required", + existingAccount, + existingAccount.getAccountIdentifier(), + new RegistrationRequest(null, + existingRecoveryPassword, + null, + accountAttributes, + false, + aciIdentityKey, + pniIdentityKey, + new DeviceActivationRequest(aciSignedPreKey, + Optional.of(pniSignedPreKey), + aciPqLastResortPreKey, + Optional.of(pniPqLastResortPreKey), + Optional.empty(), + Optional.empty())), + 409) + ); + } + private static boolean accountAttributesEqual(final AccountAttributes a, final AccountAttributes b) { return a.getFetchesMessages() == b.getFetchesMessages() && a.getRegistrationId() == b.getRegistrationId() diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/entities/RegistrationRequestTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/entities/RegistrationRequestTest.java new file mode 100644 index 000000000..a6a9a1129 --- /dev/null +++ b/service/src/test/java/org/whispersystems/textsecuregcm/entities/RegistrationRequestTest.java @@ -0,0 +1,179 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ + +package org.whispersystems.textsecuregcm.entities; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import javax.annotation.Nullable; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junitpioneer.jupiter.cartesian.CartesianTest; +import org.signal.libsignal.protocol.IdentityKey; +import org.signal.libsignal.protocol.ecc.ECKeyPair; +import org.whispersystems.textsecuregcm.tests.util.KeysHelper; + +class RegistrationRequestTest { + + @ParameterizedTest + @MethodSource + void isEverySignedKeyValid(final RegistrationRequest registrationRequest, final boolean expectEverySignedKeyValid) { + assertEquals(expectEverySignedKeyValid, registrationRequest.isEverySignedKeyValid("test")); + } + + private static List isEverySignedKeyValid() { + final ECKeyPair aciKeyPair = ECKeyPair.generate(); + final ECKeyPair pniKeyPair = ECKeyPair.generate(); + + final IdentityKey aciIdentityKey = new IdentityKey(aciKeyPair.getPublicKey()); + final IdentityKey pniIdentityKey = new IdentityKey(pniKeyPair.getPublicKey()); + + final ECSignedPreKey aciEcSignedPreKey = KeysHelper.signedECPreKey(1, aciKeyPair); + final ECSignedPreKey pniEcSignedPreKey = KeysHelper.signedECPreKey(2, pniKeyPair); + + final KEMSignedPreKey aciKemSignedPreKey = KeysHelper.signedKEMPreKey(3, aciKeyPair); + final KEMSignedPreKey pniKemSignedPreKey = KeysHelper.signedKEMPreKey(4, pniKeyPair); + + return List.of( + Arguments.argumentSet("All keys specified", + buildRegistrationRequestWithKeys(aciIdentityKey, pniIdentityKey, aciEcSignedPreKey, pniEcSignedPreKey, aciKemSignedPreKey, pniKemSignedPreKey), + true), + + Arguments.argumentSet("Only ACI keys specified", + buildRegistrationRequestWithKeys(aciIdentityKey, null, aciEcSignedPreKey, null, aciKemSignedPreKey, null), + true), + + Arguments.argumentSet("ACI EC pre-key missing", + buildRegistrationRequestWithKeys(aciIdentityKey, pniIdentityKey, null, pniEcSignedPreKey, aciKemSignedPreKey, pniKemSignedPreKey), + false), + + Arguments.argumentSet("ACI KEM pre-key missing", + buildRegistrationRequestWithKeys(aciIdentityKey, pniIdentityKey, aciEcSignedPreKey, pniEcSignedPreKey, null, pniKemSignedPreKey), + false), + + Arguments.argumentSet("PNI identity key missing", + buildRegistrationRequestWithKeys(aciIdentityKey, null, aciEcSignedPreKey, pniEcSignedPreKey, aciKemSignedPreKey, pniKemSignedPreKey), + false), + + Arguments.argumentSet("PNI EC pre-key missing", + buildRegistrationRequestWithKeys(aciIdentityKey, pniIdentityKey, aciEcSignedPreKey, null, aciKemSignedPreKey, pniKemSignedPreKey), + false), + + Arguments.argumentSet("PNI KEM pre-identity key missing", + buildRegistrationRequestWithKeys(aciIdentityKey, pniIdentityKey, aciEcSignedPreKey, pniEcSignedPreKey, aciKemSignedPreKey, null), + false), + + Arguments.argumentSet("Incorrect ACI signature", + buildRegistrationRequestWithKeys(new IdentityKey(ECKeyPair.generate().getPublicKey()), pniIdentityKey, aciEcSignedPreKey, pniEcSignedPreKey, aciKemSignedPreKey, pniKemSignedPreKey), + false), + + Arguments.argumentSet("Incorrect PNI signature", + buildRegistrationRequestWithKeys(aciIdentityKey, new IdentityKey(ECKeyPair.generate().getPublicKey()), aciEcSignedPreKey, pniEcSignedPreKey, aciKemSignedPreKey, pniKemSignedPreKey), + false) + ); + } + + private static RegistrationRequest buildRegistrationRequestWithKeys(@Nullable final IdentityKey aciIdentityKey, + @Nullable final IdentityKey pniIdentityKey, + @Nullable final ECSignedPreKey aciEcSignedPreKey, + @Nullable final ECSignedPreKey pniEcSignedPreKey, + @Nullable final KEMSignedPreKey aciKemSignedPreKey, + @Nullable final KEMSignedPreKey pniKemSignedPreKey) { + + return new RegistrationRequest(null, + null, + null, + null, + true, + aciIdentityKey, + pniIdentityKey, + new DeviceActivationRequest(aciEcSignedPreKey, + Optional.ofNullable(pniEcSignedPreKey), + aciKemSignedPreKey, + Optional.ofNullable(pniKemSignedPreKey), + Optional.empty(), + Optional.empty())); + } + + @ParameterizedTest + @MethodSource + void isExactlyOneMessageDeliveryChannel(final RegistrationRequest registrationRequest, final boolean expectExactlyOneMessageDeliveryChannel) { + assertEquals(expectExactlyOneMessageDeliveryChannel, registrationRequest.isExactlyOneMessageDeliveryChannel()); + } + + private static List isExactlyOneMessageDeliveryChannel() { + return List.of( + Arguments.argumentSet("Fetches messages", + buildRegistrationRequestWithDeliveryChannel(true, null, null), true), + + Arguments.argumentSet("APNs token", + buildRegistrationRequestWithDeliveryChannel(false, "apns", null), true), + + Arguments.argumentSet("FCM token", + buildRegistrationRequestWithDeliveryChannel(false, null, "fcm"), true), + + Arguments.argumentSet("Multiple delivery channels", + buildRegistrationRequestWithDeliveryChannel(true, "apns", "fcm"), false), + + Arguments.argumentSet("No delivery channel", + buildRegistrationRequestWithDeliveryChannel(false, null, null), false) + ); + }; + + private static RegistrationRequest buildRegistrationRequestWithDeliveryChannel(final boolean fetchesMessages, + @Nullable final String apnsToken, + @Nullable final String fcmToken) { + + return new RegistrationRequest(null, + null, + null, + new AccountAttributes(fetchesMessages, 1, 2, null, null, false, Collections.emptySet(), null), + true, + null, + null, + new DeviceActivationRequest(null, + Optional.empty(), + null, + Optional.empty(), + Optional.ofNullable(apnsToken).map(ApnRegistrationId::new), + Optional.ofNullable(fcmToken).map(GcmRegistrationId::new))); + } + + @CartesianTest + void isAllOrNoPhoneNumberInformationProvided(@CartesianTest.Values(booleans = {true, false}) final boolean pniIdentityKeyPresent, + @CartesianTest.Values(booleans = {true, false}) final boolean pniRegistrationIdPresent, + @CartesianTest.Values(booleans = {true, false}) final boolean pniEcSignedPreKeyPresent, + @CartesianTest.Values(booleans = {true, false}) final boolean pniKemSignedPreKeyPresent) { + + final ECKeyPair pniKeyPair = ECKeyPair.generate(); + final IdentityKey pniIdentityKey = new IdentityKey(pniKeyPair.getPublicKey()); + final ECSignedPreKey pniEcSignedPreKey = KeysHelper.signedECPreKey(2, pniKeyPair); + final KEMSignedPreKey pniKemSignedPreKey = KeysHelper.signedKEMPreKey(4, pniKeyPair); + + final RegistrationRequest registrationRequest = new RegistrationRequest(null, + null, + null, + new AccountAttributes(true, 1, pniRegistrationIdPresent ? 2 : null, null, null, false, Collections.emptySet(), null), + true, + null, + pniIdentityKeyPresent ? pniIdentityKey : null, + new DeviceActivationRequest(null, + pniEcSignedPreKeyPresent ? Optional.of(pniEcSignedPreKey) : Optional.empty(), + null, + pniKemSignedPreKeyPresent ? Optional.of(pniKemSignedPreKey) : Optional.empty(), + Optional.empty(), + Optional.empty())); + + final boolean expectAllPresentOrAbsent = + (pniIdentityKeyPresent && pniRegistrationIdPresent && pniEcSignedPreKeyPresent && pniKemSignedPreKeyPresent) || + !(pniIdentityKeyPresent || pniRegistrationIdPresent || pniEcSignedPreKeyPresent || pniKemSignedPreKeyPresent); + + assertEquals(expectAllPresentOrAbsent, registrationRequest.isAllOrNoPhoneNumberInformationProvided()); + } +} diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountCreationDeletionIntegrationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountCreationDeletionIntegrationTest.java index b2917ee78..500b6efb3 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountCreationDeletionIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountCreationDeletionIntegrationTest.java @@ -23,6 +23,7 @@ import java.time.Instant; import java.time.ZoneId; import java.util.ArrayList; import java.util.Collections; +import java.util.HexFormat; import java.util.List; import java.util.Optional; import java.util.Set; @@ -33,6 +34,7 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -488,6 +490,142 @@ public class AccountCreationDeletionIntegrationTest { assertFalse(phoneNumberRecoveryPasswordsManager.verify(reregisteredAccount.getPhoneNumberIdentifierOptional().orElseThrow(), originalRecoveryPassword)); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void reclaimAccount(final boolean hasE164) + throws InvalidInputException, VerificationFailedException, ReceiptAlreadyRedeemedException { + final String number = PhoneNumberUtil.getInstance().format( + PhoneNumberUtil.getInstance().getExampleNumber("US"), + PhoneNumberUtil.PhoneNumberFormat.E164); + + final byte[] originalRecoveryPassword = TestRandomUtil.nextBytes(32); + final byte[] updatedRecoveryPassword = TestRandomUtil.nextBytes(32); + + final List existingAccountBadges = new ArrayList<>(List.of(new AccountBadge( + RandomStringUtils.secure().nextAlphabetic(8), + CLOCK.instant().plus(Duration.ofDays(7)), + true))); + + final UUID existingAccountIdentifier; + { + final ECKeyPair aciKeyPair = ECKeyPair.generate(); + final ECKeyPair pniKeyPair = ECKeyPair.generate(); + + final ECSignedPreKey aciSignedPreKey = KeysHelper.signedECPreKey(1, aciKeyPair); + final ECSignedPreKey pniSignedPreKey = KeysHelper.signedECPreKey(2, pniKeyPair); + final KEMSignedPreKey aciPqLastResortPreKey = KeysHelper.signedKEMPreKey(3, aciKeyPair); + final KEMSignedPreKey pniPqLastResortPreKey = KeysHelper.signedKEMPreKey(4, pniKeyPair); + + final ReceiptSerial receiptSerial = new ReceiptSerial(TestRandomUtil.nextBytes(ReceiptSerial.SIZE)); + + final Account existingAccount = hasE164 + ? accountsManager.create(number, + new AccountAttributes(true, 1, 2, "name".getBytes(StandardCharsets.UTF_8), "registration-lock", false, Set.of(), + originalRecoveryPassword), + new IdentityKey(aciKeyPair.getPublicKey()), + new IdentityKey(pniKeyPair.getPublicKey()), + new DeviceSpec(null, + "password?", + "OWI", + Set.of(), + new DeviceIdentityInfo(1, aciSignedPreKey, aciPqLastResortPreKey), + Optional.of(new DeviceIdentityInfo(2, pniSignedPreKey, pniPqLastResortPreKey)), + true, + Optional.empty(), + Optional.empty()), + null) + : accountsManager.create(new AccountAttributes(true, 1, null, "name".getBytes(StandardCharsets.UTF_8), null, false, Set.of(), + originalRecoveryPassword), + new IdentityKey(aciKeyPair.getPublicKey()), + receiptPresentation(receiptSerial, CLOCK.instant().plus(Duration.ofDays(30)), 1), + new DeviceSpec(null, + "password?", + "OWI", + Set.of(), + new DeviceIdentityInfo(1, aciSignedPreKey, aciPqLastResortPreKey), + Optional.empty(), + true, + Optional.empty(), + Optional.empty()), + null); + + accountsManager.update(existingAccount, a -> a.setBadges(CLOCK, existingAccountBadges)); + + existingAccountIdentifier = existingAccount.getAccountIdentifier(); + } + + final ECKeyPair aciKeyPair = ECKeyPair.generate(); + final ECKeyPair pniKeyPair = ECKeyPair.generate(); + + final IdentityKey aciIdentityKey = new IdentityKey(aciKeyPair.getPublicKey()); + final IdentityKey pniIdentityKey = new IdentityKey(pniKeyPair.getPublicKey()); + + final ECSignedPreKey aciSignedPreKey = KeysHelper.signedECPreKey(1, aciKeyPair); + final ECSignedPreKey pniSignedPreKey = KeysHelper.signedECPreKey(2, pniKeyPair); + final KEMSignedPreKey aciPqLastResortPreKey = KeysHelper.signedKEMPreKey(3, aciKeyPair); + final KEMSignedPreKey pniPqLastResortPreKey = KeysHelper.signedKEMPreKey(4, pniKeyPair); + + final int aciRegistrationId = 17; + final int pniRegistrationId = 19; + + final DeviceSpec primaryDeviceSpec = new DeviceSpec(null, + "updated password", + "OWI", + Set.of(), + new DeviceIdentityInfo(aciRegistrationId, aciSignedPreKey, aciPqLastResortPreKey), + hasE164 ? Optional.of(new DeviceIdentityInfo(pniRegistrationId, pniSignedPreKey, pniPqLastResortPreKey)) : Optional.empty(), + true, + Optional.empty(), + Optional.empty()); + + final Account existingAccount = accountsManager.getByAccountIdentifier(existingAccountIdentifier).orElseThrow(); + + final Account reclaimedAccount = accountsManager.recover(existingAccount, + new AccountAttributes(true, aciRegistrationId, hasE164 ? pniRegistrationId : null, "name".getBytes(StandardCharsets.UTF_8), null, hasE164, Set.of(), + updatedRecoveryPassword), + aciIdentityKey, + hasE164 ? Optional.of(pniIdentityKey) : Optional.empty(), + primaryDeviceSpec, + null); + + assertEquals(existingAccount.getAccountIdentifier(), reclaimedAccount.getAccountIdentifier()); + assertEquals(existingAccount.getNumberOptional(), reclaimedAccount.getNumberOptional()); + assertEquals(existingAccount.getPhoneNumberIdentifierOptional(), reclaimedAccount.getPhoneNumberIdentifierOptional()); + assertEquals(aciIdentityKey, reclaimedAccount.getAccountIdentityKey()); + assertEquals(hasE164 ? Optional.of(pniIdentityKey) : Optional.empty(), reclaimedAccount.getPhoneNumberIdentityKey()); + + final Device reclaimedPrimaryDevice = reclaimedAccount.getPrimaryDevice(); + assertArrayEquals(primaryDeviceSpec.deviceNameCiphertext(), reclaimedPrimaryDevice.getName()); + assertEquals(primaryDeviceSpec.signalAgent(), reclaimedPrimaryDevice.getUserAgent()); + assertEquals(aciRegistrationId, reclaimedPrimaryDevice.getAccountRegistrationId()); + assertEquals(hasE164 ? Optional.of(pniRegistrationId) : Optional.empty(), reclaimedPrimaryDevice.getPhoneNumberIdentityRegistrationId()); + assertTrue(reclaimedPrimaryDevice.getFetchesMessages()); + assertTrue(StringUtils.isBlank(reclaimedPrimaryDevice.getApnId())); + assertTrue(StringUtils.isBlank(reclaimedPrimaryDevice.getGcmId())); + + assertTrue(reclaimedAccount.getAccountRecoveryPassword().orElseThrow().verify(HexFormat.of().formatHex(updatedRecoveryPassword))); + assertTrue(reclaimedPrimaryDevice.getAuthTokenHash().verify(primaryDeviceSpec.password())); + + assertExpectedStoredAccount(reclaimedAccount, + hasE164 ? Optional.of(number) : Optional.empty(), + primaryDeviceSpec.password(), + primaryDeviceSpec.signalAgent(), + new DeliveryChannels(true, null, null), + aciRegistrationId, + hasE164 ? Optional.of(pniRegistrationId) : Optional.empty(), + primaryDeviceSpec.deviceNameCiphertext(), + hasE164, + Collections.emptySet(), + existingAccountBadges, + Optional.empty(), + Optional.empty(), + Optional.empty(), + aciSignedPreKey, + hasE164 ? Optional.of(pniSignedPreKey) : Optional.empty(), + aciPqLastResortPreKey, + hasE164 ? Optional.of(pniPqLastResortPreKey) : Optional.empty()); + } + @ParameterizedTest @ValueSource(booleans = {false, true}) void deleteAccount(final boolean hasE164) diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerTest.java index 60240ec24..0cebce0e1 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerTest.java @@ -63,6 +63,8 @@ import java.util.function.Consumer; import java.util.stream.Stream; import javax.annotation.Nullable; import javax.crypto.spec.SecretKeySpec; +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; @@ -951,6 +953,198 @@ class AccountsManagerTest { Arguments.argumentSet("Re-register a numberless account", Optional.empty(), Optional.empty())); } + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void reclaim(final boolean hasPhoneNumber) { + final Account existingAccount = new Account(); + existingAccount.setAccountIdentifier(UUID.randomUUID()); + + final Device existingPrimaryDevice = new Device(); + existingPrimaryDevice.setId(Device.PRIMARY_ID); + + existingAccount.addDevice(existingPrimaryDevice); + + final byte[] recoveryPassword = TestRandomUtil.nextBytes(16); + + existingAccount.setAccountRecoveryPassword(recoveryPassword); + + final int aciRegistrationId = 17; + final int pniRegistrationId = 19; + + final ECKeyPair aciKeyPair = ECKeyPair.generate(); + final ECKeyPair pniKeyPair = ECKeyPair.generate(); + final IdentityKey aciIdentityKey = new IdentityKey(aciKeyPair.getPublicKey()); + final IdentityKey pniIdentityKey = new IdentityKey(pniKeyPair.getPublicKey()); + final ECSignedPreKey aciSignedPreKey = KeysHelper.signedECPreKey(1, aciKeyPair); + final ECSignedPreKey pniSignedPreKey = KeysHelper.signedECPreKey(2, pniKeyPair); + final KEMSignedPreKey aciPqLastResortPreKey = KeysHelper.signedKEMPreKey(3, aciKeyPair); + final KEMSignedPreKey pniPqLastResortPreKey = KeysHelper.signedKEMPreKey(4, pniKeyPair); + + if (hasPhoneNumber) { + existingAccount.setNumber(PhoneNumberUtil.getInstance().format( + PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164), + UUID.randomUUID()); + } + + final AccountAttributes accountAttributes = new AccountAttributes(false, + aciRegistrationId, + hasPhoneNumber ? pniRegistrationId : null, + TestRandomUtil.nextBytes(16), + hasPhoneNumber ? "registration-lock" : null, + hasPhoneNumber, + Collections.emptySet(), + recoveryPassword); + + final DeviceSpec primaryDeviceSpec = new DeviceSpec( + TestRandomUtil.nextBytes(16), + RandomStringUtils.insecure().nextAlphanumeric(12), + "test", + Collections.emptySet(), + new DeviceIdentityInfo(aciRegistrationId, aciSignedPreKey, aciPqLastResortPreKey), + Optional.of(new DeviceIdentityInfo(pniRegistrationId, pniSignedPreKey, pniPqLastResortPreKey)).filter(_ -> hasPhoneNumber), + true, + Optional.empty(), + Optional.empty()); + + when(accounts.reclaimAccount(any(), any(), any())).thenReturn(CompletableFuture.completedFuture(null)); + + final Account reclaimedAccount = accountsManager.recover(existingAccount, + accountAttributes, + aciIdentityKey, + hasPhoneNumber ? Optional.of(pniIdentityKey) : Optional.empty(), + primaryDeviceSpec, + null); + + assertEquals(existingAccount.getAccountIdentifier(), reclaimedAccount.getAccountIdentifier()); + assertEquals(existingAccount.getNumberOptional(), reclaimedAccount.getNumberOptional()); + assertEquals(existingAccount.getPhoneNumberIdentifierOptional(), reclaimedAccount.getPhoneNumberIdentifierOptional()); + assertEquals(aciIdentityKey, reclaimedAccount.getAccountIdentityKey()); + assertEquals(hasPhoneNumber ? Optional.of(pniIdentityKey) : Optional.empty(), reclaimedAccount.getPhoneNumberIdentityKey()); + + final Device reclaimedPrimaryDevice = reclaimedAccount.getPrimaryDevice(); + assertArrayEquals(primaryDeviceSpec.deviceNameCiphertext(), reclaimedPrimaryDevice.getName()); + assertEquals(primaryDeviceSpec.signalAgent(), reclaimedPrimaryDevice.getUserAgent()); + assertEquals(aciRegistrationId, reclaimedPrimaryDevice.getAccountRegistrationId()); + assertEquals(hasPhoneNumber ? Optional.of(pniRegistrationId) : Optional.empty(), reclaimedPrimaryDevice.getPhoneNumberIdentityRegistrationId()); + assertTrue(reclaimedPrimaryDevice.getFetchesMessages()); + assertTrue(StringUtils.isBlank(reclaimedPrimaryDevice.getApnId())); + assertTrue(StringUtils.isBlank(reclaimedPrimaryDevice.getGcmId())); + + assertTrue(reclaimedAccount.getAccountRecoveryPassword().orElseThrow().verify(HexFormat.of().formatHex(recoveryPassword))); + assertTrue(reclaimedPrimaryDevice.getAuthTokenHash().verify(primaryDeviceSpec.password())); + + verify(accounts).reclaimAccount(eq(existingAccount), argThat(account -> existingAccount.getAccountIdentifier().equals(account.getAccountIdentifier())), any()); + + verify(keysManager).buildWriteItemsForNewDevice( + eq(reclaimedAccount.getAccountIdentifier()), + eq(reclaimedAccount.getPhoneNumberIdentifierOptional()), + eq(Device.PRIMARY_ID), + notNull(), + hasPhoneNumber ? notNull() : eq(Optional.empty()), + notNull(), + hasPhoneNumber ? notNull() : eq(Optional.empty())); + + verify(keysManager, times(2)).deleteSingleUsePreKeys(existingAccount.getAccountIdentifier()); + existingAccount.getPhoneNumberIdentifierOptional().ifPresent(phoneNumberIdentifier -> + verify(keysManager, times(2)).deleteSingleUsePreKeys(phoneNumberIdentifier)); + verify(messagesManager, times(2)).clear(existingAccount.getAccountIdentifier()); + verify(profilesManager, times(2)).deleteAll(existingAccount.getAccountIdentifier(), false); + verify(disconnectionRequestManager).requestDisconnection(argThat(account -> + account.getAccountIdentifier().equals(existingAccount.getAccountIdentifier()) && account != reclaimedAccount)); + verify(changeNumberWaitingPeriodManager).handleAccountCreated(eq(existingAccount.getAccountIdentifier()), any(Instant.class)); + } + + @Test + void reclaimPniPresenceMismatch() { + final Account existingAccount = new Account(); + existingAccount.setAccountIdentifier(UUID.randomUUID()); + + final Device existingPrimaryDevice = new Device(); + existingPrimaryDevice.setId(Device.PRIMARY_ID); + + existingAccount.addDevice(existingPrimaryDevice); + + final byte[] recoveryPassword = TestRandomUtil.nextBytes(16); + + existingAccount.setAccountRecoveryPassword(recoveryPassword); + + final int aciRegistrationId = 17; + final int pniRegistrationId = 19; + + final ECKeyPair aciKeyPair = ECKeyPair.generate(); + final ECKeyPair pniKeyPair = ECKeyPair.generate(); + final IdentityKey aciIdentityKey = new IdentityKey(aciKeyPair.getPublicKey()); + final IdentityKey pniIdentityKey = new IdentityKey(pniKeyPair.getPublicKey()); + final ECSignedPreKey aciSignedPreKey = KeysHelper.signedECPreKey(1, aciKeyPair); + final ECSignedPreKey pniSignedPreKey = KeysHelper.signedECPreKey(2, pniKeyPair); + final KEMSignedPreKey aciPqLastResortPreKey = KeysHelper.signedKEMPreKey(3, aciKeyPair); + final KEMSignedPreKey pniPqLastResortPreKey = KeysHelper.signedKEMPreKey(4, pniKeyPair); + + existingAccount.setNumber(PhoneNumberUtil.getInstance().format( + PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164), + UUID.randomUUID()); + + { + final AccountAttributes accountAttributes = new AccountAttributes(false, + aciRegistrationId, + pniRegistrationId, + TestRandomUtil.nextBytes(16), + "registration-lock", + true, + Collections.emptySet(), + recoveryPassword); + + final DeviceSpec primaryDeviceSpec = new DeviceSpec( + TestRandomUtil.nextBytes(16), + RandomStringUtils.insecure().nextAlphanumeric(12), + "test", + Collections.emptySet(), + new DeviceIdentityInfo(aciRegistrationId, aciSignedPreKey, aciPqLastResortPreKey), + Optional.of(new DeviceIdentityInfo(pniRegistrationId, pniSignedPreKey, pniPqLastResortPreKey)), + true, + Optional.empty(), + Optional.empty()); + + assertThrows(IllegalArgumentException.class, () -> accountsManager.recover(existingAccount, + accountAttributes, + aciIdentityKey, + Optional.empty(), + primaryDeviceSpec, + null)); + } + + existingAccount.setNumber(null, null); + + { + final AccountAttributes accountAttributes = new AccountAttributes(false, + aciRegistrationId, + null, + TestRandomUtil.nextBytes(16), + null, + false, + Collections.emptySet(), + recoveryPassword); + + final DeviceSpec primaryDeviceSpec = new DeviceSpec( + TestRandomUtil.nextBytes(16), + RandomStringUtils.insecure().nextAlphanumeric(12), + "test", + Collections.emptySet(), + new DeviceIdentityInfo(aciRegistrationId, aciSignedPreKey, aciPqLastResortPreKey), + Optional.empty(), + true, + Optional.empty(), + Optional.empty()); + + assertThrows(IllegalArgumentException.class, () -> accountsManager.recover(existingAccount, + accountAttributes, + aciIdentityKey, + Optional.of(pniIdentityKey), + primaryDeviceSpec, + null)); + } + } + @Test void testCreateAccountRecentlyDeleted() throws InterruptedException, AccountAlreadyExistsException { final UUID recentlyDeletedUuid = UUID.randomUUID(); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsTest.java index 1fe3b9e19..f686fb098 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsTest.java @@ -762,6 +762,38 @@ class AccountsTest { } + @Test + void testReclaimAccountExistingAccountVersionChange() { + final Device device = generateDevice(DEVICE_ID_1); + final String number = PhoneNumberUtil.getInstance().format( + PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164); + + final UUID existingUuid = UUID.randomUUID(); + final UUID existingPni = UUID.randomUUID(); + final byte[] accountRecoveryPassword = TestRandomUtil.nextBytes(16); + final Account existingAccount = generateAccount(number, existingUuid, existingPni, List.of(device), accountRecoveryPassword); + + createAccount(existingAccount); + + // Update the existing account without directly modifying the in-memory version so the stored version is out of + // sync with the in-memory version + { + final Account updatedExistingAccount = accounts.getByAccountIdentifier(existingUuid).orElseThrow(); + updatedExistingAccount.setUnrestrictedUnidentifiedAccess(!existingAccount.isUnrestrictedUnidentifiedAccess()); + + accounts.update(updatedExistingAccount); + } + + final Account reclaimedAccount = new Account(); + reclaimedAccount.setAccountIdentifier(existingAccount.getAccountIdentifier()); + reclaimedAccount.setNumber(number, existingPni); + + final CompletionException completionException = assertThrows(CompletionException.class, + () -> accounts.reclaimAccount(existingAccount, reclaimedAccount, Collections.emptyList()).toCompletableFuture().join()); + + assertInstanceOf(ContestedOptimisticLockException.class, completionException.getCause()); + } + @Test void testUpdateAccountWithMismatchedJsonDdbPhoneNumbers() { // Test that fixing the DynamoDB/JSON phone number mismatch does not break account updates for existing accounts