mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-11-30 01:16:50 +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
@@ -210,6 +210,7 @@ import org.whispersystems.textsecuregcm.mappers.JsonMappingExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.NonNormalizedPhoneNumberExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.ObsoletePhoneNumberFormatExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.RegistrationLockFailureExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.ServerRejectedExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
|
||||
@@ -1069,8 +1070,15 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getDeliveryCertificate().expiresDays(),
|
||||
config.getDeliveryCertificate().embedSigner());
|
||||
|
||||
final PhoneVerificationTokenManager phoneVerificationTokenManager = new PhoneVerificationTokenManager(
|
||||
phoneNumberIdentifiers, registrationServiceClient, registrationRecoveryPasswordsManager, registrationRecoveryChecker);
|
||||
|
||||
final ChangeNumberManager changeNumberManager = new ChangeNumberManager(messageSender, accountsManager,
|
||||
phoneVerificationTokenManager, registrationLockVerificationManager, rateLimiters,
|
||||
changeNumberWaitingPeriodManager, Clock.systemUTC());
|
||||
|
||||
final List<ServerServiceDefinition> authenticatedServices = Stream.of(
|
||||
new AccountsGrpcService(accountsManager, rateLimiters, usernameHashZkProofVerifier, registrationRecoveryPasswordsManager, Clock.systemUTC()),
|
||||
new AccountsGrpcService(accountsManager, rateLimiters, usernameHashZkProofVerifier, registrationRecoveryPasswordsManager, Clock.systemUTC(), changeNumberManager),
|
||||
new CallingGrpcService(cloudflareTurnCredentialsManager, rateLimiters),
|
||||
new CredentialsGrpcService(accountsManager, certificateGenerator, zkAuthOperations, callingGenericZkSecretParams, rateLimiters, Clock.systemUTC(), ExternalServiceDefinitions.createExternalServiceList(config, Clock.systemUTC())),
|
||||
new KeysGrpcService(accountsManager, keysManager, rateLimiters),
|
||||
@@ -1217,13 +1225,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
final PersistentTimer persistentTimer = new PersistentTimer(rateLimitersCluster, clock);
|
||||
|
||||
final PhoneVerificationTokenManager phoneVerificationTokenManager = new PhoneVerificationTokenManager(
|
||||
phoneNumberIdentifiers, registrationServiceClient, registrationRecoveryPasswordsManager, registrationRecoveryChecker);
|
||||
|
||||
final ChangeNumberManager changeNumberManager = new ChangeNumberManager(messageSender, accountsManager,
|
||||
phoneVerificationTokenManager, registrationLockVerificationManager, rateLimiters,
|
||||
changeNumberWaitingPeriodManager, Clock.systemUTC());
|
||||
|
||||
final List<Object> commonControllers = Lists.newArrayList(
|
||||
new AccountController(accountsManager, rateLimiters, registrationRecoveryPasswordsManager,
|
||||
usernameHashZkProofVerifier),
|
||||
@@ -1340,7 +1341,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new RegistrationServiceSenderExceptionMapper(),
|
||||
new SubscriptionExceptionMapper(),
|
||||
new BackupExceptionMapper(),
|
||||
new JsonMappingExceptionMapper()
|
||||
new JsonMappingExceptionMapper(),
|
||||
new RegistrationLockFailureExceptionMapper()
|
||||
).forEach(exceptionMapper -> {
|
||||
environment.jersey().register(exceptionMapper);
|
||||
webSocketEnvironment.jersey().register(exceptionMapper);
|
||||
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
|
||||
|
||||
public class InvalidRegistrationSessionException extends NoStackTraceException {
|
||||
|
||||
public InvalidRegistrationSessionException(final String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+29
-25
@@ -7,12 +7,7 @@ package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
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 jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.Duration;
|
||||
import java.util.UUID;
|
||||
@@ -55,23 +50,27 @@ public class PhoneVerificationTokenManager {
|
||||
* Checks if a {@link PhoneVerificationRequest} has a token that verifies the caller has confirmed access to the e164
|
||||
* number
|
||||
*
|
||||
* @param requestContext the container request context
|
||||
* @param number the e164 presented for verification
|
||||
* @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
|
||||
* @throws InvalidRegistrationSessionException if the number does not match the sessionId’s number, or the remote service rejects
|
||||
* the session ID as invalid
|
||||
* @throws NotAuthorizedException if the session is not verified
|
||||
* @throws ForbiddenException if the recovery password is not valid
|
||||
* @throws UnverifiedRegistrationSessionException if the session is not verified
|
||||
* @throws RecoveryPasswordVerificationFailedException if the recovery password is not valid
|
||||
* @throws InterruptedException if verification did not complete before a timeout
|
||||
* @throws IOException if there was an error talking to registration service
|
||||
*/
|
||||
public PhoneVerificationRequest.VerificationType verify(final ContainerRequestContext requestContext,
|
||||
public PhoneVerificationRequest.VerificationType verify(
|
||||
final String number,
|
||||
@Nullable final String userAgent,
|
||||
@Nullable final String acceptLanguage,
|
||||
@Nullable final String mostRecentProxy,
|
||||
@Nullable final byte[] sessionId,
|
||||
@Nullable final byte[] recoveryPassword) throws InterruptedException {
|
||||
@Nullable final byte[] recoveryPassword)
|
||||
throws InterruptedException, UnverifiedRegistrationSessionException, InvalidRegistrationSessionException, IOException, RecoveryPasswordVerificationFailedException {
|
||||
|
||||
if ((sessionId == null) == (recoveryPassword == null)) {
|
||||
throw new IllegalArgumentException("Exactly one of session ID or recovery password must non-null");
|
||||
@@ -83,40 +82,45 @@ public class PhoneVerificationTokenManager {
|
||||
|
||||
switch (verificationType) {
|
||||
case SESSION -> verifyBySessionId(number, sessionId);
|
||||
case RECOVERY_PASSWORD -> verifyByRecoveryPassword(requestContext, number, recoveryPassword);
|
||||
case RECOVERY_PASSWORD -> verifyByRecoveryPassword(number, userAgent, acceptLanguage, mostRecentProxy, recoveryPassword);
|
||||
}
|
||||
|
||||
return verificationType;
|
||||
}
|
||||
|
||||
private void verifyBySessionId(final String number, final byte[] sessionId) {
|
||||
private void verifyBySessionId(final String number, final byte[] sessionId)
|
||||
throws UnverifiedRegistrationSessionException, InvalidRegistrationSessionException, IOException {
|
||||
try {
|
||||
final RegistrationServiceSession session = registrationServiceClient
|
||||
.getSession(sessionId, REGISTRATION_RPC_TIMEOUT)
|
||||
.orElseThrow(() -> new NotAuthorizedException("session not verified"));
|
||||
.orElseThrow(UnverifiedRegistrationSessionException::new);
|
||||
|
||||
if (!MessageDigest.isEqual(number.getBytes(), session.number().getBytes())) {
|
||||
throw new BadRequestException("number does not match session");
|
||||
throw new InvalidRegistrationSessionException("number does not match session");
|
||||
}
|
||||
if (!session.verified()) {
|
||||
throw new NotAuthorizedException("session not verified");
|
||||
throw new UnverifiedRegistrationSessionException();
|
||||
}
|
||||
} catch (final StatusRuntimeException e) {
|
||||
if (e.getStatus().getCode() == Status.Code.INVALID_ARGUMENT) {
|
||||
throw new BadRequestException();
|
||||
throw new InvalidRegistrationSessionException(e.getMessage());
|
||||
}
|
||||
|
||||
logger.error("Registration service failure", e);
|
||||
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE);
|
||||
throw new IOException("Registration service failure", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void verifyByRecoveryPassword(final ContainerRequestContext requestContext,
|
||||
private void verifyByRecoveryPassword(
|
||||
final String number,
|
||||
final byte[] recoveryPassword) throws InterruptedException {
|
||||
@Nullable final String userAgent,
|
||||
@Nullable final String acceptLanguage,
|
||||
@Nullable final String mostRecentProxy,
|
||||
final byte[] recoveryPassword)
|
||||
throws InterruptedException, IOException, RecoveryPasswordVerificationFailedException {
|
||||
|
||||
if (!registrationRecoveryChecker.checkRegistrationRecoveryAttempt(requestContext, number)) {
|
||||
throw new ForbiddenException("recoveryPassword couldn't be verified");
|
||||
if (!registrationRecoveryChecker.checkRegistrationRecoveryAttempt(number, userAgent, acceptLanguage, mostRecentProxy)) {
|
||||
throw new RecoveryPasswordVerificationFailedException();
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -126,10 +130,10 @@ public class PhoneVerificationTokenManager {
|
||||
final boolean verified = registrationRecoveryPasswordsManager.verify(phoneNumberIdentifier, recoveryPassword);
|
||||
|
||||
if (!verified) {
|
||||
throw new ForbiddenException("recoveryPassword couldn't be verified");
|
||||
throw new RecoveryPasswordVerificationFailedException();
|
||||
}
|
||||
} catch (final ExecutionException | TimeoutException e) {
|
||||
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE);
|
||||
throw new IOException("registration service unavailable", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
|
||||
|
||||
public class RecoveryPasswordVerificationFailedException extends NoStackTraceException {
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
|
||||
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
|
||||
|
||||
public class RegistrationLockFailureException extends NoStackTraceException {
|
||||
|
||||
private final RegistrationLockFailure failure;
|
||||
|
||||
public RegistrationLockFailureException(final RegistrationLockFailure failure) {
|
||||
super();
|
||||
this.failure = failure;
|
||||
}
|
||||
|
||||
public RegistrationLockFailure getFailure() {
|
||||
return failure;
|
||||
}
|
||||
}
|
||||
+6
-9
@@ -12,8 +12,6 @@ import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import jakarta.ws.rs.WebApplicationException;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
@@ -80,13 +78,13 @@ public class RegistrationLockVerificationManager {
|
||||
* @param account
|
||||
* @param clientRegistrationLock
|
||||
* @throws RateLimitExceededException
|
||||
* @throws WebApplicationException
|
||||
* @throws RegistrationLockFailureException
|
||||
*/
|
||||
public void verifyRegistrationLock(final Account account, @Nullable final String clientRegistrationLock,
|
||||
final String userAgent,
|
||||
@Nullable final String userAgent,
|
||||
final Flow flow,
|
||||
final PhoneVerificationRequest.VerificationType phoneVerificationType
|
||||
) throws RateLimitExceededException, WebApplicationException {
|
||||
) throws RateLimitExceededException, RegistrationLockFailureException {
|
||||
|
||||
final Tags expiredTags = Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(REGISTRATION_LOCK_VERIFICATION_FLOW_TAG_NAME, flow.name()),
|
||||
@@ -165,11 +163,10 @@ public class RegistrationLockVerificationManager {
|
||||
Metrics.counter(CHALLENGED_DEVICE_NOT_PUSH_REGISTERED_COUNTER_NAME).increment();
|
||||
}
|
||||
|
||||
throw new WebApplicationException(Response.status(FAILURE_HTTP_STATUS)
|
||||
.entity(new RegistrationLockFailure(
|
||||
throw new RegistrationLockFailureException(
|
||||
new RegistrationLockFailure(
|
||||
existingRegistrationLock.getTimeRemaining().toMillis(),
|
||||
svr2FailureCredentials(existingRegistrationLock, updatedAccount)))
|
||||
.build());
|
||||
svr2FailureCredentials(existingRegistrationLock, updatedAccount)));
|
||||
}
|
||||
|
||||
rateLimiters.getPinLimiter().clear(phoneNumber);
|
||||
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
|
||||
|
||||
public class UnverifiedRegistrationSessionException extends NoStackTraceException {
|
||||
}
|
||||
+20
-2
@@ -19,6 +19,7 @@ import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.ForbiddenException;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.HeaderParam;
|
||||
import jakarta.ws.rs.NotAuthorizedException;
|
||||
import jakarta.ws.rs.PUT;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.Produces;
|
||||
@@ -28,11 +29,16 @@ import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.ChangesPhoneNumber;
|
||||
import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.auth.RecoveryPasswordVerificationFailedException;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockFailureException;
|
||||
import org.whispersystems.textsecuregcm.auth.UnverifiedRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountDataReportResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ChangeNumberRequest;
|
||||
@@ -40,6 +46,7 @@ import org.whispersystems.textsecuregcm.entities.MismatchedDevicesResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneNumberDiscoverabilityRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
|
||||
import org.whispersystems.textsecuregcm.entities.StaleDevicesResponse;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
@@ -80,7 +87,8 @@ public class AccountControllerV2 {
|
||||
public AccountIdentityResponse changeNumber(@Auth final AuthenticatedDevice authenticatedDevice,
|
||||
@NotNull @Valid final ChangeNumberRequest request,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgentString,
|
||||
@Context final ContainerRequestContext requestContext) throws RateLimitExceededException, InterruptedException {
|
||||
@Context final ContainerRequestContext requestContext)
|
||||
throws RateLimitExceededException, InterruptedException, RegistrationLockFailureException {
|
||||
|
||||
if (authenticatedDevice.deviceId() != Device.PRIMARY_ID) {
|
||||
throw new ForbiddenException();
|
||||
@@ -102,7 +110,9 @@ public class AccountControllerV2 {
|
||||
request.devicePniPqLastResortPrekeys(),
|
||||
request.deviceMessages(),
|
||||
request.pniRegistrationIds(),
|
||||
requestContext);
|
||||
userAgentString,
|
||||
requestContext.getHeaderString(HttpHeaders.ACCEPT_LANGUAGE),
|
||||
(String) requestContext.getProperty(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME));
|
||||
|
||||
return AccountIdentityResponseBuilder.fromAccount(updatedAccount);
|
||||
} catch (final MismatchedDevicesException e) {
|
||||
@@ -124,6 +134,14 @@ public class AccountControllerV2 {
|
||||
throw new WebApplicationException(Response.Status.REQUEST_ENTITY_TOO_LARGE);
|
||||
} catch (final MessageDeliveryNotAllowedException e) {
|
||||
throw new ServiceUnavailableException();
|
||||
} catch (final UnverifiedRegistrationSessionException e) {
|
||||
throw new NotAuthorizedException("registration session is unverified");
|
||||
} catch (final InvalidRegistrationSessionException e) {
|
||||
throw new BadRequestException(e.getMessage());
|
||||
} catch (final IOException e) {
|
||||
throw new ServiceUnavailableException(e.getMessage());
|
||||
} catch (final RecoveryPasswordVerificationFailedException e) {
|
||||
throw new ForbiddenException("recovery password could not be verified");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+30
-6
@@ -19,16 +19,21 @@ import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.ws.rs.BadRequestException;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.ForbiddenException;
|
||||
import jakarta.ws.rs.HeaderParam;
|
||||
import jakarta.ws.rs.NotAuthorizedException;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.ServiceUnavailableException;
|
||||
import jakarta.ws.rs.WebApplicationException;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
@@ -38,13 +43,18 @@ import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
|
||||
import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RecoveryPasswordVerificationFailedException;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockFailureException;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
import org.whispersystems.textsecuregcm.auth.UnverifiedRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountCreationResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationRequest;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
|
||||
@@ -116,7 +126,8 @@ public class RegistrationController {
|
||||
@HeaderParam(HeaderUtils.X_SIGNAL_AGENT) final String signalAgent,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@NotNull @Valid final RegistrationRequest registrationRequest,
|
||||
@Context final ContainerRequestContext requestContext) throws RateLimitExceededException, InterruptedException {
|
||||
@Context final ContainerRequestContext requestContext)
|
||||
throws RateLimitExceededException, InterruptedException, RegistrationLockFailureException {
|
||||
|
||||
final String number = authorizationHeader.getUsername();
|
||||
final String password = authorizationHeader.getPassword();
|
||||
@@ -134,11 +145,24 @@ public class RegistrationController {
|
||||
|
||||
rateLimiters.getRegistrationLimiter().validate(number);
|
||||
|
||||
final PhoneVerificationRequest.VerificationType verificationType =
|
||||
phoneVerificationTokenManager.verify(requestContext,
|
||||
number,
|
||||
StringUtils.isNotBlank(registrationRequest.sessionId()) ? registrationRequest.decodeSessionId() : null,
|
||||
registrationRequest.recoveryPassword());
|
||||
final PhoneVerificationRequest.VerificationType verificationType;
|
||||
try {
|
||||
verificationType = phoneVerificationTokenManager.verify(
|
||||
number,
|
||||
requestContext.getHeaderString(HttpHeaders.USER_AGENT),
|
||||
requestContext.getHeaderString(HttpHeaders.ACCEPT_LANGUAGE),
|
||||
(String) requestContext.getProperty(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME),
|
||||
StringUtils.isNotBlank(registrationRequest.sessionId()) ? registrationRequest.decodeSessionId() : null,
|
||||
registrationRequest.recoveryPassword());
|
||||
} catch (final UnverifiedRegistrationSessionException e) {
|
||||
throw new NotAuthorizedException("registration session is unverified");
|
||||
} catch (final InvalidRegistrationSessionException e) {
|
||||
throw new BadRequestException(e.getMessage());
|
||||
} catch (final IOException e) {
|
||||
throw new ServiceUnavailableException(e.getMessage());
|
||||
} catch (final RecoveryPasswordVerificationFailedException e) {
|
||||
throw new ForbiddenException("recovery password could not be verified");
|
||||
}
|
||||
|
||||
// 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.
|
||||
|
||||
+1
-1
@@ -28,7 +28,7 @@ public record AccountDataReportResponse(UUID reportId,
|
||||
|
||||
@JsonProperty
|
||||
@Schema(description = "A plaintext representation of the data report")
|
||||
String text() {
|
||||
public String text() {
|
||||
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@ import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import org.whispersystems.textsecuregcm.registration.VerificationSession;
|
||||
|
||||
public record VerificationSessionResponse(
|
||||
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "A URL-safe ID for the session")
|
||||
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "A URL-safe base64-encoded ID for the session")
|
||||
String id,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = "Duration in seconds after which next SMS can be requested for this session")
|
||||
|
||||
+229
-19
@@ -6,14 +6,21 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.io.IOException;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
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;
|
||||
@@ -26,10 +33,14 @@ import org.signal.chat.account.DeleteUsernameHashRequest;
|
||||
import org.signal.chat.account.DeleteUsernameHashResponse;
|
||||
import org.signal.chat.account.DeleteUsernameLinkRequest;
|
||||
import org.signal.chat.account.DeleteUsernameLinkResponse;
|
||||
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;
|
||||
@@ -43,26 +54,45 @@ import org.signal.chat.account.SetUsernameLinkResponse;
|
||||
import org.signal.chat.account.SetZkCredentialKeyRequest;
|
||||
import org.signal.chat.account.SetZkCredentialKeyResponse;
|
||||
import org.signal.chat.account.SimpleAccountsGrpc;
|
||||
import org.signal.chat.account.StaleDevices;
|
||||
import org.signal.chat.account.UsernameNotAvailable;
|
||||
import org.signal.chat.common.AccountIdentifiers;
|
||||
import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.signal.chat.messages.SendMessageType;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.InvalidKeyException;
|
||||
import org.signal.libsignal.usernames.BaseUsernameException;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
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.auth.grpc.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
|
||||
import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedException;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountDataReportResponse;
|
||||
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.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableException;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernameReservationNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.util.RegistrationIdValidator;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
|
||||
|
||||
@@ -75,38 +105,27 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
private final UsernameHashZkProofVerifier usernameHashZkProofVerifier;
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
private final Clock clock;
|
||||
private final ChangeNumberManager changeNumberManager;
|
||||
|
||||
public AccountsGrpcService(final AccountsManager accountsManager,
|
||||
final RateLimiters rateLimiters,
|
||||
final UsernameHashZkProofVerifier usernameHashZkProofVerifier,
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
|
||||
final Clock clock) {
|
||||
final Clock clock,
|
||||
final ChangeNumberManager changeNumberManager) {
|
||||
|
||||
this.accountsManager = accountsManager;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.usernameHashZkProofVerifier = usernameHashZkProofVerifier;
|
||||
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
|
||||
this.clock = clock;
|
||||
this.changeNumberManager = changeNumberManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetAccountIdentityResponse getAccountIdentity(final GetAccountIdentityRequest request) {
|
||||
final Account account = getAuthenticatedAccount();
|
||||
|
||||
final AccountIdentifiers.Builder accountIdentifiersBuilder = AccountIdentifiers.newBuilder()
|
||||
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getUuid())))
|
||||
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new PniServiceIdentifier(account.getPhoneNumberIdentifier())))
|
||||
.setE164(account.getNumber());
|
||||
|
||||
account.getUsernameHash().ifPresent(usernameHash ->
|
||||
accountIdentifiersBuilder.setUsernameHash(ByteString.copyFrom(usernameHash)));
|
||||
|
||||
if (account.getUsernameLinkHandle() != null) {
|
||||
accountIdentifiersBuilder.setUsernameLinkHandle(UUIDUtil.toByteString(account.getUsernameLinkHandle()));
|
||||
}
|
||||
|
||||
return GetAccountIdentityResponse.newBuilder()
|
||||
.setAccountIdentifiers(accountIdentifiersBuilder)
|
||||
.setAccountIdentifiers(buildAccountIdentifiers(getAuthenticatedAccount()))
|
||||
.build();
|
||||
}
|
||||
|
||||
@@ -146,10 +165,8 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
|
||||
@Override
|
||||
public SetRegistrationLockResponse setRegistrationLock(final SetRegistrationLockRequest request) {
|
||||
// In the previous REST-based API, clients would send hex strings directly. For backward compatibility, we
|
||||
// convert the registration lock secret to a lowercase hex string before turning it into a salted hash.
|
||||
final SaltedTokenHash credentials =
|
||||
SaltedTokenHash.generateFor(HexFormat.of().withLowerCase().formatHex(request.getRegistrationLock().toByteArray()));
|
||||
SaltedTokenHash.generateFor(formatRegistrationLock(request.getRegistrationLock().toByteArray()));
|
||||
|
||||
accountsManager.update(AuthenticationUtil.requireAuthenticatedPrimaryDevice().accountIdentifier(),
|
||||
account -> account.setRegistrationLock(credentials.hash(), credentials.salt()));
|
||||
@@ -337,6 +354,178 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChangeNumberResponse changeNumber(final ChangeNumberRequest request)
|
||||
throws RateLimitExceededException, InterruptedException {
|
||||
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedPrimaryDevice();
|
||||
|
||||
final IdentityKey pniIdentityKey;
|
||||
try {
|
||||
pniIdentityKey = new IdentityKey(request.getPniIdentityKey().toByteArray());
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw GrpcExceptions.fieldViolation("pni_identity_key", "invalid identity key");
|
||||
}
|
||||
|
||||
final Map<Byte, ECSignedPreKey> devicePniSignedPreKeys = transformDeviceMap(request.getDevicePniSignedPreKeysMap(),
|
||||
key -> KeysGrpcHelper.checkEcSignedPreKey(key, pniIdentityKey,
|
||||
invalidPublicKeyException("device_pni_signed_pre_keys"),
|
||||
invalidSignatureException("device_pni_signed_pre_keys")));
|
||||
|
||||
final Map<Byte, KEMSignedPreKey> devicePniPqLastResortPreKeys = transformDeviceMap(request.getDevicePniPqLastResortPreKeysMap(),
|
||||
key -> KeysGrpcHelper.checkKemSignedPreKey(key, pniIdentityKey,
|
||||
invalidPublicKeyException("device_pni_pq_last_resort_pre_keys"),
|
||||
invalidSignatureException("device_pni_pq_last_resort_pre_keys")));
|
||||
|
||||
final Map<Byte, Integer> pniRegistrationIds = transformDeviceMap(request.getPniRegistrationIdsMap(), Function.identity());
|
||||
|
||||
if (!pniRegistrationIds.values().stream().allMatch(RegistrationIdValidator::validRegistrationId)) {
|
||||
throw GrpcExceptions.fieldViolation("pni_registration_ids", "invalid registration id");
|
||||
}
|
||||
|
||||
final List<IncomingMessage> deviceMessages = request.getDeviceMessages().getMessagesMap()
|
||||
.entrySet()
|
||||
.stream()
|
||||
.map(entry -> new IncomingMessage(
|
||||
getEnvelopeType(entry.getValue().getType()).getNumber(),
|
||||
(byte) (int) entry.getKey(),
|
||||
entry.getValue().getRegistrationId(),
|
||||
entry.getValue().getPayload().toByteArray()))
|
||||
.toList();
|
||||
|
||||
final byte[] sessionId = request.getVerificationCase() == ChangeNumberRequest.VerificationCase.SESSION_ID
|
||||
? request.getSessionId().toByteArray()
|
||||
: null;
|
||||
|
||||
final byte[] recoveryPassword =
|
||||
request.getVerificationCase() == ChangeNumberRequest.VerificationCase.RECOVERY_PASSWORD
|
||||
? request.getRecoveryPassword().toByteArray()
|
||||
: null;
|
||||
|
||||
final String registrationLock = request.getRegistrationLock().isEmpty() ? null :
|
||||
formatRegistrationLock(request.getRegistrationLock().toByteArray());
|
||||
|
||||
try {
|
||||
final Account updatedAccount = changeNumberManager.changeNumber(
|
||||
authenticatedDevice.accountIdentifier(),
|
||||
sessionId,
|
||||
recoveryPassword,
|
||||
registrationLock,
|
||||
request.getNumber(),
|
||||
pniIdentityKey,
|
||||
devicePniSignedPreKeys,
|
||||
devicePniPqLastResortPreKeys,
|
||||
deviceMessages,
|
||||
pniRegistrationIds,
|
||||
RequestAttributesUtil.getUserAgent().orElse(null),
|
||||
RequestAttributesUtil.getAcceptLanguageRaw(),
|
||||
RequestAttributesUtil.getRemoteAddress().getHostAddress());
|
||||
|
||||
return ChangeNumberResponse.newBuilder()
|
||||
.setAccountIdentifiers(buildAccountIdentifiers(updatedAccount))
|
||||
.build();
|
||||
} catch (final MismatchedDevicesException e) {
|
||||
if (!e.getMismatchedDevices().staleDeviceIds().isEmpty()) {
|
||||
return ChangeNumberResponse.newBuilder()
|
||||
.setStaleDevices(StaleDevices.newBuilder()
|
||||
.addAllStaleDevices(e.getMismatchedDevices().staleDeviceIds().stream().map(Byte::intValue).toList()))
|
||||
.build();
|
||||
}
|
||||
|
||||
return ChangeNumberResponse.newBuilder()
|
||||
.setMismatchedDevices(MessagesGrpcHelper.buildMismatchedDevices(
|
||||
new AciServiceIdentifier(authenticatedDevice.accountIdentifier()), e.getMismatchedDevices()))
|
||||
.build();
|
||||
} catch (final MessageTooLargeException e) {
|
||||
return ChangeNumberResponse.newBuilder()
|
||||
.setMessageTooLarge(FailedPrecondition.newBuilder()
|
||||
.setDescription("one or more device messages was too large"))
|
||||
.build();
|
||||
} catch (final MessageDeliveryNotAllowedException e) {
|
||||
throw GrpcExceptions.unavailable();
|
||||
} catch (final IllegalArgumentException e) {
|
||||
throw GrpcExceptions.invalidArguments(e.getMessage());
|
||||
} catch (final RegistrationLockFailureException e) {
|
||||
final RegistrationLockFailure.Builder failureBuilder = RegistrationLockFailure.newBuilder()
|
||||
.setTimeRemainingMillis(e.getFailure().timeRemaining());
|
||||
|
||||
if (e.getFailure().svr2Credentials() != null) {
|
||||
failureBuilder.setSvr2Credentials(ExternalServiceCredentials.newBuilder()
|
||||
.setUsername(e.getFailure().svr2Credentials().username())
|
||||
.setPassword(e.getFailure().svr2Credentials().password()));
|
||||
}
|
||||
|
||||
return ChangeNumberResponse.newBuilder()
|
||||
.setRegistrationLockFailure(failureBuilder)
|
||||
.build();
|
||||
} catch (final UnverifiedRegistrationSessionException e) {
|
||||
return ChangeNumberResponse.newBuilder()
|
||||
.setUnverifiedRegistrationSession(FailedPrecondition.getDefaultInstance())
|
||||
.build();
|
||||
} catch (final InvalidRegistrationSessionException e) {
|
||||
return ChangeNumberResponse.newBuilder()
|
||||
.setInvalidRegistrationSession(FailedPrecondition.newBuilder().setDescription(e.getMessage()))
|
||||
.build();
|
||||
} catch (final IOException e) {
|
||||
throw GrpcExceptions.unavailable(e.getMessage());
|
||||
} catch (final RecoveryPasswordVerificationFailedException e) {
|
||||
return ChangeNumberResponse.newBuilder()
|
||||
.setRecoveryPasswordVerificationFailed(FailedPrecondition.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetAccountDataReportResponse getAccountDataReport(final GetAccountDataReportRequest request)
|
||||
throws IOException {
|
||||
final Account account = getAuthenticatedAccount();
|
||||
|
||||
final AccountDataReportResponse report = new AccountDataReportResponse(UUID.randomUUID(), clock.instant(),
|
||||
new AccountDataReportResponse.AccountAndDevicesDataReport(
|
||||
new AccountDataReportResponse.AccountDataReport(
|
||||
account.getNumber(),
|
||||
account.getBadges().stream().map(AccountDataReportResponse.BadgeDataReport::new).toList(),
|
||||
account.isUnrestrictedUnidentifiedAccess(),
|
||||
account.isDiscoverableByPhoneNumber()),
|
||||
account.getDevices().stream().map(device ->
|
||||
new AccountDataReportResponse.DeviceDataReport(
|
||||
device.getId(),
|
||||
Instant.ofEpochMilli(device.getLastSeen()),
|
||||
Instant.ofEpochMilli(device.getCreated()),
|
||||
device.getUserAgent())).toList()));
|
||||
|
||||
return GetAccountDataReportResponse.newBuilder()
|
||||
.setJson(SystemMapper.jsonMapper().writeValueAsString(report))
|
||||
.setText(report.text())
|
||||
.build();
|
||||
}
|
||||
|
||||
private static AccountIdentifiers buildAccountIdentifiers(final Account account) {
|
||||
final AccountIdentifiers.Builder accountIdentifiersBuilder = AccountIdentifiers.newBuilder()
|
||||
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getUuid())))
|
||||
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new PniServiceIdentifier(account.getPhoneNumberIdentifier())))
|
||||
.setE164(account.getNumber());
|
||||
|
||||
account.getUsernameHash().ifPresent(usernameHash ->
|
||||
accountIdentifiersBuilder.setUsernameHash(ByteString.copyFrom(usernameHash)));
|
||||
|
||||
if (account.getUsernameLinkHandle() != null) {
|
||||
accountIdentifiersBuilder.setUsernameLinkHandle(UUIDUtil.toByteString(account.getUsernameLinkHandle()));
|
||||
}
|
||||
|
||||
return accountIdentifiersBuilder.build();
|
||||
}
|
||||
|
||||
private static MessageProtos.Envelope.Type getEnvelopeType(final SendMessageType type) {
|
||||
return switch (type) {
|
||||
case DOUBLE_RATCHET -> MessageProtos.Envelope.Type.CIPHERTEXT;
|
||||
case PREKEY_MESSAGE -> MessageProtos.Envelope.Type.PREKEY_BUNDLE;
|
||||
case PLAINTEXT_CONTENT -> MessageProtos.Envelope.Type.PLAINTEXT_CONTENT;
|
||||
case UNIDENTIFIED_SENDER -> throw GrpcExceptions.invalidArguments("illegal envelope type for change-number sync messages");
|
||||
case UNSPECIFIED, UNRECOGNIZED -> throw GrpcExceptions.invalidArguments("unrecognized envelope type");
|
||||
};
|
||||
}
|
||||
|
||||
private Account getAuthenticatedAccount() {
|
||||
return getAuthenticatedAccount(AuthenticationUtil.requireAuthenticatedDevice());
|
||||
}
|
||||
@@ -345,4 +534,25 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
return accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
}
|
||||
|
||||
private static String formatRegistrationLock(final byte[] registrationLock) {
|
||||
// In the previous REST-based API, clients would send hex strings directly. For backward compatibility, we
|
||||
// convert the registration lock secret to a lowercase hex string before turning it into a salted hash.
|
||||
return HexFormat.of().withLowerCase().formatHex(registrationLock);
|
||||
}
|
||||
|
||||
private static StatusRuntimeException invalidPublicKeyException(final String fieldName) {
|
||||
return GrpcExceptions.fieldViolation(fieldName, "invalid public key");
|
||||
}
|
||||
|
||||
private static StatusRuntimeException invalidSignatureException(final String fieldName) {
|
||||
return GrpcExceptions.fieldViolation(fieldName, "pre-key signature did not match PNI identity key");
|
||||
}
|
||||
|
||||
private static <T, U> Map<Byte, U> transformDeviceMap(final Map<Integer, T> byDeviceId, final Function<T, U> f) {
|
||||
return byDeviceId.entrySet()
|
||||
.stream()
|
||||
.collect(Collectors.<Map.Entry<Integer, T>, Byte, U>toMap(entry -> entry.getKey().byteValue(),
|
||||
entry -> f.apply(entry.getValue())));
|
||||
}
|
||||
}
|
||||
@@ -11,11 +11,19 @@ import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import org.signal.chat.common.EcPreKey;
|
||||
import org.signal.chat.common.EcSignedPreKey;
|
||||
import org.signal.chat.common.KemSignedPreKey;
|
||||
import org.signal.chat.keys.AccountPreKeyBundles;
|
||||
import org.signal.chat.keys.DevicePreKeyBundle;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.InvalidKeyException;
|
||||
import org.signal.libsignal.protocol.ecc.ECPublicKey;
|
||||
import org.signal.libsignal.protocol.kem.KEMPublicKey;
|
||||
import org.whispersystems.textsecuregcm.entities.ECPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
@@ -89,4 +97,46 @@ class KeysGrpcHelper {
|
||||
|
||||
return Optional.of(preKeyBundlesBuilder.build());
|
||||
}
|
||||
|
||||
public static ECPreKey checkEcPreKey(final EcPreKey preKey, final StatusRuntimeException invalidPublicKeyException) {
|
||||
try {
|
||||
return new ECPreKey(preKey.getKeyId(), new ECPublicKey(preKey.getPublicKey().toByteArray()));
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw invalidPublicKeyException;
|
||||
}
|
||||
}
|
||||
|
||||
public static ECSignedPreKey checkEcSignedPreKey(final EcSignedPreKey preKey, final IdentityKey identityKey,
|
||||
final StatusRuntimeException invalidPublicKeyException, final StatusRuntimeException invalidSignatureException) {
|
||||
try {
|
||||
final ECSignedPreKey ecSignedPreKey = new ECSignedPreKey(preKey.getKeyId(),
|
||||
new ECPublicKey(preKey.getPublicKey().toByteArray()),
|
||||
preKey.getSignature().toByteArray());
|
||||
|
||||
if (ecSignedPreKey.signatureValid(identityKey)) {
|
||||
return ecSignedPreKey;
|
||||
} else {
|
||||
throw invalidSignatureException;
|
||||
}
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw invalidPublicKeyException;
|
||||
}
|
||||
}
|
||||
|
||||
public static KEMSignedPreKey checkKemSignedPreKey(final KemSignedPreKey preKey, final IdentityKey identityKey,
|
||||
final StatusRuntimeException invalidPublicKeyException, final StatusRuntimeException invalidSignatureException) {
|
||||
try {
|
||||
final KEMSignedPreKey kemSignedPreKey = new KEMSignedPreKey(preKey.getKeyId(),
|
||||
new KEMPublicKey(preKey.getPublicKey().toByteArray()),
|
||||
preKey.getSignature().toByteArray());
|
||||
|
||||
if (kemSignedPreKey.signatureValid(identityKey)) {
|
||||
return kemSignedPreKey;
|
||||
} else {
|
||||
throw invalidSignatureException;
|
||||
}
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw invalidPublicKeyException;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,9 +11,6 @@ import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.BiFunction;
|
||||
import org.signal.chat.common.EcPreKey;
|
||||
import org.signal.chat.common.EcSignedPreKey;
|
||||
import org.signal.chat.common.KemSignedPreKey;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
import org.signal.chat.keys.GetPreKeyCountRequest;
|
||||
import org.signal.chat.keys.GetPreKeyCountResponse;
|
||||
@@ -26,16 +23,10 @@ import org.signal.chat.keys.SetOneTimeKemSignedPreKeysRequest;
|
||||
import org.signal.chat.keys.SetPreKeyResponse;
|
||||
import org.signal.chat.keys.SimpleKeysGrpc;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.InvalidKeyException;
|
||||
import org.signal.libsignal.protocol.ecc.ECPublicKey;
|
||||
import org.signal.libsignal.protocol.kem.KEMPublicKey;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitKeys;
|
||||
import org.whispersystems.textsecuregcm.entities.ECPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
@@ -136,7 +127,7 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
|
||||
storeOneTimePreKeys(authenticatedDevice.accountIdentifier(),
|
||||
request.getPreKeysList(),
|
||||
IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType()),
|
||||
(requestPreKey, _) -> checkEcPreKey(requestPreKey),
|
||||
(requestPreKey, _) -> KeysGrpcHelper.checkEcPreKey(requestPreKey, INVALID_PUBLIC_KEY_EXCEPTION),
|
||||
(identifier, preKeys) -> keysManager.storeEcOneTimePreKeys(identifier, authenticatedDevice.deviceId(), preKeys));
|
||||
|
||||
return SetPreKeyResponse.getDefaultInstance();
|
||||
@@ -149,7 +140,7 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
|
||||
storeOneTimePreKeys(authenticatedDevice.accountIdentifier(),
|
||||
request.getPreKeysList(),
|
||||
IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType()),
|
||||
KeysGrpcService::checkKemSignedPreKey,
|
||||
(preKey, identityKey) -> KeysGrpcHelper.checkKemSignedPreKey(preKey, identityKey, INVALID_PUBLIC_KEY_EXCEPTION, INVALID_SIGNATURE_EXCEPTION),
|
||||
(identifier, preKeys) -> keysManager.storeKemOneTimePreKeys(identifier, authenticatedDevice.deviceId(), preKeys));
|
||||
|
||||
return SetPreKeyResponse.getDefaultInstance();
|
||||
@@ -177,7 +168,7 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
|
||||
storeRepeatedUseKey(authenticatedDevice.accountIdentifier(),
|
||||
request.getIdentityType(),
|
||||
request.getSignedPreKey(),
|
||||
KeysGrpcService::checkEcSignedPreKey,
|
||||
(preKey, identityKey) -> KeysGrpcHelper.checkEcSignedPreKey(preKey, identityKey, INVALID_PUBLIC_KEY_EXCEPTION, INVALID_SIGNATURE_EXCEPTION),
|
||||
(account, signedPreKey) -> {
|
||||
final IdentityType identityType = IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType());
|
||||
final UUID identifier = account.getIdentifier(identityType);
|
||||
@@ -195,7 +186,7 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
|
||||
storeRepeatedUseKey(authenticatedDevice.accountIdentifier(),
|
||||
request.getIdentityType(),
|
||||
request.getSignedPreKey(),
|
||||
KeysGrpcService::checkKemSignedPreKey,
|
||||
(preKey, identityKey) -> KeysGrpcHelper.checkKemSignedPreKey(preKey, identityKey, INVALID_PUBLIC_KEY_EXCEPTION, INVALID_SIGNATURE_EXCEPTION),
|
||||
(account, lastResortKey) -> {
|
||||
final UUID identifier =
|
||||
account.getIdentifier(IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType()));
|
||||
@@ -220,45 +211,6 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
|
||||
storeKeyFunction.apply(account, key).join();
|
||||
}
|
||||
|
||||
private static ECPreKey checkEcPreKey(final EcPreKey preKey) {
|
||||
try {
|
||||
return new ECPreKey(preKey.getKeyId(), new ECPublicKey(preKey.getPublicKey().toByteArray()));
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw INVALID_PUBLIC_KEY_EXCEPTION;
|
||||
}
|
||||
}
|
||||
|
||||
private static ECSignedPreKey checkEcSignedPreKey(final EcSignedPreKey preKey, final IdentityKey identityKey) {
|
||||
try {
|
||||
final ECSignedPreKey ecSignedPreKey = new ECSignedPreKey(preKey.getKeyId(),
|
||||
new ECPublicKey(preKey.getPublicKey().toByteArray()),
|
||||
preKey.getSignature().toByteArray());
|
||||
|
||||
if (ecSignedPreKey.signatureValid(identityKey)) {
|
||||
return ecSignedPreKey;
|
||||
} else {
|
||||
throw INVALID_SIGNATURE_EXCEPTION;
|
||||
}
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw INVALID_PUBLIC_KEY_EXCEPTION;
|
||||
}
|
||||
}
|
||||
|
||||
private static KEMSignedPreKey checkKemSignedPreKey(final KemSignedPreKey preKey, final IdentityKey identityKey) {
|
||||
try {
|
||||
final KEMSignedPreKey kemSignedPreKey = new KEMSignedPreKey(preKey.getKeyId(),
|
||||
new KEMPublicKey(preKey.getPublicKey().toByteArray()),
|
||||
preKey.getSignature().toByteArray());
|
||||
|
||||
if (kemSignedPreKey.signatureValid(identityKey)) {
|
||||
return kemSignedPreKey;
|
||||
} else {
|
||||
throw INVALID_SIGNATURE_EXCEPTION;
|
||||
}
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw INVALID_PUBLIC_KEY_EXCEPTION;
|
||||
}
|
||||
}
|
||||
|
||||
private Account getAuthenticatedAccount(final UUID authenticatedAccountId) {
|
||||
return accountsManager.getByAccountIdentifier(authenticatedAccountId)
|
||||
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package org.whispersystems.textsecuregcm.mappers;
|
||||
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.ext.ExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockFailureException;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
|
||||
public class RegistrationLockFailureExceptionMapper implements ExceptionMapper<RegistrationLockFailureException> {
|
||||
|
||||
@Override
|
||||
public Response toResponse(final RegistrationLockFailureException exception) {
|
||||
return Response.status(RegistrationLockVerificationManager.FAILURE_HTTP_STATUS)
|
||||
.entity(exception.getFailure())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
package org.whispersystems.textsecuregcm.spam;
|
||||
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.annotation.Nullable;
|
||||
|
||||
public interface RegistrationRecoveryChecker {
|
||||
|
||||
@@ -11,9 +11,9 @@ public interface RegistrationRecoveryChecker {
|
||||
* @param e164 The E164 formatted phone number of the requester
|
||||
* @return true if the registration recovery attempt is allowed, false otherwise.
|
||||
*/
|
||||
boolean checkRegistrationRecoveryAttempt(final ContainerRequestContext requestContext, final String e164);
|
||||
boolean checkRegistrationRecoveryAttempt(String e164, @Nullable String userAgent, @Nullable String acceptLanguage, @Nullable String mostRecentProxy);
|
||||
|
||||
static RegistrationRecoveryChecker noop() {
|
||||
return (ignoredCtx, ignoredE164) -> true;
|
||||
return (_, _, _, _) -> true;
|
||||
}
|
||||
}
|
||||
+14
-11
@@ -6,11 +6,10 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
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 java.io.IOException;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
@@ -22,8 +21,12 @@ import javax.annotation.Nullable;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RecoveryPasswordVerificationFailedException;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockFailureException;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
import org.whispersystems.textsecuregcm.auth.UnverifiedRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.controllers.AccountControllerV2;
|
||||
import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedException;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
@@ -88,10 +91,10 @@ public class ChangeNumberManager {
|
||||
final Map<Byte, KEMSignedPreKey> devicePqLastResortPreKeys,
|
||||
final List<IncomingMessage> deviceMessages,
|
||||
final Map<Byte, Integer> pniRegistrationIds,
|
||||
final ContainerRequestContext containerRequestContext)
|
||||
throws InterruptedException, MismatchedDevicesException, MessageTooLargeException, RateLimitExceededException, MessageDeliveryNotAllowedException {
|
||||
|
||||
final String senderUserAgent = containerRequestContext.getHeaderString(HttpHeaders.USER_AGENT);
|
||||
@Nullable final String userAgent,
|
||||
@Nullable final String acceptLanguage,
|
||||
@Nullable final String mostRecentProxy)
|
||||
throws InterruptedException, MismatchedDevicesException, MessageTooLargeException, RateLimitExceededException, MessageDeliveryNotAllowedException, RegistrationLockFailureException, UnverifiedRegistrationSessionException, InvalidRegistrationSessionException, IOException, RecoveryPasswordVerificationFailedException {
|
||||
|
||||
final Pair<Account, Optional<Account>> accountAndMaybeExistingAccount =
|
||||
accountsManager.getAccountsForChangeNumber(accountIdentifier, number);
|
||||
@@ -110,16 +113,16 @@ public class ChangeNumberManager {
|
||||
rateLimiters.getRegistrationLimiter().validate(number);
|
||||
|
||||
final PhoneVerificationRequest.VerificationType verificationType =
|
||||
phoneVerificationTokenManager.verify(containerRequestContext, number, sessionId, recoveryPassword);
|
||||
phoneVerificationTokenManager.verify(number, userAgent, acceptLanguage, mostRecentProxy, sessionId, recoveryPassword);
|
||||
|
||||
final Optional<Account> existingAccount = accountAndMaybeExistingAccount.second();
|
||||
|
||||
if (existingAccount.isPresent()) {
|
||||
registrationLockVerificationManager.verifyRegistrationLock(existingAccount.get(), registrationLock,
|
||||
senderUserAgent, RegistrationLockVerificationManager.Flow.CHANGE_NUMBER, verificationType);
|
||||
userAgent, RegistrationLockVerificationManager.Flow.CHANGE_NUMBER, verificationType);
|
||||
}
|
||||
|
||||
Metrics.counter(CHANGE_NUMBER_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(senderUserAgent),
|
||||
Metrics.counter(CHANGE_NUMBER_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(VERIFICATION_TYPE_TAG_NAME, verificationType.name())))
|
||||
.increment();
|
||||
}
|
||||
@@ -152,7 +155,7 @@ public class ChangeNumberManager {
|
||||
messagesByDeviceId,
|
||||
registrationIdsByDeviceId,
|
||||
Optional.of(Device.PRIMARY_ID),
|
||||
senderUserAgent);
|
||||
userAgent);
|
||||
}
|
||||
|
||||
final Account updatedAccount = accountsManager.changeNumber(
|
||||
@@ -170,7 +173,7 @@ public class ChangeNumberManager {
|
||||
messagesByDeviceId,
|
||||
registrationIdsByDeviceId,
|
||||
Optional.of(Device.PRIMARY_ID),
|
||||
senderUserAgent);
|
||||
userAgent);
|
||||
} catch (final RuntimeException e) {
|
||||
logger.warn("Changed number but could not send all device messages for {}",
|
||||
account.getIdentifier(IdentityType.ACI), e);
|
||||
|
||||
@@ -6,6 +6,7 @@ package org.signal.chat.account;
|
||||
|
||||
import "org/signal/chat/common.proto";
|
||||
import "org/signal/chat/errors.proto";
|
||||
import "org/signal/chat/messages.proto";
|
||||
import "org/signal/chat/require.proto";
|
||||
import "org/signal/chat/tag.proto";
|
||||
|
||||
@@ -65,6 +66,12 @@ service Accounts {
|
||||
|
||||
// Store a public key used to issue and verify zero-knowledge (anonymous) credentials for the account.
|
||||
rpc SetZkCredentialKey(SetZkCredentialKeyRequest) returns (SetZkCredentialKeyResponse) {}
|
||||
|
||||
// Changes the phone number associated with the authenticated account.
|
||||
rpc ChangeNumber(ChangeNumberRequest) returns (ChangeNumberResponse) {}
|
||||
|
||||
// Produces a report of non-ephemeral account data stored by the service
|
||||
rpc GetAccountDataReport(GetAccountDataReportRequest) returns (GetAccountDataReportResponse) {}
|
||||
}
|
||||
|
||||
// Provides methods for looking up Signal accounts. Callers must not provide
|
||||
@@ -316,3 +323,114 @@ message SetZkCredentialKeyResponse {
|
||||
// as reverting to the previous key will result in a new rotation ID.
|
||||
uint64 rotation_id = 1;
|
||||
}
|
||||
|
||||
message ChangeNumberRequest {
|
||||
// A means of authenticating the change-number request for the new phone
|
||||
// number. Exactly one must be provided.
|
||||
oneof verification {
|
||||
// A verified registration session ID (as returned by the registration
|
||||
// service) for the new phone number.
|
||||
bytes session_id = 1 [(require.nonEmpty) = true];
|
||||
|
||||
// A registration recovery password for the new phone number.
|
||||
bytes recovery_password = 2 [(require.exactlySize) = 32];
|
||||
}
|
||||
|
||||
// The new phone number for the authenticated account.
|
||||
string number = 3 [(require.e164) = true];
|
||||
|
||||
// The registration lock secret for the new phone number, if the account
|
||||
// associated with the new phone number has a registration lock configured.
|
||||
bytes registration_lock = 4 [(require.exactlySize) = 0, (require.exactlySize) = 32];
|
||||
|
||||
// The new public identity key to use for the phone-number identity (PNI)
|
||||
// associated with the new phone number.
|
||||
bytes pni_identity_key = 5 [(require.nonEmpty) = true];
|
||||
|
||||
// Synchronization messages to send to companion devices to supply the private
|
||||
// keys associated with the new identity key and their new pre-keys. Exactly
|
||||
// one message must be supplied for each device other than the sending
|
||||
// (primary) device. May be omitted if no companion devices are linked to the
|
||||
// account.
|
||||
messages.IndividualRecipientMessageBundle device_messages = 6;
|
||||
|
||||
// A new signed EC pre-key for each device on the account, including the
|
||||
// sending device, keyed by device ID. Each must be accompanied by a valid
|
||||
// signature from the identity key in this request.
|
||||
map<uint32, common.EcSignedPreKey> device_pni_signed_pre_keys = 7;
|
||||
|
||||
// A new signed post-quantum last-resort pre-key for each device on the
|
||||
// account, including the sending device, keyed by device ID. Each must be
|
||||
// accompanied by a valid signature from the identity key in this request.
|
||||
map<uint32, common.KemSignedPreKey> device_pni_pq_last_resort_pre_keys = 8;
|
||||
|
||||
// The new phone-number-identity registration ID for each device on the
|
||||
// account, including the sending device, keyed by device ID.
|
||||
map<uint32, uint32> pni_registration_ids = 9;
|
||||
}
|
||||
|
||||
message ChangeNumberResponse {
|
||||
oneof response {
|
||||
// The identifiers of the account after the successful
|
||||
// number change.
|
||||
common.AccountIdentifiers account_identifiers = 1;
|
||||
|
||||
// Mismatched number of devices or device ids in 'devices to notify' list
|
||||
messages.MismatchedDevices mismatched_devices = 2 [(tag.reason) = "mismatched_devices"];
|
||||
|
||||
// The account associated with the new phone number has a registration lock,
|
||||
// and the provided registration lock secret was missing or incorrect.
|
||||
RegistrationLockFailure registration_lock_failure = 3 [(tag.reason) = "registration_lock_failure"];
|
||||
|
||||
// Mismatched registration ids in 'devices to notify' list
|
||||
StaleDevices stale_devices = 4 [(tag.reason) = "stale_devices"];
|
||||
|
||||
// One or more device messages was too large
|
||||
errors.FailedPrecondition message_too_large = 5 [(tag.reason) = "message_too_large"];
|
||||
|
||||
// The registration session is unverified
|
||||
errors.FailedPrecondition unverified_registration_session = 6 [(tag.reason) = "unverified_registration_session"];
|
||||
|
||||
// The number does not match the registration session, or the registration session is invalid
|
||||
errors.FailedPrecondition invalid_registration_session = 7 [(tag.reason) = "invalid_registration_session"];
|
||||
|
||||
errors.FailedPrecondition recovery_password_verification_failed = 8 [(tag.reason) = "recovery_password_verification_failed"];
|
||||
}
|
||||
}
|
||||
|
||||
// Information about the current Registration lock and SVR credentials. With a correct PIN, the credentials can
|
||||
// be used to recover the secret used to derive the registration lock password.
|
||||
message RegistrationLockFailure {
|
||||
// Time remaining in milliseconds before the existing registration lock expires
|
||||
uint64 time_remaining_millis = 1;
|
||||
|
||||
// Credentials that can be used with SVR2
|
||||
ExternalServiceCredentials svr2_credentials = 2;
|
||||
}
|
||||
|
||||
// A username/password pair for authenticating with an external service.
|
||||
message ExternalServiceCredentials {
|
||||
// A username that can be presented to authenticate with the external service.
|
||||
string username = 1;
|
||||
|
||||
// A password that can be presented to authenticate with the external service.
|
||||
string password = 2;
|
||||
}
|
||||
|
||||
// A list of devices that are linked to the account but presented a stale
|
||||
// registration ID (indicating the device has likely been replaced by another
|
||||
// device).
|
||||
message StaleDevices {
|
||||
// The IDs of devices that are no longer active.
|
||||
repeated uint32 stale_devices = 1 [(require.each) = {range: {max: 0x7f}}];
|
||||
}
|
||||
|
||||
message GetAccountDataReportRequest {
|
||||
}
|
||||
|
||||
message GetAccountDataReportResponse {
|
||||
// The JSON representation of the data report
|
||||
string json = 3;
|
||||
// A plaintext representation of the data report
|
||||
string text = 4;
|
||||
}
|
||||
+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