From 48954c9f620cf98024fbfa8f429eb3938252dfc1 Mon Sep 17 00:00:00 2001 From: Jon Chambers <63609320+jon-signal@users.noreply.github.com> Date: Tue, 18 Aug 2026 12:05:17 -0400 Subject: [PATCH] Scuttle deprecated phone number getters --- .../auth/CertificateGenerator.java | 4 +- .../auth/DisconnectionRequestManager.java | 2 +- .../RegistrationLockVerificationManager.java | 4 +- .../controllers/AccountController.java | 4 +- .../controllers/AccountControllerV2.java | 4 +- .../AccountIdentityResponseBuilder.java | 4 +- .../controllers/CertificateController.java | 2 +- .../controllers/DeviceController.java | 7 +- .../controllers/KeysController.java | 35 +++- .../controllers/MessageController.java | 8 +- .../controllers/ProfileController.java | 18 +- .../controllers/RegistrationController.java | 4 +- .../controllers/VerificationController.java | 2 +- .../textsecuregcm/entities/DeviceInfo.java | 8 +- .../IdleDevicePushNotificationExperiment.java | 2 +- .../grpc/AccountsGrpcService.java | 10 +- .../grpc/CredentialsGrpcService.java | 4 +- .../grpc/DevicesGrpcService.java | 6 +- .../grpc/KeysAnonymousGrpcService.java | 14 +- .../textsecuregcm/grpc/KeysGrpcHelper.java | 21 ++- .../textsecuregcm/grpc/KeysGrpcService.java | 25 ++- .../textsecuregcm/grpc/MessageDispatcher.java | 6 +- .../grpc/MessagesAnonymousGrpcService.java | 2 +- .../textsecuregcm/grpc/ProfileGrpcHelper.java | 2 +- .../push/IdleDeviceNotificationScheduler.java | 2 +- .../textsecuregcm/push/MessageSender.java | 12 +- .../push/PushNotificationManager.java | 2 +- .../textsecuregcm/push/ReceiptSender.java | 6 +- .../scheduler/SchedulingUtil.java | 4 +- .../textsecuregcm/storage/Account.java | 89 +--------- .../storage/AccountChangeValidator.java | 8 +- .../storage/AccountLockManager.java | 2 +- .../textsecuregcm/storage/Accounts.java | 58 +++---- .../storage/AccountsManager.java | 55 +++--- .../storage/ChangeNumberManager.java | 8 +- .../textsecuregcm/storage/Device.java | 21 --- .../storage/MessagePersister.java | 4 +- .../storage/MessagesManager.java | 2 +- .../storage/PhoneNumberIdentifiers.java | 4 +- .../storage/ReportMessageManager.java | 2 +- .../textsecuregcm/util/ProfileHelper.java | 2 +- .../textsecuregcm/util/Util.java | 4 +- .../AuthenticatedConnectListener.java | 4 +- .../websocket/WebSocketConnection.java | 6 +- ...earExpiredFoundationDbMessagesCommand.java | 2 +- .../workers/DeleteUserCommand.java | 4 +- .../workers/IdleWakeupEligibilityChecker.java | 4 +- .../workers/NotifyIdleDevicesCommand.java | 4 +- .../RemoveExpiredLinkedDevicesCommand.java | 2 +- .../RemoveExpiredUsernameHoldsCommand.java | 2 +- .../SetUserDiscoverabilityCommand.java | 2 +- ...tartPushNotificationExperimentCommand.java | 6 +- ...sizedFoundationDbMessageQueuesCommand.java | 2 +- .../UnlinkDevicesWithIdlePrimaryCommand.java | 2 +- .../auth/CertificateGeneratorTest.java | 4 +- .../auth/DisconnectionRequestManagerTest.java | 2 +- ...gistrationLockVerificationManagerTest.java | 8 +- .../backup/BackupAuthManagerTest.java | 2 +- .../controllers/AccountControllerTest.java | 4 +- .../controllers/AccountControllerV2Test.java | 10 +- .../AccountIdentityResponseBuilderTest.java | 8 +- .../controllers/DeviceControllerTest.java | 13 +- .../DirectoryControllerV2Test.java | 2 +- .../controllers/KeysControllerTest.java | 39 +++-- .../controllers/MessageControllerTest.java | 49 +++--- .../controllers/ProfileControllerTest.java | 15 +- .../RegistrationControllerTest.java | 10 +- .../VerificationControllerTest.java | 2 +- ...eDevicePushNotificationExperimentTest.java | 6 +- .../grpc/AccountsGrpcServiceTest.java | 18 +- .../grpc/CredentialsGrpcServiceTest.java | 8 +- .../grpc/DevicesGrpcServiceTest.java | 6 +- .../grpc/KeysAnonymousGrpcServiceTest.java | 21 ++- .../grpc/KeysGrpcServiceTest.java | 59 +++++-- .../MessageDispatcherIntegrationTest.java | 14 +- .../grpc/MessageDispatcherTest.java | 2 +- .../MessagesAnonymousGrpcServiceTest.java | 2 +- .../grpc/MessagesGrpcServiceTest.java | 8 +- .../grpc/ProfileAnonymousGrpcServiceTest.java | 6 +- .../grpc/ProfileGrpcServiceTest.java | 10 +- .../limits/RateLimitChallengeManagerTest.java | 2 +- .../metrics/MessageMetricsTest.java | 2 +- .../textsecuregcm/push/MessageSenderTest.java | 39 ++--- .../push/PushNotificationManagerTest.java | 6 +- .../push/PushNotificationSchedulerTest.java | 4 +- .../scheduler/SchedulingUtilTest.java | 6 +- .../storage/AccountChangeValidatorTest.java | 20 +-- ...ccountCreationDeletionIntegrationTest.java | 34 ++-- .../storage/AccountLockManagerTest.java | 4 +- .../textsecuregcm/storage/AccountTest.java | 4 +- ...ntsManagerChangeNumberIntegrationTest.java | 48 ++--- ...ConcurrentModificationIntegrationTest.java | 2 +- ...sManagerDeviceTransferIntegrationTest.java | 8 +- ...igrateRecoveryPasswordIntegrationTest.java | 2 +- .../storage/AccountsManagerTest.java | 111 ++++++------ .../textsecuregcm/storage/AccountsTest.java | 164 +++++++++--------- .../AddRemoveDeviceIntegrationTest.java | 80 +++++---- .../storage/ChangeNumberManagerTest.java | 25 ++- .../MessagePersisterIntegrationTest.java | 2 +- .../storage/MessagePersisterTest.java | 6 +- .../storage/MessagesManagerTest.java | 4 +- .../storage/PhoneNumberIdentifiersTest.java | 4 +- .../storage/ReportMessageManagerTest.java | 2 +- .../tests/util/AccountsHelper.java | 26 +-- .../textsecuregcm/tests/util/AuthHelper.java | 55 ++---- .../textsecuregcm/util/ProfileHelperTest.java | 6 +- ...ticatedConnectListenerIntegrationTest.java | 5 +- .../AuthenticatedConnectListenerTest.java | 2 +- .../WebSocketConnectionIntegrationTest.java | 19 +- .../websocket/WebSocketConnectionTest.java | 30 ++-- ...xpiredFoundationDbMessagesCommandTest.java | 2 +- .../IdleWakeupEligibilityCheckerTest.java | 12 +- .../workers/NotifyIdleDevicesCommandTest.java | 2 +- ...RemoveExpiredUsernameHoldsCommandTest.java | 2 +- ...PushNotificationExperimentCommandTest.java | 8 +- ...dFoundationDbMessageQueuesCommandTest.java | 2 +- ...linkDevicesWithIdlePrimaryCommandTest.java | 8 +- 117 files changed, 767 insertions(+), 842 deletions(-) diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/auth/CertificateGenerator.java b/service/src/main/java/org/whispersystems/textsecuregcm/auth/CertificateGenerator.java index 103e31874..d4591667f 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/auth/CertificateGenerator.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/auth/CertificateGenerator.java @@ -34,7 +34,7 @@ public class CertificateGenerator { } public byte[] createFor(final Account account, final byte deviceId, boolean includeE164) { - if (includeE164 && account.getNumberOptional().isEmpty()) { + if (includeE164 && account.getNumber().isEmpty()) { throw new IllegalArgumentException(); } @@ -45,7 +45,7 @@ public class CertificateGenerator { .setSenderUuid(UUIDUtil.toByteString(account.getAccountIdentifier())); if (includeE164) { - builder.setSenderE164(account.getNumberOptional().get()); + builder.setSenderE164(account.getNumber().get()); } if (embedSigner) { diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/auth/DisconnectionRequestManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/auth/DisconnectionRequestManager.java index 564732386..dc44ce139 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/auth/DisconnectionRequestManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/auth/DisconnectionRequestManager.java @@ -164,7 +164,7 @@ public class DisconnectionRequestManager extends RedisPubSubAdapter requestDisconnection(final Account account) { - return requestDisconnection(account.getIdentifier(IdentityType.ACI), + return requestDisconnection(account.getAccountIdentifier(), account.getDevices().stream().map(Device::getId).toList()); } 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 70173be58..1a6cf85a9 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/auth/RegistrationLockVerificationManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/auth/RegistrationLockVerificationManager.java @@ -87,7 +87,7 @@ public class RegistrationLockVerificationManager { final PhoneVerificationRequest.VerificationType phoneVerificationType ) throws RateLimitExceededException, RegistrationLockFailureException { - final String phoneNumber = account.getNumberOptional() + final String phoneNumber = account.getNumber() .orElseThrow(() -> new IllegalArgumentException("account does not have a phone number")); final Tags expiredTags = Tags.of(UserAgentTagUtil.getPlatformTag(userAgent), @@ -149,7 +149,7 @@ 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) { - additionalWriteItems = List.of(phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForRemovePassword(account.getPhoneNumberIdentifierOptional() + additionalWriteItems = List.of(phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForRemovePassword(account.getPhoneNumberIdentifier() .orElseThrow(() -> new AssertionError("Account with a phone number did not have a phone number identifier")))); } else { additionalWriteItems = Collections.emptyList(); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/AccountController.java b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/AccountController.java index 9bf76315e..8bd8c6ed3 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/AccountController.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/AccountController.java @@ -223,7 +223,7 @@ public class AccountController { .orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED)); final Collection additionalWriteItems = - account.getPhoneNumberIdentifierOptional() + account.getPhoneNumberIdentifier() .flatMap(phoneNumberIdentifier -> attributes.recoveryPassword().map(recoveryPassword -> List.of(phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForStorePassword(phoneNumberIdentifier, recoveryPassword)))) .orElseGet(Collections::emptyList); @@ -243,7 +243,7 @@ public class AccountController { a.setUnidentifiedAccessKey(attributes.getUnidentifiedAccessKey()); a.setUnrestrictedUnidentifiedAccess(attributes.isUnrestrictedUnidentifiedAccess()); - if (attributes.isDiscoverableByPhoneNumber() && a.getNumberOptional().isEmpty()) { + if (attributes.isDiscoverableByPhoneNumber() && a.getNumber().isEmpty()) { throw new BadRequestException("account does not have a phone number"); } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/AccountControllerV2.java b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/AccountControllerV2.java index fa354bc8d..d96737a0c 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/AccountControllerV2.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/AccountControllerV2.java @@ -156,7 +156,7 @@ public class AccountControllerV2 { @NotNull @Valid PhoneNumberDiscoverabilityRequest phoneNumberDiscoverability) { accountsManager.update(auth.accountIdentifier(), account -> { - if (account.getNumberOptional().isEmpty()) { + if (account.getNumber().isEmpty()) { throw new BadRequestException(); } @@ -179,7 +179,7 @@ public class AccountControllerV2 { return new AccountDataReportResponse(UUID.randomUUID(), Instant.now(), new AccountDataReportResponse.AccountAndDevicesDataReport( new AccountDataReportResponse.AccountDataReport( - account.getNumberOptional(), + account.getNumber(), account.getBadges().stream().map(AccountDataReportResponse.BadgeDataReport::new).toList(), account.isUnrestrictedUnidentifiedAccess(), account.isDiscoverableByPhoneNumber()), diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/AccountIdentityResponseBuilder.java b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/AccountIdentityResponseBuilder.java index e9a3305bd..90c9f6205 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/AccountIdentityResponseBuilder.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/AccountIdentityResponseBuilder.java @@ -48,8 +48,8 @@ public class AccountIdentityResponseBuilder { .orElse(null); return new AccountIdentityResponse(account.getAccountIdentifier(), - account.getNumberOptional(), - account.getPhoneNumberIdentifierOptional(), + account.getNumber(), + account.getPhoneNumberIdentifier(), account.getUsernameHash().filter(h -> h.length > 0).orElse(null), account.getUsernameLinkHandle(), storageCapable, diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/CertificateController.java b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/CertificateController.java index 522c4c201..e16d8d043 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/CertificateController.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/CertificateController.java @@ -113,7 +113,7 @@ public class CertificateController { final List callLinkAuthCredentials = new ArrayList<>(); final ServiceId.Aci aci = new ServiceId.Aci(account.getAccountIdentifier()); - final Optional maybePni = account.getPhoneNumberIdentifierOptional().map(ServiceId.Pni::new); + final Optional maybePni = account.getPhoneNumberIdentifier().map(ServiceId.Pni::new); for (Instant redemption : redemptionRange) { final AuthCredentialWithPniResponse authCredentialWithPni = diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/DeviceController.java b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/DeviceController.java index b69c01f88..8fba504d1 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/DeviceController.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/DeviceController.java @@ -42,13 +42,11 @@ import java.util.EnumMap; import java.util.List; import java.util.Locale; import java.util.Map; -import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletionStage; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import javax.annotation.Nullable; -import org.apache.commons.lang3.ObjectUtils; import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice; import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader; import org.whispersystems.textsecuregcm.auth.ChangesLinkedDevices; @@ -64,7 +62,6 @@ import org.whispersystems.textsecuregcm.entities.RemoteAttachment; import org.whispersystems.textsecuregcm.entities.RemoteAttachmentError; import org.whispersystems.textsecuregcm.entities.RestoreAccountRequest; import org.whispersystems.textsecuregcm.entities.TransferArchiveUploadedRequest; -import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.limits.RateLimitedByIp; import org.whispersystems.textsecuregcm.limits.RateLimiters; import org.whispersystems.textsecuregcm.metrics.DevicePlatformUtil; @@ -246,7 +243,7 @@ public class DeviceController { // Check the optional-phone-number capability before checking PNI keys, so we can give a better error code (since an // older device will improperly supply PNI keys for a PNI-less account) - if (account.getPhoneNumberIdentifierOptional().isEmpty() && + if (account.getPhoneNumberIdentifier().isEmpty() && !linkDeviceRequest.deviceAttributes().capabilities().contains(DeviceCapability.OPTIONAL_PHONE_NUMBER)) { throw new WebApplicationException("Missing required device capability", 409); } @@ -318,7 +315,7 @@ public class DeviceController { return new LinkDeviceResponse( accountAndDevice.first().getAccountIdentifier(), - accountAndDevice.first().getPhoneNumberIdentifierOptional(), + accountAndDevice.first().getPhoneNumberIdentifier(), accountAndDevice.second().getId()); } catch (final LinkDeviceTokenAlreadyUsedException e) { throw new ForbiddenException(); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/KeysController.java b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/KeysController.java index 746bd4108..3a511b304 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/KeysController.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/KeysController.java @@ -159,7 +159,7 @@ public class KeysController { final UUID identifier = getIdentifier(account, identityType); - checkSignedPreKeySignatures(setKeysRequest, account.getIdentityKey(identityType), userAgent); + checkSignedPreKeySignatures(setKeysRequest, getIdentityKey(account, identityType), userAgent); final Tag platformTag = UserAgentTagUtil.getPlatformTag(userAgent); final Tag primaryDeviceTag = Tag.of(PRIMARY_DEVICE_TAG_NAME, String.valueOf(auth.deviceId() == Device.PRIMARY_ID)); @@ -279,7 +279,7 @@ public class KeysController { final boolean digestsMatch; if (maybeSignedPreKey.isPresent() && maybeLastResortKey.isPresent()) { - final IdentityKey identityKey = account.getIdentityKey(checkKeysRequest.identityType()); + final IdentityKey identityKey = getIdentityKey(account, checkKeysRequest.identityType()); final ECSignedPreKey ecSignedPreKey = maybeSignedPreKey.get(); final KEMSignedPreKey lastResortKey = maybeLastResortKey.get(); @@ -384,7 +384,12 @@ public class KeysController { .fromCompletionStage(keysManager.takeDevicePreKeys(device.getId(), targetIdentifier, userAgent)) .flatMap(Mono::justOrEmpty) .map(devicePreKeys -> new PreKeyResponseItem( - device.getId(), device.getRegistrationId(targetIdentifier.identityType()), + device.getId(), + switch (targetIdentifier.identityType()) { + case ACI -> device.getAccountRegistrationId(); + case PNI -> device.getPhoneNumberIdentityRegistrationId() + .orElseThrow(() -> new IllegalStateException("Device on account retrieved by PNI does not have a PNI registration ID")); + }, devicePreKeys.ecSignedPreKey(), devicePreKeys.ecPreKey().orElse(null), devicePreKeys.kemSignedPreKey()))) @@ -392,7 +397,11 @@ public class KeysController { .blockOptional() .orElseGet(Collections::emptyList); - final IdentityKey identityKey = target.getIdentityKey(targetIdentifier.identityType()); + final IdentityKey identityKey = switch (targetIdentifier.identityType()) { + case ACI -> target.getAccountIdentityKey(); + case PNI -> target.getPhoneNumberIdentityKey() + .orElseThrow(() -> new IllegalStateException("Account retrieved by PNI does not have a PNI identity key")); + }; if (responseItems.isEmpty()) { throw new WebApplicationException(Response.Status.NOT_FOUND); @@ -428,7 +437,10 @@ public class KeysController { final Optional parsedTargetDeviceId = parseDeviceId(targetDeviceId); final Optional targetRegistrationId = parsedTargetDeviceId .flatMap(targetAccount::getDevice) - .map(device -> device.getRegistrationId(targetIdentifier.identityType())); + .flatMap(device -> switch (targetIdentifier.identityType()) { + case ACI -> Optional.of(device.getAccountRegistrationId()); + case PNI -> device.getPhoneNumberIdentityRegistrationId(); + }); return RateLimitKeys.preKeyLimiterKey( account.getAccountIdentifier(), authenticatedDevice.deviceId(), @@ -438,12 +450,19 @@ public class KeysController { /// Get the identity of the requested `idenityType`, or throw a [BadRequestException] if `account` does not contain /// that type. - private UUID getIdentifier(final Account account, final IdentityType identityType) { + private static UUID getIdentifier(final Account account, final IdentityType identityType) { return switch (identityType) { case ACI -> account.getAccountIdentifier(); - case PNI -> account.getPhoneNumberIdentifierOptional().orElseThrow(() -> - new BadRequestException("Cannot set PNI identity keys on an account without a number")); + case PNI -> account.getPhoneNumberIdentifier() + .orElseThrow(() -> new BadRequestException("Cannot set PNI identity keys on an account without a number")); }; } + private static IdentityKey getIdentityKey(final Account account, final IdentityType identityType) { + return switch (identityType) { + case ACI -> account.getAccountIdentityKey(); + case PNI -> account.getPhoneNumberIdentityKey() + .orElseThrow(() -> new BadRequestException("Account does not have a phone number")); + }; + } } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/MessageController.java b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/MessageController.java index a4bb1162f..d1556f57c 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/MessageController.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/MessageController.java @@ -605,7 +605,7 @@ public class MessageController { CompletableFuture.allOf(resolvedRecipients.values() .stream() - .map(account -> account.getIdentifier(IdentityType.ACI)) + .map(account -> account.getAccountIdentifier()) .map(accountIdentifier -> rateLimiters.getStoriesLimiter().validateAsync(accountIdentifier).toCompletableFuture()) .toList() @@ -746,7 +746,7 @@ public class MessageController { final Optional maybeAccount = accountsManager.getByE164(source); if (maybeAccount.isPresent()) { sourceAci = maybeAccount.map(Account::getAccountIdentifier); - sourcePni = maybeAccount.flatMap(Account::getPhoneNumberIdentifierOptional); + sourcePni = maybeAccount.flatMap(Account::getPhoneNumberIdentifier); } else { sourcePni = Optional.ofNullable(phoneNumberIdentifiers.getPhoneNumberIdentifier(source).join()); sourceAci = sourcePni.flatMap(accountsManager::findRecentlyDeletedAccountIdentifier); @@ -764,8 +764,8 @@ public class MessageController { Util.getCanonicalNumber(phoneNumberIdentifiers.getPhoneNumber(pni).join())); sourceAccountDeleted = true; } else { - sourceNumber = sourceAccount.flatMap(Account::getNumberOptional); - sourcePni = sourceAccount.flatMap(Account::getPhoneNumberIdentifierOptional); + sourceNumber = sourceAccount.flatMap(Account::getNumber); + sourcePni = sourceAccount.flatMap(Account::getPhoneNumberIdentifier); } } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/ProfileController.java b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/ProfileController.java index e32e9e776..816d1d8ae 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/ProfileController.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/ProfileController.java @@ -414,11 +414,17 @@ public class ProfileController { final Optional maybeAccount = accountsManager.getByServiceIdentifier(identifier); maybeAccount.ifPresent(account -> { - final IdentityKey identityKey = account.getIdentityKey(identifier.identityType()); - if (identityKey == null) { + final Optional maybeIdentityKey = switch (identifier.identityType()) { + case ACI -> Optional.of(account.getAccountIdentityKey()); + case PNI -> account.getPhoneNumberIdentityKey(); + }; + + if (maybeIdentityKey.isEmpty()) { return; } + final IdentityKey identityKey = maybeIdentityKey.get(); + md.reset(); byte[] digest = md.digest(identityKey.serialize()); byte[] fingerprint = Util.truncate(digest, 4); @@ -503,7 +509,7 @@ public class ProfileController { final boolean isSelf, final ContainerRequestContext containerRequestContext) { - return new BaseProfileResponse(account.getIdentityKey(IdentityType.ACI), + return new BaseProfileResponse(account.getAccountIdentityKey(), account.getUnidentifiedAccessKey().map(UnidentifiedAccessChecksum::generateFor).orElse(null), account.isUnrestrictedUnidentifiedAccess(), getAccountCapabilities(account), @@ -515,12 +521,14 @@ public class ProfileController { } private BaseProfileResponse buildBaseProfileResponseForPhoneNumberIdentity(final Account account) { - return new BaseProfileResponse(account.getIdentityKey(IdentityType.PNI), + return new BaseProfileResponse(account.getPhoneNumberIdentityKey() + .orElseThrow(() -> new IllegalStateException("Account retrieved by PNI does not have PNI identity key")), null, false, getAccountCapabilities(account), Collections.emptyList(), - new PniServiceIdentifier(account.getPhoneNumberIdentifier())); + new PniServiceIdentifier(account.getPhoneNumberIdentifier() + .orElseThrow(() -> new IllegalStateException("Account retrieved by PNI does not have PNI")))); } /** 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 b80bcd3c5..8c4a95323 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/RegistrationController.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/RegistrationController.java @@ -268,7 +268,7 @@ public class RegistrationController { } if (existingAccount.isPresent()) { - assert existingAccount.get().getNumberOptional().isPresent(); + assert existingAccount.get().getNumber().isPresent(); registrationLockVerificationManager.verifyRegistrationLock(existingAccount.get(), registrationRequest.accountAttributes().getRegistrationLock(), userAgent, RegistrationLockVerificationManager.Flow.REGISTRATION, verificationType); @@ -426,7 +426,7 @@ public class RegistrationController { throw new WebApplicationException(Response.status(409, "device transfer available").build()); } - final Account reclaimedAccount = existingAccount.getNumberOptional().isPresent() + final Account reclaimedAccount = existingAccount.getNumber().isPresent() ? recoverAccountWithPhoneNumber(existingAccount, registrationRequest, password, userAgent, signalAgent) : recoverAccountWithoutPhoneNumber(existingAccount, registrationRequest, password, userAgent, signalAgent); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/VerificationController.java b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/VerificationController.java index 6796ed45b..722e2daed 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/VerificationController.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/VerificationController.java @@ -666,7 +666,7 @@ public class VerificationController { accountsManager.getByE164(registrationServiceSession.number()) .filter(existingAccount -> - experimentEnrollmentManager.isEnrolled(existingAccount.getIdentifier(IdentityType.ACI), VERIFICATION_CODE_PUSH_NOTIFICATION_EXPERIMENT_NAME)) + experimentEnrollmentManager.isEnrolled(existingAccount.getAccountIdentifier(), VERIFICATION_CODE_PUSH_NOTIFICATION_EXPERIMENT_NAME)) .ifPresent(existingAccount -> { try { pushNotificationManager.sendVerificationCodeRequestedNotifications(existingAccount, clock.instant()); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/entities/DeviceInfo.java b/service/src/main/java/org/whispersystems/textsecuregcm/entities/DeviceInfo.java index b640340a4..aa2e2b6e4 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/entities/DeviceInfo.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/entities/DeviceInfo.java @@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.entities; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import io.swagger.v3.oas.annotations.media.Schema; -import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.storage.Device; import org.whispersystems.textsecuregcm.util.ByteArrayAdapter; import org.whispersystems.textsecuregcm.util.ByteArrayBase64WithPaddingAdapter; @@ -33,7 +32,10 @@ public record DeviceInfo(long id, byte[] createdAtCiphertext) { public static DeviceInfo forDevice(final Device device) { - return new DeviceInfo(device.getId(), device.getName(), device.getLastSeen(), device.getRegistrationId( - IdentityType.ACI), device.getCreatedAtCiphertext()); + return new DeviceInfo(device.getId(), + device.getName(), + device.getLastSeen(), + device.getAccountRegistrationId(), + device.getCreatedAtCiphertext()); } } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/experiment/IdleDevicePushNotificationExperiment.java b/service/src/main/java/org/whispersystems/textsecuregcm/experiment/IdleDevicePushNotificationExperiment.java index c44aea9b5..2d8c9ca22 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/experiment/IdleDevicePushNotificationExperiment.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/experiment/IdleDevicePushNotificationExperiment.java @@ -65,7 +65,7 @@ abstract class IdleDevicePushNotificationExperiment implements PushNotificationE } else { pushTokenType = null; } - return new DeviceLastSeenState(true, device.getRegistrationId(IdentityType.ACI), hasPushToken(device), device.getLastSeen(), pushTokenType); + return new DeviceLastSeenState(true, device.getAccountRegistrationId(), hasPushToken(device), device.getLastSeen(), pushTokenType); } else { return DeviceLastSeenState.MISSING_DEVICE_STATE; } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/AccountsGrpcService.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/AccountsGrpcService.java index 960b1ab50..a15e3b33f 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/AccountsGrpcService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/AccountsGrpcService.java @@ -317,7 +317,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase { public SetDiscoverableByPhoneNumberResponse setDiscoverableByPhoneNumber(final SetDiscoverableByPhoneNumberRequest request) { accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(), account -> { - if (account.getNumberOptional().isEmpty()) { + if (account.getNumber().isEmpty()) { throw GrpcExceptions.invalidArguments("account does not have a phone number"); } @@ -332,7 +332,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase { final Account account = getAuthenticatedAccount(); final byte[] recoveryPassword = request.getRegistrationRecoveryPassword().toByteArray(); - final Collection additionalWriteItems = account.getPhoneNumberIdentifierOptional() + final Collection additionalWriteItems = account.getPhoneNumberIdentifier() .map(phoneNumberIdentifier -> List.of(phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForStorePassword(phoneNumberIdentifier, recoveryPassword))) .orElseGet(Collections::emptyList); @@ -505,7 +505,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase { final AccountDataReportResponse report = new AccountDataReportResponse(UUID.randomUUID(), clock.instant(), new AccountDataReportResponse.AccountAndDevicesDataReport( new AccountDataReportResponse.AccountDataReport( - account.getNumberOptional(), + account.getNumber(), account.getBadges().stream().map(AccountDataReportResponse.BadgeDataReport::new).toList(), account.isUnrestrictedUnidentifiedAccess(), account.isDiscoverableByPhoneNumber()), @@ -538,11 +538,11 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase { final AccountIdentifiers.Builder accountIdentifiersBuilder = AccountIdentifiers.newBuilder() .addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getAccountIdentifier()))); - account.getPhoneNumberIdentifierOptional() + account.getPhoneNumberIdentifier() .map(phoneNumberIdentifier -> GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new PniServiceIdentifier(phoneNumberIdentifier))) .ifPresent(accountIdentifiersBuilder::addServiceIdentifiers); - account.getNumberOptional().ifPresent(accountIdentifiersBuilder::setE164); + account.getNumber().ifPresent(accountIdentifiersBuilder::setE164); account.getUsernameHash().ifPresent(usernameHash -> accountIdentifiersBuilder.setUsernameHash(ByteString.copyFrom(usernameHash))); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/CredentialsGrpcService.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/CredentialsGrpcService.java index 768833935..d232f0a9a 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/CredentialsGrpcService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/CredentialsGrpcService.java @@ -98,7 +98,7 @@ public class CredentialsGrpcService extends SimpleCredentialsGrpc.CredentialsImp .setCertificateWithoutE164(ByteString.copyFrom( certificateGenerator.createFor(account, authenticatedDevice.deviceId(), false))); - if (account.getNumberOptional().isPresent()) { + if (account.getNumber().isPresent()) { responseBuilder.setCertificateWithE164(ByteString.copyFrom( certificateGenerator.createFor(account, authenticatedDevice.deviceId(), true))); } @@ -123,7 +123,7 @@ public class CredentialsGrpcService extends SimpleCredentialsGrpc.CredentialsImp .orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials")); final ServiceId.Aci aci = new ServiceId.Aci(account.getAccountIdentifier()); - final Optional maybePni = account.getPhoneNumberIdentifierOptional().map(ServiceId.Pni::new); + final Optional maybePni = account.getPhoneNumberIdentifier().map(ServiceId.Pni::new); final GetGroupCredentialsResponse.Builder responseBuilder = GetGroupCredentialsResponse.newBuilder(); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/DevicesGrpcService.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/DevicesGrpcService.java index 916228067..3dd5a0f1f 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/DevicesGrpcService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/DevicesGrpcService.java @@ -54,7 +54,7 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase { GetDevicesResponse.LinkedDevice.newBuilder() .setId(device.getId()) .setLastSeen(device.getLastSeen()) - .setRegistrationId(device.getRegistrationId(IdentityType.ACI)) + .setRegistrationId(device.getAccountRegistrationId()) .setCreatedAtCiphertext(ByteString.copyFrom(device.getCreatedAtCiphertext())); if (device.getName() != null) { @@ -104,7 +104,7 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase { return SetDeviceNameResponse.newBuilder().setTargetDeviceNotFound(NotFound.getDefaultInstance()).build(); } - accountsManager.updateDevice(account.getIdentifier(IdentityType.ACI), deviceId, device -> device.setName(request.getName().toByteArray())); + accountsManager.updateDevice(account.getAccountIdentifier(), deviceId, device -> device.setName(request.getName().toByteArray())); return SetDeviceNameResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build(); } @@ -141,7 +141,7 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase { // Unlike FCM tokens, we need current "last updated" timestamps for APNs tokens and so update device records // unconditionally if it's an APNS request if (request.hasApnsTokenRequest() || !Objects.equals(device.getGcmId(), fcmToken)) { - accountsManager.updateDevice(account.getIdentifier(IdentityType.ACI), authenticatedDevice.deviceId(), d -> { + accountsManager.updateDevice(account.getAccountIdentifier(), authenticatedDevice.deviceId(), d -> { d.setApnId(apnsToken); d.setGcmId(fcmToken); d.setFetchesMessages(false); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/KeysAnonymousGrpcService.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/KeysAnonymousGrpcService.java index 784bd5eff..47ad5972c 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/KeysAnonymousGrpcService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/KeysAnonymousGrpcService.java @@ -10,6 +10,7 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.time.Clock; import java.util.Arrays; +import java.util.Optional; import java.util.concurrent.Flow; import org.signal.chat.errors.FailedUnidentifiedAuthorization; import org.signal.chat.errors.NotFound; @@ -94,14 +95,17 @@ public class KeysAnonymousGrpcService extends SimpleKeysAnonymousGrpc.KeysAnonym request.getFingerprint().toByteArray())) .flatMap(serviceIdentifierAndFingerprint -> Mono.fromFuture( () -> accountsManager.getByServiceIdentifierAsync(serviceIdentifierAndFingerprint.getT1())) + .map(maybeAccount -> maybeAccount.flatMap( + account -> switch (serviceIdentifierAndFingerprint.getT1().identityType()) { + case ACI -> Optional.of(account.getAccountIdentityKey()); + case PNI -> account.getPhoneNumberIdentityKey(); + })) .flatMap(Mono::justOrEmpty) - .filter(account -> !fingerprintMatches(account.getIdentityKey(serviceIdentifierAndFingerprint.getT1() - .identityType()), serviceIdentifierAndFingerprint.getT2())) - .map(account -> CheckIdentityKeyResponse.newBuilder() + .filter(identityKey -> !fingerprintMatches(identityKey, serviceIdentifierAndFingerprint.getT2())) + .map(identityKey -> CheckIdentityKeyResponse.newBuilder() .setTargetIdentifier( GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifierAndFingerprint.getT1())) - .setIdentityKey(ByteString.copyFrom(account.getIdentityKey(serviceIdentifierAndFingerprint.getT1() - .identityType()).serialize())) + .setIdentityKey(ByteString.copyFrom(identityKey.serialize())) .build()))); } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/KeysGrpcHelper.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/KeysGrpcHelper.java index f9a2868fb..2e57d0978 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/KeysGrpcHelper.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/KeysGrpcHelper.java @@ -6,13 +6,12 @@ package org.whispersystems.textsecuregcm.grpc; import com.google.protobuf.ByteString; -import java.util.Arrays; +import io.grpc.StatusRuntimeException; import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import java.util.stream.Stream; -import io.grpc.StatusRuntimeException; import org.signal.chat.common.EcPreKey; import org.signal.chat.common.EcSignedPreKey; import org.signal.chat.common.KemSignedPreKey; @@ -22,15 +21,14 @@ import org.signal.libsignal.protocol.IdentityKey; import org.signal.libsignal.protocol.InvalidKeyException; import org.signal.libsignal.protocol.ecc.ECPublicKey; import org.signal.libsignal.protocol.kem.KEMPublicKey; +import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum; import org.whispersystems.textsecuregcm.entities.ECPreKey; import org.whispersystems.textsecuregcm.entities.ECSignedPreKey; import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey; -import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum; import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.identity.ServiceIdentifier; import org.whispersystems.textsecuregcm.storage.Account; import org.whispersystems.textsecuregcm.storage.Device; -import org.whispersystems.textsecuregcm.storage.DeviceCapability; import org.whispersystems.textsecuregcm.storage.KeyIdUtil; import org.whispersystems.textsecuregcm.storage.KeysManager; @@ -74,8 +72,14 @@ class KeysGrpcHelper { return Optional.empty(); } + final IdentityKey identityKey = switch (targetServiceIdentifier.identityType()) { + case ACI -> targetAccount.getAccountIdentityKey(); + case PNI -> targetAccount.getPhoneNumberIdentityKey() + .orElseThrow(() -> new IllegalArgumentException("Target account does not have a PNI identity key")); + }; + final AccountPreKeyBundles.Builder preKeyBundlesBuilder = AccountPreKeyBundles.newBuilder() - .setIdentityKey(ByteString.copyFrom(targetAccount.getIdentityKey(targetServiceIdentifier.identityType()).serialize())) + .setIdentityKey(ByteString.copyFrom(identityKey.serialize())) .setUnrestrictedUnidentifiedAccess(targetServiceIdentifier.identityType() == IdentityType.ACI && targetAccount.isUnrestrictedUnidentifiedAccess()); // Set the UAK hash if the account has a UAK and we're targeting an ACI. PNIs don't allow unidentified access. @@ -89,6 +93,11 @@ class KeysGrpcHelper { preKeysByDeviceId.forEach((deviceId, devicePreKeys) -> { final Device device = targetAccount.getDevice(deviceId).orElseThrow(); + final int registrationId = switch (targetServiceIdentifier.identityType()) { + case ACI -> device.getAccountRegistrationId(); + case PNI -> device.getPhoneNumberIdentityRegistrationId() + .orElseThrow(() -> new IllegalArgumentException("Device does not have a PNI registration ID")); + }; final DevicePreKeyBundle.Builder builder = DevicePreKeyBundle.newBuilder() .setEcSignedPreKey(EcSignedPreKey.newBuilder() @@ -99,7 +108,7 @@ class KeysGrpcHelper { .setKeyId(KeyIdUtil.toUnsignedInt(devicePreKeys.kemSignedPreKey().keyId())) .setPublicKey(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().serializedPublicKey())) .setSignature(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().signature()))) - .setRegistrationId(device.getRegistrationId(targetServiceIdentifier.identityType())); + .setRegistrationId(registrationId); devicePreKeys.ecPreKey().ifPresent(ecPreKey -> builder.setEcOneTimePreKey(EcPreKey.newBuilder() .setKeyId(KeyIdUtil.toUnsignedInt(ecPreKey.keyId())) diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/KeysGrpcService.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/KeysGrpcService.java index 66470c274..06caff5a7 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/KeysGrpcService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/KeysGrpcService.java @@ -65,14 +65,14 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase { final CompletableFuture aciEcKeyCountFuture = keysManager.getEcCount(aci, authenticatedDevice.deviceId()); - final CompletableFuture pniEcKeyCountFuture = account.getPhoneNumberIdentifierOptional() + final CompletableFuture pniEcKeyCountFuture = account.getPhoneNumberIdentifier() .map(pni -> keysManager.getEcCount(pni, authenticatedDevice.deviceId())) .orElseGet(() -> CompletableFuture.completedFuture(0)); final CompletableFuture aciKemKeyCountFuture = keysManager.getPqCount(aci, authenticatedDevice.deviceId()); - final CompletableFuture pniKemKeyCountFuture = account.getPhoneNumberIdentifierOptional() + final CompletableFuture pniKemKeyCountFuture = account.getPhoneNumberIdentifier() .map(pni -> keysManager.getPqCount(pni, authenticatedDevice.deviceId())) .orElseGet(() -> CompletableFuture.completedFuture(0)); @@ -103,7 +103,10 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase { final Optional targetRegistrationId = maybeTargetAccount .filter(_ -> request.hasDeviceId()) .flatMap(targetAccount -> targetAccount.getDevice(deviceId)) - .map(device -> device.getRegistrationId(targetIdentifier.identityType())); + .flatMap(device -> switch (targetIdentifier.identityType()) { + case ACI -> Optional.of(device.getAccountRegistrationId()); + case PNI -> device.getPhoneNumberIdentityRegistrationId(); + }); final String rateLimitKey = RateLimitKeys.preKeyLimiterKey( authenticatedDevice.accountIdentifier(), @@ -158,10 +161,16 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase { final Account account = getAuthenticatedAccount(authenticatedAccountUuid); + final IdentityKey identityKey = switch (identityType) { + case ACI -> account.getAccountIdentityKey(); + case PNI -> account.getPhoneNumberIdentityKey() + .orElseThrow(() -> new IllegalArgumentException("Account does not have a PNI identity key")); + }; + final UUID identifier = getIdentifier(account, identityType); final List preKeys = requestPreKeys.stream() - .map(requestPreKey -> extractPreKeyFunction.apply(requestPreKey, account.getIdentityKey(identityType))) + .map(requestPreKey -> extractPreKeyFunction.apply(requestPreKey, identityKey)) .toList(); storeKeysFunction.apply(identifier, preKeys).join(); @@ -200,9 +209,13 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase { final BiFunction> storeKeyFunction) { final Account account = getAuthenticatedAccount(authenticatedAccountUuid); + final IdentityKey identityKey = switch (identityType) { + case ACI -> account.getAccountIdentityKey(); + case PNI -> account.getPhoneNumberIdentityKey() + .orElseThrow(() -> new IllegalArgumentException("Account does not have a PNI identity key")); + }; final UUID identifier = getIdentifier(account, identityType); - final IdentityKey identityKey = account.getIdentityKey(identityType); final K key = extractKeyFunction.apply(storeKeyRequest, identityKey); storeKeyFunction.apply(identifier, key).join(); @@ -218,7 +231,7 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase { private static UUID getIdentifier(Account account, IdentityType identityType) { return switch (identityType) { case ACI -> account.getAccountIdentifier(); - case PNI -> account.getPhoneNumberIdentifierOptional() + case PNI -> account.getPhoneNumberIdentifier() .orElseThrow(() -> GrpcExceptions.invalidArguments("PNI identity type not allowed for an account without a phone number")); }; } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/MessageDispatcher.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/MessageDispatcher.java index a2593ae4e..4977fdb72 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/MessageDispatcher.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/MessageDispatcher.java @@ -130,7 +130,7 @@ public class MessageDispatcher { final Device device, final Flux acknowledgedMessageGuids) { - final MessageStream messageStream = messagesManager.getMessages(account.getIdentifier(IdentityType.ACI), device); + final MessageStream messageStream = messagesManager.getMessages(account.getAccountIdentifier(), device); @Nullable final UserAgent userAgent = UserAgentUtil.maybeParseUserAgentString(userAgentString); final PendingAcknowledgementTracker pendingAcknowledgementTracker = new PendingAcknowledgementTracker(messageMetrics, userAgent); @@ -213,7 +213,7 @@ public class MessageDispatcher { /// If the device potentially has more messages available, schedule a push notification. private void maybeSchedulePush(final Account account, final Device device) { - messagesManager.mayHaveMessages(account.getIdentifier(IdentityType.ACI), device) + messagesManager.mayHaveMessages(account.getAccountIdentifier(), device) .thenAccept(mayHaveMessages -> { if (mayHaveMessages) { pushNotificationScheduler.scheduleDelayedNotification(account, device, @@ -240,7 +240,7 @@ public class MessageDispatcher { private void recordDeliveryAttempt(final Account account, final Device device, final String userAgent, final Signal firstEntry) { if (firstEntry.get() instanceof MessageStreamEntry.Envelope(final MessageProtos.Envelope message)) { - messageDeliveryLoopMonitor.recordDeliveryAttempt(account.getIdentifier(IdentityType.ACI), + messageDeliveryLoopMonitor.recordDeliveryAttempt(account.getAccountIdentifier(), device.getId(), UUIDUtil.fromByteString(message.getServerGuid()), userAgent, diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/MessagesAnonymousGrpcService.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/MessagesAnonymousGrpcService.java index 669498a9c..69d6b33ab 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/MessagesAnonymousGrpcService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/MessagesAnonymousGrpcService.java @@ -143,7 +143,7 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me final Account destination = maybeDestination.get(); - rateLimiters.getStoriesLimiter().validate(destination.getIdentifier(IdentityType.ACI)); + rateLimiters.getStoriesLimiter().validate(destination.getAccountIdentifier()); return sendIndividualMessage(destination, destinationServiceIdentifier, diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcHelper.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcHelper.java index b9fd8414f..563e0f9b6 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcHelper.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcHelper.java @@ -110,7 +110,7 @@ public class ProfileGrpcHelper { final Account account) { final AccountInfo.Builder accountInfoBuilder = AccountInfo.newBuilder() .addAllBadgeIds(profileBadgeConverter.visibleBadgeIds(account.getBadges())) - .setIdentityKey(ByteString.copyFrom(account.getIdentityKey(IdentityType.ACI).serialize())) + .setIdentityKey(ByteString.copyFrom(account.getAccountIdentityKey().serialize())) .setUnrestrictedUnidentifiedAccess(account.isUnrestrictedUnidentifiedAccess()); account.getUnidentifiedAccessKey() diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/push/IdleDeviceNotificationScheduler.java b/service/src/main/java/org/whispersystems/textsecuregcm/push/IdleDeviceNotificationScheduler.java index 59625d6d1..c5057c13a 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/push/IdleDeviceNotificationScheduler.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/push/IdleDeviceNotificationScheduler.java @@ -81,7 +81,7 @@ public class IdleDeviceNotificationScheduler extends JobScheduler { try { return scheduleJob(runAt, SystemMapper.jsonMapper().writeValueAsBytes( - new JobDescriptor(account.getIdentifier(IdentityType.ACI), device.getId(), device.getLastSeen()))); + new JobDescriptor(account.getAccountIdentifier(), device.getId(), device.getLastSeen()))); } catch (final JsonProcessingException e) { // This should never happen when serializing an `AccountAndDeviceIdentifier` throw new AssertionError(e); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/push/MessageSender.java b/service/src/main/java/org/whispersystems/textsecuregcm/push/MessageSender.java index 9a2ce91d6..e7e30bf73 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/push/MessageSender.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/push/MessageSender.java @@ -30,7 +30,6 @@ import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedExc import org.whispersystems.textsecuregcm.controllers.MismatchedDevices; import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException; import org.whispersystems.textsecuregcm.controllers.MultiRecipientMismatchedDevicesException; -import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.identity.ServiceIdentifier; import org.whispersystems.textsecuregcm.metrics.MetricsUtil; import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil; @@ -131,7 +130,7 @@ public class MessageSender { syncMessageSenderDeviceId, platformTag); - messagesManager.insert(destination.getIdentifier(IdentityType.ACI), messagesByDeviceId) + messagesManager.insert(destination.getAccountIdentifier(), messagesByDeviceId) .forEach((deviceId, destinationPresent) -> { final Envelope message = messagesByDeviceId.get(deviceId); @@ -409,9 +408,14 @@ public class MessageSender { // We know the device must be present because we've already filtered out device IDs that aren't associated // with the given account final Device device = account.getDevice(deviceId).orElseThrow(); - final int expectedRegistrationId = device.getRegistrationId(serviceIdentifier.identityType()); + final Optional maybeExpectedRegistrationId = switch (serviceIdentifier.identityType()) { + case ACI -> Optional.of(device.getAccountRegistrationId()); + case PNI -> device.getPhoneNumberIdentityRegistrationId(); + }; - return registrationId != expectedRegistrationId; + return maybeExpectedRegistrationId + .map(expectedRegistrationId -> registrationId != expectedRegistrationId) + .orElse(true); }) .map(Map.Entry::getKey) .collect(Collectors.toSet()); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/push/PushNotificationManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/push/PushNotificationManager.java index 796ccf204..6b4c2262c 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/push/PushNotificationManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/push/PushNotificationManager.java @@ -217,7 +217,7 @@ public class PushNotificationManager { // updating an uninstalled feedback timestamp though. accountsManager.getByAccountIdentifier(account.getAccountIdentifier()).ifPresent(rereadAccount -> rereadAccount.getDevice(device.getId()).ifPresent(rereadDevice -> - accountsManager.updateDevice(rereadAccount.getIdentifier(IdentityType.ACI), device.getId(), d -> { + accountsManager.updateDevice(rereadAccount.getAccountIdentifier(), device.getId(), d -> { // Don't clear the token if it's already changed if (originalToken.equals(getPushToken(d, tokenType))) { switch (tokenType) { diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/push/ReceiptSender.java b/service/src/main/java/org/whispersystems/textsecuregcm/push/ReceiptSender.java index 9fd934e07..926a08f21 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/push/ReceiptSender.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/push/ReceiptSender.java @@ -57,7 +57,11 @@ public class ReceiptSender { final Map registrationIdsByDeviceId = destinationAccount.getDevices().stream() .collect(Collectors.toMap(Device::getId, - device -> device.getRegistrationId(destinationIdentifier.identityType()))); + device -> switch (destinationIdentifier.identityType()) { + case ACI -> device.getAccountRegistrationId(); + case PNI -> device.getPhoneNumberIdentityRegistrationId() + .orElseThrow(() -> new IllegalStateException("Destination account identified by PNI has device without PNI registration ID")); + })); try { messageSender.sendMessages(destinationAccount, diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/scheduler/SchedulingUtil.java b/service/src/main/java/org/whispersystems/textsecuregcm/scheduler/SchedulingUtil.java index f8ed4ef80..41b831eba 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/scheduler/SchedulingUtil.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/scheduler/SchedulingUtil.java @@ -42,14 +42,14 @@ public class SchedulingUtil { final LocalTime preferredTime, final Clock clock) { - final ZonedDateTime candidateNotificationTime = account.getNumberOptional() + final ZonedDateTime candidateNotificationTime = account.getNumber() .flatMap(number -> getZoneId(number, clock)) .map(zoneId -> { Metrics.counter(PARSED_TIMEZONE_COUNTER_NAME, HAS_TIMEZONE_TAG_NAME, String.valueOf(true)).increment(); return ZonedDateTime.now(clock.withZone(zoneId)).with(preferredTime); }) .orElseGet(() -> { - if (account.getNumberOptional().isPresent()) { + if (account.getNumber().isPresent()) { Metrics.counter(PARSED_TIMEZONE_COUNTER_NAME, HAS_TIMEZONE_TAG_NAME, String.valueOf(false)).increment(); } return ZonedDateTime.now(ZoneId.systemDefault()).with(preferredTime); 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 68acb120a..75bbc1847 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/Account.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/Account.java @@ -24,11 +24,9 @@ import java.util.Base64; import java.util.Collections; import java.util.HexFormat; import java.util.List; -import java.util.NoSuchElementException; import java.util.Objects; import java.util.Optional; import java.util.UUID; -import java.util.stream.Stream; import javax.annotation.Nullable; import org.apache.commons.lang3.StringUtils; import org.signal.libsignal.protocol.IdentityKey; @@ -39,9 +37,6 @@ import org.slf4j.LoggerFactory; import org.whispersystems.textsecuregcm.auth.SaltedTokenHash; import org.whispersystems.textsecuregcm.auth.StoredRegistrationLock; import org.whispersystems.textsecuregcm.entities.AccountAttributes; -import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; -import org.whispersystems.textsecuregcm.identity.IdentityType; -import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier; import org.whispersystems.textsecuregcm.identity.ServiceIdentifier; import org.whispersystems.textsecuregcm.util.ByteArrayBase64UrlAdapter; import org.whispersystems.textsecuregcm.util.IdentityKeyAdapter; @@ -167,26 +162,6 @@ public class Account { public record BackupVoucher(@JsonProperty("rl") long receiptLevel, @JsonProperty("e") Instant expiration) {} - /// Returns an identifier for the given identity type for this account with the assumption that all accounts have - /// identifiers for all identity types. - /// - /// @param identityType the identity type for which to retrieve an account identifier - /// - /// @return the identifier for the given identity type - /// - /// @throws NoSuchElementException if the account does not have an identifier for the given identity type - /// - /// @deprecated Different identity types have significantly differing presence and staleness requirements/guarantees - /// for their respective account identifiers. Please use [#getAccountIdentifier()] or - /// [#getPhoneNumberIdentifierOptional()] instead. - @Deprecated - public UUID getIdentifier(final IdentityType identityType) { - return switch (identityType) { - case ACI -> getAccountIdentifier(); - case PNI -> getPhoneNumberIdentifier(); - }; - } - /// Returns the core account identifier (ACI) for this account. An account's core identifier never changes. /// /// @return the core account identifier for this account @@ -201,28 +176,10 @@ public class Account { this.uuid = accountIdentifier; } - /// Returns the phone number identifier for this account. - /// - /// @throws NoSuchElementException if this account does not have a phone number identifier - /// - /// @return the phone number identifier for this account - /// - /// @deprecated Please use [#getPhoneNumberIdentifierOptional()] (which has clearer presence semantics) instead. - @Deprecated - public UUID getPhoneNumberIdentifier() { - requireNotStale(); - - if (phoneNumberIdentifier == null) { - throw new NoSuchElementException(); - } - - return phoneNumberIdentifier; - } - /// Returns the phone number identifier for this account or empty if this account does not have a phone number. /// /// @return the phone number identifier for this account or empty if this account does not have a phone number - public Optional getPhoneNumberIdentifierOptional() { + public Optional getPhoneNumberIdentifier() { requireNotStale(); return Optional.ofNullable(phoneNumberIdentifier); @@ -240,26 +197,10 @@ public class Account { }; } - /// Returns the E.164-formatted phone number for this account. - /// - /// @return the E.164-formatted phone number for this account - /// - /// @throws NoSuchElementException if this account does not have a phone number - @Deprecated - public String getNumber() { - requireNotStale(); - - if (number == null) { - throw new NoSuchElementException(); - } - - return number; - } - /// Returns the phone number for this account or empty if this account does not have a phone number. /// /// @return the phone number for this account or empty if this account does not have a phone number - public Optional getNumberOptional() { + public Optional getNumber() { requireNotStale(); return Optional.ofNullable(number); @@ -393,28 +334,6 @@ public class Account { this.identityKey = identityKey; } - /// Returns an identity key for the given identity type for this account with the assumption that all accounts have - /// identity keys for all identity types. - /// - /// @param identityType the identity type for which to retrieve an identity key - /// - /// @return the identity key for the given identity type - /// - /// @throws NoSuchElementException if the account does not have an identifier (and therefore identity key) for the given identity type - /// - /// @deprecated Different identity types have significantly differing existence requirements/guarantees - /// for their respective identity keys. Please use [#getAccountIdentityKey()] or - /// [#getPhoneNumberIdentityKey()] instead. - @Deprecated - public IdentityKey getIdentityKey(final IdentityType identityType) { - requireNotStale(); - - return switch (identityType) { - case ACI -> identityKey; - case PNI -> Optional.ofNullable(phoneNumberIdentityKey).orElseThrow(NoSuchElementException::new); - }; - } - /// Returns an identity key for the ACI identity for this account. public IdentityKey getAccountIdentityKey() { requireNotStale(); @@ -591,12 +510,12 @@ public class Account { /// @return `true` if this account has a phone number and has opted into discovery by phone number or `false` /// otherwise /// - /// @see #getPhoneNumberIdentifierOptional() + /// @see #getPhoneNumberIdentifier() /// @see #setDiscoverableByPhoneNumber(boolean) public boolean isDiscoverableByPhoneNumber() { requireNotStale(); - return getPhoneNumberIdentifierOptional().isPresent() && this.discoverableByPhoneNumber; + return getPhoneNumberIdentifier().isPresent() && this.discoverableByPhoneNumber; } public void setDiscoverableByPhoneNumber(final boolean discoverableByPhoneNumber) { diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountChangeValidator.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountChangeValidator.java index 4d8cab062..d875e117c 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountChangeValidator.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountChangeValidator.java @@ -32,16 +32,16 @@ class AccountChangeValidator { public void validateChange(final Account originalAccount, final Account updatedAccount) { if (!allowNumberChange) { - assert updatedAccount.getNumberOptional().equals(originalAccount.getNumberOptional()); + assert updatedAccount.getNumber().equals(originalAccount.getNumber()); - if (!updatedAccount.getNumberOptional().equals(originalAccount.getNumberOptional())) { + if (!updatedAccount.getNumber().equals(originalAccount.getNumber())) { logger.error("Account number changed via \"normal\" update; numbers must be changed via changeNumber method", new RuntimeException()); } - assert updatedAccount.getPhoneNumberIdentifierOptional().equals(originalAccount.getPhoneNumberIdentifierOptional()); + assert updatedAccount.getPhoneNumberIdentifier().equals(originalAccount.getPhoneNumberIdentifier()); - if (!updatedAccount.getPhoneNumberIdentifierOptional().equals(originalAccount.getPhoneNumberIdentifierOptional())) { + if (!updatedAccount.getPhoneNumberIdentifier().equals(originalAccount.getPhoneNumberIdentifier())) { logger.error( "Phone number identifier changed via \"normal\" update; PNIs must be changed via changeNumber method", new RuntimeException()); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountLockManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountLockManager.java index 1bdc72074..b26809d2c 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountLockManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountLockManager.java @@ -113,6 +113,6 @@ public class AccountLockManager { public V withSingleAccountLock(Account account, final ThrowingSupplier task, final Executor lockAcquisitionExecutor) throws E { - return withLock(Set.of(account.getPhoneNumberIdentifierOptional().orElse(account.getAccountIdentifier())), task, lockAcquisitionExecutor); + return withLock(Set.of(account.getPhoneNumberIdentifier().orElse(account.getAccountIdentifier())), task, lockAcquisitionExecutor); } } 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 bea45d7f2..79d111c9b 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/Accounts.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/Accounts.java @@ -217,7 +217,7 @@ public class Accounts { boolean create(final Account account, final List additionalWriteItems) throws AccountAlreadyExistsException { - if (account.getNumberOptional().isEmpty() || account.getPhoneNumberIdentifierOptional().isEmpty()) { + if (account.getNumber().isEmpty() || account.getPhoneNumberIdentifier().isEmpty()) { throw new IllegalArgumentException("Phone number and phone number identifier must be set"); } @@ -225,8 +225,8 @@ public class Accounts { try { final AttributeValue uuidAttr = AttributeValues.fromUUID(account.getAccountIdentifier()); - final AttributeValue numberAttr = AttributeValues.fromString(account.getNumberOptional().get()); - final AttributeValue pniUuidAttr = AttributeValues.fromUUID(account.getPhoneNumberIdentifierOptional().get()); + final AttributeValue numberAttr = AttributeValues.fromString(account.getNumber().get()); + final AttributeValue pniUuidAttr = AttributeValues.fromUUID(account.getPhoneNumberIdentifier().get()); final TransactWriteItem phoneNumberConstraintPut = buildConstraintTablePutIfAbsent( phoneNumberConstraintTableName, uuidAttr, ATTR_ACCOUNT_E164, numberAttr); @@ -237,7 +237,7 @@ public class Accounts { // Clear any "recently deleted account" record for this number since, if it existed, we've used its old ACI for // the newly-created account. - final TransactWriteItem deletedAccountDelete = buildRemoveDeletedAccount(account.getPhoneNumberIdentifierOptional().get()); + final TransactWriteItem deletedAccountDelete = buildRemoveDeletedAccount(account.getPhoneNumberIdentifier().get()); final Collection writeItems = new ArrayList<>( List.of(phoneNumberConstraintPut, phoneNumberIdentifierConstraintPut, accountPut, deletedAccountDelete)); @@ -379,12 +379,12 @@ public class Accounts { final Collection additionalWriteItems) { if (!existingAccount.getAccountIdentifier().equals(accountToCreate.getAccountIdentifier()) || - existingAccount.getNumberOptional().isPresent() != accountToCreate.getNumberOptional().isPresent() || - !existingAccount.getPhoneNumberIdentifierOptional().equals(accountToCreate.getPhoneNumberIdentifierOptional())) { + existingAccount.getNumber().isPresent() != accountToCreate.getNumber().isPresent() || + !existingAccount.getPhoneNumberIdentifier().equals(accountToCreate.getPhoneNumberIdentifier())) { 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()); + existingAccount.getAccountIdentifier(), existingAccount.getNumber().map(Accounts::redactPhoneNumber), existingAccount.getPhoneNumberIdentifier(), + accountToCreate.getAccountIdentifier(), accountToCreate.getNumber().map(Accounts::redactPhoneNumber), accountToCreate.getPhoneNumberIdentifier()); throw new IllegalArgumentException("reclaimed accounts must match"); } @@ -459,11 +459,11 @@ public class Accounts { // Phone number canonicalization means that a user can use a different phone number in the same equivalence class // to reclaim the account. - if (!existingAccount.getNumberOptional().equals(accountToCreate.getNumberOptional()) - && existingAccount.getNumberOptional().isPresent() - && accountToCreate.getNumberOptional().isPresent()) { - final String existingAccountNumber = existingAccount.getNumberOptional().get(); - final String accountToCreateNumber = accountToCreate.getNumberOptional().get(); + if (!existingAccount.getNumber().equals(accountToCreate.getNumber()) + && existingAccount.getNumber().isPresent() + && accountToCreate.getNumber().isPresent()) { + final String existingAccountNumber = existingAccount.getNumber().get(); + final String accountToCreateNumber = accountToCreate.getNumber().get(); if (getAlternateForms(existingAccountNumber).contains(accountToCreateNumber)) { final AttributeValue uuidAttr = AttributeValues.fromUUID(existingAccount.getAccountIdentifier()); final AttributeValue numberAttr = AttributeValues.fromString(accountToCreateNumber); @@ -474,13 +474,13 @@ public class Accounts { writeItems.add(phoneNumberConstraintPut); } else { throw new IllegalStateException(String.format("Reclaiming account with a non-equivalent phone number. Old account %s:%s:%s, new account %s:%s:%s", - existingAccount.getAccountIdentifier(), redactPhoneNumber(existingAccountNumber), existingAccount.getPhoneNumberIdentifierOptional(), - accountToCreate.getAccountIdentifier(), redactPhoneNumber(accountToCreateNumber), accountToCreate.getPhoneNumberIdentifierOptional())); + existingAccount.getAccountIdentifier(), redactPhoneNumber(existingAccountNumber), existingAccount.getPhoneNumberIdentifier(), + accountToCreate.getAccountIdentifier(), redactPhoneNumber(accountToCreateNumber), accountToCreate.getPhoneNumberIdentifier())); } } final int updateAccountItemIndex = writeItems.size(); - writeItems.add(UpdateAccountSpec.forReclaimedAccount(accountsTableName, accountToCreate, existingAccount.getNumberOptional()).transactItem()); + writeItems.add(UpdateAccountSpec.forReclaimedAccount(accountsTableName, accountToCreate, existingAccount.getNumber()).transactItem()); writeItems.addAll(additionalWriteItems); return dynamoDbAsyncClient.transactWriteItems(TransactWriteItemsRequest.builder().transactItems(writeItems).build()) @@ -494,9 +494,9 @@ public class Accounts { if (Accounts.conditionalCheckFailed(te.cancellationReasons().get(updateAccountItemIndex))) { final Map item = te.cancellationReasons().get(updateAccountItemIndex).item(); final Optional existingNumber = Optional.ofNullable(AttributeValues.getString(item, Accounts.ATTR_ACCOUNT_E164, null)); - if (!existingAccount.getNumberOptional().equals(existingNumber)) { + if (!existingAccount.getNumber().equals(existingNumber)) { log.error("Failed to update account due to unexpected existing phone number. Account {}. Expected {}, got {}", - existingAccount.getAccountIdentifier(), existingAccount.getNumberOptional(), existingNumber); + existingAccount.getAccountIdentifier(), existingAccount.getNumber(), existingNumber); throw new UnexpectedExistingPhoneNumberException(); } } @@ -531,8 +531,8 @@ public class Accounts { final Collection additionalWriteItems) { CHANGE_NUMBER_TIMER.record(() -> { - final String originalNumber = account.getNumber(); - final UUID originalPni = account.getPhoneNumberIdentifier(); + final String originalNumber = account.getNumber().orElseThrow(() -> new IllegalArgumentException("Account does not have a phone number")); + final UUID originalPni = account.getPhoneNumberIdentifier().orElseThrow(() -> new IllegalArgumentException("Account does not have a phone number")); boolean succeeded = false; @@ -1083,7 +1083,7 @@ public class Accounts { final UpdateExpression updateExpression = base.updateExpression(); final List setClauses = new ArrayList<>(updateExpression.setClauses()); - final String conditionExpression = account.getNumberOptional() + final String conditionExpression = account.getNumber() .map(number -> { attrNames.put("#number", ATTR_ACCOUNT_E164); attrValues.put(":number", AttributeValues.fromString(number)); @@ -1401,10 +1401,10 @@ public class Accounts { final List transactWriteItems = new ArrayList<>(); transactWriteItems.add(buildConditionalDeleteAccount(account)); - account.getNumberOptional().ifPresent(e164 -> transactWriteItems.add( + account.getNumber().ifPresent(e164 -> transactWriteItems.add( buildDelete(phoneNumberConstraintTableName, ATTR_ACCOUNT_E164, e164))); - account.getPhoneNumberIdentifierOptional().ifPresent(pni -> { + account.getPhoneNumberIdentifier().ifPresent(pni -> { transactWriteItems.add(buildDelete(phoneNumberIdentifierConstraintTableName, ATTR_PNI_UUID, pni)); transactWriteItems.add(buildPutDeletedAccount(uuid, pni)); }); @@ -1692,13 +1692,13 @@ public class Accounts { CompletableFuture regenerateConstraints(final Account account) { final List> constraintFutures = new ArrayList<>(); - account.getNumberOptional().ifPresent(phoneNumber -> + account.getNumber().ifPresent(phoneNumber -> constraintFutures.add(writeConstraint(phoneNumberConstraintTableName, account.getAccountIdentifier(), ATTR_ACCOUNT_E164, AttributeValues.fromString(phoneNumber)))); - account.getPhoneNumberIdentifierOptional().ifPresent(phoneNumberIdentifier -> + account.getPhoneNumberIdentifier().ifPresent(phoneNumberIdentifier -> constraintFutures.add(writeConstraint(phoneNumberIdentifierConstraintTableName, account.getAccountIdentifier(), ATTR_PNI_UUID, @@ -1774,15 +1774,15 @@ public class Accounts { final UUID accountIdentifier = UUIDUtil.fromByteBuffer(item.get(KEY_ACCOUNT_UUID).b().asByteBuffer()); final UUID phoneNumberIdentifierFromAttribute = AttributeValues.getUUID(item, ATTR_PNI_UUID, null); - if (!account.getPhoneNumberIdentifierOptional().equals(Optional.ofNullable(phoneNumberIdentifierFromAttribute))) { + if (!account.getPhoneNumberIdentifier().equals(Optional.ofNullable(phoneNumberIdentifierFromAttribute))) { log.warn("Mismatched PNIs for account {}. From JSON: {}; from attribute: {}", - accountIdentifier, account.getPhoneNumberIdentifierOptional(), phoneNumberIdentifierFromAttribute); + accountIdentifier, account.getPhoneNumberIdentifier(), phoneNumberIdentifierFromAttribute); } final String attributeNumber = AttributeValues.getString(item, ATTR_ACCOUNT_E164, null); - if (!account.getNumberOptional().equals(Optional.ofNullable(attributeNumber))) { + if (!account.getNumber().equals(Optional.ofNullable(attributeNumber))) { log.error("Mismatched phone numbers for account {}. From JSON: {}; from attribute: {}", - accountIdentifier, account.getNumberOptional(), attributeNumber); + accountIdentifier, account.getNumber(), attributeNumber); } account.setNumber(attributeNumber, phoneNumberIdentifierFromAttribute); 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 7e23a774d..b4225a89a 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountsManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountsManager.java @@ -74,7 +74,6 @@ import org.whispersystems.textsecuregcm.entities.ECSignedPreKey; import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey; import org.whispersystems.textsecuregcm.entities.RestoreAccountRequest; import org.whispersystems.textsecuregcm.entities.TransferArchiveResult; -import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.identity.ServiceIdentifier; import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil; import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubConnection; @@ -461,7 +460,7 @@ public class AccountsManager extends RedisPubSubAdapter implemen try { final List additionalWriteItems = new ArrayList<>(keysManager.buildWriteItemsForNewDevice(account.getAccountIdentifier(), - account.getPhoneNumberIdentifierOptional(), + account.getPhoneNumberIdentifier(), Device.PRIMARY_ID, primaryDeviceSpec.aciInfo().signedPreKey(), primaryDeviceSpec.pniInfo().map(DeviceIdentityInfo::signedPreKey), @@ -525,9 +524,9 @@ public class AccountsManager extends RedisPubSubAdapter implemen final Account account = new Account(); account.setAccountIdentifier(existingAccount.getAccountIdentifier()); - if (existingAccount.getNumberOptional().isPresent()) { - account.setNumber(existingAccount.getNumberOptional().get(), - existingAccount.getPhoneNumberIdentifierOptional() + if (existingAccount.getNumber().isPresent()) { + account.setNumber(existingAccount.getNumber().get(), + existingAccount.getPhoneNumberIdentifier() .orElseThrow(() -> new AssertionError("Accounts that have a phone number must also have a PNI"))); account.setPhoneNumberIdentityKey(maybePniIdentityKey @@ -580,7 +579,7 @@ public class AccountsManager extends RedisPubSubAdapter implemen account.setAccountIdentifier(aci); final List additionalWriteItems = new ArrayList<>(keysManager.buildWriteItemsForNewDevice(account.getAccountIdentifier(), - account.getPhoneNumberIdentifierOptional(), + account.getPhoneNumberIdentifier(), Device.PRIMARY_ID, primaryDeviceSpec.aciInfo().signedPreKey(), primaryDeviceSpec.pniInfo().map(DeviceIdentityInfo::signedPreKey), @@ -594,16 +593,16 @@ public class AccountsManager extends RedisPubSubAdapter implemen // transaction anyhow .filter(existingDeviceId -> existingDeviceId != Device.PRIMARY_ID) .map(existingDeviceId -> - keysManager.buildWriteItemsForRemovedDevice(aci, account.getPhoneNumberIdentifierOptional(), existingDeviceId)) + keysManager.buildWriteItemsForRemovedDevice(aci, account.getPhoneNumberIdentifier(), existingDeviceId)) .forEach(additionalWriteItems::addAll); - account.getPhoneNumberIdentifierOptional().ifPresent(phoneNumberIdentifier -> + account.getPhoneNumberIdentifier().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)), + account.getPhoneNumberIdentifier().map(keysManager::deleteSingleUsePreKeys).orElse(CompletableFuture.completedFuture(null)), messagesManager.clear(aci), profilesManager.deleteAll(aci, false)) .thenCompose(ignored -> disconnectionRequestManager.requestDisconnection(existingAccount)) @@ -617,7 +616,7 @@ public class AccountsManager extends RedisPubSubAdapter implemen // 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)), + account.getPhoneNumberIdentifier().map(keysManager::deleteSingleUsePreKeys).orElse(CompletableFuture.completedFuture(null)), messagesManager.clear(aci), profilesManager.deleteAll(aci, false)); }) @@ -668,7 +667,7 @@ public class AccountsManager extends RedisPubSubAdapter implemen CompletableFuture .allOf( keysManager.deleteSingleUsePreKeys(account.getAccountIdentifier(), nextDeviceId), - account.getPhoneNumberIdentifierOptional() + account.getPhoneNumberIdentifier() .map(pni -> keysManager.deleteSingleUsePreKeys(pni, nextDeviceId)) .orElse(CompletableFuture.completedFuture(null)), messagesManager.clear(account.getAccountIdentifier(), nextDeviceId)) @@ -678,7 +677,7 @@ public class AccountsManager extends RedisPubSubAdapter implemen final List additionalWriteItems = new ArrayList<>(keysManager.buildWriteItemsForNewDevice( account.getAccountIdentifier(), - account.getPhoneNumberIdentifierOptional(), + account.getPhoneNumberIdentifier(), nextDeviceId, deviceSpec.aciInfo().signedPreKey(), deviceSpec.pniInfo().map(DeviceIdentityInfo::signedPreKey), @@ -862,7 +861,7 @@ public class AccountsManager extends RedisPubSubAdapter implemen CompletableFuture.allOf( keysManager.deleteSingleUsePreKeys(account.getAccountIdentifier(), deviceId), - account.getPhoneNumberIdentifierOptional() + account.getPhoneNumberIdentifier() .map(pni -> keysManager.deleteSingleUsePreKeys(pni, deviceId)) .orElse(CompletableFuture.completedFuture(null)), messagesManager.clear(account.getAccountIdentifier(), deviceId)) @@ -873,7 +872,7 @@ public class AccountsManager extends RedisPubSubAdapter implemen final List additionalWriteItems = new ArrayList<>( keysManager.buildWriteItemsForRemovedDevice( account.getAccountIdentifier(), - account.getPhoneNumberIdentifierOptional(), + account.getPhoneNumberIdentifier(), deviceId)); try { accounts.updateTransactionally(account, additionalWriteItems); @@ -883,7 +882,7 @@ public class AccountsManager extends RedisPubSubAdapter implemen // Ensure any messages/single-use pre-keys that came in while we were working are also removed CompletableFuture.allOf( keysManager.deleteSingleUsePreKeys(account.getAccountIdentifier(), deviceId), - account.getPhoneNumberIdentifierOptional() + account.getPhoneNumberIdentifier() .map(pni -> keysManager.deleteSingleUsePreKeys(pni, deviceId)) .orElse(CompletableFuture.completedFuture(null)), messagesManager.clear(account.getAccountIdentifier(), deviceId)) @@ -912,7 +911,7 @@ public class AccountsManager extends RedisPubSubAdapter implemen final Account account = accounts.getByAccountIdentifier(accountIdentifier) .orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier)); - final UUID originalPhoneNumberIdentifier = account.getPhoneNumberIdentifierOptional() + final UUID originalPhoneNumberIdentifier = account.getPhoneNumberIdentifier() .orElseThrow(() -> new IllegalArgumentException("Cannot change phone number for accounts without phone numbers")); final UUID targetPhoneNumberIdentifier = phoneNumberIdentifiers.getPhoneNumberIdentifier(targetNumber).join(); @@ -934,7 +933,7 @@ public class AccountsManager extends RedisPubSubAdapter implemen final Map pniPqLastResortPreKeys, final Map pniRegistrationIds) throws MismatchedDevicesException { - final UUID originalPhoneNumberIdentifier = account.getPhoneNumberIdentifierOptional() + final UUID originalPhoneNumberIdentifier = account.getPhoneNumberIdentifier() .orElseThrow(() -> new IllegalArgumentException("Cannot change phone number for accounts without phone numbers")); validateDevices(account, pniSignedPreKeys, pniPqLastResortPreKeys, pniRegistrationIds); @@ -1167,7 +1166,7 @@ public class AccountsManager extends RedisPubSubAdapter implemen } public Account update(final Account account, final Consumer updater) { - final Account updatedAccount = update(account.getIdentifier(IdentityType.ACI), updater); + final Account updatedAccount = update(account.getAccountIdentifier(), updater); account.markStale(); return updatedAccount; @@ -1450,19 +1449,19 @@ public class AccountsManager extends RedisPubSubAdapter implemen account.getDevices().stream() .flatMap(device -> keysManager.buildWriteItemsForRemovedDevice( - account.getIdentifier(IdentityType.ACI), - account.getPhoneNumberIdentifierOptional(), + account.getAccountIdentifier(), + account.getPhoneNumberIdentifier(), device.getId()) .stream()) .forEach(additionalWriteItems::add); - account.getPhoneNumberIdentifierOptional().ifPresent(phoneNumberIdentifier -> + account.getPhoneNumberIdentifier().ifPresent(phoneNumberIdentifier -> additionalWriteItems.add(phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForRemovePassword(phoneNumberIdentifier))); CompletableFuture.allOf( secureStorageClient.deleteStoredData(account.getAccountIdentifier()), secureValueRecovery2Client.removeData(account.getAccountIdentifier()), keysManager.deleteSingleUsePreKeys(account.getAccountIdentifier()), - account.getPhoneNumberIdentifierOptional().map(keysManager::deleteSingleUsePreKeys).orElse(CompletableFuture.completedFuture(null)), + account.getPhoneNumberIdentifier().map(keysManager::deleteSingleUsePreKeys).orElse(CompletableFuture.completedFuture(null)), messagesManager.clear(account.getAccountIdentifier()), profilesManager.deleteAll(account.getAccountIdentifier(), true)) .join(); @@ -1488,7 +1487,7 @@ public class AccountsManager extends RedisPubSubAdapter implemen cacheCluster.useCluster(connection -> { final RedisAdvancedClusterCommands commands = connection.sync(); - account.getPhoneNumberIdentifierOptional().ifPresent(pni -> + account.getPhoneNumberIdentifier().ifPresent(pni -> commands.setex(getAccountMapKey(pni.toString()), CACHE_TTL_SECONDS, account.getAccountIdentifier().toString())); commands.setex(getAccountEntityKey(account.getAccountIdentifier()), CACHE_TTL_SECONDS, accountJson); }); @@ -1508,7 +1507,7 @@ public class AccountsManager extends RedisPubSubAdapter implemen } return cacheCluster.withCluster(connection -> CompletableFuture.allOf( - account.getPhoneNumberIdentifierOptional().map(pni -> + account.getPhoneNumberIdentifier().map(pni -> connection.async().setex(getAccountMapKey(pni.toString()), CACHE_TTL_SECONDS, account.getAccountIdentifier().toString()) .toCompletableFuture()) .orElseGet(() -> CompletableFuture.completedFuture(null)), @@ -1637,7 +1636,7 @@ public class AccountsManager extends RedisPubSubAdapter implemen private void redisDelete(final Account account) { final List keysToDelete = new ArrayList<>(2); - account.getPhoneNumberIdentifierOptional() + account.getPhoneNumberIdentifier() .map(pni -> getAccountMapKey(pni.toString())) .ifPresent(keysToDelete::add); keysToDelete.add(getAccountEntityKey(account.getAccountIdentifier())); @@ -1739,8 +1738,8 @@ public class AccountsManager extends RedisPubSubAdapter implemen } public CompletableFuture> waitForTransferArchive(final Account account, final Device device, final Duration timeout) { - final DeviceIdentifier deviceIdentifier = new DeviceIdentifier(account.getAccountIdentifier(), device.getId(), device.getRegistrationId(IdentityType.ACI)); - final String registrationIdTransferArchiveKey = getRegistrationIdTransferArchiveKey(account.getAccountIdentifier(), device.getId(), device.getRegistrationId(IdentityType.ACI)); + final DeviceIdentifier deviceIdentifier = new DeviceIdentifier(account.getAccountIdentifier(), device.getId(), device.getAccountRegistrationId()); + final String registrationIdTransferArchiveKey = getRegistrationIdTransferArchiveKey(account.getAccountIdentifier(), device.getId(), device.getAccountRegistrationId()); return waitForPubSubKey(waitForTransferArchiveFuturesByDeviceIdentifier, deviceIdentifier, @@ -1953,7 +1952,7 @@ public class AccountsManager extends RedisPubSubAdapter implemen final Account account = accounts.getByAccountIdentifier(accountIdentifier) .orElseThrow(ContestedOptimisticLockException::new); - account.getPhoneNumberIdentifierOptional() + account.getPhoneNumberIdentifier() .flatMap(phoneNumberRecoveryPasswordsManager::getPasswordAndWriteItemForMigration) .ifPresent(passwordAndWriteItem -> { account.setAccountRecoveryPassword(passwordAndWriteItem.first()); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/ChangeNumberManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/ChangeNumberManager.java index dfab9b503..5889fed84 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/ChangeNumberManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/ChangeNumberManager.java @@ -101,12 +101,12 @@ public class ChangeNumberManager { final Account account = accountAndMaybeExistingAccount.first(); - if (account.getNumberOptional().isEmpty()) { + if (account.getNumber().isEmpty()) { throw new IllegalArgumentException("account does not have a phone number"); } // Only verify and check reglock if there's a data change to be made... - if (!account.getNumberOptional().get().equals(number)) { + if (!account.getNumber().get().equals(number)) { final Optional waitingPeriodRemaining = changeNumberWaitingPeriodManager.getWaitingPeriodRemaining(account.getAccountIdentifier()); if (waitingPeriodRemaining.isPresent()) { @@ -122,7 +122,7 @@ public class ChangeNumberManager { final Optional existingAccount = accountAndMaybeExistingAccount.second(); if (existingAccount.isPresent()) { - assert existingAccount.get().getNumberOptional().isPresent(); + assert existingAccount.get().getNumber().isPresent(); registrationLockVerificationManager.verifyRegistrationLock(existingAccount.get(), registrationLock, userAgent, RegistrationLockVerificationManager.Flow.CHANGE_NUMBER, verificationType); } @@ -170,7 +170,7 @@ public class ChangeNumberManager { try { // Now that we've actually updated the account, populate the "updated PNI" field on all envelopes messagesByDeviceId.replaceAll((_, envelope) -> - envelope.toBuilder().setUpdatedPni(UUIDUtil.toByteString(updatedAccount.getPhoneNumberIdentifierOptional() + envelope.toBuilder().setUpdatedPni(UUIDUtil.toByteString(updatedAccount.getPhoneNumberIdentifier() .orElseThrow(() -> new AssertionError("Account does not have a PNI after changing number")))) .build()); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/Device.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/Device.java index 8f699d319..355b59cc0 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/Device.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/Device.java @@ -14,14 +14,12 @@ import java.time.Duration; import java.util.Collections; import java.util.EnumSet; import java.util.List; -import java.util.NoSuchElementException; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import javax.annotation.Nullable; import org.whispersystems.textsecuregcm.auth.SaltedTokenHash; -import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.util.ByteArrayAdapter; import org.whispersystems.textsecuregcm.util.DeviceCapabilityAdapter; import org.whispersystems.textsecuregcm.util.DeviceNameByteArrayAdapter; @@ -224,25 +222,6 @@ public class Device { return getId() == PRIMARY_ID; } - /// Returns the registration ID for this device associated with the given identity type. - /// - /// @param identityType the type of identity for which to return the registration ID - /// - /// @return the registration ID for the given identity type for the device - /// - /// @throws NoSuchElementException if a PNI identity is requested for a device attached - /// to an account without a phone number identity. - /// - /// @deprecated Please use [#getAccountRegistrationId()] or - /// [#getPhoneNumberIdentityRegistrationId()] instead. - @Deprecated - public int getRegistrationId(final IdentityType identityType) { - return switch (identityType) { - case ACI -> getAccountRegistrationId(); - case PNI -> getPhoneNumberIdentityRegistrationId().orElseThrow(NoSuchElementException::new); - }; - } - /// Returns the registration ID for this device associated with its account's account identity. /// /// @return the registration ID for this device associated with its account's account identity. diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagePersister.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagePersister.java index a94637396..7313509b5 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagePersister.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagePersister.java @@ -249,7 +249,7 @@ public class MessagePersister implements Managed { .filter(e -> !(e instanceof MessagePersistenceException))) .onErrorResume(e -> { logger.warn("Failed to persist queue {}::{} ({}); will schedule for retry", - account.getIdentifier(IdentityType.ACI), device.getId(), node.getUri().getHost(), e); + account.getAccountIdentifier(), device.getId(), node.getUri().getHost(), e); return Mono.empty(); }); @@ -331,7 +331,7 @@ public class MessagePersister implements Managed { } private Mono trimQueue(final Account account, final Device device) { - final UUID aci = account.getIdentifier(IdentityType.ACI); + final UUID aci = account.getAccountIdentifier(); final byte deviceId = device.getId(); final double extraRoomRatio = this.dynamicConfigurationManager.getConfiguration() diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesManager.java index 6d9da2674..0478cdcbb 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesManager.java @@ -241,7 +241,7 @@ public class MessagesManager { final SealedSenderMultiRecipientMessage.Recipient recipient = serviceIdAndRecipient.getValue(); final byte[] devices = recipient.getDevices(); - return insertAsync(resolvedRecipients.get(recipient).getIdentifier(IdentityType.ACI), + return insertAsync(resolvedRecipients.get(recipient).getAccountIdentifier(), IntStream.range(0, devices.length).mapToObj(i -> devices[i]) .collect(Collectors.toMap(deviceId -> deviceId, _ -> prototypeMessage.toBuilder() .setContent(ByteString.copyFrom(multiRecipientMessage.messageForRecipient(serviceIdAndRecipient.getValue()))) diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/PhoneNumberIdentifiers.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/PhoneNumberIdentifiers.java index 0580823bd..3604e31dd 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/PhoneNumberIdentifiers.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/PhoneNumberIdentifiers.java @@ -245,10 +245,10 @@ public class PhoneNumberIdentifiers { } CompletableFuture regeneratePhoneNumberIdentifierMappings(final Account account) { - return account.getNumberOptional() + return account.getNumber() .map(phoneNumber -> setPni(phoneNumber, Util.getAlternateForms(phoneNumber), - account.getPhoneNumberIdentifierOptional() + account.getPhoneNumberIdentifier() .orElseThrow(() -> new AssertionError("Account has a phone number, but no PNI"))) .thenRun(Util.NOOP)) .orElseGet(() -> CompletableFuture.completedFuture(null)); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/ReportMessageManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/ReportMessageManager.java index 720c50562..db62804e1 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/ReportMessageManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/ReportMessageManager.java @@ -117,7 +117,7 @@ public class ReportMessageManager { return rateLimitCluster.withCluster( connection -> Math.max( - account.getPhoneNumberIdentifierOptional().map(pni -> connection.sync().pfcount(getReportedSenderPniKey(pni)).intValue()).orElse(0), + account.getPhoneNumberIdentifier().map(pni -> connection.sync().pfcount(getReportedSenderPniKey(pni)).intValue()).orElse(0), connection.sync().pfcount(getReportedSenderAciKey(account.getAccountIdentifier())).intValue())); } catch (final RedisException e) { return 0; diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/util/ProfileHelper.java b/service/src/main/java/org/whispersystems/textsecuregcm/util/ProfileHelper.java index a76593fef..9ae97da7a 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/util/ProfileHelper.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/util/ProfileHelper.java @@ -119,7 +119,7 @@ public class ProfileHelper { final DynamicPaymentsConfiguration paymentsConfiguration = dynamicConfigurationManager.getConfiguration().getPaymentsConfiguration(); - final boolean hasDisallowedRegion = account.getNumberOptional() + final boolean hasDisallowedRegion = account.getNumber() .map(phoneNumber -> paymentsConfiguration.disallowedPrefixes().stream().anyMatch(phoneNumber::startsWith)) .orElseGet(() -> asnInfoProvider.lookup(ipAddress) .map(asnInfo -> paymentsConfiguration.disallowedAsnRegions().stream() diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/util/Util.java b/service/src/main/java/org/whispersystems/textsecuregcm/util/Util.java index 5f13d637b..f41c5f42e 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/util/Util.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/util/Util.java @@ -87,7 +87,7 @@ public class Util { } public static String getCountryCode(final Account account) { - return account.getNumberOptional().map(Util::getCountryCode).orElse(COUNTRY_CODE_NOT_APPLICABLE); + return account.getNumber().map(Util::getCountryCode).orElse(COUNTRY_CODE_NOT_APPLICABLE); } public static String getCountryCode(final String number) { @@ -99,7 +99,7 @@ public class Util { } public static String getRegion(final Account account) { - return account.getNumberOptional().map(Util::getRegion).orElse(REGION_NOT_APPLICABLE); + return account.getNumber().map(Util::getRegion).orElse(REGION_NOT_APPLICABLE); } public static String getRegion(final String number) { diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/websocket/AuthenticatedConnectListener.java b/service/src/main/java/org/whispersystems/textsecuregcm/websocket/AuthenticatedConnectListener.java index f089ff84a..9974a5b7a 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/websocket/AuthenticatedConnectListener.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/websocket/AuthenticatedConnectListener.java @@ -138,11 +138,11 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener { new WebSocketDisconnectionRequestListener(messageMetrics, context.getClient(), disableMessages); disconnectionRequestManager - .addListener(account.getIdentifier(IdentityType.ACI), device.getId(), disconnectionListener); + .addListener(account.getAccountIdentifier(), device.getId(), disconnectionListener); context.addWebsocketClosedListener((_, _, _) -> { disconnectionRequestManager - .removeListener(account.getIdentifier(IdentityType.ACI), device.getId(), disconnectionListener); + .removeListener(account.getAccountIdentifier(), device.getId(), disconnectionListener); maybeWebSocketConnection.ifPresent(WebSocketConnection::stop); }); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/websocket/WebSocketConnection.java b/service/src/main/java/org/whispersystems/textsecuregcm/websocket/WebSocketConnection.java index d2b204cdc..466b27fee 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/websocket/WebSocketConnection.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/websocket/WebSocketConnection.java @@ -135,7 +135,7 @@ public class WebSocketConnection { this.experimentEnrollmentManager = experimentEnrollmentManager; this.messageStream = - messagesManager.getMessages(authenticatedAccount.getIdentifier(IdentityType.ACI), authenticatedDevice); + messagesManager.getMessages(authenticatedAccount.getAccountIdentifier(), authenticatedDevice); this.userAgent = UserAgentUtil.maybeParseUserAgentString(client.getUserAgent()); } @@ -161,7 +161,7 @@ public class WebSocketConnection { .doOnNext(entry -> { if (entry instanceof MessageStreamEntry.Envelope(final Envelope message)) { if (hasSentFirstMessage.compareAndSet(false, true)) { - messageDeliveryLoopMonitor.recordDeliveryAttempt(authenticatedAccount.getIdentifier(IdentityType.ACI), + messageDeliveryLoopMonitor.recordDeliveryAttempt(authenticatedAccount.getAccountIdentifier(), authenticatedDevice.getId(), UUIDUtil.fromByteString(message.getServerGuid()), client.getUserAgent(), @@ -208,7 +208,7 @@ public class WebSocketConnection { client.close(1000, "OK"); - messagesManager.mayHaveMessages(authenticatedAccount.getIdentifier(IdentityType.ACI), authenticatedDevice) + messagesManager.mayHaveMessages(authenticatedAccount.getAccountIdentifier(), authenticatedDevice) .thenAccept(mayHaveMessages -> { if (mayHaveMessages) { pushNotificationScheduler.scheduleDelayedNotification(authenticatedAccount, diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/ClearExpiredFoundationDbMessagesCommand.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/ClearExpiredFoundationDbMessagesCommand.java index 9779b7867..7a14ddbdf 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/ClearExpiredFoundationDbMessagesCommand.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/ClearExpiredFoundationDbMessagesCommand.java @@ -99,7 +99,7 @@ public class ClearExpiredFoundationDbMessagesCommand extends AbstractSinglePassC .buffer(batchSize) .map(batch -> batch.stream().collect( Collectors.toMap( - account -> new AciServiceIdentifier(account.getIdentifier(IdentityType.ACI)), + account -> new AciServiceIdentifier(account.getAccountIdentifier()), account -> account.getDevices().stream().map(Device::getId).toList()))) .doOnNext( dryRun ? _ -> {} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/DeleteUserCommand.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/DeleteUserCommand.java index 2efa2521f..f7c8daa3e 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/DeleteUserCommand.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/DeleteUserCommand.java @@ -52,8 +52,8 @@ public class DeleteUserCommand extends AbstractCommandWithDependencies { Optional account = accountsManager.getByE164(user); if (account.isPresent()) { - accountsManager.delete(account.get().getIdentifier(IdentityType.ACI), DeletionReason.ADMIN_DELETED); - logger.warn("Removed " + account.get().getNumber()); + accountsManager.delete(account.get().getAccountIdentifier(), DeletionReason.ADMIN_DELETED); + logger.warn("Removed " + account.get().getAccountIdentifier()); } else { logger.warn("Account not found"); } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/IdleWakeupEligibilityChecker.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/IdleWakeupEligibilityChecker.java index c166e4816..d56446084 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/IdleWakeupEligibilityChecker.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/IdleWakeupEligibilityChecker.java @@ -65,9 +65,9 @@ public class IdleWakeupEligibilityChecker { } if (isShortIdle(device, clock)) { - return messagesManager.mayHaveUrgentPersistedMessages(account.getIdentifier(IdentityType.ACI), device); + return messagesManager.mayHaveUrgentPersistedMessages(account.getAccountIdentifier(), device); } else if (isLongIdle(device, clock)) { - return messagesManager.mayHavePersistedMessages(account.getIdentifier(IdentityType.ACI), device) + return messagesManager.mayHavePersistedMessages(account.getAccountIdentifier(), device) .thenApply(mayHavePersistedMessages -> !mayHavePersistedMessages); } else { return CompletableFuture.completedFuture(false); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/NotifyIdleDevicesCommand.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/NotifyIdleDevicesCommand.java index 72ef89c76..af15b706b 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/NotifyIdleDevicesCommand.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/NotifyIdleDevicesCommand.java @@ -85,7 +85,7 @@ public class NotifyIdleDevicesCommand extends AbstractSinglePassCrawlAccountsCom .retryWhen(Retry.backoff(3, Duration.ofSeconds(1))) .onErrorResume(throwable -> { log.warn("Failed to check eligibility for {}:{}", - accountAndDevice.getT1().getIdentifier(IdentityType.ACI), + accountAndDevice.getT1().getAccountIdentifier(), accountAndDevice.getT2().getId(), throwable); @@ -101,7 +101,7 @@ public class NotifyIdleDevicesCommand extends AbstractSinglePassCrawlAccountsCom : Mono.fromFuture(() -> idleDeviceNotificationScheduler.scheduleNotification(account, device, PREFERRED_NOTIFICATION_TIME)) .onErrorResume(throwable -> { log.warn("Failed to schedule notification for {}:{}", - account.getIdentifier(IdentityType.ACI), + account.getAccountIdentifier(), device.getId(), throwable); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/RemoveExpiredLinkedDevicesCommand.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/RemoveExpiredLinkedDevicesCommand.java index 0cd2b37db..fdf6825d8 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/RemoveExpiredLinkedDevicesCommand.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/RemoveExpiredLinkedDevicesCommand.java @@ -131,7 +131,7 @@ public class RemoveExpiredLinkedDevicesCommand extends AbstractSinglePassCrawlAc return Flux.fromIterable(expiredDevices) .flatMap(deviceId -> - Mono.fromRunnable(() -> getCommandDependencies().accountsManager().removeDevice(account.getIdentifier(IdentityType.ACI), deviceId)) + Mono.fromRunnable(() -> getCommandDependencies().accountsManager().removeDevice(account.getAccountIdentifier(), deviceId)) .retryWhen(Retry.backoff(maxRetries, Duration.ofSeconds(1)) .doAfterRetry(ignored -> retryCounter.increment()) .onRetryExhaustedThrow((spec, rs) -> rs.failure())) diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/RemoveExpiredUsernameHoldsCommand.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/RemoveExpiredUsernameHoldsCommand.java index 91cad3cf0..c2565ace8 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/RemoveExpiredUsernameHoldsCommand.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/RemoveExpiredUsernameHoldsCommand.java @@ -86,7 +86,7 @@ public class RemoveExpiredUsernameHoldsCommand extends AbstractSinglePassCrawlAc final int holdsToRemove = removeExpired(holds); final Mono purgeMono = isDryRun || holdsToRemove == 0 ? Mono.empty() - : Mono.fromRunnable(() -> accountManager.update(account.getIdentifier(IdentityType.ACI), a -> a.setUsernameHolds(holds))) + : Mono.fromRunnable(() -> accountManager.update(account.getAccountIdentifier(), a -> a.setUsernameHolds(holds))) .subscribeOn(Schedulers.boundedElastic()) .then(); Metrics.counter(INSPECTED_ACCOUNTS_COUNTER_NAME, diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/SetUserDiscoverabilityCommand.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/SetUserDiscoverabilityCommand.java index af93a46db..9bb854f27 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/SetUserDiscoverabilityCommand.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/SetUserDiscoverabilityCommand.java @@ -62,7 +62,7 @@ public class SetUserDiscoverabilityCommand extends AbstractCommandWithDependenci maybeAccount.ifPresentOrElse(account -> { final boolean initiallyDiscoverable = account.isDiscoverableByPhoneNumber(); - accountsManager.update(account.getIdentifier(IdentityType.ACI), a -> a.setDiscoverableByPhoneNumber(namespace.getBoolean("discoverable"))); + accountsManager.update(account.getAccountIdentifier(), a -> a.setDiscoverableByPhoneNumber(namespace.getBoolean("discoverable"))); System.out.format("Set discoverability flag for %s to %s (was previously %s)\n", namespace.getString("user"), diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/StartPushNotificationExperimentCommand.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/StartPushNotificationExperimentCommand.java index c50f1d59b..1650641f3 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/StartPushNotificationExperimentCommand.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/StartPushNotificationExperimentCommand.java @@ -92,7 +92,7 @@ public class StartPushNotificationExperimentCommand extends AbstractSinglePas experiment.isDeviceEligible(accountAndDevice.getT1(), accountAndDevice.getT2())) .mapNotNull(eligible -> eligible ? accountAndDevice : null), maxConcurrency) .flatMap(accountAndDevice -> { - final UUID accountIdentifier = accountAndDevice.getT1().getIdentifier(IdentityType.ACI); + final UUID accountIdentifier = accountAndDevice.getT1().getAccountIdentifier(); final byte deviceId = accountAndDevice.getT2().getId(); final Mono recordInitialSampleMono = dryRun @@ -131,7 +131,7 @@ public class StartPushNotificationExperimentCommand extends AbstractSinglePas final Account account = accountAndDevice.getT1(); final Device device = accountAndDevice.getT2(); final boolean inExperimentGroup = - isInExperimentGroup(account.getIdentifier(IdentityType.ACI), device.getId(), experiment.getExperimentName()); + isInExperimentGroup(account.getAccountIdentifier(), device.getId(), experiment.getExperimentName()); final Mono applyTreatmentMono = dryRun ? Mono.empty() @@ -141,7 +141,7 @@ public class StartPushNotificationExperimentCommand extends AbstractSinglePas .onErrorResume(throwable -> { log.warn("Failed to apply {} treatment for {}:{} in experiment {}", inExperimentGroup ? "experimental" : " control", - account.getIdentifier(IdentityType.ACI), + account.getAccountIdentifier(), device.getId(), experiment.getExperimentName(), throwable); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/TrimOversizedFoundationDbMessageQueuesCommand.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/TrimOversizedFoundationDbMessageQueuesCommand.java index f47754972..0d238c75a 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/TrimOversizedFoundationDbMessageQueuesCommand.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/TrimOversizedFoundationDbMessageQueuesCommand.java @@ -124,7 +124,7 @@ public class TrimOversizedFoundationDbMessageQueuesCommand extends AbstractSingl accounts .flatMapIterable(account -> account.getDevices().stream().map( - device -> new Pair<>(new AciServiceIdentifier(account.getIdentifier(IdentityType.ACI)), device)).toList()) + device -> new Pair<>(new AciServiceIdentifier(account.getAccountIdentifier()), device)).toList()) .doOnNext(_ -> Metrics.counter(QUEUES_INSPECTED_COUNTER_NAME, "dryRun", String.valueOf(dryRun)).increment()) .flatMap(accountAndDevice -> messagesManager.trimQueue(accountAndDevice.first(), accountAndDevice.second(), maxQueueSizeBytes, targetQueueSizeBytes, rangeSplitChunkSizeBytes, dryRun), diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/UnlinkDevicesWithIdlePrimaryCommand.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/UnlinkDevicesWithIdlePrimaryCommand.java index 81f665a54..78debf7bd 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/UnlinkDevicesWithIdlePrimaryCommand.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/UnlinkDevicesWithIdlePrimaryCommand.java @@ -93,7 +93,7 @@ public class UnlinkDevicesWithIdlePrimaryCommand extends AbstractSinglePassCrawl .filter(account -> isPrimaryDeviceIdle(account, currentTime, idleDurationThreshold)) .flatMap(accountWithIdlePrimaryDevice -> Flux.fromIterable(accountWithIdlePrimaryDevice.getDevices()) .filter(device -> !device.isPrimary()) - .map(linkedDevice -> Tuples.of(accountWithIdlePrimaryDevice.getIdentifier(IdentityType.ACI), linkedDevice.getId()))) + .map(linkedDevice -> Tuples.of(accountWithIdlePrimaryDevice.getAccountIdentifier(), linkedDevice.getId()))) .flatMap(accountAndLinkedDeviceId -> { final Mono unlinkDeviceMono = isDryRun ? Mono.empty() diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/auth/CertificateGeneratorTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/auth/CertificateGeneratorTest.java index 1dc98c0f5..f97e76a23 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/auth/CertificateGeneratorTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/auth/CertificateGeneratorTest.java @@ -62,7 +62,7 @@ class CertificateGeneratorTest { when(account.getAccountIdentityKey()).thenReturn(IDENTITY_KEY); when(account.getAccountIdentifier()).thenReturn(ACI); - when(account.getNumberOptional()).thenReturn(Optional.of(E164)); + when(account.getNumber()).thenReturn(Optional.of(E164)); final byte[] contents = certificateGenerator.createFor(account, deviceId, includeE164); final SenderCertificate fullCertificate = SenderCertificate.parseFrom(contents); @@ -102,7 +102,7 @@ class CertificateGeneratorTest { when(account.getAccountIdentityKey()).thenReturn(IDENTITY_KEY); when(account.getAccountIdentifier()).thenReturn(ACI); - when(account.getNumberOptional()).thenReturn(Optional.empty()); + when(account.getNumber()).thenReturn(Optional.empty()); final Executable generateCertificate = () -> certificateGenerator.createFor(account, deviceId, includeE164); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/auth/DisconnectionRequestManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/auth/DisconnectionRequestManagerTest.java index 7c3f78f7a..c0b1f5423 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/auth/DisconnectionRequestManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/auth/DisconnectionRequestManagerTest.java @@ -115,7 +115,7 @@ class DisconnectionRequestManagerTest { when(linkedDevice.getId()).thenReturn(linkedDeviceId); final Account account = mock(Account.class); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier); + when(account.getAccountIdentifier()).thenReturn(accountIdentifier); when(account.getDevices()).thenReturn(List.of(primaryDevice, linkedDevice)); final DisconnectionRequestListener primaryDeviceListener = mock(DisconnectionRequestListener.class); 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 bbcdfb842..8d17e09a9 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/auth/RegistrationLockVerificationManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/auth/RegistrationLockVerificationManagerTest.java @@ -77,8 +77,8 @@ class RegistrationLockVerificationManagerTest { account = mock(Account.class); final UUID accountIdentifier = UUID.randomUUID(); when(account.getAccountIdentifier()).thenReturn(accountIdentifier); - when(account.getNumberOptional()).thenReturn(Optional.of("+18005551212")); - when(account.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(UUID.randomUUID())); + when(account.getNumber()).thenReturn(Optional.of("+18005551212")); + when(account.getPhoneNumberIdentifier()).thenReturn(Optional.of(UUID.randomUUID())); when(account.getDevices()).thenReturn(List.of(device)); AccountsHelper.setupMockGet(accountsManager, account); @@ -107,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).buildTransactWriteItemForRemovePassword(account.getPhoneNumberIdentifierOptional().orElseThrow()); + verify(phoneNumberRecoveryPasswordsManager).buildTransactWriteItemForRemovePassword(account.getPhoneNumberIdentifier().orElseThrow()); } else { verify(phoneNumberRecoveryPasswordsManager, never()).remove(any()); } @@ -192,7 +192,7 @@ class RegistrationLockVerificationManagerTest { @Test void testAccountWithNoPhoneNumber() { - when(account.getNumberOptional()).thenReturn(Optional.empty()); + when(account.getNumber()).thenReturn(Optional.empty()); assertThrows(IllegalArgumentException.class, () -> registrationLockVerificationManager.verifyRegistrationLock(account, null, null, RegistrationLockVerificationManager.Flow.REGISTRATION, PhoneVerificationRequest.VerificationType.SESSION)); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/backup/BackupAuthManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/backup/BackupAuthManagerTest.java index fd0a5ee63..8ce5b3c86 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/backup/BackupAuthManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/backup/BackupAuthManagerTest.java @@ -112,7 +112,7 @@ public class BackupAuthManagerTest { final Account account = mock(Account.class); when(account.getAccountIdentifier()).thenReturn(aci); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(aci); + when(account.getAccountIdentifier()).thenReturn(aci); AccountsHelper.setupMockGet(accountsManager, account); AccountsHelper.setupMockUpdate(accountsManager); 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 3c4da9f15..7036c41b1 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AccountControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AccountControllerTest.java @@ -197,12 +197,12 @@ class AccountControllerTest { Optional.of(registrationLockCredentials.salt()), Instant.ofEpochMilli(System.currentTimeMillis()))); when(senderRegLockAccount.getLastSeen()).thenReturn(System.currentTimeMillis()); when(senderRegLockAccount.getAccountIdentifier()).thenReturn(SENDER_REG_LOCK_UUID); - when(senderRegLockAccount.getNumberOptional()).thenReturn(Optional.of(SENDER_REG_LOCK)); + when(senderRegLockAccount.getNumber()).thenReturn(Optional.of(SENDER_REG_LOCK)); when(senderTransfer.getRegistrationLock()).thenReturn( new StoredRegistrationLock(Optional.empty(), Optional.empty(), Instant.ofEpochMilli(System.currentTimeMillis()))); when(senderTransfer.getAccountIdentifier()).thenReturn(SENDER_TRANSFER_UUID); - when(senderTransfer.getNumberOptional()).thenReturn(Optional.of(SENDER_TRANSFER)); + when(senderTransfer.getNumber()).thenReturn(Optional.of(SENDER_TRANSFER)); when(accountsManager.getByE164(eq(SENDER_PIN))).thenReturn(Optional.of(senderPinAccount)); when(accountsManager.getByE164(eq(SENDER_REG_LOCK))).thenReturn(Optional.of(senderRegLockAccount)); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AccountControllerV2Test.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AccountControllerV2Test.java index a6d92996d..1b9cb49f4 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AccountControllerV2Test.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AccountControllerV2Test.java @@ -127,14 +127,14 @@ class AccountControllerV2Test { final Account updatedAccount = mock(Account.class); when(updatedAccount.getAccountIdentifier()).thenReturn(uuid); - when(updatedAccount.getNumberOptional()).thenReturn(Optional.of(number)); + when(updatedAccount.getNumber()).thenReturn(Optional.of(number)); when(updatedAccount.getPhoneNumberIdentityKey()).thenReturn(Optional.of(pniIdentityKey)); - if (Optional.of(number).equals(account.getNumberOptional())) { - when(updatedAccount.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(AuthHelper.VALID_PNI)); + if (Optional.of(number).equals(account.getNumber())) { + when(updatedAccount.getPhoneNumberIdentifier()).thenReturn(Optional.of(AuthHelper.VALID_PNI)); } else { final UUID pni = UUID.randomUUID(); - when(updatedAccount.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(pni)); + when(updatedAccount.getPhoneNumberIdentifier()).thenReturn(Optional.of(pni)); } when(updatedAccount.getDevices()).thenReturn(devices); @@ -530,7 +530,7 @@ class AccountControllerV2Test { final AccountDataReportResponse structuredResponse = SystemMapper.jsonMapper() .readValue(stringResponse, AccountDataReportResponse.class); - assertEquals(account.getNumberOptional(), structuredResponse.data().account().phoneNumber()); + assertEquals(account.getNumber(), structuredResponse.data().account().phoneNumber()); assertEquals(account.isDiscoverableByPhoneNumber(), structuredResponse.data().account().findAccountByPhoneNumber()); assertEquals(account.isUnrestrictedUnidentifiedAccess(), diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AccountIdentityResponseBuilderTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AccountIdentityResponseBuilderTest.java index 98b0394fd..d48d8c029 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AccountIdentityResponseBuilderTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AccountIdentityResponseBuilderTest.java @@ -76,18 +76,18 @@ class AccountIdentityResponseBuilderTest { final Account account = mock(Account.class); when(account.getAccountIdentifier()).thenReturn(UUID.randomUUID()); - when(account.getNumberOptional()).thenReturn(hasPhoneNumber + when(account.getNumber()).thenReturn(hasPhoneNumber ? Optional.of(PhoneNumberUtil.getInstance().format( PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164)) : Optional.empty()); - when(account.getPhoneNumberIdentifierOptional()) + when(account.getPhoneNumberIdentifier()) .thenReturn(hasPhoneNumber ? Optional.of(UUID.randomUUID()) : Optional.empty()); final AccountIdentityResponse accountIdentityResponse = new AccountIdentityResponseBuilder(account).build(); assertThat(accountIdentityResponse.uuid()).isEqualTo(account.getAccountIdentifier()); - assertThat(accountIdentityResponse.number()).isEqualTo(account.getNumberOptional()); - assertThat(accountIdentityResponse.pni()).isEqualTo(account.getPhoneNumberIdentifierOptional()); + assertThat(accountIdentityResponse.number()).isEqualTo(account.getNumber()); + assertThat(accountIdentityResponse.pni()).isEqualTo(account.getPhoneNumberIdentifier()); } } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/DeviceControllerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/DeviceControllerTest.java index bf56d1da1..0867e045c 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/DeviceControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/DeviceControllerTest.java @@ -72,7 +72,6 @@ import org.whispersystems.textsecuregcm.entities.RemoteAttachment; import org.whispersystems.textsecuregcm.entities.RemoteAttachmentError; import org.whispersystems.textsecuregcm.entities.RestoreAccountRequest; import org.whispersystems.textsecuregcm.entities.TransferArchiveUploadedRequest; -import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.limits.RateLimiter; import org.whispersystems.textsecuregcm.limits.RateLimiters; import org.whispersystems.textsecuregcm.mappers.DeviceLimitExceededExceptionMapper; @@ -137,13 +136,9 @@ class DeviceControllerTest { when(primaryDevice.getId()).thenReturn(Device.PRIMARY_ID); when(account.getNextDeviceId()).thenReturn(NEXT_DEVICE_ID); - when(account.getNumber()).thenReturn(AuthHelper.VALID_NUMBER); - when(account.getNumberOptional()).thenReturn(Optional.of((AuthHelper.VALID_NUMBER))); + when(account.getNumber()).thenReturn(Optional.of((AuthHelper.VALID_NUMBER))); when(account.getAccountIdentifier()).thenReturn(AuthHelper.VALID_UUID); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(AuthHelper.VALID_UUID); - when(account.getPhoneNumberIdentifier()).thenReturn(AuthHelper.VALID_PNI); - when(account.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(AuthHelper.VALID_PNI)); - when(account.getIdentifier(IdentityType.PNI)).thenReturn(AuthHelper.VALID_PNI); + when(account.getPhoneNumberIdentifier()).thenReturn(Optional.of(AuthHelper.VALID_PNI)); when(account.getPrimaryDevice()).thenReturn(primaryDevice); when(account.getDevice(anyByte())).thenReturn(Optional.empty()); when(account.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(primaryDevice)); @@ -191,7 +186,7 @@ class DeviceControllerTest { when(refreshedDevice.getId()).thenReturn(deviceId); when(refreshedDevice.getName()).thenReturn(deviceName); when(refreshedDevice.getLastSeen()).thenReturn(deviceLastSeen); - when(refreshedDevice.getRegistrationId(IdentityType.ACI)).thenReturn(registrationId); + when(refreshedDevice.getAccountRegistrationId()).thenReturn(registrationId); when(refreshedDevice.getCreatedAtCiphertext()).thenReturn(createdAtCiphertext); final Account refreshedAccount = mock(Account.class); @@ -741,7 +736,7 @@ class DeviceControllerTest { when(account.getDevices()).thenReturn(List.of(existingDevice)); when(account.getAccountIdentityKey()).thenReturn(new IdentityKey(aciIdentityKeyPair.getPublicKey())); - when(account.getPhoneNumberIdentifierOptional()).thenReturn(Optional.empty()); + when(account.getPhoneNumberIdentifier()).thenReturn(Optional.empty()); when(accountsManager.checkDeviceLinkingToken(anyString())).thenReturn(Optional.of(AuthHelper.VALID_UUID)); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/DirectoryControllerV2Test.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/DirectoryControllerV2Test.java index 9fe34d7a7..e0d65370c 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/DirectoryControllerV2Test.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/DirectoryControllerV2Test.java @@ -36,7 +36,7 @@ class DirectoryControllerV2Test { final Account account = mock(Account.class); final UUID uuid = UUID.fromString("11111111-1111-1111-1111-111111111111"); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(uuid); + when(account.getAccountIdentifier()).thenReturn(uuid); final ExternalServiceCredentials credentials = controller.getAuthToken( new AuthenticatedDevice(uuid, Device.PRIMARY_ID, Instant.now())); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/KeysControllerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/KeysControllerTest.java index 93244378d..9e5837115 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/KeysControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/KeysControllerTest.java @@ -186,8 +186,8 @@ class KeysControllerTest { private Device createSampleDevice(byte deviceId, int registrationId, int pniRegistrationId) { final Device sampleDevice = mock(Device.class); - when(sampleDevice.getRegistrationId(IdentityType.ACI)).thenReturn(registrationId); - when(sampleDevice.getRegistrationId(IdentityType.PNI)).thenReturn(pniRegistrationId); + when(sampleDevice.getAccountRegistrationId()).thenReturn(registrationId); + when(sampleDevice.getPhoneNumberIdentityRegistrationId()).thenReturn(Optional.of(pniRegistrationId)); when(sampleDevice.getId()).thenReturn(deviceId); return sampleDevice; @@ -212,20 +212,15 @@ class KeysControllerTest { when(KEYS.takeDevicePreKeys(eq(SAMPLE_DEVICE_ID), eq(EXISTS_PNI_SERVICE_ID), any())) .thenReturn(CompletableFuture.completedFuture(Optional.of(pniKeys))); - when(existsAccount.getAccountIdentifier()).thenReturn(EXISTS_UUID); when(existsAccount.isIdentifiedBy(new AciServiceIdentifier(EXISTS_UUID))).thenReturn(true); - when(existsAccount.getPhoneNumberIdentifier()).thenReturn(EXISTS_PNI); when(existsAccount.isIdentifiedBy(new PniServiceIdentifier(EXISTS_PNI))).thenReturn(true); - when(existsAccount.getIdentifier(any())).thenThrow(new UnsupportedOperationException()); - when(existsAccount.getPhoneNumberIdentifier()).thenThrow(new UnsupportedOperationException()); when(existsAccount.getAccountIdentifier()).thenReturn(EXISTS_ACI.uuid()); - when(existsAccount.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(EXISTS_PNI)); + when(existsAccount.getPhoneNumberIdentifier()).thenReturn(Optional.of(EXISTS_PNI)); when(existsAccount.getDevice(SAMPLE_DEVICE_ID)).thenReturn(Optional.of(sampleDevice)); when(existsAccount.getDevices()).thenReturn(List.of(sampleDevice)); - when(existsAccount.getIdentityKey(IdentityType.ACI)).thenReturn(IDENTITY_KEY); - when(existsAccount.getIdentityKey(IdentityType.PNI)).thenReturn(PNI_IDENTITY_KEY); - when(existsAccount.getNumber()).thenReturn(EXISTS_NUMBER); - when(existsAccount.getNumberOptional()).thenReturn(Optional.of(EXISTS_NUMBER)); + when(existsAccount.getAccountIdentityKey()).thenReturn(IDENTITY_KEY); + when(existsAccount.getPhoneNumberIdentityKey()).thenReturn(Optional.of(PNI_IDENTITY_KEY)); + when(existsAccount.getNumber()).thenReturn(Optional.of(EXISTS_NUMBER)); when(existsAccount.getUnidentifiedAccessKey()).thenReturn(Optional.of(EXISTS_UAK)); when(accounts.getByServiceIdentifier(any())).thenReturn(Optional.empty()); @@ -303,7 +298,7 @@ class KeysControllerTest { .header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD)) .get(PreKeyResponse.class); - assertThat(result.getIdentityKey()).isEqualTo(existsAccount.getIdentityKey(IdentityType.ACI)); + assertThat(result.getIdentityKey()).isEqualTo(existsAccount.getAccountIdentityKey()); assertThat(result.getDevicesCount()).isEqualTo(1); assertEquals(SAMPLE_KEY, result.getDevice(SAMPLE_DEVICE_ID).getPreKey()); assertThat(result.getDevice(SAMPLE_DEVICE_ID).getPqPreKey()).isEqualTo(SAMPLE_PQ_KEY); @@ -323,7 +318,7 @@ class KeysControllerTest { .header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD)) .get(PreKeyResponse.class); - assertThat(result.getIdentityKey()).isEqualTo(existsAccount.getIdentityKey(IdentityType.ACI)); + assertThat(result.getIdentityKey()).isEqualTo(existsAccount.getAccountIdentityKey()); assertThat(result.getDevicesCount()).isEqualTo(1); assertEquals(SAMPLE_KEY, result.getDevice(SAMPLE_DEVICE_ID).getPreKey()); assertEquals(SAMPLE_PQ_KEY, result.getDevice(SAMPLE_DEVICE_ID).getPqPreKey()); @@ -342,7 +337,7 @@ class KeysControllerTest { .header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD)) .get(PreKeyResponse.class); - assertThat(result.getIdentityKey()).isEqualTo(existsAccount.getIdentityKey(IdentityType.PNI)); + assertThat(result.getIdentityKey()).isEqualTo(existsAccount.getPhoneNumberIdentityKey().orElseThrow()); assertThat(result.getDevicesCount()).isEqualTo(1); assertEquals(SAMPLE_KEY_PNI, result.getDevice(SAMPLE_DEVICE_ID).getPreKey()); assertThat(result.getDevice(SAMPLE_DEVICE_ID).getPqPreKey()).isEqualTo(SAMPLE_PQ_KEY_PNI); @@ -362,7 +357,7 @@ class KeysControllerTest { .header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD)) .get(PreKeyResponse.class); - assertThat(result.getIdentityKey()).isEqualTo(existsAccount.getIdentityKey(IdentityType.PNI)); + assertThat(result.getIdentityKey()).isEqualTo(existsAccount.getPhoneNumberIdentityKey().orElseThrow()); assertThat(result.getDevicesCount()).isEqualTo(1); assertEquals(SAMPLE_KEY_PNI, result.getDevice(SAMPLE_DEVICE_ID).getPreKey()); assertThat(result.getDevice(SAMPLE_DEVICE_ID).getPqPreKey()).isEqualTo(SAMPLE_PQ_KEY_PNI); @@ -405,7 +400,7 @@ class KeysControllerTest { .header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, AuthHelper.getUnidentifiedAccessHeader(EXISTS_UAK)) .get(PreKeyResponse.class); - assertThat(result.getIdentityKey()).isEqualTo(existsAccount.getIdentityKey(IdentityType.ACI)); + assertThat(result.getIdentityKey()).isEqualTo(existsAccount.getAccountIdentityKey()); assertThat(result.getDevicesCount()).isEqualTo(1); assertEquals(SAMPLE_KEY, result.getDevice(SAMPLE_DEVICE_ID).getPreKey()); assertEquals(SAMPLE_PQ_KEY, result.getDevice(SAMPLE_DEVICE_ID).getPqPreKey()); @@ -470,7 +465,7 @@ class KeysControllerTest { if (expectedResponse == 200) { PreKeyResponse result = response.readEntity(PreKeyResponse.class); - assertThat(result.getIdentityKey()).isEqualTo(existsAccount.getIdentityKey(IdentityType.ACI)); + assertThat(result.getIdentityKey()).isEqualTo(existsAccount.getAccountIdentityKey()); assertThat(result.getDevicesCount()).isEqualTo(1); assertEquals(SAMPLE_KEY, result.getDevice(SAMPLE_DEVICE_ID).getPreKey()); assertEquals(SAMPLE_PQ_KEY, result.getDevice(SAMPLE_DEVICE_ID).getPqPreKey()); @@ -577,14 +572,20 @@ class KeysControllerTest { .get(PreKeyResponse.class); assertThat(results.getDevicesCount()).isEqualTo(4); - assertThat(results.getIdentityKey()).isEqualTo(existsAccount.getIdentityKey(identityType)); + assertThat(results.getIdentityKey()).isEqualTo(switch (identityType) { + case ACI -> existsAccount.getAccountIdentityKey(); + case PNI -> existsAccount.getPhoneNumberIdentityKey().orElseThrow(); + }); for (int i = 0; i < 4; i++) { final PreKeyResponseItem result = results.getDevice((byte) i); final KeysManager.DevicePreKeys expectedPreKeys = devicePreKeys.get(i); final Device expectedDevice = devices.get(i); - assertEquals(expectedDevice.getRegistrationId(identityType), result.getRegistrationId()); + assertEquals(switch (identityType) { + case ACI -> expectedDevice.getAccountRegistrationId(); + case PNI -> (int) expectedDevice.getPhoneNumberIdentityRegistrationId().orElseThrow(); + }, result.getRegistrationId()); assertEquals(expectedPreKeys.ecPreKey().orElseThrow(), result.getPreKey()); assertEquals(expectedPreKeys.ecSignedPreKey(), result.getSignedPreKey()); assertEquals(expectedPreKeys.kemSignedPreKey(), result.getPqPreKey()); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/MessageControllerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/MessageControllerTest.java index d3d6cb647..a79480282 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/MessageControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/MessageControllerTest.java @@ -79,7 +79,6 @@ import org.whispersystems.textsecuregcm.entities.SendMultiRecipientMessageRespon import org.whispersystems.textsecuregcm.entities.SpamReport; import org.whispersystems.textsecuregcm.entities.StaleDevicesResponse; import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; -import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier; import org.whispersystems.textsecuregcm.identity.ServiceIdentifier; import org.whispersystems.textsecuregcm.limits.CardinalityEstimator; @@ -723,8 +722,8 @@ class MessageControllerTest { final Account account = mock(Account.class); when(account.getAccountIdentifier()).thenReturn(senderAci); - when(account.getNumberOptional()).thenReturn(Optional.of(senderNumber)); - when(account.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(senderPni)); + when(account.getNumber()).thenReturn(Optional.of(senderNumber)); + when(account.getPhoneNumberIdentifier()).thenReturn(Optional.of(senderPni)); when(accountsManager.getByE164(senderNumber)).thenReturn(Optional.of(account)); @@ -755,8 +754,8 @@ class MessageControllerTest { final Account account = mock(Account.class); when(account.getAccountIdentifier()).thenReturn(senderAci); - when(account.getNumberOptional()).thenReturn(Optional.of(senderNumber)); - when(account.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(senderPni)); + when(account.getNumber()).thenReturn(Optional.of(senderNumber)); + when(account.getPhoneNumberIdentifier()).thenReturn(Optional.of(senderPni)); when(accountsManager.getByE164(senderNumber)).thenReturn(Optional.empty()); when(phoneNumberIdentifiers.getPhoneNumberIdentifier(senderNumber)).thenReturn(CompletableFuture.completedFuture(senderPni)); @@ -787,8 +786,8 @@ class MessageControllerTest { final Account account = mock(Account.class); when(account.getAccountIdentifier()).thenReturn(senderAci); - when(account.getNumberOptional()).thenReturn(Optional.of(senderNumber)); - when(account.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(senderPni)); + when(account.getNumber()).thenReturn(Optional.of(senderNumber)); + when(account.getPhoneNumberIdentifier()).thenReturn(Optional.of(senderPni)); when(accountsManager.getByAccountIdentifier(senderAci)).thenReturn(Optional.of(account)); when(phoneNumberIdentifiers.getPhoneNumber(senderPni)).thenReturn(CompletableFuture.completedFuture(List.of(senderNumber))); @@ -820,8 +819,8 @@ class MessageControllerTest { final Account account = mock(Account.class); when(account.getAccountIdentifier()).thenReturn(senderAci); - when(account.getNumberOptional()).thenReturn(Optional.of(senderNumber)); - when(account.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(senderPni)); + when(account.getNumber()).thenReturn(Optional.of(senderNumber)); + when(account.getPhoneNumberIdentifier()).thenReturn(Optional.of(senderPni)); when(accountsManager.getByAccountIdentifier(senderAci)).thenReturn(Optional.empty()); when(accountsManager.findRecentlyDeletedPhoneNumberIdentifier(senderAci)).thenReturn(Optional.of(senderPni)); @@ -852,8 +851,8 @@ class MessageControllerTest { final Account account = mock(Account.class); when(account.getAccountIdentifier()).thenReturn(senderAci); - when(account.getNumberOptional()).thenReturn(Optional.of(senderNumber)); - when(account.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(senderPni)); + when(account.getNumber()).thenReturn(Optional.of(senderNumber)); + when(account.getPhoneNumberIdentifier()).thenReturn(Optional.of(senderPni)); when(accountsManager.getByAccountIdentifier(senderAci)).thenReturn(Optional.of(account)); when(accountsManager.findRecentlyDeletedPhoneNumberIdentifier(senderAci)).thenReturn(Optional.of(senderPni)); @@ -917,8 +916,8 @@ class MessageControllerTest { final Account account = mock(Account.class); when(account.getAccountIdentifier()).thenReturn(senderAci); - when(account.getNumberOptional()).thenReturn(Optional.of(senderNumber)); - when(account.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(senderPni)); + when(account.getNumber()).thenReturn(Optional.of(senderNumber)); + when(account.getPhoneNumberIdentifier()).thenReturn(Optional.of(senderPni)); when(accountsManager.getByAccountIdentifier(senderAci)).thenReturn(Optional.of(account)); when(accountsManager.findRecentlyDeletedPhoneNumberIdentifier(senderAci)).thenReturn(Optional.of(senderPni)); @@ -1096,25 +1095,25 @@ class MessageControllerTest { final Device singleDeviceAccountPrimary = mock(Device.class); when(singleDeviceAccountPrimary.getId()).thenReturn(Device.PRIMARY_ID); - when(singleDeviceAccountPrimary.getRegistrationId(IdentityType.ACI)).thenReturn(singleDevicePrimaryRegistrationId); + when(singleDeviceAccountPrimary.getAccountRegistrationId()).thenReturn(singleDevicePrimaryRegistrationId); final Device multiDeviceAccountPrimary = mock(Device.class); when(multiDeviceAccountPrimary.getId()).thenReturn(Device.PRIMARY_ID); - when(multiDeviceAccountPrimary.getRegistrationId(IdentityType.ACI)).thenReturn(multiDevicePrimaryRegistrationId); + when(multiDeviceAccountPrimary.getAccountRegistrationId()).thenReturn(multiDevicePrimaryRegistrationId); final Device multiDeviceAccountLinked = mock(Device.class); when(multiDeviceAccountLinked.getId()).thenReturn((byte) (Device.PRIMARY_ID + 1)); - when(multiDeviceAccountLinked.getRegistrationId(IdentityType.ACI)).thenReturn(multiDeviceLinkedRegistrationId); + when(multiDeviceAccountLinked.getAccountRegistrationId()).thenReturn(multiDeviceLinkedRegistrationId); final Account singleDeviceAccount = mock(Account.class); - when(singleDeviceAccount.getIdentifier(IdentityType.ACI)).thenReturn(singleDeviceAccountAci); + when(singleDeviceAccount.getAccountIdentifier()).thenReturn(singleDeviceAccountAci); when(singleDeviceAccount.getUnidentifiedAccessKey()).thenReturn(Optional.of(singleDeviceAccountUak)); when(singleDeviceAccount.getDevices()).thenReturn(List.of(singleDeviceAccountPrimary)); when(singleDeviceAccount.getDevice(anyByte())).thenReturn(Optional.empty()); when(singleDeviceAccount.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(singleDeviceAccountPrimary)); final Account multiDeviceAccount = mock(Account.class); - when(multiDeviceAccount.getIdentifier(IdentityType.ACI)).thenReturn(multiDeviceAccountAci); + when(multiDeviceAccount.getAccountIdentifier()).thenReturn(multiDeviceAccountAci); when(multiDeviceAccount.getUnidentifiedAccessKey()).thenReturn(Optional.of(multiDeviceAccountUak)); when(multiDeviceAccount.getDevices()).thenReturn(List.of(multiDeviceAccountPrimary, multiDeviceAccountLinked)); when(multiDeviceAccount.getDevice(anyByte())).thenReturn(Optional.empty()); @@ -1514,25 +1513,25 @@ class MessageControllerTest { final Device singleDeviceAccountPrimary = mock(Device.class); when(singleDeviceAccountPrimary.getId()).thenReturn(Device.PRIMARY_ID); - when(singleDeviceAccountPrimary.getRegistrationId(IdentityType.ACI)).thenReturn(singleDevicePrimaryRegistrationId); + when(singleDeviceAccountPrimary.getAccountRegistrationId()).thenReturn(singleDevicePrimaryRegistrationId); final Device multiDeviceAccountPrimary = mock(Device.class); when(multiDeviceAccountPrimary.getId()).thenReturn(Device.PRIMARY_ID); - when(multiDeviceAccountPrimary.getRegistrationId(IdentityType.ACI)).thenReturn(multiDevicePrimaryRegistrationId); + when(multiDeviceAccountPrimary.getAccountRegistrationId()).thenReturn(multiDevicePrimaryRegistrationId); final Device multiDeviceAccountLinked = mock(Device.class); when(multiDeviceAccountLinked.getId()).thenReturn((byte) (Device.PRIMARY_ID + 1)); - when(multiDeviceAccountLinked.getRegistrationId(IdentityType.ACI)).thenReturn(multiDeviceLinkedRegistrationId); + when(multiDeviceAccountLinked.getAccountRegistrationId()).thenReturn(multiDeviceLinkedRegistrationId); final Account singleDeviceAccount = mock(Account.class); - when(singleDeviceAccount.getIdentifier(IdentityType.ACI)).thenReturn(singleDeviceAccountAci); + when(singleDeviceAccount.getAccountIdentifier()).thenReturn(singleDeviceAccountAci); when(singleDeviceAccount.getUnidentifiedAccessKey()).thenReturn(Optional.of(singleDeviceAccountUak)); when(singleDeviceAccount.getDevices()).thenReturn(List.of(singleDeviceAccountPrimary)); when(singleDeviceAccount.getDevice(anyByte())).thenReturn(Optional.empty()); when(singleDeviceAccount.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(singleDeviceAccountPrimary)); final Account multiDeviceAccount = mock(Account.class); - when(multiDeviceAccount.getIdentifier(IdentityType.ACI)).thenReturn(multiDeviceAccountAci); + when(multiDeviceAccount.getAccountIdentifier()).thenReturn(multiDeviceAccountAci); when(multiDeviceAccount.getUnidentifiedAccessKey()).thenReturn(Optional.of(multiDeviceAccountUak)); when(multiDeviceAccount.getDevices()).thenReturn(List.of(multiDeviceAccountPrimary, multiDeviceAccountLinked)); when(multiDeviceAccount.getDevice(anyByte())).thenReturn(Optional.empty()); @@ -1600,10 +1599,10 @@ class MessageControllerTest { final Device singleDeviceAccountPrimary = mock(Device.class); when(singleDeviceAccountPrimary.getId()).thenReturn(Device.PRIMARY_ID); - when(singleDeviceAccountPrimary.getRegistrationId(IdentityType.ACI)).thenReturn(singleDevicePrimaryRegistrationId); + when(singleDeviceAccountPrimary.getAccountRegistrationId()).thenReturn(singleDevicePrimaryRegistrationId); final Account singleDeviceAccount = mock(Account.class); - when(singleDeviceAccount.getIdentifier(IdentityType.ACI)).thenReturn(singleDeviceAccountAci); + when(singleDeviceAccount.getAccountIdentifier()).thenReturn(singleDeviceAccountAci); when(singleDeviceAccount.getUnidentifiedAccessKey()).thenReturn(Optional.of(singleDeviceAccountUak)); when(singleDeviceAccount.getDevices()).thenReturn(List.of(singleDeviceAccountPrimary)); when(singleDeviceAccount.getDevice(anyByte())).thenReturn(Optional.empty()); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/ProfileControllerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/ProfileControllerTest.java index 7cc5bb37a..b7e358143 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/ProfileControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/ProfileControllerTest.java @@ -97,7 +97,6 @@ import org.whispersystems.textsecuregcm.entities.ExpiringProfileKeyCredentialPro import org.whispersystems.textsecuregcm.entities.ProfileAvatarUploadAttributes; import org.whispersystems.textsecuregcm.entities.VersionedProfileResponse; import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; -import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier; import org.whispersystems.textsecuregcm.identity.ServiceIdentifier; import org.whispersystems.textsecuregcm.limits.RateLimiter; @@ -215,10 +214,10 @@ class ProfileControllerTest { profileAccount = mock(Account.class); - when(profileAccount.getIdentityKey(IdentityType.ACI)).thenReturn(ACCOUNT_TWO_IDENTITY_KEY); - when(profileAccount.getIdentityKey(IdentityType.PNI)).thenReturn(ACCOUNT_TWO_PHONE_NUMBER_IDENTITY_KEY); + when(profileAccount.getAccountIdentityKey()).thenReturn(ACCOUNT_TWO_IDENTITY_KEY); + when(profileAccount.getPhoneNumberIdentityKey()).thenReturn(Optional.of(ACCOUNT_TWO_PHONE_NUMBER_IDENTITY_KEY)); when(profileAccount.getAccountIdentifier()).thenReturn(AuthHelper.VALID_UUID_TWO); - when(profileAccount.getPhoneNumberIdentifier()).thenReturn(AuthHelper.VALID_PNI_TWO); + when(profileAccount.getPhoneNumberIdentifier()).thenReturn(Optional.of(AuthHelper.VALID_PNI_TWO)); when(profileAccount.getCurrentProfileVersion()).thenReturn(Optional.empty()); when(profileAccount.getUsernameHash()).thenReturn(Optional.of(USERNAME_HASH)); when(profileAccount.getUnidentifiedAccessKey()).thenReturn(Optional.of(UNIDENTIFIED_ACCESS_KEY)); @@ -228,8 +227,8 @@ class ProfileControllerTest { capabilitiesAccount = mock(Account.class); when(capabilitiesAccount.getAccountIdentifier()).thenReturn(AuthHelper.VALID_UUID); - when(capabilitiesAccount.getIdentityKey(IdentityType.ACI)).thenReturn(ACCOUNT_IDENTITY_KEY); - when(capabilitiesAccount.getIdentityKey(IdentityType.PNI)).thenReturn(ACCOUNT_PHONE_NUMBER_IDENTITY_KEY); + when(capabilitiesAccount.getAccountIdentityKey()).thenReturn(ACCOUNT_IDENTITY_KEY); + when(capabilitiesAccount.getPhoneNumberIdentityKey()).thenReturn(Optional.of(ACCOUNT_PHONE_NUMBER_IDENTITY_KEY)); when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.empty()); @@ -1042,7 +1041,7 @@ class ProfileControllerTest { void testGetProfileWithExpiringProfileKeyCredentialVersionNotFound() throws VerificationFailedException { final Account account = mock(Account.class); when(account.getAccountIdentifier()).thenReturn(AuthHelper.VALID_UUID); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(AuthHelper.VALID_UUID); + when(account.getAccountIdentifier()).thenReturn(AuthHelper.VALID_UUID); when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version("version"))); when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID)).thenReturn(Optional.of(account)); @@ -1254,7 +1253,7 @@ class ProfileControllerTest { final Account account = mock(Account.class); when(account.getAccountIdentifier()).thenReturn(AuthHelper.VALID_UUID); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(AuthHelper.VALID_UUID); + when(account.getAccountIdentifier()).thenReturn(AuthHelper.VALID_UUID); when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version)); when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(UNIDENTIFIED_ACCESS_KEY)); when(account.isIdentifiedBy(new AciServiceIdentifier(AuthHelper.VALID_UUID))).thenReturn(true); 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 c903a7fc3..e7c1dca5d 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/RegistrationControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/RegistrationControllerTest.java @@ -303,7 +303,7 @@ class RegistrationControllerTest { final Account account = mock(Account.class); when(accountsManager.getByE164(any())).thenReturn(Optional.of(account)); - when(account.getNumberOptional()).thenReturn(Optional.of(NUMBER)); + when(account.getNumber()).thenReturn(Optional.of(NUMBER)); when(account.hasCapability(DeviceCapability.TRANSFER)).thenReturn(deviceTransferSupported); final int expectedStatus; @@ -355,7 +355,7 @@ class RegistrationControllerTest { final Account account = mock(Account.class); when(accountsManager.getByE164(oldFormatBeninNumber)).thenReturn(Optional.of(account)); - when(account.getNumberOptional()).thenReturn(Optional.of(oldFormatBeninNumber)); + when(account.getNumber()).thenReturn(Optional.of(oldFormatBeninNumber)); when(accountsManager.getByE164(newFormatBeninNumber)).thenReturn(Optional.empty()); doThrow(new WebApplicationException(RegistrationLockError.MISMATCH.getExpectedStatus())) @@ -386,7 +386,7 @@ class RegistrationControllerTest { if (existingAccount) { final Account account = mock(Account.class); when(account.hasCapability(DeviceCapability.TRANSFER)).thenReturn(transferSupported); - when(account.getNumberOptional()).thenReturn(Optional.of(NUMBER)); + when(account.getNumber()).thenReturn(Optional.of(NUMBER)); maybeAccount = Optional.of(account); } else { maybeAccount = Optional.empty(); @@ -660,7 +660,7 @@ class RegistrationControllerTest { @ValueSource(booleans = {true, false}) void reregistrationFlag(final boolean accountExists) { final Account existingAccount = mock(Account.class); - when(existingAccount.getNumberOptional()).thenReturn(Optional.of(NUMBER)); + when(existingAccount.getNumber()).thenReturn(Optional.of(NUMBER)); when(accountsManager.getByE164(any())).thenReturn(accountExists ? Optional.of(existingAccount) : Optional.empty()); final Account account = mock(Account.class); @@ -1457,7 +1457,7 @@ class RegistrationControllerTest { final Account account = mock(Account.class); when(account.getAccountIdentifier()).thenReturn(accountIdentifier); - when(account.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(phoneNumberIdentifier)); + when(account.getPhoneNumberIdentifier()).thenReturn(Optional.of(phoneNumberIdentifier)); when(account.getPrimaryDevice()).thenReturn(device); when(accountsManager.create(any(), any(), any(), any(), any(), any())) diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/VerificationControllerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/VerificationControllerTest.java index ca67d1667..e4ecdb0a1 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/VerificationControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/VerificationControllerTest.java @@ -1054,7 +1054,7 @@ class VerificationControllerTest { final UUID accountIdentifier = UUID.randomUUID(); final Account existingAccount = mock(Account.class); - when(existingAccount.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier); + when(existingAccount.getAccountIdentifier()).thenReturn(accountIdentifier); when(accountsManager.getByE164(any())) .thenReturn(accountExistsWithNumber ? Optional.of(existingAccount) : Optional.empty()); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/experiment/IdleDevicePushNotificationExperimentTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/experiment/IdleDevicePushNotificationExperimentTest.java index 90a899f31..388deee9f 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/experiment/IdleDevicePushNotificationExperimentTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/experiment/IdleDevicePushNotificationExperimentTest.java @@ -72,7 +72,7 @@ abstract class IdleDevicePushNotificationExperimentTest { { final Device apnsDevice = mock(Device.class); when(apnsDevice.getApnId()).thenReturn("apns-token"); - when(apnsDevice.getRegistrationId(IdentityType.ACI)).thenReturn(registrationId); + when(apnsDevice.getAccountRegistrationId()).thenReturn(registrationId); when(apnsDevice.getLastSeen()).thenReturn(CURRENT_TIME.toEpochMilli()); assertEquals( @@ -83,7 +83,7 @@ abstract class IdleDevicePushNotificationExperimentTest { { final Device fcmDevice = mock(Device.class); when(fcmDevice.getGcmId()).thenReturn("fcm-token"); - when(fcmDevice.getRegistrationId(IdentityType.ACI)).thenReturn(registrationId); + when(fcmDevice.getAccountRegistrationId()).thenReturn(registrationId); when(fcmDevice.getLastSeen()).thenReturn(CURRENT_TIME.toEpochMilli()); assertEquals( @@ -93,7 +93,7 @@ abstract class IdleDevicePushNotificationExperimentTest { { final Device noTokenDevice = mock(Device.class); - when(noTokenDevice.getRegistrationId(IdentityType.ACI)).thenReturn(registrationId); + when(noTokenDevice.getAccountRegistrationId()).thenReturn(registrationId); when(noTokenDevice.getLastSeen()).thenReturn(CURRENT_TIME.toEpochMilli()); assertEquals( diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/AccountsGrpcServiceTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/AccountsGrpcServiceTest.java index 8ac296cae..1373f4e2d 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/AccountsGrpcServiceTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/AccountsGrpcServiceTest.java @@ -187,11 +187,11 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest @@ -751,7 +751,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest setPreKeysFunction) { - when(authenticatedAccount.getPhoneNumberIdentifierOptional()).thenReturn(Optional.empty()); + when(authenticatedAccount.getPhoneNumberIdentifier()).thenReturn(Optional.empty()); assertStatusException(Status.INVALID_ARGUMENT, () -> setPreKeysFunction.apply(authenticatedServiceStub())); @@ -557,8 +554,18 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest { + when(targetAccount.getAccountIdentifier()).thenReturn(identifier); + when(targetAccount.getAccountIdentityKey()).thenReturn(identityKey); + } + case PNI -> { + when(targetAccount.getPhoneNumberIdentifier()).thenReturn(Optional.of(identifier)); + when(targetAccount.getPhoneNumberIdentityKey()).thenReturn(Optional.of(identityKey)); + } + } + when(accountsManager.getByServiceIdentifier(serviceIdentifier)) .thenReturn(Optional.of(targetAccount)); @@ -605,7 +612,11 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest when(device.getAccountRegistrationId()).thenReturn(entry.getValue()); + case PNI -> when(device.getPhoneNumberIdentityRegistrationId()).thenReturn(Optional.of(entry.getValue())); + } devices.put(entry.getKey(), device); when(targetAccount.getDevice(entry.getKey())).thenReturn(Optional.of(device)); @@ -674,7 +685,7 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest { + when(targetAccount.getAccountIdentifier()).thenReturn(identifier); + when(targetAccount.getAccountIdentityKey()).thenReturn(identityKey); + } + case PNI -> { + when(targetAccount.getPhoneNumberIdentifier()).thenReturn(Optional.of(identifier)); + when(targetAccount.getPhoneNumberIdentityKey()).thenReturn(Optional.of(identityKey)); + } + } + when(accountsManager.getByServiceIdentifier(serviceIdentifier)) .thenReturn(Optional.of(targetAccount)); @@ -770,7 +791,11 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest when(device.getAccountRegistrationId()).thenReturn(registrationId); + case PNI -> when(device.getPhoneNumberIdentityRegistrationId()).thenReturn(Optional.of(registrationId)); + } final Map devices = Map.of(deviceId1, device); when(targetAccount.getDevice(deviceId1)).thenReturn(Optional.of(device)); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MessageDispatcherIntegrationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MessageDispatcherIntegrationTest.java index 6ed00539e..01716f184 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MessageDispatcherIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MessageDispatcherIntegrationTest.java @@ -19,6 +19,7 @@ import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; @@ -44,7 +45,6 @@ import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfigurati import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope; import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager; import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; -import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor; import org.whispersystems.textsecuregcm.metrics.MessageMetrics; import org.whispersystems.textsecuregcm.push.PushNotificationManager; @@ -119,8 +119,8 @@ class MessageDispatcherIntegrationTest { device = mock(Device.class); clientReleaseManager = mock(ClientReleaseManager.class); - when(account.getNumber()).thenReturn("+18005551234"); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(UUID.randomUUID()); + when(account.getNumber()).thenReturn(Optional.of("+18005551234")); + when(account.getAccountIdentifier()).thenReturn(UUID.randomUUID()); when(device.getId()).thenReturn(Device.PRIMARY_ID); redisMessageAvailabilityManager.start(); @@ -214,7 +214,7 @@ class MessageDispatcherIntegrationTest { final Exception thrown = assertThrows(Exception.class, () -> messageDispatcher .getMessages(true, null, account, device, acks.flux()) .doOnNext(response -> { - assertTrue(redisMessageAvailabilityManager.isLocallyPresent(account.getIdentifier(IdentityType.ACI), + assertTrue(redisMessageAvailabilityManager.isLocallyPresent(account.getAccountIdentifier(), device.getId())); receivedMessages.add(response.getEnvelope()); acks.error(new IOException("test exception")); @@ -223,7 +223,7 @@ class MessageDispatcherIntegrationTest { .block()); assertInstanceOf(IOException.class, thrown.getCause()); assertTrue(expectedMessages.containsAll(receivedMessages)); - assertFalse(redisMessageAvailabilityManager.isLocallyPresent(account.getIdentifier(IdentityType.ACI), device.getId())); + assertFalse(redisMessageAvailabilityManager.isLocallyPresent(account.getAccountIdentifier(), device.getId())); } private List fillRandomMessages(final int persistedMessageCount, final int cachedMessageCount) { @@ -233,13 +233,13 @@ class MessageDispatcherIntegrationTest { final Envelope envelope = generateRandomMessage(UUID.randomUUID()); expectedMessages.add(envelope); } - messagesDynamoDb.store(expectedMessages, account.getIdentifier(IdentityType.ACI), device); + messagesDynamoDb.store(expectedMessages, account.getAccountIdentifier(), device); for (int i = 0; i < cachedMessageCount; i++) { final UUID messageGuid = UUID.randomUUID(); final Envelope envelope = generateRandomMessage(messageGuid); - messagesCache.insert(messageGuid, account.getIdentifier(IdentityType.ACI), device.getId(), envelope).join(); + messagesCache.insert(messageGuid, account.getAccountIdentifier(), device.getId(), envelope).join(); expectedMessages.add(envelope); } return expectedMessages; diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MessageDispatcherTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MessageDispatcherTest.java index d5a92ee7c..8ba19f46a 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MessageDispatcherTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MessageDispatcherTest.java @@ -82,7 +82,7 @@ class MessageDispatcherTest { @BeforeEach void setUp() { account = mock(Account.class); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(ACI); + when(account.getAccountIdentifier()).thenReturn(ACI); when(account.getAccountIdentifier()).thenReturn(ACI); device = mock(Device.class); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MessagesAnonymousGrpcServiceTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MessagesAnonymousGrpcServiceTest.java index 610c34855..126166752 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MessagesAnonymousGrpcServiceTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MessagesAnonymousGrpcServiceTest.java @@ -1141,7 +1141,7 @@ class MessagesAnonymousGrpcServiceTest extends final Account destinationAccount = mock(Account.class); when(destinationAccount.getDevices()).thenReturn(List.of(destinationDevice)); when(destinationAccount.getDevice(deviceId)).thenReturn(Optional.of(destinationDevice)); - when(destinationAccount.getIdentifier(IdentityType.ACI)).thenReturn(serviceIdentifier.uuid()); + when(destinationAccount.getAccountIdentifier()).thenReturn(serviceIdentifier.uuid()); when(accountsManager.getByServiceIdentifier(serviceIdentifier)).thenReturn(Optional.of(destinationAccount)); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MessagesGrpcServiceTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MessagesGrpcServiceTest.java index 33a9f9f31..88221e708 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MessagesGrpcServiceTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MessagesGrpcServiceTest.java @@ -161,18 +161,18 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest(Optional.empty(), Optional.empty())); when(authenticatedDevice.getId()).thenReturn(AUTHENTICATED_DEVICE_ID); - when(authenticatedDevice.getRegistrationId(IdentityType.ACI)).thenReturn(AUTHENTICATED_REGISTRATION_ID); + when(authenticatedDevice.getAccountRegistrationId()).thenReturn(AUTHENTICATED_REGISTRATION_ID); when(authenticatedDevice.getLastSeen()).thenReturn(CLOCK.instant().toEpochMilli()); when(authenticatedDevice.isPrimary()).thenReturn(true); when(linkedDevice.getId()).thenReturn(LINKED_DEVICE_ID); - when(linkedDevice.getRegistrationId(IdentityType.ACI)).thenReturn(LINKED_DEVICE_REGISTRATION_ID); + when(linkedDevice.getAccountRegistrationId()).thenReturn(LINKED_DEVICE_REGISTRATION_ID); when(secondLinkedDevice.getId()).thenReturn(SECOND_LINKED_DEVICE_ID); - when(secondLinkedDevice.getRegistrationId(IdentityType.ACI)).thenReturn(SECOND_LINKED_DEVICE_REGISTRATION_ID); + when(secondLinkedDevice.getAccountRegistrationId()).thenReturn(SECOND_LINKED_DEVICE_REGISTRATION_ID); when(authenticatedAccount.getAccountIdentifier()).thenReturn(AUTHENTICATED_ACI); - when(authenticatedAccount.getIdentifier(IdentityType.ACI)).thenReturn(AUTHENTICATED_ACI); + when(authenticatedAccount.getAccountIdentifier()).thenReturn(AUTHENTICATED_ACI); when(authenticatedAccount.getDevice(anyByte())).thenReturn(Optional.empty()); when(authenticatedAccount.getDevice(AUTHENTICATED_DEVICE_ID)).thenReturn(Optional.of(authenticatedDevice)); when(authenticatedAccount.getDevice(LINKED_DEVICE_ID)).thenReturn(Optional.of(linkedDevice)); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProfileAnonymousGrpcServiceTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProfileAnonymousGrpcServiceTest.java index 88183ef44..2aea879ea 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProfileAnonymousGrpcServiceTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProfileAnonymousGrpcServiceTest.java @@ -184,7 +184,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest scoreThreshold, float actualScore, boolean expectSuccess) throws RateLimitExceededException, IOException, InvalidCaptchaArgumentException { final Account account = mock(Account.class); - when(account.getNumber()).thenReturn("+18005551234"); + when(account.getNumber()).thenReturn(Optional.of("+18005551234")); when(account.getAccountIdentifier()).thenReturn(UUID.randomUUID()); when(captchaChecker.verify(any(), eq(Action.CHALLENGE), any(), any(), any())) diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/metrics/MessageMetricsTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/metrics/MessageMetricsTest.java index c01ba0857..4cd7e5264 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/metrics/MessageMetricsTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/metrics/MessageMetricsTest.java @@ -36,7 +36,7 @@ class MessageMetricsTest { @BeforeEach void setup() { when(account.getAccountIdentifier()).thenReturn(aci); - when(account.getPhoneNumberIdentifier()).thenReturn(pni); + when(account.getPhoneNumberIdentifier()).thenReturn(Optional.of(pni)); when(account.isIdentifiedBy(any())).thenReturn(false); when(account.isIdentifiedBy(new AciServiceIdentifier(aci))).thenReturn(true); when(account.isIdentifiedBy(new PniServiceIdentifier(pni))).thenReturn(true); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/push/MessageSenderTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/push/MessageSenderTest.java index 88c52cbbd..0844321ca 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/push/MessageSenderTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/push/MessageSenderTest.java @@ -47,7 +47,6 @@ import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException; import org.whispersystems.textsecuregcm.controllers.MultiRecipientMismatchedDevicesException; import org.whispersystems.textsecuregcm.entities.MessageProtos; import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; -import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier; import org.whispersystems.textsecuregcm.identity.ServiceIdentifier; import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil; @@ -112,12 +111,12 @@ class MessageSenderTest { .build(); when(account.getAccountIdentifier()).thenReturn(accountIdentifier); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier); + when(account.getAccountIdentifier()).thenReturn(accountIdentifier); when(account.isIdentifiedBy(serviceIdentifier)).thenReturn(true); when(account.getDevices()).thenReturn(List.of(device)); when(account.getDevice(deviceId)).thenReturn(Optional.of(device)); when(device.getId()).thenReturn(deviceId); - when(device.getRegistrationId(IdentityType.ACI)).thenReturn(registrationId); + when(device.getAccountRegistrationId()).thenReturn(registrationId); if (hasPushToken) { when(device.getApnId()).thenReturn("apns-token"); @@ -169,12 +168,12 @@ class MessageSenderTest { final MessageProtos.Envelope message = MessageProtos.Envelope.newBuilder().build(); when(account.getAccountIdentifier()).thenReturn(accountIdentifier); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier); + when(account.getAccountIdentifier()).thenReturn(accountIdentifier); when(account.isIdentifiedBy(serviceIdentifier)).thenReturn(true); when(account.getDevices()).thenReturn(List.of(device)); when(account.getDevice(deviceId)).thenReturn(Optional.of(device)); when(device.getId()).thenReturn(deviceId); - when(device.getRegistrationId(IdentityType.ACI)).thenReturn(registrationId); + when(device.getAccountRegistrationId()).thenReturn(registrationId); when(device.getApnId()).thenReturn("apns-token"); final MismatchedDevicesException mismatchedDevicesException = @@ -210,12 +209,12 @@ class MessageSenderTest { final MessageProtos.Envelope message = MessageProtos.Envelope.newBuilder().build(); when(account.getAccountIdentifier()).thenReturn(accountIdentifier); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier); + when(account.getAccountIdentifier()).thenReturn(accountIdentifier); when(account.isIdentifiedBy(serviceIdentifier)).thenReturn(true); when(account.getDevices()).thenReturn(List.of(device)); when(account.getDevice(deviceId)).thenReturn(Optional.of(device)); when(device.getId()).thenReturn(deviceId); - when(device.getRegistrationId(IdentityType.ACI)).thenReturn(registrationId); + when(device.getAccountRegistrationId()).thenReturn(registrationId); when(device.getApnId()).thenReturn("apns-token"); when(dynamicMessageDeliveryConfiguration.isReadOnly()).thenReturn(true); @@ -246,12 +245,12 @@ class MessageSenderTest { final Device device = mock(Device.class); when(account.getAccountIdentifier()).thenReturn(accountIdentifier); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier); + when(account.getAccountIdentifier()).thenReturn(accountIdentifier); when(account.isIdentifiedBy(serviceIdentifier)).thenReturn(true); when(account.getDevices()).thenReturn(List.of(device)); when(account.getDevice(deviceId)).thenReturn(Optional.of(device)); when(device.getId()).thenReturn(deviceId); - when(device.getRegistrationId(IdentityType.ACI)).thenReturn(registrationId); + when(device.getAccountRegistrationId()).thenReturn(registrationId); when(device.getApnId()).thenReturn("apns-token"); if (hasPushToken) { @@ -307,12 +306,12 @@ class MessageSenderTest { final Device device = mock(Device.class); when(account.getAccountIdentifier()).thenReturn(accountIdentifier); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier); + when(account.getAccountIdentifier()).thenReturn(accountIdentifier); when(account.isIdentifiedBy(serviceIdentifier)).thenReturn(true); when(account.getDevices()).thenReturn(List.of(device)); when(account.getDevice(deviceId)).thenReturn(Optional.of(device)); when(device.getId()).thenReturn(deviceId); - when(device.getRegistrationId(IdentityType.ACI)).thenReturn(registrationId); + when(device.getAccountRegistrationId()).thenReturn(registrationId); when(device.getApnId()).thenReturn("apns-token"); final SealedSenderMultiRecipientMessage multiRecipientMessage = @@ -362,12 +361,12 @@ class MessageSenderTest { final Device device = mock(Device.class); when(account.getAccountIdentifier()).thenReturn(accountIdentifier); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier); + when(account.getAccountIdentifier()).thenReturn(accountIdentifier); when(account.isIdentifiedBy(serviceIdentifier)).thenReturn(true); when(account.getDevices()).thenReturn(List.of(device)); when(account.getDevice(deviceId)).thenReturn(Optional.of(device)); when(device.getId()).thenReturn(deviceId); - when(device.getRegistrationId(IdentityType.ACI)).thenReturn(registrationId); + when(device.getAccountRegistrationId()).thenReturn(registrationId); when(device.getApnId()).thenReturn("apns-token"); when(device.getApnId()).thenReturn("apns-token"); @@ -425,11 +424,11 @@ class MessageSenderTest { final Device primaryDevice = mock(Device.class); when(primaryDevice.getId()).thenReturn(primaryDeviceId); - when(primaryDevice.getRegistrationId(IdentityType.ACI)).thenReturn(primaryDeviceRegistrationId); + when(primaryDevice.getAccountRegistrationId()).thenReturn(primaryDeviceRegistrationId); final Device linkedDevice = mock(Device.class); when(linkedDevice.getId()).thenReturn(linkedDeviceId); - when(linkedDevice.getRegistrationId(IdentityType.ACI)).thenReturn(linkedDeviceRegistrationId); + when(linkedDevice.getAccountRegistrationId()).thenReturn(linkedDeviceRegistrationId); final Account destination = mock(Account.class); when(destination.isIdentifiedBy(any())).thenReturn(false); @@ -594,13 +593,13 @@ class MessageSenderTest { final Device primaryDevice = mock(Device.class); when(primaryDevice.getId()).thenReturn(primaryDeviceId); - when(primaryDevice.getRegistrationId(IdentityType.ACI)).thenReturn(primaryDeviceAciRegistrationId); - when(primaryDevice.getRegistrationId(IdentityType.PNI)).thenReturn(primaryDevicePniRegistrationId); + when(primaryDevice.getAccountRegistrationId()).thenReturn(primaryDeviceAciRegistrationId); + when(primaryDevice.getPhoneNumberIdentityRegistrationId()).thenReturn(Optional.of(primaryDevicePniRegistrationId)); final Device linkedDevice = mock(Device.class); when(linkedDevice.getId()).thenReturn(linkedDeviceId); - when(linkedDevice.getRegistrationId(IdentityType.ACI)).thenReturn(linkedDeviceAciRegistrationId); - when(linkedDevice.getRegistrationId(IdentityType.PNI)).thenReturn(linkedDevicePniRegistrationId); + when(linkedDevice.getAccountRegistrationId()).thenReturn(linkedDeviceAciRegistrationId); + when(linkedDevice.getPhoneNumberIdentityRegistrationId()).thenReturn(Optional.of(linkedDevicePniRegistrationId)); final Account account = mock(Account.class); when(account.getDevices()).thenReturn(List.of(primaryDevice, linkedDevice)); @@ -687,7 +686,7 @@ class MessageSenderTest { final Account account = mock(Account.class); when(account.getAccountIdentifier()).thenReturn(accountIdentifier); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier); + when(account.getAccountIdentifier()).thenReturn(accountIdentifier); when(account.isIdentifiedBy(serviceIdentifier)).thenReturn(true); final Account nonSyncDestination = mock(Account.class); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/push/PushNotificationManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/push/PushNotificationManagerTest.java index 145188dfb..54c1145b4 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/push/PushNotificationManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/push/PushNotificationManagerTest.java @@ -157,7 +157,7 @@ class PushNotificationManagerTest { final Device device = mock(Device.class); when(device.getId()).thenReturn(Device.PRIMARY_ID); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier); + when(account.getAccountIdentifier()).thenReturn(accountIdentifier); when(account.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(device)); AccountsHelper.setupMockGet(accountsManager, account); @@ -227,7 +227,7 @@ class PushNotificationManagerTest { when(device.getGcmId()).thenReturn("token"); when(account.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(device)); when(account.getAccountIdentifier()).thenReturn(aci); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(aci); + when(account.getAccountIdentifier()).thenReturn(aci); when(accountsManager.getByAccountIdentifier(aci)).thenReturn(Optional.of(account)); final PushNotification pushNotification = new PushNotification( @@ -253,7 +253,7 @@ class PushNotificationManagerTest { when(device.getApnId()).thenReturn("apns-token"); when(account.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(device)); when(account.getAccountIdentifier()).thenReturn(aci); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(aci); + when(account.getAccountIdentifier()).thenReturn(aci); when(accountsManager.getByAccountIdentifier(aci)).thenReturn(Optional.of(account)); final PushNotification pushNotification = new PushNotification( diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/push/PushNotificationSchedulerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/push/PushNotificationSchedulerTest.java index c9ccf7674..162fd640c 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/push/PushNotificationSchedulerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/push/PushNotificationSchedulerTest.java @@ -32,7 +32,6 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.EnumSource; import org.mockito.ArgumentCaptor; -import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient; import org.whispersystems.textsecuregcm.redis.RedisClusterExtension; import org.whispersystems.textsecuregcm.storage.Account; @@ -71,8 +70,7 @@ class PushNotificationSchedulerTest { account = mock(Account.class); when(account.getAccountIdentifier()).thenReturn(ACCOUNT_UUID); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(ACCOUNT_UUID); - when(account.getNumber()).thenReturn(ACCOUNT_NUMBER); + when(account.getNumber()).thenReturn(Optional.of(ACCOUNT_NUMBER)); when(account.getDevice(DEVICE_ID)).thenReturn(Optional.of(device)); final AccountsManager accountsManager = mock(AccountsManager.class); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/scheduler/SchedulingUtilTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/scheduler/SchedulingUtilTest.java index 3ff6b72bd..00c6b3087 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/scheduler/SchedulingUtilTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/scheduler/SchedulingUtilTest.java @@ -29,7 +29,7 @@ class SchedulingUtilTest { final Account account = mock(Account.class); // The account has a phone number that can be resolved to a region with known timezones - when(account.getNumberOptional()).thenReturn(Optional.of(PhoneNumberUtil.getInstance().format( + when(account.getNumber()).thenReturn(Optional.of(PhoneNumberUtil.getInstance().format( PhoneNumberUtil.getInstance().getExampleNumber("DE"), PhoneNumberUtil.PhoneNumberFormat.E164))); final ZoneId berlinZoneId = ZoneId.of("Europe/Berlin"); @@ -55,7 +55,7 @@ class SchedulingUtilTest { final Account account = mock(Account.class); // The account does not have a phone number that can be connected to a region/time zone - when(account.getNumberOptional()).thenReturn(Optional.ofNullable(number)); + when(account.getNumber()).thenReturn(Optional.ofNullable(number)); final ZonedDateTime beforeNotificationTime = ZonedDateTime.now(ZoneId.systemDefault()).with(LocalTime.of(13, 59)); final LocalTime preferredNotificationTime = LocalTime.of(14, 0); @@ -78,7 +78,7 @@ class SchedulingUtilTest { final Account account = mock(Account.class); // The account has a phone number that can be resolved to a region with known timezones - when(account.getNumberOptional()).thenReturn(Optional.of(PhoneNumberUtil.getInstance().format( + when(account.getNumber()).thenReturn(Optional.of(PhoneNumberUtil.getInstance().format( PhoneNumberUtil.getInstance().getExampleNumber("DE"), PhoneNumberUtil.PhoneNumberFormat.E164))); final LocalDateTime afterNotificationTime = LocalDateTime.of(2025, 3, 29, 15, 0); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountChangeValidatorTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountChangeValidatorTest.java index b7da68f59..70b2954b0 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountChangeValidatorTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountChangeValidatorTest.java @@ -54,28 +54,28 @@ class AccountChangeValidatorTest { private static Stream validateChange() { final Account originalAccount = mock(Account.class); - when(originalAccount.getNumberOptional()).thenReturn(Optional.of(ORIGINAL_NUMBER)); - when(originalAccount.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(ORIGINAL_PNI)); + when(originalAccount.getNumber()).thenReturn(Optional.of(ORIGINAL_NUMBER)); + when(originalAccount.getPhoneNumberIdentifier()).thenReturn(Optional.of(ORIGINAL_PNI)); when(originalAccount.getUsernameHash()).thenReturn(Optional.of(ORIGINAL_USERNAME_HASH)); final Account unchangedAccount = mock(Account.class); - when(unchangedAccount.getNumberOptional()).thenReturn(Optional.of(ORIGINAL_NUMBER)); - when(unchangedAccount.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(ORIGINAL_PNI)); + when(unchangedAccount.getNumber()).thenReturn(Optional.of(ORIGINAL_NUMBER)); + when(unchangedAccount.getPhoneNumberIdentifier()).thenReturn(Optional.of(ORIGINAL_PNI)); when(unchangedAccount.getUsernameHash()).thenReturn(Optional.of(ORIGINAL_USERNAME_HASH)); final Account changedNumberAccount = mock(Account.class); - when(changedNumberAccount.getNumberOptional()).thenReturn(Optional.of(CHANGED_NUMBER)); - when(changedNumberAccount.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(CHANGED_PNI)); + when(changedNumberAccount.getNumber()).thenReturn(Optional.of(CHANGED_NUMBER)); + when(changedNumberAccount.getPhoneNumberIdentifier()).thenReturn(Optional.of(CHANGED_PNI)); when(changedNumberAccount.getUsernameHash()).thenReturn(Optional.of(ORIGINAL_USERNAME_HASH)); final Account changedUsernameAccount = mock(Account.class); - when(changedUsernameAccount.getNumberOptional()).thenReturn(Optional.of(ORIGINAL_NUMBER)); - when(changedUsernameAccount.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(ORIGINAL_PNI)); + when(changedUsernameAccount.getNumber()).thenReturn(Optional.of(ORIGINAL_NUMBER)); + when(changedUsernameAccount.getPhoneNumberIdentifier()).thenReturn(Optional.of(ORIGINAL_PNI)); when(changedUsernameAccount.getUsernameHash()).thenReturn(Optional.of(CHANGED_USERNAME_HASH)); final Account numberlessAccount = mock(Account.class); - when(numberlessAccount.getNumberOptional()).thenReturn(Optional.empty()); - when(numberlessAccount.getPhoneNumberIdentifierOptional()).thenReturn(Optional.empty()); + when(numberlessAccount.getNumber()).thenReturn(Optional.empty()); + when(numberlessAccount.getPhoneNumberIdentifier()).thenReturn(Optional.empty()); when(numberlessAccount.getUsernameHash()).thenReturn(Optional.of(ORIGINAL_USERNAME_HASH)); return Stream.of( 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 500b6efb3..18652c096 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountCreationDeletionIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountCreationDeletionIntegrationTest.java @@ -267,10 +267,10 @@ public class AccountCreationDeletionIntegrationTest { Optional.of(pniPqLastResortPreKey)); assertEquals(Optional.of(aciSignedPreKey), keysManager.getEcSignedPreKey(account.getAccountIdentifier(), Device.PRIMARY_ID).join()); - assertEquals(Optional.of(pniSignedPreKey), keysManager.getEcSignedPreKey(account.getPhoneNumberIdentifierOptional().orElseThrow(), Device.PRIMARY_ID).join()); + assertEquals(Optional.of(pniSignedPreKey), keysManager.getEcSignedPreKey(account.getPhoneNumberIdentifier().orElseThrow(), Device.PRIMARY_ID).join()); assertEquals(Optional.of(aciPqLastResortPreKey), keysManager.getLastResort(account.getAccountIdentifier(), Device.PRIMARY_ID).join()); - assertEquals(Optional.of(pniPqLastResortPreKey), keysManager.getLastResort(account.getPhoneNumberIdentifierOptional().orElseThrow(), Device.PRIMARY_ID).join()); - assertTrue(phoneNumberRecoveryPasswordsManager.verify(account.getPhoneNumberIdentifierOptional().orElseThrow(), recoveryPassword)); + assertEquals(Optional.of(pniPqLastResortPreKey), keysManager.getLastResort(account.getPhoneNumberIdentifier().orElseThrow(), Device.PRIMARY_ID).join()); + assertTrue(phoneNumberRecoveryPasswordsManager.verify(account.getPhoneNumberIdentifier().orElseThrow(), recoveryPassword)); } @ParameterizedTest @@ -344,8 +344,8 @@ public class AccountCreationDeletionIntegrationTest { assertEquals(Optional.of(aciSignedPreKey), keysManager.getEcSignedPreKey(account.getAccountIdentifier(), Device.PRIMARY_ID).join()); assertEquals(Optional.of(aciPqLastResortPreKey), keysManager.getLastResort(account.getAccountIdentifier(), Device.PRIMARY_ID).join()); - assertTrue(account.getNumberOptional().isEmpty()); - assertTrue(account.getPhoneNumberIdentifierOptional().isEmpty()); + assertTrue(account.getNumber().isEmpty()); + assertTrue(account.getPhoneNumberIdentifier().isEmpty()); assertTrue(account.getPhoneNumberIdentityKey().isEmpty()); } @@ -486,8 +486,8 @@ public class AccountCreationDeletionIntegrationTest { verify(disconnectionRequestManager).requestDisconnection(argThat(account -> account.getAccountIdentifier().equals(existingAccountUuid) && account != reregisteredAccount)); - assertTrue(phoneNumberRecoveryPasswordsManager.verify(reregisteredAccount.getPhoneNumberIdentifierOptional().orElseThrow(), updatedRecoveryPassword)); - assertFalse(phoneNumberRecoveryPasswordsManager.verify(reregisteredAccount.getPhoneNumberIdentifierOptional().orElseThrow(), originalRecoveryPassword)); + assertTrue(phoneNumberRecoveryPasswordsManager.verify(reregisteredAccount.getPhoneNumberIdentifier().orElseThrow(), updatedRecoveryPassword)); + assertFalse(phoneNumberRecoveryPasswordsManager.verify(reregisteredAccount.getPhoneNumberIdentifier().orElseThrow(), originalRecoveryPassword)); } @ParameterizedTest @@ -589,8 +589,8 @@ public class AccountCreationDeletionIntegrationTest { null); assertEquals(existingAccount.getAccountIdentifier(), reclaimedAccount.getAccountIdentifier()); - assertEquals(existingAccount.getNumberOptional(), reclaimedAccount.getNumberOptional()); - assertEquals(existingAccount.getPhoneNumberIdentifierOptional(), reclaimedAccount.getPhoneNumberIdentifierOptional()); + assertEquals(existingAccount.getNumber(), reclaimedAccount.getNumber()); + assertEquals(existingAccount.getPhoneNumberIdentifier(), reclaimedAccount.getPhoneNumberIdentifier()); assertEquals(aciIdentityKey, reclaimedAccount.getAccountIdentityKey()); assertEquals(hasE164 ? Optional.of(pniIdentityKey) : Optional.empty(), reclaimedAccount.getPhoneNumberIdentityKey()); @@ -678,7 +678,7 @@ public class AccountCreationDeletionIntegrationTest { Optional.empty(), Optional.empty()), null); - assertTrue(phoneNumberRecoveryPasswordsManager.verify(account.getPhoneNumberIdentifierOptional().orElseThrow(), + assertTrue(phoneNumberRecoveryPasswordsManager.verify(account.getPhoneNumberIdentifier().orElseThrow(), accountAttributes.recoveryPassword().orElseThrow())); } else { account = accountsManager.create(accountAttributes, @@ -706,9 +706,9 @@ public class AccountCreationDeletionIntegrationTest { assertFalse(keysManager.getEcSignedPreKey(account.getAccountIdentifier(), Device.PRIMARY_ID).join().isPresent()); assertFalse(keysManager.getLastResort(account.getAccountIdentifier(), Device.PRIMARY_ID).join().isPresent()); if (hasE164) { - assertFalse(keysManager.getEcSignedPreKey(account.getPhoneNumberIdentifierOptional().orElseThrow(), Device.PRIMARY_ID).join().isPresent()); - assertFalse(keysManager.getLastResort(account.getPhoneNumberIdentifierOptional().orElseThrow(), Device.PRIMARY_ID).join().isPresent()); - assertFalse(phoneNumberRecoveryPasswordsManager.verify(account.getPhoneNumberIdentifierOptional().orElseThrow(), + assertFalse(keysManager.getEcSignedPreKey(account.getPhoneNumberIdentifier().orElseThrow(), Device.PRIMARY_ID).join().isPresent()); + assertFalse(keysManager.getLastResort(account.getPhoneNumberIdentifier().orElseThrow(), Device.PRIMARY_ID).join().isPresent()); + assertFalse(phoneNumberRecoveryPasswordsManager.verify(account.getPhoneNumberIdentifier().orElseThrow(), accountAttributes.recoveryPassword().orElseThrow())); } @@ -809,8 +809,8 @@ public class AccountCreationDeletionIntegrationTest { assertEquals(existingAccountUuid, retriedAccount.getAccountIdentifier()); - assertTrue(retriedAccount.getNumberOptional().isEmpty()); - assertTrue(retriedAccount.getPhoneNumberIdentifierOptional().isEmpty()); + assertTrue(retriedAccount.getNumber().isEmpty()); + assertTrue(retriedAccount.getPhoneNumberIdentifier().isEmpty()); assertTrue(retriedAccount.getPhoneNumberIdentityKey().isEmpty()); verify(disconnectionRequestManager).requestDisconnection(argThat(account -> @@ -883,7 +883,7 @@ public class AccountCreationDeletionIntegrationTest { final Device primaryDevice = account.getPrimaryDevice(); - assertEquals(number, account.getNumberOptional()); + assertEquals(number, account.getNumber()); assertEquals(signalAgent, primaryDevice.getUserAgent()); assertEquals(deliveryChannels.fetchesMessages(), primaryDevice.getFetchesMessages()); assertEquals(registrationId, primaryDevice.getAccountRegistrationId()); @@ -906,7 +906,7 @@ public class AccountCreationDeletionIntegrationTest { assertNotNull(primaryDevice.getCreatedAtCiphertext()); assertEquals(Optional.of(aciSignedPreKey), keysManager.getEcSignedPreKey(account.getAccountIdentifier(), Device.PRIMARY_ID).join()); assertEquals(Optional.of(aciPqLastResortPreKey), keysManager.getLastResort(account.getAccountIdentifier(), Device.PRIMARY_ID).join()); - account.getPhoneNumberIdentifierOptional().ifPresent( + account.getPhoneNumberIdentifier().ifPresent( pni -> { assertEquals(pniSignedPreKey, keysManager.getEcSignedPreKey(pni, Device.PRIMARY_ID).join()); assertEquals(pniPqLastResortPreKey, keysManager.getLastResort(pni, Device.PRIMARY_ID).join()); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountLockManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountLockManagerTest.java index c121e3a2c..5541b74de 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountLockManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountLockManagerTest.java @@ -80,7 +80,7 @@ class AccountLockManagerTest { void withLockPniAccount() throws Exception { final Account account = mock(Account.class); when(account.getAccountIdentifier()).thenReturn(ACI); - when(account.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(FIRST_PNI)); + when(account.getPhoneNumberIdentifier()).thenReturn(Optional.of(FIRST_PNI)); accountLockManager.withSingleAccountLock(account, () -> null, executor); verify(lockClient, times(1)).acquireLock( @@ -91,7 +91,7 @@ class AccountLockManagerTest { void withLockNoPniAccount() throws Exception { final Account account = mock(Account.class); when(account.getAccountIdentifier()).thenReturn(ACI); - when(account.getPhoneNumberIdentifierOptional()).thenReturn(Optional.empty()); + when(account.getPhoneNumberIdentifier()).thenReturn(Optional.empty()); accountLockManager.withSingleAccountLock(account, () -> null, executor); verify(lockClient, times(1)).acquireLock( diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountTest.java index f111a1b95..e08a66c8d 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountTest.java @@ -138,11 +138,11 @@ class AccountTest { final Account account = AccountsHelper.generateTestAccount("+14151234567", UUID.randomUUID(), UUID.randomUUID(), Collections.emptyList(), new byte[0]); - assertDoesNotThrow(account::getNumberOptional); + assertDoesNotThrow(account::getNumber); account.markStale(); - assertThrows(AssertionError.class, account::getNumberOptional); + assertThrows(AssertionError.class, account::getNumber); assertDoesNotThrow(account::getAccountIdentifier); } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerChangeNumberIntegrationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerChangeNumberIntegrationTest.java index 39938adc2..2219420b3 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerChangeNumberIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerChangeNumberIntegrationTest.java @@ -174,7 +174,7 @@ class AccountsManagerChangeNumberIntegrationTest { final Account account = AccountsHelper.createAccount(accountsManager, originalNumber); final UUID originalUuid = account.getAccountIdentifier(); - final UUID originalPni = account.getPhoneNumberIdentifierOptional().orElseThrow(); + final UUID originalPni = account.getPhoneNumberIdentifier().orElseThrow(); final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate(); @@ -189,11 +189,11 @@ class AccountsManagerChangeNumberIntegrationTest { final Account updatedAccount = accountsManager.getByE164(secondNumber).orElseThrow(); assertEquals(originalUuid, updatedAccount.getAccountIdentifier()); - assertEquals(Optional.of(secondNumber), updatedAccount.getNumberOptional()); - assertNotEquals(Optional.of(originalPni), updatedAccount.getPhoneNumberIdentifierOptional()); + assertEquals(Optional.of(secondNumber), updatedAccount.getNumber()); + assertNotEquals(Optional.of(originalPni), updatedAccount.getPhoneNumberIdentifier()); assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(originalPni)); - assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(updatedAccount.getPhoneNumberIdentifierOptional().orElseThrow())); + assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(updatedAccount.getPhoneNumberIdentifier().orElseThrow())); } @Test @@ -215,7 +215,7 @@ class AccountsManagerChangeNumberIntegrationTest { final Account account = AccountsHelper.createAccount(accountsManager, originalNumber); final UUID originalUuid = account.getAccountIdentifier(); - final UUID originalPni = account.getPhoneNumberIdentifierOptional().orElseThrow(); + final UUID originalPni = account.getPhoneNumberIdentifier().orElseThrow(); final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate(); @@ -228,11 +228,11 @@ class AccountsManagerChangeNumberIntegrationTest { final Account updatedAccount = accountsManager.getByE164(originalNumber).orElseThrow(); assertEquals(originalUuid, updatedAccount.getAccountIdentifier()); - assertEquals(Optional.of(originalNumber), updatedAccount.getNumberOptional()); - assertEquals(Optional.of(originalPni), updatedAccount.getPhoneNumberIdentifierOptional()); + assertEquals(Optional.of(originalNumber), updatedAccount.getNumber()); + assertEquals(Optional.of(originalPni), updatedAccount.getPhoneNumberIdentifier()); assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(originalPni)); - assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(updatedAccount.getPhoneNumberIdentifierOptional().orElseThrow())); + assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(updatedAccount.getPhoneNumberIdentifier().orElseThrow())); } @Test @@ -253,7 +253,7 @@ class AccountsManagerChangeNumberIntegrationTest { Device.PRIMARY_ID, KeysHelper.signedECPreKey(1, rotatedPniIdentityKeyPair)).join(); final UUID originalUuid = account.getAccountIdentifier(); - final UUID originalPni = account.getPhoneNumberIdentifierOptional().orElseThrow(); + final UUID originalPni = account.getPhoneNumberIdentifier().orElseThrow(); final IdentityKey pniIdentityKey = new IdentityKey(rotatedPniIdentityKeyPair.getPublicKey()); final Map preKeys = Map.of(Device.PRIMARY_ID, rotatedSignedPreKey); @@ -261,16 +261,16 @@ class AccountsManagerChangeNumberIntegrationTest { final Map registrationIds = Map.of(Device.PRIMARY_ID, rotatedPniRegistrationId); final Account updatedAccount = accountsManager.changeNumber(originalUuid, secondNumber, pniIdentityKey, preKeys, kemSignedPreKeys, registrationIds); - final UUID secondPni = updatedAccount.getPhoneNumberIdentifierOptional().orElseThrow(); + final UUID secondPni = updatedAccount.getPhoneNumberIdentifier().orElseThrow(); assertTrue(accountsManager.getByE164(originalNumber).isEmpty()); assertTrue(accountsManager.getByE164(secondNumber).isPresent()); assertEquals(originalUuid, accountsManager.getByE164(secondNumber).map(Account::getAccountIdentifier).orElseThrow()); assertNotEquals(originalPni, secondPni); - assertEquals(secondPni, accountsManager.getByE164(secondNumber).flatMap(Account::getPhoneNumberIdentifierOptional).orElseThrow()); + assertEquals(secondPni, accountsManager.getByE164(secondNumber).flatMap(Account::getPhoneNumberIdentifier).orElseThrow()); - assertEquals(secondNumber, accountsManager.getByAccountIdentifier(originalUuid).flatMap(Account::getNumberOptional).orElseThrow()); + assertEquals(secondNumber, accountsManager.getByAccountIdentifier(originalUuid).flatMap(Account::getNumber).orElseThrow()); assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(originalPni)); assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(secondPni)); @@ -279,7 +279,7 @@ class AccountsManagerChangeNumberIntegrationTest { assertEquals(Optional.of(rotatedPniRegistrationId), updatedAccount.getPrimaryDevice().getPhoneNumberIdentityRegistrationId()); assertEquals(Optional.of(rotatedSignedPreKey), - keysManager.getEcSignedPreKey(updatedAccount.getPhoneNumberIdentifierOptional().orElseThrow(), Device.PRIMARY_ID).join()); + keysManager.getEcSignedPreKey(updatedAccount.getPhoneNumberIdentifier().orElseThrow(), Device.PRIMARY_ID).join()); } @Test @@ -290,7 +290,7 @@ class AccountsManagerChangeNumberIntegrationTest { Account account = AccountsHelper.createAccount(accountsManager, originalNumber); final UUID originalUuid = account.getAccountIdentifier(); - final UUID originalPni = account.getPhoneNumberIdentifierOptional().orElseThrow(); + final UUID originalPni = account.getPhoneNumberIdentifier().orElseThrow(); final ECKeyPair originalIdentityKeyPair = ECKeyPair.generate(); final ECKeyPair secondIdentityKeyPair = ECKeyPair.generate(); @@ -302,7 +302,7 @@ class AccountsManagerChangeNumberIntegrationTest { Map.of(Device.PRIMARY_ID, KeysHelper.signedKEMPreKey(2, secondIdentityKeyPair)), Map.of(Device.PRIMARY_ID, 1)); - final UUID secondPni = account.getPhoneNumberIdentifierOptional().orElseThrow(); + final UUID secondPni = account.getPhoneNumberIdentifier().orElseThrow(); accountsManager.changeNumber(originalUuid, originalNumber, @@ -313,11 +313,11 @@ class AccountsManagerChangeNumberIntegrationTest { assertTrue(accountsManager.getByE164(originalNumber).isPresent()); assertEquals(originalUuid, accountsManager.getByE164(originalNumber).map(Account::getAccountIdentifier).orElseThrow()); - assertEquals(originalPni, accountsManager.getByE164(originalNumber).flatMap(Account::getPhoneNumberIdentifierOptional).orElseThrow()); + assertEquals(originalPni, accountsManager.getByE164(originalNumber).flatMap(Account::getPhoneNumberIdentifier).orElseThrow()); assertTrue(accountsManager.getByE164(secondNumber).isEmpty()); - assertEquals(originalNumber, accountsManager.getByAccountIdentifier(originalUuid).flatMap(Account::getNumberOptional).orElseThrow()); + assertEquals(originalNumber, accountsManager.getByAccountIdentifier(originalUuid).flatMap(Account::getNumber).orElseThrow()); assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(originalPni)); assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(secondPni)); @@ -331,7 +331,7 @@ class AccountsManagerChangeNumberIntegrationTest { final Account account = AccountsHelper.createAccount(accountsManager, originalNumber); final UUID originalUuid = account.getAccountIdentifier(); - final UUID originalPni = account.getPhoneNumberIdentifierOptional().orElseThrow(); + final UUID originalPni = account.getPhoneNumberIdentifier().orElseThrow(); final ECKeyPair originalIdentityKeyPair = ECKeyPair.generate(); final ECKeyPair secondIdentityKeyPair = ECKeyPair.generate(); @@ -347,14 +347,14 @@ class AccountsManagerChangeNumberIntegrationTest { Map.of(Device.PRIMARY_ID, KeysHelper.signedKEMPreKey(2, secondIdentityKeyPair)), Map.of(Device.PRIMARY_ID, 1)); - final UUID secondPni = accountsManager.getByE164(secondNumber).get().getPhoneNumberIdentifierOptional().orElseThrow(); + final UUID secondPni = accountsManager.getByE164(secondNumber).get().getPhoneNumberIdentifier().orElseThrow(); assertTrue(accountsManager.getByE164(originalNumber).isEmpty()); assertTrue(accountsManager.getByE164(secondNumber).isPresent()); assertEquals(Optional.of(originalUuid), accountsManager.getByE164(secondNumber).map(Account::getAccountIdentifier)); - assertEquals(secondNumber, accountsManager.getByAccountIdentifier(originalUuid).flatMap(Account::getNumberOptional).orElseThrow()); + assertEquals(secondNumber, accountsManager.getByAccountIdentifier(originalUuid).flatMap(Account::getNumber).orElseThrow()); verify(disconnectionRequestManager).requestDisconnection(argThat(disconnectedAccount -> disconnectedAccount.getAccountIdentifier().equals(existingAccountUuid) && disconnectedAccount != account)); @@ -382,7 +382,7 @@ class AccountsManagerChangeNumberIntegrationTest { final Account account = AccountsHelper.createAccount(accountsManager, originalNumber); final UUID originalUuid = account.getAccountIdentifier(); - final UUID originalPni = account.getPhoneNumberIdentifierOptional().orElseThrow(); + final UUID originalPni = account.getPhoneNumberIdentifier().orElseThrow(); final Account existingAccount = AccountsHelper.createAccount(accountsManager, secondNumber); @@ -396,12 +396,12 @@ class AccountsManagerChangeNumberIntegrationTest { Map.of(Device.PRIMARY_ID, KeysHelper.signedKEMPreKey(2, pniIdentityKeyPair)), Map.of(Device.PRIMARY_ID, 1)); - final UUID secondPni = changedNumberAccount.getPhoneNumberIdentifierOptional().orElseThrow(); + final UUID secondPni = changedNumberAccount.getPhoneNumberIdentifier().orElseThrow(); final Account reRegisteredAccount = AccountsHelper.createAccount(accountsManager, originalNumber); assertEquals(existingAccountUuid, reRegisteredAccount.getAccountIdentifier()); - assertEquals(Optional.of(originalPni), reRegisteredAccount.getPhoneNumberIdentifierOptional()); + assertEquals(Optional.of(originalPni), reRegisteredAccount.getPhoneNumberIdentifier()); assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(originalPni)); assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(secondPni)); @@ -417,6 +417,6 @@ class AccountsManagerChangeNumberIntegrationTest { assertEquals(Optional.of(originalUuid), accountsManager.findRecentlyDeletedAccountIdentifier(originalPni)); assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(secondPni)); - assertEquals(Optional.of(secondPni), changedNumberReRegisteredAccount.getPhoneNumberIdentifierOptional()); + assertEquals(Optional.of(secondPni), changedNumberReRegisteredAccount.getPhoneNumberIdentifier()); } } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerConcurrentModificationIntegrationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerConcurrentModificationIntegrationTest.java index a922b82ca..7f9fb182f 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerConcurrentModificationIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerConcurrentModificationIntegrationTest.java @@ -222,7 +222,7 @@ class AccountsManagerConcurrentModificationIntegrationTest { () -> assertArrayEquals(currentProfileVersion, account.getCurrentProfileVersion().orElseThrow()), () -> assertEquals(identityKey, account.getAccountIdentityKey()), () -> assertArrayEquals(unidentifiedAccessKey, account.getUnidentifiedAccessKey().orElseThrow()), - () -> assertTrue(account.getPhoneNumberIdentifierOptional().isEmpty() || account.getRegistrationLock().verify(clientRegistrationLock)), + () -> assertTrue(account.getPhoneNumberIdentifier().isEmpty() || account.getRegistrationLock().verify(clientRegistrationLock)), () -> assertTrue(account.getAccountRecoveryPassword().orElseThrow().verify(accountRecoveryPassword)), () -> assertEquals(unrestrictedUnidentifiedAccess, account.isUnrestrictedUnidentifiedAccess()) ); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerDeviceTransferIntegrationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerDeviceTransferIntegrationTest.java index d380356cb..986caa13d 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerDeviceTransferIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerDeviceTransferIntegrationTest.java @@ -94,7 +94,7 @@ public class AccountsManagerDeviceTransferIntegrationTest { final Device device = mock(Device.class); when(device.getId()).thenReturn(deviceId); - when(device.getRegistrationId(IdentityType.ACI)).thenReturn(registrationId); + when(device.getAccountRegistrationId()).thenReturn(registrationId); final Account account = mock(Account.class); when(account.getAccountIdentifier()).thenReturn(accountIdentifier); @@ -123,7 +123,7 @@ public class AccountsManagerDeviceTransferIntegrationTest { final Device device = mock(Device.class); when(device.getId()).thenReturn(deviceId); - when(device.getRegistrationId(IdentityType.ACI)).thenReturn(registrationId); + when(device.getAccountRegistrationId()).thenReturn(registrationId); final Account account = mock(Account.class); when(account.getAccountIdentifier()).thenReturn(accountIdentifier); @@ -145,7 +145,7 @@ public class AccountsManagerDeviceTransferIntegrationTest { final Device device = mock(Device.class); when(device.getId()).thenReturn(deviceId); - when(device.getRegistrationId(IdentityType.ACI)).thenReturn(registrationId); + when(device.getAccountRegistrationId()).thenReturn(registrationId); final Account account = mock(Account.class); when(account.getAccountIdentifier()).thenReturn(accountIdentifier); @@ -162,7 +162,7 @@ public class AccountsManagerDeviceTransferIntegrationTest { final UUID accountIdentifier = UUID.randomUUID(); final Device device = mock(Device.class); - when(device.getRegistrationId(IdentityType.ACI)).thenReturn(123); + when(device.getAccountRegistrationId()).thenReturn(123); final Account account = mock(Account.class); when(account.getAccountIdentifier()).thenReturn(accountIdentifier); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerMigrateRecoveryPasswordIntegrationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerMigrateRecoveryPasswordIntegrationTest.java index ecb3570ae..7b5fa061d 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerMigrateRecoveryPasswordIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerMigrateRecoveryPasswordIntegrationTest.java @@ -165,7 +165,7 @@ public class AccountsManagerMigrateRecoveryPasswordIntegrationTest { .setDeviceAttributes(new DeviceAttributes(false, 1, 1, new byte[0], Collections.emptySet()))) .build(); - final UUID phoneNumberIdentifier = account.getPhoneNumberIdentifierOptional().orElseThrow(); + final UUID phoneNumberIdentifier = account.getPhoneNumberIdentifier().orElseThrow(); final byte[] recoveryPassword = TestRandomUtil.nextBytes(16); phoneNumberRecoveryPasswordsManager.store(phoneNumberIdentifier, recoveryPassword); 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 0cebce0e1..e6869675e 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerTest.java @@ -88,7 +88,6 @@ import org.whispersystems.textsecuregcm.entities.AccountAttributes; import org.whispersystems.textsecuregcm.entities.ECSignedPreKey; import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey; import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; -import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier; import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient; import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient; @@ -322,11 +321,11 @@ class AccountsManagerTest { assertEquals(account.get().getAccountIdentifier(), uuid); if (hasNumber) { - assertEquals("+14152222222", account.get().getNumberOptional().orElseThrow()); - assertEquals(UUID.fromString("de24dc73-fbd8-41be-a7d5-764c70d9da7e"), account.get().getPhoneNumberIdentifierOptional().orElseThrow()); + assertEquals("+14152222222", account.get().getNumber().orElseThrow()); + assertEquals(UUID.fromString("de24dc73-fbd8-41be-a7d5-764c70d9da7e"), account.get().getPhoneNumberIdentifier().orElseThrow()); } else { - assertTrue(account.get().getNumberOptional().isEmpty()); - assertTrue(account.get().getPhoneNumberIdentifierOptional().isEmpty()); + assertTrue(account.get().getNumber().isEmpty()); + assertTrue(account.get().getPhoneNumberIdentifier().isEmpty()); } verify(clusterCommands, times(1)).get(eq("Account3::" + uuid)); @@ -355,11 +354,11 @@ class AccountsManagerTest { assertEquals(account.get().getAccountIdentifier(), uuid); if (hasNumber) { - assertEquals( "+14152222222", account.get().getNumberOptional().orElseThrow()); - assertEquals(UUID.fromString("de24dc73-fbd8-41be-a7d5-764c70d9da7e"), account.get().getPhoneNumberIdentifierOptional().orElseThrow()); + assertEquals( "+14152222222", account.get().getNumber().orElseThrow()); + assertEquals(UUID.fromString("de24dc73-fbd8-41be-a7d5-764c70d9da7e"), account.get().getPhoneNumberIdentifier().orElseThrow()); } else { - assertTrue(account.get().getNumberOptional().isEmpty()); - assertTrue(account.get().getPhoneNumberIdentifierOptional().isEmpty()); + assertTrue(account.get().getNumber().isEmpty()); + assertTrue(account.get().getPhoneNumberIdentifier().isEmpty()); } verify(asyncClusterCommands, times(1)).get(eq("Account3::" + uuid)); @@ -380,8 +379,8 @@ class AccountsManagerTest { Optional account = accountsManager.getByPhoneNumberIdentifier(pni); assertTrue(account.isPresent()); - assertEquals("+14152222222", account.get().getNumberOptional().orElseThrow()); - assertEquals(UUID.fromString("de24dc73-fbd8-41be-a7d5-764c70d9da7e"), account.get().getPhoneNumberIdentifierOptional().orElseThrow()); + assertEquals("+14152222222", account.get().getNumber().orElseThrow()); + assertEquals(UUID.fromString("de24dc73-fbd8-41be-a7d5-764c70d9da7e"), account.get().getPhoneNumberIdentifier().orElseThrow()); verify(clusterCommands).get(eq("AccountMap::" + pni)); verify(clusterCommands).get(eq("Account3::" + uuid)); @@ -406,8 +405,8 @@ class AccountsManagerTest { Optional account = accountsManager.getByPhoneNumberIdentifierAsync(pni).join(); assertTrue(account.isPresent()); - assertEquals("+14152222222", account.get().getNumberOptional().orElseThrow()); - assertEquals(UUID.fromString("de24dc73-fbd8-41be-a7d5-764c70d9da7e"), account.get().getPhoneNumberIdentifierOptional().orElseThrow()); + assertEquals("+14152222222", account.get().getNumber().orElseThrow()); + assertEquals(UUID.fromString("de24dc73-fbd8-41be-a7d5-764c70d9da7e"), account.get().getPhoneNumberIdentifier().orElseThrow()); verify(asyncClusterCommands).get(eq("AccountMap::" + pni)); verify(asyncClusterCommands).get(eq("Account3::" + uuid)); @@ -780,10 +779,10 @@ class AccountsManagerTest { verify(keysManager, never()).deleteSingleUsePreKeys(argThat(id -> !id.equals(aci)), anyByte()); } else { //noinspection OptionalGetWithoutIsPresent - verify(keysManager, times(2)).deleteSingleUsePreKeys(eq(account.getPhoneNumberIdentifierOptional().get()), eq(linkedDevice.getId())); + verify(keysManager, times(2)).deleteSingleUsePreKeys(eq(account.getPhoneNumberIdentifier().get()), eq(linkedDevice.getId())); } - verify(keysManager).buildWriteItemsForRemovedDevice(aci, account.getPhoneNumberIdentifierOptional(), linkedDevice.getId()); + verify(keysManager).buildWriteItemsForRemovedDevice(aci, account.getPhoneNumberIdentifier(), linkedDevice.getId()); verify(disconnectionRequestManager).requestDisconnection(aci, List.of(linkedDevice.getId())); } @@ -824,7 +823,7 @@ class AccountsManagerTest { // Check existence (or lack thereof) of phone number, phone number identifier, phone number identity key, // phone number identity registration ID, and auth credential salt. final Device primaryDevice = createdAccount.getDevices().stream().findFirst().orElseThrow(); - assertEquals(maybeE164, createdAccount.getNumberOptional()); + assertEquals(maybeE164, createdAccount.getNumber()); maybeE164.ifPresentOrElse( number -> { assertTrue(phoneNumberIdentifiersByE164.containsKey(number)); @@ -840,13 +839,13 @@ class AccountsManagerTest { }); if (maybeE164.isPresent()) { - verify(accounts).create(argThat(account -> maybeE164.equals(account.getNumberOptional())), any()); + verify(accounts).create(argThat(account -> maybeE164.equals(account.getNumber())), any()); } else { - verify(accounts).create(argThat(account -> account.getNumberOptional().isEmpty()), any(), any(), any()); + verify(accounts).create(argThat(account -> account.getNumber().isEmpty()), any(), any(), any()); } verify(keysManager).buildWriteItemsForNewDevice( eq(createdAccount.getAccountIdentifier()), - eq(createdAccount.getPhoneNumberIdentifierOptional()), + eq(createdAccount.getPhoneNumberIdentifier()), eq(Device.PRIMARY_ID), notNull(), maybeE164.isPresent() ? notNull() : eq(Optional.empty()), @@ -879,8 +878,8 @@ class AccountsManagerTest { final Account existingAccount = mock(Account.class); when(existingAccount.getAccountIdentifier()).thenReturn(existingUuid); - when(existingAccount.getNumberOptional()).thenReturn(maybeExistingAccountE164); - when(existingAccount.getPhoneNumberIdentifierOptional()).thenReturn(requestedAccount.getPhoneNumberIdentifierOptional()); + when(existingAccount.getNumber()).thenReturn(maybeExistingAccountE164); + when(existingAccount.getPhoneNumberIdentifier()).thenReturn(requestedAccount.getPhoneNumberIdentifier()); when(existingAccount.getPrimaryDevice()).thenReturn(existingPrimaryDevice); when(existingAccount.getAccountIdentityKey()).thenReturn(requestedAccount.getAccountIdentityKey()); when(existingAccount.getAccountRecoveryPassword()).thenReturn( @@ -905,7 +904,7 @@ class AccountsManagerTest { // and phone number identity registration ID final Device primaryDevice = reregisteredAccount.getDevices().stream().findFirst().orElseThrow(); - assertEquals(maybeE164, reregisteredAccount.getNumberOptional()); + assertEquals(maybeE164, reregisteredAccount.getNumber()); maybeE164.ifPresentOrElse( number -> { assertTrue(phoneNumberIdentifiersByE164.containsKey(number)); @@ -928,7 +927,7 @@ class AccountsManagerTest { verify(keysManager).buildWriteItemsForNewDevice( eq(reregisteredAccount.getAccountIdentifier()), - eq(reregisteredAccount.getPhoneNumberIdentifierOptional()), + eq(reregisteredAccount.getPhoneNumberIdentifier()), eq(Device.PRIMARY_ID), notNull(), maybeE164.isPresent() ? notNull() : eq(Optional.empty()), @@ -1016,8 +1015,8 @@ class AccountsManagerTest { null); assertEquals(existingAccount.getAccountIdentifier(), reclaimedAccount.getAccountIdentifier()); - assertEquals(existingAccount.getNumberOptional(), reclaimedAccount.getNumberOptional()); - assertEquals(existingAccount.getPhoneNumberIdentifierOptional(), reclaimedAccount.getPhoneNumberIdentifierOptional()); + assertEquals(existingAccount.getNumber(), reclaimedAccount.getNumber()); + assertEquals(existingAccount.getPhoneNumberIdentifier(), reclaimedAccount.getPhoneNumberIdentifier()); assertEquals(aciIdentityKey, reclaimedAccount.getAccountIdentityKey()); assertEquals(hasPhoneNumber ? Optional.of(pniIdentityKey) : Optional.empty(), reclaimedAccount.getPhoneNumberIdentityKey()); @@ -1037,7 +1036,7 @@ class AccountsManagerTest { verify(keysManager).buildWriteItemsForNewDevice( eq(reclaimedAccount.getAccountIdentifier()), - eq(reclaimedAccount.getPhoneNumberIdentifierOptional()), + eq(reclaimedAccount.getPhoneNumberIdentifier()), eq(Device.PRIMARY_ID), notNull(), hasPhoneNumber ? notNull() : eq(Optional.empty()), @@ -1045,7 +1044,7 @@ class AccountsManagerTest { hasPhoneNumber ? notNull() : eq(Optional.empty())); verify(keysManager, times(2)).deleteSingleUsePreKeys(existingAccount.getAccountIdentifier()); - existingAccount.getPhoneNumberIdentifierOptional().ifPresent(phoneNumberIdentifier -> + existingAccount.getPhoneNumberIdentifier().ifPresent(phoneNumberIdentifier -> verify(keysManager, times(2)).deleteSingleUsePreKeys(phoneNumberIdentifier)); verify(messagesManager, times(2)).clear(existingAccount.getAccountIdentifier()); verify(profilesManager, times(2)).deleteAll(existingAccount.getAccountIdentifier(), false); @@ -1158,11 +1157,11 @@ class AccountsManagerTest { final Account account = createAccount(e164, attributes); verify(accounts).create( - argThat(a -> e164.equals(a.getNumberOptional().get()) && recentlyDeletedUuid.equals(a.getAccountIdentifier())), + argThat(a -> e164.equals(a.getNumber().get()) && recentlyDeletedUuid.equals(a.getAccountIdentifier())), any()); verify(keysManager).buildWriteItemsForNewDevice(eq(account.getAccountIdentifier()), - eq(account.getPhoneNumberIdentifierOptional()), + eq(account.getPhoneNumberIdentifier()), eq(Device.PRIMARY_ID), any(), any(), @@ -1205,7 +1204,7 @@ class AccountsManagerTest { ? AccountsHelper.generateTestAccount(phoneNumber, List.of(generateTestDevice(CLOCK.millis()))) : AccountsHelper.generateTestAccountNoPhoneNumber(List.of(generateTestDevice(CLOCK.millis()))); final UUID aci = account.getAccountIdentifier(); - final Optional maybePni = account.getPhoneNumberIdentifierOptional(); + final Optional maybePni = account.getPhoneNumberIdentifier(); account.setIdentityKey(new IdentityKey(ECKeyPair.generate().getPublicKey())); final byte nextDeviceId = account.getNextDeviceId(); @@ -1320,7 +1319,7 @@ class AccountsManagerTest { Map.of(Device.PRIMARY_ID, kemLastResortPreKey), Map.of(Device.PRIMARY_ID, 1)); - assertEquals(targetNumber, account.getNumber()); + assertEquals(Optional.of(targetNumber), account.getNumber()); assertTrue(phoneNumberIdentifiersByE164.containsKey(targetNumber)); @@ -1343,17 +1342,17 @@ class AccountsManagerTest { addRetrievableAccount(account); - phoneNumberIdentifiersByE164.put(originalNumber, account.getPhoneNumberIdentifier()); - phoneNumberIdentifiersByE164.put(newNumber, account.getPhoneNumberIdentifier()); - account = accountsManager.changeNumber(account.getIdentifier(IdentityType.ACI), + phoneNumberIdentifiersByE164.put(originalNumber, account.getPhoneNumberIdentifier().orElseThrow()); + phoneNumberIdentifiersByE164.put(newNumber, account.getPhoneNumberIdentifier().orElseThrow()); + account = accountsManager.changeNumber(account.getAccountIdentifier(), newNumber, new IdentityKey(pniIdentityKeyPair.getPublicKey()), Map.of(Device.PRIMARY_ID, KeysHelper.signedECPreKey(1, pniIdentityKeyPair)), Map.of(Device.PRIMARY_ID, KeysHelper.signedKEMPreKey(2, pniIdentityKeyPair)), Map.of(Device.PRIMARY_ID, 1)); - assertEquals(newNumber, account.getNumber()); - assertEquals(phoneNumberIdentifier, account.getIdentifier(IdentityType.PNI)); + assertEquals(Optional.of(newNumber), account.getNumber()); + assertEquals(Optional.of(phoneNumberIdentifier), account.getPhoneNumberIdentifier()); verify(accounts, never()).delete(any(), any()); } @@ -1383,7 +1382,7 @@ class AccountsManagerTest { Map.of(Device.PRIMARY_ID, kemLastResoryPreKey), Map.of(Device.PRIMARY_ID, 1)); - assertEquals(targetNumber, account.getNumber()); + assertEquals(Optional.of(targetNumber), account.getNumber()); assertTrue(phoneNumberIdentifiersByE164.containsKey(targetNumber)); final UUID newPni = phoneNumberIdentifiersByE164.get(targetNumber); @@ -1428,7 +1427,7 @@ class AccountsManagerTest { final Account updatedAccount = accountsManager.changeNumber( uuid, targetNumber, new IdentityKey(ECKeyPair.generate().getPublicKey()), newSignedKeys, newSignedPqKeys, newRegistrationIds); - assertEquals(targetNumber, updatedAccount.getNumber()); + assertEquals(Optional.of(targetNumber), updatedAccount.getNumber()); assertTrue(phoneNumberIdentifiersByE164.containsKey(targetNumber)); @@ -1492,7 +1491,7 @@ class AccountsManagerTest { final List usernameHashes = List.of(TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(32)); - final UsernameReservation result = accountsManager.reserveUsernameHash(account.getIdentifier(IdentityType.ACI), usernameHashes); + final UsernameReservation result = accountsManager.reserveUsernameHash(account.getAccountIdentifier(), usernameHashes); assertArrayEquals(usernameHashes.getFirst(), result.reservedUsernameHash()); verify(accounts, times(1)).reserveUsernameHash(eq(account), any(), eq(Duration.ofMinutes(5))); } @@ -1506,7 +1505,7 @@ class AccountsManagerTest { final List usernameHashes = List.of(TestRandomUtil.nextBytes(32), oldUsernameHash, TestRandomUtil.nextBytes(32)); - final UsernameReservation result = accountsManager.reserveUsernameHash(account.getIdentifier(IdentityType.ACI), usernameHashes); + final UsernameReservation result = accountsManager.reserveUsernameHash(account.getAccountIdentifier(), usernameHashes); assertArrayEquals(oldUsernameHash, result.reservedUsernameHash()); verify(accounts, never()).reserveUsernameHash(any(), any(), any()); } @@ -1522,7 +1521,7 @@ class AccountsManagerTest { .doNothing() .when(accounts).reserveUsernameHash(any(), any(), any()); - final UsernameReservation result = accountsManager.reserveUsernameHash(account.getIdentifier(IdentityType.ACI), usernameHashes); + final UsernameReservation result = accountsManager.reserveUsernameHash(account.getAccountIdentifier(), usernameHashes); assertArrayEquals(usernameHashes.getFirst(), result.reservedUsernameHash()); verify(accounts, times(2)).reserveUsernameHash(eq(account), any(), eq(Duration.ofMinutes(5))); } @@ -1536,7 +1535,7 @@ class AccountsManagerTest { .when(accounts).reserveUsernameHash(any(), any(), any()); assertThrows(UsernameHashNotAvailableException.class, () -> - accountsManager.reserveUsernameHash(account.getIdentifier(IdentityType.ACI), List.of(USERNAME_HASH_1, USERNAME_HASH_2))); + accountsManager.reserveUsernameHash(account.getAccountIdentifier(), List.of(USERNAME_HASH_1, USERNAME_HASH_2))); } @ParameterizedTest @@ -1547,7 +1546,7 @@ class AccountsManagerTest { setReservationHash(account, USERNAME_HASH_1); - accountsManager.confirmReservedUsernameHash(account.getIdentifier(IdentityType.ACI), USERNAME_HASH_1, ENCRYPTED_USERNAME_1); + accountsManager.confirmReservedUsernameHash(account.getAccountIdentifier(), USERNAME_HASH_1, ENCRYPTED_USERNAME_1); verify(accounts).confirmUsernameHash(eq(account), eq(USERNAME_HASH_1), eq(ENCRYPTED_USERNAME_1)); } @@ -1561,7 +1560,7 @@ class AccountsManagerTest { .doNothing() .when(accounts).confirmUsernameHash(account, USERNAME_HASH_1, ENCRYPTED_USERNAME_1); - accountsManager.confirmReservedUsernameHash(account.getIdentifier(IdentityType.ACI), USERNAME_HASH_1, ENCRYPTED_USERNAME_1); + accountsManager.confirmReservedUsernameHash(account.getAccountIdentifier(), USERNAME_HASH_1, ENCRYPTED_USERNAME_1); verify(accounts, times(2)).confirmUsernameHash(eq(account), eq(USERNAME_HASH_1), eq(ENCRYPTED_USERNAME_1)); } @@ -1572,7 +1571,7 @@ class AccountsManagerTest { setReservationHash(account, USERNAME_HASH_1); assertThrows(UsernameReservationNotFoundException.class, - () -> accountsManager.confirmReservedUsernameHash(account.getIdentifier(IdentityType.ACI), USERNAME_HASH_2, ENCRYPTED_USERNAME_2)); + () -> accountsManager.confirmReservedUsernameHash(account.getAccountIdentifier(), USERNAME_HASH_2, ENCRYPTED_USERNAME_2)); } @Test @@ -1584,7 +1583,7 @@ class AccountsManagerTest { doThrow(new UsernameHashNotAvailableException()) .when(accounts).confirmUsernameHash(account, USERNAME_HASH_1, ENCRYPTED_USERNAME_1); assertThrows(UsernameHashNotAvailableException.class, - () -> accountsManager.confirmReservedUsernameHash(account.getIdentifier(IdentityType.ACI), USERNAME_HASH_1, ENCRYPTED_USERNAME_1)); + () -> accountsManager.confirmReservedUsernameHash(account.getAccountIdentifier(), USERNAME_HASH_1, ENCRYPTED_USERNAME_1)); assertTrue(account.getUsernameHash().isEmpty()); } @@ -1595,7 +1594,7 @@ class AccountsManagerTest { account.setUsernameHash(USERNAME_HASH_1); // reserved username already set, should be treated as a replay - accountsManager.confirmReservedUsernameHash(account.getIdentifier(IdentityType.ACI), USERNAME_HASH_1, ENCRYPTED_USERNAME_1); + accountsManager.confirmReservedUsernameHash(account.getAccountIdentifier(), USERNAME_HASH_1, ENCRYPTED_USERNAME_1); verify(accounts, never()).confirmUsernameHash(any(), any(), any()); } @@ -1606,7 +1605,7 @@ class AccountsManagerTest { addRetrievableAccount(account); assertThrows(UsernameReservationNotFoundException.class, - () -> accountsManager.confirmReservedUsernameHash(account.getIdentifier(IdentityType.ACI), USERNAME_HASH_1, ENCRYPTED_USERNAME_1)); + () -> accountsManager.confirmReservedUsernameHash(account.getAccountIdentifier(), USERNAME_HASH_1, ENCRYPTED_USERNAME_1)); verify(accounts, never()).confirmUsernameHash(any(), any(), any()); } @@ -1617,7 +1616,7 @@ class AccountsManagerTest { addRetrievableAccount(account); account.setUsernameHash(USERNAME_HASH_1); - accountsManager.clearUsernameHash(account.getIdentifier(IdentityType.ACI)); + accountsManager.clearUsernameHash(account.getAccountIdentifier()); verify(accounts).clearUsernameHash(eq(account)); } @@ -1628,7 +1627,7 @@ class AccountsManagerTest { addRetrievableAccount(account); assertThrows(AssertionError.class, () -> - accountsManager.update(account.getIdentifier(IdentityType.ACI), a -> a.setUsernameHash(USERNAME_HASH_1))); + accountsManager.update(account.getAccountIdentifier(), a -> a.setUsernameHash(USERNAME_HASH_1))); } @Test @@ -1664,10 +1663,8 @@ class AccountsManagerTest { final Account parsedAccount = AccountsManager.parseAccountJson(serialized, originalAccount.getAccountIdentifier()).orElseThrow(); assertEquals(originalAccount.getAccountIdentifier(), parsedAccount.getAccountIdentifier()); - assertEquals(originalAccount.getPhoneNumberIdentifierOptional(), parsedAccount.getPhoneNumberIdentifierOptional()); - assertEquals(originalAccount.getAccountIdentifier(), parsedAccount.getAccountIdentifier()); - assertEquals(originalAccount.getPhoneNumberIdentifierOptional(), parsedAccount.getPhoneNumberIdentifierOptional()); - assertEquals(originalAccount.getNumberOptional(), parsedAccount.getNumberOptional()); + assertEquals(originalAccount.getPhoneNumberIdentifier(), parsedAccount.getPhoneNumberIdentifier()); + assertEquals(originalAccount.getNumber(), parsedAccount.getNumber()); assertArrayEquals(originalAccount.getUnidentifiedAccessKey().orElseThrow(), parsedAccount.getUnidentifiedAccessKey().orElseThrow()); assertEquals(originalAccount.isDiscoverableByPhoneNumber(), parsedAccount.isDiscoverableByPhoneNumber()); @@ -1888,7 +1885,7 @@ class AccountsManagerTest { @Test void getAccountsForChangeNumber() { final Account account = AccountsHelper.generateTestAccount("+14152222222", UUID.randomUUID(), UUID.randomUUID(), new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]); - final UUID accountIdentifier = account.getIdentifier(IdentityType.ACI); + final UUID accountIdentifier = account.getAccountIdentifier(); addRetrievableAccount(account); final String targetNumber = "+13102222222"; @@ -1915,10 +1912,10 @@ class AccountsManagerTest { } private void addRetrievableAccount(final Account account) { - when(accounts.getByAccountIdentifier(account.getIdentifier(IdentityType.ACI))) + when(accounts.getByAccountIdentifier(account.getAccountIdentifier())) .thenReturn(Optional.of(account)); - when(accounts.getByAccountIdentifierAsync(account.getIdentifier(IdentityType.ACI))) + when(accounts.getByAccountIdentifierAsync(account.getAccountIdentifier())) .thenReturn(CompletableFuture.completedFuture(Optional.of(account))); } } 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 f686fb098..09617c986 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsTest.java @@ -25,6 +25,7 @@ import static org.whispersystems.textsecuregcm.util.CompletableFutureTestUtil.as import com.fasterxml.jackson.core.JsonProcessingException; import com.google.i18n.phonenumbers.PhoneNumberUtil; +import jakarta.annotation.Nullable; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.time.Duration; @@ -51,7 +52,6 @@ import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; -import jakarta.annotation.Nullable; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; @@ -70,7 +70,6 @@ import org.signal.libsignal.zkgroup.backups.BackupCredentialType; import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation; import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil; import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration; -import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables; import org.whispersystems.textsecuregcm.tests.util.AccountsHelper; import org.whispersystems.textsecuregcm.tests.util.DevicesHelper; @@ -211,12 +210,12 @@ class AccountsTest { boolean freshUser = number != null ? createAccount(account) : createNumberlessAccount(account, receiptCredentialPresentation, TestRandomUtil.nextBytes(16)); assertThat(freshUser).isTrue(); - verifyStoredState(number, account.getAccountIdentifier(), account.getPhoneNumberIdentifierOptional().orElse(null), null, account, number != null); + verifyStoredState(number, account.getAccountIdentifier(), account.getPhoneNumberIdentifier(), null, account, number != null); if (number != null) { - assertThat(account.getPhoneNumberIdentifierOptional()).isPresent(); + assertThat(account.getPhoneNumberIdentifier()).isPresent(); assertPhoneNumberConstraintExists(number, account.getAccountIdentifier()); - assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifierOptional().get(), account.getAccountIdentifier()); + assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifier().get(), account.getAccountIdentifier()); } else { assertRedeemedReceiptConstraintExists(receiptCredentialPresentation, account.getAccountIdentifier()); } @@ -224,12 +223,12 @@ class AccountsTest { freshUser = number != null ? createAccount(account) : createNumberlessAccount(account, receiptCredentialPresentation, TestRandomUtil.nextBytes(16)); assertThat(freshUser).isTrue(); - verifyStoredState(number, account.getAccountIdentifier(), account.getPhoneNumberIdentifierOptional().orElse(null), null, account, number != null); + verifyStoredState(number, account.getAccountIdentifier(), account.getPhoneNumberIdentifier(), null, account, number != null); if (number != null) { - assertThat(account.getPhoneNumberIdentifierOptional()).isPresent(); + assertThat(account.getPhoneNumberIdentifier()).isPresent(); assertPhoneNumberConstraintExists(number, account.getAccountIdentifier()); - assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifierOptional().get(), account.getAccountIdentifier()); + assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifier().get(), account.getAccountIdentifier()); } else { assertRedeemedReceiptConstraintExists(receiptCredentialPresentation, account.getAccountIdentifier()); } @@ -248,19 +247,19 @@ class AccountsTest { verifyStoredState("+14151112222", account.getAccountIdentifier(), account.getPhoneNumberIdentifier(), null, account, true); assertPhoneNumberConstraintExists("+14151112222", account.getAccountIdentifier()); - assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifier(), account.getAccountIdentifier()); + assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifier().orElseThrow(), account.getAccountIdentifier()); accounts.delete(originalUuid, Collections.emptyList()); - assertThat(accounts.findRecentlyDeletedAccountIdentifier(account.getPhoneNumberIdentifier())).hasValue(originalUuid); + assertThat(accounts.findRecentlyDeletedAccountIdentifier(account.getPhoneNumberIdentifier().orElseThrow())).hasValue(originalUuid); freshUser = createAccount(account); assertThat(freshUser).isTrue(); verifyStoredState("+14151112222", account.getAccountIdentifier(), account.getPhoneNumberIdentifier(), null, account, true); assertPhoneNumberConstraintExists("+14151112222", account.getAccountIdentifier()); - assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifier(), account.getAccountIdentifier()); + assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifier().orElseThrow(), account.getAccountIdentifier()); - assertThat(accounts.findRecentlyDeletedAccountIdentifier(account.getPhoneNumberIdentifier())).isEmpty(); + assertThat(accounts.findRecentlyDeletedAccountIdentifier(account.getPhoneNumberIdentifier().orElseThrow())).isEmpty(); } @ParameterizedTest @@ -277,12 +276,12 @@ class AccountsTest { createNumberlessAccount(account, receiptCredentialPresentation, TestRandomUtil.nextBytes(16)); } - verifyStoredState(number, account.getAccountIdentifier(), account.getPhoneNumberIdentifierOptional().orElse(null), null, account, number != null); + verifyStoredState(number, account.getAccountIdentifier(), account.getPhoneNumberIdentifier(), null, account, number != null); if (number != null) { - assertThat(account.getPhoneNumberIdentifierOptional()).isPresent(); + assertThat(account.getPhoneNumberIdentifier()).isPresent(); assertPhoneNumberConstraintExists(number, account.getAccountIdentifier()); - assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifierOptional().get(), account.getAccountIdentifier()); + assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifier().get(), account.getAccountIdentifier()); } else { assertRedeemedReceiptConstraintExists(receiptCredentialPresentation, account.getAccountIdentifier()); } @@ -299,7 +298,7 @@ class AccountsTest { verifyStoredState("+14151112222", account.getAccountIdentifier(), account.getPhoneNumberIdentifier(), null, account, true); assertPhoneNumberConstraintExists("+14151112222", account.getAccountIdentifier()); - assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifier(), account.getAccountIdentifier()); + assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifier().orElseThrow(), account.getAccountIdentifier()); account.setNumber("+14153334444", UUID.randomUUID()); assertThrows(IllegalArgumentException.class, () -> createAccount(account), @@ -317,10 +316,10 @@ class AccountsTest { verifyStoredState("+14151112222", account1.getAccountIdentifier(), account1.getPhoneNumberIdentifier(), null, account1, true); assertPhoneNumberConstraintExists("+14151112222", account1.getAccountIdentifier()); - assertPhoneNumberIdentifierConstraintExists(account1.getPhoneNumberIdentifier(), account1.getAccountIdentifier()); + assertPhoneNumberIdentifierConstraintExists(account1.getPhoneNumberIdentifier().orElseThrow(), account1.getAccountIdentifier()); Device device2 = generateDevice(DEVICE_ID_1); - Account account2 = generateAccount("+14151112222", UUID.randomUUID(), account1.getPhoneNumberIdentifier(), + Account account2 = generateAccount("+14151112222", UUID.randomUUID(), account1.getPhoneNumberIdentifier().orElseThrow(), List.of(device2)); assertThrows(AccountAlreadyExistsException.class, () -> accounts.create(account2, Collections.emptyList()), @@ -350,8 +349,8 @@ class AccountsTest { assertThat(retrievedFirst.isPresent()).isTrue(); assertThat(retrievedSecond.isPresent()).isTrue(); - verifyStoredState("+14151112222", uuidFirst, pniFirst, null, retrievedFirst.get(), accountFirst); - verifyStoredState("+14152221111", uuidSecond, pniSecond, null, retrievedSecond.get(), accountSecond); + verifyStoredState("+14151112222", uuidFirst, Optional.of(pniFirst), null, retrievedFirst.get(), accountFirst); + verifyStoredState("+14152221111", uuidSecond, Optional.of(pniSecond), null, retrievedSecond.get(), accountSecond); retrievedFirst = accounts.getByAccountIdentifier(uuidFirst); retrievedSecond = accounts.getByAccountIdentifier(uuidSecond); @@ -359,8 +358,8 @@ class AccountsTest { assertThat(retrievedFirst.isPresent()).isTrue(); assertThat(retrievedSecond.isPresent()).isTrue(); - verifyStoredState("+14151112222", uuidFirst, pniFirst, null, retrievedFirst.get(), accountFirst); - verifyStoredState("+14152221111", uuidSecond, pniSecond, null, retrievedSecond.get(), accountSecond); + verifyStoredState("+14151112222", uuidFirst, Optional.of(pniFirst), null, retrievedFirst.get(), accountFirst); + verifyStoredState("+14152221111", uuidSecond, Optional.of(pniSecond), null, retrievedSecond.get(), accountSecond); retrievedFirst = accounts.getByPhoneNumberIdentifier(pniFirst); retrievedSecond = accounts.getByPhoneNumberIdentifier(pniSecond); @@ -368,8 +367,8 @@ class AccountsTest { assertThat(retrievedFirst.isPresent()).isTrue(); assertThat(retrievedSecond.isPresent()).isTrue(); - verifyStoredState("+14151112222", uuidFirst, pniFirst, null, retrievedFirst.get(), accountFirst); - verifyStoredState("+14152221111", uuidSecond, pniSecond, null, retrievedSecond.get(), accountSecond); + verifyStoredState("+14151112222", uuidFirst, Optional.of(pniFirst), null, retrievedFirst.get(), accountFirst); + verifyStoredState("+14152221111", uuidSecond, Optional.of(pniSecond), null, retrievedSecond.get(), accountSecond); } @Test @@ -393,8 +392,8 @@ class AccountsTest { assertThat(retrievedFirst.isPresent()).isTrue(); assertThat(retrievedSecond.isPresent()).isTrue(); - verifyStoredState(null, uuidFirst, null, null, retrievedFirst.get(), accountFirst); - verifyStoredState(null, uuidSecond, null, null, retrievedSecond.get(), accountSecond); + verifyStoredState(null, uuidFirst, Optional.empty(), null, retrievedFirst.get(), accountFirst); + verifyStoredState(null, uuidSecond, Optional.empty(), null, retrievedSecond.get(), accountSecond); } // State before the account is re-registered @@ -498,8 +497,8 @@ class AccountsTest { // Phone number canonicalization means that a user can re-register with a different phone number // in the same equivalence class and get back the same phone number identifier. // In that case, we favor the re-registering account's phone number. - reregisteredAccount.setNumber(reregisteredAccount.getNumber(), - accountAlreadyExistsException.getExistingAccount().getPhoneNumberIdentifier()); + reregisteredAccount.setNumber(reregisteredAccount.getNumber().orElseThrow(), + accountAlreadyExistsException.getExistingAccount().getPhoneNumberIdentifier().orElseThrow()); assertDoesNotThrow(() -> accounts.reclaimAccount(accountAlreadyExistsException.getExistingAccount(), reregisteredAccount, @@ -588,11 +587,11 @@ class AccountsTest { final UUID usernameLinkHandle = existingAccount.getUsernameLinkHandle(); verifyStoredState(number, existingAccount.getAccountIdentifier(), - existingAccount.getPhoneNumberIdentifierOptional().orElse(null), usernameHash, existingAccount, + existingAccount.getPhoneNumberIdentifier(), usernameHash, existingAccount, number != null); if (number != null) { - assertThat(existingAccount.getPhoneNumberIdentifierOptional()).isPresent(); + assertThat(existingAccount.getPhoneNumberIdentifier()).isPresent(); assertPhoneNumberConstraintExists(number, existingUuid); assertPhoneNumberIdentifierConstraintExists(existingPni, existingUuid); } else { @@ -614,7 +613,7 @@ class AccountsTest { } // usernameHash should be unset - verifyStoredState(number, existingUuid, existingPni, null, secondAccount, number != null); + verifyStoredState(number, existingUuid, Optional.ofNullable(existingPni), null, secondAccount, number != null); // username should become 'reclaimable' Map item = readAccount(existingUuid); @@ -661,8 +660,8 @@ class AccountsTest { createAccount(existingAccount); - assertTrue(existingAccount.getPhoneNumberIdentifierOptional().isPresent()); - verifyStoredState(firstNumber, existingAccount.getAccountIdentifier(), existingAccount.getPhoneNumberIdentifierOptional().get(), null, existingAccount, true); + assertTrue(existingAccount.getPhoneNumberIdentifier().isPresent()); + verifyStoredState(firstNumber, existingAccount.getAccountIdentifier(), existingAccount.getPhoneNumberIdentifier(), null, existingAccount, true); assertPhoneNumberConstraintExists(firstNumber, existingUuid); assertPhoneNumberIdentifierConstraintExists(pni, existingUuid); @@ -678,10 +677,10 @@ class AccountsTest { Map item = readAccount(existingUuid); final Account account = SystemMapper.jsonMapper().readValue(item.get(Accounts.ATTR_ACCOUNT_DATA).b().asByteArray(), Account.class); - assertTrue(account.getNumberOptional().isPresent()); + assertTrue(account.getNumber().isPresent()); assertThat(AttributeValues.getString(item, Accounts.ATTR_ACCOUNT_E164, null)) .isEqualTo(secondNumber) - .isEqualTo(account.getNumberOptional().get()); + .isEqualTo(account.getNumber().get()); assertPhoneNumberConstraintDoesNotExist(firstNumber); assertPhoneNumberConstraintExists(secondNumber, existingUuid); assertPhoneNumberIdentifierConstraintExists(pni, existingUuid); @@ -707,8 +706,8 @@ class AccountsTest { createAccount(existingAccount); - assertTrue(existingAccount.getPhoneNumberIdentifierOptional().isPresent()); - verifyStoredState(beninPhoneNumber, existingAccount.getAccountIdentifier(), existingAccount.getPhoneNumberIdentifierOptional().get(), null, existingAccount, true); + assertTrue(existingAccount.getPhoneNumberIdentifier().isPresent()); + verifyStoredState(beninPhoneNumber, existingAccount.getAccountIdentifier(), existingAccount.getPhoneNumberIdentifier(), null, existingAccount, true); assertPhoneNumberConstraintExists(beninPhoneNumber, existingUuid); assertPhoneNumberIdentifierConstraintExists(pni, existingUuid); @@ -743,8 +742,8 @@ class AccountsTest { createAccount(existingAccount); - assertTrue(existingAccount.getPhoneNumberIdentifierOptional().isPresent()); - verifyStoredState(beninPhoneNumber, existingAccount.getAccountIdentifier(), existingAccount.getPhoneNumberIdentifierOptional().get(), null, existingAccount, true); + assertTrue(existingAccount.getPhoneNumberIdentifier().isPresent()); + verifyStoredState(beninPhoneNumber, existingAccount.getAccountIdentifier(), existingAccount.getPhoneNumberIdentifier(), null, existingAccount, true); assertPhoneNumberConstraintExists(beninPhoneNumber, existingUuid); assertPhoneNumberIdentifierConstraintExists(existingPni, existingUuid); @@ -842,9 +841,9 @@ class AccountsTest { } if (number != null) { - assertThat(account.getPhoneNumberIdentifierOptional()).isPresent(); + assertThat(account.getPhoneNumberIdentifier()).isPresent(); assertPhoneNumberConstraintExists(number, account.getAccountIdentifier()); - assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifierOptional().get(), account.getAccountIdentifier()); + assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifier().get(), account.getAccountIdentifier()); } else { assertRedeemedReceiptConstraintExists(receiptCredentialPresentation, account.getAccountIdentifier()); } @@ -854,19 +853,19 @@ class AccountsTest { accounts.update(account); if (number != null) { - assertThat(account.getPhoneNumberIdentifierOptional()).isPresent(); + assertThat(account.getPhoneNumberIdentifier()).isPresent(); assertPhoneNumberConstraintExists(number, account.getAccountIdentifier()); - assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifierOptional().get(), account.getAccountIdentifier()); + assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifier().get(), account.getAccountIdentifier()); } else { assertRedeemedReceiptConstraintExists(receiptCredentialPresentation, account.getAccountIdentifier()); } if (number != null) { - assertThat(account.getPhoneNumberIdentifierOptional()).isPresent(); + assertThat(account.getPhoneNumberIdentifier()).isPresent(); final Optional retrievedByE164 = accounts.getByE164(number); assertThat(retrievedByE164).isPresent(); - verifyStoredState(number, account.getAccountIdentifier(), account.getPhoneNumberIdentifierOptional().get(), null, + verifyStoredState(number, account.getAccountIdentifier(), account.getPhoneNumberIdentifier(), null, retrievedByE164.get(), account); } @@ -874,7 +873,7 @@ class AccountsTest { assertThat(retrieved.isPresent()).isTrue(); verifyStoredState(number, account.getAccountIdentifier(), - account.getPhoneNumberIdentifierOptional().orElse(null), null, account, number != null); + account.getPhoneNumberIdentifier(), null, account, number != null); device = generateDevice(DEVICE_ID_1); Account unknownAccount = generateAccount(number == null ? null : "+14151113333", UUID.randomUUID(), @@ -887,7 +886,7 @@ class AccountsTest { assertThat(account.getVersion()).isEqualTo(2); verifyStoredState(number, account.getAccountIdentifier(), - account.getPhoneNumberIdentifierOptional().orElse(null), null, account, number != null); + account.getPhoneNumberIdentifier(), null, account, number != null); account.setVersion(1); @@ -898,13 +897,13 @@ class AccountsTest { accounts.update(account); verifyStoredState(number, account.getAccountIdentifier(), - account.getPhoneNumberIdentifierOptional().orElse(null), null, account, number != null); + account.getPhoneNumberIdentifier(), null, account, number != null); } @ParameterizedTest @ValueSource(strings = "+14151112222") @NullSource - void testUpdateWithMockTransactionConflictException(@Nullable final String number) throws Exception { + void testUpdateWithMockTransactionConflictException(@Nullable final String number) { final DynamoDbClient dynamoDbClient = mock(DynamoDbClient.class); accounts = new Accounts( @@ -1105,12 +1104,12 @@ class AccountsTest { createAccount(deletedAccount); createAccount(retainedAccount); - assertThat(accounts.findRecentlyDeletedAccountIdentifier(deletedAccount.getPhoneNumberIdentifier())).isEmpty(); + assertThat(accounts.findRecentlyDeletedAccountIdentifier(deletedAccount.getPhoneNumberIdentifier().orElseThrow())).isEmpty(); assertPhoneNumberConstraintExists("+14151112222", deletedAccount.getAccountIdentifier()); - assertPhoneNumberIdentifierConstraintExists(deletedAccount.getPhoneNumberIdentifier(), deletedAccount.getAccountIdentifier()); + assertPhoneNumberIdentifierConstraintExists(deletedAccount.getPhoneNumberIdentifier().orElseThrow(), deletedAccount.getAccountIdentifier()); assertPhoneNumberConstraintExists("+14151112345", retainedAccount.getAccountIdentifier()); - assertPhoneNumberIdentifierConstraintExists(retainedAccount.getPhoneNumberIdentifier(), retainedAccount.getAccountIdentifier()); + assertPhoneNumberIdentifierConstraintExists(retainedAccount.getPhoneNumberIdentifier().orElseThrow(), retainedAccount.getAccountIdentifier()); assertThat(accounts.getByAccountIdentifier(deletedAccount.getAccountIdentifier())).isPresent(); assertThat(accounts.getByAccountIdentifier(retainedAccount.getAccountIdentifier())).isPresent(); @@ -1118,27 +1117,27 @@ class AccountsTest { accounts.delete(deletedAccount.getAccountIdentifier(), Collections.emptyList()); assertThat(accounts.getByAccountIdentifier(deletedAccount.getAccountIdentifier())).isNotPresent(); - assertThat(accounts.findRecentlyDeletedAccountIdentifier(deletedAccount.getPhoneNumberIdentifier())).hasValue(deletedAccount.getAccountIdentifier()); + assertThat(accounts.findRecentlyDeletedAccountIdentifier(deletedAccount.getPhoneNumberIdentifier().orElseThrow())).hasValue(deletedAccount.getAccountIdentifier()); - assertPhoneNumberConstraintDoesNotExist(deletedAccount.getNumber()); - assertPhoneNumberIdentifierConstraintDoesNotExist(deletedAccount.getPhoneNumberIdentifier()); + assertPhoneNumberConstraintDoesNotExist(deletedAccount.getNumber().orElseThrow()); + assertPhoneNumberIdentifierConstraintDoesNotExist(deletedAccount.getPhoneNumberIdentifier().orElseThrow()); - verifyStoredState(retainedAccount.getNumber(), retainedAccount.getAccountIdentifier(), retainedAccount.getPhoneNumberIdentifier(), + verifyStoredState(retainedAccount.getNumber().orElseThrow(), retainedAccount.getAccountIdentifier(), retainedAccount.getPhoneNumberIdentifier(), null, accounts.getByAccountIdentifier(retainedAccount.getAccountIdentifier()).orElseThrow(), retainedAccount); { - final Account recreatedAccount = generateAccount(deletedAccount.getNumber(), UUID.randomUUID(), - deletedAccount.getPhoneNumberIdentifier(), List.of(generateDevice(DEVICE_ID_1))); + final Account recreatedAccount = generateAccount(deletedAccount.getNumber().orElseThrow(), UUID.randomUUID(), + deletedAccount.getPhoneNumberIdentifier().orElseThrow(), List.of(generateDevice(DEVICE_ID_1))); final boolean freshUser = createAccount(recreatedAccount); assertThat(freshUser).isTrue(); assertThat(accounts.getByAccountIdentifier(recreatedAccount.getAccountIdentifier())).isPresent(); - verifyStoredState(recreatedAccount.getNumber(), recreatedAccount.getAccountIdentifier(), recreatedAccount.getPhoneNumberIdentifier(), + verifyStoredState(recreatedAccount.getNumber().orElseThrow(), recreatedAccount.getAccountIdentifier(), recreatedAccount.getPhoneNumberIdentifier(), null, accounts.getByAccountIdentifier(recreatedAccount.getAccountIdentifier()).orElseThrow(), recreatedAccount); - assertPhoneNumberConstraintExists(recreatedAccount.getNumber(), recreatedAccount.getAccountIdentifier()); - assertPhoneNumberIdentifierConstraintExists(recreatedAccount.getPhoneNumberIdentifier(), recreatedAccount.getAccountIdentifier()); + assertPhoneNumberConstraintExists(recreatedAccount.getNumber().orElseThrow(), recreatedAccount.getAccountIdentifier()); + assertPhoneNumberIdentifierConstraintExists(recreatedAccount.getPhoneNumberIdentifier().orElseThrow(), recreatedAccount.getAccountIdentifier()); } } @@ -1201,7 +1200,7 @@ class AccountsTest { createAccount(account); - assertThat(accounts.getByPhoneNumberIdentifierAsync(account.getPhoneNumberIdentifier()).join()).isPresent(); + assertThat(accounts.getByPhoneNumberIdentifierAsync(account.getPhoneNumberIdentifier().orElseThrow()).join()).isPresent(); } @Test @@ -1276,7 +1275,7 @@ class AccountsTest { verifyStoredState(targetNumber, account.getAccountIdentifier(), account.getPhoneNumberIdentifier(), null, retrieved.get(), account); - assertThat(retrieved.get().getPhoneNumberIdentifier()).isEqualTo(targetPni); + assertThat(retrieved.get().getPhoneNumberIdentifier()).hasValue(targetPni); assertThat(accounts.getByPhoneNumberIdentifier(targetPni)).isPresent(); } @@ -1445,7 +1444,7 @@ class AccountsTest { final Optional maybeAccount = accounts.getByUsernameHash(USERNAME_HASH_1).join(); assertThat(maybeAccount).isPresent(); - verifyStoredState(firstAccount.getNumber(), firstAccount.getAccountIdentifier(), firstAccount.getPhoneNumberIdentifier(), USERNAME_HASH_1, maybeAccount.get(), firstAccount); + verifyStoredState(firstAccount.getNumber().orElseThrow(), firstAccount.getAccountIdentifier(), firstAccount.getPhoneNumberIdentifier(), USERNAME_HASH_1, maybeAccount.get(), firstAccount); // throw an error if second account tries to reserve or confirm the same username hash assertThrows(UsernameHashNotAvailableException.class, @@ -2123,7 +2122,7 @@ class AccountsTest { // Check that constraints do what they should from a functional perspective if (!numberless) { final Account conflictingNumberAccount = nextRandomAccount(); - conflictingNumberAccount.setNumber(account.getNumberOptional().get(), account.getAccountIdentifier()); + conflictingNumberAccount.setNumber(account.getNumber().get(), account.getAccountIdentifier()); assertThrows(AccountAlreadyExistsException.class, () -> accounts.create(conflictingNumberAccount, Collections.emptyList())); @@ -2149,11 +2148,11 @@ class AccountsTest { if (!numberless) { assertEquals(Optional.of(account.getAccountIdentifier()), getConstraintValue(Tables.NUMBERS.tableName(), Accounts.ATTR_ACCOUNT_E164, - AttributeValues.fromString(account.getNumberOptional().get()))); + AttributeValues.fromString(account.getNumber().get()))); assertEquals(Optional.of(account.getAccountIdentifier()), getConstraintValue(Tables.PNI_ASSIGNMENTS.tableName(), Accounts.ATTR_PNI_UUID, - AttributeValues.fromUUID(account.getPhoneNumberIdentifierOptional().get()))); + AttributeValues.fromUUID(account.getPhoneNumberIdentifier().get()))); } assertEquals(Optional.of(new UsernameConstraint(account.getAccountIdentifier(), true, Optional.empty())), @@ -2181,14 +2180,14 @@ class AccountsTest { final Map originalE164ConstraintItem = DYNAMO_DB_EXTENSION.getDynamoDbClient().getItem(GetItemRequest.builder() .tableName(Tables.NUMBERS.tableName()) - .key(Map.of(Accounts.ATTR_ACCOUNT_E164, AttributeValues.fromString(account.getNumber()))) + .key(Map.of(Accounts.ATTR_ACCOUNT_E164, AttributeValues.fromString(account.getNumber().orElseThrow()))) .build()) .item(); final Map originalPniConstraintItem = DYNAMO_DB_EXTENSION.getDynamoDbClient().getItem(GetItemRequest.builder() .tableName(Tables.PNI_ASSIGNMENTS.tableName()) - .key(Map.of(Accounts.ATTR_PNI_UUID, AttributeValues.fromUUID(account.getIdentifier(IdentityType.PNI)))) + .key(Map.of(Accounts.ATTR_PNI_UUID, AttributeValues.fromUUID(account.getPhoneNumberIdentifier().orElseThrow()))) .build()) .item(); @@ -2198,7 +2197,7 @@ class AccountsTest { .build()) .items()); - accounts.delete(account.getIdentifier(IdentityType.ACI), Collections.emptyList()); + accounts.delete(account.getAccountIdentifier(), Collections.emptyList()); writeAccountRecordWithoutConstraints(account); accounts.regenerateConstraints(account).join(); @@ -2206,14 +2205,14 @@ class AccountsTest { final Map regeneratedE164ConstraintItem = DYNAMO_DB_EXTENSION.getDynamoDbClient().getItem(GetItemRequest.builder() .tableName(Tables.NUMBERS.tableName()) - .key(Map.of(Accounts.ATTR_ACCOUNT_E164, AttributeValues.fromString(account.getNumber()))) + .key(Map.of(Accounts.ATTR_ACCOUNT_E164, AttributeValues.fromString(account.getNumber().orElseThrow()))) .build()) .item(); final Map regeneratedPniConstraintItem = DYNAMO_DB_EXTENSION.getDynamoDbClient().getItem(GetItemRequest.builder() .tableName(Tables.PNI_ASSIGNMENTS.tableName()) - .key(Map.of(Accounts.ATTR_PNI_UUID, AttributeValues.fromUUID(account.getIdentifier(IdentityType.PNI)))) + .key(Map.of(Accounts.ATTR_PNI_UUID, AttributeValues.fromUUID(account.getPhoneNumberIdentifier().orElseThrow()))) .build()) .item(); @@ -2243,11 +2242,11 @@ class AccountsTest { Accounts.ATTR_VERSION, AttributeValues.fromInt(account.getVersion()), Accounts.ATTR_CANONICALLY_DISCOVERABLE, AttributeValues.fromBool(account.isDiscoverableByPhoneNumber()))); - account.getNumberOptional() + account.getNumber() .map(AttributeValues::fromString) .ifPresent(number -> item.put(Accounts.ATTR_ACCOUNT_E164, number)); - account.getPhoneNumberIdentifierOptional() + account.getPhoneNumberIdentifier() .map(AttributeValues::fromUUID) .ifPresent(pni -> item.put(Accounts.ATTR_PNI_UUID, pni)); @@ -2435,8 +2434,8 @@ class AccountsTest { .item(); } - @SuppressWarnings("SameParameterValue") - private void verifyStoredState(String number, UUID uuid, UUID pni, byte[] usernameHash, Account expecting, boolean canonicallyDiscoverable) { + @SuppressWarnings({"SameParameterValue", "OptionalUsedAsFieldOrParameterType"}) + private void verifyStoredState(String number, UUID uuid, Optional maybePni, byte[] usernameHash, Account expecting, boolean canonicallyDiscoverable) { final DynamoDbClient db = DYNAMO_DB_EXTENSION.getDynamoDbClient(); final GetItemResponse get = db.getItem(GetItemRequest.builder() @@ -2461,7 +2460,7 @@ class AccountsTest { assertArrayEquals(AttributeValues.getByteArray(get.item(), Accounts.ATTR_USERNAME_HASH, null), usernameHash); Account result = Accounts.fromItem(get.item()); - verifyStoredState(number, uuid, pni, usernameHash, result, expecting); + verifyStoredState(number, uuid, maybePni, usernameHash, result, expecting); } else { throw new AssertionError("No data"); } @@ -2469,17 +2468,18 @@ class AccountsTest { private void verifyAccountEquals(Account result, Account expecting) { verifyStoredState( - expecting.getNumberOptional().orElse(null), + expecting.getNumber().orElse(null), expecting.getAccountIdentifier(), - expecting.getPhoneNumberIdentifierOptional().orElse(null), + expecting.getPhoneNumberIdentifier(), expecting.getUsernameHash().orElse(null), result, expecting); } - private void verifyStoredState(String number, UUID uuid, UUID pni, byte[] usernameHash, Account result, Account expecting) { - assertThat(result.getNumberOptional()).isEqualTo(Optional.ofNullable(number)); - assertThat(result.getPhoneNumberIdentifierOptional()).isEqualTo(Optional.ofNullable(pni)); + @SuppressWarnings("OptionalUsedAsFieldOrParameterType") + private void verifyStoredState(String number, UUID uuid, Optional maybePni, byte[] usernameHash, Account result, Account expecting) { + assertThat(result.getNumber()).isEqualTo(Optional.ofNullable(number)); + assertThat(result.getPhoneNumberIdentifier()).isEqualTo(maybePni); assertThat(result.getLastSeen()).isEqualTo(expecting.getLastSeen()); assertThat(result.getAccountIdentifier()).isEqualTo(uuid); assertThat(result.getVersion()).isEqualTo(expecting.getVersion()); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AddRemoveDeviceIntegrationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AddRemoveDeviceIntegrationTest.java index c4952d664..84c0d8060 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AddRemoveDeviceIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AddRemoveDeviceIntegrationTest.java @@ -35,7 +35,6 @@ import org.junit.jupiter.params.provider.CsvSource; import org.signal.libsignal.protocol.ecc.ECKeyPair; import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager; import org.whispersystems.textsecuregcm.entities.DeviceInfo; -import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.redis.RedisClusterExtension; import org.whispersystems.textsecuregcm.redis.RedisServerExtension; import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient; @@ -178,7 +177,7 @@ public class AddRemoveDeviceIntegrationTest { } @Test - void addDevice() throws InterruptedException, LinkDeviceTokenAlreadyUsedException { + void addDevice() throws LinkDeviceTokenAlreadyUsedException { final String number = PhoneNumberUtil.getInstance().format( PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164); @@ -190,7 +189,7 @@ public class AddRemoveDeviceIntegrationTest { assertEquals(1, accountsManager.getByAccountIdentifier(account.getAccountIdentifier()).orElseThrow().getDevices().size()); final Pair updatedAccountAndDevice = - accountsManager.addDevice(account.getIdentifier(IdentityType.ACI), new DeviceSpec( + accountsManager.addDevice(account.getAccountIdentifier(), new DeviceSpec( "device-name".getBytes(StandardCharsets.UTF_8), "password", "OWT", @@ -200,7 +199,7 @@ public class AddRemoveDeviceIntegrationTest { true, Optional.empty(), Optional.empty()), - accountsManager.generateLinkDeviceToken(account.getIdentifier(IdentityType.ACI))); + accountsManager.generateLinkDeviceToken(account.getAccountIdentifier())); assertEquals(2, updatedAccountAndDevice.first().getDevices().size()); @@ -213,16 +212,16 @@ public class AddRemoveDeviceIntegrationTest { assertTrue( keysManager.getEcSignedPreKey(updatedAccountAndDevice.first().getAccountIdentifier(), addedDeviceId).join().isPresent()); assertTrue( - keysManager.getEcSignedPreKey(updatedAccountAndDevice.first().getPhoneNumberIdentifier(), addedDeviceId).join() + keysManager.getEcSignedPreKey(updatedAccountAndDevice.first().getPhoneNumberIdentifier().orElseThrow(), addedDeviceId).join() .isPresent()); assertTrue(keysManager.getLastResort(updatedAccountAndDevice.first().getAccountIdentifier(), addedDeviceId).join().isPresent()); assertTrue( - keysManager.getLastResort(updatedAccountAndDevice.first().getPhoneNumberIdentifier(), addedDeviceId).join() + keysManager.getLastResort(updatedAccountAndDevice.first().getPhoneNumberIdentifier().orElseThrow(), addedDeviceId).join() .isPresent()); } @Test - void addDeviceReusedToken() throws InterruptedException, LinkDeviceTokenAlreadyUsedException { + void addDeviceReusedToken() throws LinkDeviceTokenAlreadyUsedException { final String number = PhoneNumberUtil.getInstance().format( PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164); @@ -233,10 +232,10 @@ public class AddRemoveDeviceIntegrationTest { final Account account = AccountsHelper.createAccount(accountsManager, number); assertEquals(1, accountsManager.getByAccountIdentifier(account.getAccountIdentifier()).orElseThrow().getDevices().size()); - final String linkDeviceToken = accountsManager.generateLinkDeviceToken(account.getIdentifier(IdentityType.ACI)); + final String linkDeviceToken = accountsManager.generateLinkDeviceToken(account.getAccountIdentifier()); final Pair updatedAccountAndDevice = - accountsManager.addDevice(account.getIdentifier(IdentityType.ACI), new DeviceSpec( + accountsManager.addDevice(account.getAccountIdentifier(), new DeviceSpec( "device-name".getBytes(StandardCharsets.UTF_8), "password", "OWT", @@ -253,7 +252,7 @@ public class AddRemoveDeviceIntegrationTest { .size()); assertThrows(LinkDeviceTokenAlreadyUsedException.class, - () -> accountsManager.addDevice(account.getIdentifier(IdentityType.ACI), new DeviceSpec( + () -> accountsManager.addDevice(account.getAccountIdentifier(), new DeviceSpec( "device-name".getBytes(StandardCharsets.UTF_8), "password", "OWT", @@ -271,7 +270,7 @@ public class AddRemoveDeviceIntegrationTest { } @Test - void removeDevice() throws InterruptedException, LinkDeviceTokenAlreadyUsedException { + void removeDevice() throws LinkDeviceTokenAlreadyUsedException { final String number = PhoneNumberUtil.getInstance().format( PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164); @@ -283,7 +282,7 @@ public class AddRemoveDeviceIntegrationTest { assertEquals(1, accountsManager.getByAccountIdentifier(account.getAccountIdentifier()).orElseThrow().getDevices().size()); final Pair updatedAccountAndDevice = - accountsManager.addDevice(account.getIdentifier(IdentityType.ACI), new DeviceSpec( + accountsManager.addDevice(account.getAccountIdentifier(), new DeviceSpec( "device-name".getBytes(StandardCharsets.UTF_8), "password", "OWT", @@ -293,30 +292,30 @@ public class AddRemoveDeviceIntegrationTest { true, Optional.empty(), Optional.empty()), - accountsManager.generateLinkDeviceToken(account.getIdentifier(IdentityType.ACI))); + accountsManager.generateLinkDeviceToken(account.getAccountIdentifier())); final byte addedDeviceId = updatedAccountAndDevice.second().getId(); - final Account updatedAccount = accountsManager.removeDevice(updatedAccountAndDevice.first().getIdentifier(IdentityType.ACI), addedDeviceId); + final Account updatedAccount = accountsManager.removeDevice(updatedAccountAndDevice.first().getAccountIdentifier(), addedDeviceId); assertEquals(1, updatedAccount.getDevices().size()); assertFalse(keysManager.getEcSignedPreKey(updatedAccount.getAccountIdentifier(), addedDeviceId).join().isPresent()); assertFalse( - keysManager.getEcSignedPreKey(updatedAccount.getPhoneNumberIdentifier(), addedDeviceId).join().isPresent()); + keysManager.getEcSignedPreKey(updatedAccount.getPhoneNumberIdentifier().orElseThrow(), addedDeviceId).join().isPresent()); assertFalse(keysManager.getLastResort(updatedAccount.getAccountIdentifier(), addedDeviceId).join().isPresent()); - assertFalse(keysManager.getLastResort(updatedAccount.getPhoneNumberIdentifier(), addedDeviceId).join().isPresent()); + assertFalse(keysManager.getLastResort(updatedAccount.getPhoneNumberIdentifier().orElseThrow(), addedDeviceId).join().isPresent()); assertTrue(keysManager.getEcSignedPreKey(updatedAccount.getAccountIdentifier(), Device.PRIMARY_ID).join().isPresent()); assertTrue( - keysManager.getEcSignedPreKey(updatedAccount.getPhoneNumberIdentifier(), Device.PRIMARY_ID).join().isPresent()); + keysManager.getEcSignedPreKey(updatedAccount.getPhoneNumberIdentifier().orElseThrow(), Device.PRIMARY_ID).join().isPresent()); assertTrue(keysManager.getLastResort(updatedAccount.getAccountIdentifier(), Device.PRIMARY_ID).join().isPresent()); assertTrue( - keysManager.getLastResort(updatedAccount.getPhoneNumberIdentifier(), Device.PRIMARY_ID).join().isPresent()); + keysManager.getLastResort(updatedAccount.getPhoneNumberIdentifier().orElseThrow(), Device.PRIMARY_ID).join().isPresent()); } @Test - void removeDevicePartialFailure() throws InterruptedException, LinkDeviceTokenAlreadyUsedException { + void removeDevicePartialFailure() throws LinkDeviceTokenAlreadyUsedException { final String number = PhoneNumberUtil.getInstance().format( PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164); @@ -327,10 +326,10 @@ public class AddRemoveDeviceIntegrationTest { final Account account = AccountsHelper.createAccount(accountsManager, number); assertEquals(1, accountsManager.getByAccountIdentifier(account.getAccountIdentifier()).orElseThrow().getDevices().size()); - final UUID aci = account.getIdentifier(IdentityType.ACI); + final UUID aci = account.getAccountIdentifier(); final Pair updatedAccountAndDevice = - accountsManager.addDevice(account.getIdentifier(IdentityType.ACI), new DeviceSpec( + accountsManager.addDevice(account.getAccountIdentifier(), new DeviceSpec( "device-name".getBytes(StandardCharsets.UTF_8), "password", "OWT", @@ -340,7 +339,7 @@ public class AddRemoveDeviceIntegrationTest { true, Optional.empty(), Optional.empty()), - accountsManager.generateLinkDeviceToken(account.getIdentifier(IdentityType.ACI))); + accountsManager.generateLinkDeviceToken(account.getAccountIdentifier())); final byte addedDeviceId = updatedAccountAndDevice.second().getId(); @@ -348,7 +347,7 @@ public class AddRemoveDeviceIntegrationTest { .thenReturn(CompletableFuture.failedFuture(new RuntimeException("OH NO"))); assertThrows(RuntimeException.class, - () -> accountsManager.removeDevice(updatedAccountAndDevice.first().getIdentifier(IdentityType.ACI), addedDeviceId)); + () -> accountsManager.removeDevice(updatedAccountAndDevice.first().getAccountIdentifier(), addedDeviceId)); final Account retrievedAccount = accountsManager.getByAccountIdentifierAsync(aci).join().orElseThrow(); @@ -356,21 +355,21 @@ public class AddRemoveDeviceIntegrationTest { assertTrue(keysManager.getEcSignedPreKey(retrievedAccount.getAccountIdentifier(), addedDeviceId).join().isPresent()); assertTrue( - keysManager.getEcSignedPreKey(retrievedAccount.getPhoneNumberIdentifier(), addedDeviceId).join().isPresent()); + keysManager.getEcSignedPreKey(retrievedAccount.getPhoneNumberIdentifier().orElseThrow(), addedDeviceId).join().isPresent()); assertTrue(keysManager.getLastResort(retrievedAccount.getAccountIdentifier(), addedDeviceId).join().isPresent()); assertTrue( - keysManager.getLastResort(retrievedAccount.getPhoneNumberIdentifier(), addedDeviceId).join().isPresent()); + keysManager.getLastResort(retrievedAccount.getPhoneNumberIdentifier().orElseThrow(), addedDeviceId).join().isPresent()); assertTrue(keysManager.getEcSignedPreKey(retrievedAccount.getAccountIdentifier(), Device.PRIMARY_ID).join().isPresent()); - assertTrue(keysManager.getEcSignedPreKey(retrievedAccount.getPhoneNumberIdentifier(), Device.PRIMARY_ID).join() + assertTrue(keysManager.getEcSignedPreKey(retrievedAccount.getPhoneNumberIdentifier().orElseThrow(), Device.PRIMARY_ID).join() .isPresent()); assertTrue(keysManager.getLastResort(retrievedAccount.getAccountIdentifier(), Device.PRIMARY_ID).join().isPresent()); assertTrue( - keysManager.getLastResort(retrievedAccount.getPhoneNumberIdentifier(), Device.PRIMARY_ID).join().isPresent()); + keysManager.getLastResort(retrievedAccount.getPhoneNumberIdentifier().orElseThrow(), Device.PRIMARY_ID).join().isPresent()); } @Test - void waitForNewLinkedDevice() throws InterruptedException, LinkDeviceTokenAlreadyUsedException { + void waitForNewLinkedDevice() throws LinkDeviceTokenAlreadyUsedException { final String number = PhoneNumberUtil.getInstance().format( PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164); @@ -380,7 +379,7 @@ public class AddRemoveDeviceIntegrationTest { final Account account = AccountsHelper.createAccount(accountsManager, number); - final String linkDeviceToken = accountsManager.generateLinkDeviceToken(account.getIdentifier(IdentityType.ACI)); + final String linkDeviceToken = accountsManager.generateLinkDeviceToken(account.getAccountIdentifier()); final String linkDeviceTokenIdentifier = AccountsManager.getLinkDeviceTokenIdentifier(linkDeviceToken); final CompletableFuture> displacedFuture = accountsManager.waitForNewLinkedDevice( @@ -396,7 +395,7 @@ public class AddRemoveDeviceIntegrationTest { assertEquals(Optional.empty(), displacedFuture.join()); final Pair updatedAccountAndDevice = - accountsManager.addDevice(account.getIdentifier(IdentityType.ACI), new DeviceSpec( + accountsManager.addDevice(account.getAccountIdentifier(), new DeviceSpec( "device-name".getBytes(StandardCharsets.UTF_8), "password", "OWT", @@ -414,12 +413,12 @@ public class AddRemoveDeviceIntegrationTest { final DeviceInfo deviceInfo = maybeDeviceInfo.get(); assertEquals(updatedAccountAndDevice.second().getId(), deviceInfo.id()); - assertEquals(updatedAccountAndDevice.second().getRegistrationId(IdentityType.ACI), deviceInfo.registrationId()); + assertEquals(updatedAccountAndDevice.second().getAccountRegistrationId(), deviceInfo.registrationId()); assertNotNull(deviceInfo.createdAtCiphertext()); } @Test - void waitForNewLinkedDeviceAlreadyAdded() throws InterruptedException, LinkDeviceTokenAlreadyUsedException { + void waitForNewLinkedDeviceAlreadyAdded() throws LinkDeviceTokenAlreadyUsedException { final String number = PhoneNumberUtil.getInstance().format( PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164); @@ -429,11 +428,11 @@ public class AddRemoveDeviceIntegrationTest { final Account account = AccountsHelper.createAccount(accountsManager, number); - final String linkDeviceToken = accountsManager.generateLinkDeviceToken(account.getIdentifier(IdentityType.ACI)); + final String linkDeviceToken = accountsManager.generateLinkDeviceToken(account.getAccountIdentifier()); final String linkDeviceTokenIdentifier = AccountsManager.getLinkDeviceTokenIdentifier(linkDeviceToken); final Pair updatedAccountAndDevice = - accountsManager.addDevice(account.getIdentifier(IdentityType.ACI), new DeviceSpec( + accountsManager.addDevice(account.getAccountIdentifier(), new DeviceSpec( "device-name".getBytes(StandardCharsets.UTF_8), "password", "OWT", @@ -457,12 +456,12 @@ public class AddRemoveDeviceIntegrationTest { final DeviceInfo deviceInfo = maybeDeviceInfo.get(); assertEquals(updatedAccountAndDevice.second().getId(), deviceInfo.id()); - assertEquals(updatedAccountAndDevice.second().getRegistrationId(IdentityType.ACI), deviceInfo.registrationId()); + assertEquals(updatedAccountAndDevice.second().getAccountRegistrationId(), deviceInfo.registrationId()); assertNotNull(deviceInfo.createdAtCiphertext()); } @Test - void waitForNewLinkedDeviceTimeout() throws InterruptedException { + void waitForNewLinkedDeviceTimeout() { final String number = PhoneNumberUtil.getInstance().format( PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164); @@ -487,7 +486,7 @@ public class AddRemoveDeviceIntegrationTest { "10_000,10_001,false", // pending message after now }) void waitForMessageFetch(long currentTime, Long oldestMessage, boolean shouldWait) - throws InterruptedException, LinkDeviceTokenAlreadyUsedException { + throws LinkDeviceTokenAlreadyUsedException { final String number = PhoneNumberUtil.getInstance().format( PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164); @@ -498,7 +497,7 @@ public class AddRemoveDeviceIntegrationTest { final String linkDeviceToken = accountsManager.generateLinkDeviceToken(UUID.randomUUID()); final String linkDeviceTokenIdentifier = AccountsManager.getLinkDeviceTokenIdentifier(linkDeviceToken); - accountsManager.addDevice(account.getIdentifier(IdentityType.ACI), new DeviceSpec( + accountsManager.addDevice(account.getAccountIdentifier(), new DeviceSpec( "device-name".getBytes(StandardCharsets.UTF_8), "password", "OWT", @@ -524,8 +523,7 @@ public class AddRemoveDeviceIntegrationTest { // preempted by the timeout check @Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD) @Test - void waitForMessageFetchRetries() - throws InterruptedException, LinkDeviceTokenAlreadyUsedException { + void waitForMessageFetchRetries() throws LinkDeviceTokenAlreadyUsedException { final String number = PhoneNumberUtil.getInstance().format( PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164); @@ -537,7 +535,7 @@ public class AddRemoveDeviceIntegrationTest { final String linkDeviceTokenIdentifier = AccountsManager.getLinkDeviceTokenIdentifier(linkDeviceToken); clock.pin(Instant.ofEpochMilli(0)); - accountsManager.addDevice(account.getIdentifier(IdentityType.ACI), new DeviceSpec( + accountsManager.addDevice(account.getAccountIdentifier(), new DeviceSpec( "device-name".getBytes(StandardCharsets.UTF_8), "password", "OWT", diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/ChangeNumberManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/ChangeNumberManagerTest.java index 0a92ef679..fe6fea87c 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/ChangeNumberManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/ChangeNumberManagerTest.java @@ -51,7 +51,6 @@ import org.whispersystems.textsecuregcm.entities.MessageProtos; import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest; import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure; import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; -import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier; import org.whispersystems.textsecuregcm.limits.RateLimiter; import org.whispersystems.textsecuregcm.limits.RateLimiters; @@ -120,11 +119,11 @@ public class ChangeNumberManagerTest { final Account updatedAccount = mock(Account.class); when(updatedAccount.getAccountIdentifier()).thenReturn(uuid); - when(updatedAccount.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(updatedPni)); + when(updatedAccount.getPhoneNumberIdentifier()).thenReturn(Optional.of(updatedPni)); when(updatedAccount.isIdentifiedBy(any())).thenReturn(false); when(updatedAccount.isIdentifiedBy(new AciServiceIdentifier(uuid))).thenReturn(true); when(updatedAccount.isIdentifiedBy(new PniServiceIdentifier(updatedPni))).thenReturn(true); - when(updatedAccount.getNumberOptional()).thenReturn(Optional.of(number)); + when(updatedAccount.getNumber()).thenReturn(Optional.of(number)); when(updatedAccount.getDevices()).thenReturn(devices); when(updatedAccount.getDevice(anyByte())).thenReturn(Optional.empty()); when(updatedAccount.getPrimaryDevice()).thenReturn(primaryDevice); @@ -156,7 +155,7 @@ public class ChangeNumberManagerTest { final UUID accountIdentifier = UUID.randomUUID(); final Account account = mock(Account.class); - when(account.getNumberOptional()).thenReturn(Optional.of(originalNumber)); + when(account.getNumber()).thenReturn(Optional.of(originalNumber)); when(account.getAccountIdentifier()).thenReturn(accountIdentifier); when(account.isIdentifiedBy(any())).thenReturn(false); when(account.isIdentifiedBy(new AciServiceIdentifier(accountIdentifier))).thenReturn(true); @@ -187,14 +186,14 @@ public class ChangeNumberManagerTest { final Device primaryDevice = mock(Device.class); when(primaryDevice.getId()).thenReturn(primaryDeviceId); - when(primaryDevice.getRegistrationId(IdentityType.ACI)).thenReturn(primaryDeviceRegistrationId); + when(primaryDevice.getAccountRegistrationId()).thenReturn(primaryDeviceRegistrationId); final Device linkedDevice = mock(Device.class); when(linkedDevice.getId()).thenReturn(linkedDeviceId); - when(linkedDevice.getRegistrationId(IdentityType.ACI)).thenReturn(linkedDeviceRegistrationId); + when(linkedDevice.getAccountRegistrationId()).thenReturn(linkedDeviceRegistrationId); final Account account = mock(Account.class); - when(account.getNumberOptional()).thenReturn(Optional.of(originalNumber)); + when(account.getNumber()).thenReturn(Optional.of(originalNumber)); when(account.getAccountIdentifier()).thenReturn(aci); when(account.isIdentifiedBy(any())).thenReturn(false); when(account.isIdentifiedBy(new AciServiceIdentifier(aci))).thenReturn(true); @@ -280,7 +279,7 @@ public class ChangeNumberManagerTest { final UUID accountIdentifier = UUID.randomUUID(); final Account account = mock(Account.class); - when(account.getNumberOptional()).thenReturn(Optional.of(targetNumber)); + when(account.getNumber()).thenReturn(Optional.of(targetNumber)); when(account.getAccountIdentifier()).thenReturn(accountIdentifier); when(account.isIdentifiedBy(any())).thenReturn(false); when(account.isIdentifiedBy(new AciServiceIdentifier(accountIdentifier))).thenReturn(true); @@ -319,7 +318,7 @@ public class ChangeNumberManagerTest { final UUID accountIdentifier = UUID.randomUUID(); final Account account = mock(Account.class); - when(account.getNumberOptional()).thenReturn(Optional.of(originalNumber)); + when(account.getNumber()).thenReturn(Optional.of(originalNumber)); when(account.getAccountIdentifier()).thenReturn(accountIdentifier); when(account.isIdentifiedBy(any())).thenReturn(false); when(account.isIdentifiedBy(new AciServiceIdentifier(accountIdentifier))).thenReturn(true); @@ -367,13 +366,13 @@ public class ChangeNumberManagerTest { final UUID accountIdentifier = UUID.randomUUID(); final Account account = mock(Account.class); - when(account.getNumberOptional()).thenReturn(Optional.of(originalNumber)); + when(account.getNumber()).thenReturn(Optional.of(originalNumber)); when(account.getAccountIdentifier()).thenReturn(accountIdentifier); when(account.isIdentifiedBy(any())).thenReturn(false); when(account.isIdentifiedBy(new AciServiceIdentifier(accountIdentifier))).thenReturn(true); final Account existingAccount = mock(Account.class); - when(existingAccount.getNumberOptional()).thenReturn(Optional.of(targetNumber)); + when(existingAccount.getNumber()).thenReturn(Optional.of(targetNumber)); when(accountsManager.getAccountsForChangeNumber(eq(accountIdentifier), any())) .thenReturn(new Pair<>(account, Optional.of(existingAccount))); @@ -414,7 +413,7 @@ public class ChangeNumberManagerTest { final UUID accountIdentifier = UUID.randomUUID(); final Account account = mock(Account.class); - when(account.getNumberOptional()).thenReturn(Optional.empty()); + when(account.getNumber()).thenReturn(Optional.empty()); when(accountsManager.getAccountsForChangeNumber(eq(accountIdentifier), any())) .thenReturn(new Pair<>(account, Optional.empty())); @@ -456,7 +455,7 @@ public class ChangeNumberManagerTest { final UUID accountIdentifier = UUID.randomUUID(); final Account account = mock(Account.class); - when(account.getNumberOptional()).thenReturn(Optional.of(originalNumber)); + when(account.getNumber()).thenReturn(Optional.of(originalNumber)); when(account.getAccountIdentifier()).thenReturn(accountIdentifier); when(account.isIdentifiedBy(any())).thenReturn(false); when(account.isIdentifiedBy(new AciServiceIdentifier(accountIdentifier))).thenReturn(true); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagePersisterIntegrationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagePersisterIntegrationTest.java index fe34b273d..b57a9dd7c 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagePersisterIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagePersisterIntegrationTest.java @@ -126,7 +126,7 @@ class MessagePersisterIntegrationTest { final UUID accountUuid = UUID.randomUUID(); - when(account.getNumber()).thenReturn("+18005551234"); + when(account.getNumber()).thenReturn(Optional.of("+18005551234")); when(account.getAccountIdentifier()).thenReturn(accountUuid); when(accountsManager.getByAccountIdentifier(accountUuid)).thenReturn(Optional.of(account)); when(accountsManager.getByAccountIdentifierAsync(accountUuid)).thenReturn(CompletableFuture.completedFuture(Optional.of(account))); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagePersisterTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagePersisterTest.java index aef8b9725..7d9ab2bc0 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagePersisterTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagePersisterTest.java @@ -56,7 +56,6 @@ import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfigurati import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicMessagePersisterConfiguration; import org.whispersystems.textsecuregcm.entities.MessageProtos; import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; -import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.redis.RedisClusterExtension; import org.whispersystems.textsecuregcm.tests.util.DevicesHelper; import org.whispersystems.textsecuregcm.util.TestClock; @@ -119,8 +118,7 @@ class MessagePersisterTest { .thenAnswer(invocation -> accountsManager.getByAccountIdentifier(invocation.getArgument(0)).orElseThrow()); when(destinationAccount.getAccountIdentifier()).thenReturn(DESTINATION_ACCOUNT_UUID); - when(destinationAccount.getIdentifier(IdentityType.ACI)).thenReturn(DESTINATION_ACCOUNT_UUID); - when(destinationAccount.getNumber()).thenReturn(DESTINATION_ACCOUNT_NUMBER); + when(destinationAccount.getNumber()).thenReturn(Optional.of(DESTINATION_ACCOUNT_NUMBER)); when(destinationAccount.getDevice(DESTINATION_DEVICE_ID)).thenReturn(Optional.of(DESTINATION_DEVICE)); dynamicConfiguration = mock(DynamicConfiguration.class); @@ -250,7 +248,7 @@ class MessagePersisterTest { .thenReturn(CompletableFuture.completedFuture(Optional.of(account))); when(account.getAccountIdentifier()).thenReturn(accountUuid); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountUuid); + when(account.getAccountIdentifier()).thenReturn(accountUuid); when(account.getDevice(anyByte())).thenAnswer(invocation -> Optional.of(DevicesHelper.createDevice(invocation.getArgument(0)))); insertMessages(accountUuid, deviceId, messagesPerQueue, CLOCK.instant().minus(PERSIST_DELAY.plusSeconds(1))); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesManagerTest.java index 29130d5e2..e6d1b8944 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesManagerTest.java @@ -193,10 +193,10 @@ class MessagesManagerTest { final Account singleDeviceAccount = mock(Account.class); final Account multiDeviceAccount = mock(Account.class); - when(singleDeviceAccount.getIdentifier(IdentityType.ACI)) + when(singleDeviceAccount.getAccountIdentifier()) .thenReturn(singleDeviceAccountAciServiceIdentifier.uuid()); - when(multiDeviceAccount.getIdentifier(IdentityType.ACI)) + when(multiDeviceAccount.getAccountIdentifier()) .thenReturn(multiDeviceAccountAciServiceIdentifier.uuid()); final byte[] multiRecipientMessageBytes = MultiRecipientMessageHelper.generateMultiRecipientMessage(List.of( diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/PhoneNumberIdentifiersTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/PhoneNumberIdentifiersTest.java index 679ed2078..c044204a7 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/PhoneNumberIdentifiersTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/PhoneNumberIdentifiersTest.java @@ -216,8 +216,8 @@ class PhoneNumberIdentifiersTest { final UUID phoneNumberIdentifier = UUID.randomUUID(); final Account account = mock(Account.class); - when(account.getNumberOptional()).thenReturn(Optional.of(newFormatBeninE164)); - when(account.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(phoneNumberIdentifier)); + when(account.getNumber()).thenReturn(Optional.of(newFormatBeninE164)); + when(account.getPhoneNumberIdentifier()).thenReturn(Optional.of(phoneNumberIdentifier)); phoneNumberIdentifiers.regeneratePhoneNumberIdentifierMappings(account).join(); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/ReportMessageManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/ReportMessageManagerTest.java index 9b2b24262..ad2b3a90b 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/ReportMessageManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/ReportMessageManagerTest.java @@ -54,7 +54,7 @@ class ReportMessageManagerTest { sourceAccount = mock(Account.class); when(sourceAccount.getAccountIdentifier()).thenReturn(sourceAci); - when(sourceAccount.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(sourcePni)); + when(sourceAccount.getPhoneNumberIdentifier()).thenReturn(Optional.of(sourcePni)); } @Test diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/tests/util/AccountsHelper.java b/service/src/test/java/org/whispersystems/textsecuregcm/tests/util/AccountsHelper.java index 10377c75e..c48a2ba58 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/tests/util/AccountsHelper.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/tests/util/AccountsHelper.java @@ -22,7 +22,6 @@ import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; -import org.junit.platform.commons.util.StringUtils; import org.mockito.MockingDetails; import org.mockito.stubbing.Stubbing; import org.signal.libsignal.protocol.IdentityKey; @@ -33,7 +32,6 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation; import org.whispersystems.textsecuregcm.entities.AccountAttributes; import org.whispersystems.textsecuregcm.entities.DeviceAttributes; import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; -import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier; import org.whispersystems.textsecuregcm.storage.Account; import org.whispersystems.textsecuregcm.storage.AccountsManager; @@ -189,9 +187,9 @@ public class AccountsHelper { } public static void setupMockGet(final AccountsManager mockAccountsManager, final Account account) { - if (account.getAccountIdentifier() != null || account.getIdentifier(IdentityType.ACI) != null) { + if (account.getAccountIdentifier() != null || account.getAccountIdentifier() != null) { final UUID accountIdentifier = - Objects.requireNonNullElseGet(account.getIdentifier(IdentityType.ACI), account::getAccountIdentifier); + Objects.requireNonNullElseGet(account.getAccountIdentifier(), account::getAccountIdentifier); when(mockAccountsManager.getByAccountIdentifier(accountIdentifier)) .thenReturn(Optional.of(account)); @@ -206,10 +204,7 @@ public class AccountsHelper { .thenReturn(CompletableFuture.completedFuture(Optional.of(account))); } - if (account.getPhoneNumberIdentifier() != null || account.getIdentifier(IdentityType.PNI) != null) { - final UUID phoneNumberIdentifier = - Objects.requireNonNullElseGet(account.getIdentifier(IdentityType.PNI), account::getPhoneNumberIdentifier); - + account.getPhoneNumberIdentifier().ifPresent(phoneNumberIdentifier -> { when(mockAccountsManager.getByPhoneNumberIdentifier(phoneNumberIdentifier)) .thenReturn(Optional.of(account)); @@ -221,11 +216,11 @@ public class AccountsHelper { when(mockAccountsManager.getByServiceIdentifierAsync(new PniServiceIdentifier(phoneNumberIdentifier))) .thenReturn(CompletableFuture.completedFuture(Optional.of(account))); - } + }); - if (StringUtils.isNotBlank(account.getNumber())) { - when(mockAccountsManager.getByE164(account.getNumber())).thenReturn(Optional.of(account)); - } + account.getNumber().ifPresent(number -> { + when(mockAccountsManager.getByE164(number)).thenReturn(Optional.of(account)); + }); account.getUsernameHash().ifPresent(usernameHash -> when(mockAccountsManager.getByUsernameHash(usernameHash)) .thenReturn(CompletableFuture.completedFuture(Optional.of(account)))); @@ -249,12 +244,9 @@ public class AccountsHelper { for (Stubbing stubbing : mockingDetails.getStubbings()) { switch (stubbing.getInvocation().getMethod().getName()) { case "getAccountIdentifier" -> when(updatedAccount.getAccountIdentifier()).thenAnswer(stubbing); - case "getPhoneNumberIdentifierOptional" -> when(updatedAccount.getPhoneNumberIdentifierOptional()).thenAnswer(stubbing); case "getPhoneNumberIdentifier" -> when(updatedAccount.getPhoneNumberIdentifier()).thenAnswer(stubbing); - case "getIdentifier" -> when(updatedAccount.getIdentifier(stubbing.getInvocation().getArgument(0))).thenAnswer(stubbing); case "isIdentifiedBy" -> when(updatedAccount.isIdentifiedBy(stubbing.getInvocation().getArgument(0))).thenAnswer(stubbing); case "getNumber" -> when(updatedAccount.getNumber()).thenAnswer(stubbing); - case "getNumberOptional" -> when(updatedAccount.getNumberOptional()).thenAnswer(stubbing); case "getUsername" -> when(updatedAccount.getUsernameHash()).thenAnswer(stubbing); case "getUsernameHash" -> when(updatedAccount.getUsernameHash()).thenAnswer(stubbing); case "getUsernameLinkHandle" -> when(updatedAccount.getUsernameLinkHandle()).thenAnswer(stubbing); @@ -265,8 +257,6 @@ public class AccountsHelper { case "getNextDeviceId" -> when(updatedAccount.getNextDeviceId()).thenAnswer(stubbing); case "hasCapability" -> when(updatedAccount.hasCapability(stubbing.getInvocation().getArgument(0))).thenAnswer(stubbing); case "getRegistrationLock" -> when(updatedAccount.getRegistrationLock()).thenAnswer(stubbing); - case "getIdentityKey" -> - when(updatedAccount.getIdentityKey(stubbing.getInvocation().getArgument(0))).thenAnswer(stubbing); case "getBadges" -> when(updatedAccount.getBadges()).thenAnswer(stubbing); case "getBackupVoucher" -> when(updatedAccount.getBackupVoucher()).thenAnswer(stubbing); case "getLastSeen" -> when(updatedAccount.getLastSeen()).thenAnswer(stubbing); @@ -281,7 +271,7 @@ public class AccountsHelper { } else { final ObjectMapper mapper = SystemMapper.jsonMapper(); updatedAccount = mapper.readValue(mapper.writeValueAsBytes(account), Account.class); - updatedAccount.setNumber(account.getNumber(), account.getPhoneNumberIdentifier()); + updatedAccount.setNumber(account.getNumber().orElseThrow(), account.getPhoneNumberIdentifier().orElseThrow()); account.markStale(); } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/tests/util/AuthHelper.java b/service/src/test/java/org/whispersystems/textsecuregcm/tests/util/AuthHelper.java index 941f60c3b..132c190cd 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/tests/util/AuthHelper.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/tests/util/AuthHelper.java @@ -6,7 +6,6 @@ package org.whispersystems.textsecuregcm.tests.util; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.when; @@ -27,12 +26,10 @@ import java.util.Base64; import java.util.Collection; import java.util.HashSet; import java.util.List; -import java.util.NoSuchElementException; import java.util.Optional; import java.util.Random; import java.util.UUID; import java.util.stream.Stream; - import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.ExtensionContext; import org.mockito.quality.Strictness; @@ -47,13 +44,12 @@ import org.signal.libsignal.zkgroup.groups.GroupSecretParams; import org.signal.libsignal.zkgroup.groups.UuidCiphertext; import org.signal.libsignal.zkgroup.groupsend.GroupSendDerivedKeyPair; import org.signal.libsignal.zkgroup.groupsend.GroupSendEndorsementsResponse; -import org.signal.libsignal.zkgroup.groupsend.GroupSendFullToken; import org.signal.libsignal.zkgroup.groupsend.GroupSendEndorsementsResponse.ReceivedEndorsements; +import org.signal.libsignal.zkgroup.groupsend.GroupSendFullToken; import org.whispersystems.textsecuregcm.auth.AccountAuthenticator; import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice; import org.whispersystems.textsecuregcm.auth.SaltedTokenHash; import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; -import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier; import org.whispersystems.textsecuregcm.identity.ServiceIdentifier; import org.whispersystems.textsecuregcm.storage.Account; @@ -169,34 +165,18 @@ public class AuthHelper { when(UNDISCOVERABLE_ACCOUNT.getDevices()).thenReturn(List.of(UNDISCOVERABLE_DEVICE)); when(VALID_ACCOUNT_3.getDevices()).thenReturn(List.of(VALID_DEVICE_3_PRIMARY, VALID_DEVICE_3_LINKED)); - when(VALID_ACCOUNT.getNumber()).thenReturn(VALID_NUMBER); - when(VALID_ACCOUNT.getNumberOptional()).thenReturn(Optional.of(VALID_NUMBER)); + when(VALID_ACCOUNT.getNumber()).thenReturn(Optional.of(VALID_NUMBER)); when(VALID_ACCOUNT.getAccountIdentifier()).thenReturn(VALID_UUID); - when(VALID_ACCOUNT.getPhoneNumberIdentifier()).thenReturn(VALID_PNI); - when(VALID_ACCOUNT.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(VALID_PNI)); - when(VALID_ACCOUNT.getIdentifier(IdentityType.ACI)).thenReturn(VALID_UUID); - when(VALID_ACCOUNT.getIdentifier(IdentityType.PNI)).thenReturn(VALID_PNI); - when(VALID_ACCOUNT_TWO.getNumber()).thenReturn(VALID_NUMBER_TWO); - when(VALID_ACCOUNT_TWO.getNumberOptional()).thenReturn(Optional.of(VALID_NUMBER_TWO)); + when(VALID_ACCOUNT.getPhoneNumberIdentifier()).thenReturn(Optional.of(VALID_PNI)); + when(VALID_ACCOUNT_TWO.getNumber()).thenReturn(Optional.of(VALID_NUMBER_TWO)); when(VALID_ACCOUNT_TWO.getAccountIdentifier()).thenReturn(VALID_UUID_TWO); - when(VALID_ACCOUNT_TWO.getPhoneNumberIdentifier()).thenReturn(VALID_PNI_TWO); - when(VALID_ACCOUNT_TWO.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(VALID_PNI_TWO)); - when(VALID_ACCOUNT_TWO.getIdentifier(IdentityType.ACI)).thenReturn(VALID_UUID_TWO); - when(VALID_ACCOUNT_TWO.getIdentifier(IdentityType.PNI)).thenReturn(VALID_PNI_TWO); - when(UNDISCOVERABLE_ACCOUNT.getNumber()).thenReturn(UNDISCOVERABLE_NUMBER); - when(UNDISCOVERABLE_ACCOUNT.getNumberOptional()).thenReturn(Optional.of(UNDISCOVERABLE_NUMBER)); + when(VALID_ACCOUNT_TWO.getPhoneNumberIdentifier()).thenReturn(Optional.of(VALID_PNI_TWO)); + when(UNDISCOVERABLE_ACCOUNT.getNumber()).thenReturn(Optional.of(UNDISCOVERABLE_NUMBER)); when(UNDISCOVERABLE_ACCOUNT.getAccountIdentifier()).thenReturn(UNDISCOVERABLE_UUID); - when(UNDISCOVERABLE_ACCOUNT.getPhoneNumberIdentifier()).thenReturn(UNDISCOVERABLE_PNI); - when(UNDISCOVERABLE_ACCOUNT.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(UNDISCOVERABLE_PNI)); - when(UNDISCOVERABLE_ACCOUNT.getIdentifier(IdentityType.ACI)).thenReturn(UNDISCOVERABLE_UUID); - when(UNDISCOVERABLE_ACCOUNT.getIdentifier(IdentityType.PNI)).thenReturn(UNDISCOVERABLE_PNI); - when(VALID_ACCOUNT_3.getNumber()).thenReturn(VALID_NUMBER_3); - when(VALID_ACCOUNT_3.getNumberOptional()).thenReturn(Optional.of(VALID_NUMBER_3)); + when(UNDISCOVERABLE_ACCOUNT.getPhoneNumberIdentifier()).thenReturn(Optional.of(UNDISCOVERABLE_PNI)); + when(VALID_ACCOUNT_3.getNumber()).thenReturn(Optional.of(VALID_NUMBER_3)); when(VALID_ACCOUNT_3.getAccountIdentifier()).thenReturn(VALID_UUID_3); - when(VALID_ACCOUNT_3.getPhoneNumberIdentifier()).thenReturn(VALID_PNI_3); - when(VALID_ACCOUNT_3.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(VALID_PNI_3)); - when(VALID_ACCOUNT_3.getIdentifier(IdentityType.ACI)).thenReturn(VALID_UUID_3); - when(VALID_ACCOUNT_3.getIdentifier(IdentityType.PNI)).thenReturn(VALID_PNI_3); + when(VALID_ACCOUNT_3.getPhoneNumberIdentifier()).thenReturn(Optional.of(VALID_PNI_3)); when(VALID_ACCOUNT.isDiscoverableByPhoneNumber()).thenReturn(true); when(VALID_ACCOUNT_TWO.isDiscoverableByPhoneNumber()).thenReturn(true); @@ -211,9 +191,7 @@ public class AuthHelper { when(VALID_ACCOUNT_3.isIdentifiedBy(new AciServiceIdentifier(VALID_UUID_3))).thenReturn(true); when(VALID_ACCOUNT_3.isIdentifiedBy(new PniServiceIdentifier(VALID_PNI_3))).thenReturn(true); - when(VALID_ACCOUNT.getIdentityKey(IdentityType.ACI)).thenReturn(VALID_IDENTITY); when(VALID_ACCOUNT.getAccountIdentityKey()).thenReturn(VALID_IDENTITY); - when(VALID_ACCOUNT.getIdentityKey(IdentityType.PNI)).thenReturn(VALID_PNI_IDENTITY); when(VALID_ACCOUNT.getPhoneNumberIdentityKey()).thenReturn(Optional.of(VALID_PNI_IDENTITY)); when(NUMBERLESS_CREDENTIALS.verify(NUMBERLESS_PASSWORD)).thenReturn(true); @@ -226,16 +204,11 @@ public class AuthHelper { when(NUMBERLESS_ACCOUNT.getAccountIdentifier()).thenReturn(NUMBERLESS_UUID); when(NUMBERLESS_ACCOUNT.isIdentifiedBy(new AciServiceIdentifier(NUMBERLESS_UUID))).thenReturn(true); when(NUMBERLESS_ACCOUNT.isDiscoverableByPhoneNumber()).thenReturn(false); - when(NUMBERLESS_ACCOUNT.getIdentityKey(IdentityType.ACI)).thenReturn(VALID_IDENTITY); when(NUMBERLESS_ACCOUNT.getAccountIdentityKey()).thenReturn(VALID_IDENTITY); - when(NUMBERLESS_ACCOUNT.getNumberOptional()).thenReturn(Optional.empty()); - when(NUMBERLESS_ACCOUNT.getPhoneNumberIdentifierOptional()).thenReturn(Optional.empty()); + when(NUMBERLESS_ACCOUNT.getNumber()).thenReturn(Optional.empty()); + when(NUMBERLESS_ACCOUNT.getPhoneNumberIdentifier()).thenReturn(Optional.empty()); when(NUMBERLESS_ACCOUNT.getAuthCredentialSalt()).thenReturn(Optional.of(NUMBERLESS_AUTH_CREDENTIAL_SALT)); - doThrow(new NoSuchElementException()).when(NUMBERLESS_ACCOUNT).getNumber(); - doThrow(new NoSuchElementException()).when(NUMBERLESS_ACCOUNT).getPhoneNumberIdentifier(); - doThrow(new NoSuchElementException()).when(NUMBERLESS_ACCOUNT).getIdentityKey(IdentityType.PNI); - doThrow(new NoSuchElementException()).when(NUMBERLESS_ACCOUNT).getIdentifier(IdentityType.PNI); - when(NUMBERLESS_ACCOUNT.getIdentifier(IdentityType.ACI)).thenReturn(NUMBERLESS_UUID); + when(NUMBERLESS_ACCOUNT.getAccountIdentifier()).thenReturn(NUMBERLESS_UUID); reset(ACCOUNTS_MANAGER); @@ -320,9 +293,9 @@ public class AuthHelper { when(device.getId()).thenReturn(Device.PRIMARY_ID); when(account.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(device)); when(account.getPrimaryDevice()).thenReturn(device); - when(account.getNumber()).thenReturn(number); + when(account.getNumber()).thenReturn(Optional.of(number)); + when(account.getAccountIdentifier()).thenReturn(uuid); when(account.getAccountIdentifier()).thenReturn(uuid); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(uuid); when(accountsManager.getByE164(number)).thenReturn(Optional.of(account)); when(accountsManager.getByAccountIdentifier(uuid)).thenReturn(Optional.of(account)); } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/util/ProfileHelperTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/util/ProfileHelperTest.java index f226e2250..cd573419e 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/util/ProfileHelperTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/util/ProfileHelperTest.java @@ -65,15 +65,15 @@ class ProfileHelperTest { final Account account = mock(Account.class); switch (phoneNumberType) { - case ALLOWED -> when(account.getNumberOptional()) + case ALLOWED -> when(account.getNumber()) .thenReturn(Optional.of(PhoneNumberUtil.getInstance().format( PhoneNumberUtil.getInstance().getExampleNumber("DE"), PhoneNumberUtil.PhoneNumberFormat.E164))); - case FORBIDDEN -> when(account.getNumberOptional()) + case FORBIDDEN -> when(account.getNumber()) .thenReturn(Optional.of(PhoneNumberUtil.getInstance().format( PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164))); - case NONE -> when(account.getNumberOptional()).thenReturn(Optional.empty()); + case NONE -> when(account.getNumber()).thenReturn(Optional.empty()); } final AsnInfoProvider asnInfoProvider = mock(AsnInfoProvider.class); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/websocket/AuthenticatedConnectListenerIntegrationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/websocket/AuthenticatedConnectListenerIntegrationTest.java index 223ac2907..454d7ff87 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/websocket/AuthenticatedConnectListenerIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/websocket/AuthenticatedConnectListenerIntegrationTest.java @@ -54,7 +54,6 @@ import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager; import org.whispersystems.textsecuregcm.filters.PriorityFilter; import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter; import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; -import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor; import org.whispersystems.textsecuregcm.metrics.MessageMetrics; import org.whispersystems.textsecuregcm.push.PushNotificationManager; @@ -103,8 +102,8 @@ class AuthenticatedConnectListenerIntegrationTest { void setUp() throws Exception { reset(messagesManager, disconnectionRequestManager, accountsManager, account, device); when(messagesManager.mayHaveMessages(any(), any())).thenReturn(CompletableFuture.completedFuture(false)); - when(account.getNumber()).thenReturn(E164); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(ACCOUNT_UUID); + when(account.getNumber()).thenReturn(Optional.of(E164)); + when(account.getAccountIdentifier()).thenReturn(ACCOUNT_UUID); when(account.getDevice(DEVICE_ID)).thenReturn(Optional.of(device)); when(device.getId()).thenReturn(DEVICE_ID); when(accountsManager.getByAccountIdentifier(ACCOUNT_UUID)).thenReturn(Optional.of(account)); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/websocket/AuthenticatedConnectListenerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/websocket/AuthenticatedConnectListenerTest.java index 537ea3ef9..8a3f43a5f 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/websocket/AuthenticatedConnectListenerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/websocket/AuthenticatedConnectListenerTest.java @@ -68,7 +68,7 @@ class AuthenticatedConnectListenerTest { when(device.getId()).thenReturn(DEVICE_ID); authenticatedAccount = mock(Account.class); - when(authenticatedAccount.getIdentifier(IdentityType.ACI)).thenReturn(ACCOUNT_IDENTIFIER); + when(authenticatedAccount.getAccountIdentifier()).thenReturn(ACCOUNT_IDENTIFIER); when(authenticatedAccount.getDevice(DEVICE_ID)).thenReturn(Optional.of(device)); webSocketClient = mock(WebSocketClient.class); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/websocket/WebSocketConnectionIntegrationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/websocket/WebSocketConnectionIntegrationTest.java index f7d222414..a0fac687c 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/websocket/WebSocketConnectionIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/websocket/WebSocketConnectionIntegrationTest.java @@ -50,7 +50,6 @@ import org.whispersystems.textsecuregcm.entities.MessageProtos; import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope; import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager; import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; -import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor; import org.whispersystems.textsecuregcm.metrics.MessageMetrics; import org.whispersystems.textsecuregcm.push.PushNotificationManager; @@ -120,8 +119,8 @@ class WebSocketConnectionIntegrationTest { webSocketClient = mock(WebSocketClient.class); clientReleaseManager = mock(ClientReleaseManager.class); - when(account.getNumber()).thenReturn("+18005551234"); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(UUID.randomUUID()); + when(account.getNumber()).thenReturn(Optional.of("+18005551234")); + when(account.getAccountIdentifier()).thenReturn(UUID.randomUUID()); when(device.getId()).thenReturn(Device.PRIMARY_ID); redisMessageAvailabilityManager.start(); @@ -177,14 +176,14 @@ class WebSocketConnectionIntegrationTest { expectedMessages.add(envelope); } - messagesDynamoDb.store(persistedMessages, account.getIdentifier(IdentityType.ACI), device); + messagesDynamoDb.store(persistedMessages, account.getAccountIdentifier(), device); } for (int i = 0; i < cachedMessageCount; i++) { final UUID messageGuid = UUID.randomUUID(); final MessageProtos.Envelope envelope = generateRandomMessage(messageGuid); - messagesCache.insert(messageGuid, account.getIdentifier(IdentityType.ACI), device.getId(), envelope).join(); + messagesCache.insert(messageGuid, account.getAccountIdentifier(), device.getId(), envelope).join(); expectedMessages.add(envelope); } @@ -255,14 +254,14 @@ class WebSocketConnectionIntegrationTest { expectedMessages.add(envelope); } - messagesDynamoDb.store(persistedMessages, account.getIdentifier(IdentityType.ACI), device); + messagesDynamoDb.store(persistedMessages, account.getAccountIdentifier(), device); } for (int i = 0; i < cachedMessageCount; i++) { final UUID messageGuid = UUID.randomUUID(); final MessageProtos.Envelope envelope = generateRandomMessage(messageGuid); - messagesCache.insert(messageGuid, account.getIdentifier(IdentityType.ACI), device.getId(), envelope).join(); + messagesCache.insert(messageGuid, account.getAccountIdentifier(), device.getId(), envelope).join(); expectedMessages.add(envelope); } @@ -280,7 +279,7 @@ class WebSocketConnectionIntegrationTest { final UUID messageGuid = UUID.randomUUID(); final MessageProtos.Envelope envelope = generateRandomMessage(messageGuid); - messagesCache.insert(messageGuid, account.getIdentifier(IdentityType.ACI), device.getId(), envelope).join(); + messagesCache.insert(messageGuid, account.getAccountIdentifier(), device.getId(), envelope).join(); expectedMessages.add(envelope); } }); @@ -349,13 +348,13 @@ class WebSocketConnectionIntegrationTest { expectedMessages.add(envelope); } - messagesDynamoDb.store(persistedMessages, account.getIdentifier(IdentityType.ACI), device); + messagesDynamoDb.store(persistedMessages, account.getAccountIdentifier(), device); } for (int i = 0; i < cachedMessageCount; i++) { final UUID messageGuid = UUID.randomUUID(); final MessageProtos.Envelope envelope = generateRandomMessage(messageGuid); - messagesCache.insert(messageGuid, account.getIdentifier(IdentityType.ACI), device.getId(), envelope).join(); + messagesCache.insert(messageGuid, account.getAccountIdentifier(), device.getId(), envelope).join(); expectedMessages.add(envelope); } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/websocket/WebSocketConnectionTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/websocket/WebSocketConnectionTest.java index f971033f5..a1c774881 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/websocket/WebSocketConnectionTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/websocket/WebSocketConnectionTest.java @@ -134,7 +134,7 @@ class WebSocketConnectionTest { void testSendMessages() { final UUID destinationAccountIdentifier = UUID.randomUUID(); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(destinationAccountIdentifier); + when(account.getAccountIdentifier()).thenReturn(destinationAccountIdentifier); final byte deviceId = 2; when(device.getId()).thenReturn(deviceId); @@ -152,7 +152,7 @@ class WebSocketConnectionTest { when(messageStream.acknowledgeMessage(any(), anyLong())).thenReturn(CompletableFuture.completedFuture(null)); - when(messagesManager.getMessages(account.getIdentifier(IdentityType.ACI), device)) + when(messagesManager.getMessages(account.getAccountIdentifier(), device)) .thenReturn(messageStream); when(messagesManager.mayHaveMessages(any(), any())).thenReturn(CompletableFuture.completedFuture(false)); @@ -201,7 +201,7 @@ class WebSocketConnectionTest { void testSendMessagesWithError() { final UUID destinationAccountIdentifier = UUID.randomUUID(); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(destinationAccountIdentifier); + when(account.getAccountIdentifier()).thenReturn(destinationAccountIdentifier); final byte deviceId = 2; when(device.getId()).thenReturn(deviceId); @@ -221,7 +221,7 @@ class WebSocketConnectionTest { when(messageStream.acknowledgeMessage(any(), anyLong())).thenReturn(CompletableFuture.completedFuture(null)); - when(messagesManager.getMessages(account.getIdentifier(IdentityType.ACI), device)) + when(messagesManager.getMessages(account.getAccountIdentifier(), device)) .thenReturn(messageStream); when(messagesManager.mayHaveMessages(any(), any())).thenReturn(CompletableFuture.completedFuture(false)); @@ -281,7 +281,7 @@ class WebSocketConnectionTest { void testQueueEmptySignalOrder() { final UUID destinationAccountIdentifier = UUID.randomUUID(); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(destinationAccountIdentifier); + when(account.getAccountIdentifier()).thenReturn(destinationAccountIdentifier); final byte deviceId = 2; when(device.getId()).thenReturn(deviceId); @@ -299,7 +299,7 @@ class WebSocketConnectionTest { when(messageStream.acknowledgeMessage(any(), anyLong())).thenReturn(CompletableFuture.completedFuture(null)); - when(messagesManager.getMessages(account.getIdentifier(IdentityType.ACI), device)) + when(messagesManager.getMessages(account.getAccountIdentifier(), device)) .thenReturn(messageStream); when(messagesManager.mayHaveMessages(any(), any())).thenReturn(CompletableFuture.completedFuture(false)); @@ -331,7 +331,7 @@ class WebSocketConnectionTest { void testConflictingConsumerSignalOrder() { final UUID destinationAccountIdentifier = UUID.randomUUID(); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(destinationAccountIdentifier); + when(account.getAccountIdentifier()).thenReturn(destinationAccountIdentifier); final byte deviceId = 2; when(device.getId()).thenReturn(deviceId); @@ -346,7 +346,7 @@ class WebSocketConnectionTest { when(messageStream.acknowledgeMessage(any(), anyLong())).thenReturn(CompletableFuture.completedFuture(null)); - when(messagesManager.getMessages(account.getIdentifier(IdentityType.ACI), device)) + when(messagesManager.getMessages(account.getAccountIdentifier(), device)) .thenReturn(messageStream); when(messagesManager.mayHaveMessages(any(), any())).thenReturn(CompletableFuture.completedFuture(false)); @@ -379,7 +379,7 @@ class WebSocketConnectionTest { void testSendMessagesEmptyQueue() { final UUID accountUuid = UUID.randomUUID(); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountUuid); + when(account.getAccountIdentifier()).thenReturn(accountUuid); when(device.getId()).thenReturn(Device.PRIMARY_ID); final MessageStream messageStream = mock(MessageStream.class); @@ -408,7 +408,7 @@ class WebSocketConnectionTest { void testSendMessagesConflictingConsumer() { final UUID accountUuid = UUID.randomUUID(); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountUuid); + when(account.getAccountIdentifier()).thenReturn(accountUuid); when(device.getId()).thenReturn(Device.PRIMARY_ID); final MessageStream messageStream = mock(MessageStream.class); @@ -435,7 +435,7 @@ class WebSocketConnectionTest { final UUID accountUuid = UUID.randomUUID(); when(device.getId()).thenReturn((byte) 2); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountUuid); + when(account.getAccountIdentifier()).thenReturn(accountUuid); final MessageStream messageStream = mock(MessageStream.class); @@ -466,7 +466,7 @@ class WebSocketConnectionTest { final byte deviceId = 2; when(device.getId()).thenReturn(deviceId); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountUuid); + when(account.getAccountIdentifier()).thenReturn(accountUuid); final int totalMessages = 1000; @@ -518,7 +518,7 @@ class WebSocketConnectionTest { final byte deviceId = 2; when(device.getId()).thenReturn(deviceId); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountUuid); + when(account.getAccountIdentifier()).thenReturn(accountUuid); final AtomicBoolean canceled = new AtomicBoolean(); @@ -576,7 +576,7 @@ class WebSocketConnectionTest { void testSendDeliveryReceipt(final boolean deliveryReceiptFromPni) { final UUID destinationAccountIdentifier = UUID.randomUUID(); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(destinationAccountIdentifier); + when(account.getAccountIdentifier()).thenReturn(destinationAccountIdentifier); final byte deviceId = 2; when(device.getId()).thenReturn(deviceId); @@ -597,7 +597,7 @@ class WebSocketConnectionTest { when(messageStream.acknowledgeMessage(any(), anyLong())).thenReturn(CompletableFuture.completedFuture(null)); - when(messagesManager.getMessages(account.getIdentifier(IdentityType.ACI), device)) + when(messagesManager.getMessages(account.getAccountIdentifier(), device)) .thenReturn(messageStream); when(messagesManager.mayHaveMessages(any(), any())).thenReturn(CompletableFuture.completedFuture(false)); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/workers/ClearExpiredFoundationDbMessagesCommandTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/workers/ClearExpiredFoundationDbMessagesCommandTest.java index 9bf550dc6..b18b0408d 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/workers/ClearExpiredFoundationDbMessagesCommandTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/workers/ClearExpiredFoundationDbMessagesCommandTest.java @@ -92,7 +92,7 @@ class ClearExpiredFoundationDbMessagesCommandTest { when(linkedDevice.getId()).thenReturn(linkedDeviceId); final Account account = mock(Account.class); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier); + when(account.getAccountIdentifier()).thenReturn(accountIdentifier); when(account.getDevices()).thenReturn(i % 2 == 0 ? List.of(primaryDevice) : List.of(primaryDevice, linkedDevice)); accounts.add(account); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/workers/IdleWakeupEligibilityCheckerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/workers/IdleWakeupEligibilityCheckerTest.java index c5703f146..741d2fc38 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/workers/IdleWakeupEligibilityCheckerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/workers/IdleWakeupEligibilityCheckerTest.java @@ -16,13 +16,13 @@ import java.time.Instant; import java.time.ZoneId; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.storage.Account; import org.whispersystems.textsecuregcm.storage.Device; import org.whispersystems.textsecuregcm.storage.MessagesManager; @@ -49,10 +49,10 @@ public class IdleWakeupEligibilityCheckerTest { final boolean mayHaveUrgentMessages, final boolean expectEligible) { - when(messagesManager.mayHavePersistedMessages(account.getIdentifier(IdentityType.ACI), device)) + when(messagesManager.mayHavePersistedMessages(account.getAccountIdentifier(), device)) .thenReturn(CompletableFuture.completedFuture(mayHaveMessages)); - when(messagesManager.mayHaveUrgentPersistedMessages(account.getIdentifier(IdentityType.ACI), device)) + when(messagesManager.mayHaveUrgentPersistedMessages(account.getAccountIdentifier(), device)) .thenReturn(CompletableFuture.completedFuture(mayHaveUrgentMessages)); assertEquals(expectEligible, idleChecker.isDeviceEligible(account, device).join()); @@ -62,9 +62,9 @@ public class IdleWakeupEligibilityCheckerTest { final List arguments = new ArrayList<>(); final Account account = mock(Account.class); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(UUID.randomUUID()); - when(account.getNumber()).thenReturn(PhoneNumberUtil.getInstance().format( - PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164)); + when(account.getAccountIdentifier()).thenReturn(UUID.randomUUID()); + when(account.getNumber()).thenReturn(Optional.of(PhoneNumberUtil.getInstance().format( + PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164))); { // Long-idle device with push token and messages diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/workers/NotifyIdleDevicesCommandTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/workers/NotifyIdleDevicesCommandTest.java index 9490181ed..01a2c9bed 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/workers/NotifyIdleDevicesCommandTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/workers/NotifyIdleDevicesCommandTest.java @@ -130,7 +130,7 @@ class NotifyIdleDevicesCommandTest { final Account account = mock(Account.class); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier); + when(account.getAccountIdentifier()).thenReturn(accountIdentifier); when(account.getDevices()).thenReturn(List.of(eligibleDevice, ineligibleDevice)); when(messagesManager.mayHavePersistedMessages(accountIdentifier, eligibleDevice)) diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/workers/RemoveExpiredUsernameHoldsCommandTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/workers/RemoveExpiredUsernameHoldsCommandTest.java index 8e898eca7..9948c8ae1 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/workers/RemoveExpiredUsernameHoldsCommandTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/workers/RemoveExpiredUsernameHoldsCommandTest.java @@ -81,7 +81,7 @@ class RemoveExpiredUsernameHoldsCommandTest { final UUID hasHoldsAccountIdentifier = UUID.randomUUID(); final Account hasHolds = mock(Account.class); - when(hasHolds.getIdentifier(IdentityType.ACI)).thenReturn(hasHoldsAccountIdentifier); + when(hasHolds.getAccountIdentifier()).thenReturn(hasHoldsAccountIdentifier); final List originalHolds = List.of( // expired new Account.UsernameHold(TestRandomUtil.nextBytes(32), Instant.EPOCH.getEpochSecond()), diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/workers/StartPushNotificationExperimentCommandTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/workers/StartPushNotificationExperimentCommandTest.java index 0146f6eca..1798d72ac 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/workers/StartPushNotificationExperimentCommandTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/workers/StartPushNotificationExperimentCommandTest.java @@ -127,7 +127,7 @@ class StartPushNotificationExperimentCommandTest { when(device.getId()).thenReturn(DEVICE_ID); final Account account = mock(Account.class); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(ACCOUNT_IDENTIFIER); + when(account.getAccountIdentifier()).thenReturn(ACCOUNT_IDENTIFIER); when(account.getDevices()).thenReturn(List.of(device)); assertDoesNotThrow(() -> startPushNotificationExperimentCommand.crawlAccounts(Flux.just(account))); @@ -150,7 +150,7 @@ class StartPushNotificationExperimentCommandTest { when(device.getId()).thenReturn(DEVICE_ID); final Account account = mock(Account.class); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(ACCOUNT_IDENTIFIER); + when(account.getAccountIdentifier()).thenReturn(ACCOUNT_IDENTIFIER); when(account.getDevices()).thenReturn(List.of(device)); when(pushNotificationExperimentSamples.recordInitialState(any(), anyByte(), any(), anyBoolean(), any())) @@ -169,7 +169,7 @@ class StartPushNotificationExperimentCommandTest { when(device.getId()).thenReturn(DEVICE_ID); final Account account = mock(Account.class); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(ACCOUNT_IDENTIFIER); + when(account.getAccountIdentifier()).thenReturn(ACCOUNT_IDENTIFIER); when(account.getDevices()).thenReturn(List.of(device)); when(pushNotificationExperimentSamples.recordInitialState(any(), anyByte(), any(), anyBoolean(), any())) @@ -198,7 +198,7 @@ class StartPushNotificationExperimentCommandTest { when(device.getId()).thenReturn(DEVICE_ID); final Account account = mock(Account.class); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(ACCOUNT_IDENTIFIER); + when(account.getAccountIdentifier()).thenReturn(ACCOUNT_IDENTIFIER); when(account.getDevices()).thenReturn(List.of(device)); when(experiment.applyExperimentTreatment(account, device)) diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/workers/TrimOversizedFoundationDbMessageQueuesCommandTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/workers/TrimOversizedFoundationDbMessageQueuesCommandTest.java index cd3b92639..d2ac2d0a0 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/workers/TrimOversizedFoundationDbMessageQueuesCommandTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/workers/TrimOversizedFoundationDbMessageQueuesCommandTest.java @@ -72,7 +72,7 @@ public class TrimOversizedFoundationDbMessageQueuesCommandTest { final UUID uuid = UUID.randomUUID(); final Account account = mock(Account.class); - when(account.getIdentifier(IdentityType.ACI)).thenReturn(uuid); + when(account.getAccountIdentifier()).thenReturn(uuid); when(account.getDevices()).thenReturn(List.of(device)); when(messagesManager.trimQueue(any(), any(), anyLong(), anyLong(), anyLong(), anyBoolean())).thenReturn(Mono.empty()); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/workers/UnlinkDevicesWithIdlePrimaryCommandTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/workers/UnlinkDevicesWithIdlePrimaryCommandTest.java index 9f04bd190..6df58c13b 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/workers/UnlinkDevicesWithIdlePrimaryCommandTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/workers/UnlinkDevicesWithIdlePrimaryCommandTest.java @@ -79,7 +79,7 @@ class UnlinkDevicesWithIdlePrimaryCommandTest { final Account accountWithIdlePrimaryAndNoLinkedDevice = mock(Account.class); { - when(accountWithIdlePrimaryAndNoLinkedDevice.getIdentifier(IdentityType.ACI)).thenReturn(UUID.randomUUID()); + when(accountWithIdlePrimaryAndNoLinkedDevice.getAccountIdentifier()).thenReturn(UUID.randomUUID()); final Device primaryDevice = generateMockDevice(Device.PRIMARY_ID, idleDeviceLastSeenDuration); @@ -90,7 +90,7 @@ class UnlinkDevicesWithIdlePrimaryCommandTest { final Account accountWithActivePrimaryAndLinkedDevice = mock(Account.class); { - when(accountWithActivePrimaryAndLinkedDevice.getIdentifier(IdentityType.ACI)).thenReturn(UUID.randomUUID()); + when(accountWithActivePrimaryAndLinkedDevice.getAccountIdentifier()).thenReturn(UUID.randomUUID()); final Device primaryDevice = generateMockDevice(Device.PRIMARY_ID, activeDeviceLastSeenDuration); @@ -105,7 +105,7 @@ class UnlinkDevicesWithIdlePrimaryCommandTest { final Account accountWithIdlePrimaryAndLinkedDevice = mock(Account.class); { - when(accountWithIdlePrimaryAndLinkedDevice.getIdentifier(IdentityType.ACI)).thenReturn(UUID.randomUUID()); + when(accountWithIdlePrimaryAndLinkedDevice.getAccountIdentifier()).thenReturn(UUID.randomUUID()); final Device primaryDevice = generateMockDevice(Device.PRIMARY_ID, idleDeviceLastSeenDuration); @@ -124,7 +124,7 @@ class UnlinkDevicesWithIdlePrimaryCommandTest { accountWithIdlePrimaryAndLinkedDevice)); if (!isDryRun) { - verify(accountsManager).removeDevice(accountWithIdlePrimaryAndLinkedDevice.getIdentifier(IdentityType.ACI), linkedDeviceId); + verify(accountsManager).removeDevice(accountWithIdlePrimaryAndLinkedDevice.getAccountIdentifier(), linkedDeviceId); } verifyNoMoreInteractions(accountsManager);