mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-02 11:46:53 +00:00
Port AccountControllerV2 to gRPC
This commit is contained in:
1 parent
54ea7a288c
commit
d3c93dd1a2
25 files changed
+1088
-384
No files matched your search
+44
-25
@@ -14,11 +14,7 @@ import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import io.grpc.Status;
|
||||
import jakarta.ws.rs.BadRequestException;
|
||||
import jakarta.ws.rs.ForbiddenException;
|
||||
import jakarta.ws.rs.NotAuthorizedException;
|
||||
import jakarta.ws.rs.ServerErrorException;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
@@ -79,8 +75,11 @@ class PhoneVerificationTokenManagerTest {
|
||||
.thenReturn(Optional.of(
|
||||
new RegistrationServiceSession(sessionId, PHONE_NUMBER, true, null, null, null, 0)));
|
||||
|
||||
assertDoesNotThrow(() -> phoneVerificationTokenManager.verify(mock(ContainerRequestContext.class),
|
||||
assertDoesNotThrow(() -> phoneVerificationTokenManager.verify(
|
||||
PHONE_NUMBER,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
sessionId,
|
||||
null));
|
||||
}
|
||||
@@ -92,8 +91,11 @@ class PhoneVerificationTokenManagerTest {
|
||||
when(registrationServiceClient.getSession(eq(sessionId), any()))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(NotAuthorizedException.class, () -> phoneVerificationTokenManager.verify(mock(ContainerRequestContext.class),
|
||||
assertThrows(UnverifiedRegistrationSessionException.class, () -> phoneVerificationTokenManager.verify(
|
||||
PHONE_NUMBER,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
sessionId,
|
||||
null));
|
||||
}
|
||||
@@ -106,8 +108,11 @@ class PhoneVerificationTokenManagerTest {
|
||||
.thenReturn(Optional.of(
|
||||
new RegistrationServiceSession(sessionId, PHONE_NUMBER + "0", true, null, null, null, 0)));
|
||||
|
||||
assertThrows(BadRequestException.class, () -> phoneVerificationTokenManager.verify(mock(ContainerRequestContext.class),
|
||||
assertThrows(InvalidRegistrationSessionException.class, () -> phoneVerificationTokenManager.verify(
|
||||
PHONE_NUMBER,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
sessionId,
|
||||
null));
|
||||
}
|
||||
@@ -120,8 +125,11 @@ class PhoneVerificationTokenManagerTest {
|
||||
.thenReturn(Optional.of(
|
||||
new RegistrationServiceSession(sessionId, PHONE_NUMBER, false, null, null, null, 0)));
|
||||
|
||||
assertThrows(NotAuthorizedException.class, () -> phoneVerificationTokenManager.verify(mock(ContainerRequestContext.class),
|
||||
assertThrows(UnverifiedRegistrationSessionException.class, () -> phoneVerificationTokenManager.verify(
|
||||
PHONE_NUMBER,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
sessionId,
|
||||
null));
|
||||
}
|
||||
@@ -133,17 +141,20 @@ class PhoneVerificationTokenManagerTest {
|
||||
|
||||
when(registrationServiceClient.getSession(any(), any())).thenThrow(registrationServiceClientException);
|
||||
|
||||
assertThrows(expectedExceptionClass, () -> phoneVerificationTokenManager.verify(mock(ContainerRequestContext.class),
|
||||
assertThrows(expectedExceptionClass, () -> phoneVerificationTokenManager.verify(
|
||||
PHONE_NUMBER,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
TestRandomUtil.nextBytes(16),
|
||||
null));
|
||||
}
|
||||
|
||||
private static List<Arguments> verifyRegistrationServiceClientException() {
|
||||
return List.of(
|
||||
Arguments.arguments(Status.INVALID_ARGUMENT.asRuntimeException(), BadRequestException.class),
|
||||
Arguments.arguments(Status.RESOURCE_EXHAUSTED.asRuntimeException(), ServerErrorException.class),
|
||||
Arguments.arguments(Status.DEADLINE_EXCEEDED.asRuntimeException(), ServerErrorException.class)
|
||||
Arguments.arguments(Status.INVALID_ARGUMENT.asRuntimeException(), InvalidRegistrationSessionException.class),
|
||||
Arguments.arguments(Status.RESOURCE_EXHAUSTED.asRuntimeException(), IOException.class),
|
||||
Arguments.arguments(Status.DEADLINE_EXCEEDED.asRuntimeException(), IOException.class)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -153,52 +164,58 @@ class PhoneVerificationTokenManagerTest {
|
||||
|
||||
@Test
|
||||
void verify() {
|
||||
final ContainerRequestContext containerRequestContext = mock(ContainerRequestContext.class);
|
||||
final byte[] recoveryPassword = TestRandomUtil.nextBytes(16);
|
||||
|
||||
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(containerRequestContext, PHONE_NUMBER))
|
||||
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(PHONE_NUMBER, null, null, null))
|
||||
.thenReturn(true);
|
||||
|
||||
when(registrationRecoveryPasswordsManager.verify(PHONE_NUMBER_IDENTIFIER, recoveryPassword))
|
||||
.thenReturn(true);
|
||||
|
||||
assertDoesNotThrow(() -> phoneVerificationTokenManager.verify(containerRequestContext,
|
||||
assertDoesNotThrow(() -> phoneVerificationTokenManager.verify(
|
||||
PHONE_NUMBER,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
recoveryPassword));
|
||||
}
|
||||
|
||||
@Test
|
||||
void verifyRecoveryCheckerDeclined() {
|
||||
final ContainerRequestContext containerRequestContext = mock(ContainerRequestContext.class);
|
||||
final byte[] recoveryPassword = TestRandomUtil.nextBytes(16);
|
||||
|
||||
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(containerRequestContext, PHONE_NUMBER))
|
||||
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(PHONE_NUMBER, null, null, null))
|
||||
.thenReturn(false);
|
||||
|
||||
when(registrationRecoveryPasswordsManager.verify(PHONE_NUMBER_IDENTIFIER, recoveryPassword))
|
||||
.thenReturn(true);
|
||||
|
||||
assertThrows(ForbiddenException.class, () -> phoneVerificationTokenManager.verify(containerRequestContext,
|
||||
assertThrows(RecoveryPasswordVerificationFailedException.class, () -> phoneVerificationTokenManager.verify(
|
||||
PHONE_NUMBER,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
recoveryPassword));
|
||||
}
|
||||
|
||||
@Test
|
||||
void verifyRecoveryPasswordNotVerified() {
|
||||
final ContainerRequestContext containerRequestContext = mock(ContainerRequestContext.class);
|
||||
final byte[] recoveryPassword = TestRandomUtil.nextBytes(16);
|
||||
|
||||
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(containerRequestContext, PHONE_NUMBER))
|
||||
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(PHONE_NUMBER, null, null, null))
|
||||
.thenReturn(true);
|
||||
|
||||
when(registrationRecoveryPasswordsManager.verify(PHONE_NUMBER_IDENTIFIER, recoveryPassword))
|
||||
.thenReturn(false);
|
||||
|
||||
assertThrows(ForbiddenException.class, () -> phoneVerificationTokenManager.verify(containerRequestContext,
|
||||
assertThrows(RecoveryPasswordVerificationFailedException.class, () -> phoneVerificationTokenManager.verify(
|
||||
PHONE_NUMBER,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
recoveryPassword));
|
||||
}
|
||||
|
||||
@@ -206,18 +223,20 @@ class PhoneVerificationTokenManagerTest {
|
||||
@MethodSource
|
||||
void verifyPhoneNumberIdentifiersException(final Throwable phoneNumberIdentifiersException) {
|
||||
|
||||
final ContainerRequestContext containerRequestContext = mock(ContainerRequestContext.class);
|
||||
final byte[] recoveryPassword = TestRandomUtil.nextBytes(16);
|
||||
|
||||
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(containerRequestContext, PHONE_NUMBER))
|
||||
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(PHONE_NUMBER, null, null, null))
|
||||
.thenReturn(true);
|
||||
|
||||
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(PHONE_NUMBER))
|
||||
.thenReturn(CompletableFuture.failedFuture(phoneNumberIdentifiersException));
|
||||
|
||||
assertThrows(ServerErrorException.class, () -> phoneVerificationTokenManager.verify(containerRequestContext,
|
||||
assertThrows(IOException.class, () -> phoneVerificationTokenManager.verify(
|
||||
PHONE_NUMBER,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
recoveryPassword));
|
||||
}
|
||||
|
||||
|
||||
+2
-5
@@ -6,7 +6,6 @@
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
@@ -19,7 +18,6 @@ import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import jakarta.ws.rs.WebApplicationException;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
@@ -101,9 +99,8 @@ class RegistrationLockVerificationManagerTest {
|
||||
final Pair<Class<? extends Exception>, Consumer<Exception>> exceptionType = switch (error) {
|
||||
case MISMATCH -> {
|
||||
when(existingRegistrationLock.verify(clientRegistrationLock)).thenReturn(false);
|
||||
yield new Pair<>(WebApplicationException.class, e -> {
|
||||
if (e instanceof WebApplicationException wae) {
|
||||
assertEquals(RegistrationLockVerificationManager.FAILURE_HTTP_STATUS, wae.getResponse().getStatus());
|
||||
yield new Pair<>(RegistrationLockFailureException.class, e -> {
|
||||
if (e instanceof RegistrationLockFailureException) {
|
||||
if (!verificationType.equals(PhoneVerificationRequest.VerificationType.RECOVERY_PASSWORD) || clientRegistrationLock != null) {
|
||||
verify(registrationRecoveryPasswordsManager).remove(account.getIdentifier(IdentityType.PNI));
|
||||
} else {
|
||||
|
||||
+19
-189
@@ -20,25 +20,16 @@ import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
import io.dropwizard.auth.AuthValueFactoryProvider;
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import io.dropwizard.testing.junit5.ResourceExtension;
|
||||
import jakarta.ws.rs.BadRequestException;
|
||||
import jakarta.ws.rs.ForbiddenException;
|
||||
import jakarta.ws.rs.NotAuthorizedException;
|
||||
import jakarta.ws.rs.ServerErrorException;
|
||||
import jakarta.ws.rs.client.Entity;
|
||||
import jakarta.ws.rs.client.Invocation;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
@@ -58,6 +49,7 @@ 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.ArgumentsSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
@@ -65,7 +57,9 @@ 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.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.auth.RecoveryPasswordVerificationFailedException;
|
||||
import org.whispersystems.textsecuregcm.auth.UnverifiedRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountDataReportResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ChangeNumberRequest;
|
||||
@@ -78,15 +72,14 @@ import org.whispersystems.textsecuregcm.mappers.NonNormalizedPhoneNumberExceptio
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsTestHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
@ExtendWith(DropwizardExtensionsSupport.class)
|
||||
class AccountControllerV2Test {
|
||||
@@ -122,7 +115,7 @@ class AccountControllerV2Test {
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID)).thenReturn(Optional.of(AuthHelper.VALID_ACCOUNT));
|
||||
|
||||
when(changeNumberManager.changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any())).thenAnswer(
|
||||
when(changeNumberManager.changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any())).thenAnswer(
|
||||
(Answer<Account>) invocation -> {
|
||||
final UUID uuid = invocation.getArgument(0);
|
||||
final Account account = accountsManager.getByAccountIdentifier(uuid).orElseThrow();
|
||||
@@ -173,7 +166,7 @@ class AccountControllerV2Test {
|
||||
MediaType.APPLICATION_JSON_TYPE), AccountIdentityResponse.class);
|
||||
|
||||
verify(changeNumberManager).changeNumber(eq(AuthHelper.VALID_UUID), any(), any(), any(), eq(NEW_NUMBER), any(),
|
||||
any(), any(), any(), any(), any());
|
||||
any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
assertEquals(AuthHelper.VALID_UUID, accountIdentityResponse.uuid());
|
||||
assertEquals(NEW_NUMBER, accountIdentityResponse.number());
|
||||
@@ -276,7 +269,7 @@ class AccountControllerV2Test {
|
||||
@Test
|
||||
void rateLimitedNumber() throws Exception {
|
||||
doThrow(new RateLimitExceededException(null))
|
||||
.when(changeNumberManager).changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
.when(changeNumberManager).changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v2/accounts/number")
|
||||
@@ -292,9 +285,9 @@ class AccountControllerV2Test {
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void phoneVerificationException(final Exception exception, final int expectedStatus)
|
||||
throws InterruptedException, MessageTooLargeException, MismatchedDevicesException, RateLimitExceededException, MessageDeliveryNotAllowedException {
|
||||
throws Exception {
|
||||
doThrow(exception)
|
||||
.when(changeNumberManager).changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
.when(changeNumberManager).changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v2/accounts/number")
|
||||
@@ -309,17 +302,17 @@ class AccountControllerV2Test {
|
||||
|
||||
private static List<Arguments> phoneVerificationException() {
|
||||
return List.of(
|
||||
Arguments.argumentSet("Bad request", new BadRequestException(), HttpStatus.SC_BAD_REQUEST),
|
||||
Arguments.argumentSet("Not authorized", new NotAuthorizedException("test"), HttpStatus.SC_UNAUTHORIZED),
|
||||
Arguments.argumentSet("Forbidden", new ForbiddenException(), HttpStatus.SC_FORBIDDEN),
|
||||
Arguments.argumentSet("Unexpected exception", new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE), HttpStatus.SC_SERVICE_UNAVAILABLE)
|
||||
Arguments.argumentSet("Bad request", new InvalidRegistrationSessionException("invalid registration session"), HttpStatus.SC_BAD_REQUEST),
|
||||
Arguments.argumentSet("Not authorized", new UnverifiedRegistrationSessionException(), HttpStatus.SC_UNAUTHORIZED),
|
||||
Arguments.argumentSet("Forbidden", new RecoveryPasswordVerificationFailedException(), HttpStatus.SC_FORBIDDEN),
|
||||
Arguments.argumentSet("Unexpected exception", new IOException("unavailable"), HttpStatus.SC_SERVICE_UNAVAILABLE)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deviceMessageTooLarge() throws Exception {
|
||||
doThrow(MessageTooLargeException.class)
|
||||
.when(changeNumberManager).changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
.when(changeNumberManager).changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v2/accounts/number")
|
||||
@@ -341,7 +334,7 @@ class AccountControllerV2Test {
|
||||
@Test
|
||||
void messageDeliveryNotAllowed() throws Exception {
|
||||
doThrow(MessageDeliveryNotAllowedException.class)
|
||||
.when(changeNumberManager).changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
.when(changeNumberManager).changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v2/accounts/number")
|
||||
@@ -360,13 +353,6 @@ class AccountControllerV2Test {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Valid request JSON with the given Recovery Password
|
||||
*/
|
||||
private static String requestJsonRecoveryPassword(final byte[] recoveryPassword, final String newNumber) {
|
||||
return requestJson("", recoveryPassword, newNumber, 123);
|
||||
}
|
||||
|
||||
/**
|
||||
* Valid request JSON with the give session ID and recovery password
|
||||
*/
|
||||
@@ -481,7 +467,7 @@ class AccountControllerV2Test {
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
@ArgumentsSource(AccountsTestHelper.AccountsDataReportArgumentProvider.class)
|
||||
void testGetAccountDataReport(final Account account, final String expectedTextAfterHeader) throws Exception {
|
||||
when(AuthHelper.ACCOUNTS_MANAGER.getByAccountIdentifier(account.getUuid())).thenReturn(Optional.of(account));
|
||||
when(accountsManager.getByAccountIdentifier(account.getUuid())).thenReturn(Optional.of(account));
|
||||
@@ -516,163 +502,7 @@ class AccountControllerV2Test {
|
||||
assertTrue(deviceIds.isEmpty());
|
||||
|
||||
final String actualText = (String) SystemMapper.jsonMapper().readValue(stringResponse, Map.class).get("text");
|
||||
final int headerEnd = actualText.indexOf("# Account");
|
||||
assertEquals(expectedTextAfterHeader, actualText.substring(headerEnd));
|
||||
|
||||
final String actualHeader = actualText.substring(0, headerEnd);
|
||||
assertTrue(actualHeader.matches(
|
||||
"Report ID: [a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}\nReport timestamp: \\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z\n\n"));
|
||||
}
|
||||
|
||||
static Stream<Arguments> testGetAccountDataReport() {
|
||||
final String exampleNumber1 = toE164(PhoneNumberUtil.getInstance().getExampleNumber("ES"));
|
||||
final String account2PhoneNumber = toE164(PhoneNumberUtil.getInstance().getExampleNumber("AU"));
|
||||
final String account3PhoneNumber = toE164(PhoneNumberUtil.getInstance().getExampleNumber("IN"));
|
||||
|
||||
final Instant account1Device1Created = Instant.ofEpochSecond(1669323142); // 2022-11-24T20:52:22Z
|
||||
final Instant account1Device2Created = Instant.ofEpochSecond(1679155122); // 2023-03-18T15:58:42Z
|
||||
final Instant account1Device1LastSeen = Instant.ofEpochMilli(Util.todayInMillis());
|
||||
final Instant account1Device2LastSeen = Instant.ofEpochSecond(1678838400); // 2023-03-15T00:00:00Z
|
||||
|
||||
final Instant account2Device1Created = Instant.ofEpochSecond(1659123001); // 2022-07-29T19:30:01Z
|
||||
final Instant account2Device1LastSeen = Instant.ofEpochMilli(Util.todayInMillis());
|
||||
final Instant badgeAExpiration = Instant.now().plus(Duration.ofDays(21)).truncatedTo(ChronoUnit.SECONDS);
|
||||
|
||||
final Instant account3Device1Created = Instant.ofEpochSecond(1639923487); // 2021-12-19T14:18:07Z
|
||||
final Instant account3Device1LastSeen = Instant.ofEpochMilli(Util.todayInMillis());
|
||||
final Instant badgeBExpiration = Instant.now().plus(Duration.ofDays(21)).truncatedTo(ChronoUnit.SECONDS);
|
||||
final Instant badgeCExpiration = Instant.now().plus(Duration.ofDays(24)).truncatedTo(ChronoUnit.SECONDS);
|
||||
|
||||
return Stream.of(
|
||||
Arguments.of(
|
||||
buildTestAccountForDataReport(UUID.randomUUID(), exampleNumber1,
|
||||
true, true,
|
||||
Collections.emptyList(),
|
||||
List.of(new DeviceData(Device.PRIMARY_ID, account1Device1LastSeen, account1Device1Created, null),
|
||||
new DeviceData((byte) 2, account1Device2LastSeen, account1Device2Created, "OWP"))),
|
||||
String.format("""
|
||||
# Account
|
||||
Phone number: %s
|
||||
Allow sealed sender from anyone: true
|
||||
Find account by phone number: true
|
||||
Badges: None
|
||||
|
||||
# Devices
|
||||
- ID: 1
|
||||
Created: 2022-11-24T20:52:22Z
|
||||
Last seen: %s
|
||||
User-agent: null
|
||||
- ID: 2
|
||||
Created: 2023-03-18T15:58:42Z
|
||||
Last seen: 2023-03-15T00:00:00Z
|
||||
User-agent: OWP
|
||||
""",
|
||||
exampleNumber1,
|
||||
account1Device1LastSeen)
|
||||
),
|
||||
Arguments.of(
|
||||
buildTestAccountForDataReport(UUID.randomUUID(), account2PhoneNumber,
|
||||
false, true,
|
||||
List.of(new AccountBadge("badge_a", badgeAExpiration, true)),
|
||||
List.of(new DeviceData(Device.PRIMARY_ID, account2Device1LastSeen, account2Device1Created, "OWI"))),
|
||||
String.format("""
|
||||
# Account
|
||||
Phone number: %s
|
||||
Allow sealed sender from anyone: false
|
||||
Find account by phone number: true
|
||||
Badges:
|
||||
- ID: badge_a
|
||||
Expiration: %s
|
||||
Visible: true
|
||||
|
||||
# Devices
|
||||
- ID: 1
|
||||
Created: 2022-07-29T19:30:01Z
|
||||
Last seen: %s
|
||||
User-agent: OWI
|
||||
""", account2PhoneNumber,
|
||||
badgeAExpiration,
|
||||
account2Device1LastSeen)
|
||||
),
|
||||
Arguments.of(
|
||||
buildTestAccountForDataReport(UUID.randomUUID(), account3PhoneNumber,
|
||||
true, false,
|
||||
List.of(
|
||||
new AccountBadge("badge_b", badgeBExpiration, true),
|
||||
new AccountBadge("badge_c", badgeCExpiration, false)),
|
||||
List.of(new DeviceData(Device.PRIMARY_ID, account3Device1LastSeen, account3Device1Created, "OWA"))),
|
||||
String.format("""
|
||||
# Account
|
||||
Phone number: %s
|
||||
Allow sealed sender from anyone: true
|
||||
Find account by phone number: false
|
||||
Badges:
|
||||
- ID: badge_b
|
||||
Expiration: %s
|
||||
Visible: true
|
||||
- ID: badge_c
|
||||
Expiration: %s
|
||||
Visible: false
|
||||
|
||||
# Devices
|
||||
- ID: 1
|
||||
Created: 2021-12-19T14:18:07Z
|
||||
Last seen: %s
|
||||
User-agent: OWA
|
||||
""", account3PhoneNumber,
|
||||
badgeBExpiration,
|
||||
badgeCExpiration,
|
||||
account3Device1LastSeen)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an {@link Account} with data sufficient for
|
||||
* {@link AccountControllerV2#getAccountDataReport(AuthenticatedDevice)}.
|
||||
* <p>
|
||||
* Note: All devices will have a {@link SaltedTokenHash} for "password"
|
||||
*/
|
||||
static Account buildTestAccountForDataReport(final UUID aci, final String number,
|
||||
final boolean unrestrictedUnidentifiedAccess, final boolean discoverableByPhoneNumber,
|
||||
List<AccountBadge> badges, List<DeviceData> devices) {
|
||||
|
||||
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
|
||||
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
|
||||
|
||||
final Account account = new Account();
|
||||
account.setUuid(aci);
|
||||
account.setNumber(number, UUID.randomUUID());
|
||||
account.setUnrestrictedUnidentifiedAccess(unrestrictedUnidentifiedAccess);
|
||||
account.setDiscoverableByPhoneNumber(discoverableByPhoneNumber);
|
||||
account.setBadges(Clock.systemUTC(), new ArrayList<>(badges));
|
||||
account.setIdentityKey(new IdentityKey(aciIdentityKeyPair.getPublicKey()));
|
||||
account.setPhoneNumberIdentityKey(new IdentityKey(pniIdentityKeyPair.getPublicKey()));
|
||||
|
||||
assert !devices.isEmpty();
|
||||
|
||||
final SaltedTokenHash passwordTokenHash = SaltedTokenHash.generateFor("password");
|
||||
|
||||
devices.forEach(deviceData -> {
|
||||
final Device device = new Device();
|
||||
device.setId(deviceData.id);
|
||||
device.setAuthTokenHash(passwordTokenHash);
|
||||
device.setFetchesMessages(true);
|
||||
device.setLastSeen(deviceData.lastSeen().toEpochMilli());
|
||||
device.setCreated(deviceData.created().toEpochMilli());
|
||||
device.setUserAgent(deviceData.userAgent());
|
||||
account.addDevice(device);
|
||||
});
|
||||
|
||||
return account;
|
||||
}
|
||||
|
||||
private record DeviceData(byte id, Instant lastSeen, Instant created, @Nullable String userAgent) {
|
||||
|
||||
}
|
||||
|
||||
private static String toE164(Phonenumber.PhoneNumber phoneNumber) {
|
||||
return PhoneNumberUtil.getInstance().format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
AccountsTestHelper.verifyAccountDataReportText(actualText, expectedTextAfterHeader);
|
||||
}
|
||||
}
|
||||
}
|
||||
+13
-13
@@ -20,15 +20,12 @@ import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import io.dropwizard.testing.junit5.ResourceExtension;
|
||||
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;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
@@ -60,9 +57,12 @@ import org.junitpioneer.jupiter.cartesian.ArgumentSets;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RecoveryPasswordVerificationFailedException;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockError;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
import org.whispersystems.textsecuregcm.auth.UnverifiedRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountCreationResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
@@ -120,7 +120,7 @@ class RegistrationControllerTest {
|
||||
.build();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws InterruptedException {
|
||||
void setUp() throws Exception {
|
||||
when(rateLimiters.getRegistrationLimiter()).thenReturn(registrationLimiter);
|
||||
|
||||
when(accountsManager.update(any(UUID.class), any())).thenAnswer(invocation -> {
|
||||
@@ -135,8 +135,8 @@ class RegistrationControllerTest {
|
||||
reset(registrationFraudChecker);
|
||||
reset(phoneVerificationTokenManager);
|
||||
|
||||
when(phoneVerificationTokenManager.verify(any(), any(), any(), any())).thenAnswer(invocation -> {
|
||||
final byte[] sessionId = invocation.getArgument(2);
|
||||
when(phoneVerificationTokenManager.verify(any(), any(), any(), any(), any(), any())).thenAnswer(invocation -> {
|
||||
final byte[] sessionId = invocation.getArgument(4);
|
||||
|
||||
return sessionId != null
|
||||
? PhoneVerificationRequest.VerificationType.SESSION
|
||||
@@ -235,9 +235,9 @@ class RegistrationControllerTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void phoneVerificationException(final Exception exception, final int expectedStatus) throws InterruptedException {
|
||||
void phoneVerificationException(final Exception exception, final int expectedStatus) throws Exception {
|
||||
doThrow(exception)
|
||||
.when(phoneVerificationTokenManager).verify(any(), any(), any(), any());
|
||||
.when(phoneVerificationTokenManager).verify(any(), any(), any(), any(), any(), any());
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/registration")
|
||||
@@ -251,10 +251,10 @@ class RegistrationControllerTest {
|
||||
|
||||
private static List<Arguments> phoneVerificationException() {
|
||||
return List.of(
|
||||
Arguments.argumentSet("Bad request", new BadRequestException(), HttpStatus.SC_BAD_REQUEST),
|
||||
Arguments.argumentSet("Not authorized", new NotAuthorizedException("test"), HttpStatus.SC_UNAUTHORIZED),
|
||||
Arguments.argumentSet("Forbidden", new ForbiddenException(), HttpStatus.SC_FORBIDDEN),
|
||||
Arguments.argumentSet("Unexpected exception", new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE), HttpStatus.SC_SERVICE_UNAVAILABLE)
|
||||
Arguments.argumentSet("Bad request", new InvalidRegistrationSessionException("invalid registration session"), HttpStatus.SC_BAD_REQUEST),
|
||||
Arguments.argumentSet("Not authorized", new UnverifiedRegistrationSessionException(), HttpStatus.SC_UNAUTHORIZED),
|
||||
Arguments.argumentSet("Forbidden", new RecoveryPasswordVerificationFailedException(), HttpStatus.SC_FORBIDDEN),
|
||||
Arguments.argumentSet("Unexpected exception", new IOException("unavailable"), HttpStatus.SC_SERVICE_UNAVAILABLE)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+229
-1
@@ -21,22 +21,27 @@ import static org.mockito.Mockito.when;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.grpc.Status;
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.ArgumentsSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.signal.chat.account.AccountsGrpc;
|
||||
import org.signal.chat.account.ChangeNumberRequest;
|
||||
import org.signal.chat.account.ChangeNumberResponse;
|
||||
import org.signal.chat.account.ClearRegistrationLockRequest;
|
||||
import org.signal.chat.account.ClearRegistrationLockResponse;
|
||||
import org.signal.chat.account.ConfigureUnidentifiedAccessRequest;
|
||||
@@ -46,10 +51,14 @@ import org.signal.chat.account.DeleteAccountRequest;
|
||||
import org.signal.chat.account.DeleteAccountResponse;
|
||||
import org.signal.chat.account.DeleteUsernameHashRequest;
|
||||
import org.signal.chat.account.DeleteUsernameLinkRequest;
|
||||
import org.signal.chat.account.ExternalServiceCredentials;
|
||||
import org.signal.chat.account.GetAccountDataReportRequest;
|
||||
import org.signal.chat.account.GetAccountDataReportResponse;
|
||||
import org.signal.chat.account.GetAccountIdentityRequest;
|
||||
import org.signal.chat.account.GetAccountIdentityResponse;
|
||||
import org.signal.chat.account.GetEntitlementsRequest;
|
||||
import org.signal.chat.account.GetEntitlementsResponse;
|
||||
import org.signal.chat.account.RegistrationLockFailure;
|
||||
import org.signal.chat.account.ReserveUsernameHashRequest;
|
||||
import org.signal.chat.account.ReserveUsernameHashResponse;
|
||||
import org.signal.chat.account.SetDiscoverableByPhoneNumberRequest;
|
||||
@@ -60,31 +69,50 @@ import org.signal.chat.account.SetUsernameLinkRequest;
|
||||
import org.signal.chat.account.SetUsernameLinkResponse;
|
||||
import org.signal.chat.account.SetZkCredentialKeyRequest;
|
||||
import org.signal.chat.account.SetZkCredentialKeyResponse;
|
||||
import org.signal.chat.account.StaleDevices;
|
||||
import org.signal.chat.account.UsernameNotAvailable;
|
||||
import org.signal.chat.common.AccountIdentifiers;
|
||||
import org.signal.chat.common.EcSignedPreKey;
|
||||
import org.signal.chat.common.KemSignedPreKey;
|
||||
import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.signal.libsignal.usernames.BaseUsernameException;
|
||||
import org.signal.libsignal.zkgroup.ZkCredentialKeyPair;
|
||||
import org.signal.libsignal.zkgroup.ZkCredentialPublicKey;
|
||||
import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.auth.RecoveryPasswordVerificationFailedException;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockFailureException;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.auth.UnverifiedRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.controllers.AccountController;
|
||||
import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedException;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevices;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.EncryptedUsername;
|
||||
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.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.KeyIdUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableException;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernameReservationNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsTestHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
|
||||
@@ -105,6 +133,9 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
|
||||
private final TestClock testClock = TestClock.pinned(Instant.now());
|
||||
|
||||
@Mock
|
||||
private ChangeNumberManager changeNumberManager;
|
||||
|
||||
@Override
|
||||
protected AccountsGrpcService createServiceBeforeEachTest() {
|
||||
AccountsHelper.setupMockUpdate(accountsManager);
|
||||
@@ -120,7 +151,8 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
rateLimiters,
|
||||
usernameHashZkProofVerifier,
|
||||
registrationRecoveryPasswordsManager,
|
||||
testClock);
|
||||
testClock,
|
||||
changeNumberManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -155,6 +187,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
assertEquals(expectedResponse, authenticatedServiceStub().getAccountIdentity(GetAccountIdentityRequest.newBuilder().build()));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void deleteAccount() {
|
||||
final DeleteAccountResponse ignored =
|
||||
@@ -811,4 +844,199 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
.setVisible(badge.visible())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void changeNumber() throws Exception {
|
||||
final String newNumber = PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
|
||||
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
|
||||
final IdentityKey pniIdentityKey = new IdentityKey(pniIdentityKeyPair.getPublicKey());
|
||||
|
||||
final ECSignedPreKey ecSignedPreKey = KeysHelper.signedECPreKey(1, pniIdentityKeyPair);
|
||||
final KEMSignedPreKey kemSignedPreKey = KeysHelper.signedKEMPreKey(2, pniIdentityKeyPair);
|
||||
|
||||
final byte[] sessionId = TestRandomUtil.nextBytes(16);
|
||||
final UUID updatedPni = UUID.randomUUID();
|
||||
|
||||
final Account updatedAccount = mock(Account.class);
|
||||
when(updatedAccount.getUuid()).thenReturn(AUTHENTICATED_ACI);
|
||||
when(updatedAccount.getNumber()).thenReturn(newNumber);
|
||||
when(updatedAccount.getPhoneNumberIdentifier()).thenReturn(updatedPni);
|
||||
when(updatedAccount.getUsernameHash()).thenReturn(Optional.empty());
|
||||
|
||||
when(changeNumberManager.changeNumber(eq(AUTHENTICATED_ACI), any(), any(), any(), eq(newNumber),
|
||||
any(), any(), any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(updatedAccount);
|
||||
|
||||
final ChangeNumberResponse response = authenticatedServiceStub().changeNumber(ChangeNumberRequest.newBuilder()
|
||||
.setSessionId(ByteString.copyFrom(sessionId))
|
||||
.setNumber(newNumber)
|
||||
.setRegistrationLock(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
|
||||
.setPniIdentityKey(ByteString.copyFrom(pniIdentityKey.serialize()))
|
||||
.putDevicePniSignedPreKeys(Device.PRIMARY_ID, EcSignedPreKey.newBuilder()
|
||||
.setKeyId(KeyIdUtil.toUnsignedInt(ecSignedPreKey.keyId()))
|
||||
.setPublicKey(ByteString.copyFrom(ecSignedPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(ecSignedPreKey.signature()))
|
||||
.build())
|
||||
.putDevicePniPqLastResortPreKeys(Device.PRIMARY_ID, KemSignedPreKey.newBuilder()
|
||||
.setKeyId(KeyIdUtil.toUnsignedInt(kemSignedPreKey.keyId()))
|
||||
.setPublicKey(ByteString.copyFrom(kemSignedPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(kemSignedPreKey.signature()))
|
||||
.build())
|
||||
.putPniRegistrationIds(Device.PRIMARY_ID, 17)
|
||||
.build());
|
||||
|
||||
final ChangeNumberResponse expectedResponse = ChangeNumberResponse.newBuilder()
|
||||
.setAccountIdentifiers(AccountIdentifiers.newBuilder()
|
||||
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(AUTHENTICATED_ACI)))
|
||||
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new PniServiceIdentifier(updatedPni)))
|
||||
.setE164(newNumber))
|
||||
.build();
|
||||
|
||||
assertEquals(expectedResponse, response);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void changeNumberErrorResponse(final Exception exceptionToThrow, final ChangeNumberResponse expectedResponse)
|
||||
throws Exception {
|
||||
|
||||
when(changeNumberManager.changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any()))
|
||||
.thenThrow(exceptionToThrow);
|
||||
|
||||
assertEquals(expectedResponse, authenticatedServiceStub().changeNumber(createChangeNumberRequest()));
|
||||
}
|
||||
|
||||
private static List<Arguments> changeNumberErrorResponse() {
|
||||
return List.of(
|
||||
Arguments.argumentSet("Invalid registration session",
|
||||
new InvalidRegistrationSessionException("invalid registration session"),
|
||||
ChangeNumberResponse.newBuilder()
|
||||
.setInvalidRegistrationSession(FailedPrecondition.newBuilder().setDescription("invalid registration session"))
|
||||
.build()),
|
||||
Arguments.argumentSet("Unverified registration session",
|
||||
new UnverifiedRegistrationSessionException(),
|
||||
ChangeNumberResponse.newBuilder()
|
||||
.setUnverifiedRegistrationSession(FailedPrecondition.getDefaultInstance())
|
||||
.build()),
|
||||
Arguments.argumentSet("Recovery password verification failed",
|
||||
new RecoveryPasswordVerificationFailedException(),
|
||||
ChangeNumberResponse.newBuilder()
|
||||
.setRecoveryPasswordVerificationFailed(FailedPrecondition.getDefaultInstance())
|
||||
.build()),
|
||||
Arguments.argumentSet("Message too large",
|
||||
new MessageTooLargeException(),
|
||||
ChangeNumberResponse.newBuilder()
|
||||
.setMessageTooLarge(FailedPrecondition.newBuilder().setDescription("one or more device messages was too large"))
|
||||
.build()));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void changeNumberUnavailable(final Exception exceptionToThrow) throws Exception {
|
||||
when(changeNumberManager.changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any()))
|
||||
.thenThrow(exceptionToThrow);
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
GrpcTestUtils.assertStatusException(Status.UNAVAILABLE,
|
||||
() -> authenticatedServiceStub().changeNumber(createChangeNumberRequest()));
|
||||
}
|
||||
|
||||
private static List<Arguments> changeNumberUnavailable() {
|
||||
return List.of(
|
||||
Arguments.argumentSet("Message delivery not allowed", new MessageDeliveryNotAllowedException()),
|
||||
Arguments.argumentSet("Registration service unavailable", new IOException("unavailable")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void changeNumberRegistrationLockFailure() throws Exception {
|
||||
final long timeRemaining = Duration.ofDays(7).toMillis();
|
||||
|
||||
when(changeNumberManager.changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any()))
|
||||
.thenThrow(new RegistrationLockFailureException(new org.whispersystems.textsecuregcm.entities.RegistrationLockFailure(
|
||||
timeRemaining,
|
||||
new org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials("test-username", "test-password"))));
|
||||
|
||||
final ChangeNumberResponse expectedResponse = ChangeNumberResponse.newBuilder()
|
||||
.setRegistrationLockFailure(RegistrationLockFailure.newBuilder()
|
||||
.setTimeRemainingMillis(timeRemaining)
|
||||
.setSvr2Credentials(ExternalServiceCredentials.newBuilder()
|
||||
.setUsername("test-username")
|
||||
.setPassword("test-password")))
|
||||
.build();
|
||||
|
||||
assertEquals(expectedResponse, authenticatedServiceStub().changeNumber(createChangeNumberRequest()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void changeNumberStaleDevices() throws Exception {
|
||||
final byte staleDeviceId = (byte) (Device.PRIMARY_ID + 1);
|
||||
|
||||
when(changeNumberManager.changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any()))
|
||||
.thenThrow(new MismatchedDevicesException(new MismatchedDevices(Set.of(), Set.of(), Set.of(staleDeviceId))));
|
||||
|
||||
final ChangeNumberResponse expectedResponse = ChangeNumberResponse.newBuilder()
|
||||
.setStaleDevices(StaleDevices.newBuilder().addStaleDevices(staleDeviceId))
|
||||
.build();
|
||||
|
||||
assertEquals(expectedResponse, authenticatedServiceStub().changeNumber(createChangeNumberRequest()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void changeNumberMismatchedDevices() throws Exception {
|
||||
final byte missingDeviceId = (byte) (Device.PRIMARY_ID + 1);
|
||||
final byte extraDeviceId = (byte) (Device.PRIMARY_ID + 2);
|
||||
|
||||
when(changeNumberManager.changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any()))
|
||||
.thenThrow(new MismatchedDevicesException(new MismatchedDevices(Set.of(missingDeviceId), Set.of(extraDeviceId), Set.of())));
|
||||
|
||||
final ChangeNumberResponse expectedResponse = ChangeNumberResponse.newBuilder()
|
||||
.setMismatchedDevices(org.signal.chat.messages.MismatchedDevices.newBuilder()
|
||||
.setServiceIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(AUTHENTICATED_ACI)))
|
||||
.addMissingDevices(missingDeviceId)
|
||||
.addExtraDevices(extraDeviceId))
|
||||
.build();
|
||||
|
||||
assertEquals(expectedResponse, authenticatedServiceStub().changeNumber(createChangeNumberRequest()));
|
||||
}
|
||||
|
||||
private static ChangeNumberRequest createChangeNumberRequest() {
|
||||
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
|
||||
final IdentityKey pniIdentityKey = new IdentityKey(pniIdentityKeyPair.getPublicKey());
|
||||
|
||||
final ECSignedPreKey ecSignedPreKey = KeysHelper.signedECPreKey(1, pniIdentityKeyPair);
|
||||
final KEMSignedPreKey kemSignedPreKey = KeysHelper.signedKEMPreKey(2, pniIdentityKeyPair);
|
||||
|
||||
return ChangeNumberRequest.newBuilder()
|
||||
.setSessionId(ByteString.copyFrom(TestRandomUtil.nextBytes(16)))
|
||||
.setNumber(PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164))
|
||||
.setPniIdentityKey(ByteString.copyFrom(pniIdentityKey.serialize()))
|
||||
.putDevicePniSignedPreKeys(Device.PRIMARY_ID, EcSignedPreKey.newBuilder()
|
||||
.setKeyId(KeyIdUtil.toUnsignedInt(ecSignedPreKey.keyId()))
|
||||
.setPublicKey(ByteString.copyFrom(ecSignedPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(ecSignedPreKey.signature()))
|
||||
.build())
|
||||
.putDevicePniPqLastResortPreKeys(Device.PRIMARY_ID, KemSignedPreKey.newBuilder()
|
||||
.setKeyId(KeyIdUtil.toUnsignedInt(kemSignedPreKey.keyId()))
|
||||
.setPublicKey(ByteString.copyFrom(kemSignedPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(kemSignedPreKey.signature()))
|
||||
.build())
|
||||
.putPniRegistrationIds(Device.PRIMARY_ID, 17)
|
||||
.build();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ArgumentsSource(AccountsTestHelper.AccountsDataReportArgumentProvider.class)
|
||||
void getAccountDataReport(final Account account, final String expectedTextAfterHeader) {
|
||||
getMockAuthenticationInterceptor().setAuthenticatedDevice(account.getUuid(), Device.PRIMARY_ID);
|
||||
when(accountsManager.getByAccountIdentifier(account.getUuid())).thenReturn(Optional.of(account));
|
||||
|
||||
final GetAccountDataReportResponse response =
|
||||
authenticatedServiceStub().getAccountDataReport(GetAccountDataReportRequest.newBuilder().build());
|
||||
|
||||
final String actualText = response.getText();
|
||||
AccountsTestHelper.verifyAccountDataReportText(actualText, expectedTextAfterHeader);
|
||||
}
|
||||
}
|
||||
+13
-13
@@ -20,8 +20,6 @@ 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.Collection;
|
||||
@@ -41,6 +39,7 @@ 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.RegistrationLockFailureException;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedException;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
@@ -50,6 +49,7 @@ 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.entities.RegistrationLockFailure;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
@@ -85,8 +85,8 @@ public class ChangeNumberManagerTest {
|
||||
changeNumberWaitingPeriodManager = mock(ChangeNumberWaitingPeriodManager.class);
|
||||
rateLimiter = mock(RateLimiter.class);
|
||||
|
||||
when(phoneVerificationTokenManager.verify(any(), any(), any(), any())).thenAnswer(invocation -> {
|
||||
final byte[] sessionId = invocation.getArgument(2);
|
||||
when(phoneVerificationTokenManager.verify(any(), any(), any(), any(), any(), any())).thenAnswer(invocation -> {
|
||||
final byte[] sessionId = invocation.getArgument(4);
|
||||
|
||||
return sessionId != null
|
||||
? PhoneVerificationRequest.VerificationType.SESSION
|
||||
@@ -164,7 +164,7 @@ public class ChangeNumberManagerTest {
|
||||
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));
|
||||
changeNumberManager.changeNumber(accountIdentifier, null, null, null, targetNumber, pniIdentityKey, ecSignedPreKeys, kemLastResortPreKeys, Collections.emptyList(), Collections.emptyMap(), null, null, null);
|
||||
verify(accountsManager).changeNumber(accountIdentifier, targetNumber, pniIdentityKey, ecSignedPreKeys, kemLastResortPreKeys, Collections.emptyMap());
|
||||
verify(messageSender, never()).sendMessages(any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
@@ -233,7 +233,7 @@ public class ChangeNumberManagerTest {
|
||||
kemLastResortPreKeys,
|
||||
List.of(incomingMessage),
|
||||
registrationIds,
|
||||
mock(ContainerRequestContext.class));
|
||||
null, null, null);
|
||||
|
||||
verify(accountsManager).changeNumber(aci,
|
||||
targetNumber,
|
||||
@@ -288,7 +288,7 @@ public class ChangeNumberManagerTest {
|
||||
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));
|
||||
changeNumberManager.changeNumber(accountIdentifier, null, null, null, targetNumber, pniIdentityKey, ecSignedPreKeys, kemLastResortPreKeys, Collections.emptyList(), Collections.emptyMap(), null, null, null);
|
||||
|
||||
verifyNoInteractions(rateLimiter);
|
||||
verifyNoInteractions(phoneVerificationTokenManager);
|
||||
@@ -340,7 +340,7 @@ public class ChangeNumberManagerTest {
|
||||
kemLastResortPreKeys,
|
||||
Collections.emptyList(),
|
||||
Collections.emptyMap(),
|
||||
mock(ContainerRequestContext.class)));
|
||||
null, null, null));
|
||||
|
||||
verify(accountsManager, never()).changeNumber(any(), any(), any(), any(), any(), any());
|
||||
verify(messageSender, never()).sendMessages(any(), any(), any(), any(), any(), any());
|
||||
@@ -348,7 +348,7 @@ public class ChangeNumberManagerTest {
|
||||
|
||||
@Test
|
||||
void changeNumberRegistrationLockFailed()
|
||||
throws MismatchedDevicesException, InterruptedException, MessageTooLargeException, RateLimitExceededException, MessageDeliveryNotAllowedException {
|
||||
throws Exception {
|
||||
final String originalNumber = PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("DE"), PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
|
||||
@@ -378,10 +378,10 @@ public class ChangeNumberManagerTest {
|
||||
when(accountsManager.getAccountsForChangeNumber(eq(accountIdentifier), any()))
|
||||
.thenReturn(new Pair<>(account, Optional.of(existingAccount)));
|
||||
|
||||
doThrow(new WebApplicationException(423))
|
||||
doThrow(new RegistrationLockFailureException(new RegistrationLockFailure(0L, null)))
|
||||
.when(registrationLockVerificationManager).verifyRegistrationLock(eq(existingAccount), any(), any(), any(), any());
|
||||
|
||||
assertThrows(WebApplicationException.class, () -> changeNumberManager.changeNumber(accountIdentifier,
|
||||
assertThrows(RegistrationLockFailureException.class, () -> changeNumberManager.changeNumber(accountIdentifier,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
@@ -391,7 +391,7 @@ public class ChangeNumberManagerTest {
|
||||
kemLastResortPreKeys,
|
||||
Collections.emptyList(),
|
||||
Collections.emptyMap(),
|
||||
mock(ContainerRequestContext.class)));
|
||||
null, null, null));
|
||||
|
||||
verify(accountsManager, never()).changeNumber(any(), any(), any(), any(), any(), any());
|
||||
verify(messageSender, never()).sendMessages(any(), any(), any(), any(), any(), any());
|
||||
@@ -445,7 +445,7 @@ public class ChangeNumberManagerTest {
|
||||
kemLastResortPreKeys,
|
||||
Collections.emptyList(),
|
||||
Collections.emptyMap(),
|
||||
mock(ContainerRequestContext.class));
|
||||
null, null, null);
|
||||
if (expectRateLimited) {
|
||||
final RateLimitExceededException e = assertThrows(RateLimitExceededException.class, changeNumberOperation);
|
||||
assertEquals(waitingPeriod, e.getRetryDuration().orElseThrow());
|
||||
|
||||
+196
@@ -0,0 +1,196 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.tests.util;
|
||||
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.ArgumentsProvider;
|
||||
import org.junit.jupiter.params.support.ParameterDeclarations;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class AccountsTestHelper {
|
||||
|
||||
public static class AccountsDataReportArgumentProvider implements ArgumentsProvider {
|
||||
|
||||
@Override
|
||||
public Stream<? extends Arguments> provideArguments(final ParameterDeclarations parameters,
|
||||
final ExtensionContext context) {
|
||||
|
||||
final String exampleNumber1 = toE164(PhoneNumberUtil.getInstance().getExampleNumber("ES"));
|
||||
final String account2PhoneNumber = toE164(PhoneNumberUtil.getInstance().getExampleNumber("AU"));
|
||||
final String account3PhoneNumber = toE164(PhoneNumberUtil.getInstance().getExampleNumber("IN"));
|
||||
|
||||
final Instant account1Device1Created = Instant.ofEpochSecond(1669323142); // 2022-11-24T20:52:22Z
|
||||
final Instant account1Device2Created = Instant.ofEpochSecond(1679155122); // 2023-03-18T15:58:42Z
|
||||
final Instant account1Device1LastSeen = Instant.ofEpochMilli(Util.todayInMillis());
|
||||
final Instant account1Device2LastSeen = Instant.ofEpochSecond(1678838400); // 2023-03-15T00:00:00Z
|
||||
|
||||
final Instant account2Device1Created = Instant.ofEpochSecond(1659123001); // 2022-07-29T19:30:01Z
|
||||
final Instant account2Device1LastSeen = Instant.ofEpochMilli(Util.todayInMillis());
|
||||
final Instant badgeAExpiration = Instant.now().plus(Duration.ofDays(21)).truncatedTo(ChronoUnit.SECONDS);
|
||||
|
||||
final Instant account3Device1Created = Instant.ofEpochSecond(1639923487); // 2021-12-19T14:18:07Z
|
||||
final Instant account3Device1LastSeen = Instant.ofEpochMilli(Util.todayInMillis());
|
||||
final Instant badgeBExpiration = Instant.now().plus(Duration.ofDays(21)).truncatedTo(ChronoUnit.SECONDS);
|
||||
final Instant badgeCExpiration = Instant.now().plus(Duration.ofDays(24)).truncatedTo(ChronoUnit.SECONDS);
|
||||
|
||||
return Stream.of(
|
||||
Arguments.of(
|
||||
buildTestAccountForDataReport(UUID.randomUUID(), exampleNumber1,
|
||||
true, true,
|
||||
Collections.emptyList(),
|
||||
List.of(new DeviceData(Device.PRIMARY_ID, account1Device1LastSeen, account1Device1Created, null),
|
||||
new DeviceData((byte) 2, account1Device2LastSeen, account1Device2Created, "OWP"))),
|
||||
String.format("""
|
||||
# Account
|
||||
Phone number: %s
|
||||
Allow sealed sender from anyone: true
|
||||
Find account by phone number: true
|
||||
Badges: None
|
||||
|
||||
# Devices
|
||||
- ID: 1
|
||||
Created: 2022-11-24T20:52:22Z
|
||||
Last seen: %s
|
||||
User-agent: null
|
||||
- ID: 2
|
||||
Created: 2023-03-18T15:58:42Z
|
||||
Last seen: 2023-03-15T00:00:00Z
|
||||
User-agent: OWP
|
||||
""",
|
||||
exampleNumber1,
|
||||
account1Device1LastSeen)
|
||||
),
|
||||
Arguments.of(
|
||||
buildTestAccountForDataReport(UUID.randomUUID(), account2PhoneNumber,
|
||||
false, true,
|
||||
List.of(new AccountBadge("badge_a", badgeAExpiration, true)),
|
||||
List.of(new DeviceData(Device.PRIMARY_ID, account2Device1LastSeen, account2Device1Created, "OWI"))),
|
||||
String.format("""
|
||||
# Account
|
||||
Phone number: %s
|
||||
Allow sealed sender from anyone: false
|
||||
Find account by phone number: true
|
||||
Badges:
|
||||
- ID: badge_a
|
||||
Expiration: %s
|
||||
Visible: true
|
||||
|
||||
# Devices
|
||||
- ID: 1
|
||||
Created: 2022-07-29T19:30:01Z
|
||||
Last seen: %s
|
||||
User-agent: OWI
|
||||
""", account2PhoneNumber,
|
||||
badgeAExpiration,
|
||||
account2Device1LastSeen)
|
||||
),
|
||||
Arguments.of(
|
||||
buildTestAccountForDataReport(UUID.randomUUID(), account3PhoneNumber,
|
||||
true, false,
|
||||
List.of(
|
||||
new AccountBadge("badge_b", badgeBExpiration, true),
|
||||
new AccountBadge("badge_c", badgeCExpiration, false)),
|
||||
List.of(new DeviceData(Device.PRIMARY_ID, account3Device1LastSeen, account3Device1Created, "OWA"))),
|
||||
String.format("""
|
||||
# Account
|
||||
Phone number: %s
|
||||
Allow sealed sender from anyone: true
|
||||
Find account by phone number: false
|
||||
Badges:
|
||||
- ID: badge_b
|
||||
Expiration: %s
|
||||
Visible: true
|
||||
- ID: badge_c
|
||||
Expiration: %s
|
||||
Visible: false
|
||||
|
||||
# Devices
|
||||
- ID: 1
|
||||
Created: 2021-12-19T14:18:07Z
|
||||
Last seen: %s
|
||||
User-agent: OWA
|
||||
""", account3PhoneNumber,
|
||||
badgeBExpiration,
|
||||
badgeCExpiration,
|
||||
account3Device1LastSeen)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
public static Account buildTestAccountForDataReport(final UUID aci, final String number,
|
||||
final boolean unrestrictedUnidentifiedAccess, final boolean discoverableByPhoneNumber,
|
||||
final List<AccountBadge> badges, final List<DeviceData> devices) {
|
||||
|
||||
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
|
||||
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
|
||||
|
||||
final Account account = new Account();
|
||||
account.setUuid(aci);
|
||||
account.setNumber(number, UUID.randomUUID());
|
||||
account.setUnrestrictedUnidentifiedAccess(unrestrictedUnidentifiedAccess);
|
||||
account.setDiscoverableByPhoneNumber(discoverableByPhoneNumber);
|
||||
account.setBadges(Clock.systemUTC(), new ArrayList<>(badges));
|
||||
account.setIdentityKey(new IdentityKey(aciIdentityKeyPair.getPublicKey()));
|
||||
account.setPhoneNumberIdentityKey(new IdentityKey(pniIdentityKeyPair.getPublicKey()));
|
||||
|
||||
assert !devices.isEmpty();
|
||||
|
||||
final SaltedTokenHash passwordTokenHash = SaltedTokenHash.generateFor("password");
|
||||
|
||||
devices.forEach(deviceData -> {
|
||||
final Device device = new Device();
|
||||
device.setId(deviceData.id());
|
||||
device.setAuthTokenHash(passwordTokenHash);
|
||||
device.setFetchesMessages(true);
|
||||
device.setLastSeen(deviceData.lastSeen().toEpochMilli());
|
||||
device.setCreated(deviceData.created().toEpochMilli());
|
||||
device.setUserAgent(deviceData.userAgent());
|
||||
account.addDevice(device);
|
||||
});
|
||||
|
||||
return account;
|
||||
}
|
||||
|
||||
private static String toE164(final Phonenumber.PhoneNumber phoneNumber) {
|
||||
return PhoneNumberUtil.getInstance().format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
}
|
||||
|
||||
public record DeviceData(byte id, Instant lastSeen, Instant created, @Nullable String userAgent) {
|
||||
}
|
||||
}
|
||||
|
||||
public static void verifyAccountDataReportText(final String actualText, final String expectedTextAfterHeader) {
|
||||
final int headerEnd = actualText.indexOf("# Account");
|
||||
assertEquals(expectedTextAfterHeader, actualText.substring(headerEnd));
|
||||
|
||||
final String actualHeader = actualText.substring(0, headerEnd);
|
||||
assertTrue(actualHeader.matches(
|
||||
"Report ID: [a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}\nReport timestamp: \\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z\n\n"));
|
||||
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user