mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-11-30 01:16:50 +00:00
Always use fresh, non-cached Account instances when changing numbers
This commit is contained in:
1 parent
3790b53496
commit
3e19b415b6
10 files changed
+351
-212
No files matched your search
@@ -766,8 +766,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
PushChallengeManager pushChallengeManager = new PushChallengeManager(pushNotificationManager,
|
||||
pushChallengeDynamoDb);
|
||||
|
||||
ChangeNumberManager changeNumberManager = new ChangeNumberManager(messageSender, accountsManager, Clock.systemUTC());
|
||||
|
||||
HttpClient currencyClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2).connectTimeout(Duration.ofSeconds(10)).build();
|
||||
FixerClient fixerClient = config.getPaymentsServiceConfiguration().externalClients()
|
||||
.buildFixerClient(currencyClient);
|
||||
@@ -1090,11 +1088,14 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
final PhoneVerificationTokenManager phoneVerificationTokenManager = new PhoneVerificationTokenManager(
|
||||
phoneNumberIdentifiers, registrationServiceClient, registrationRecoveryPasswordsManager, registrationRecoveryChecker);
|
||||
|
||||
final ChangeNumberManager changeNumberManager = new ChangeNumberManager(messageSender, accountsManager,
|
||||
phoneVerificationTokenManager, registrationLockVerificationManager, rateLimiters, Clock.systemUTC());
|
||||
|
||||
final List<Object> commonControllers = Lists.newArrayList(
|
||||
new AccountController(accountsManager, rateLimiters, registrationRecoveryPasswordsManager,
|
||||
usernameHashZkProofVerifier),
|
||||
new AccountControllerV2(accountsManager, changeNumberManager, phoneVerificationTokenManager,
|
||||
registrationLockVerificationManager, rateLimiters),
|
||||
new AccountControllerV2(accountsManager, changeNumberManager),
|
||||
new AttachmentControllerV4(rateLimiters, gcsAttachmentGenerator, tusAttachmentGenerator,
|
||||
experimentEnrollmentManager, config.getAttachments().maxUploadSizeInBytes()),
|
||||
new ArchiveController(accountsManager, backupAuthManager, backupManager, backupMetrics, config.getAttachments().maxUploadSizeInBytes()),
|
||||
|
||||
+19
-7
@@ -27,6 +27,7 @@ import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
|
||||
import org.whispersystems.textsecuregcm.spam.RegistrationRecoveryChecker;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
public class PhoneVerificationTokenManager {
|
||||
|
||||
@@ -56,8 +57,10 @@ public class PhoneVerificationTokenManager {
|
||||
*
|
||||
* @param requestContext the container request context
|
||||
* @param number the e164 presented for verification
|
||||
* @param request the request with exactly one verification token (RegistrationService sessionId or registration
|
||||
* recovery password)
|
||||
* @param sessionId a verification session ID; exactly one of {@code sessionId} or {@code recoveryPassword} must be
|
||||
* non-null
|
||||
* @param recoveryPassword a registration recovery password; exactly one of {@code sessionId} or
|
||||
* {@code recoveryPassword} must be non-null
|
||||
* @return if verification was successful, returns the verification type
|
||||
* @throws BadRequestException if the number does not match the sessionId’s number, or the remote service rejects
|
||||
* the session ID as invalid
|
||||
@@ -65,13 +68,22 @@ public class PhoneVerificationTokenManager {
|
||||
* @throws ForbiddenException if the recovery password is not valid
|
||||
* @throws InterruptedException if verification did not complete before a timeout
|
||||
*/
|
||||
public PhoneVerificationRequest.VerificationType verify(final ContainerRequestContext requestContext, final String number, final PhoneVerificationRequest request)
|
||||
throws InterruptedException {
|
||||
public PhoneVerificationRequest.VerificationType verify(final ContainerRequestContext requestContext,
|
||||
final String number,
|
||||
@Nullable final byte[] sessionId,
|
||||
@Nullable final byte[] recoveryPassword) throws InterruptedException {
|
||||
|
||||
if ((sessionId == null) == (recoveryPassword == null)) {
|
||||
throw new IllegalArgumentException("Exactly one of session ID or recovery password must non-null");
|
||||
}
|
||||
|
||||
final PhoneVerificationRequest.VerificationType verificationType = sessionId != null
|
||||
? PhoneVerificationRequest.VerificationType.SESSION
|
||||
: PhoneVerificationRequest.VerificationType.RECOVERY_PASSWORD;
|
||||
|
||||
final PhoneVerificationRequest.VerificationType verificationType = request.verificationType();
|
||||
switch (verificationType) {
|
||||
case SESSION -> verifyBySessionId(number, request.decodeSessionId());
|
||||
case RECOVERY_PASSWORD -> verifyByRecoveryPassword(requestContext, number, request.recoveryPassword());
|
||||
case SESSION -> verifyBySessionId(number, sessionId);
|
||||
case RECOVERY_PASSWORD -> verifyByRecoveryPassword(requestContext, number, recoveryPassword);
|
||||
}
|
||||
|
||||
return verificationType;
|
||||
|
||||
+9
-55
@@ -5,13 +5,8 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.headers.Header;
|
||||
import io.swagger.v3.oas.annotations.media.Content;
|
||||
@@ -33,22 +28,16 @@ import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.ChangesPhoneNumber;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountDataReportResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ChangeNumberRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.MismatchedDevicesResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneNumberDiscoverabilityRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
|
||||
import org.whispersystems.textsecuregcm.entities.StaleDevicesResponse;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
@@ -59,26 +48,14 @@ import org.whispersystems.textsecuregcm.storage.Device;
|
||||
@io.swagger.v3.oas.annotations.tags.Tag(name = "Account")
|
||||
public class AccountControllerV2 {
|
||||
|
||||
private static final String CHANGE_NUMBER_COUNTER_NAME = name(AccountControllerV2.class, "changeNumber");
|
||||
private static final String VERIFICATION_TYPE_TAG_NAME = "verification";
|
||||
|
||||
private final AccountsManager accountsManager;
|
||||
private final ChangeNumberManager changeNumberManager;
|
||||
private final PhoneVerificationTokenManager phoneVerificationTokenManager;
|
||||
private final RegistrationLockVerificationManager registrationLockVerificationManager;
|
||||
private final RateLimiters rateLimiters;
|
||||
|
||||
public AccountControllerV2(final AccountsManager accountsManager,
|
||||
final ChangeNumberManager changeNumberManager,
|
||||
final PhoneVerificationTokenManager phoneVerificationTokenManager,
|
||||
final RegistrationLockVerificationManager registrationLockVerificationManager,
|
||||
final RateLimiters rateLimiters) {
|
||||
final ChangeNumberManager changeNumberManager) {
|
||||
|
||||
this.accountsManager = accountsManager;
|
||||
this.changeNumberManager = changeNumberManager;
|
||||
this.phoneVerificationTokenManager = phoneVerificationTokenManager;
|
||||
this.registrationLockVerificationManager = registrationLockVerificationManager;
|
||||
this.rateLimiters = rateLimiters;
|
||||
}
|
||||
|
||||
@PUT
|
||||
@@ -111,45 +88,22 @@ public class AccountControllerV2 {
|
||||
throw new WebApplicationException("Invalid signature", 422);
|
||||
}
|
||||
|
||||
final String number = request.number();
|
||||
|
||||
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
|
||||
|
||||
// Only verify and check reglock if there's a data change to be made...
|
||||
if (!account.getNumber().equals(number)) {
|
||||
|
||||
rateLimiters.getRegistrationLimiter().validate(number);
|
||||
|
||||
final PhoneVerificationRequest.VerificationType verificationType = phoneVerificationTokenManager.verify(
|
||||
requestContext, number, request);
|
||||
|
||||
final Optional<Account> existingAccount = accountsManager.getByE164(number);
|
||||
|
||||
if (existingAccount.isPresent()) {
|
||||
registrationLockVerificationManager.verifyRegistrationLock(existingAccount.get(), request.registrationLock(),
|
||||
userAgentString, RegistrationLockVerificationManager.Flow.CHANGE_NUMBER, verificationType);
|
||||
}
|
||||
|
||||
Metrics.counter(CHANGE_NUMBER_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgentString),
|
||||
Tag.of(VERIFICATION_TYPE_TAG_NAME, verificationType.name())))
|
||||
.increment();
|
||||
}
|
||||
|
||||
// ...but always attempt to make the change in case a client retries and needs to re-send messages
|
||||
try {
|
||||
final Account updatedAccount = changeNumberManager.changeNumber(
|
||||
account,
|
||||
authenticatedDevice.accountIdentifier(),
|
||||
request.decodeSessionId(),
|
||||
request.recoveryPassword(),
|
||||
request.registrationLock(),
|
||||
request.number(),
|
||||
request.pniIdentityKey(),
|
||||
request.devicePniSignedPrekeys(),
|
||||
request.devicePniPqLastResortPrekeys(),
|
||||
request.deviceMessages(),
|
||||
request.pniRegistrationIds(),
|
||||
userAgentString);
|
||||
requestContext);
|
||||
|
||||
return AccountIdentityResponseBuilder.fromAccount(updatedAccount);
|
||||
} catch (MismatchedDevicesException e) {
|
||||
} catch (final MismatchedDevicesException e) {
|
||||
if (!e.getMismatchedDevices().staleDeviceIds().isEmpty()) {
|
||||
throw new WebApplicationException(Response.status(410)
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
@@ -162,9 +116,9 @@ public class AccountControllerV2 {
|
||||
e.getMismatchedDevices().extraDeviceIds()))
|
||||
.build());
|
||||
}
|
||||
} catch (IllegalArgumentException e) {
|
||||
} catch (final IllegalArgumentException e) {
|
||||
throw new BadRequestException(e);
|
||||
} catch (MessageTooLargeException e) {
|
||||
} catch (final MessageTooLargeException e) {
|
||||
throw new WebApplicationException(Response.Status.REQUEST_ENTITY_TOO_LARGE);
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -134,7 +134,7 @@ public class RegistrationController {
|
||||
rateLimiters.getRegistrationLimiter().validate(number);
|
||||
|
||||
final PhoneVerificationRequest.VerificationType verificationType =
|
||||
phoneVerificationTokenManager.verify(requestContext, number, registrationRequest);
|
||||
phoneVerificationTokenManager.verify(requestContext, number, registrationRequest.decodeSessionId(), registrationRequest.recoveryPassword());
|
||||
|
||||
// There can be at most one existing account for a set of numbers in the same equivalence class, so it's sufficient
|
||||
// to find the first one.
|
||||
|
||||
@@ -1098,6 +1098,22 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
);
|
||||
}
|
||||
|
||||
/// Returns a fresh, uncached copy of the identified account (the account preparing to change its number) and a fresh,
|
||||
/// uncached copy of the account that holds the target phone number if such an account exists.
|
||||
///
|
||||
/// @param accountIdentifier the identifier for the account changing its phone number
|
||||
/// @param targetNumber the new phone number for the identified account
|
||||
///
|
||||
/// @return a fresh, uncached copy of the identified account and a fresh, uncached copy of the account that has
|
||||
/// `targetNumber` if one exists
|
||||
///
|
||||
/// @throws IllegalArgumentException if no account was found for `accountIdentifier`
|
||||
Pair<Account, Optional<Account>> getAccountsForChangeNumber(final UUID accountIdentifier, final String targetNumber) {
|
||||
return new Pair<>(accounts.getByAccountIdentifier(accountIdentifier)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier)),
|
||||
accounts.getByE164(targetNumber));
|
||||
}
|
||||
|
||||
public UUID getPhoneNumberIdentifier(String e164) {
|
||||
return phoneNumberIdentifiers.getPhoneNumberIdentifier(e164).join();
|
||||
}
|
||||
|
||||
+66
-5
@@ -8,47 +8,108 @@ import java.time.Clock;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
import org.whispersystems.textsecuregcm.controllers.AccountControllerV2;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.IncomingMessage;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.MessageSender;
|
||||
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
public class ChangeNumberManager {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ChangeNumberManager.class);
|
||||
private final MessageSender messageSender;
|
||||
private final AccountsManager accountsManager;
|
||||
private final PhoneVerificationTokenManager phoneVerificationTokenManager;
|
||||
private final RegistrationLockVerificationManager registrationLockVerificationManager;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final Clock clock;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ChangeNumberManager.class);
|
||||
|
||||
// Note that this counter name references another class deliberately in the interest of metric continuity
|
||||
private static final String CHANGE_NUMBER_COUNTER_NAME = name(AccountControllerV2.class, "changeNumber");
|
||||
private static final String VERIFICATION_TYPE_TAG_NAME = "verification";
|
||||
|
||||
public ChangeNumberManager(
|
||||
final MessageSender messageSender,
|
||||
final AccountsManager accountsManager,
|
||||
final PhoneVerificationTokenManager phoneVerificationTokenManager,
|
||||
final RegistrationLockVerificationManager registrationLockVerificationManager,
|
||||
final RateLimiters rateLimiters,
|
||||
final Clock clock) {
|
||||
|
||||
this.messageSender = messageSender;
|
||||
this.accountsManager = accountsManager;
|
||||
this.phoneVerificationTokenManager = phoneVerificationTokenManager;
|
||||
this.registrationLockVerificationManager = registrationLockVerificationManager;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
public Account changeNumber(final Account account,
|
||||
public Account changeNumber(final UUID accountIdentifier,
|
||||
@Nullable final byte[] sessionId,
|
||||
@Nullable final byte[] recoveryPassword,
|
||||
@Nullable final String registrationLock,
|
||||
final String number,
|
||||
final IdentityKey pniIdentityKey,
|
||||
final Map<Byte, ECSignedPreKey> deviceSignedPreKeys,
|
||||
final Map<Byte, KEMSignedPreKey> devicePqLastResortPreKeys,
|
||||
final List<IncomingMessage> deviceMessages,
|
||||
final Map<Byte, Integer> pniRegistrationIds,
|
||||
final String senderUserAgent)
|
||||
throws InterruptedException, MismatchedDevicesException, MessageTooLargeException {
|
||||
final ContainerRequestContext containerRequestContext)
|
||||
throws InterruptedException, MismatchedDevicesException, MessageTooLargeException, RateLimitExceededException {
|
||||
|
||||
final String senderUserAgent = containerRequestContext.getHeaderString(HttpHeaders.USER_AGENT);
|
||||
|
||||
final Pair<Account, Optional<Account>> accountAndMaybeExistingAccount =
|
||||
accountsManager.getAccountsForChangeNumber(accountIdentifier, number);
|
||||
|
||||
final Account account = accountAndMaybeExistingAccount.first();
|
||||
|
||||
// Only verify and check reglock if there's a data change to be made...
|
||||
if (!account.getNumber().equals(number)) {
|
||||
rateLimiters.getRegistrationLimiter().validate(number);
|
||||
|
||||
final PhoneVerificationRequest.VerificationType verificationType =
|
||||
phoneVerificationTokenManager.verify(containerRequestContext, number, sessionId, recoveryPassword);
|
||||
|
||||
final Optional<Account> existingAccount = accountAndMaybeExistingAccount.second();
|
||||
|
||||
if (existingAccount.isPresent()) {
|
||||
registrationLockVerificationManager.verifyRegistrationLock(existingAccount.get(), registrationLock,
|
||||
senderUserAgent, RegistrationLockVerificationManager.Flow.CHANGE_NUMBER, verificationType);
|
||||
}
|
||||
|
||||
Metrics.counter(CHANGE_NUMBER_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(senderUserAgent),
|
||||
Tag.of(VERIFICATION_TYPE_TAG_NAME, verificationType.name())))
|
||||
.increment();
|
||||
}
|
||||
|
||||
// ...but always attempt to make the change in case a client retries and needs to re-send messages
|
||||
final long serverTimestamp = clock.millis();
|
||||
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(account.getIdentifier(IdentityType.ACI));
|
||||
|
||||
@@ -86,7 +147,7 @@ public class ChangeNumberManager {
|
||||
// Now that we've actually updated the account, populate the "updated PNI" field on all envelopes
|
||||
final String updatedPniString = updatedAccount.getIdentifier(IdentityType.PNI).toString();
|
||||
|
||||
messagesByDeviceId.replaceAll((deviceId, envelope) ->
|
||||
messagesByDeviceId.replaceAll((_, envelope) ->
|
||||
envelope.toBuilder().setUpdatedPni(updatedPniString).build());
|
||||
|
||||
messageSender.sendMessages(updatedAccount,
|
||||
|
||||
+18
-20
@@ -20,7 +20,6 @@ import jakarta.ws.rs.ForbiddenException;
|
||||
import jakarta.ws.rs.NotAuthorizedException;
|
||||
import jakarta.ws.rs.ServerErrorException;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
@@ -54,16 +53,6 @@ class PhoneVerificationTokenManagerTest {
|
||||
|
||||
private static final UUID PHONE_NUMBER_IDENTIFIER = UUID.randomUUID();
|
||||
|
||||
record PhoneVerificationRequest(String sessionId, byte[] recoveryPassword) implements org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest {
|
||||
static PhoneVerificationRequest forSessionId(final byte[] sessionId) {
|
||||
return new PhoneVerificationRequest(Base64.getUrlEncoder().encodeToString(sessionId), null);
|
||||
}
|
||||
|
||||
static PhoneVerificationRequest forRecoveryPassword(final byte[] recoveryPassword) {
|
||||
return new PhoneVerificationRequest(null, recoveryPassword);
|
||||
}
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers = mock(PhoneNumberIdentifiers.class);
|
||||
@@ -93,7 +82,8 @@ class PhoneVerificationTokenManagerTest {
|
||||
|
||||
assertDoesNotThrow(() -> phoneVerificationTokenManager.verify(mock(ContainerRequestContext.class),
|
||||
PHONE_NUMBER,
|
||||
PhoneVerificationRequest.forSessionId(sessionId)));
|
||||
sessionId,
|
||||
null));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -105,7 +95,8 @@ class PhoneVerificationTokenManagerTest {
|
||||
|
||||
assertThrows(NotAuthorizedException.class, () -> phoneVerificationTokenManager.verify(mock(ContainerRequestContext.class),
|
||||
PHONE_NUMBER,
|
||||
PhoneVerificationRequest.forSessionId(sessionId)));
|
||||
sessionId,
|
||||
null));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -118,7 +109,8 @@ class PhoneVerificationTokenManagerTest {
|
||||
|
||||
assertThrows(BadRequestException.class, () -> phoneVerificationTokenManager.verify(mock(ContainerRequestContext.class),
|
||||
PHONE_NUMBER,
|
||||
PhoneVerificationRequest.forSessionId(sessionId)));
|
||||
sessionId,
|
||||
null));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -131,7 +123,8 @@ class PhoneVerificationTokenManagerTest {
|
||||
|
||||
assertThrows(NotAuthorizedException.class, () -> phoneVerificationTokenManager.verify(mock(ContainerRequestContext.class),
|
||||
PHONE_NUMBER,
|
||||
PhoneVerificationRequest.forSessionId(sessionId)));
|
||||
sessionId,
|
||||
null));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -147,7 +140,8 @@ class PhoneVerificationTokenManagerTest {
|
||||
|
||||
assertThrows(expectedExceptionClass, () -> phoneVerificationTokenManager.verify(mock(ContainerRequestContext.class),
|
||||
PHONE_NUMBER,
|
||||
PhoneVerificationRequest.forSessionId(TestRandomUtil.nextBytes(16))));
|
||||
TestRandomUtil.nextBytes(16),
|
||||
null));
|
||||
}
|
||||
|
||||
private static List<Arguments> verifyRegistrationServiceClientException() {
|
||||
@@ -176,7 +170,8 @@ class PhoneVerificationTokenManagerTest {
|
||||
|
||||
assertDoesNotThrow(() -> phoneVerificationTokenManager.verify(containerRequestContext,
|
||||
PHONE_NUMBER,
|
||||
PhoneVerificationRequest.forRecoveryPassword(recoveryPassword)));
|
||||
null,
|
||||
recoveryPassword));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -192,7 +187,8 @@ class PhoneVerificationTokenManagerTest {
|
||||
|
||||
assertThrows(ForbiddenException.class, () -> phoneVerificationTokenManager.verify(containerRequestContext,
|
||||
PHONE_NUMBER,
|
||||
PhoneVerificationRequest.forRecoveryPassword(recoveryPassword)));
|
||||
null,
|
||||
recoveryPassword));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -208,7 +204,8 @@ class PhoneVerificationTokenManagerTest {
|
||||
|
||||
assertThrows(ForbiddenException.class, () -> phoneVerificationTokenManager.verify(containerRequestContext,
|
||||
PHONE_NUMBER,
|
||||
PhoneVerificationRequest.forRecoveryPassword(recoveryPassword)));
|
||||
null,
|
||||
recoveryPassword));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -230,7 +227,8 @@ class PhoneVerificationTokenManagerTest {
|
||||
|
||||
assertThrows(ServerErrorException.class, () -> phoneVerificationTokenManager.verify(containerRequestContext,
|
||||
PHONE_NUMBER,
|
||||
PhoneVerificationRequest.forRecoveryPassword(recoveryPassword)));
|
||||
null,
|
||||
recoveryPassword));
|
||||
}
|
||||
|
||||
private static List<Throwable> verifyRecoveryPasswordManagerException() {
|
||||
|
||||
+15
-105
@@ -11,7 +11,6 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
@@ -29,7 +28,6 @@ import jakarta.ws.rs.BadRequestException;
|
||||
import jakarta.ws.rs.ForbiddenException;
|
||||
import jakarta.ws.rs.NotAuthorizedException;
|
||||
import jakarta.ws.rs.ServerErrorException;
|
||||
import jakarta.ws.rs.WebApplicationException;
|
||||
import jakarta.ws.rs.client.Entity;
|
||||
import jakarta.ws.rs.client.Invocation;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
@@ -60,16 +58,12 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.stubbing.Answer;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockError;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountDataReportResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
@@ -77,10 +71,7 @@ import org.whispersystems.textsecuregcm.entities.ChangeNumberRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneNumberDiscoverabilityRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.mappers.ImpossiblePhoneNumberExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.NonNormalizedPhoneNumberExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
@@ -108,11 +99,6 @@ class AccountControllerV2Test {
|
||||
|
||||
private final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
private final ChangeNumberManager changeNumberManager = mock(ChangeNumberManager.class);
|
||||
private final PhoneVerificationTokenManager phoneVerificationTokenManager = mock(PhoneVerificationTokenManager.class);
|
||||
private final RegistrationLockVerificationManager registrationLockVerificationManager = mock(
|
||||
RegistrationLockVerificationManager.class);
|
||||
private final RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
private final RateLimiter registrationLimiter = mock(RateLimiter.class);
|
||||
|
||||
private final ResourceExtension resources = ResourceExtension.builder()
|
||||
.addProperty(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE)
|
||||
@@ -123,9 +109,7 @@ class AccountControllerV2Test {
|
||||
.addProvider(new NonNormalizedPhoneNumberExceptionMapper())
|
||||
.setMapper(SystemMapper.jsonMapper())
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addResource(
|
||||
new AccountControllerV2(accountsManager, changeNumberManager, phoneVerificationTokenManager,
|
||||
registrationLockVerificationManager, rateLimiters))
|
||||
.addResource(new AccountControllerV2(accountsManager, changeNumberManager))
|
||||
.build();
|
||||
|
||||
@Nested
|
||||
@@ -135,17 +119,16 @@ class AccountControllerV2Test {
|
||||
void setUp() throws Exception {
|
||||
reset(changeNumberManager);
|
||||
|
||||
when(rateLimiters.getRegistrationLimiter()).thenReturn(registrationLimiter);
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID)).thenReturn(Optional.of(AuthHelper.VALID_ACCOUNT));
|
||||
|
||||
when(changeNumberManager.changeNumber(any(), any(), any(), any(), any(), any(), any(), any())).thenAnswer(
|
||||
when(changeNumberManager.changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any())).thenAnswer(
|
||||
(Answer<Account>) invocation -> {
|
||||
final Account account = invocation.getArgument(0);
|
||||
final String number = invocation.getArgument(1);
|
||||
final IdentityKey pniIdentityKey = invocation.getArgument(2);
|
||||
final UUID uuid = invocation.getArgument(0);
|
||||
final Account account = accountsManager.getByAccountIdentifier(uuid).orElseThrow();
|
||||
|
||||
final String number = invocation.getArgument(4);
|
||||
final IdentityKey pniIdentityKey = invocation.getArgument(5);
|
||||
|
||||
final UUID uuid = account.getUuid();
|
||||
final List<Device> devices = account.getDevices();
|
||||
|
||||
final Account updatedAccount = mock(Account.class);
|
||||
@@ -166,11 +149,6 @@ class AccountControllerV2Test {
|
||||
|
||||
return updatedAccount;
|
||||
});
|
||||
|
||||
when(phoneVerificationTokenManager.verify(any(), any(), any())).thenAnswer(invocation -> {
|
||||
final PhoneVerificationRequest request = invocation.getArgument(2);
|
||||
return request.verificationType();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -190,38 +168,14 @@ class AccountControllerV2Test {
|
||||
Map.of(Device.PRIMARY_ID, 17)),
|
||||
MediaType.APPLICATION_JSON_TYPE), AccountIdentityResponse.class);
|
||||
|
||||
verify(changeNumberManager).changeNumber(eq(AuthHelper.VALID_ACCOUNT), eq(NEW_NUMBER), any(), any(), any(),
|
||||
any(), any(), any());
|
||||
verify(changeNumberManager).changeNumber(eq(AuthHelper.VALID_UUID), any(), any(), any(), eq(NEW_NUMBER), any(),
|
||||
any(), any(), any(), any(), any());
|
||||
|
||||
assertEquals(AuthHelper.VALID_UUID, accountIdentityResponse.uuid());
|
||||
assertEquals(NEW_NUMBER, accountIdentityResponse.number());
|
||||
assertNotEquals(AuthHelper.VALID_PNI, accountIdentityResponse.pni());
|
||||
}
|
||||
|
||||
@Test
|
||||
void changeNumberSameNumber() throws Exception {
|
||||
final AccountIdentityResponse accountIdentityResponse =
|
||||
resources.getJerseyTest()
|
||||
.target("/v2/accounts/number")
|
||||
.request()
|
||||
.header(HttpHeaders.AUTHORIZATION,
|
||||
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.put(Entity.entity(
|
||||
new ChangeNumberRequest(encodeSessionId("session"), null, AuthHelper.VALID_NUMBER, null, IDENTITY_KEY,
|
||||
Collections.emptyList(),
|
||||
Map.of(Device.PRIMARY_ID, KeysHelper.signedECPreKey(1, IDENTITY_KEY_PAIR)),
|
||||
Map.of(Device.PRIMARY_ID, KeysHelper.signedKEMPreKey(2, IDENTITY_KEY_PAIR)),
|
||||
Map.of(Device.PRIMARY_ID, 17)),
|
||||
MediaType.APPLICATION_JSON_TYPE), AccountIdentityResponse.class);
|
||||
|
||||
verify(changeNumberManager).changeNumber(eq(AuthHelper.VALID_ACCOUNT), eq(AuthHelper.VALID_NUMBER), any(), any(), any(),
|
||||
any(), any(), any());
|
||||
|
||||
assertEquals(AuthHelper.VALID_UUID, accountIdentityResponse.uuid());
|
||||
assertEquals(AuthHelper.VALID_NUMBER, accountIdentityResponse.number());
|
||||
assertEquals(AuthHelper.VALID_PNI, accountIdentityResponse.pni());
|
||||
}
|
||||
|
||||
@Test
|
||||
void changeNumberNonNormalizedNumber() {
|
||||
try (Response response = resources.getJerseyTest()
|
||||
@@ -318,13 +272,14 @@ class AccountControllerV2Test {
|
||||
@Test
|
||||
void rateLimitedNumber() throws Exception {
|
||||
doThrow(new RateLimitExceededException(null))
|
||||
.when(registrationLimiter).validate(anyString());
|
||||
.when(changeNumberManager).changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v2/accounts/number")
|
||||
.request()
|
||||
.header(HttpHeaders.AUTHORIZATION,
|
||||
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD));
|
||||
|
||||
try (Response response = request.put(Entity.json(requestJson("sessionId", NEW_NUMBER)))) {
|
||||
assertEquals(429, response.getStatus());
|
||||
}
|
||||
@@ -332,9 +287,10 @@ class AccountControllerV2Test {
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void phoneVerificationException(final Exception exception, final int expectedStatus) throws InterruptedException {
|
||||
void phoneVerificationException(final Exception exception, final int expectedStatus)
|
||||
throws InterruptedException, MessageTooLargeException, MismatchedDevicesException, RateLimitExceededException {
|
||||
doThrow(exception)
|
||||
.when(phoneVerificationTokenManager).verify(any(), any(), any());
|
||||
.when(changeNumberManager).changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v2/accounts/number")
|
||||
@@ -356,56 +312,10 @@ class AccountControllerV2Test {
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(RegistrationLockError.class)
|
||||
void registrationLock(final RegistrationLockError error) throws Exception {
|
||||
when(accountsManager.getByE164(any())).thenReturn(Optional.of(mock(Account.class)));
|
||||
|
||||
final Exception e = switch (error) {
|
||||
case MISMATCH -> new WebApplicationException(error.getExpectedStatus());
|
||||
case RATE_LIMITED -> new RateLimitExceededException(null);
|
||||
};
|
||||
doThrow(e)
|
||||
.when(registrationLockVerificationManager).verifyRegistrationLock(any(), any(), any(), any(), any());
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v2/accounts/number")
|
||||
.request()
|
||||
.header(HttpHeaders.AUTHORIZATION,
|
||||
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD));
|
||||
try (Response response = request.put(Entity.json(requestJson("sessionId", NEW_NUMBER)))) {
|
||||
assertEquals(error.getExpectedStatus(), response.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void recoveryPasswordManagerVerificationTrue() throws Exception {
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v2/accounts/number")
|
||||
.request()
|
||||
.header(HttpHeaders.AUTHORIZATION,
|
||||
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD));
|
||||
|
||||
final byte[] recoveryPassword = new byte[32];
|
||||
|
||||
try (final Response response = request.put(Entity.json(requestJsonRecoveryPassword(recoveryPassword, NEW_NUMBER)))) {
|
||||
assertEquals(200, response.getStatus());
|
||||
|
||||
final AccountIdentityResponse accountIdentityResponse = response.readEntity(AccountIdentityResponse.class);
|
||||
|
||||
verify(changeNumberManager).changeNumber(eq(AuthHelper.VALID_ACCOUNT), eq(NEW_NUMBER), any(), any(), any(),
|
||||
any(), any(), any());
|
||||
|
||||
assertEquals(AuthHelper.VALID_UUID, accountIdentityResponse.uuid());
|
||||
assertEquals(NEW_NUMBER, accountIdentityResponse.number());
|
||||
assertNotEquals(AuthHelper.VALID_PNI, accountIdentityResponse.pni());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void deviceMessageTooLarge() throws Exception {
|
||||
doThrow(MessageTooLargeException.class)
|
||||
.when(changeNumberManager).changeNumber(any(), any(), any(), any(), any(), any(), any(), any());
|
||||
.when(changeNumberManager).changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v2/accounts/number")
|
||||
|
||||
+7
-4
@@ -135,9 +135,12 @@ class RegistrationControllerTest {
|
||||
reset(registrationFraudChecker);
|
||||
reset(phoneVerificationTokenManager);
|
||||
|
||||
when(phoneVerificationTokenManager.verify(any(), any(), any())).thenAnswer(invocation -> {
|
||||
final PhoneVerificationRequest request = invocation.getArgument(2);
|
||||
return request.verificationType();
|
||||
when(phoneVerificationTokenManager.verify(any(), any(), any(), any())).thenAnswer(invocation -> {
|
||||
final byte[] sessionId = invocation.getArgument(2);
|
||||
|
||||
return sessionId != null
|
||||
? PhoneVerificationRequest.VerificationType.SESSION
|
||||
: PhoneVerificationRequest.VerificationType.RECOVERY_PASSWORD;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -234,7 +237,7 @@ class RegistrationControllerTest {
|
||||
@MethodSource
|
||||
void phoneVerificationException(final Exception exception, final int expectedStatus) throws InterruptedException {
|
||||
doThrow(exception)
|
||||
.when(phoneVerificationTokenManager).verify(any(), any(), any());
|
||||
.when(phoneVerificationTokenManager).verify(any(), any(), any(), any());
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/registration")
|
||||
|
||||
+195
-11
@@ -4,17 +4,23 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyByte;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import com.google.protobuf.ByteString;
|
||||
import jakarta.ws.rs.WebApplicationException;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
@@ -27,21 +33,33 @@ import org.junit.jupiter.api.Test;
|
||||
import org.mockito.stubbing.Answer;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.IncomingMessage;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
|
||||
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;
|
||||
import org.whispersystems.textsecuregcm.push.MessageSender;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
|
||||
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
|
||||
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
|
||||
public class ChangeNumberManagerTest {
|
||||
private AccountsManager accountsManager;
|
||||
private MessageSender messageSender;
|
||||
private AccountsManager accountsManager;
|
||||
private PhoneVerificationTokenManager phoneVerificationTokenManager;
|
||||
private RegistrationLockVerificationManager registrationLockVerificationManager;
|
||||
private RateLimiter rateLimiter;
|
||||
|
||||
private ChangeNumberManager changeNumberManager;
|
||||
|
||||
private Map<Account, UUID> updatedPhoneNumberIdentifiersByAccount;
|
||||
@@ -50,15 +68,34 @@ public class ChangeNumberManagerTest {
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
accountsManager = mock(AccountsManager.class);
|
||||
messageSender = mock(MessageSender.class);
|
||||
changeNumberManager = new ChangeNumberManager(messageSender, accountsManager, CLOCK);
|
||||
accountsManager = mock(AccountsManager.class);
|
||||
registrationLockVerificationManager = mock(RegistrationLockVerificationManager.class);
|
||||
rateLimiter = mock(RateLimiter.class);
|
||||
phoneVerificationTokenManager = mock(PhoneVerificationTokenManager.class);
|
||||
|
||||
when(phoneVerificationTokenManager.verify(any(), any(), any(), any())).thenAnswer(invocation -> {
|
||||
final byte[] sessionId = invocation.getArgument(2);
|
||||
|
||||
return sessionId != null
|
||||
? PhoneVerificationRequest.VerificationType.SESSION
|
||||
: PhoneVerificationRequest.VerificationType.RECOVERY_PASSWORD;
|
||||
});
|
||||
|
||||
final RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
when(rateLimiters.getRegistrationLimiter()).thenReturn(rateLimiter);
|
||||
|
||||
changeNumberManager = new ChangeNumberManager(messageSender, accountsManager,
|
||||
phoneVerificationTokenManager, registrationLockVerificationManager, rateLimiters, CLOCK);
|
||||
|
||||
updatedPhoneNumberIdentifiersByAccount = new HashMap<>();
|
||||
|
||||
when(accountsManager.changeNumber(any(), any(), any(), any(), any(), any())).thenAnswer((Answer<Account>)invocation -> {
|
||||
final Account account = accountsManager.getByAccountIdentifier(invocation.getArgument(0)).orElseThrow();
|
||||
final String number = invocation.getArgument(1, String.class);
|
||||
final UUID accountIdentifier = invocation.getArgument(0);
|
||||
final String number = invocation.getArgument(1);
|
||||
|
||||
final Account account =
|
||||
accountsManager.getAccountsForChangeNumber(accountIdentifier, number).first();
|
||||
|
||||
final UUID uuid = account.getIdentifier(IdentityType.ACI);
|
||||
final List<Device> devices = account.getDevices();
|
||||
@@ -85,6 +122,9 @@ public class ChangeNumberManagerTest {
|
||||
|
||||
@Test
|
||||
void changeNumberSingleDevice() throws Exception {
|
||||
final String originalNumber = PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("DE"), PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
|
||||
final String targetNumber = PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
|
||||
@@ -100,19 +140,24 @@ public class ChangeNumberManagerTest {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getNumber()).thenReturn(originalNumber);
|
||||
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
|
||||
when(account.isIdentifiedBy(any())).thenReturn(false);
|
||||
when(account.isIdentifiedBy(new AciServiceIdentifier(accountIdentifier))).thenReturn(true);
|
||||
|
||||
AccountsHelper.setupMockGet(accountsManager, account);
|
||||
when(accountsManager.getAccountsForChangeNumber(eq(accountIdentifier), any()))
|
||||
.thenReturn(new Pair<>(account, Optional.empty()));
|
||||
|
||||
changeNumberManager.changeNumber(account, targetNumber, pniIdentityKey, ecSignedPreKeys, kemLastResortPreKeys, Collections.emptyList(), Collections.emptyMap(), null);
|
||||
changeNumberManager.changeNumber(accountIdentifier, null, null, null, targetNumber, pniIdentityKey, ecSignedPreKeys, kemLastResortPreKeys, Collections.emptyList(), Collections.emptyMap(), mock(ContainerRequestContext.class));
|
||||
verify(accountsManager).changeNumber(accountIdentifier, targetNumber, pniIdentityKey, ecSignedPreKeys, kemLastResortPreKeys, Collections.emptyMap());
|
||||
verify(messageSender, never()).sendMessages(eq(account), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void changeNumberLinkedDevices() throws Exception {
|
||||
final String originalNumber = PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("DE"), PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
|
||||
final String targetNumber = PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
|
||||
@@ -133,6 +178,7 @@ public class ChangeNumberManagerTest {
|
||||
when(linkedDevice.getRegistrationId(IdentityType.ACI)).thenReturn(linkedDeviceRegistrationId);
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getNumber()).thenReturn(originalNumber);
|
||||
when(account.getIdentifier(IdentityType.ACI)).thenReturn(aci);
|
||||
when(account.isIdentifiedBy(any())).thenReturn(false);
|
||||
when(account.isIdentifiedBy(new AciServiceIdentifier(aci))).thenReturn(true);
|
||||
@@ -158,16 +204,20 @@ public class ChangeNumberManagerTest {
|
||||
final IncomingMessage incomingMessage =
|
||||
new IncomingMessage(1, linkedDeviceId, linkedDeviceRegistrationId, new byte[] { 1 });
|
||||
|
||||
AccountsHelper.setupMockGet(accountsManager, account);
|
||||
when(accountsManager.getAccountsForChangeNumber(eq(aci), any()))
|
||||
.thenReturn(new Pair<>(account, Optional.empty()));
|
||||
|
||||
changeNumberManager.changeNumber(account,
|
||||
changeNumberManager.changeNumber(aci,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
targetNumber,
|
||||
pniIdentityKey,
|
||||
ecSignedPreKeys,
|
||||
kemLastResortPreKeys,
|
||||
List.of(incomingMessage),
|
||||
registrationIds,
|
||||
null);
|
||||
mock(ContainerRequestContext.class));
|
||||
|
||||
verify(accountsManager).changeNumber(aci,
|
||||
targetNumber,
|
||||
@@ -196,4 +246,138 @@ public class ChangeNumberManagerTest {
|
||||
eq(Optional.of(primaryDeviceId)),
|
||||
any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void changeNumberSameNumber() throws Exception {
|
||||
final String targetNumber = PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
|
||||
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
|
||||
final IdentityKey pniIdentityKey = new IdentityKey(ECKeyPair.generate().getPublicKey());
|
||||
|
||||
final Map<Byte, ECSignedPreKey> ecSignedPreKeys =
|
||||
Map.of(Device.PRIMARY_ID, KeysHelper.signedECPreKey(1, pniIdentityKeyPair));
|
||||
|
||||
final Map<Byte, KEMSignedPreKey> kemLastResortPreKeys =
|
||||
Map.of(Device.PRIMARY_ID, KeysHelper.signedKEMPreKey(2, pniIdentityKeyPair));
|
||||
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getNumber()).thenReturn(targetNumber);
|
||||
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
|
||||
when(account.isIdentifiedBy(any())).thenReturn(false);
|
||||
when(account.isIdentifiedBy(new AciServiceIdentifier(accountIdentifier))).thenReturn(true);
|
||||
|
||||
when(accountsManager.getAccountsForChangeNumber(eq(accountIdentifier), any()))
|
||||
.thenReturn(new Pair<>(account, Optional.empty()));
|
||||
|
||||
changeNumberManager.changeNumber(accountIdentifier, null, null, null, targetNumber, pniIdentityKey, ecSignedPreKeys, kemLastResortPreKeys, Collections.emptyList(), Collections.emptyMap(), mock(ContainerRequestContext.class));
|
||||
|
||||
verifyNoInteractions(rateLimiter);
|
||||
verifyNoInteractions(phoneVerificationTokenManager);
|
||||
verifyNoInteractions(registrationLockVerificationManager);
|
||||
|
||||
verify(accountsManager).changeNumber(accountIdentifier, targetNumber, pniIdentityKey, ecSignedPreKeys, kemLastResortPreKeys, Collections.emptyMap());
|
||||
verify(messageSender, never()).sendMessages(eq(account), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void changeNumberRateLimited()
|
||||
throws MismatchedDevicesException, InterruptedException, MessageTooLargeException, RateLimitExceededException {
|
||||
final String originalNumber = PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("DE"), PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
|
||||
final String targetNumber = PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
|
||||
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
|
||||
final IdentityKey pniIdentityKey = new IdentityKey(ECKeyPair.generate().getPublicKey());
|
||||
|
||||
final Map<Byte, ECSignedPreKey> ecSignedPreKeys =
|
||||
Map.of(Device.PRIMARY_ID, KeysHelper.signedECPreKey(1, pniIdentityKeyPair));
|
||||
|
||||
final Map<Byte, KEMSignedPreKey> kemLastResortPreKeys =
|
||||
Map.of(Device.PRIMARY_ID, KeysHelper.signedKEMPreKey(2, pniIdentityKeyPair));
|
||||
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getNumber()).thenReturn(originalNumber);
|
||||
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
|
||||
when(account.isIdentifiedBy(any())).thenReturn(false);
|
||||
when(account.isIdentifiedBy(new AciServiceIdentifier(accountIdentifier))).thenReturn(true);
|
||||
|
||||
when(accountsManager.getAccountsForChangeNumber(eq(accountIdentifier), any()))
|
||||
.thenReturn(new Pair<>(account, Optional.empty()));
|
||||
|
||||
doThrow(new RateLimitExceededException(Duration.ofMinutes(1)))
|
||||
.when(rateLimiter).validate(targetNumber);
|
||||
|
||||
assertThrows(RateLimitExceededException.class, () -> changeNumberManager.changeNumber(accountIdentifier,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
targetNumber,
|
||||
pniIdentityKey,
|
||||
ecSignedPreKeys,
|
||||
kemLastResortPreKeys,
|
||||
Collections.emptyList(),
|
||||
Collections.emptyMap(),
|
||||
mock(ContainerRequestContext.class)));
|
||||
|
||||
verify(accountsManager, never()).changeNumber(any(), any(), any(), any(), any(), any());
|
||||
verify(messageSender, never()).sendMessages(any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void changeNumberRegistrationLockFailed()
|
||||
throws MismatchedDevicesException, InterruptedException, MessageTooLargeException, RateLimitExceededException {
|
||||
final String originalNumber = PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("DE"), PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
|
||||
final String targetNumber = PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
|
||||
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
|
||||
final IdentityKey pniIdentityKey = new IdentityKey(ECKeyPair.generate().getPublicKey());
|
||||
|
||||
final Map<Byte, ECSignedPreKey> ecSignedPreKeys =
|
||||
Map.of(Device.PRIMARY_ID, KeysHelper.signedECPreKey(1, pniIdentityKeyPair));
|
||||
|
||||
final Map<Byte, KEMSignedPreKey> kemLastResortPreKeys =
|
||||
Map.of(Device.PRIMARY_ID, KeysHelper.signedKEMPreKey(2, pniIdentityKeyPair));
|
||||
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getNumber()).thenReturn(originalNumber);
|
||||
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
|
||||
when(account.isIdentifiedBy(any())).thenReturn(false);
|
||||
when(account.isIdentifiedBy(new AciServiceIdentifier(accountIdentifier))).thenReturn(true);
|
||||
|
||||
final Account existingAccount = mock(Account.class);
|
||||
when(existingAccount.getNumber()).thenReturn(targetNumber);
|
||||
|
||||
when(accountsManager.getAccountsForChangeNumber(eq(accountIdentifier), any()))
|
||||
.thenReturn(new Pair<>(account, Optional.of(existingAccount)));
|
||||
|
||||
doThrow(new WebApplicationException(423))
|
||||
.when(registrationLockVerificationManager).verifyRegistrationLock(eq(existingAccount), any(), any(), any(), any());
|
||||
|
||||
assertThrows(WebApplicationException.class, () -> changeNumberManager.changeNumber(accountIdentifier,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
targetNumber,
|
||||
pniIdentityKey,
|
||||
ecSignedPreKeys,
|
||||
kemLastResortPreKeys,
|
||||
Collections.emptyList(),
|
||||
Collections.emptyMap(),
|
||||
mock(ContainerRequestContext.class)));
|
||||
|
||||
verify(accountsManager, never()).changeNumber(any(), any(), any(), any(), any(), any());
|
||||
verify(messageSender, never()).sendMessages(any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user