Scuttle deprecated phone number getters

This commit is contained in:
Jon Chambers authored and GitHub committed 2026-08-18 12:05:17 -04:00
1 parent 336e0472f6
commit 48954c9f62
117 files changed
+767 -842

No files matched your search

@@ -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) {
@@ -164,7 +164,7 @@ public class DisconnectionRequestManager extends RedisPubSubAdapter<byte[], byte
* @return a future that completes when the request has been broadcast
*/
public CompletionStage<Void> requestDisconnection(final Account account) {
return requestDisconnection(account.getIdentifier(IdentityType.ACI),
return requestDisconnection(account.getAccountIdentifier(),
account.getDevices().stream().map(Device::getId).toList());
}
@@ -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();
@@ -223,7 +223,7 @@ public class AccountController {
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
final Collection<TransactWriteItem> 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");
}
@@ -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()),
@@ -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,
@@ -113,7 +113,7 @@ public class CertificateController {
final List<GroupCredentials.CallLinkAuthCredential> callLinkAuthCredentials = new ArrayList<>();
final ServiceId.Aci aci = new ServiceId.Aci(account.getAccountIdentifier());
final Optional<ServiceId.Pni> maybePni = account.getPhoneNumberIdentifierOptional().map(ServiceId.Pni::new);
final Optional<ServiceId.Pni> maybePni = account.getPhoneNumberIdentifier().map(ServiceId.Pni::new);
for (Instant redemption : redemptionRange) {
final AuthCredentialWithPniResponse authCredentialWithPni =
@@ -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();
@@ -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<Byte> parsedTargetDeviceId = parseDeviceId(targetDeviceId);
final Optional<Integer> 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"));
};
}
}
@@ -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<Account> 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);
}
}
@@ -414,11 +414,17 @@ public class ProfileController {
final Optional<Account> maybeAccount = accountsManager.getByServiceIdentifier(identifier);
maybeAccount.ifPresent(account -> {
final IdentityKey identityKey = account.getIdentityKey(identifier.identityType());
if (identityKey == null) {
final Optional<IdentityKey> 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"))));
}
/**
@@ -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);
@@ -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());
@@ -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());
}
}
@@ -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;
}
@@ -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<TransactWriteItem> additionalWriteItems = account.getPhoneNumberIdentifierOptional()
final Collection<TransactWriteItem> 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)));
@@ -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<ServiceId.Pni> maybePni = account.getPhoneNumberIdentifierOptional().map(ServiceId.Pni::new);
final Optional<ServiceId.Pni> maybePni = account.getPhoneNumberIdentifier().map(ServiceId.Pni::new);
final GetGroupCredentialsResponse.Builder responseBuilder = GetGroupCredentialsResponse.newBuilder();
@@ -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);
@@ -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())));
}
@@ -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()))
@@ -65,14 +65,14 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
final CompletableFuture<Integer> aciEcKeyCountFuture =
keysManager.getEcCount(aci, authenticatedDevice.deviceId());
final CompletableFuture<Integer> pniEcKeyCountFuture = account.getPhoneNumberIdentifierOptional()
final CompletableFuture<Integer> pniEcKeyCountFuture = account.getPhoneNumberIdentifier()
.map(pni -> keysManager.getEcCount(pni, authenticatedDevice.deviceId()))
.orElseGet(() -> CompletableFuture.completedFuture(0));
final CompletableFuture<Integer> aciKemKeyCountFuture =
keysManager.getPqCount(aci, authenticatedDevice.deviceId());
final CompletableFuture<Integer> pniKemKeyCountFuture = account.getPhoneNumberIdentifierOptional()
final CompletableFuture<Integer> 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<Integer> 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<K> 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<UUID, K, CompletableFuture<Void>> 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"));
};
}
@@ -130,7 +130,7 @@ public class MessageDispatcher {
final Device device,
final Flux<UUID> 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<? extends MessageStreamEntry> 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,
@@ -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,
@@ -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()
@@ -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);
@@ -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<Integer> 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());
@@ -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) {
@@ -57,7 +57,11 @@ public class ReceiptSender {
final Map<Byte, Integer> 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,
@@ -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);
@@ -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<UUID> getPhoneNumberIdentifierOptional() {
public Optional<UUID> 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<String> getNumberOptional() {
public Optional<String> 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) {
@@ -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());
@@ -113,6 +113,6 @@ public class AccountLockManager {
public <V, E extends Exception> V withSingleAccountLock(Account account,
final ThrowingSupplier<V, E> 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);
}
}
@@ -217,7 +217,7 @@ public class Accounts {
boolean create(final Account account, final List<TransactWriteItem> 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<TransactWriteItem> writeItems = new ArrayList<>(
List.of(phoneNumberConstraintPut, phoneNumberIdentifierConstraintPut, accountPut, deletedAccountDelete));
@@ -379,12 +379,12 @@ public class Accounts {
final Collection<TransactWriteItem> 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<String, AttributeValue> item = te.cancellationReasons().get(updateAccountItemIndex).item();
final Optional<String> 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<TransactWriteItem> 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<String> 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<TransactWriteItem> 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<Void> regenerateConstraints(final Account account) {
final List<CompletableFuture<?>> 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);
@@ -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<String, String> implemen
try {
final List<TransactWriteItem> 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<String, String> 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<String, String> implemen
account.setAccountIdentifier(aci);
final List<TransactWriteItem> 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<String, String> 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<String, String> 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<String, String> 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<String, String> implemen
final List<TransactWriteItem> 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<String, String> 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<String, String> implemen
final List<TransactWriteItem> 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<String, String> 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<String, String> 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<String, String> implemen
final Map<Byte, KEMSignedPreKey> pniPqLastResortPreKeys,
final Map<Byte, Integer> 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<String, String> implemen
}
public Account update(final Account account, final Consumer<Account> 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<String, String> 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<String, String> implemen
cacheCluster.useCluster(connection -> {
final RedisAdvancedClusterCommands<String, String> 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<String, String> 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<String, String> implemen
private void redisDelete(final Account account) {
final List<String> 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<String, String> implemen
}
public CompletableFuture<Optional<TransferArchiveResult>> 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<String, String> implemen
final Account account = accounts.getByAccountIdentifier(accountIdentifier)
.orElseThrow(ContestedOptimisticLockException::new);
account.getPhoneNumberIdentifierOptional()
account.getPhoneNumberIdentifier()
.flatMap(phoneNumberRecoveryPasswordsManager::getPasswordAndWriteItemForMigration)
.ifPresent(passwordAndWriteItem -> {
account.setAccountRecoveryPassword(passwordAndWriteItem.first());
@@ -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<Duration> waitingPeriodRemaining = changeNumberWaitingPeriodManager.getWaitingPeriodRemaining(account.getAccountIdentifier());
if (waitingPeriodRemaining.isPresent()) {
@@ -122,7 +122,7 @@ public class ChangeNumberManager {
final Optional<Account> 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());
@@ -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.
@@ -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<Void> 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()
@@ -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())))
@@ -245,10 +245,10 @@ public class PhoneNumberIdentifiers {
}
CompletableFuture<Void> 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));
@@ -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;
@@ -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()
@@ -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) {
@@ -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);
});
@@ -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,
@@ -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 ? _ -> {}
@@ -52,8 +52,8 @@ public class DeleteUserCommand extends AbstractCommandWithDependencies {
Optional<Account> 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");
}
@@ -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);
@@ -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);
@@ -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()))
@@ -86,7 +86,7 @@ public class RemoveExpiredUsernameHoldsCommand extends AbstractSinglePassCrawlAc
final int holdsToRemove = removeExpired(holds);
final Mono<Void> 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,
@@ -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"),
@@ -92,7 +92,7 @@ public class StartPushNotificationExperimentCommand<T> 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<Boolean> recordInitialSampleMono = dryRun
@@ -131,7 +131,7 @@ public class StartPushNotificationExperimentCommand<T> 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<Void> applyTreatmentMono = dryRun
? Mono.empty()
@@ -141,7 +141,7 @@ public class StartPushNotificationExperimentCommand<T> 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);
@@ -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),
@@ -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<Account> unlinkDeviceMono = isDryRun
? Mono.empty()
@@ -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);
@@ -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);
@@ -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));
@@ -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);
@@ -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));
@@ -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(),
@@ -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());
}
}
@@ -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));
@@ -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()));
@@ -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());
@@ -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());
@@ -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);
@@ -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()))
@@ -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());
@@ -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(
@@ -187,11 +187,11 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new PniServiceIdentifier(phoneNumberIdentifier)))
.setE164(e164);
when(account.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(phoneNumberIdentifier));
when(account.getNumberOptional()).thenReturn(Optional.of(e164));
when(account.getPhoneNumberIdentifier()).thenReturn(Optional.of(phoneNumberIdentifier));
when(account.getNumber()).thenReturn(Optional.of(e164));
} else {
when(account.getPhoneNumberIdentifierOptional()).thenReturn(Optional.empty());
when(account.getNumberOptional()).thenReturn(Optional.empty());
when(account.getPhoneNumberIdentifier()).thenReturn(Optional.empty());
when(account.getNumber()).thenReturn(Optional.empty());
}
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
@@ -714,7 +714,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
when(account.getNumberOptional())
when(account.getNumber())
.thenReturn(Optional.of(PhoneNumberUtil.getInstance().format(
PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164)));
@@ -734,7 +734,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
when(account.getNumberOptional())
when(account.getNumber())
.thenReturn(Optional.empty());
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT, () ->
@@ -751,7 +751,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
final Account account = mock(Account.class);
when(account.getAccountIdentifier()).thenReturn(AUTHENTICATED_ACI);
when(account.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(phoneNumberIdentifier));
when(account.getPhoneNumberIdentifier()).thenReturn(Optional.of(phoneNumberIdentifier));
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
@@ -887,8 +887,8 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
final Account updatedAccount = mock(Account.class);
when(updatedAccount.getAccountIdentifier()).thenReturn(AUTHENTICATED_ACI);
when(updatedAccount.getNumberOptional()).thenReturn(Optional.of(newNumber));
when(updatedAccount.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(updatedPni));
when(updatedAccount.getNumber()).thenReturn(Optional.of(newNumber));
when(updatedAccount.getPhoneNumberIdentifier()).thenReturn(Optional.of(updatedPni));
when(updatedAccount.getUsernameHash()).thenReturn(Optional.empty());
when(changeNumberManager.changeNumber(eq(AUTHENTICATED_ACI), any(), any(), any(), eq(newNumber),
@@ -150,8 +150,8 @@ public class CredentialsGrpcServiceTest
@BeforeEach
void setUp() {
when(authenticatedAccount.getAccountIdentifier()).thenReturn(AUTHENTICATED_ACI);
when(authenticatedAccount.getNumberOptional()).thenReturn(Optional.of(PHONE_NUMBER));
when(authenticatedAccount.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(AUTHENTICATED_PNI));
when(authenticatedAccount.getNumber()).thenReturn(Optional.of(PHONE_NUMBER));
when(authenticatedAccount.getPhoneNumberIdentifier()).thenReturn(Optional.of(AUTHENTICATED_PNI));
when(authenticatedAccount.getAccountIdentityKey())
.thenReturn(new IdentityKey(IDENTITY_KEY_PAIR.getPublicKey()));
@@ -292,7 +292,7 @@ public class CredentialsGrpcServiceTest
@Test
void getDeliveryCertificateAccountHasNoNumber() throws InvalidProtocolBufferException, InvalidKeyException {
when(authenticatedAccount.getNumberOptional()).thenReturn(Optional.empty());
when(authenticatedAccount.getNumber()).thenReturn(Optional.empty());
final GetDeliveryCertificateResponse response =
authenticatedServiceStub().getDeliveryCertificate(GetDeliveryCertificateRequest.getDefaultInstance());
@@ -312,7 +312,7 @@ public class CredentialsGrpcServiceTest
when(account.getAccountIdentifier()).thenReturn(AUTHENTICATED_ACI);
when(account.getAccountIdentityKey())
.thenReturn(new IdentityKey(IDENTITY_KEY_PAIR.getPublicKey()));
when(account.getPhoneNumberIdentifierOptional()).thenReturn(
when(account.getPhoneNumberIdentifier()).thenReturn(
Optional.ofNullable(accountHasPhoneNumber ? AUTHENTICATED_PNI : null));
final byte[] authCredentialSalt;
@@ -67,7 +67,7 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
@Override
protected DevicesGrpcService createServiceBeforeEachTest() {
when(authenticatedAccount.getAccountIdentifier()).thenReturn(AUTHENTICATED_ACI);
when(authenticatedAccount.getIdentifier(IdentityType.ACI)).thenReturn(AUTHENTICATED_ACI);
when(authenticatedAccount.getAccountIdentifier()).thenReturn(AUTHENTICATED_ACI);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(authenticatedAccount));
@@ -95,7 +95,7 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
when(primaryDevice.getId()).thenReturn(Device.PRIMARY_ID);
when(primaryDevice.getCreated()).thenReturn(primaryDeviceCreated.toEpochMilli());
when(primaryDevice.getLastSeen()).thenReturn(primaryDeviceLastSeen.toEpochMilli());
when(primaryDevice.getRegistrationId(IdentityType.ACI)).thenReturn(primaryRegistrationId);
when(primaryDevice.getAccountRegistrationId()).thenReturn(primaryRegistrationId);
when(primaryDevice.getCreatedAtCiphertext()).thenReturn(primaryCreatedAtCiphertext);
final String linkedDeviceName = "A linked device";
@@ -105,7 +105,7 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
when(linkedDevice.getCreated()).thenReturn(linkedDeviceCreated.toEpochMilli());
when(linkedDevice.getLastSeen()).thenReturn(linkedDeviceLastSeen.toEpochMilli());
when(linkedDevice.getName()).thenReturn(linkedDeviceName.getBytes(StandardCharsets.UTF_8));
when(linkedDevice.getRegistrationId(IdentityType.ACI)).thenReturn(linkedRegistrationId);
when(linkedDevice.getAccountRegistrationId()).thenReturn(linkedRegistrationId);
when(linkedDevice.getCreatedAtCiphertext()).thenReturn(linkedCreatedAtCiphertext);
when(authenticatedAccount.getDevices()).thenReturn(List.of(primaryDevice, linkedDevice));
@@ -61,7 +61,6 @@ import org.whispersystems.textsecuregcm.entities.ECPreKey;
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.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
@@ -107,8 +106,8 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
when(targetAccount.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(targetAccount.getIdentifier(IdentityType.ACI)).thenReturn(uuid);
when(targetAccount.getIdentityKey(IdentityType.ACI)).thenReturn(identityKey);
when(targetAccount.getAccountIdentifier()).thenReturn(uuid);
when(targetAccount.getAccountIdentityKey()).thenReturn(identityKey);
when(accountsManager.getByServiceIdentifier(identifier))
.thenReturn(Optional.of(targetAccount));
@@ -156,8 +155,8 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
when(targetAccount.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(targetAccount.getIdentifier(IdentityType.ACI)).thenReturn(uuid);
when(targetAccount.getIdentityKey(IdentityType.ACI)).thenReturn(identityKey);
when(targetAccount.getAccountIdentifier()).thenReturn(uuid);
when(targetAccount.getAccountIdentityKey()).thenReturn(identityKey);
when(accountsManager.getByServiceIdentifier(identifier))
.thenReturn(Optional.of(targetAccount));
@@ -211,8 +210,8 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
when(targetAccount.isUnrestrictedUnidentifiedAccess()).thenReturn(true);
when(targetAccount.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(targetAccount.getIdentifier(IdentityType.ACI)).thenReturn(uuid);
when(targetAccount.getIdentityKey(IdentityType.ACI)).thenReturn(identityKey);
when(targetAccount.getAccountIdentifier()).thenReturn(uuid);
when(targetAccount.getAccountIdentityKey()).thenReturn(identityKey);
when(accountsManager.getByServiceIdentifier(identifier))
.thenReturn(Optional.of(targetAccount));
@@ -382,7 +381,7 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
final Account targetAccount = mock(Account.class);
when(targetAccount.getAccountIdentifier()).thenReturn(accountIdentifier);
when(targetAccount.getIdentityKey(IdentityType.ACI)).thenReturn(new IdentityKey(ECKeyPair.generate().getPublicKey()));
when(targetAccount.getAccountIdentityKey()).thenReturn(new IdentityKey(ECKeyPair.generate().getPublicKey()));
when(targetAccount.getDevices()).thenReturn(Collections.emptyList());
when(targetAccount.getDevice(anyByte())).thenReturn(Optional.empty());
when(targetAccount.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
@@ -425,15 +424,15 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
// Complete futures asynchronously to catch potential async/context-propagation issues
final Duration futureDelay = Duration.ofMillis(1);
when(mismatchedAciFingerprintAccount.getIdentityKey(IdentityType.ACI)).thenReturn(mismatchedAciFingerprintAccountIdentityKey);
when(mismatchedAciFingerprintAccount.getAccountIdentityKey()).thenReturn(mismatchedAciFingerprintAccountIdentityKey);
when(accountsManager.getByServiceIdentifierAsync(new AciServiceIdentifier(mismatchedAciFingerprintAccountIdentifier)))
.thenReturn(delayedAccount(mismatchedAciFingerprintAccount));
when(matchingAciFingerprintAccount.getIdentityKey(IdentityType.ACI)).thenReturn(matchingAciFingerprintAccountIdentityKey);
when(matchingAciFingerprintAccount.getAccountIdentityKey()).thenReturn(matchingAciFingerprintAccountIdentityKey);
when(accountsManager.getByServiceIdentifierAsync(new AciServiceIdentifier(matchingAciFingerprintAccountIdentifier)))
.thenReturn(delayedAccount(matchingAciFingerprintAccount));
when(mismatchedPniFingerprintAccount.getIdentityKey(IdentityType.PNI)).thenReturn(mismatchedPniFingerpringAccountIdentityKey);
when(mismatchedPniFingerprintAccount.getPhoneNumberIdentityKey()).thenReturn(Optional.of(mismatchedPniFingerpringAccountIdentityKey));
when(accountsManager.getByServiceIdentifierAsync(new PniServiceIdentifier(mismatchedPniFingerprintAccountIdentifier)))
.thenReturn(delayedAccount(mismatchedPniFingerprintAccount));
@@ -15,7 +15,6 @@ import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
@@ -115,12 +114,10 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest<KeysGrpcService, KeysGrpc.K
authenticatedAccount = mock(Account.class);
when(authenticatedAccount.getAccountIdentifier()).thenReturn(AUTHENTICATED_ACI);
when(authenticatedAccount.getPhoneNumberIdentifierOptional()).thenReturn(Optional.of(AUTHENTICATED_PNI));
when(authenticatedAccount.getPhoneNumberIdentifier()).thenThrow(new UnsupportedOperationException());
when(authenticatedAccount.getIdentifier(any())).thenThrow(new UnsupportedOperationException());
when(authenticatedAccount.getPhoneNumberIdentifier()).thenReturn(Optional.of(AUTHENTICATED_PNI));
when(authenticatedAccount.getIdentityKey(IdentityType.ACI)).thenReturn(new IdentityKey(ACI_IDENTITY_KEY_PAIR.getPublicKey()));
when(authenticatedAccount.getIdentityKey(IdentityType.PNI)).thenReturn(new IdentityKey(PNI_IDENTITY_KEY_PAIR.getPublicKey()));
when(authenticatedAccount.getAccountIdentityKey()).thenReturn(new IdentityKey(ACI_IDENTITY_KEY_PAIR.getPublicKey()));
when(authenticatedAccount.getPhoneNumberIdentityKey()).thenReturn(Optional.of(new IdentityKey(PNI_IDENTITY_KEY_PAIR.getPublicKey())));
when(authenticatedAccount.getDevice(AUTHENTICATED_DEVICE_ID)).thenReturn(Optional.of(authenticatedDevice));
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI)).thenReturn(Optional.of(authenticatedAccount));
@@ -157,7 +154,7 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest<KeysGrpcService, KeysGrpc.K
@Test
void getPreKeyCountWithoutPhoneNumber() {
when(authenticatedAccount.getPhoneNumberIdentifierOptional()).thenReturn(Optional.empty());
when(authenticatedAccount.getPhoneNumberIdentifier()).thenReturn(Optional.empty());
when(keysManager.getEcCount(AUTHENTICATED_ACI, AUTHENTICATED_DEVICE_ID))
.thenReturn(CompletableFuture.completedFuture(1));
@@ -180,7 +177,7 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest<KeysGrpcService, KeysGrpc.K
@ParameterizedTest
@MethodSource
void setPreKeysWithoutPhoneNumber(final Function<KeysGrpc.KeysBlockingStub, Object> 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<KeysGrpcService, KeysGrpc.K
};
when(targetAccount.getAccountIdentifier()).thenReturn(UUID.randomUUID());
when(targetAccount.getIdentifier(identityType)).thenReturn(identifier);
when(targetAccount.getIdentityKey(identityType)).thenReturn(identityKey);
switch (identityType) {
case ACI -> {
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<KeysGrpcService, KeysGrpc.K
final Device device = mock(Device.class);
when(device.getId()).thenReturn(entry.getKey());
when(device.getRegistrationId(any())).thenReturn(entry.getValue());
switch (identityType) {
case ACI -> 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<KeysGrpcService, KeysGrpc.K
final Account targetAccount = mock(Account.class);
when(targetAccount.getAccountIdentifier()).thenReturn(accountIdentifier);
when(targetAccount.getIdentityKey(IdentityType.ACI)).thenReturn(new IdentityKey(ECKeyPair.generate().getPublicKey()));
when(targetAccount.getAccountIdentityKey()).thenReturn(new IdentityKey(ECKeyPair.generate().getPublicKey()));
when(targetAccount.getDevices()).thenReturn(Collections.emptyList());
when(targetAccount.getDevice(anyByte())).thenReturn(Optional.empty());
@@ -701,11 +712,11 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest<KeysGrpcService, KeysGrpc.K
if (!targetMissing) {
final Device mockDevice = mock(Device.class);
when(mockDevice.getRegistrationId(IdentityType.ACI)).thenReturn(registrationId);
when(mockDevice.getAccountRegistrationId()).thenReturn(registrationId);
final Account targetAccount = mock(Account.class);
when(targetAccount.getAccountIdentifier()).thenReturn(targetAccountId);
when(targetAccount.getIdentityKey(IdentityType.ACI)).thenReturn(new IdentityKey(ECKeyPair.generate().getPublicKey()));
when(targetAccount.getAccountIdentityKey()).thenReturn(new IdentityKey(ECKeyPair.generate().getPublicKey()));
when(targetAccount.getDevice(targetDeviceId)).thenReturn(Optional.of(mockDevice));
when(targetAccount.getDevices()).thenReturn(List.of(mockDevice));
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetAccountId)))
@@ -754,8 +765,18 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest<KeysGrpcService, KeysGrpc.K
};
when(targetAccount.getAccountIdentifier()).thenReturn(UUID.randomUUID());
when(targetAccount.getIdentifier(identityType)).thenReturn(identifier);
when(targetAccount.getIdentityKey(identityType)).thenReturn(identityKey);
switch (identityType) {
case ACI -> {
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<KeysGrpcService, KeysGrpc.K
final Device device = mock(Device.class);
when(device.getId()).thenReturn(deviceId1);
when(device.getRegistrationId(any())).thenReturn(registrationId);
switch (identityType) {
case ACI -> when(device.getAccountRegistrationId()).thenReturn(registrationId);
case PNI -> when(device.getPhoneNumberIdentityRegistrationId()).thenReturn(Optional.of(registrationId));
}
final Map<Byte, Device> devices = Map.of(deviceId1, device);
when(targetAccount.getDevice(deviceId1)).thenReturn(Optional.of(device));
@@ -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<Envelope> 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;
@@ -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);
@@ -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));
@@ -161,18 +161,18 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
.thenReturn(new SpamCheckResult<>(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));
@@ -184,7 +184,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
when(account.getCurrentProfileVersion()).thenReturn(Optional.ofNullable(accountVersion));
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
when(account.getIdentityKey(org.whispersystems.textsecuregcm.identity.IdentityType.ACI)).thenReturn(identityKey);
when(account.getAccountIdentityKey()).thenReturn(identityKey);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(account.getBadges()).thenReturn(Collections.emptyList());
@@ -262,7 +262,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(true);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
when(account.getIdentityKey(org.whispersystems.textsecuregcm.identity.IdentityType.ACI)).thenReturn(identityKey);
when(account.getAccountIdentityKey()).thenReturn(identityKey);
when(account.getBadges()).thenReturn(Collections.emptyList());
when(profileBadgeConverter.visibleBadgeIds(anyList())).thenReturn(badgeIds);
@@ -318,7 +318,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(true);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
when(account.getIdentityKey(org.whispersystems.textsecuregcm.identity.IdentityType.ACI)).thenReturn(identityKey);
when(account.getAccountIdentityKey()).thenReturn(identityKey);
when(account.getBadges()).thenReturn(Collections.emptyList());
when(profileBadgeConverter.visibleBadgeIds(anyList())).thenReturn(badgeIds);
@@ -185,7 +185,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
when(dynamicConfiguration.getPaymentsConfiguration()).thenReturn(dynamicPaymentsConfiguration);
when(account.getAccountIdentifier()).thenReturn(AUTHENTICATED_ACI);
when(account.getNumberOptional()).thenReturn(Optional.of(phoneNumber));
when(account.getNumber()).thenReturn(Optional.of(phoneNumber));
when(account.getBadges()).thenReturn(Collections.emptyList());
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
@@ -514,7 +514,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
.build();
final String disallowedCountryCode = String.format("+%d", disallowedPhoneNumber.getCountryCode());
when(dynamicPaymentsConfiguration.disallowedPrefixes()).thenReturn(List.of(disallowedCountryCode));
when(account.getNumberOptional()).thenReturn(Optional.of(PhoneNumberUtil.getInstance().format(
when(account.getNumber()).thenReturn(Optional.of(PhoneNumberUtil.getInstance().format(
disallowedPhoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164)));
when(profilesManager.getV1(any(), anyString())).thenReturn(Optional.of(profile));
@@ -633,7 +633,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
when(profilesManager.getV1(any(), any())).thenReturn(profile);
when(account.getIdentityKey(org.whispersystems.textsecuregcm.identity.IdentityType.ACI)).thenReturn(identityKey);
when(account.getAccountIdentityKey()).thenReturn(identityKey);
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(true);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(account.getBadges()).thenReturn(Collections.emptyList());
@@ -689,7 +689,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
when(account.getAccountIdentifier()).thenReturn(targetAci);
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version));
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
when(account.getIdentityKey(org.whispersystems.textsecuregcm.identity.IdentityType.ACI)).thenReturn(identityKey);
when(account.getAccountIdentityKey()).thenReturn(identityKey);
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(true);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(account.getBadges()).thenReturn(Collections.emptyList());
@@ -743,7 +743,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetAci))).thenReturn(Optional.of(account));
when(account.getIdentityKey(org.whispersystems.textsecuregcm.identity.IdentityType.ACI)).thenReturn(identityKey);
when(account.getAccountIdentityKey()).thenReturn(identityKey);
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(true);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(account.getBadges()).thenReturn(Collections.emptyList());
@@ -83,7 +83,7 @@ class RateLimitChallengeManagerTest {
void answerCaptchaChallenge(Optional<Float> 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()))
@@ -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);
@@ -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);
@@ -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(
@@ -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);
@@ -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);
@@ -54,28 +54,28 @@ class AccountChangeValidatorTest {
private static Stream<Arguments> 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(
@@ -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());
@@ -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(
@@ -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);
}
@@ -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<Byte, ECSignedPreKey> preKeys = Map.of(Device.PRIMARY_ID, rotatedSignedPreKey);
@@ -261,16 +261,16 @@ class AccountsManagerChangeNumberIntegrationTest {
final Map<Byte, Integer> 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());
}
}
@@ -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())
);
@@ -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);
@@ -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);
@@ -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> 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> 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<UUID> maybePni = account.getPhoneNumberIdentifierOptional();
final Optional<UUID> 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<byte[]> 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<byte[]> 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)));
}
}
@@ -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<String, AttributeValue> 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<String, AttributeValue> 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<Account> 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<Account> 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<String, AttributeValue> 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<String, AttributeValue> 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<String, AttributeValue> 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<String, AttributeValue> 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<UUID> 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<UUID> 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());
@@ -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<Account, Device> 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<Account, Device> 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<Account, Device> 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<Account, Device> 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<Optional<DeviceInfo>> displacedFuture = accountsManager.waitForNewLinkedDevice(
@@ -396,7 +395,7 @@ public class AddRemoveDeviceIntegrationTest {
assertEquals(Optional.empty(), displacedFuture.join());
final Pair<Account, Device> 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<Account, Device> 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",
@@ -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);
@@ -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)));
@@ -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)));
Loaded 100 of 117 files, more files were not shown because too many files have changed in this diff. Show more