Compare commits

..
Author SHA1 Message Date
Chris Eager 305b015784 Update to the latest version of the spam filter 2026-05-06 12:53:24 -05:00
Chris Eager f6ebde8185 Add Profile gRPC services to server 2026-05-06 12:48:58 -05:00
dependabot[bot] 58d4a3b687 Bump aws-actions/configure-aws-credentials
Bumps the minor-actions-dependencies group with 1 update: [aws-actions/configure-aws-credentials](https://github.com/aws-actions/configure-aws-credentials).


Updates `aws-actions/configure-aws-credentials` from 6.0.0 to 6.1.0
- [Release notes](https://github.com/aws-actions/configure-aws-credentials/releases)
- [Changelog](https://github.com/aws-actions/configure-aws-credentials/blob/main/CHANGELOG.md)
- [Commits](https://github.com/aws-actions/configure-aws-credentials/compare/8df5847569e6427dd6c4fb1cf565c83acfa8afa7...ec61189d14ec14c8efccab744f656cffd0e33f37)

---
updated-dependencies:
- dependency-name: aws-actions/configure-aws-credentials
  dependency-version: 6.1.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-actions-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-05-06 12:48:47 -05:00
Chris Eager 9c6ec78a4e Match profiles V2 test table name in Java and configuration 2026-04-29 19:57:20 -05:00
Chris Eager 1e3b2c8ce8 Profiles gRPC: initial v2 implementation 2026-04-29 10:32:18 -05:00
Katherine Yen 1b11c3efc2 Log when DynamoDB/JSON phone numbers differ 2026-04-29 10:28:27 -05:00
Ravi Khadiwala b441fde213 Enforce key-ids fit in a positive signed 32-bit int 2026-04-29 10:28:15 -05:00
Jon Chambers de5cb3370d Don't try to decode null session IDs 2026-04-17 14:51:07 -04:00
Ameya Lokare 52b4e0b87f Enforce rate limiting on batch identity check endpoint 2026-04-17 13:52:41 -04:00
Jon Chambers 3e19b415b6 Always use fresh, non-cached Account instances when changing numbers 2026-04-17 13:47:54 -04:00
Jon Chambers 3790b53496 Update to the latest version of the spam filter 2026-04-17 11:48:27 -04:00
Jon Chambers 6c26c38b96 Turn on compact object headers 2026-04-17 11:47:58 -04:00
Chris Eager aa1ff253fb Enforce AccountAttributes#isUnrestrictedUakValid 2026-04-17 09:54:53 -04:00
Jon Chambers 1301bfda93 Avoid blocking in an async context 2026-04-17 09:54:36 -04:00
Jon Chambers c02667e2e4 Add unit tests for PhoneVerificationTokenManager 2026-04-17 09:54:36 -04:00
Jon Chambers 9e6cbe8f82 Always use fresh/non-cached copies of accounts when making modifications 2026-04-17 09:41:59 -04:00
Chris Eager 1e2d27585a Add gRPC size annotations; allow non-empty UAK for unrestricted 2026-04-16 13:18:56 -05:00
Chris Eager c70674ed26 Update serialization test 2026-04-16 13:18:56 -05:00
Chris Eager 0281756c01 Add metrics for invalid unrestricted UAK 2026-04-16 13:18:56 -05:00
Chris Eager 5e1338a571 Factor out DeviceAttributes from AccountAttributes 2026-04-16 13:18:56 -05:00
Chris Eager 149de6c464 Add UAK validator to AccountAttributes 2026-04-16 13:18:56 -05:00
Chris Eager b551e0cb34 Require UAKs to be non-zero length or null 2026-04-16 13:18:56 -05:00
Chris Eager 2344d3d9b7 Add AccountAttributes serialization test 2026-04-16 13:18:56 -05:00
Chris Eager 04aa528ad8 Add Accounts.SetZkCredentialKey 2026-04-16 12:13:34 -05:00
Jon Chambers 1b5c602351 Retire the device count override system 2026-04-16 12:52:15 -04:00
Ravi Khadiwala bbeeed9d1f Remove unused static grpcAllowList configuration 2026-04-15 18:05:06 -04:00
Chris Eager aabbbe486f Update exception for empty non-sync messages to MessageSender 2026-04-15 17:03:10 -05:00
Jon Chambers b702d9d5a9 Remove service level objectives for captcha outcome distribution 2026-04-15 18:01:59 -04:00
105 changed files with 4721 additions and 2314 deletions

No files matched your search

+1 -1
View File
@@ -24,7 +24,7 @@ jobs:
distribution: 'temurin'
java-version-file: .java-version
cache: 'maven'
- uses: aws-actions/configure-aws-credentials@8df5847569e6427dd6c4fb1cf565c83acfa8afa7 # v6.0.0
- uses: aws-actions/configure-aws-credentials@ec61189d14ec14c8efccab744f656cffd0e33f37 # v6.1.0
name: Configure AWS credentials from Test account
with:
role-to-assume: ${{ vars.AWS_ROLE }}
@@ -130,8 +130,8 @@ public class TestUser {
public AccountAttributes accountAttributes() {
return new AccountAttributes(true, registrationId, pniRegistrationId, "".getBytes(StandardCharsets.UTF_8), "", true,
DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES)
.withUnidentifiedAccessKey(unidentifiedAccessKey)
.withRecoveryPassword(registrationPassword);
.setUnidentifiedAccessKey(unidentifiedAccessKey)
.setRecoveryPassword(registrationPassword);
}
public void setAciUuid(final UUID aciUuid) {
+2
View File
@@ -125,6 +125,8 @@ dynamoDbTables:
tableName: Example_PhoneNumberIdentifiers
profiles:
tableName: Example_Profiles
profilesV2:
tableName: Example_ProfilesV2
pushChallenge:
tableName: Example_PushChallenge
pushNotificationExperimentSamples:
+3
View File
@@ -696,6 +696,9 @@
<jvmFlag>-XX:MaxRAMPercentage=75</jvmFlag>
<jvmFlag>-XX:+HeapDumpOnOutOfMemoryError</jvmFlag>
<jvmFlag>-XX:HeapDumpPath=/tmp/heapdump.bin</jvmFlag>
<!-- This will likely become the default in a future version of Java, and we can remove this flag when
that happens. Please see https://openjdk.org/jeps/534 for details. -->
<jvmFlag>-XX:+UseCompactObjectHeaders</jvmFlag>
</jvmFlags>
<ports>
<port>8080</port>
@@ -10,9 +10,6 @@ import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.whispersystems.textsecuregcm.attachments.TusConfiguration;
import org.whispersystems.textsecuregcm.configuration.ApnConfiguration;
@@ -32,7 +29,6 @@ import org.whispersystems.textsecuregcm.configuration.DeviceCheckConfiguration;
import org.whispersystems.textsecuregcm.configuration.DirectoryV2Configuration;
import org.whispersystems.textsecuregcm.configuration.DynamoDbClientFactory;
import org.whispersystems.textsecuregcm.configuration.DynamoDbTables;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicGrpcAllowListConfiguration;
import org.whispersystems.textsecuregcm.configuration.ExternalRequestFilterConfiguration;
import org.whispersystems.textsecuregcm.configuration.FaultTolerantRedisClientFactory;
import org.whispersystems.textsecuregcm.configuration.FaultTolerantRedisClusterFactory;
@@ -45,7 +41,6 @@ import org.whispersystems.textsecuregcm.configuration.HlrLookupConfiguration;
import org.whispersystems.textsecuregcm.configuration.IdlePrimaryDeviceReminderConfiguration;
import org.whispersystems.textsecuregcm.configuration.KeyTransparencyServiceConfiguration;
import org.whispersystems.textsecuregcm.configuration.LinkDeviceSecretConfiguration;
import org.whispersystems.textsecuregcm.configuration.MaxDeviceConfiguration;
import org.whispersystems.textsecuregcm.configuration.MessageByteLimitCardinalityEstimatorConfiguration;
import org.whispersystems.textsecuregcm.configuration.MessageCacheConfiguration;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
@@ -188,11 +183,6 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private MessageCacheConfiguration messageCache;
@Valid
@NotNull
@JsonProperty
private List<MaxDeviceConfiguration> maxDevices = new LinkedList<>();
@Valid
@NotNull
@JsonProperty
@@ -355,11 +345,6 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private GrpcConfiguration grpc;
@NotNull
@Valid
@JsonProperty
private DynamicGrpcAllowListConfiguration grpcAllowList = new DynamicGrpcAllowListConfiguration();
@Valid
@NotNull
@JsonProperty
@@ -486,17 +471,6 @@ public class WhisperServerConfiguration extends Configuration {
return unidentifiedDelivery;
}
public Map<String, Integer> getMaxDevices() {
Map<String, Integer> results = new HashMap<>();
for (MaxDeviceConfiguration maxDeviceConfiguration : maxDevices) {
results.put(maxDeviceConfiguration.getNumber(),
maxDeviceConfiguration.getCount());
}
return results;
}
public PaymentsServiceConfiguration getPaymentsServiceConfiguration() {
return paymentsService;
}
@@ -605,10 +579,6 @@ public class WhisperServerConfiguration extends Configuration {
return grpc;
}
public DynamicGrpcAllowListConfiguration getGrpcAllowList() {
return grpcAllowList;
}
public S3ObjectMonitorFactory getAsnTableConfiguration() {
return asnTable;
}
@@ -159,6 +159,8 @@ import org.whispersystems.textsecuregcm.grpc.MessagesAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.MessagesGrpcService;
import org.whispersystems.textsecuregcm.grpc.MetricServerInterceptor;
import org.whispersystems.textsecuregcm.grpc.PaymentsGrpcService;
import org.whispersystems.textsecuregcm.grpc.ProfileAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.ProfileGrpcService;
import org.whispersystems.textsecuregcm.grpc.RequestAttributesInterceptor;
import org.whispersystems.textsecuregcm.grpc.ValidatingInterceptor;
import org.whispersystems.textsecuregcm.grpc.net.ManagedGrpcServer;
@@ -238,6 +240,7 @@ import org.whispersystems.textsecuregcm.storage.PersistentTimer;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.Profiles;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.ProfilesV2;
import org.whispersystems.textsecuregcm.storage.PushChallengeDynamoDb;
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswords;
@@ -469,8 +472,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getDynamoDbTables().getClientReleases().getTableName());
PhoneNumberIdentifiers phoneNumberIdentifiers = new PhoneNumberIdentifiers(dynamoDbAsyncClient,
config.getDynamoDbTables().getPhoneNumberIdentifiers().getTableName());
Profiles profiles = new Profiles(dynamoDbClient, dynamoDbAsyncClient,
config.getDynamoDbTables().getProfiles().getTableName());
Profiles profilesV1 = new Profiles(dynamoDbClient, dynamoDbAsyncClient,
config.getDynamoDbTables().getProfilesV1().getTableName());
ProfilesV2 profiles = new ProfilesV2(dynamoDbClient, dynamoDbAsyncClient, config.getDynamoDbTables().getProfilesV2().getTableName());
S3AsyncClient asyncKeysS3Client = S3AsyncClient.builder()
.credentialsProvider(awsCredentialsProvider)
@@ -678,7 +682,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
storageServiceExecutor, retryExecutor, config.getSecureStorageServiceConfiguration());
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient,
disconnectionRequestListenerExecutor, retryExecutor);
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster, retryExecutor, asyncCdnS3Client,
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, cacheCluster, retryExecutor, asyncCdnS3Client,
config.getCdnConfiguration().bucket());
MessagesCache messagesCache = new MessagesCache(messagesCluster, messageDeliveryScheduler,
messageDeletionAsyncExecutor, retryExecutor, clock, experimentEnrollmentManager);
@@ -766,8 +770,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
PushChallengeManager pushChallengeManager = new PushChallengeManager(pushNotificationManager,
pushChallengeDynamoDb);
ChangeNumberManager changeNumberManager = new ChangeNumberManager(messageSender, accountsManager, Clock.systemUTC());
HttpClient currencyClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2).connectTimeout(Duration.ofSeconds(10)).build();
FixerClient fixerClient = config.getPaymentsServiceConfiguration().externalClients()
.buildFixerClient(currencyClient);
@@ -970,6 +972,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new AccountsGrpcService(accountsManager, rateLimiters, usernameHashZkProofVerifier, registrationRecoveryPasswordsManager),
ExternalServiceCredentialsGrpcService.createForAllExternalServices(config, rateLimiters),
new KeysGrpcService(accountsManager, keysManager, rateLimiters),
new ProfileGrpcService(clock, accountsManager, profilesManager, dynamicConfigurationManager, config.getBadges(), profileCdnPolicyGenerator, profileCdnPolicySigner, profileBadgeConverter, rateLimiters),
new MessagesGrpcService(accountsManager, rateLimiters, messageSender, messageByteLimitCardinalityEstimator, spamChecker, Clock.systemUTC()),
new BackupsGrpcService(accountsManager, backupAuthManager, backupMetrics),
new DevicesGrpcService(accountsManager),
@@ -991,6 +994,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new AccountsAnonymousGrpcService(accountsManager, rateLimiters),
new CallQualitySurveyGrpcService(callQualitySurveyManager, rateLimiters),
new KeysAnonymousGrpcService(accountsManager, keysManager, zkSecretParams, Clock.systemUTC()),
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, zkSecretParams),
new PaymentsGrpcService(currencyManager),
new MessagesAnonymousGrpcService(accountsManager, rateLimiters, messageSender, groupSendTokenUtil, messageByteLimitCardinalityEstimator, spamChecker, Clock.systemUTC()),
new BackupsAnonymousGrpcService(backupManager, backupMetrics, config.getAttachments().maxUploadSizeInBytes()),
@@ -1090,11 +1094,14 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final PhoneVerificationTokenManager phoneVerificationTokenManager = new PhoneVerificationTokenManager(
phoneNumberIdentifiers, registrationServiceClient, registrationRecoveryPasswordsManager, registrationRecoveryChecker);
final ChangeNumberManager changeNumberManager = new ChangeNumberManager(messageSender, accountsManager,
phoneVerificationTokenManager, registrationLockVerificationManager, rateLimiters, Clock.systemUTC());
final List<Object> commonControllers = Lists.newArrayList(
new AccountController(accountsManager, rateLimiters, registrationRecoveryPasswordsManager,
usernameHashZkProofVerifier),
new AccountControllerV2(accountsManager, changeNumberManager, phoneVerificationTokenManager,
registrationLockVerificationManager, rateLimiters),
new AccountControllerV2(accountsManager, changeNumberManager),
new AttachmentControllerV4(rateLimiters, gcsAttachmentGenerator, tusAttachmentGenerator,
experimentEnrollmentManager, config.getAttachments().maxUploadSizeInBytes()),
new ArchiveController(accountsManager, backupAuthManager, backupManager, backupMetrics, config.getAttachments().maxUploadSizeInBytes()),
@@ -1105,7 +1112,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getDeliveryCertificate().ecPrivateKey(), config.getDeliveryCertificate().expiresDays(), config.getDeliveryCertificate().embedSigner()),
zkAuthOperations, callingGenericZkSecretParams, clock),
new ChallengeController(accountsManager, rateLimitChallengeManager, challengeConstraintChecker),
new DeviceController(accountsManager, rateLimiters, persistentTimer, config.getMaxDevices()),
new DeviceController(accountsManager, rateLimiters, persistentTimer),
new DeviceCheckController(clock, accountsManager, backupAuthManager, appleDeviceCheckManager, rateLimiters,
config.getDeviceCheck().backupRedemptionLevel(),
config.getDeviceCheck().backupRedemptionDuration()),
@@ -142,7 +142,7 @@ public class AccountAuthenticator implements Authenticator<BasicCredentials, Aut
Metrics.summary(DAYS_SINCE_LAST_SEEN_DISTRIBUTION_NAME, IS_PRIMARY_DEVICE_TAG, String.valueOf(device.isPrimary()))
.record(Duration.ofMillis(todayInMillisWithOffset - device.getLastSeen()).toDays());
return accountsManager.updateDeviceLastSeen(account, device, Util.todayInMillis(clock));
return accountsManager.updateDeviceLastSeen(account.getIdentifier(IdentityType.ACI), device, Util.todayInMillis(clock));
}
return account;
@@ -16,6 +16,9 @@ public class Anonymous {
public Anonymous(String header) {
try {
this.unidentifiedSenderAccessKey = Base64.getDecoder().decode(header);
if (unidentifiedSenderAccessKey.length != UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH) {
throw new WebApplicationException("access key length must be 16", Response.Status.UNAUTHORIZED);
}
} catch (IllegalArgumentException e) {
throw new WebApplicationException(e, Response.Status.UNAUTHORIZED);
}
@@ -27,6 +27,7 @@ import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
import org.whispersystems.textsecuregcm.spam.RegistrationRecoveryChecker;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import javax.annotation.Nullable;
public class PhoneVerificationTokenManager {
@@ -56,8 +57,10 @@ public class PhoneVerificationTokenManager {
*
* @param requestContext the container request context
* @param number the e164 presented for verification
* @param request the request with exactly one verification token (RegistrationService sessionId or registration
* recovery password)
* @param sessionId a verification session ID; exactly one of {@code sessionId} or {@code recoveryPassword} must be
* non-null
* @param recoveryPassword a registration recovery password; exactly one of {@code sessionId} or
* {@code recoveryPassword} must be non-null
* @return if verification was successful, returns the verification type
* @throws BadRequestException if the number does not match the sessionId’s number, or the remote service rejects
* the session ID as invalid
@@ -65,13 +68,22 @@ public class PhoneVerificationTokenManager {
* @throws ForbiddenException if the recovery password is not valid
* @throws InterruptedException if verification did not complete before a timeout
*/
public PhoneVerificationRequest.VerificationType verify(final ContainerRequestContext requestContext, final String number, final PhoneVerificationRequest request)
throws InterruptedException {
public PhoneVerificationRequest.VerificationType verify(final ContainerRequestContext requestContext,
final String number,
@Nullable final byte[] sessionId,
@Nullable final byte[] recoveryPassword) throws InterruptedException {
if ((sessionId == null) == (recoveryPassword == null)) {
throw new IllegalArgumentException("Exactly one of session ID or recovery password must non-null");
}
final PhoneVerificationRequest.VerificationType verificationType = sessionId != null
? PhoneVerificationRequest.VerificationType.SESSION
: PhoneVerificationRequest.VerificationType.RECOVERY_PASSWORD;
final PhoneVerificationRequest.VerificationType verificationType = request.verificationType();
switch (verificationType) {
case SESSION -> verifyBySessionId(number, request.decodeSessionId());
case RECOVERY_PASSWORD -> verifyByRecoveryPassword(requestContext, number, request.recoveryPassword());
case SESSION -> verifyBySessionId(number, sessionId);
case RECOVERY_PASSWORD -> verifyByRecoveryPassword(requestContext, number, recoveryPassword);
}
return verificationType;
@@ -108,14 +120,19 @@ public class PhoneVerificationTokenManager {
}
}
private void verifyByRecoveryPassword(final ContainerRequestContext requestContext, final String number, final byte[] recoveryPassword)
throws InterruptedException {
private void verifyByRecoveryPassword(final ContainerRequestContext requestContext,
final String number,
final byte[] recoveryPassword) throws InterruptedException {
if (!registrationRecoveryChecker.checkRegistrationRecoveryAttempt(requestContext, number)) {
throw new ForbiddenException("recoveryPassword couldn't be verified");
}
try {
final boolean verified = registrationRecoveryPasswordsManager.verify(phoneNumberIdentifiers.getPhoneNumberIdentifier(number).join(), recoveryPassword)
final boolean verified = phoneNumberIdentifiers.getPhoneNumberIdentifier(number)
.thenCompose(phoneNumberIdentifier -> registrationRecoveryPasswordsManager.verify(phoneNumberIdentifier, recoveryPassword))
.get(VERIFICATION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
if (!verified) {
throw new ForbiddenException("recoveryPassword couldn't be verified");
}
@@ -123,5 +140,4 @@ public class PhoneVerificationTokenManager {
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE);
}
}
}
@@ -284,7 +284,7 @@ public class BackupAuthManager {
accountsManager.update(account, a -> {
// Receipt credential expirations must be day aligned. Make sure any manually set backupVoucher is also day
// aligned
final Account.BackupVoucher newPayment = new Account.BackupVoucher(
final Account.BackupVoucher newPayment = new Account.BackupVoucher(
backupVoucher.receiptLevel(),
backupVoucher.expiration().truncatedTo(ChronoUnit.DAYS));
final Account.BackupVoucher existingPayment = a.getBackupVoucher();
@@ -64,6 +64,7 @@ public class DynamoDbTables {
private final TableWithExpiration onetimeDonations;
private final Table phoneNumberIdentifiers;
private final Table profiles;
private final Table profilesV2;
private final Table pushChallenge;
private final Table pushNotificationExperimentSamples;
private final TableWithExpiration redeemedReceipts;
@@ -92,6 +93,7 @@ public class DynamoDbTables {
@JsonProperty("onetimeDonations") final TableWithExpiration onetimeDonations,
@JsonProperty("phoneNumberIdentifiers") final Table phoneNumberIdentifiers,
@JsonProperty("profiles") final Table profiles,
@JsonProperty("profilesV2") final Table profilesV2,
@JsonProperty("pushChallenge") final Table pushChallenge,
@JsonProperty("pushNotificationExperimentSamples") final Table pushNotificationExperimentSamples,
@JsonProperty("redeemedReceipts") final TableWithExpiration redeemedReceipts,
@@ -119,6 +121,7 @@ public class DynamoDbTables {
this.onetimeDonations = onetimeDonations;
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
this.profiles = profiles;
this.profilesV2 = profilesV2;
this.pushChallenge = pushChallenge;
this.pushNotificationExperimentSamples = pushNotificationExperimentSamples;
this.redeemedReceipts = redeemedReceipts;
@@ -228,10 +231,16 @@ public class DynamoDbTables {
@NotNull
@Valid
public Table getProfiles() {
public Table getProfilesV1() {
return profiles;
}
@NotNull
@Valid
public Table getProfilesV2() {
return profilesV2;
}
@NotNull
@Valid
public Table getPushChallenge() {
@@ -1,30 +0,0 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
public class MaxDeviceConfiguration {
@JsonProperty
@NotEmpty
private String number;
@JsonProperty
@NotNull
private int count;
public String getNumber() {
return number;
}
public int getCount() {
return count;
}
}
@@ -108,33 +108,26 @@ public class AccountController {
public void setGcmRegistrationId(@Auth AuthenticatedDevice auth,
@NotNull @Valid GcmRegistrationId registrationId) {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
final String currentGcmId = accounts.getByAccountIdentifier(auth.accountIdentifier())
.flatMap(account -> account.getDevice(auth.deviceId()))
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED))
.getGcmId();
final Device device = account.getDevice(auth.deviceId())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
if (Objects.equals(device.getGcmId(), registrationId.gcmRegistrationId())) {
if (Objects.equals(currentGcmId, registrationId.gcmRegistrationId())) {
return;
}
accounts.updateDevice(account, device.getId(), d -> {
d.setApnId(null);
d.setGcmId(registrationId.gcmRegistrationId());
d.setFetchesMessages(false);
accounts.updateDevice(auth.accountIdentifier(), auth.deviceId(), device -> {
device.setApnId(null);
device.setGcmId(registrationId.gcmRegistrationId());
device.setFetchesMessages(false);
});
}
@DELETE
@Path("/gcm/")
public void deleteGcmRegistrationId(@Auth AuthenticatedDevice auth) {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
final Device device = account.getDevice(auth.deviceId())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
accounts.updateDevice(account, device.getId(), d -> {
accounts.updateDevice(auth.accountIdentifier(), auth.deviceId(), d -> {
d.setGcmId(null);
d.setFetchesMessages(false);
d.setUserAgent("OWA");
@@ -148,15 +141,9 @@ public class AccountController {
public void setApnRegistrationId(@Auth AuthenticatedDevice auth,
@NotNull @Valid ApnRegistrationId registrationId) {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
final Device device = account.getDevice(auth.deviceId())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
// Unlike FCM tokens, we need current "last updated" timestamps for APNs tokens and so update device records
// unconditionally
accounts.updateDevice(account, device.getId(), d -> {
accounts.updateDevice(auth.accountIdentifier(), auth.deviceId(), d -> {
d.setApnId(registrationId.apnRegistrationId());
d.setGcmId(null);
d.setFetchesMessages(false);
@@ -166,20 +153,10 @@ public class AccountController {
@DELETE
@Path("/apn/")
public void deleteApnRegistrationId(@Auth AuthenticatedDevice auth) {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
final Device device = account.getDevice(auth.deviceId())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
accounts.updateDevice(account, device.getId(), d -> {
accounts.updateDevice(auth.accountIdentifier(), auth.deviceId(), d -> {
d.setApnId(null);
d.setFetchesMessages(false);
if (d.getId() == 1) {
d.setUserAgent("OWI");
} else {
d.setUserAgent("OWP");
}
d.setUserAgent(d.isPrimary() ? "OWI" : "OWP");
});
}
@@ -189,20 +166,14 @@ public class AccountController {
public void setRegistrationLock(@Auth AuthenticatedDevice auth, @NotNull @Valid RegistrationLock accountLock) {
final SaltedTokenHash credentials = SaltedTokenHash.generateFor(accountLock.registrationLock());
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
accounts.update(account,
accounts.update(auth.accountIdentifier(),
a -> a.setRegistrationLock(credentials.hash(), credentials.salt()));
}
@DELETE
@Path("/registration_lock")
public void removeRegistrationLock(@Auth AuthenticatedDevice auth) {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
accounts.update(account, a -> a.setRegistrationLock(null, null));
accounts.update(auth.accountIdentifier(), a -> a.setRegistrationLock(null, null));
}
@PUT
@@ -240,7 +211,7 @@ public class AccountController {
throw new ForbiddenException();
}
accounts.updateDevice(account, targetDeviceId, d -> d.setName(deviceName.deviceName()));
accounts.updateDevice(account.getIdentifier(IdentityType.ACI), targetDeviceId, d -> d.setName(deviceName.deviceName()));
}
@PUT
@@ -252,10 +223,8 @@ public class AccountController {
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent,
@HeaderParam(HeaderUtils.X_SIGNAL_AGENT) String signalAgent,
@NotNull @Valid AccountAttributes attributes) {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
final Account updatedAccount = accounts.update(account, a -> {
final Account updatedAccount = accounts.update(auth.accountIdentifier(), a -> {
a.getDevice(auth.deviceId()).ifPresent(d -> {
d.setFetchesMessages(attributes.getFetchesMessages());
d.setName(attributes.getName());
@@ -306,10 +275,7 @@ public class AccountController {
@ApiResponse(responseCode = "204", description = "Username successfully deleted.", useReturnTypeSchema = true)
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
public void deleteUsernameHash(@Auth final AuthenticatedDevice auth) {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
accounts.clearUsernameHash(account);
accounts.clearUsernameHash(auth.accountIdentifier());
}
@PUT
@@ -332,9 +298,6 @@ public class AccountController {
@Auth final AuthenticatedDevice auth,
@NotNull @Valid final ReserveUsernameHashRequest usernameRequest) throws RateLimitExceededException {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
rateLimiters.getUsernameReserveLimiter().validate(auth.accountIdentifier());
for (final byte[] hash : usernameRequest.usernameHashes()) {
@@ -345,7 +308,7 @@ public class AccountController {
try {
final AccountsManager.UsernameReservation reservation =
accounts.reserveUsernameHash(account, usernameRequest.usernameHashes());
accounts.reserveUsernameHash(auth.accountIdentifier(), usernameRequest.usernameHashes());
return new ReserveUsernameHashResponse(reservation.reservedUsernameHash());
} catch (final UsernameHashNotAvailableException e) {
@@ -374,20 +337,17 @@ public class AccountController {
@Auth final AuthenticatedDevice auth,
@NotNull @Valid final ConfirmUsernameHashRequest confirmRequest) throws RateLimitExceededException {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
try {
usernameHashZkProofVerifier.verifyProof(confirmRequest.zkProof(), confirmRequest.usernameHash());
} catch (final BaseUsernameException e) {
throw new WebApplicationException(Response.status(422).build());
}
rateLimiters.getUsernameSetLimiter().validate(account.getUuid());
rateLimiters.getUsernameSetLimiter().validate(auth.accountIdentifier());
try {
final Account updatedAccount = accounts.confirmReservedUsernameHash(
account,
auth.accountIdentifier(),
confirmRequest.usernameHash(),
confirmRequest.encryptedUsername());
@@ -474,7 +434,7 @@ public class AccountController {
} else {
usernameLinkHandle = UUID.randomUUID();
}
updateUsernameLink(account, usernameLinkHandle, encryptedUsername.usernameLinkEncryptedValue());
updateUsernameLink(account.getIdentifier(IdentityType.ACI), usernameLinkHandle, encryptedUsername.usernameLinkEncryptedValue());
return new UsernameLinkHandle(usernameLinkHandle);
}
@@ -494,10 +454,7 @@ public class AccountController {
// check ratelimiter for username link operations
rateLimiters.forDescriptor(RateLimiters.For.USERNAME_LINK_OPERATION).validate(auth.accountIdentifier());
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
clearUsernameLink(account);
clearUsernameLink(auth.accountIdentifier());
}
@GET
@@ -559,24 +516,21 @@ public class AccountController {
@DELETE
@Path("/me")
public void deleteAccount(@Auth AuthenticatedDevice auth) {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
accounts.delete(account, AccountsManager.DeletionReason.USER_REQUEST);
accounts.delete(auth.accountIdentifier(), AccountsManager.DeletionReason.USER_REQUEST);
}
private void clearUsernameLink(final Account account) {
updateUsernameLink(account, null, null);
private void clearUsernameLink(final UUID accountIdentifier) {
updateUsernameLink(accountIdentifier, null, null);
}
private void updateUsernameLink(
final Account account,
final UUID accountIdentifier,
@Nullable final UUID usernameLinkHandle,
@Nullable final byte[] encryptedUsername) {
if ((encryptedUsername == null) ^ (usernameLinkHandle == null)) {
throw new IllegalStateException("Both or neither arguments must be null");
}
accounts.update(account, a -> a.setUsernameLinkDetails(usernameLinkHandle, encryptedUsername));
accounts.update(accountIdentifier, a -> a.setUsernameLinkDetails(usernameLinkHandle, encryptedUsername));
}
private void requireNotAuthenticated(final Optional<AuthenticatedDevice> authenticatedAccount) {
@@ -5,13 +5,8 @@
package org.whispersystems.textsecuregcm.controllers;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.net.HttpHeaders;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.headers.Header;
import io.swagger.v3.oas.annotations.media.Content;
@@ -33,22 +28,17 @@ import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.time.Instant;
import java.util.Optional;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.ChangesPhoneNumber;
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
import org.whispersystems.textsecuregcm.entities.AccountDataReportResponse;
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
import org.whispersystems.textsecuregcm.entities.ChangeNumberRequest;
import org.whispersystems.textsecuregcm.entities.MismatchedDevicesResponse;
import org.whispersystems.textsecuregcm.entities.PhoneNumberDiscoverabilityRequest;
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
import org.whispersystems.textsecuregcm.entities.StaleDevicesResponse;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
@@ -59,26 +49,14 @@ import org.whispersystems.textsecuregcm.storage.Device;
@io.swagger.v3.oas.annotations.tags.Tag(name = "Account")
public class AccountControllerV2 {
private static final String CHANGE_NUMBER_COUNTER_NAME = name(AccountControllerV2.class, "changeNumber");
private static final String VERIFICATION_TYPE_TAG_NAME = "verification";
private final AccountsManager accountsManager;
private final ChangeNumberManager changeNumberManager;
private final PhoneVerificationTokenManager phoneVerificationTokenManager;
private final RegistrationLockVerificationManager registrationLockVerificationManager;
private final RateLimiters rateLimiters;
public AccountControllerV2(final AccountsManager accountsManager,
final ChangeNumberManager changeNumberManager,
final PhoneVerificationTokenManager phoneVerificationTokenManager,
final RegistrationLockVerificationManager registrationLockVerificationManager,
final RateLimiters rateLimiters) {
final ChangeNumberManager changeNumberManager) {
this.accountsManager = accountsManager;
this.changeNumberManager = changeNumberManager;
this.phoneVerificationTokenManager = phoneVerificationTokenManager;
this.registrationLockVerificationManager = registrationLockVerificationManager;
this.rateLimiters = rateLimiters;
}
@PUT
@@ -111,45 +89,22 @@ public class AccountControllerV2 {
throw new WebApplicationException("Invalid signature", 422);
}
final String number = request.number();
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
// Only verify and check reglock if there's a data change to be made...
if (!account.getNumber().equals(number)) {
rateLimiters.getRegistrationLimiter().validate(number);
final PhoneVerificationRequest.VerificationType verificationType = phoneVerificationTokenManager.verify(
requestContext, number, request);
final Optional<Account> existingAccount = accountsManager.getByE164(number);
if (existingAccount.isPresent()) {
registrationLockVerificationManager.verifyRegistrationLock(existingAccount.get(), request.registrationLock(),
userAgentString, RegistrationLockVerificationManager.Flow.CHANGE_NUMBER, verificationType);
}
Metrics.counter(CHANGE_NUMBER_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgentString),
Tag.of(VERIFICATION_TYPE_TAG_NAME, verificationType.name())))
.increment();
}
// ...but always attempt to make the change in case a client retries and needs to re-send messages
try {
final Account updatedAccount = changeNumberManager.changeNumber(
account,
authenticatedDevice.accountIdentifier(),
StringUtils.isNotBlank(request.sessionId()) ? request.decodeSessionId() : null,
request.recoveryPassword(),
request.registrationLock(),
request.number(),
request.pniIdentityKey(),
request.devicePniSignedPrekeys(),
request.devicePniPqLastResortPrekeys(),
request.deviceMessages(),
request.pniRegistrationIds(),
userAgentString);
requestContext);
return AccountIdentityResponseBuilder.fromAccount(updatedAccount);
} catch (MismatchedDevicesException e) {
} catch (final MismatchedDevicesException e) {
if (!e.getMismatchedDevices().staleDeviceIds().isEmpty()) {
throw new WebApplicationException(Response.status(410)
.type(MediaType.APPLICATION_JSON)
@@ -162,9 +117,9 @@ public class AccountControllerV2 {
e.getMismatchedDevices().extraDeviceIds()))
.build());
}
} catch (IllegalArgumentException e) {
} catch (final IllegalArgumentException e) {
throw new BadRequestException(e);
} catch (MessageTooLargeException e) {
} catch (final MessageTooLargeException e) {
throw new WebApplicationException(Response.Status.REQUEST_ENTITY_TOO_LARGE);
}
}
@@ -179,10 +134,7 @@ public class AccountControllerV2 {
@Auth AuthenticatedDevice auth,
@NotNull @Valid PhoneNumberDiscoverabilityRequest phoneNumberDiscoverability) {
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
accountsManager.update(account, a -> a.setDiscoverableByPhoneNumber(
accountsManager.update(auth.accountIdentifier(), a -> a.setDiscoverableByPhoneNumber(
phoneNumberDiscoverability.discoverableByPhoneNumber()));
}
@@ -50,8 +50,8 @@ import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
import org.whispersystems.textsecuregcm.auth.ChangesLinkedDevices;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.entities.DeviceActivationRequest;
import org.whispersystems.textsecuregcm.entities.DeviceAttributes;
import org.whispersystems.textsecuregcm.entities.DeviceInfo;
import org.whispersystems.textsecuregcm.entities.DeviceInfoList;
import org.whispersystems.textsecuregcm.entities.LinkDeviceRequest;
@@ -93,7 +93,6 @@ public class DeviceController {
private final AccountsManager accounts;
private final RateLimiters rateLimiters;
private final PersistentTimer persistentTimer;
private final Map<String, Integer> maxDeviceConfiguration;
private final EnumMap<ClientPlatform, AtomicInteger> linkedDeviceListenersByPlatform;
private final AtomicInteger linkedDeviceListenersForUnrecognizedPlatforms;
@@ -117,13 +116,11 @@ public class DeviceController {
public DeviceController(final AccountsManager accounts,
final RateLimiters rateLimiters,
final PersistentTimer persistentTimer,
final Map<String, Integer> maxDeviceConfiguration) {
final PersistentTimer persistentTimer) {
this.accounts = accounts;
this.rateLimiters = rateLimiters;
this.persistentTimer = persistentTimer;
this.maxDeviceConfiguration = maxDeviceConfiguration;
linkedDeviceListenersByPlatform =
EnumMapUtil.toEnumMap(ClientPlatform.class, clientPlatform -> buildGauge(clientPlatform.name().toLowerCase()));
@@ -162,10 +159,7 @@ public class DeviceController {
throw new ForbiddenException();
}
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
accounts.removeDevice(account, deviceId);
accounts.removeDevice(auth.accountIdentifier(), deviceId);
}
/**
@@ -204,14 +198,8 @@ public class DeviceController {
rateLimiters.getAllocateDeviceLimiter().validate(account.getUuid());
int maxDeviceLimit = MAX_DEVICES;
if (maxDeviceConfiguration.containsKey(account.getNumber())) {
maxDeviceLimit = maxDeviceConfiguration.get(account.getNumber());
}
if (account.getDevices().size() >= maxDeviceLimit) {
throw new DeviceLimitExceededException(account.getDevices().size(), maxDeviceLimit);
if (account.getDevices().size() >= MAX_DEVICES) {
throw new DeviceLimitExceededException(account.getDevices().size(), MAX_DEVICES);
}
if (auth.deviceId() != Device.PRIMARY_ID) {
@@ -250,7 +238,7 @@ public class DeviceController {
.orElseThrow(ForbiddenException::new);
final DeviceActivationRequest deviceActivationRequest = linkDeviceRequest.deviceActivationRequest();
final AccountAttributes accountAttributes = linkDeviceRequest.accountAttributes();
final DeviceAttributes deviceAttributes = linkDeviceRequest.deviceAttributes();
rateLimiters.getVerifyDeviceLimiter().validate(account.getUuid());
@@ -268,13 +256,11 @@ public class DeviceController {
throw new WebApplicationException(Response.status(422).build());
}
final int maxDeviceLimit = maxDeviceConfiguration.getOrDefault(account.getNumber(), MAX_DEVICES);
if (account.getDevices().size() >= maxDeviceLimit) {
throw new DeviceLimitExceededException(account.getDevices().size(), maxDeviceLimit);
if (account.getDevices().size() >= MAX_DEVICES) {
throw new DeviceLimitExceededException(account.getDevices().size(), MAX_DEVICES);
}
final Set<DeviceCapability> capabilities = accountAttributes.getCapabilities();
final Set<DeviceCapability> capabilities = deviceAttributes.capabilities();
if (capabilities == null) {
throw new WebApplicationException(Response.status(422, "Missing device capabilities").build());
@@ -293,20 +279,21 @@ public class DeviceController {
}
try {
final Pair<Account, Device> accountAndDevice = accounts.addDevice(account, new DeviceSpec(accountAttributes.getName(),
authorizationHeader.getPassword(),
signalAgent,
capabilities,
accountAttributes.getRegistrationId(),
accountAttributes.getPhoneNumberIdentityRegistrationId(),
accountAttributes.getFetchesMessages(),
deviceActivationRequest.apnToken(),
deviceActivationRequest.gcmToken(),
deviceActivationRequest.aciSignedPreKey(),
deviceActivationRequest.pniSignedPreKey(),
deviceActivationRequest.aciPqLastResortPreKey(),
deviceActivationRequest.pniPqLastResortPreKey()),
linkDeviceRequest.verificationCode());
final Pair<Account, Device> accountAndDevice = accounts.addDevice(account.getIdentifier(IdentityType.ACI),
new DeviceSpec(deviceAttributes.name(),
authorizationHeader.getPassword(),
signalAgent,
capabilities,
deviceAttributes.registrationId(),
deviceAttributes.phoneNumberIdentityRegistrationId(),
deviceAttributes.fetchesMessages(),
deviceActivationRequest.apnToken(),
deviceActivationRequest.gcmToken(),
deviceActivationRequest.aciSignedPreKey(),
deviceActivationRequest.pniSignedPreKey(),
deviceActivationRequest.aciPqLastResortPreKey(),
deviceActivationRequest.pniPqLastResortPreKey()),
linkDeviceRequest.verificationCode());
return new LinkDeviceResponse(
accountAndDevice.first().getIdentifier(IdentityType.ACI),
@@ -395,15 +382,8 @@ public class DeviceController {
@PUT
@Produces(MediaType.APPLICATION_JSON)
@Path("/capabilities")
public void setCapabilities(@Auth final AuthenticatedDevice auth,
@NotNull
final Map<String, Boolean> capabilities) {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
accounts.updateDevice(account, auth.deviceId(),
public void setCapabilities(@Auth final AuthenticatedDevice auth, @NotNull final Map<String, Boolean> capabilities) {
accounts.updateDevice(auth.accountIdentifier(), auth.deviceId(),
d -> d.setCapabilities(DeviceCapabilityAdapter.mapToSet(capabilities)));
}
@@ -15,16 +15,12 @@ import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import java.time.Clock;
import java.time.Instant;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.Function;
import javax.annotation.Nonnull;
import org.glassfish.jersey.server.ManagedAsync;
import org.signal.libsignal.zkgroup.InvalidInputException;
@@ -35,7 +31,6 @@ import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
import org.whispersystems.textsecuregcm.entities.RedeemReceiptRequest;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountBadge;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
@@ -121,9 +116,6 @@ public class DonationController {
.build();
}
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
final boolean receiptMatched = redeemedReceiptsManager.put(
receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, auth.accountIdentifier()).join();
if (!receiptMatched) {
@@ -133,7 +125,7 @@ public class DonationController {
.build();
}
accountsManager.update(account, a -> {
accountsManager.update(auth.accountIdentifier(), a -> {
a.addBadge(clock, new AccountBadge(badgeId, receiptExpiration, request.isVisible()));
if (request.isPrimary()) {
a.makeBadgePrimaryIfExists(clock, badgeId);
@@ -53,7 +53,6 @@ import java.util.concurrent.Executor;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.glassfish.jersey.server.ManagedAsync;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ServiceId;
@@ -63,6 +62,8 @@ import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.groupsend.GroupSendDerivedKeyPair;
import org.signal.libsignal.zkgroup.groupsend.GroupSendFullToken;
import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialResponse;
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCommitment;
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.whispersystems.textsecuregcm.auth.Anonymous;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
@@ -80,11 +81,11 @@ import org.whispersystems.textsecuregcm.entities.CreateProfileRequest;
import org.whispersystems.textsecuregcm.entities.ExpiringProfileKeyCredentialProfileResponse;
import org.whispersystems.textsecuregcm.entities.ProfileAvatarUploadAttributes;
import org.whispersystems.textsecuregcm.entities.VersionedProfileResponse;
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.s3.PolicySigner;
@@ -95,8 +96,7 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.ProfileHelper;
@@ -125,7 +125,6 @@ public class ProfileController {
private static final String VERSION_NOT_FOUND_COUNTER_NAME = name(ProfileController.class, "versionNotFound");
private static final String DUPLICATE_AUTHENTICATION_COUNTER_NAME = name(ProfileController.class, "duplicateAuthentication");
private static final String BATCH_IDENTITY_CHECK_RATE_LIMITED_COUNTER_NAME = name(ProfileController.class, "batchIdentityCheckRateLimited");
public ProfileController(
Clock clock,
@@ -175,33 +174,28 @@ public class ProfileController {
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
final Optional<VersionedProfile> currentProfile =
profilesManager.get(auth.accountIdentifier(), request.version());
if (account.hasCapability(DeviceCapability.PROFILES_V2)) {
return Response.status(Response.Status.PRECONDITION_FAILED).build();
}
final Optional<VersionedProfileV1> currentProfile =
profilesManager.getV1(auth.accountIdentifier(), request.version());
if (request.paymentAddress() != null && request.paymentAddress().length != 0) {
final boolean hasDisallowedPrefix =
dynamicConfigurationManager.getConfiguration().getPaymentsConfiguration().getDisallowedPrefixes().stream()
.anyMatch(prefix -> account.getNumber().startsWith(prefix));
if (hasDisallowedPrefix && currentProfile.map(VersionedProfile::paymentAddress).isEmpty()) {
if (hasDisallowedPrefix && currentProfile.map(VersionedProfileV1::paymentAddress).isEmpty()) {
return Response.status(Response.Status.FORBIDDEN).build();
}
}
Optional<String> currentAvatar = Optional.empty();
if (currentProfile.isPresent() && currentProfile.get().avatar() != null && currentProfile.get().avatar()
.startsWith("profiles/")) {
currentAvatar = Optional.of(currentProfile.get().avatar());
}
final Optional<String> currentAvatar = ProfileHelper.getCurrentAvatar(currentProfile);
final String avatar = ProfileHelper.getAvatar(request.getAvatarChange(), currentAvatar);
final String avatar = switch (request.getAvatarChange()) {
case UNCHANGED -> currentAvatar.orElse(null);
case CLEAR -> null;
case UPDATE -> ProfileHelper.generateAvatarObjectName();
};
profilesManager.set(auth.accountIdentifier(),
new VersionedProfile(
profilesManager.setV1(auth.accountIdentifier(),
new VersionedProfileV1(
request.version(),
request.name(),
avatar,
@@ -215,7 +209,7 @@ public class ProfileController {
currentAvatar.ifPresent(profilesManager::deleteAvatar);
}
accountsManager.update(account, a -> {
accountsManager.update(account.getIdentifier(IdentityType.ACI), a -> {
final List<AccountBadge> updatedBadges = request.badges()
.map(badges -> ProfileHelper.mergeBadgeIdsWithExistingAccountBadges(clock, badgeConfigurationMap, badges, a.getBadges()))
@@ -368,6 +362,7 @@ public class ProfileController {
@Path("/identity_check/batch")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@RateLimitedByIp(RateLimiters.For.BATCH_IDENTITY_CHECK)
@Operation(
summary = "Batch identity key check",
description = "Checks identity key fingerprints for multiple accounts. Returns accounts where the fingerprint does not match. Should not be authenticated.")
@@ -376,20 +371,8 @@ public class ProfileController {
description = "Batch check completed successfully. Response may contain accounts with mismatched fingerprints.",
content = @Content(schema = @Schema(implementation = BatchIdentityCheckResponse.class)))
@ApiResponse(responseCode = "400", description = "Invalid request format or validation failed.")
public CompletableFuture<BatchIdentityCheckResponse> runBatchIdentityCheck(
@NotNull @Valid final BatchIdentityCheckRequest request,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@Context final ContainerRequestContext containerRequestContext) {
final String remoteAddress = (String) containerRequestContext.getProperty(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
if (StringUtils.isNotBlank(remoteAddress)) {
rateLimiters.getBatchIdentityCheckLimiter().validateAsync(remoteAddress)
.whenComplete((_, t) -> {
if (t != null && ExceptionUtils.unwrap(t) instanceof RateLimitExceededException) {
Metrics.counter(BATCH_IDENTITY_CHECK_RATE_LIMITED_COUNTER_NAME,
Tags.of(UserAgentTagUtil.getPlatformTag(userAgent))).increment();
}
});
}
@ApiResponse(responseCode = "429", description = "Rate limit exceeded.")
public CompletableFuture<BatchIdentityCheckResponse> runBatchIdentityCheck(@NotNull @Valid final BatchIdentityCheckRequest request) {
return CompletableFuture.supplyAsync(() -> {
List<BatchIdentityCheckResponse.Element> responseElements = Collections.synchronizedList(new ArrayList<>());
@@ -454,13 +437,14 @@ public class ProfileController {
final ExpiringProfileKeyCredentialResponse expiringProfileKeyCredentialResponse;
if (account.getCurrentProfileVersion().map(version::equals).orElse(false)) {
expiringProfileKeyCredentialResponse = profilesManager.get(account.getUuid(), version)
expiringProfileKeyCredentialResponse = profilesManager.getV1(account.getUuid(), version)
.map(profile -> {
final ExpiringProfileKeyCredentialResponse profileKeyCredentialResponse;
try {
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(
HexFormat.of().parseHex(encodedCredentialRequest),
profile, new ServiceId.Aci(account.getUuid()), zkProfileOperations);
new ProfileKeyCredentialRequest(HexFormat.of().parseHex(encodedCredentialRequest)),
new ProfileKeyCommitment(profile.commitment()), new ServiceId.Aci(account.getUuid()),
zkProfileOperations);
} catch (VerificationFailedException | InvalidInputException e) {
throw new BadRequestException(e);
}
@@ -482,7 +466,7 @@ public class ProfileController {
final boolean hasCredentialRequest,
final ContainerRequestContext containerRequestContext) {
final Optional<VersionedProfile> maybeProfile = profilesManager.get(account.getUuid(), version);
final Optional<VersionedProfileV1> maybeProfile = profilesManager.getV1(account.getUuid(), version);
if (maybeProfile.isEmpty()) {
// this can happen if an account re-registers, which includes some device-transfer scenarios
@@ -495,17 +479,17 @@ public class ProfileController {
.increment();
}
final byte[] name = maybeProfile.map(VersionedProfile::name).orElse(null);
final byte[] about = maybeProfile.map(VersionedProfile::about).orElse(null);
final byte[] aboutEmoji = maybeProfile.map(VersionedProfile::aboutEmoji).orElse(null);
final String avatar = maybeProfile.map(VersionedProfile::avatar).orElse(null);
final byte[] phoneNumberSharing = maybeProfile.map(VersionedProfile::phoneNumberSharing).orElse(null);
final byte[] name = maybeProfile.map(VersionedProfileV1::name).orElse(null);
final byte[] about = maybeProfile.map(VersionedProfileV1::about).orElse(null);
final byte[] aboutEmoji = maybeProfile.map(VersionedProfileV1::aboutEmoji).orElse(null);
final String avatar = maybeProfile.map(VersionedProfileV1::avatar).orElse(null);
final byte[] phoneNumberSharing = maybeProfile.map(VersionedProfileV1::phoneNumberSharing).orElse(null);
// Allow requests where either the version matches the latest version on Account or the latest version on Account
// is empty to read the payment address.
final byte[] paymentAddress = maybeProfile
.filter(p -> account.getCurrentProfileVersion().map(v -> v.equals(version)).orElse(true))
.map(VersionedProfile::paymentAddress)
.filter(p -> account.getCurrentProfileVersion().map(v -> v.equals(p.version())).orElse(true))
.map(VersionedProfileV1::paymentAddress)
.orElse(null);
return new VersionedProfileResponse(
@@ -34,6 +34,7 @@ import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
@@ -134,7 +135,10 @@ public class RegistrationController {
rateLimiters.getRegistrationLimiter().validate(number);
final PhoneVerificationRequest.VerificationType verificationType =
phoneVerificationTokenManager.verify(requestContext, number, registrationRequest);
phoneVerificationTokenManager.verify(requestContext,
number,
StringUtils.isNotBlank(registrationRequest.sessionId()) ? registrationRequest.decodeSessionId() : null,
registrationRequest.recoveryPassword());
// There can be at most one existing account for a set of numbers in the same equivalence class, so it's sufficient
// to find the first one.
@@ -4,40 +4,26 @@
*/
package org.whispersystems.textsecuregcm.entities;
import static org.whispersystems.textsecuregcm.util.RegistrationIdValidator.validRegistrationId;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.google.common.annotations.VisibleForTesting;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.Size;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import org.whispersystems.textsecuregcm.util.DeviceCapabilityAdapter;
import org.whispersystems.textsecuregcm.util.ExactlySize;
public class AccountAttributes {
@JsonProperty
private boolean fetchesMessages;
@JsonProperty
private int registrationId;
@JsonProperty("pniRegistrationId")
private int phoneNumberIdentityRegistrationId;
@JsonProperty
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
@Size(max = 225)
private byte[] name;
@JsonUnwrapped
@Valid
private DeviceAttributes deviceAttributes;
@JsonProperty
@ExactlySize({0, 64})
@@ -50,12 +36,6 @@ public class AccountAttributes {
@JsonProperty
private boolean unrestrictedUnidentifiedAccess;
@JsonProperty
@JsonSerialize(using = DeviceCapabilityAdapter.Serializer.class)
@JsonDeserialize(using = DeviceCapabilityAdapter.Deserializer.class)
@Nullable
private Set<DeviceCapability> capabilities;
@JsonProperty
private boolean discoverableByPhoneNumber = true;
@@ -77,29 +57,26 @@ public class AccountAttributes {
final String registrationLock,
final boolean discoverableByPhoneNumber,
final Set<DeviceCapability> capabilities) {
this.fetchesMessages = fetchesMessages;
this.registrationId = registrationId;
this.phoneNumberIdentityRegistrationId = phoneNumberIdentifierRegistrationId;
this.name = name;
this.deviceAttributes = new DeviceAttributes(fetchesMessages, registrationId, phoneNumberIdentifierRegistrationId, name, capabilities);
this.registrationLock = registrationLock;
this.discoverableByPhoneNumber = discoverableByPhoneNumber;
this.capabilities = capabilities;
}
public boolean getFetchesMessages() {
return fetchesMessages;
return deviceAttributes.fetchesMessages();
}
public int getRegistrationId() {
return registrationId;
return deviceAttributes.registrationId();
}
public int getPhoneNumberIdentityRegistrationId() {
return phoneNumberIdentityRegistrationId;
return deviceAttributes.phoneNumberIdentityRegistrationId();
}
public byte[] getName() {
return name;
return deviceAttributes.name();
}
public String getRegistrationLock() {
@@ -116,7 +93,7 @@ public class AccountAttributes {
@Nullable
public Set<DeviceCapability> getCapabilities() {
return capabilities;
return deviceAttributes.capabilities();
}
public boolean isDiscoverableByPhoneNumber() {
@@ -128,20 +105,33 @@ public class AccountAttributes {
}
@VisibleForTesting
public AccountAttributes withUnidentifiedAccessKey(final byte[] unidentifiedAccessKey) {
public AccountAttributes setUnidentifiedAccessKey(final byte[] unidentifiedAccessKey) {
this.unidentifiedAccessKey = unidentifiedAccessKey;
return this;
}
@VisibleForTesting
public AccountAttributes withRecoveryPassword(final byte[] recoveryPassword) {
public AccountAttributes setRecoveryPassword(final byte[] recoveryPassword) {
this.recoveryPassword = recoveryPassword;
return this;
}
@VisibleForTesting
public AccountAttributes setDeviceAttributes(final DeviceAttributes deviceAttributes) {
this.deviceAttributes = deviceAttributes;
return this;
}
@VisibleForTesting
public AccountAttributes setUnrestrictedUnidentifiedAccess(final boolean unrestrictedUnidentifiedAccess) {
this.unrestrictedUnidentifiedAccess = unrestrictedUnidentifiedAccess;
return this;
}
@AssertTrue
@Schema(hidden = true)
public boolean isEachRegistrationIdValid() {
return validRegistrationId(registrationId) && validRegistrationId(phoneNumberIdentityRegistrationId);
public boolean isUnrestrictedUakValid() {
return unrestrictedUnidentifiedAccess || (unidentifiedAccessKey != null && unidentifiedAccessKey.length == 16);
}
}
@@ -0,0 +1,46 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.entities;
import static org.whispersystems.textsecuregcm.util.RegistrationIdValidator.validRegistrationId;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.Size;
import java.util.Set;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import org.whispersystems.textsecuregcm.util.DeviceCapabilityAdapter;
public record DeviceAttributes(
boolean fetchesMessages,
int registrationId,
@JsonProperty("pniRegistrationId") int phoneNumberIdentityRegistrationId,
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
@Size(max = 225)
byte[] name,
@JsonSerialize(using = DeviceCapabilityAdapter.Serializer.class)
@JsonDeserialize(using = DeviceCapabilityAdapter.Deserializer.class)
@Nullable
Set<DeviceCapability> capabilities) {
@AssertTrue
@Schema(hidden = true)
public boolean isEachRegistrationIdValid() {
return validRegistrationId(registrationId) && validRegistrationId(phoneNumberIdentityRegistrationId);
}
}
@@ -19,7 +19,8 @@ public record LinkDeviceRequest(@Schema(requiredMode = Schema.RequiredMode.REQUI
@NotNull
@Valid
AccountAttributes accountAttributes,
@JsonProperty("accountAttributes")
DeviceAttributes deviceAttributes,
@NotNull
@Valid
@@ -30,7 +31,7 @@ public record LinkDeviceRequest(@Schema(requiredMode = Schema.RequiredMode.REQUI
@JsonCreator
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public LinkDeviceRequest(@JsonProperty("verificationCode") String verificationCode,
@JsonProperty("accountAttributes") AccountAttributes accountAttributes,
@JsonProperty("accountAttributes") DeviceAttributes deviceAttributes,
@JsonProperty("aciSignedPreKey") @NotNull @Valid ECSignedPreKey aciSignedPreKey,
@JsonProperty("pniSignedPreKey") @NotNull @Valid ECSignedPreKey pniSignedPreKey,
@JsonProperty("aciPqLastResortPreKey") @NotNull @Valid KEMSignedPreKey aciPqLastResortPreKey,
@@ -38,14 +39,14 @@ public record LinkDeviceRequest(@Schema(requiredMode = Schema.RequiredMode.REQUI
@JsonProperty("apnToken") Optional<@Valid ApnRegistrationId> apnToken,
@JsonProperty("gcmToken") Optional<@Valid GcmRegistrationId> gcmToken) {
this(verificationCode, accountAttributes,
this(verificationCode, deviceAttributes,
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, apnToken, gcmToken));
}
@AssertTrue
@Schema(hidden = true)
public boolean isExactlyOneMessageDeliveryChannel() {
if (accountAttributes != null && accountAttributes.getFetchesMessages()) {
if (deviceAttributes != null && deviceAttributes.fetchesMessages()) {
return deviceActivationRequest().apnToken().isEmpty() && deviceActivationRequest().gcmToken().isEmpty();
} else {
return deviceActivationRequest().apnToken().isPresent() ^ deviceActivationRequest().gcmToken().isPresent();
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.List;
import java.util.UUID;
@@ -34,6 +35,8 @@ import org.signal.chat.account.SetRegistrationRecoveryPasswordRequest;
import org.signal.chat.account.SetRegistrationRecoveryPasswordResponse;
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.SimpleAccountsGrpc;
import org.signal.chat.account.UsernameNotAvailable;
import org.signal.chat.common.AccountIdentifiers;
@@ -94,8 +97,8 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
@Override
public DeleteAccountResponse deleteAccount(final DeleteAccountRequest request) {
accountsManager.delete(getAuthenticatedAccount(AuthenticationUtil.requireAuthenticatedPrimaryDevice()),
AccountsManager.DeletionReason.USER_REQUEST);
accountsManager.delete(AuthenticationUtil.requireAuthenticatedPrimaryDevice().accountIdentifier(),
AccountsManager.DeletionReason.USER_REQUEST);
return DeleteAccountResponse.getDefaultInstance();
}
@@ -107,7 +110,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
final SaltedTokenHash credentials =
SaltedTokenHash.generateFor(HexFormat.of().withLowerCase().formatHex(request.getRegistrationLock().toByteArray()));
accountsManager.update(getAuthenticatedAccount(AuthenticationUtil.requireAuthenticatedPrimaryDevice()),
accountsManager.update(AuthenticationUtil.requireAuthenticatedPrimaryDevice().accountIdentifier(),
account -> account.setRegistrationLock(credentials.hash(), credentials.salt()));
return SetRegistrationLockResponse.getDefaultInstance();
@@ -115,7 +118,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
@Override
public ClearRegistrationLockResponse clearRegistrationLock(final ClearRegistrationLockRequest request) {
accountsManager.update(getAuthenticatedAccount(AuthenticationUtil.requireAuthenticatedPrimaryDevice()),
accountsManager.update(AuthenticationUtil.requireAuthenticatedPrimaryDevice().accountIdentifier(),
account -> account.setRegistrationLock(null, null));
return ClearRegistrationLockResponse.getDefaultInstance();
@@ -139,11 +142,9 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
rateLimiters.getUsernameReserveLimiter().validate(authenticatedDevice.accountIdentifier());
final Account account = getAuthenticatedAccount();
try {
final AccountsManager.UsernameReservation usernameReservation =
accountsManager.reserveUsernameHash(account, usernameHashes);
accountsManager.reserveUsernameHash(authenticatedDevice.accountIdentifier(), usernameHashes);
return ReserveUsernameHashResponse.newBuilder()
.setUsernameHash(ByteString.copyFrom(usernameReservation.reservedUsernameHash()))
@@ -169,7 +170,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
rateLimiters.getUsernameSetLimiter().validate(authenticatedDevice.accountIdentifier());
try {
final Account updatedAccount = accountsManager.confirmReservedUsernameHash(getAuthenticatedAccount(),
final Account updatedAccount = accountsManager.confirmReservedUsernameHash(authenticatedDevice.accountIdentifier(),
request.getUsernameHash().toByteArray(),
request.getUsernameCiphertext().toByteArray());
@@ -193,7 +194,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
@Override
public DeleteUsernameHashResponse deleteUsernameHash(final DeleteUsernameHashRequest request) {
accountsManager.clearUsernameHash(getAuthenticatedAccount());
accountsManager.clearUsernameHash(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier());
return DeleteUsernameHashResponse.getDefaultInstance();
}
@@ -217,7 +218,8 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
? account.getUsernameLinkHandle()
: UUID.randomUUID();
accountsManager.update(account, a -> a.setUsernameLinkDetails(linkHandle, request.getUsernameCiphertext().toByteArray()));
accountsManager.update(account.getIdentifier(IdentityType.ACI),
a -> a.setUsernameLinkDetails(linkHandle, request.getUsernameCiphertext().toByteArray()));
return responseBuilder.setUsernameLinkHandle(UUIDUtil.toByteString(linkHandle)).build();
}
@@ -229,7 +231,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
rateLimiters.getUsernameLinkOperationLimiter().validate(authenticatedDevice.accountIdentifier());
accountsManager.update(getAuthenticatedAccount(), a -> a.setUsernameLinkDetails(null, null));
accountsManager.update(authenticatedDevice.accountIdentifier(), a -> a.setUsernameLinkDetails(null, null));
return DeleteUsernameLinkResponse.getDefaultInstance();
}
@@ -242,7 +244,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH, request.getUnidentifiedAccessKey().size()));
}
accountsManager.update(getAuthenticatedAccount(), account -> {
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(), account -> {
account.setUnrestrictedUnidentifiedAccess(request.getAllowUnrestrictedUnidentifiedAccess());
account.setUnidentifiedAccessKey(request.getAllowUnrestrictedUnidentifiedAccess() ? null : request.getUnidentifiedAccessKey().toByteArray());
});
@@ -252,7 +254,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
@Override
public SetDiscoverableByPhoneNumberResponse setDiscoverableByPhoneNumber(final SetDiscoverableByPhoneNumberRequest request) {
accountsManager.update(getAuthenticatedAccount(),
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
account -> account.setDiscoverableByPhoneNumber(request.getDiscoverableByPhoneNumber()));
return SetDiscoverableByPhoneNumberResponse.getDefaultInstance();
@@ -267,6 +269,24 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
return SetRegistrationRecoveryPasswordResponse.getDefaultInstance();
}
@Override
public SetZkCredentialKeyResponse setZkCredentialKey(final SetZkCredentialKeyRequest request) throws RateLimitExceededException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final Account authenticatedAccount = getAuthenticatedAccount();
final byte[] zkCredentialKey = request.getPublicKey().toByteArray();
if (Arrays.equals(authenticatedAccount.getZkCredentialKey(), zkCredentialKey)) {
return SetZkCredentialKeyResponse.getDefaultInstance();
}
rateLimiters.getSetZkCredentialKeyLimiter().validate(authenticatedDevice.accountIdentifier());
accountsManager.update(authenticatedDevice.accountIdentifier(), account -> account.setZkCredentialKey(zkCredentialKey));
return SetZkCredentialKeyResponse.getDefaultInstance();
}
private Account getAuthenticatedAccount() {
return getAuthenticatedAccount(AuthenticationUtil.requireAuthenticatedDevice());
}
@@ -9,7 +9,7 @@ import io.grpc.Status;
import org.whispersystems.textsecuregcm.entities.AvatarChange;
public class AvatarChangeUtil {
public static AvatarChange fromGrpcAvatarChange(final org.signal.chat.profile.SetProfileRequest.AvatarChange avatarChangeType) {
public static AvatarChange fromGrpcAvatarChange(final org.signal.chat.profile.SetProfileV1Request.AvatarChange avatarChangeType) {
return switch (avatarChangeType) {
case AVATAR_CHANGE_UNCHANGED -> AvatarChange.AVATAR_CHANGE_UNCHANGED;
case AVATAR_CHANGE_CLEAR -> AvatarChange.AVATAR_CHANGE_CLEAR;
@@ -18,6 +18,7 @@ public class DeviceCapabilityUtil {
case DEVICE_CAPABILITY_TRANSFER -> DeviceCapability.TRANSFER;
case DEVICE_CAPABILITY_ATTACHMENT_BACKFILL -> DeviceCapability.ATTACHMENT_BACKFILL;
case DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET -> DeviceCapability.SPARSE_POST_QUANTUM_RATCHET;
case DEVICE_CAPABILITY_PROFILES_V2 -> DeviceCapability.PROFILES_V2;
case DEVICE_CAPABILITY_UNSPECIFIED, UNRECOGNIZED ->
throw GrpcExceptions.invalidArguments("unrecognized device capability");
};
@@ -29,6 +30,7 @@ public class DeviceCapabilityUtil {
case TRANSFER -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_TRANSFER;
case ATTACHMENT_BACKFILL -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_ATTACHMENT_BACKFILL;
case SPARSE_POST_QUANTUM_RATCHET -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET;
case PROFILES_V2 -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_PROFILES_V2;
};
}
}
@@ -80,9 +80,7 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase {
throw GrpcExceptions.badAuthentication("linked devices cannot remove devices other than themselves");
}
final byte deviceId = DeviceIdUtil.validate(request.getId());
accountsManager.removeDevice(getAuthenticatedAccount(), deviceId);
accountsManager.removeDevice(authenticatedDevice.accountIdentifier(), DeviceIdUtil.validate(request.getId()));
return RemoveDeviceResponse.getDefaultInstance();
}
@@ -106,7 +104,7 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase {
return SetDeviceNameResponse.newBuilder().setTargetDeviceNotFound(NotFound.getDefaultInstance()).build();
}
accountsManager.updateDevice(account, deviceId, device -> device.setName(request.getName().toByteArray()));
accountsManager.updateDevice(account.getIdentifier(IdentityType.ACI), deviceId, device -> device.setName(request.getName().toByteArray()));
return SetDeviceNameResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
}
@@ -141,7 +139,7 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase {
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
if (!Objects.equals(device.getApnId(), apnsToken) || !Objects.equals(device.getGcmId(), fcmToken)) {
accountsManager.updateDevice(account, authenticatedDevice.deviceId(), d -> {
accountsManager.updateDevice(account.getIdentifier(IdentityType.ACI), authenticatedDevice.deviceId(), d -> {
d.setApnId(apnsToken);
d.setGcmId(fcmToken);
d.setFetchesMessages(false);
@@ -154,9 +152,8 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase {
@Override
public ClearPushTokenResponse clearPushToken(final ClearPushTokenRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final Account account = getAuthenticatedAccount();
accountsManager.updateDevice(account, authenticatedDevice.deviceId(), device -> {
accountsManager.updateDevice(authenticatedDevice.accountIdentifier(), authenticatedDevice.deviceId(), device -> {
if (StringUtils.isNotBlank(device.getApnId())) {
device.setUserAgent(device.isPrimary() ? "OWI" : "OWP");
} else if (StringUtils.isNotBlank(device.getGcmId())) {
@@ -179,7 +176,7 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase {
.map(DeviceCapabilityUtil::fromGrpcDeviceCapability)
.collect(Collectors.toSet());
accountsManager.updateDevice(getAuthenticatedAccount(), authenticatedDevice.deviceId(),
accountsManager.updateDevice(authenticatedDevice.accountIdentifier(), authenticatedDevice.deviceId(),
device -> device.setCapabilities(capabilities));
return SetCapabilitiesResponse.getDefaultInstance();
@@ -5,16 +5,18 @@
package org.whispersystems.textsecuregcm.grpc;
import io.grpc.Status;
import io.grpc.StatusException;
import java.time.Clock;
import java.util.Optional;
import com.google.common.annotations.VisibleForTesting;
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
import org.signal.chat.errors.NotFound;
import org.signal.chat.profile.CredentialType;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousRequest;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResponse;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousResponse;
import org.signal.chat.profile.GetUnversionedProfileAnonymousRequest;
import org.signal.chat.profile.GetUnversionedProfileResponse;
import org.signal.chat.profile.GetUnversionedProfileAnonymousResponse;
import org.signal.chat.profile.GetVersionedProfileAnonymousRequest;
import org.signal.chat.profile.GetVersionedProfileResponse;
import org.signal.chat.profile.GetVersionedProfileAnonymousResponse;
import org.signal.chat.profile.SimpleProfileAnonymousGrpc;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
@@ -38,77 +40,116 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
final ProfilesManager profilesManager,
final ProfileBadgeConverter profileBadgeConverter,
final ServerSecretParams serverSecretParams) {
this(accountsManager,
profilesManager,
profileBadgeConverter,
new ServerZkProfileOperations(serverSecretParams),
new GroupSendTokenUtil(serverSecretParams, Clock.systemUTC()));
}
@VisibleForTesting
ProfileAnonymousGrpcService(final AccountsManager accountsManager,
final ProfilesManager profilesManager,
final ProfileBadgeConverter profileBadgeConverter,
final ServerZkProfileOperations zkProfileOperations,
final GroupSendTokenUtil groupSendTokenUtil) {
this.accountsManager = accountsManager;
this.profilesManager = profilesManager;
this.profileBadgeConverter = profileBadgeConverter;
this.zkProfileOperations = new ServerZkProfileOperations(serverSecretParams);
this.groupSendTokenUtil = new GroupSendTokenUtil(serverSecretParams, Clock.systemUTC());
this.zkProfileOperations = zkProfileOperations;
this.groupSendTokenUtil = groupSendTokenUtil;
}
@Override
public GetUnversionedProfileResponse getUnversionedProfile(final GetUnversionedProfileAnonymousRequest request) throws StatusException {
public GetUnversionedProfileAnonymousResponse getUnversionedProfile(final GetUnversionedProfileAnonymousRequest request) {
final ServiceIdentifier targetIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getServiceIdentifier());
// Callers must be authenticated to request unversioned profiles by PNI
if (targetIdentifier.identityType() == IdentityType.PNI) {
throw Status.UNAUTHENTICATED.asException();
throw GrpcExceptions.invalidArguments("aci service identifier type required");
}
final Account account = switch (request.getAuthenticationCase()) {
case GROUP_SEND_TOKEN -> {
if (!groupSendTokenUtil.checkGroupSendToken(request.getGroupSendToken(), targetIdentifier)) {
throw Status.UNAUTHENTICATED.asException();
}
yield accountsManager.getByServiceIdentifier(targetIdentifier)
.orElseThrow(Status.NOT_FOUND::asException);
}
final Optional<Account> targetAccount = accountsManager.getByServiceIdentifier(targetIdentifier);
final boolean authorized = switch (request.getAuthenticationCase()) {
case GROUP_SEND_TOKEN -> groupSendTokenUtil.checkGroupSendToken(request.getGroupSendToken(), targetIdentifier);
case UNIDENTIFIED_ACCESS_KEY ->
getTargetAccountAndValidateUnidentifiedAccess(targetIdentifier, request.getUnidentifiedAccessKey().toByteArray());
default -> throw Status.INVALID_ARGUMENT.asException();
targetAccount.map(a -> UnidentifiedAccessUtil.checkUnidentifiedAccess(a, request.getUnidentifiedAccessKey().toByteArray()))
.orElse(false);
default -> throw GrpcExceptions.constraintViolation("invalid authentication");
};
return ProfileGrpcHelper.buildUnversionedProfileResponse(targetIdentifier,
null,
account,
profileBadgeConverter);
if (!authorized) {
return GetUnversionedProfileAnonymousResponse.newBuilder()
.setFailedUnidentifiedAuthorization(FailedUnidentifiedAuthorization.getDefaultInstance())
.build();
}
return targetAccount.map(account ->
GetUnversionedProfileAnonymousResponse.newBuilder()
.setResult(ProfileGrpcHelper.buildUnversionedProfileResult(targetIdentifier,
null,
account,
profileBadgeConverter))
.build())
.orElseGet(() -> GetUnversionedProfileAnonymousResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build());
}
@Override
public GetVersionedProfileResponse getVersionedProfile(final GetVersionedProfileAnonymousRequest request) throws StatusException {
public GetVersionedProfileAnonymousResponse getVersionedProfile(final GetVersionedProfileAnonymousRequest request) {
final ServiceIdentifier targetIdentifier = ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier());
if (targetIdentifier.identityType() != IdentityType.ACI) {
throw Status.INVALID_ARGUMENT.withDescription("Expected ACI service identifier").asException();
}
final Optional<Account> targetAccount = getTargetAccountAndValidateUnidentifiedAccess(targetIdentifier, request.getUnidentifiedAccessKey().toByteArray());
final Account targetAccount = getTargetAccountAndValidateUnidentifiedAccess(targetIdentifier, request.getUnidentifiedAccessKey().toByteArray());
return ProfileGrpcHelper.getVersionedProfile(targetAccount, profilesManager, request.getRequest().getVersion());
return targetAccount.flatMap(account ->
ProfileGrpcHelper.getVersionedProfile(account,
profilesManager,
request.getRequest().getVersion().toByteArray(),
request.getRequest().getDataEtag().toByteArray(),
request.getRequest().getPaymentAddressEtag().toByteArray()))
.map(result ->
GetVersionedProfileAnonymousResponse.newBuilder()
.setResult(result)
.build())
.orElseGet(() ->
GetVersionedProfileAnonymousResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build());
}
@Override
public GetExpiringProfileKeyCredentialResponse getExpiringProfileKeyCredential(
final GetExpiringProfileKeyCredentialAnonymousRequest request) throws StatusException {
public GetExpiringProfileKeyCredentialAnonymousResponse getExpiringProfileKeyCredential(
final GetExpiringProfileKeyCredentialAnonymousRequest request) {
final ServiceIdentifier targetIdentifier = ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier());
if (targetIdentifier.identityType() != IdentityType.ACI) {
throw Status.INVALID_ARGUMENT.withDescription("Expected ACI service identifier").asException();
}
if (request.getRequest().getCredentialType() != CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY) {
throw Status.INVALID_ARGUMENT.withDescription("Expected expiring profile key credential type").asException();
throw GrpcExceptions.constraintViolation("invalid credential type");
}
final Account account = getTargetAccountAndValidateUnidentifiedAccess(
final Optional<Account> maybeAccount = getTargetAccountAndValidateUnidentifiedAccess(
targetIdentifier, request.getUnidentifiedAccessKey().toByteArray());
return ProfileGrpcHelper.getExpiringProfileKeyCredentialResponse(account.getUuid(),
request.getRequest().getVersion(), request.getRequest().getCredentialRequest().toByteArray(), profilesManager, zkProfileOperations);
return maybeAccount.map(account ->
ProfileGrpcHelper.getExpiringProfileKeyCredentialResult(account,
request.getRequest().getVersion().toByteArray(), request.getRequest().getCredentialRequest().toByteArray(),
profilesManager, zkProfileOperations)
.map(result -> GetExpiringProfileKeyCredentialAnonymousResponse.newBuilder()
.setResult(result)
.build())
.orElseGet(() -> GetExpiringProfileKeyCredentialAnonymousResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build())).orElseGet(() -> GetExpiringProfileKeyCredentialAnonymousResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build());
}
private Account getTargetAccountAndValidateUnidentifiedAccess(final ServiceIdentifier targetIdentifier, final byte[] unidentifiedAccessKey) throws StatusException {
private Optional<Account> getTargetAccountAndValidateUnidentifiedAccess(final ServiceIdentifier targetIdentifier, final byte[] unidentifiedAccessKey) {
return accountsManager.getByServiceIdentifier(targetIdentifier)
.filter(targetAccount -> UnidentifiedAccessUtil.checkUnidentifiedAccess(targetAccount, unidentifiedAccessKey))
.orElseThrow(Status.UNAUTHENTICATED::asException);
.filter(targetAccount -> UnidentifiedAccessUtil.checkUnidentifiedAccess(targetAccount, unidentifiedAccessKey));
}
}
@@ -7,21 +7,27 @@ package org.whispersystems.textsecuregcm.grpc;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.ByteString;
import io.grpc.Status;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import io.grpc.StatusException;
import org.signal.chat.profile.Badge;
import org.signal.chat.profile.BadgeSvg;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResponse;
import org.signal.chat.profile.GetUnversionedProfileResponse;
import org.signal.chat.profile.GetVersionedProfileResponse;
import org.signal.chat.profile.DataEtag;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResult;
import org.signal.chat.profile.GetUnversionedProfileResult;
import org.signal.chat.profile.GetVersionedProfileResult;
import org.signal.chat.profile.GetVersionedProfileV1Response;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialResponse;
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCommitment;
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
@@ -30,32 +36,88 @@ import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
import org.whispersystems.textsecuregcm.util.ProfileHelper;
public class ProfileGrpcHelper {
static GetVersionedProfileResponse getVersionedProfile(final Account account,
static Optional<GetVersionedProfileResult> getVersionedProfile(final Account account,
final ProfilesManager profilesManager,
final String requestVersion) throws StatusException {
final byte[] requestVersion,
final byte[] requestDataEtag,
final byte[] requestPaymentAddressEtag) {
final VersionedProfile profile = profilesManager.get(account.getUuid(), requestVersion)
.orElseThrow(Status.NOT_FOUND.withDescription("Profile version not found")::asException);
final GetVersionedProfileResponse.Builder responseBuilder = GetVersionedProfileResponse.newBuilder();
responseBuilder
.setName(ByteString.copyFrom(profile.name()))
.setAbout(ByteString.copyFrom(profile.about()))
.setAboutEmoji(ByteString.copyFrom(profile.aboutEmoji()))
.setAvatar(profile.avatar())
.setPhoneNumberSharing(ByteString.copyFrom(profile.phoneNumberSharing()));
// Allow requests where either the version matches the latest version on Account or the latest version on Account
// is empty to read the payment address.
if (account.getCurrentProfileVersion().map(v -> v.equals(requestVersion)).orElse(true)) {
responseBuilder.setPaymentAddress(ByteString.copyFrom(profile.paymentAddress()));
final Optional<VersionedProfile> profile;
if (account.hasCapability(DeviceCapability.PROFILES_V2)) {
profile = profilesManager.get(account.getUuid(), requestVersion);
} else {
profile = Optional.empty();
}
return responseBuilder.build();
final Optional<VersionedProfileV1> v1Profile;
if (profile.isEmpty()) {
v1Profile = profilesManager.getV1(account.getUuid(), HexFormat.of().formatHex(requestVersion));
} else {
v1Profile = Optional.empty();
}
if (profile.isEmpty() && v1Profile.isEmpty()) {
return Optional.empty();
}
final GetVersionedProfileResult.Builder responseBuilder = GetVersionedProfileResult.newBuilder();
profile.ifPresent(p -> {
if (requestDataEtag.length > 0 && Arrays.equals(requestDataEtag, p.dataHash())) {
responseBuilder.setDataEtagMatched(true);
} else {
responseBuilder.setDataEtag(DataEtag.newBuilder()
.setData(ByteString.copyFrom(p.data()))
.setEtag(ByteString.copyFrom(p.dataHash()))
.build());
}
});
v1Profile.ifPresent(p -> {
final GetVersionedProfileV1Response.Builder v1ResponseBuilder = GetVersionedProfileV1Response.newBuilder();
v1ResponseBuilder
.setName(ByteString.copyFrom(p.name()))
.setAbout(ByteString.copyFrom(p.about()))
.setAboutEmoji(ByteString.copyFrom(p.aboutEmoji()))
.setPhoneNumberSharing(ByteString.copyFrom(p.phoneNumberSharing()));
if (p.avatar() != null) {
v1ResponseBuilder.setAvatar(p.avatar());
}
responseBuilder.setV1Response(v1ResponseBuilder);
});
// Include payment address if the version matches the latest version on Account or the latest version on Account
// is empty
if (account.getCurrentProfileVersion().map(v -> v.equals(HexFormat.of().formatHex(requestVersion))).orElse(true)) {
final Optional<byte []> paymentAddress = profile.map(VersionedProfile::paymentAddress).or(() -> v1Profile.map(VersionedProfileV1::paymentAddress));
if (paymentAddress.isPresent()) {
final boolean paymentAddressETagMatches = requestPaymentAddressEtag.length > 0 &&
profile.map(VersionedProfile::paymentAddressHash)
.map(h -> Arrays.equals(requestPaymentAddressEtag, h))
.orElse(false);
if (paymentAddressETagMatches) {
responseBuilder.setPaymentAddressEtagMatched(true);
} else {
responseBuilder.setPaymentAddressDataEtag(DataEtag.newBuilder()
.setData(ByteString.copyFrom(paymentAddress.get()))
.setEtag(ByteString.copyFrom(
profile.map(VersionedProfile::paymentAddressHash).orElseGet(() -> hash(paymentAddress.get()))))
.build());
}
}
}
return Optional.of(responseBuilder.build());
}
@VisibleForTesting
@@ -95,54 +157,79 @@ public class ProfileGrpcHelper {
return grpcBadgeSvgs;
}
static GetUnversionedProfileResponse buildUnversionedProfileResponse(
static GetUnversionedProfileResult buildUnversionedProfileResult(
final ServiceIdentifier targetIdentifier,
final UUID requesterUuid,
final Account targetAccount,
final ProfileBadgeConverter profileBadgeConverter) {
final GetUnversionedProfileResponse.Builder responseBuilder = GetUnversionedProfileResponse.newBuilder()
final GetUnversionedProfileResult.Builder resultBuilder = GetUnversionedProfileResult.newBuilder()
.setIdentityKey(ByteString.copyFrom(targetAccount.getIdentityKey(targetIdentifier.identityType()).serialize()))
.addAllCapabilities(buildAccountCapabilities(targetAccount));
switch (targetIdentifier.identityType()) {
case ACI -> {
responseBuilder.setUnrestrictedUnidentifiedAccess(targetAccount.isUnrestrictedUnidentifiedAccess())
.addAllBadges(buildBadges(profileBadgeConverter.convert(
RequestAttributesUtil.getAvailableAcceptedLocales(),
resultBuilder.setUnrestrictedUnidentifiedAccess(targetAccount.isUnrestrictedUnidentifiedAccess())
.addAllBadges(
buildBadges(profileBadgeConverter.convert(RequestAttributesUtil.getAvailableAcceptedLocales(),
targetAccount.getBadges(),
ProfileHelper.isSelfProfileRequest(requesterUuid, targetIdentifier))));
targetAccount.getUnidentifiedAccessKey()
.map(UnidentifiedAccessChecksum::generateFor)
.map(ByteString::copyFrom)
.ifPresent(responseBuilder::setUnidentifiedAccess);
.ifPresent(resultBuilder::setUnidentifiedAccess);
}
case PNI -> responseBuilder.setUnrestrictedUnidentifiedAccess(false);
case PNI -> resultBuilder.setUnrestrictedUnidentifiedAccess(false);
}
return responseBuilder.build();
return resultBuilder.build();
}
static GetExpiringProfileKeyCredentialResponse getExpiringProfileKeyCredentialResponse(
final UUID targetUuid,
final String version,
static Optional<GetExpiringProfileKeyCredentialResult> getExpiringProfileKeyCredentialResult(
final Account account,
final byte[] version,
final byte[] encodedCredentialRequest,
final ProfilesManager profilesManager,
final ServerZkProfileOperations zkProfileOperations) throws StatusException {
final ServerZkProfileOperations zkProfileOperations) {
final VersionedProfile profile = profilesManager.get(targetUuid, version)
.orElseThrow(Status.NOT_FOUND.withDescription("Profile version not found")::asException);
final ExpiringProfileKeyCredentialResponse profileKeyCredentialResponse;
try {
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(encodedCredentialRequest,
profile, new ServiceId.Aci(targetUuid), zkProfileOperations);
} catch (VerificationFailedException | InvalidInputException e) {
throw Status.INVALID_ARGUMENT.withCause(e).asException();
final Optional<VersionedProfile> versionedProfile;
if (account.hasCapability(DeviceCapability.PROFILES_V2)) {
versionedProfile = profilesManager.get(account.getUuid(), version);
} else {
versionedProfile = Optional.empty();
}
return GetExpiringProfileKeyCredentialResponse.newBuilder()
.setProfileKeyCredential(ByteString.copyFrom(profileKeyCredentialResponse.serialize()))
.build();
return versionedProfile.map(VersionedProfile::commitment)
.or(() -> profilesManager.getV1(account.getUuid(), HexFormat.of().formatHex(version)).map(VersionedProfileV1::commitment))
.map(commitment -> {
final ExpiringProfileKeyCredentialResponse profileKeyCredentialResponse;
try {
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(new ProfileKeyCredentialRequest(encodedCredentialRequest),
new ProfileKeyCommitment(commitment), new ServiceId.Aci(account.getUuid()), zkProfileOperations);
} catch (VerificationFailedException | InvalidInputException e) {
throw GrpcExceptions.constraintViolation("invalid credential request");
}
return GetExpiringProfileKeyCredentialResult.newBuilder()
.setProfileKeyCredential(ByteString.copyFrom(profileKeyCredentialResponse.serialize()))
.build();
});
}
/**
* Computes the SHA-256 hash of the given data.
* <p>
* Only needed during the v1 -> v2 migration. See also: VersionedProfile#hash(byte[])
*/
@VisibleForTesting
public static byte[] hash(final byte[] data) {
final MessageDigest sha256;
try {
sha256 = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
return sha256.digest(data);
}
}
@@ -6,29 +6,29 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import io.grpc.Status;
import java.time.Clock;
import java.time.ZonedDateTime;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
import io.grpc.StatusException;
import org.signal.chat.profile.CredentialType;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialRequest;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResponse;
import org.signal.chat.errors.FailedPrecondition;
import org.signal.chat.errors.NotFound;
import org.signal.chat.profile.GetUnversionedProfileRequest;
import org.signal.chat.profile.GetUnversionedProfileResponse;
import org.signal.chat.profile.GetVersionedProfileRequest;
import org.signal.chat.profile.GetVersionedProfileResponse;
import org.signal.chat.profile.PaymentsForbiddenInRegion;
import org.signal.chat.profile.ProfileAvatarUploadAttributes;
import org.signal.chat.profile.ProfilesV2CapabilityRequired;
import org.signal.chat.profile.SetProfileRequest;
import org.signal.chat.profile.SetProfileRequest.AvatarChange;
import org.signal.chat.profile.SetProfileResponse;
import org.signal.chat.profile.SetProfileResult;
import org.signal.chat.profile.SetProfileV1Request.AvatarChange;
import org.signal.chat.profile.SimpleProfileGrpc;
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
@@ -44,9 +44,12 @@ import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountBadge;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
import org.whispersystems.textsecuregcm.storage.WriteConflictException;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.ProfileHelper;
@@ -61,7 +64,6 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
private final PolicySigner policySigner;
private final ProfileBadgeConverter profileBadgeConverter;
private final RateLimiters rateLimiters;
private final ServerZkProfileOperations zkProfileOperations;
private record AvatarData(Optional<String> currentAvatar,
Optional<String> finalAvatar,
@@ -76,8 +78,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
final PostPolicyGenerator policyGenerator,
final PolicySigner policySigner,
final ProfileBadgeConverter profileBadgeConverter,
final RateLimiters rateLimiters,
final ServerZkProfileOperations zkProfileOperations) {
final RateLimiters rateLimiters) {
this.clock = clock;
this.accountsManager = accountsManager;
this.profilesManager = profilesManager;
@@ -88,33 +89,52 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
this.policySigner = policySigner;
this.profileBadgeConverter = profileBadgeConverter;
this.rateLimiters = rateLimiters;
this.zkProfileOperations = zkProfileOperations;
}
@Override
public SetProfileResponse setProfile(final SetProfileRequest request) throws StatusException {
validateRequest(request);
public SetProfileResponse setProfile(final SetProfileRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final Account account = accountsManager.getByAccountIdentifier(
authenticatedDevice.accountIdentifier()).orElseThrow(Status.UNAUTHENTICATED::asException);
final Optional<VersionedProfile> maybeProfile = profilesManager.get(
authenticatedDevice.accountIdentifier(), request.getVersion());
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
.orElseThrow(() -> GrpcExceptions.invalidArguments("Account not found"));
if (!request.getPaymentAddress().isEmpty()) {
final boolean hasDisallowedPrefix =
dynamicConfigurationManager.getConfiguration().getPaymentsConfiguration().getDisallowedPrefixes().stream()
.anyMatch(prefix -> account.getNumber().startsWith(prefix));
if (hasDisallowedPrefix && maybeProfile.map(VersionedProfile::paymentAddress).isEmpty()) {
throw Status.PERMISSION_DENIED.asException();
}
if (!account.hasCapability(DeviceCapability.PROFILES_V2)) {
return SetProfileResponse.newBuilder()
.setProfilesV2CapabilityRequired(ProfilesV2CapabilityRequired.getDefaultInstance())
.build();
}
final Optional<String> currentAvatar = maybeProfile.map(VersionedProfile::avatar)
validateRequest(request);
final String expectedCurrentVersionHex = HexFormat.of().formatHex(request.getExpectedCurrentVersion().toByteArray());
final boolean currentVersionMatchesExpected = account.getCurrentProfileVersion().isEmpty()
? request.getExpectedCurrentVersion().isEmpty()
: account.getCurrentProfileVersion().get().equals(expectedCurrentVersionHex);
if (!currentVersionMatchesExpected) {
return SetProfileResponse.newBuilder().setWriteConflict(FailedPrecondition.newBuilder()
.setDescription("current and expected profile versions must match")
.build()).build();
}
final byte[] version = request.getVersion().toByteArray();
final Optional<VersionedProfile> maybeProfile = profilesManager.get(authenticatedDevice.accountIdentifier(),
version);
final Optional<VersionedProfileV1> maybeV1Profile = profilesManager.getV1(
authenticatedDevice.accountIdentifier(), HexFormat.of().formatHex(version));
if (!request.getPaymentAddress().isEmpty() && ProfileHelper.isPaymentAddressUpdateForbidden(account, maybeProfile, maybeV1Profile, dynamicConfigurationManager)) {
return SetProfileResponse.newBuilder()
.setPaymentsForbiddenInRegion(PaymentsForbiddenInRegion.getDefaultInstance())
.build();
}
final Optional<String> currentAvatar = maybeV1Profile.map(VersionedProfileV1::avatar)
.filter(avatar -> avatar.startsWith("profiles/"));
final AvatarData avatarData = switch (AvatarChangeUtil.fromGrpcAvatarChange(request.getAvatarChange())) {
final AvatarData avatarData = switch (AvatarChangeUtil.fromGrpcAvatarChange(request.getV1Request().getAvatarChange())) {
case AVATAR_CHANGE_UNCHANGED -> new AvatarData(currentAvatar, currentAvatar, Optional.empty());
case AVATAR_CHANGE_CLEAR -> new AvatarData(currentAvatar, Optional.empty(), Optional.empty());
case AVATAR_CHANGE_UPDATE -> {
@@ -124,120 +144,128 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
}
};
profilesManager.set(account.getUuid(),
new VersionedProfile(
request.getVersion(),
request.getName().toByteArray(),
avatarData.finalAvatar().orElse(null),
request.getAboutEmoji().toByteArray(),
request.getAbout().toByteArray(),
request.getPaymentAddress().toByteArray(),
request.getPhoneNumberSharing().toByteArray(),
request.getCommitment().toByteArray()));
final byte[] commitment = !request.getCommitment().isEmpty()
? request.getCommitment().toByteArray()
: maybeProfile.orElseThrow(IllegalStateException::new).commitment();
accountsManager.update(account, a -> {
final VersionedProfileV1 v1Profile = new VersionedProfileV1(
HexFormat.of().formatHex(version),
request.getV1Request().getName().toByteArray(),
avatarData.finalAvatar().orElse(null),
request.getV1Request().getAboutEmoji().toByteArray(),
request.getV1Request().getAbout().toByteArray(),
request.getPaymentAddress().toByteArray(),
request.getV1Request().getPhoneNumberSharing().toByteArray(),
commitment);
final List<AccountBadge> updatedBadges = Optional.of(request.getBadgeIdsList())
.map(badges -> ProfileHelper.mergeBadgeIdsWithExistingAccountBadges(clock, badgeConfigurationMap, badges,
a.getBadges()))
.orElseGet(a::getBadges);
final VersionedProfile profile = new VersionedProfile(version,
request.getData().toByteArray(),
request.getPaymentAddress().isEmpty() ? null : request.getPaymentAddress().toByteArray(),
commitment
);
a.setBadges(clock, updatedBadges);
a.setCurrentProfileVersion(request.getVersion());
});
try {
profilesManager.set(account.getIdentifier(IdentityType.ACI), v1Profile, profile,
request.getExpectedCurrentDataHash().isEmpty() ? null : request.getExpectedCurrentDataHash().toByteArray());
if (request.getAvatarChange() != AvatarChange.AVATAR_CHANGE_UNCHANGED && avatarData.currentAvatar().isPresent()) {
} catch (WriteConflictException _) {
return SetProfileResponse.newBuilder()
.setWriteConflict(FailedPrecondition.newBuilder()
.setDescription("current and expected data hash mismatch")
.build())
.build();
}
try {
accountsManager.updateCurrentProfileVersion(account.getIdentifier(IdentityType.ACI), version, expectedCurrentVersionHex, a -> {
final List<AccountBadge> updatedBadges = Optional.of(request.getBadgeIdsList())
.map(badges -> ProfileHelper.mergeBadgeIdsWithExistingAccountBadges(clock, badgeConfigurationMap, badges,
a.getBadges()))
.orElseGet(a::getBadges);
a.setBadges(clock, updatedBadges);
});
} catch (final WriteConflictException _) {
return SetProfileResponse.newBuilder()
.setWriteConflict(FailedPrecondition.newBuilder()
.setDescription("current and expected version mismatch")
.build())
.build();
}
if (request.getV1Request().getAvatarChange() != AvatarChange.AVATAR_CHANGE_UNCHANGED && avatarData.currentAvatar().isPresent()) {
profilesManager.deleteAvatar(avatarData.currentAvatar().get());
}
return avatarData.uploadAttributes()
.map(avatarUploadAttributes -> SetProfileResponse.newBuilder().setAttributes(avatarUploadAttributes).build())
.orElse(SetProfileResponse.newBuilder().build());
.map(avatarUploadAttributes -> SetProfileResponse.newBuilder()
.setResult(SetProfileResult.newBuilder()
.setV1AvatarUploadForm(avatarUploadAttributes).build())
.build())
.orElse(SetProfileResponse.newBuilder()
.setResult(SetProfileResult.getDefaultInstance())
.build());
}
@Override
public GetUnversionedProfileResponse getUnversionedProfile(final GetUnversionedProfileRequest request) throws StatusException, RateLimitExceededException {
public GetUnversionedProfileResponse getUnversionedProfile(final GetUnversionedProfileRequest request) throws RateLimitExceededException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final ServiceIdentifier targetIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getServiceIdentifier());
final Account targetAccount = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
final Optional<Account> maybeAccount = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
return ProfileGrpcHelper.buildUnversionedProfileResponse(targetIdentifier,
return maybeAccount.map(account -> GetUnversionedProfileResponse.newBuilder()
.setResult(ProfileGrpcHelper.buildUnversionedProfileResult(targetIdentifier,
authenticatedDevice.accountIdentifier(),
targetAccount,
profileBadgeConverter);
account,
profileBadgeConverter))
.build()).orElseGet(() -> GetUnversionedProfileResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build());
}
@Override
public GetVersionedProfileResponse getVersionedProfile(final GetVersionedProfileRequest request) throws StatusException, RateLimitExceededException {
public GetVersionedProfileResponse getVersionedProfile(final GetVersionedProfileRequest request) throws RateLimitExceededException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final ServiceIdentifier targetIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getAccountIdentifier());
if (targetIdentifier.identityType() != IdentityType.ACI) {
throw Status.INVALID_ARGUMENT.withDescription("Expected ACI service identifier").asException();
}
final Optional<Account> maybeAccount = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
final Account account = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
return ProfileGrpcHelper.getVersionedProfile(account, profilesManager, request.getVersion());
return maybeAccount.map(account ->
ProfileGrpcHelper.getVersionedProfile(account, profilesManager,
request.getVersion().toByteArray(),
request.getDataEtag().toByteArray(),
request.getPaymentAddressEtag().toByteArray())
.map(result ->
GetVersionedProfileResponse.newBuilder()
.setResult(result)
.build())
.orElseGet(() -> GetVersionedProfileResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build())).orElseGet(() -> GetVersionedProfileResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build());
}
@Override
public GetExpiringProfileKeyCredentialResponse getExpiringProfileKeyCredential(
final GetExpiringProfileKeyCredentialRequest request) throws StatusException, RateLimitExceededException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final ServiceIdentifier targetIdentifier = ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getAccountIdentifier());
if (targetIdentifier.identityType() != IdentityType.ACI) {
throw Status.INVALID_ARGUMENT.withDescription("Expected ACI service identifier").asException();
}
if (request.getCredentialType() != CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY) {
throw Status.INVALID_ARGUMENT.withDescription("Expected expiring profile key credential type").asException();
}
final Account targetAccount = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
return ProfileGrpcHelper.getExpiringProfileKeyCredentialResponse(targetAccount.getUuid(),
request.getVersion(), request.getCredentialRequest().toByteArray(), profilesManager, zkProfileOperations);
}
private Account validateRateLimitAndGetAccount(final UUID requesterUuid,
final ServiceIdentifier targetIdentifier) throws RateLimitExceededException, StatusException {
private Optional<Account> validateRateLimitAndGetAccount(final UUID requesterUuid,
final ServiceIdentifier targetIdentifier) throws RateLimitExceededException {
rateLimiters.getProfileLimiter().validate(requesterUuid);
return accountsManager.getByServiceIdentifier(targetIdentifier).orElseThrow(Status.NOT_FOUND::asException);
return accountsManager.getByServiceIdentifier(targetIdentifier);
}
private void validateRequest(final SetProfileRequest request) throws StatusException {
if (request.getVersion().isEmpty()) {
throw Status.INVALID_ARGUMENT.withDescription("Missing version").asException();
private void validateRequest(final SetProfileRequest request) {
if (request.getExpectedCurrentDataHash().isEmpty() && request.getCommitment().isEmpty()) {
throw GrpcExceptions.constraintViolation("At least one of expected current data hash and commitment is required");
}
// v1 -> v2 migration
if (request.getCommitment().isEmpty()) {
throw Status.INVALID_ARGUMENT.withDescription("Missing profile commitment").asException();
throw GrpcExceptions.constraintViolation("Request must include commitment during migration");
}
checkByteStringLength(request.getName(), "Invalid name length", List.of(81, 285));
checkByteStringLength(request.getAboutEmoji(), "Invalid about emoji length", List.of(0, 60));
checkByteStringLength(request.getAbout(), "Invalid about length", List.of(0, 156, 282, 540));
checkByteStringLength(request.getPaymentAddress(), "Invalid mobile coin address length", List.of(0, 582));
}
private static void checkByteStringLength(final ByteString byteString, final String errorMessage,
final List<Integer> allowedLengths) throws StatusException {
final int byteStringLength = byteString.toByteArray().length;
for (int allowedLength : allowedLengths) {
if (byteStringLength == allowedLength) {
return;
}
}
throw Status.INVALID_ARGUMENT.withDescription(errorMessage).asException();
}
private ProfileAvatarUploadAttributes generateAvatarUploadForm(final String objectName) {
@@ -26,6 +26,7 @@ import org.whispersystems.textsecuregcm.grpc.validators.FieldValidator;
import org.whispersystems.textsecuregcm.grpc.validators.NonEmptyFieldValidator;
import org.whispersystems.textsecuregcm.grpc.validators.PresentFieldValidator;
import org.whispersystems.textsecuregcm.grpc.validators.RangeFieldValidator;
import org.whispersystems.textsecuregcm.grpc.validators.ServiceIdentifierIdentityTypeValidator;
import org.whispersystems.textsecuregcm.grpc.validators.SizeFieldValidator;
public class ValidatingInterceptor implements ServerInterceptor {
@@ -39,7 +40,8 @@ public class ValidatingInterceptor implements ServerInterceptor {
"org.signal.chat.require.exactlySize", new ExactlySizeFieldValidator(),
"org.signal.chat.require.range", new RangeFieldValidator(),
"org.signal.chat.require.size", new SizeFieldValidator(),
"org.signal.chat.require.base64url", new Base64UrlFieldValidator()
"org.signal.chat.require.base64url", new Base64UrlFieldValidator(),
"org.signal.chat.require.identityType", new ServiceIdentifierIdentityTypeValidator()
);
@Override
@@ -64,9 +66,6 @@ public class ValidatingInterceptor implements ServerInterceptor {
try {
validateMessage(message);
super.onMessage(message);
} catch (final StatusRuntimeException e) {
call.close(e.getStatus(), e.getTrailers());
forwardCalls = false;
} catch (RuntimeException runtimeException) {
final StatusRuntimeException grpcException = switch (runtimeException) {
case StatusRuntimeException e -> e;
@@ -0,0 +1,52 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc.validators;
import com.google.protobuf.Descriptors;
import com.google.protobuf.Message;
import java.util.Objects;
import java.util.Set;
import org.signal.chat.common.IdentityType;
import org.signal.chat.common.ServiceIdentifier;
public class ServiceIdentifierIdentityTypeValidator extends BaseFieldValidator<IdentityType> {
public ServiceIdentifierIdentityTypeValidator() {
super("identityType", Set.of(Descriptors.FieldDescriptor.Type.MESSAGE), MissingOptionalAction.SUCCEED, false);
}
@Override
protected IdentityType resolveExtensionValue(final Object extensionValue) throws FieldValidationException {
if (extensionValue instanceof Descriptors.EnumValueDescriptor d) {
if (d.getType().equals(org.signal.chat.require.IdentityType.getDescriptor())) {
return switch (Objects.requireNonNull(org.signal.chat.require.IdentityType.forNumber(d.getNumber()))) {
case IDENTITY_TYPE_ACI -> IdentityType.IDENTITY_TYPE_ACI;
case IDENTITY_TYPE_PNI -> IdentityType.IDENTITY_TYPE_PNI;
default -> throw new IllegalArgumentException("unsupported value: " + d.getName());
};
}
}
throw new IllegalArgumentException("value must be org.signal.chat.require.IdentityType");
}
@Override
protected void validateMessageValue(final IdentityType extensionValue, final Message msg) throws FieldValidationException {
if (msg == null) {
return;
}
if (msg instanceof ServiceIdentifier i) {
if (i.getIdentityType() == extensionValue) {
return;
}
throw new FieldValidationException("identity type must be " + extensionValue.getValueDescriptor().getName());
}
throw new IllegalArgumentException("field must be " + ServiceIdentifier.class.getName());
}
}
@@ -36,6 +36,7 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
USERNAME_LINK_LOOKUP_PER_IP("usernameLinkLookupPerIp", new RateLimiterConfig(100, Duration.ofSeconds(15), true)),
CHECK_ACCOUNT_EXISTENCE("checkAccountExistence", new RateLimiterConfig(1000, Duration.ofSeconds(4), true)),
REGISTRATION("registration", new RateLimiterConfig(6, Duration.ofSeconds(30), false)),
SET_ZK_CREDENTIAL_KEY("setZkCredentialKey", new RateLimiterConfig(5, Duration.ofDays(7), false)),
VERIFICATION_PUSH_CHALLENGE("verificationPushChallenge", new RateLimiterConfig(5, Duration.ofSeconds(30), false)),
VERIFICATION_CAPTCHA("verificationCaptcha", new RateLimiterConfig(10, Duration.ofSeconds(30), false)),
RATE_LIMIT_RESET("rateLimitReset", new RateLimiterConfig(2, Duration.ofHours(12), false)),
@@ -106,8 +107,8 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
return forDescriptor(For.VERIFY_DEVICE);
}
public RateLimiter getMessagesLimiter() {
return forDescriptor(For.MESSAGES);
public RateLimiter getSetZkCredentialKeyLimiter() {
return forDescriptor(For.SET_ZK_CREDENTIAL_KEY);
}
public RateLimiter getPreKeysLimiter() {
@@ -162,6 +163,10 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
return forDescriptor(For.REGISTRATION);
}
public RateLimiter getMessagesLimiter() {
return forDescriptor(For.MESSAGES);
}
public RateLimiter getRateLimitResetLimiter() {
return forDescriptor(For.RATE_LIMIT_RESET);
}
@@ -25,7 +25,6 @@ public class CaptchaMetrics {
"context", context)
.minimumExpectedValue(1.0d)
.maximumExpectedValue(100.0d)
.serviceLevelObjectives(10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
.register(Metrics.globalRegistry)
.record(Math.max(1, score));
}
@@ -304,8 +304,11 @@ public class MessageSender {
}
if (messagesByDeviceId.isEmpty()) {
if (syncMessageSenderDeviceId.isEmpty()) {
throw new IllegalArgumentException("Messages must not be empty for non-sync messages");
}
Metrics.counter(EMPTY_MESSAGE_LIST_COUNTER_NAME,
Tags.of(SYNC_MESSAGE_TAG_NAME, String.valueOf(syncMessageSenderDeviceId.isPresent())).and(platformTag)).increment();
Tags.of(SYNC_MESSAGE_TAG_NAME, String.valueOf(true)).and(platformTag)).increment();
}
final byte excludedDeviceId;
@@ -17,6 +17,7 @@ import java.util.function.BiConsumer;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
@@ -195,7 +196,7 @@ public class PushNotificationManager {
// updating an uninstalled feedback timestamp though.
accountsManager.getByAccountIdentifier(account.getUuid()).ifPresent(rereadAccount ->
rereadAccount.getDevice(device.getId()).ifPresent(rereadDevice ->
accountsManager.updateDevice(rereadAccount, device.getId(), d -> {
accountsManager.updateDevice(rereadAccount.getIdentifier(IdentityType.ACI), device.getId(), d -> {
// Don't clear the token if it's already changed
if (originalToken.equals(getPushToken(d, tokenType))) {
switch (tokenType) {
@@ -92,6 +92,7 @@ public class Account {
private String registrationLockSalt;
@JsonProperty("uak")
@Nullable
private byte[] unidentifiedAccessKey;
@JsonProperty("uua")
@@ -112,6 +113,10 @@ public class Account {
@Nullable
private BackupVoucher backupVoucher;
@JsonProperty("zck")
@Nullable
private byte[] zkCredentialKey;
@JsonProperty
private int version;
@@ -428,7 +433,9 @@ public class Account {
public Optional<byte[]> getUnidentifiedAccessKey() {
requireNotStale();
return Optional.ofNullable(unidentifiedAccessKey);
return Optional.ofNullable((unidentifiedAccessKey == null || unidentifiedAccessKey.length == 0)
? null
: unidentifiedAccessKey);
}
public void setUnidentifiedAccessKey(final byte[] unidentifiedAccessKey) {
@@ -536,6 +543,15 @@ public class Account {
this.usernameHolds = usernameHolds;
}
@Nullable
public byte[] getZkCredentialKey() {
return zkCredentialKey;
}
public void setZkCredentialKey(@Nullable final byte[] zkCredentialKey) {
this.zkCredentialKey = zkCredentialKey;
}
public void markStale() {
stale = true;
}
@@ -326,6 +326,9 @@ public class Accounts {
// Carry over the existing backup voucher to the new account
accountToCreate.setBackupVoucher(existingAccount.getBackupVoucher());
// Carry over the existing ZK credential key to the new account
accountToCreate.setZkCredentialKey(existingAccount.getZkCredentialKey());
final List<TransactWriteItem> writeItems = new ArrayList<>();
// If we're reclaiming an account that already has a username, we'd like to give the re-registering client
@@ -1670,7 +1673,13 @@ public class Accounts {
accountIdentifier, account.getPhoneNumberIdentifier(), phoneNumberIdentifierFromAttribute);
}
account.setNumber(item.get(ATTR_ACCOUNT_E164).s(), phoneNumberIdentifierFromAttribute);
final String attributeNumber = item.get(ATTR_ACCOUNT_E164).s();
if (account.getNumber() == null || !account.getNumber().equals(attributeNumber)) {
log.error("Missing or mismatched phone numbers for account {}. From JSON: {}; from attribute: {}",
accountIdentifier, account.getNumber(), attributeNumber);
}
account.setNumber(attributeNumber, phoneNumberIdentifierFromAttribute);
account.setUuid(accountIdentifier);
account.setUsernameHash(AttributeValues.getByteArray(item, ATTR_USERNAME_HASH, null));
account.setUsernameLinkHandle(AttributeValues.getUUID(item, ATTR_USERNAME_LINK_UUID, null));
@@ -37,8 +37,10 @@ import java.util.Arrays;
import java.util.Base64;
import java.util.Collection;
import java.util.HashSet;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Queue;
import java.util.Set;
@@ -433,11 +435,15 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
return account;
}
public Pair<Account, Device> addDevice(final Account account, final DeviceSpec deviceSpec, final String linkDeviceToken)
public Pair<Account, Device> addDevice(final UUID accountIdentifier, final DeviceSpec deviceSpec, final String linkDeviceToken)
throws LinkDeviceTokenAlreadyUsedException {
return accountLockManager.withLock(Set.of(account.getPhoneNumberIdentifier()),
() -> addDevice(account.getIdentifier(IdentityType.ACI), deviceSpec, linkDeviceToken, MAX_UPDATE_ATTEMPTS),
final UUID phoneNumberIdentifier = accounts.getByAccountIdentifier(accountIdentifier)
.map(account -> account.getIdentifier(IdentityType.PNI))
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier));
return accountLockManager.withLock(Set.of(phoneNumberIdentifier),
() -> addDevice(accountIdentifier, deviceSpec, linkDeviceToken, MAX_UPDATE_ATTEMPTS),
accountLockExecutor);
}
@@ -622,13 +628,18 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
*
* @return the updated Account
*/
public Account removeDevice(final Account account, final byte deviceId) {
public Account removeDevice(final UUID accountIdentifier, final byte deviceId) {
if (deviceId == Device.PRIMARY_ID) {
throw new IllegalArgumentException("Cannot remove primary device");
}
return accountLockManager.withLock(Set.of(account.getPhoneNumberIdentifier()),
() -> removeDevice(account.getIdentifier(IdentityType.ACI), deviceId, MAX_UPDATE_ATTEMPTS),
// Always fetch a fresh, non-cached copy of the account before making modifications
final UUID phoneNumberIdentifier = accounts.getByAccountIdentifier(accountIdentifier)
.map(account -> account.getIdentifier(IdentityType.PNI))
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier));
return accountLockManager.withLock(Set.of(phoneNumberIdentifier),
() -> removeDevice(accountIdentifier, deviceId, MAX_UPDATE_ATTEMPTS),
accountLockExecutor);
}
@@ -672,13 +683,17 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
}
public Account changeNumber(final Account account,
public Account changeNumber(final UUID accountIdentifier,
final String targetNumber,
final IdentityKey pniIdentityKey,
final Map<Byte, ECSignedPreKey> pniSignedPreKeys,
final Map<Byte, KEMSignedPreKey> pniPqLastResortPreKeys,
final Map<Byte, Integer> pniRegistrationIds) throws InterruptedException, MismatchedDevicesException {
// Always fetch a fresh, non-cached copy of the account before making modifications
final Account account = accounts.getByAccountIdentifier(accountIdentifier)
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier));
final UUID targetPhoneNumberIdentifier = phoneNumberIdentifiers.getPhoneNumberIdentifier(targetNumber).join();
try {
@@ -743,7 +758,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
buildPniKeyWriteItems(targetPhoneNumberIdentifier, pniSignedPreKeys, pniPqLastResortPreKeys);
return updateWithRetries(
account,
a -> {
setPniKeys(a, pniIdentityKey, pniRegistrationIds);
return true;
@@ -815,18 +829,23 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
/// Reserve a username hash so that no other accounts may take it.
///
/// The reserved hash can later be set with [#confirmReservedUsernameHash(Account, byte\[\], byte\[\])]. The
/// The reserved hash can later be set with [#confirmReservedUsernameHash(UUID, byte\[\], byte\[\])]. The
/// reservation will eventually expire, after which point confirmReservedUsernameHash may fail if another account has
/// taken the username hash.
///
/// @param account the account to update
/// @param accountIdentifier the unique identifier of the account to update
/// @param requestedUsernameHashes the list of username hashes to attempt to reserve
///
/// @return the reserved username hash
///
/// @throws UsernameHashNotAvailableException if none of the given username hashes are available
public UsernameReservation reserveUsernameHash(final Account account, final List<byte[]> requestedUsernameHashes)
public UsernameReservation reserveUsernameHash(final UUID accountIdentifier, final List<byte[]> requestedUsernameHashes)
throws UsernameHashNotAvailableException {
// Always fetch a fresh, non-cached copy of the account before making modifications
final Account account = accounts.getByAccountIdentifier(accountIdentifier)
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier));
if (account.getUsernameHash().filter(
oldHash -> requestedUsernameHashes.stream().anyMatch(hash -> Arrays.equals(oldHash, hash)))
.isPresent()) {
@@ -844,7 +863,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
redisDelete(account);
final Account updatedAccount = updateWithRetries(
account,
_ -> true,
a -> reservedUsernameHash.set(
checkAndReserveNextUsernameHash(a, new ArrayDeque<>(requestedUsernameHashes))),
@@ -873,9 +891,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
}
/// Set a username hash previously reserved with {@link #reserveUsernameHash(Account, List)}
/// Set a username hash previously reserved with {@link #reserveUsernameHash(UUID, List)}
///
/// @param account the account to update
/// @param accountIdentifier identifier of the account to update
/// @param reservedUsernameHash the previously reserved username hash
/// @param encryptedUsername the encrypted form of the previously reserved username for the username link
///
@@ -884,9 +902,13 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
/// @throws UsernameHashNotAvailableException if the reserved username hash has been taken (because the reservation
/// expired)
/// @throws UsernameReservationNotFoundException if `reservedUsernameHash` was not reserved for the account
public Account confirmReservedUsernameHash(final Account account, final byte[] reservedUsernameHash, @Nullable final byte[] encryptedUsername)
public Account confirmReservedUsernameHash(final UUID accountIdentifier, final byte[] reservedUsernameHash, @Nullable final byte[] encryptedUsername)
throws UsernameReservationNotFoundException, UsernameHashNotAvailableException {
// Always fetch a fresh, non-cached copy of the account before making modifications
final Account account = accounts.getByAccountIdentifier(accountIdentifier)
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier));
if (account.getUsernameHash().map(currentUsernameHash -> Arrays.equals(currentUsernameHash, reservedUsernameHash)).orElse(false)) {
// the client likely already succeeded and is retrying
return account;
@@ -900,7 +922,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
redisDelete(account);
final Account updatedAccount = updateWithRetries(account,
final Account updatedAccount = updateWithRetries(
_ -> true,
a -> accounts.confirmUsernameHash(a, reservedUsernameHash, encryptedUsername),
() -> accounts.getByAccountIdentifier(account.getUuid()).orElseThrow(),
@@ -911,13 +933,10 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
return updatedAccount;
}
public Account clearUsernameHash(final Account account) {
redisDelete(account);
final Account updatedAccount = updateWithRetries(account,
_ -> true,
public Account clearUsernameHash(final UUID accountIdentifier) {
final Account updatedAccount = updateWithRetries(_ -> true,
accounts::clearUsernameHash,
() -> accounts.getByAccountIdentifier(account.getUuid()).orElseThrow(),
() -> accounts.getByAccountIdentifier(accountIdentifier).orElseThrow(),
AccountChangeValidator.USERNAME_CHANGE_VALIDATOR);
redisDelete(updatedAccount);
@@ -925,20 +944,63 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
return updatedAccount;
}
public Account update(Account account, Consumer<Account> updater) {
return update(account, a -> {
public Account update(final Account account, final Consumer<Account> updater) {
final Account updatedAccount = update(account.getIdentifier(IdentityType.ACI), updater);
account.markStale();
return updatedAccount;
}
public Account update(final UUID accountIdentifier, final Consumer<Account> updater) {
return update(accountIdentifier, a -> {
updater.accept(a);
// assume that all updaters passed to the public method actually modify the account
return true;
});
}
/// Using a pessimistic lock, updates the current profile version to `newVersion` if `currentProfileVersion` matches
/// `expectedCurrentVersion`. The caller may provide a supplementary `Consumer<Account>` for additional updates
///
/// @throws WriteConflictException if the expected current version does not match the current version
public Account updateCurrentProfileVersion(final UUID accountIdentifier, final byte[] newVersion,
final String expectedCurrentVersion, final Consumer<Account> updater) throws WriteConflictException {
Objects.requireNonNull(expectedCurrentVersion, "expectedCurrentVersion");
// Always fetch a fresh, non-cached copy of the account before making modifications
final Account account = accounts.getByAccountIdentifier(accountIdentifier)
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier));
final String newVersionHex = HexFormat.of().formatHex(newVersion);
return accountLockManager.withLock(Set.of(account.getPhoneNumberIdentifier()), () -> {
final Account maybeUpdatedAccount = update(accountIdentifier, a -> {
if (!a.getCurrentProfileVersion().orElse("").equals(expectedCurrentVersion)) {
return false;
}
a.setCurrentProfileVersion(newVersionHex);
updater.accept(a);
return true;
});
if (!maybeUpdatedAccount.getCurrentProfileVersion().map(v -> v.equals(newVersionHex)).orElse(false)) {
throw new WriteConflictException();
}
return maybeUpdatedAccount;
}, accountLockExecutor);
}
/**
* Specialized version of {@link #updateDevice(Account, byte, Consumer)} that minimizes potentially contentious and
* Specialized version of {@link #updateDevice(UUID, byte, Consumer)} that minimizes potentially contentious and
* redundant updates of {@code device.lastSeen}
*/
public Account updateDeviceLastSeen(Account account, Device device, final long lastSeen) {
return update(account, a -> {
public Account updateDeviceLastSeen(UUID accountIdentifier, Device device, final long lastSeen) {
return update(accountIdentifier, a -> {
final Optional<Device> maybeDevice = a.getDevice(device.getId());
@@ -956,21 +1018,16 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
/**
* @param account account to update
* @param accountIdentifier identifier of account to update
* @param updater must return {@code true} if the account was actually updated
*/
private Account update(Account account, Function<Account, Boolean> updater) {
private Account update(UUID accountIdentifier, Function<Account, Boolean> updater) {
return updateTimer.record(() -> {
redisDelete(account);
final UUID uuid = account.getUuid();
final Account updatedAccount = updateWithRetries(account,
updater,
final Account updatedAccount = updateWithRetries(updater,
accounts::update,
() -> accounts.getByAccountIdentifier(uuid).orElseThrow(),
() -> accounts.getByAccountIdentifier(accountIdentifier).orElseThrow(),
AccountChangeValidator.GENERAL_CHANGE_VALIDATOR);
redisSet(updatedAccount);
@@ -979,49 +1036,38 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
});
}
private <E extends Exception> Account updateWithRetries(Account account,
final Function<Account, Boolean> updater,
private <E extends Exception> Account updateWithRetries(final Function<Account, Boolean> updater,
final ThrowingConsumer<Account, E> persister,
final Supplier<Account> retriever,
final AccountChangeValidator changeValidator) throws E {
Account originalAccount = AccountUtil.cloneAccountAsNotStale(account);
if (!updater.apply(account)) {
return account;
}
final int maxTries = 10;
int tries = 0;
while (tries < maxTries) {
try {
persister.accept(account);
final Account updatedAccount = AccountUtil.cloneAccountAsNotStale(account);
account.markStale();
changeValidator.validateChange(originalAccount, updatedAccount);
return updatedAccount;
} catch (final ContestedOptimisticLockException e) {
tries++;
account = retriever.get();
originalAccount = AccountUtil.cloneAccountAsNotStale(account);
final Account account = retriever.get();
final Account originalAccount = AccountUtil.cloneAccountAsNotStale(account);
if (!updater.apply(account)) {
return account;
}
persister.accept(account);
changeValidator.validateChange(originalAccount, account);
return account;
} catch (final ContestedOptimisticLockException e) {
tries++;
}
}
throw new OptimisticLockRetryLimitExceededException();
}
public Account updateDevice(Account account, byte deviceId, Consumer<Device> deviceUpdater) {
return update(account, a -> {
public Account updateDevice(final UUID accountIdentifier, byte deviceId, Consumer<Device> deviceUpdater) {
return update(accountIdentifier, a -> {
a.getDevice(deviceId).ifPresent(deviceUpdater);
// assume that all updaters passed to the public method actually modify the device
return true;
@@ -1090,6 +1136,22 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
);
}
/// Returns a fresh, uncached copy of the identified account (the account preparing to change its number) and a fresh,
/// uncached copy of the account that holds the target phone number if such an account exists.
///
/// @param accountIdentifier the identifier for the account changing its phone number
/// @param targetNumber the new phone number for the identified account
///
/// @return a fresh, uncached copy of the identified account and a fresh, uncached copy of the account that has
/// `targetNumber` if one exists
///
/// @throws IllegalArgumentException if no account was found for `accountIdentifier`
Pair<Account, Optional<Account>> getAccountsForChangeNumber(final UUID accountIdentifier, final String targetNumber) {
return new Pair<>(accounts.getByAccountIdentifier(accountIdentifier)
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier)),
accounts.getByE164(targetNumber));
}
public UUID getPhoneNumberIdentifier(String e164) {
return phoneNumberIdentifiers.getPhoneNumberIdentifier(e164).join();
}
@@ -1106,9 +1168,19 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
return accounts.getAll(segments, scheduler);
}
public void delete(final Account account, final DeletionReason deletionReason) {
public void delete(final UUID accountIdentifier, final DeletionReason deletionReason) {
final Timer.Sample sample = Timer.start();
final Optional<Account> maybeAccount = accounts.getByAccountIdentifier(accountIdentifier);
if (maybeAccount.isEmpty()) {
// In most cases, failing to find an account would be an error, but in this case, it's probably a sign that we've
// already succeeded in deleting the account and this is a spurious retry.
return;
}
final Account account = maybeAccount.get();
try {
accountLockManager.withLock(Set.of(account.getPhoneNumberIdentifier()), () -> {
delete(account);
@@ -1328,21 +1400,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
getAccountEntityKey(account.getUuid())))));
}
private CompletableFuture<Void> redisDeleteAsync(final Account account) {
final Timer.Sample sample = Timer.start();
final String[] keysToDelete = new String[]{
getAccountMapKey(account.getPhoneNumberIdentifier().toString()),
getAccountEntityKey(account.getUuid())
};
return ResilienceUtil.getGeneralRedisRetry(RETRY_NAME).executeCompletionStage(retryExecutor,
() -> cacheCluster.withCluster(connection -> connection.async().del(keysToDelete))
.thenRun(Util.NOOP))
.toCompletableFuture()
.whenComplete((_, _) -> sample.stop(redisDeleteTimer));
}
public CompletableFuture<Optional<DeviceInfo>> waitForNewLinkedDevice(
final UUID accountIdentifier,
final Device linkingDevice,
@@ -8,47 +8,108 @@ import java.time.Clock;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;
import com.google.common.net.HttpHeaders;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import jakarta.ws.rs.container.ContainerRequestContext;
import org.signal.libsignal.protocol.IdentityKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
import org.whispersystems.textsecuregcm.controllers.AccountControllerV2;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.IncomingMessage;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.MessageSender;
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
import org.whispersystems.textsecuregcm.util.Pair;
import javax.annotation.Nullable;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
public class ChangeNumberManager {
private static final Logger logger = LoggerFactory.getLogger(ChangeNumberManager.class);
private final MessageSender messageSender;
private final AccountsManager accountsManager;
private final PhoneVerificationTokenManager phoneVerificationTokenManager;
private final RegistrationLockVerificationManager registrationLockVerificationManager;
private final RateLimiters rateLimiters;
private final Clock clock;
private static final Logger logger = LoggerFactory.getLogger(ChangeNumberManager.class);
// Note that this counter name references another class deliberately in the interest of metric continuity
private static final String CHANGE_NUMBER_COUNTER_NAME = name(AccountControllerV2.class, "changeNumber");
private static final String VERIFICATION_TYPE_TAG_NAME = "verification";
public ChangeNumberManager(
final MessageSender messageSender,
final AccountsManager accountsManager,
final PhoneVerificationTokenManager phoneVerificationTokenManager,
final RegistrationLockVerificationManager registrationLockVerificationManager,
final RateLimiters rateLimiters,
final Clock clock) {
this.messageSender = messageSender;
this.accountsManager = accountsManager;
this.phoneVerificationTokenManager = phoneVerificationTokenManager;
this.registrationLockVerificationManager = registrationLockVerificationManager;
this.rateLimiters = rateLimiters;
this.clock = clock;
}
public Account changeNumber(final Account account,
public Account changeNumber(final UUID accountIdentifier,
@Nullable final byte[] sessionId,
@Nullable final byte[] recoveryPassword,
@Nullable final String registrationLock,
final String number,
final IdentityKey pniIdentityKey,
final Map<Byte, ECSignedPreKey> deviceSignedPreKeys,
final Map<Byte, KEMSignedPreKey> devicePqLastResortPreKeys,
final List<IncomingMessage> deviceMessages,
final Map<Byte, Integer> pniRegistrationIds,
final String senderUserAgent)
throws InterruptedException, MismatchedDevicesException, MessageTooLargeException {
final ContainerRequestContext containerRequestContext)
throws InterruptedException, MismatchedDevicesException, MessageTooLargeException, RateLimitExceededException {
final String senderUserAgent = containerRequestContext.getHeaderString(HttpHeaders.USER_AGENT);
final Pair<Account, Optional<Account>> accountAndMaybeExistingAccount =
accountsManager.getAccountsForChangeNumber(accountIdentifier, number);
final Account account = accountAndMaybeExistingAccount.first();
// Only verify and check reglock if there's a data change to be made...
if (!account.getNumber().equals(number)) {
rateLimiters.getRegistrationLimiter().validate(number);
final PhoneVerificationRequest.VerificationType verificationType =
phoneVerificationTokenManager.verify(containerRequestContext, number, sessionId, recoveryPassword);
final Optional<Account> existingAccount = accountAndMaybeExistingAccount.second();
if (existingAccount.isPresent()) {
registrationLockVerificationManager.verifyRegistrationLock(existingAccount.get(), registrationLock,
senderUserAgent, RegistrationLockVerificationManager.Flow.CHANGE_NUMBER, verificationType);
}
Metrics.counter(CHANGE_NUMBER_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(senderUserAgent),
Tag.of(VERIFICATION_TYPE_TAG_NAME, verificationType.name())))
.increment();
}
// ...but always attempt to make the change in case a client retries and needs to re-send messages
final long serverTimestamp = clock.millis();
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(account.getIdentifier(IdentityType.ACI));
@@ -80,13 +141,13 @@ public class ChangeNumberManager {
}
final Account updatedAccount = accountsManager.changeNumber(
account, number, pniIdentityKey, deviceSignedPreKeys, devicePqLastResortPreKeys, pniRegistrationIds);
account.getIdentifier(IdentityType.ACI), number, pniIdentityKey, deviceSignedPreKeys, devicePqLastResortPreKeys, pniRegistrationIds);
try {
// Now that we've actually updated the account, populate the "updated PNI" field on all envelopes
final String updatedPniString = updatedAccount.getIdentifier(IdentityType.PNI).toString();
messagesByDeviceId.replaceAll((deviceId, envelope) ->
messagesByDeviceId.replaceAll((_, envelope) ->
envelope.toBuilder().setUpdatedPni(updatedPniString).build());
messageSender.sendMessages(updatedAccount,
@@ -15,7 +15,8 @@ public enum DeviceCapability {
STORAGE("storage", AccountCapabilityMode.ANY_DEVICE, false, false, false),
TRANSFER("transfer", AccountCapabilityMode.PRIMARY_DEVICE, false, false, false),
ATTACHMENT_BACKFILL("attachmentBackfill", AccountCapabilityMode.PRIMARY_DEVICE, false, true, false),
SPARSE_POST_QUANTUM_RATCHET("spqr", AccountCapabilityMode.ALL_DEVICES, true, true, true);
SPARSE_POST_QUANTUM_RATCHET("spqr", AccountCapabilityMode.ALL_DEVICES, true, true, true),
PROFILES_V2("profiles_v2", AccountCapabilityMode.ALL_DEVICES, false, true, false);
public enum AccountCapabilityMode {
/**
@@ -5,7 +5,7 @@
package org.whispersystems.textsecuregcm.storage;
public class KeyIdUtil {
public static final long MAX_KEY_ID = (1L << 32) - 1;
public static final long MAX_KEY_ID = (1L << 31) - 1;
public static final long MIN_KEY_ID = 0;
private KeyIdUtil(){}
@@ -311,7 +311,7 @@ public class MessagePersister implements Managed {
} else {
logger.warn("Failed to persist queue {}::{} due to overfull queue; will unlink device", accountUuid, deviceId);
return Mono.fromRunnable(() -> accountsManager.removeDevice(account, deviceId))
return Mono.fromRunnable(() -> accountsManager.removeDevice(accountUuid, deviceId))
.subscribeOn(persistQueueScheduler)
.then(Mono.empty());
}
@@ -19,9 +19,7 @@ import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.whispersystems.textsecuregcm.util.AsyncTimerUtil;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
@@ -31,6 +29,8 @@ import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
import software.amazon.awssdk.services.dynamodb.model.Update;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
public class Profiles {
@@ -93,7 +93,7 @@ public class Profiles {
this.tableName = tableName;
}
public void set(final UUID uuid, final VersionedProfile profile) {
public void set(final UUID uuid, final VersionedProfileV1 profile) {
SET_PROFILES_TIMER.record(() -> {
dynamoDbClient.updateItem(UpdateItemRequest.builder()
.tableName(tableName)
@@ -105,16 +105,17 @@ public class Profiles {
});
}
public CompletableFuture<Void> setAsync(final UUID uuid, final VersionedProfile profile) {
return AsyncTimerUtil.record(SET_PROFILES_TIMER, () -> dynamoDbAsyncClient.updateItem(UpdateItemRequest.builder()
/// Used to update a profile during the v2 migration.
public TransactWriteItem getTransactWriteItem(final UUID uuid, final VersionedProfileV1 profile) {
return TransactWriteItem.builder()
.update(Update.builder()
.tableName(tableName)
.key(buildPrimaryKey(uuid, profile.version()))
.updateExpression(buildUpdateExpression(profile))
.expressionAttributeNames(UPDATE_EXPRESSION_ATTRIBUTE_NAMES)
.expressionAttributeValues(buildUpdateExpressionAttributeValues(profile))
.build()
).thenRun(Util.NOOP)
).toCompletableFuture();
.build())
.build();
}
private static Map<String, AttributeValue> buildPrimaryKey(final UUID uuid, final String version) {
@@ -124,7 +125,7 @@ public class Profiles {
}
@VisibleForTesting
static String buildUpdateExpression(final VersionedProfile profile) {
static String buildUpdateExpression(final VersionedProfileV1 profile) {
final List<String> updatedAttributes = new ArrayList<>(5);
final List<String> deletedAttributes = new ArrayList<>(5);
@@ -186,7 +187,7 @@ public class Profiles {
}
@VisibleForTesting
static Map<String, AttributeValue> buildUpdateExpressionAttributeValues(final VersionedProfile profile) {
static Map<String, AttributeValue> buildUpdateExpressionAttributeValues(final VersionedProfileV1 profile) {
final Map<String, AttributeValue> expressionValues = new HashMap<>();
expressionValues.put(":commitment", AttributeValues.fromByteArray(profile.commitment()));
@@ -217,7 +218,7 @@ public class Profiles {
return expressionValues;
}
public Optional<VersionedProfile> get(final UUID uuid, final String version) {
public Optional<VersionedProfileV1> get(final UUID uuid, final String version) {
return GET_PROFILE_TIMER.record(() -> {
final GetItemResponse response = dynamoDbClient.getItem(GetItemRequest.builder()
.tableName(tableName)
@@ -229,19 +230,8 @@ public class Profiles {
});
}
public CompletableFuture<Optional<VersionedProfile>> getAsync(final UUID uuid, final String version) {
return AsyncTimerUtil.record(GET_PROFILE_TIMER, () -> dynamoDbAsyncClient.getItem(GetItemRequest.builder()
.tableName(tableName)
.key(buildPrimaryKey(uuid, version))
.consistentRead(true)
.build())
.thenApply(response ->
response.hasItem() ? Optional.of(fromItem(response.item())) : Optional.<VersionedProfile>empty())
).toCompletableFuture();
}
private static VersionedProfile fromItem(final Map<String, AttributeValue> item) {
return new VersionedProfile(
private static VersionedProfileV1 fromItem(final Map<String, AttributeValue> item) {
return new VersionedProfileV1(
AttributeValues.getString(item, ATTR_VERSION, null),
getBytes(item, ATTR_NAME),
AttributeValues.getString(item, ATTR_AVATAR, null),
@@ -11,8 +11,10 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.annotations.VisibleForTesting;
import io.lettuce.core.RedisException;
import io.lettuce.core.ScriptOutputType;
import io.micrometer.core.instrument.Metrics;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@@ -21,12 +23,13 @@ import java.util.function.Function;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Mono;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
@@ -35,39 +38,89 @@ public class ProfilesManager {
private final Logger logger = LoggerFactory.getLogger(ProfilesManager.class);
private static final String CACHE_PREFIX_V1 = "profiles_v1::";
private static final String CACHE_PREFIX_V2 = "profiles_v2::";
private final Profiles profiles;
private static final byte[] EMPTY = new byte[0];
private final Profiles profilesV1;
private final ProfilesV2 profilesV2;
private final FaultTolerantRedisClusterClient cacheCluster;
private final ScheduledExecutorService retryExecutor;
private final S3AsyncClient s3Client;
private final String bucket;
private final ClusterLuaScript setLuaScript;
private final ObjectMapper mapper;
private static final String RETRY_NAME = ResilienceUtil.name(ProfilesManager.class);
private static final String DELETE_AVATAR_COUNTER_NAME = name(ProfilesManager.class, "deleteAvatar");
public ProfilesManager(final Profiles profiles,
public ProfilesManager(final Profiles profilesV1,
final ProfilesV2 profilesV2,
final FaultTolerantRedisClusterClient cacheCluster,
final ScheduledExecutorService retryExecutor,
final S3AsyncClient s3Client,
final String bucket) {
this.profiles = profiles;
final String bucket) throws IOException {
this(profilesV1, profilesV2, cacheCluster, retryExecutor, s3Client, bucket,
ClusterLuaScript.fromResource(cacheCluster, "lua/profile_set.lua", ScriptOutputType.STATUS));
}
@VisibleForTesting
ProfilesManager(final Profiles profilesV1,
final ProfilesV2 profilesV2,
final FaultTolerantRedisClusterClient cacheCluster,
final ScheduledExecutorService retryExecutor,
final S3AsyncClient s3Client,
final String bucket,
final ClusterLuaScript setLuaScript) {
this.profilesV1 = profilesV1;
this.profilesV2 = profilesV2;
this.cacheCluster = cacheCluster;
this.retryExecutor = retryExecutor;
this.s3Client = s3Client;
this.bucket = bucket;
this.setLuaScript = setLuaScript;
this.mapper = SystemMapper.jsonMapper();
}
public void set(UUID uuid, VersionedProfile versionedProfile) {
redisSet(uuid, versionedProfile);
profiles.set(uuid, versionedProfile);
public void setV1(UUID uuid, VersionedProfileV1 versionedProfile) {
redisDelete(uuid);
profilesV1.set(uuid, versionedProfile);
redisSet(uuid, null, versionedProfile);
try {
// until the PROFILES_V2 capability prevents downgrades, if a client sets a v2 profile, and then the account
// downgrades to v1, all v2 profiles are stale
assert !DeviceCapability.PROFILES_V2.preventDowngrade();
profilesV2.deleteAll(uuid);
} catch (final Exception e) {
logger.warn("Failed to delete v2 profile data: {}", uuid, e);
}
}
public CompletableFuture<Void> setAsync(UUID uuid, VersionedProfile versionedProfile) {
return profiles.setAsync(uuid, versionedProfile)
.thenCompose(ignored -> redisSetAsync(uuid, versionedProfile));
/// Transactionally sets v1 and v2 Profile data in DynamoDB.
///
/// Note: writes to the Redis cache are not transactional, and a failed DynamoDB write may leave incorrect data in Redis
public void set(UUID uuid, VersionedProfileV1 versionedProfileV1, VersionedProfile versionedProfile, @Nullable byte[] expectedCurrentDataHash) throws WriteConflictException {
final TransactWriteItem v1TransactWriteItem = profilesV1.getTransactWriteItem(uuid, versionedProfileV1);
redisDelete(uuid);
profilesV2.set(uuid,
versionedProfile.version(),
versionedProfile.data(),
versionedProfile.dataHash(),
versionedProfile.commitment(),
versionedProfile.paymentAddress(),
versionedProfile.paymentAddressHash(),
expectedCurrentDataHash,
v1TransactWriteItem);
redisSet(uuid, versionedProfile, versionedProfileV1);
}
/**
@@ -78,7 +131,7 @@ public class ProfilesManager {
*/
public CompletableFuture<Void> deleteAll(UUID uuid, final boolean includeAvatar) {
final CompletableFuture<Void> profilesAndAvatars = Mono.fromFuture(profiles.deleteAll(uuid))
final CompletableFuture<Void> profilesV1AndAvatars = Mono.fromFuture(profilesV1.deleteAll(uuid))
.flatMapIterable(Function.identity())
.flatMap(avatar ->
Mono.fromFuture(includeAvatar ? deleteAvatar(avatar) : CompletableFuture.completedFuture(null))
@@ -87,7 +140,7 @@ public class ProfilesManager {
.onErrorComplete())
.then().toFuture();
return CompletableFuture.allOf(redisDelete(uuid), profilesAndAvatars);
return CompletableFuture.allOf(redisDeleteAsync(uuid), profilesV1AndAvatars, profilesV2.deleteAll(uuid));
}
public CompletableFuture<Void> deleteAvatar(String avatar) {
@@ -110,87 +163,99 @@ public class ProfilesManager {
.thenRun(Util.NOOP);
}
public Optional<VersionedProfile> get(UUID uuid, String version) {
Optional<VersionedProfile> profile = redisGet(uuid, version);
if (profile.isEmpty()) {
profile = profiles.get(uuid, version);
public Optional<VersionedProfileV1> getV1(UUID uuid, String version) {
return redisGetV1(uuid, version).or(() -> {
final Optional<VersionedProfileV1> profile = profilesV1.get(uuid, version);
try {
profile.ifPresent(versionedProfile -> redisSet(uuid, versionedProfile));
profile.ifPresent(versionedProfile -> redisSet(uuid, null, versionedProfile));
} catch (RedisException e) {
logger.warn("Failed to cache retrieved profile", e);
}
}
return profile;
return profile;
});
}
public CompletableFuture<Optional<VersionedProfile>> getAsync(UUID uuid, String version) {
return redisGetAsync(uuid, version)
.thenCompose(maybeVersionedProfile -> maybeVersionedProfile
.map(versionedProfile -> CompletableFuture.completedFuture(maybeVersionedProfile))
.orElseGet(() -> profiles.getAsync(uuid, version)
.thenCompose(maybeVersionedProfileFromDynamo -> maybeVersionedProfileFromDynamo
.map(profile -> redisSetAsync(uuid, profile)
.exceptionally(ExceptionUtils.exceptionallyHandler(RedisException.class, e -> {
logger.warn("Failed to cache retrieved profile", e);
return null;
}))
.thenApply(ignored -> maybeVersionedProfileFromDynamo))
.orElseGet(() -> CompletableFuture.completedFuture(maybeVersionedProfileFromDynamo)))));
public Optional<VersionedProfile> get(UUID uuid, byte[] version) {
return redisGet(uuid, version).or(() -> {
final Optional<VersionedProfile> profile = profilesV2.get(uuid, version);
try {
profile.ifPresent(versionedProfile -> redisSet(uuid, versionedProfile, null));
} catch (RedisException e) {
logger.warn("Failed to cache retrieved profile", e);
}
return profile;
});
}
private void redisSet(UUID uuid, VersionedProfile profile) {
@VisibleForTesting
void redisSet(UUID uuid, @Nullable VersionedProfile v2Profile, @Nullable VersionedProfileV1 v1Profile) {
try {
final byte[] profileJson = mapper.writeValueAsBytes(profile);
if (v1Profile == null && v2Profile == null) {
logger.error("Expected at least one profile");
return;
}
final byte[] v1ProfileVersion;
final byte[] v1ProfileBytes;
if (v1Profile != null) {
v1ProfileVersion = v1Profile.version().getBytes();
v1ProfileBytes = mapper.writeValueAsBytes(v1Profile);
} else {
v1ProfileVersion = EMPTY;
v1ProfileBytes = EMPTY;
}
final byte[] v2ProfileVersion;
final byte[] v2ProfileBytes;
if (v2Profile != null) {
v2ProfileVersion = v2Profile.version();
v2ProfileBytes = mapper.writeValueAsBytes(v2Profile);
} else {
v2ProfileVersion = EMPTY;
v2ProfileBytes = EMPTY;
}
setLuaScript.executeBinary(List.of(getCacheKeyV1(uuid), getCacheKeyV2(uuid)),
List.of(v1ProfileVersion, v1ProfileBytes, v2ProfileVersion, v2ProfileBytes));
cacheCluster.useBinaryCluster(connection -> connection.sync().hset(getCacheKeyV1(uuid), profile.version().getBytes(), profileJson));
} catch (JsonProcessingException e) {
throw new IllegalArgumentException(e);
}
}
private CompletableFuture<Void> redisSetAsync(UUID uuid, VersionedProfile profile) {
final byte[] profileJson;
private Optional<VersionedProfile> redisGet(UUID uuid, byte[] version) {
try {
profileJson = mapper.writeValueAsBytes(profile);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException(e);
}
@Nullable final byte[] json = cacheCluster.withBinaryCluster(connection -> connection.sync().hget(getCacheKeyV2(uuid), version));
return cacheCluster.withBinaryCluster(connection ->
connection.async().hset(getCacheKeyV1(uuid), profile.version().getBytes(), profileJson)).toCompletableFuture()
.thenRun(Util.NOOP)
.toCompletableFuture();
return parseProfileJson(json, VersionedProfile.class);
} catch (RedisException e) {
logger.warn("Redis exception", e);
return Optional.empty();
}
}
private Optional<VersionedProfile> redisGet(UUID uuid, String version) {
@VisibleForTesting
static byte[] getCacheKeyV2(UUID uuid) {
return (CACHE_PREFIX_V2 + '{' + uuid.toString() + '}').getBytes();
}
private Optional<VersionedProfileV1> redisGetV1(UUID uuid, String version) {
try {
@Nullable final byte[] json = cacheCluster.withBinaryCluster(connection -> connection.sync().hget(getCacheKeyV1(uuid), version.getBytes()));
return parseProfileJson(json);
return parseProfileJson(json, VersionedProfileV1.class);
} catch (RedisException e) {
logger.warn("Failed to retrieve profile from cache", e);
return Optional.empty();
}
}
private CompletableFuture<Optional<VersionedProfile>> redisGetAsync(UUID uuid, String version) {
return cacheCluster.withBinaryCluster(connection ->
connection.async().hget(getCacheKeyV1(uuid), version.getBytes()))
.thenApply(this::parseProfileJson)
.exceptionally(throwable -> {
logger.warn("Failed to read versioned profile from Redis", throwable);
return Optional.empty();
})
.toCompletableFuture();
}
private Optional<VersionedProfile> parseProfileJson(@Nullable final byte[] maybeJson) {
private <T> Optional<T> parseProfileJson(@Nullable final byte[] maybeJson, Class<T> klass) {
try {
if (maybeJson != null) {
return Optional.of(mapper.readValue(maybeJson, VersionedProfile.class));
return Optional.of(mapper.readValue(maybeJson, klass));
}
return Optional.empty();
} catch (final IOException e) {
@@ -199,10 +264,17 @@ public class ProfilesManager {
}
}
private CompletableFuture<Void> redisDelete(UUID uuid) {
private void redisDelete(UUID uuid) {
ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
.executeRunnable(() -> cacheCluster.withBinaryCluster(
connection -> connection.sync().del(getCacheKeyV1(uuid), getCacheKeyV2(uuid))));
}
private CompletableFuture<Void> redisDeleteAsync(UUID uuid) {
return ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
.executeCompletionStage(retryExecutor, () -> cacheCluster.withBinaryCluster(connection -> connection.async().del(getCacheKeyV1(uuid))))
.executeCompletionStage(retryExecutor,
() -> cacheCluster.withBinaryCluster(connection -> connection.async().del(getCacheKeyV1(uuid), getCacheKeyV2(uuid))))
.toCompletableFuture()
.thenRun(Util.NOOP);
}
@@ -0,0 +1,342 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.CancellationReason;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.ReturnValuesOnConditionCheckFailure;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsRequest;
import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledException;
import software.amazon.awssdk.services.dynamodb.model.Update;
public class ProfilesV2 {
private static final String CONDITIONAL_CHECK_FAILED_CODE = "ConditionalCheckFailed";
private static final String TRANSACTION_CONFLICT_CODE = "TransactionConflict";
private final DynamoDbClient dynamoDbClient;
private final DynamoDbAsyncClient dynamoDbAsyncClient;
private final String tableName;
// UUID of the account that owns this profile; hash key; byte array
@VisibleForTesting
static final String KEY_ACCOUNT_UUID = "U";
// Version of this profile; sort key; byte array
@VisibleForTesting
static final String KEY_VERSION = "V";
// Profile data (serialized ciphertext); byte array
private static final String ATTR_DATA = "D";
// SHA-256 hash of data attribute; byte array
private static final String ATTR_DATA_HASH = "DH";
// Commitment; byte array
private static final String ATTR_COMMITMENT = "C";
// Payment address; byte array
private static final String ATTR_PAYMENT_ADDRESS = "P";
// SHA-256 hash of payment address attribute; byte array
private static final String ATTR_PAYMENT_ADDRESS_HASH = "PH";
private static final Map<String, String> UPDATE_EXPRESSION_ATTRIBUTE_NAMES = Map.of(
"#data", ATTR_DATA,
"#dataHash", ATTR_DATA_HASH,
"#commitment", ATTR_COMMITMENT,
"#paymentAddress", ATTR_PAYMENT_ADDRESS,
"#paymentAddressHash", ATTR_PAYMENT_ADDRESS_HASH);
private static final Timer SET_PROFILES_TIMER = Metrics.timer(name(ProfilesV2.class, "set"));
private static final Timer GET_PROFILE_TIMER = Metrics.timer(name(ProfilesV2.class, "get"));
private static final String DELETE_PROFILES_TIMER_NAME = name(ProfilesV2.class, "delete");
private static final String WRITE_CONFLICTS_COUNTER_NAME = name(ProfilesV2.class, "writeConflicts");
private static final int COMMITMENT_LENGTH = 97;
private static final int DELETE_MAX_CONCURRENCY = 32;
public ProfilesV2(final DynamoDbClient dynamoDbClient,
final DynamoDbAsyncClient dynamoDbAsyncClient,
final String tableName) {
this.dynamoDbClient = dynamoDbClient;
this.dynamoDbAsyncClient = dynamoDbAsyncClient;
this.tableName = tableName;
}
/// Put a profile version with the given data
///
/// During the migration from v1 &rarr; v2, both updates are executed transactionally
///
/// @param uuid the account UUID
/// @param version the profile version
/// @param data serialized profile ciphertext
/// @param commitment serialized profile key commitment (required for initial write, optional for updates)
/// @param paymentAddress serialized payment address ciphertext (nullable)
/// @param expectedCurrentDataHash the expected current data hash, used for conditional update (nullable for the initial write)
/// @param profileV1TransactWriteItem transact write item for v1 profile during migration
/// @throws WriteConflictException if the expected data hash does not match the stored data hash
/// @throws IllegalArgumentException if commitment is null on initial write or commitment does not match on an update
/// @throws IllegalStateException if commitment is missing after a write
public void set(final UUID uuid,
final byte[] version,
final byte[] data,
final byte[] dataHash,
@Nullable final byte[] commitment,
@Nullable final byte[] paymentAddress,
@Nullable final byte[] paymentAddressHash,
@Nullable final byte[] expectedCurrentDataHash,
final TransactWriteItem profileV1TransactWriteItem) throws WriteConflictException {
// Commitment is required for initial write (when expectedCurrentDataHash is null)
if (expectedCurrentDataHash == null && commitment == null) {
throw new IllegalArgumentException("Commitment is required for initial write");
}
final Timer.Sample sample = Timer.start();
try {
final List<TransactWriteItem> transactWriteItems = List.of(
getTransactWriteItem(uuid, version, data, dataHash, commitment, paymentAddress, paymentAddressHash, expectedCurrentDataHash),
profileV1TransactWriteItem);
dynamoDbClient.transactWriteItems(TransactWriteItemsRequest.builder()
.transactItems(transactWriteItems)
.build());
} catch (TransactionCanceledException e) {
if (e.hasCancellationReasons()) {
// check for fields with conditional check failures
if (e.cancellationReasons().getFirst() != null
&& e.cancellationReasons().getFirst().code().equals(CONDITIONAL_CHECK_FAILED_CODE)
&& e.cancellationReasons().getFirst().hasItem()) {
final Map<String, AttributeValue> item = e.cancellationReasons().getFirst().item();
final byte[] oldCommitment = AttributeValues.getByteArray(item, ATTR_COMMITMENT, null);
if (oldCommitment != null && commitment != null && !Arrays.equals(oldCommitment, commitment)) {
throw new IllegalArgumentException("Commitment is immutable");
}
if (oldCommitment == null && commitment == null) {
throw new IllegalStateException("Commitment is absent from existing profile");
}
}
final Optional<String> cancellationCode = e.cancellationReasons().stream()
.map(CancellationReason::code)
.filter(code -> CONDITIONAL_CHECK_FAILED_CODE.equals(code) || TRANSACTION_CONFLICT_CODE.equals(code))
.findFirst();
if (cancellationCode.isPresent()) {
// any other conditional check failure is an expected data hash mismatch, which is a write conflict
Metrics.counter(WRITE_CONFLICTS_COUNTER_NAME, "code", cancellationCode.get()).increment();
throw new WriteConflictException();
}
}
throw e;
} finally {
sample.stop(SET_PROFILES_TIMER);
}
}
/// Get a [TransactWriteItem] for a profile update during the v2 migration
///
/// @param uuid the account UUID
/// @param version the profile version
/// @param data the serialized profile ciphertext
/// @param dataHash the serialized profile ciphertext hash
/// @param commitment the profile key commitment (required for initial write, optional for updates)
/// @param paymentAddress the payment address (nullable; will clear existing value for this version if null)
/// @param paymentAddressHash the payment address hash (nullable; will clear existing value for this version if null)
/// @param expectedCurrentDataHash the expected current data hash for conditional update (nullable for first write)
/// @return a [TransactWriteItem] containing the Update operation
@VisibleForTesting
TransactWriteItem getTransactWriteItem(final UUID uuid,
final byte[] version,
final byte[] data,
final byte[] dataHash,
@Nullable final byte[] commitment,
@Nullable final byte[] paymentAddress,
@Nullable final byte[] paymentAddressHash,
@Nullable final byte[] expectedCurrentDataHash) {
return TransactWriteItem.builder()
.update(Update.builder()
.tableName(tableName)
.key(buildPrimaryKey(uuid, version))
.updateExpression(buildUpdateExpression(commitment != null, paymentAddress != null))
.conditionExpression(buildConditionExpression(commitment != null, expectedCurrentDataHash != null))
.expressionAttributeNames(UPDATE_EXPRESSION_ATTRIBUTE_NAMES)
.expressionAttributeValues(buildUpdateExpressionAttributeValues(data, dataHash, commitment, paymentAddress, paymentAddressHash, expectedCurrentDataHash))
.returnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD)
.build())
.build();
}
private static Map<String, AttributeValue> buildPrimaryKey(final UUID uuid, final byte[] version) {
return Map.of(
KEY_ACCOUNT_UUID, AttributeValues.fromUUID(uuid),
KEY_VERSION, AttributeValues.fromByteArray(version));
}
@VisibleForTesting
static String buildUpdateExpression(final boolean hasCommitment, final boolean hasPaymentAddress) {
final StringBuilder updateExpressionBuilder = new StringBuilder("SET #data = :data, #dataHash = :dataHash");
if (hasCommitment) {
updateExpressionBuilder.append(", #commitment = if_not_exists(#commitment, :commitment)");
}
if (hasPaymentAddress) {
updateExpressionBuilder.append(", #paymentAddress = :paymentAddress, #paymentAddressHash = :paymentAddressHash");
} else {
updateExpressionBuilder.append(" REMOVE #paymentAddress, #paymentAddressHash");
}
return updateExpressionBuilder.toString();
}
@VisibleForTesting
static String buildConditionExpression(final boolean hasCommitment, final boolean hasExpectedCurrentDataHash) {
final StringBuilder sb = new StringBuilder();
if (hasCommitment) {
sb.append("(attribute_not_exists(#commitment) OR #commitment = :commitment)");
} else {
sb.append("size(#commitment) = :commitment_length");
}
if (hasExpectedCurrentDataHash) {
// If expected hash is provided, verify it matches the stored hash
sb.append(" AND #dataHash = :expectedDataHash");
} else {
// Initial write: dataHash must not exist
sb.append(" AND attribute_not_exists(#dataHash)");
}
return sb.toString();
}
@VisibleForTesting
static Map<String, AttributeValue> buildUpdateExpressionAttributeValues(
final byte[] data,
final byte[] dataHash,
@Nullable final byte[] commitment,
@Nullable final byte[] paymentAddress,
@Nullable final byte[] paymentAddressHash,
@Nullable final byte[] expectedCurrentDataHash) {
final Map<String, AttributeValue> expressionValues = new HashMap<>();
expressionValues.put(":data", AttributeValues.fromByteArray(data));
expressionValues.put(":dataHash", AttributeValues.fromByteArray(dataHash));
if (commitment != null) {
expressionValues.put(":commitment", AttributeValues.fromByteArray(commitment));
} else {
expressionValues.put(":commitment_length", AttributeValues.fromInt(COMMITMENT_LENGTH));
}
if (paymentAddress != null) {
expressionValues.put(":paymentAddress", AttributeValues.fromByteArray(paymentAddress));
expressionValues.put(":paymentAddressHash", AttributeValues.fromByteArray(paymentAddressHash));
}
if (expectedCurrentDataHash != null) {
expressionValues.put(":expectedDataHash", AttributeValues.fromByteArray(expectedCurrentDataHash));
}
return expressionValues;
}
/// Fetch a profile version
///
/// @param uuid the account UUID
/// @param version the profile version
/// @return the VersionedProfile, if found
public Optional<VersionedProfile> get(final UUID uuid, final byte[] version) {
return GET_PROFILE_TIMER.record(() -> {
final GetItemResponse response = dynamoDbClient.getItem(GetItemRequest.builder()
.tableName(tableName)
.key(buildPrimaryKey(uuid, version))
.consistentRead(true)
.build());
return response.hasItem() ? Optional.of(fromItem(response.item())) : Optional.empty();
});
}
private static VersionedProfile fromItem(final Map<String, AttributeValue> item) {
return new VersionedProfile(
Objects.requireNonNull(AttributeValues.getByteArray(item, KEY_VERSION, null)),
Objects.requireNonNull(AttributeValues.getByteArray(item, ATTR_DATA, null)),
Objects.requireNonNull(AttributeValues.getByteArray(item, ATTR_DATA_HASH, null)),
AttributeValues.getByteArray(item, ATTR_PAYMENT_ADDRESS, null),
AttributeValues.getByteArray(item, ATTR_PAYMENT_ADDRESS_HASH, null),
Objects.requireNonNull(AttributeValues.getByteArray(item, ATTR_COMMITMENT, null)));
}
/// Deletes all profile versions for the given UUID.
///
/// @param uuid the account UUID
/// @return a CompletableFuture that completes when all versions have been deleted
public CompletableFuture<Void> deleteAll(final UUID uuid) {
final Timer.Sample sample = Timer.start();
final AttributeValue uuidAttributeValue = AttributeValues.fromUUID(uuid);
return Flux.from(dynamoDbAsyncClient.queryPaginator(QueryRequest.builder()
.tableName(tableName)
.keyConditionExpression("#uuid = :uuid")
.expressionAttributeNames(Map.of("#uuid", KEY_ACCOUNT_UUID))
.expressionAttributeValues(Map.of(":uuid", uuidAttributeValue))
.projectionExpression(KEY_VERSION)
.consistentRead(true)
.build())
.items())
.flatMap(item -> Mono.fromFuture(() -> dynamoDbAsyncClient.deleteItem(DeleteItemRequest.builder()
.tableName(tableName)
.key(Map.of(
KEY_ACCOUNT_UUID, uuidAttributeValue,
KEY_VERSION, item.get(KEY_VERSION)))
.build())), DELETE_MAX_CONCURRENCY)
.then()
.doOnSuccess(_ -> sample.stop(Metrics.timer(DELETE_PROFILES_TIMER_NAME, "outcome", "success")))
.doOnError(_ -> sample.stop(Metrics.timer(DELETE_PROFILES_TIMER_NAME, "outcome", "error")))
.toFuture();
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* Copyright 2013 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
@@ -7,34 +7,77 @@ package org.whispersystems.textsecuregcm.storage;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.google.common.annotations.VisibleForTesting;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Objects;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import org.whispersystems.textsecuregcm.util.ByteArrayBase64WithPaddingAdapter;
public record VersionedProfile (String version,
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] name,
public record VersionedProfile(@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
byte[] version,
@Nullable
String avatar,
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
byte[] data,
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] aboutEmoji,
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
byte[] dataHash,
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] about,
@Nullable
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
byte[] paymentAddress,
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] paymentAddress,
@Nullable
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
byte[] paymentAddressHash,
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
byte[] phoneNumberSharing,
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
byte[] commitment) {
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
byte[] commitment) {}
public VersionedProfile(byte[] version, byte[] data, @Nullable byte[] paymentAddress, byte[] commitment) {
this(Objects.requireNonNull(version), Objects.requireNonNull(data), hash(Objects.requireNonNull(data)), paymentAddress, paymentAddress == null ? null : hash(paymentAddress), Objects.requireNonNull(commitment));
}
@Override
public boolean equals(final Object o) {
if (!(o instanceof final VersionedProfile that))
return false;
return Arrays.equals(data, that.data) && Arrays.equals(version, that.version) && Arrays.equals(dataHash,
that.dataHash) && Arrays.equals(commitment, that.commitment) && Arrays.equals(paymentAddress,
that.paymentAddress) && Arrays.equals(paymentAddressHash, that.paymentAddressHash);
}
@Override
public int hashCode() {
return Objects.hash(
Arrays.hashCode(version),
Arrays.hashCode(data),
Arrays.hashCode(dataHash),
Arrays.hashCode(paymentAddress),
Arrays.hashCode(paymentAddressHash),
Arrays.hashCode(commitment));
}
/**
* Computes the SHA-256 hash of the given data.
*/
@VisibleForTesting
static byte[] hash(final byte[] data) {
final MessageDigest sha256;
try {
sha256 = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
return sha256.digest(data);
}
}
@@ -0,0 +1,67 @@
/*
* Copyright 2013 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import org.whispersystems.textsecuregcm.util.ByteArrayBase64WithPaddingAdapter;
import java.util.Arrays;
import java.util.Objects;
public record VersionedProfileV1(String version,
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] name,
@Nullable
String avatar,
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] aboutEmoji,
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] about,
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] paymentAddress,
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
byte[] phoneNumberSharing,
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
byte[] commitment) {
@Override
public boolean equals(final Object o) {
if (!(o instanceof final VersionedProfileV1 that))
return false;
return Arrays.equals(name, that.name) && Arrays.equals(about, that.about) && Objects.equals(avatar, that.avatar)
&& Objects.equals(version, that.version) && Arrays.equals(aboutEmoji, that.aboutEmoji) && Arrays.equals(
commitment, that.commitment) && Arrays.equals(paymentAddress, that.paymentAddress) && Arrays.equals(
phoneNumberSharing, that.phoneNumberSharing);
}
@Override
public int hashCode() {
return Objects.hash(
version,
Arrays.hashCode(name),
Objects.hashCode(avatar),
Arrays.hashCode(aboutEmoji),
Arrays.hashCode(about),
Arrays.hashCode(paymentAddress),
Arrays.hashCode(phoneNumberSharing),
Arrays.hashCode(commitment));
}
}
@@ -0,0 +1,11 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
public class WriteConflictException extends NoStackTraceException {
}
@@ -1,18 +1,6 @@
package org.whispersystems.textsecuregcm.util;
import com.google.common.annotations.VisibleForTesting;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialResponse;
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCommitment;
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.whispersystems.textsecuregcm.configuration.BadgeConfiguration;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.AccountBadge;
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
import javax.annotation.Nullable;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Duration;
@@ -23,7 +11,25 @@ import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import javax.annotation.Nullable;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialResponse;
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCommitment;
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.whispersystems.textsecuregcm.configuration.BadgeConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.entities.CreateProfileRequest;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountBadge;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
public class ProfileHelper {
public static int MAX_PROFILE_AVATAR_SIZE_BYTES = 10 * 1024 * 1024;
@@ -86,15 +92,43 @@ public class ProfileHelper {
}
public static ExpiringProfileKeyCredentialResponse getExpiringProfileKeyCredential(
final byte[] encodedCredentialRequest,
final VersionedProfile profile,
final ProfileKeyCredentialRequest request,
final ProfileKeyCommitment commitment,
final ServiceId.Aci accountIdentifier,
final ServerZkProfileOperations zkProfileOperations) throws InvalidInputException, VerificationFailedException {
final Instant expiration = Instant.now().plus(EXPIRING_PROFILE_KEY_CREDENTIAL_EXPIRATION).truncatedTo(ChronoUnit.DAYS);
final ProfileKeyCommitment commitment = new ProfileKeyCommitment(profile.commitment());
final ProfileKeyCredentialRequest request = new ProfileKeyCredentialRequest(
encodedCredentialRequest);
return zkProfileOperations.issueExpiringProfileKeyCredential(request, accountIdentifier, commitment, expiration);
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public static boolean isPaymentAddressUpdateForbidden(
final Account account, final Optional<VersionedProfile> maybeProfile,
final Optional<VersionedProfileV1> maybeV1Profile,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
final Optional<byte[]> currentPaymentAddress = maybeProfile.map(VersionedProfile::paymentAddress)
.or(() -> maybeV1Profile.map(VersionedProfileV1::paymentAddress));
final boolean hasDisallowedPrefix = dynamicConfigurationManager.getConfiguration().getPaymentsConfiguration()
.getDisallowedPrefixes().stream()
.anyMatch(prefix -> account.getNumber().startsWith(prefix));
return hasDisallowedPrefix && currentPaymentAddress.isEmpty();
}
@Nullable
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public static String getAvatar(final CreateProfileRequest.AvatarChange avatarChange, final Optional<String> currentAvatar) {
return switch (avatarChange) {
case UNCHANGED -> currentAvatar.orElse(null);
case CLEAR -> null;
case UPDATE -> ProfileHelper.generateAvatarObjectName();
};
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public static Optional<String> getCurrentAvatar(Optional<VersionedProfileV1> maybeV1Profile) {
return maybeV1Profile.map(VersionedProfileV1::avatar).filter(avatar -> avatar.startsWith("profiles/"));
}
}
@@ -63,6 +63,7 @@ import org.whispersystems.textsecuregcm.storage.PagedSingleUseKEMPreKeyStore;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.Profiles;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.ProfilesV2;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswords;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.RepeatedUseECSignedPreKeyStore;
@@ -220,8 +221,10 @@ public record CommandDependencies(
configuration.getDynamoDbTables().getAccounts().getUsedLinkDeviceTokensTableName());
PhoneNumberIdentifiers phoneNumberIdentifiers = new PhoneNumberIdentifiers(dynamoDbAsyncClient,
configuration.getDynamoDbTables().getPhoneNumberIdentifiers().getTableName());
Profiles profiles = new Profiles(dynamoDbClient, dynamoDbAsyncClient,
configuration.getDynamoDbTables().getProfiles().getTableName());
Profiles profilesV1 = new Profiles(dynamoDbClient, dynamoDbAsyncClient,
configuration.getDynamoDbTables().getProfilesV1().getTableName());
ProfilesV2 profiles = new ProfilesV2(dynamoDbClient, dynamoDbAsyncClient,
configuration.getDynamoDbTables().getProfilesV2().getTableName());
S3AsyncClient asyncKeysS3Client = S3AsyncClient.builder()
.credentialsProvider(awsCredentialsProvider)
.region(Region.of(configuration.getPagedSingleUseKEMPreKeyStore().region()))
@@ -263,7 +266,7 @@ public record CommandDependencies(
disconnectionRequestListenerExecutor, retryExecutor);
MessagesCache messagesCache = new MessagesCache(messagesCluster,
messageDeliveryScheduler, messageDeletionExecutor, retryExecutor, Clock.systemUTC(), experimentEnrollmentManager);
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster, retryExecutor, asyncCdnS3Client,
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, cacheCluster, retryExecutor, asyncCdnS3Client,
configuration.getCdnConfiguration().bucket());
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
configuration.getDynamoDbTables().getReportMessage().getTableName(),
@@ -13,6 +13,7 @@ import net.sourceforge.argparse4j.inf.Subparser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.AccountsManager.DeletionReason;
@@ -51,7 +52,7 @@ public class DeleteUserCommand extends AbstractCommandWithDependencies {
Optional<Account> account = accountsManager.getByE164(user);
if (account.isPresent()) {
accountsManager.delete(account.get(), DeletionReason.ADMIN_DELETED);
accountsManager.delete(account.get().getIdentifier(IdentityType.ACI), DeletionReason.ADMIN_DELETED);
logger.warn("Removed " + account.get().getNumber());
} else {
logger.warn("Account not found");
@@ -16,6 +16,7 @@ import java.time.Instant;
import net.sourceforge.argparse4j.inf.Subparser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import reactor.core.publisher.Mono;
@@ -67,7 +68,7 @@ public class RemoveExpiredAccountsCommand extends AbstractSinglePassCrawlAccount
.flatMap(expiredAccount -> {
final Mono<Void> deleteAccountMono = isDryRun
? Mono.empty()
: Mono.fromRunnable(() -> getCommandDependencies().accountsManager().delete(expiredAccount, AccountsManager.DeletionReason.EXPIRED))
: Mono.fromRunnable(() -> getCommandDependencies().accountsManager().delete(expiredAccount.getIdentifier(IdentityType.ACI), AccountsManager.DeletionReason.EXPIRED))
.subscribeOn(Schedulers.boundedElastic())
.then();
@@ -21,6 +21,7 @@ import java.util.stream.Collectors;
import net.sourceforge.argparse4j.inf.Subparser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import reactor.core.publisher.Flux;
@@ -130,7 +131,7 @@ public class RemoveExpiredLinkedDevicesCommand extends AbstractSinglePassCrawlAc
return Flux.fromIterable(expiredDevices)
.flatMap(deviceId ->
Mono.fromRunnable(() -> getCommandDependencies().accountsManager().removeDevice(account, deviceId))
Mono.fromRunnable(() -> getCommandDependencies().accountsManager().removeDevice(account.getIdentifier(IdentityType.ACI), deviceId))
.retryWhen(Retry.backoff(maxRetries, Duration.ofSeconds(1))
.doAfterRetry(ignored -> retryCounter.increment())
.onRetryExhaustedThrow((spec, rs) -> rs.failure()))
@@ -20,6 +20,7 @@ import java.util.concurrent.atomic.AtomicLong;
import net.sourceforge.argparse4j.inf.Subparser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import reactor.core.publisher.Flux;
@@ -85,7 +86,7 @@ public class RemoveExpiredUsernameHoldsCommand extends AbstractSinglePassCrawlAc
final int holdsToRemove = removeExpired(holds);
final Mono<Void> purgeMono = isDryRun || holdsToRemove == 0
? Mono.empty()
: Mono.fromRunnable(() -> accountManager.update(account, a -> a.setUsernameHolds(holds)))
: Mono.fromRunnable(() -> accountManager.update(account.getIdentifier(IdentityType.ACI), a -> a.setUsernameHolds(holds)))
.subscribeOn(Schedulers.boundedElastic())
.then();
Metrics.counter(INSPECTED_ACCOUNTS_COUNTER_NAME,
@@ -12,6 +12,7 @@ import java.util.UUID;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
@@ -61,7 +62,7 @@ public class SetUserDiscoverabilityCommand extends AbstractCommandWithDependenci
maybeAccount.ifPresentOrElse(account -> {
final boolean initiallyDiscoverable = account.isDiscoverableByPhoneNumber();
accountsManager.update(account, a -> a.setDiscoverableByPhoneNumber(namespace.getBoolean("discoverable")));
accountsManager.update(account.getIdentifier(IdentityType.ACI), a -> a.setDiscoverableByPhoneNumber(namespace.getBoolean("discoverable")));
System.out.format("Set discoverability flag for %s to %s (was previously %s)\n",
namespace.getString("user"),
@@ -13,6 +13,7 @@ import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
@@ -51,9 +52,6 @@ public class UnlinkDeviceCommand extends AbstractCommandWithDependencies {
final UUID aci = UUID.fromString(namespace.getString("uuid").trim());
final List<Byte> deviceIds = namespace.getList("deviceIds");
Account account = deps.accountsManager().getByAccountIdentifier(aci)
.orElseThrow(() -> new IllegalArgumentException("account id " + aci + " does not exist"));
if (deviceIds.contains(Device.PRIMARY_ID)) {
throw new IllegalArgumentException("cannot delete primary device");
}
@@ -61,7 +59,7 @@ public class UnlinkDeviceCommand extends AbstractCommandWithDependencies {
for (byte deviceId : deviceIds) {
/** see {@link org.whispersystems.textsecuregcm.controllers.DeviceController#removeDevice} */
System.out.format("Removing device %s::%d\n", aci, deviceId);
deps.accountsManager().removeDevice(account, deviceId);
deps.accountsManager().removeDevice(aci, deviceId);
}
}
}
@@ -93,7 +93,7 @@ public class UnlinkDevicesWithIdlePrimaryCommand extends AbstractSinglePassCrawl
.filter(account -> isPrimaryDeviceIdle(account, currentTime, idleDurationThreshold))
.flatMap(accountWithIdlePrimaryDevice -> Flux.fromIterable(accountWithIdlePrimaryDevice.getDevices())
.filter(device -> !device.isPrimary())
.map(linkedDevice -> Tuples.of(accountWithIdlePrimaryDevice, linkedDevice.getId())))
.map(linkedDevice -> Tuples.of(accountWithIdlePrimaryDevice.getIdentifier(IdentityType.ACI), linkedDevice.getId())))
.flatMap(accountAndLinkedDeviceId -> {
final Mono<Account> unlinkDeviceMono = isDryRun
? Mono.empty()
@@ -104,8 +104,7 @@ public class UnlinkDevicesWithIdlePrimaryCommand extends AbstractSinglePassCrawl
.doOnSuccess(ignored -> unlinkDeviceCounter.increment())
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1)).maxBackoff(Duration.ofSeconds(4)))
.onErrorResume(throwable -> {
logger.warn("Failed to unlink device to delete account {}:{}", accountAndLinkedDeviceId.getT1().getIdentifier(
IdentityType.ACI), accountAndLinkedDeviceId.getT2(), throwable);
logger.warn("Failed to unlink device to delete account {}:{}", accountAndLinkedDeviceId.getT1(), accountAndLinkedDeviceId.getT2(), throwable);
return Mono.empty();
});
@@ -57,6 +57,9 @@ service Accounts {
// Sets the registration recovery password for the authenticated account.
rpc SetRegistrationRecoveryPassword(SetRegistrationRecoveryPasswordRequest) returns (SetRegistrationRecoveryPasswordResponse) {}
// Store a public key used to issue and verify zero-knowledge (anonymous) credentials for the account.
rpc SetZkCredentialKey(SetZkCredentialKeyRequest) returns (SetZkCredentialKeyResponse) {}
}
// Provides methods for looking up Signal accounts. Callers must not provide
@@ -194,7 +197,7 @@ message ConfigureUnidentifiedAccessRequest {
// anonymously (i.e. to retrieve keys or profiles or to send messages) unless
// unrestricted unidentified access is permitted. Must be present if
// unrestricted unidentified access is not allowed.
bytes unidentified_access_key = 1;
bytes unidentified_access_key = 1 [(require.exactlySize) = 0, (require.exactlySize) = 16];
// If `true`, any user may interact with this account anonymously without
// providing an unidentified access key. Otherwise, users must provide the
@@ -265,3 +268,11 @@ message LookupUsernameLinkResponse {
errors.NotFound not_found = 2 [(tag.reason) = "not_found"];
}
}
message SetZkCredentialKeyRequest {
// A serialized Ristretto key with a one-byte type prefix
bytes public_key = 1 [(require.exactlySize) = 33];
}
message SetZkCredentialKeyResponse {
}
@@ -19,7 +19,7 @@ enum IdentityType {
message ServiceIdentifier {
// The type of identity represented by this service identifier.
IdentityType identity_type = 1;
IdentityType identity_type = 1 [(require.specified) = true];
// The UUID of the identity represented by this service identifier.
bytes uuid = 2 [(require.exactlySize) = 16];
@@ -41,7 +41,7 @@ message EcPreKey {
// A locally-unique identifier for this key, which will be provided by
// peers using this key to encrypt messages so the private key can be looked
// up.
uint32 key_id = 1;
int32 key_id = 1 [(require.range).min = 0];
// The public key, serialized in libsignal's elliptic-curve public key format.
bytes public_key = 2 [(require.nonEmpty) = true];
@@ -51,7 +51,7 @@ message EcSignedPreKey {
// A locally-unique identifier for this key, which will be provided by
// peers using this key to encrypt messages so the private key can be looked
// up.
uint32 key_id = 1;
int32 key_id = 1 [(require.range).min = 0];
// The public key, serialized in libsignal's elliptic-curve public key format.
bytes public_key = 2 [(require.nonEmpty) = true];
@@ -64,7 +64,7 @@ message EcSignedPreKey {
message KemSignedPreKey {
// An locally-unique identifier for this key, which will be provided by peers
// using this key to encrypt messages so the private key can be looked up.
uint32 key_id = 1;
int32 key_id = 1 [(require.range).min = 0];
// The public key, serialized in libsignal's Kyber1024 public key format.
bytes public_key = 2 [(require.nonEmpty) = true];
@@ -83,6 +83,7 @@ enum DeviceCapability {
reserved 5;
DEVICE_CAPABILITY_ATTACHMENT_BACKFILL = 6;
DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET = 7;
DEVICE_CAPABILITY_PROFILES_V2 = 8;
}
message ZkCredential {
@@ -10,44 +10,22 @@ option java_multiple_files = true;
package org.signal.chat.profile;
import "org/signal/chat/common.proto";
import "org/signal/chat/errors.proto";
import "org/signal/chat/require.proto";
import "org/signal/chat/tag.proto";
// Provides methods for working with profiles and profile-related data.
service Profile {
// Sets profile data and if needed, returns S3 credentials used by clients to upload an avatar.
//
// This RPC may fail with `PERMISSION_DENIED` if it attempts to set the MobileCoin wallet ID
// on an account whose profile does not currently have a MobileCoin wallet ID and
// whose phone number contains a disallowed country prefix.
// Sets profile data and, if needed, returns credentials used by clients to upload a v1 avatar.
rpc SetProfile(SetProfileRequest) returns (SetProfileResponse) {}
// Retrieves versioned profile data. Callers with an unidentified access key for the account
// should use the version of this method in `ProfileAnonymous` instead.
//
// This RPC may fail with a `NOT_FOUND` status if the target account was not
// found. It may fail with a `RESOURCE_EXHAUSTED` if a rate limit for fetching profiles has been
// exceeded, in which case a `retry-after` header containing an ISO 8601
// duration string will be present in the response trailers.
rpc GetVersionedProfile(GetVersionedProfileRequest) returns (GetVersionedProfileResponse) {}
// Retrieves unversioned profile data. Callers with an unidentified access key for the account
// should use the version of this method in `ProfileAnonymous` instead.
//
// This RPC may fail with a `NOT_FOUND` status if the target account was not
// found. It may fail with a `RESOURCE_EXHAUSTED` if a rate limit for fetching profiles has been
// exceeded, in which case a `retry-after` header containing an ISO 8601
// duration string will be present in the response trailers.
rpc GetUnversionedProfile(GetUnversionedProfileRequest) returns (GetUnversionedProfileResponse) {}
// Retrieves a profile key credential.
// Callers with an unidentified access key for the account
// should use the version of this method in `ProfileAnonymous` instead.
//
// This RPC may fail with a `NOT_FOUND` status if the target account was not
// found. It may fail with a `RESOURCE_EXHAUSTED` if a rate limit for fetching profiles has been
// exceeded, in which case a `retry-after` header containing an ISO 8601
// duration string will be present in the response trailers. It may also fail with an
// `INVALID_ARGUMENT` status if the given credential type is invalid.
rpc GetExpiringProfileKeyCredential(GetExpiringProfileKeyCredentialRequest) returns (GetExpiringProfileKeyCredentialResponse) {}
}
// Provides methods for working with profiles and profile-related data using "unidentified access"
@@ -58,97 +36,206 @@ service Profile {
// methods in `Profile` instead.
service ProfileAnonymous {
// Retrieves versioned profile data.
//
// This RPC may fail with a `NOT_FOUND` status if the target account was not
// found. It may also fail with an `UNAUTHENTICATED` status if the given
// unidentified access key did not match the target account's unidentified
// access key.
rpc GetVersionedProfile(GetVersionedProfileAnonymousRequest) returns (GetVersionedProfileResponse) {}
rpc GetVersionedProfile(GetVersionedProfileAnonymousRequest) returns (GetVersionedProfileAnonymousResponse) {}
// Retrieves unversioned profile data.
//
// This RPC may fail with a `NOT_FOUND` status if the target account was not
// found. It may also fail with an `UNAUTHENTICATED` status if the given
// unidentified access key did not match the target account's unidentified
// access key.
rpc GetUnversionedProfile(GetUnversionedProfileAnonymousRequest) returns (GetUnversionedProfileResponse) {}
rpc GetUnversionedProfile(GetUnversionedProfileAnonymousRequest) returns (GetUnversionedProfileAnonymousResponse) {}
// Retrieves a profile key credential.
//
// This RPC may fail with a `NOT_FOUND` status if the target account was not
// found. It may also fail with an `UNAUTHENTICATED` status if the given
// unidentified access key did not match the target account's unidentified
// access key, or an `INVALID_ARGUMENT` status if the given credential type is invalid.
rpc GetExpiringProfileKeyCredential(GetExpiringProfileKeyCredentialAnonymousRequest) returns (GetExpiringProfileKeyCredentialResponse) {}
rpc GetExpiringProfileKeyCredential(GetExpiringProfileKeyCredentialAnonymousRequest) returns (GetExpiringProfileKeyCredentialAnonymousResponse) {}
}
message SetProfileRequest {
message SetProfileV1Request {
enum AvatarChange {
AVATAR_CHANGE_UNCHANGED = 0;
AVATAR_CHANGE_CLEAR = 1;
AVATAR_CHANGE_UPDATE = 2;
}
// The profile version. Must be set.
string version = 1;
// The ciphertext of a name that users must set on the profile.
bytes name = 2;
bytes name = 1 [(require.exactlySize) = 81, (require.exactlySize) = 285];
// An enum to indicate what change, if any, is made to the avatar with this request.
AvatarChange avatarChange = 3;
AvatarChange avatar_change = 2;
// The ciphertext of an emoji that users can set on their profile.
bytes about_emoji = 4;
bytes about_emoji = 3 [(require.exactlySize) = 0, (require.exactlySize) = 60];
// The ciphertext of a description that users can set on their profile.
bytes about = 5;
// The ciphertext of the MobileCoin wallet ID on the profile.
bytes payment_address = 6;
// A list of badge IDs associated with the profile.
repeated string badge_ids = 7;
bytes about = 4 [(require.exactlySize) = 0, (require.exactlySize) = 156, (require.exactlySize) = 282, (require.exactlySize) = 540];
// The ciphertext of the phone-number sharing setting on the profile. 29-byte encrypted boolean.
bytes phone_number_sharing = 8;
bytes phone_number_sharing = 6 [(require.exactlySize) = 29];
}
message SetProfileRequest {
// The profile version. Required.
bytes version = 1 [(require.exactlySize) = 32];
// The ciphertext of a serialized Profile protobuf. Required.
// 937 max length = 909 plaintext serialization + 28 bytes encryption overhead
bytes data = 2 [(require.nonEmpty) = true, (require.size).max = 937];
// The SHA-256 hash of the Profile ciphertext being replaced.
// This is used an optimistic lock against concurrent changes.
//
// Optional, if this is the initial request to create a version.
bytes expected_current_data_hash = 3 [(require.exactlySize) = 0, (require.exactlySize) = 32];
// The current profile version being updated.
// This is used as an optimistic lock against concurrent changes.
//
// Optional, if there is no current profile version for the account.
bytes expected_current_version = 4 [(require.exactlySize) = 0, (require.exactlySize) = 32];
// The ciphertext of the MobileCoin wallet ID on the profile.
bytes payment_address = 5 [(require.exactlySize) = 0, (require.exactlySize) = 582];
// A list of badge IDs associated with the profile.
repeated string badge_ids = 6;
// The profile key commitment. Used to issue a profile key credential response.
// Must be set on the request.
bytes commitment = 9;
//
// Required during the v1 -> v2 migration period. Afterwards will be optional, if this is an update to an existing version.
bytes commitment = 7 [(require.exactlySize) = 0, (require.exactlySize) = 97];
// An embedded v1 request. Required during the v1 -> v2 migration period.
//
// Because this is a temporary field during the migration, it has the highest
// field number without serialization overhead. This is purely aesthetic.
SetProfileV1Request v1Request = 15 [(require.present) = true];
// next: 8
}
// Indicates that the account is not permitted to set a payment address,
// due to a disallowed country prefix on the account's phone number.
message PaymentsForbiddenInRegion {}
// Indicates that the account does not have the Profiles v2 capability, which
// is required to call Profiles.SetProfile
message ProfilesV2CapabilityRequired {}
message SetProfileResult {
// If the request included a v1 avatar change, this field contains the policy
// and credential used by clients to upload an avatar to the CDN.
//
// Because this is a temporary field during the migration, it has the highest
// field number without serialization overhead. This is purely aesthetic.
optional ProfileAvatarUploadAttributes v1_avatar_upload_form = 15;
// next: 1
}
message SetProfileResponse {
// The policy and credential used by clients to upload an avatar to S3.
ProfileAvatarUploadAttributes attributes = 1;
oneof response {
SetProfileResult result = 1;
errors.FailedPrecondition write_conflict = 2 [(tag.reason) = "write_conflict"];
PaymentsForbiddenInRegion payments_forbidden_in_region = 3 [(tag.reason) = "payments_forbidden_in_region"];
// Because this is a temporary field during the migration, it has the highest
// field number without serialization overhead. This is purely aesthetic.
ProfilesV2CapabilityRequired profiles_v2_capability_required = 15 [(tag.reason) = "profiles_v2_capability_required"];
// next: 4
}
}
message GetVersionedProfileRequest {
// The ACI of the account for which to get profile data.
common.ServiceIdentifier accountIdentifier = 1;
common.ServiceIdentifier accountIdentifier = 1 [(require.present) = true, (require.identityType) = IDENTITY_TYPE_ACI];
// The profile version to retrieve.
string version = 2;
bytes version = 2 [(require.exactlySize) = 32];
// The `data_etag` from the previous request for this Profile version. If
// unchanged, the response will omit `data` and `data_etag_matched` will be
// `true`.
bytes data_etag = 3 [(require.exactlySize) = 0, (require.exactlySize) = 32];
// The `payment_address_etag` from the previous request for this account’s
// profile. If unchanged, the response will omit `payment_address` and
// `payment_address_etag_matched` will be `true`.
bytes payment_address_etag = 4 [(require.exactlySize) = 0, (require.exactlySize) = 32];
}
message GetVersionedProfileAnonymousRequest {
// Contains the data necessary to request a versioned profile.
GetVersionedProfileRequest request = 1;
GetVersionedProfileRequest request = 1 [(require.present) = true];
// The unidentified access key for the targeted account.
bytes unidentified_access_key = 2;
bytes unidentified_access_key = 2 [(require.exactlySize) = 16];
}
message DataEtag {
bytes data = 1;
// An entity tag for `data`. This may be used in subsequent requests for
// this profile version to optimize bandwidth.
bytes etag = 2;
}
message GetVersionedProfileResult {
oneof data_result {
// The ciphertext of a serialized Profile.
// Absent if a v2 Profile is not available
// for this version, in which the client should use `v1_response`.
DataEtag data_etag = 1;
// Indicates that the request’s ETag matched the stored `data`
bool data_etag_matched = 2;
// Will be present if there is no v2 Profile data for this version.
//
// Because this is a temporary field during the migration, it has the highest
// field number without serialization overhead. This is purely aesthetic.
GetVersionedProfileV1Response v1_response = 15;
}
oneof payment_address_result {
// The ciphertext of the MobileCoin wallet ID on the profile.
DataEtag payment_address_data_etag = 3;
// Indicates that the request’s ETag matched the stored `payment_address`
bool payment_address_etag_matched = 4;
}
// next: 5
}
message GetVersionedProfileResponse {
oneof response {
GetVersionedProfileResult result = 1;
errors.NotFound not_found = 2 [(tag.reason) = "not_found"];
}
}
message GetVersionedProfileAnonymousResponse {
oneof response {
GetVersionedProfileResult result = 1;
errors.NotFound not_found = 2 [(tag.reason) = "not_found"];
errors.FailedUnidentifiedAuthorization failed_unidentified_authorization = 3 [(tag.reason) = "failed_unidentified_authorization"];
}
}
message GetVersionedProfileV1Response {
// The ciphertext of the name on the profile.
bytes name = 1;
// The ciphertext of the description on the profile.
bytes about = 2;
// The ciphertext of the emoji on the profile.
bytes about_emoji = 3;
// The S3 path of the avatar on the profile.
// The cdn0 path of the avatar on the profile.
string avatar = 4;
// The ciphertext of the MobileCoin wallet ID on the profile.
bytes payment_address = 5;
// The ciphertext of the phone-number sharing setting on the profile.
bytes phone_number_sharing = 6;
bytes phone_number_sharing = 5;
}
message GetUnversionedProfileRequest {
// The service identifier of the account for which to get profile data.
common.ServiceIdentifier serviceIdentifier = 1;
common.ServiceIdentifier service_identifier = 1 [(require.present) = true];
}
message GetUnversionedProfileAnonymousRequest {
// Contains the data necessary to request an unversioned profile.
GetUnversionedProfileRequest request = 1;
// Note: Only ACI service identifiers are permitted for anonymous requests.
GetUnversionedProfileRequest request = 1 [(require.present) = true];
oneof authentication {
// The unidentified access key for the targeted account.
@@ -159,7 +246,7 @@ message GetUnversionedProfileAnonymousRequest {
}
}
message GetUnversionedProfileResponse {
message GetUnversionedProfileResult {
// The identity key of the targeted account/identity type.
bytes identity_key = 1;
// A checksum of the unidentified access key for the targeted account.
@@ -172,28 +259,61 @@ message GetUnversionedProfileResponse {
repeated Badge badges = 5;
}
message GetUnversionedProfileResponse {
oneof response {
GetUnversionedProfileResult result = 1;
errors.NotFound not_found = 2 [(tag.reason) = "not_found"];
}
}
message GetUnversionedProfileAnonymousResponse {
oneof response {
GetUnversionedProfileResult result = 1;
// The target profile was not found
errors.NotFound not_found = 2 [(tag.reason) = "not_found"];
// The unidentified access key or group send endorsement were not valid for
// the request.
errors.FailedUnidentifiedAuthorization failed_unidentified_authorization = 3 [(tag.reason) = "failed_unidentified_authorization"];
}
}
message GetExpiringProfileKeyCredentialRequest {
// The ACI of the account for which to get a profile key credential.
common.ServiceIdentifier accountIdentifier = 1;
common.ServiceIdentifier account_identifier = 1 [(require.present) = true, (require.identityType) = IDENTITY_TYPE_ACI];
// A zkgroup request for a profile key credential.
bytes credential_request = 2;
bytes credential_request = 2 [(require.nonEmpty) = true];
// The type of credential being requested.
CredentialType credential_type = 3;
CredentialType credential_type = 3 [(require.specified) = true];
// The profile version for which to generate a profile key credential.
string version = 4;
bytes version = 4 [(require.exactlySize) = 32];
}
message GetExpiringProfileKeyCredentialAnonymousRequest {
// Contains the data necessary to request an expiring profile key credential.
GetExpiringProfileKeyCredentialRequest request = 1;
GetExpiringProfileKeyCredentialRequest request = 1 [(require.present) = true];
// The unidentified access key for the targeted account.
bytes unidentified_access_key = 2;
bytes unidentified_access_key = 2 [(require.exactlySize) = 16];
}
message GetExpiringProfileKeyCredentialResult {
// A zkgroup credential used by a client to prove that it has the profile key
// of a targeted account.
bytes profile_key_credential = 1;
}
message GetExpiringProfileKeyCredentialResponse {
// A zkgroup credential used by a client to prove that it has the profile key
// of a targeted account.
bytes profileKeyCredential = 1;
oneof response {
GetExpiringProfileKeyCredentialResult result = 1;
errors.NotFound not_found = 2 [(tag.reason) = "not_found"];
}
}
message GetExpiringProfileKeyCredentialAnonymousResponse {
oneof response {
GetExpiringProfileKeyCredentialResult result = 1;
errors.NotFound not_found = 2 [(tag.reason) = "not_found"];
errors.FailedUnidentifiedAuthorization failed_unidentified_authorization = 3 [(tag.reason) = "failed_unidentified_authorization"];
}
}
message ProfileAvatarUploadAttributes {
@@ -157,11 +157,28 @@ extend google.protobuf.FieldOptions {
* import "org/signal/chat/require.proto";
*
* message Data {
* string myString = 1 [(require.base64url)];
* string myString = 1 [(require.base64url) = true];
* }
* ```
*/
optional bool base64url = 70008;
/*
* Requires a common.ServiceIdentifier field to have its IdentityType
* be the given type (`aci` or `pni`).
*
* ```
* import "org/signal/chat/require.proto";
* import "org/signal/chat/common.proto";
*
* message Data {
* common.ServiceIdentifier accountIdentifier = 1 [(require.identityType) = IDENTITY_TYPE_ACI];
* }
* ```
*/
optional IdentityType identityType = 70009;
// next 70010
}
message SizeConstraint {
@@ -197,3 +214,11 @@ enum Auth {
AUTH_ONLY_ANONYMOUS = 2;
}
// This is duplicated from common.proto because:
// 1. importing would be a circular dependency
// 2. the canonical declaration belongs there
enum IdentityType {
IDENTITY_TYPE_UNSPECIFIED = 0;
IDENTITY_TYPE_ACI = 1;
IDENTITY_TYPE_PNI = 2;
}
@@ -0,0 +1,15 @@
-- Atomically sets v1 and v2 profile cache entries
local v1Key = KEYS[1] -- v1 profile hash key
local v2Key = KEYS[2] -- v2 profile hash key
local v1Field = ARGV[1] -- v1 profile version
local v1Value = ARGV[2] -- v1 profile data
local v2Field = ARGV[3] -- v2 profile version
local v2Value = ARGV[4] -- v2 profile data
if #v1Field > 0 then
redis.call("HSET", v1Key, v1Field, v1Value)
end
if #v2Field > 0 then
redis.call("HSET", v2Key, v2Field, v2Value)
end
@@ -64,6 +64,9 @@ class AccountAuthenticatorTest {
oldAccount = AccountsHelper.generateTestAccount("+14088675311", UUID.fromString("adfce52b-9299-4c25-9c51-412fb420c6a6"), UUID.randomUUID(), List.of(generateTestDevice(oldTime)), null);
AccountsHelper.setupMockUpdate(accountsManager);
AccountsHelper.setupMockGet(accountsManager, acct1);
AccountsHelper.setupMockGet(accountsManager, acct2);
AccountsHelper.setupMockGet(accountsManager, oldAccount);
}
private static Device generateTestDevice(final long lastSeen) {
@@ -81,17 +84,14 @@ class AccountAuthenticatorTest {
final Device device1 = acct1.getDevices().stream().findFirst().orElseThrow();
final Device device2 = acct2.getDevices().stream().findFirst().orElseThrow();
final Account updatedAcct1 = accountAuthenticator.updateLastSeen(acct1, device1);
final Account updatedAcct2 = accountAuthenticator.updateLastSeen(acct2, device2);
accountAuthenticator.updateLastSeen(acct1, device1);
accountAuthenticator.updateLastSeen(acct2, device2);
verify(accountsManager, never()).updateDeviceLastSeen(eq(acct1), any(), anyLong());
verify(accountsManager).updateDeviceLastSeen(eq(acct2), eq(device2), anyLong());
verify(accountsManager, never()).updateDeviceLastSeen(eq(acct1.getIdentifier(IdentityType.ACI)), any(), anyLong());
verify(accountsManager).updateDeviceLastSeen(eq(acct2.getIdentifier(IdentityType.ACI)), eq(device2), anyLong());
assertThat(device1.getLastSeen()).isEqualTo(yesterday);
assertThat(device2.getLastSeen()).isEqualTo(today);
assertThat(acct1).isSameAs(updatedAcct1);
assertThat(acct2).isNotSameAs(updatedAcct2);
}
@Test
@@ -101,17 +101,14 @@ class AccountAuthenticatorTest {
final Device device1 = acct1.getDevices().stream().findFirst().orElseThrow();
final Device device2 = acct2.getDevices().stream().findFirst().orElseThrow();
final Account updatedAcct1 = accountAuthenticator.updateLastSeen(acct1, device1);
final Account updatedAcct2 = accountAuthenticator.updateLastSeen(acct2, device2);
accountAuthenticator.updateLastSeen(acct1, device1);
accountAuthenticator.updateLastSeen(acct2, device2);
verify(accountsManager, never()).updateDeviceLastSeen(eq(acct1), any(), anyLong());
verify(accountsManager, never()).updateDeviceLastSeen(eq(acct2), any(), anyLong());
verify(accountsManager, never()).updateDeviceLastSeen(eq(acct1.getIdentifier(IdentityType.ACI)), any(), anyLong());
verify(accountsManager, never()).updateDeviceLastSeen(eq(acct2.getIdentifier(IdentityType.ACI)), any(), anyLong());
assertThat(device1.getLastSeen()).isEqualTo(yesterday);
assertThat(device2.getLastSeen()).isEqualTo(yesterday);
assertThat(acct1).isSameAs(updatedAcct1);
assertThat(acct2).isSameAs(updatedAcct2);
}
@Test
@@ -121,17 +118,14 @@ class AccountAuthenticatorTest {
final Device device1 = acct1.getDevices().stream().findFirst().orElseThrow();
final Device device2 = acct2.getDevices().stream().findFirst().orElseThrow();
final Account updatedAcct1 = accountAuthenticator.updateLastSeen(acct1, device1);
final Account updatedAcct2 = accountAuthenticator.updateLastSeen(acct2, device2);
accountAuthenticator.updateLastSeen(acct1, device1);
accountAuthenticator.updateLastSeen(acct2, device2);
verify(accountsManager).updateDeviceLastSeen(eq(acct1), eq(device1), anyLong());
verify(accountsManager).updateDeviceLastSeen(eq(acct2), eq(device2), anyLong());
verify(accountsManager).updateDeviceLastSeen(eq(acct1.getIdentifier(IdentityType.ACI)), eq(device1), anyLong());
verify(accountsManager).updateDeviceLastSeen(eq(acct2.getIdentifier(IdentityType.ACI)), eq(device2), anyLong());
assertThat(device1.getLastSeen()).isEqualTo(today);
assertThat(device2.getLastSeen()).isEqualTo(today);
assertThat(updatedAcct1).isNotSameAs(acct1);
assertThat(updatedAcct2).isNotSameAs(acct2);
}
@Test
@@ -142,7 +136,7 @@ class AccountAuthenticatorTest {
accountAuthenticator.updateLastSeen(oldAccount, device);
verify(accountsManager).updateDeviceLastSeen(eq(oldAccount), eq(device), anyLong());
verify(accountsManager).updateDeviceLastSeen(eq(oldAccount.getIdentifier(IdentityType.ACI)), eq(device), anyLong());
assertThat(device.getLastSeen()).isEqualTo(today);
}
@@ -13,6 +13,7 @@ import static org.mockito.Mockito.when;
import jakarta.ws.rs.WebApplicationException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.Optional;
@@ -28,6 +29,7 @@ import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
class OptionalAccessTest {
@@ -51,20 +53,23 @@ class OptionalAccessTest {
}
private static List<Arguments> verify() {
final String unidentifiedAccessKey = RandomStringUtils.secure().nextAlphanumeric(16);
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(16);
final Anonymous correctUakHeader =
new Anonymous(Base64.getEncoder().encodeToString(unidentifiedAccessKey.getBytes()));
new Anonymous(Base64.getEncoder().encodeToString(unidentifiedAccessKey));
final byte[] incorrectUnidentifiedAccessKey = Arrays.copyOf(unidentifiedAccessKey, unidentifiedAccessKey.length);
incorrectUnidentifiedAccessKey[0] = (byte)(incorrectUnidentifiedAccessKey[0]+1);
final Anonymous incorrectUakHeader =
new Anonymous(Base64.getEncoder().encodeToString((unidentifiedAccessKey + "-incorrect").getBytes()));
new Anonymous(Base64.getEncoder().encodeToString(incorrectUnidentifiedAccessKey));
final Account targetAccount = mock(Account.class);
final ServiceIdentifier targetAccountAciIdentifier = new AciServiceIdentifier(UUID.randomUUID());
final ServiceIdentifier targetAccountPniIdentifier = new PniServiceIdentifier(UUID.randomUUID());
when(targetAccount.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(mock(Device.class)));
when(targetAccount.getUnidentifiedAccessKey())
.thenReturn(Optional.of(unidentifiedAccessKey.getBytes(StandardCharsets.UTF_8)));
.thenReturn(Optional.of(unidentifiedAccessKey));
when(targetAccount.isIdentifiedBy(targetAccountAciIdentifier)).thenReturn(true);
when(targetAccount.isIdentifiedBy(targetAccountPniIdentifier)).thenReturn(true);
@@ -84,7 +89,7 @@ class OptionalAccessTest {
final ServiceIdentifier inactiveTargetAccountAciIdentifier = new AciServiceIdentifier(UUID.randomUUID());
when(inactiveTargetAccount.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(mock(Device.class)));
when(inactiveTargetAccount.getUnidentifiedAccessKey())
.thenReturn(Optional.of(unidentifiedAccessKey.getBytes(StandardCharsets.UTF_8)));
.thenReturn(Optional.of(unidentifiedAccessKey));
when(inactiveTargetAccount.isIdentifiedBy(inactiveTargetAccountAciIdentifier)).thenReturn(true);
return List.of(
@@ -0,0 +1,238 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.auth;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
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.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
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.MethodSource;
import org.whispersystems.textsecuregcm.entities.RegistrationServiceSession;
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
import org.whispersystems.textsecuregcm.spam.RegistrationRecoveryChecker;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
class PhoneVerificationTokenManagerTest {
private RegistrationServiceClient registrationServiceClient;
private RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
private RegistrationRecoveryChecker registrationRecoveryChecker;
private PhoneVerificationTokenManager phoneVerificationTokenManager;
private static final String PHONE_NUMBER = PhoneNumberUtil.getInstance()
.format(PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164);
private static final UUID PHONE_NUMBER_IDENTIFIER = UUID.randomUUID();
@BeforeEach
void setUp() {
final PhoneNumberIdentifiers phoneNumberIdentifiers = mock(PhoneNumberIdentifiers.class);
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(PHONE_NUMBER))
.thenReturn(CompletableFuture.completedFuture(PHONE_NUMBER_IDENTIFIER));
registrationServiceClient = mock(RegistrationServiceClient.class);
registrationRecoveryPasswordsManager = mock(RegistrationRecoveryPasswordsManager.class);
registrationRecoveryChecker = mock(RegistrationRecoveryChecker.class);
phoneVerificationTokenManager = new PhoneVerificationTokenManager(phoneNumberIdentifiers,
registrationServiceClient,
registrationRecoveryPasswordsManager,
registrationRecoveryChecker);
}
@Nested
class SessionBasedVerification {
@Test
void verify() {
final byte[] sessionId = TestRandomUtil.nextBytes(16);
when(registrationServiceClient.getSession(eq(sessionId), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.of(
new RegistrationServiceSession(sessionId, PHONE_NUMBER, true, null, null, null, 0))));
assertDoesNotThrow(() -> phoneVerificationTokenManager.verify(mock(ContainerRequestContext.class),
PHONE_NUMBER,
sessionId,
null));
}
@Test
void verifySessionNotFound() {
final byte[] sessionId = TestRandomUtil.nextBytes(16);
when(registrationServiceClient.getSession(eq(sessionId), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.empty()));
assertThrows(NotAuthorizedException.class, () -> phoneVerificationTokenManager.verify(mock(ContainerRequestContext.class),
PHONE_NUMBER,
sessionId,
null));
}
@Test
void verifyNumberMismatch() {
final byte[] sessionId = TestRandomUtil.nextBytes(16);
when(registrationServiceClient.getSession(eq(sessionId), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.of(
new RegistrationServiceSession(sessionId, PHONE_NUMBER + "0", true, null, null, null, 0))));
assertThrows(BadRequestException.class, () -> phoneVerificationTokenManager.verify(mock(ContainerRequestContext.class),
PHONE_NUMBER,
sessionId,
null));
}
@Test
void verifySessionNotVerified() {
final byte[] sessionId = TestRandomUtil.nextBytes(16);
when(registrationServiceClient.getSession(eq(sessionId), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.of(
new RegistrationServiceSession(sessionId, PHONE_NUMBER, false, null, null, null, 0))));
assertThrows(NotAuthorizedException.class, () -> phoneVerificationTokenManager.verify(mock(ContainerRequestContext.class),
PHONE_NUMBER,
sessionId,
null));
}
@ParameterizedTest
@MethodSource
void verifyRegistrationServiceClientException(final Throwable registrationServiceClientException,
final Class<Throwable> expectedExceptionClass) throws ExecutionException, InterruptedException, TimeoutException {
@SuppressWarnings("unchecked") final CompletableFuture<Optional<RegistrationServiceSession>> mockFuture
= mock(CompletableFuture.class);
when(mockFuture.get(anyLong(), any())).thenThrow(registrationServiceClientException);
when(registrationServiceClient.getSession(any(), any())).thenReturn(mockFuture);
assertThrows(expectedExceptionClass, () -> phoneVerificationTokenManager.verify(mock(ContainerRequestContext.class),
PHONE_NUMBER,
TestRandomUtil.nextBytes(16),
null));
}
private static List<Arguments> verifyRegistrationServiceClientException() {
return List.of(
Arguments.arguments(new ExecutionException(Status.INVALID_ARGUMENT.asRuntimeException()), BadRequestException.class),
Arguments.arguments(new ExecutionException(Status.RESOURCE_EXHAUSTED.asRuntimeException()), ServerErrorException.class),
Arguments.arguments(new CancellationException(), ServerErrorException.class),
Arguments.arguments(new TimeoutException(), ServerErrorException.class)
);
}
}
@Nested
class PasswordBasedVerification {
@Test
void verify() {
final ContainerRequestContext containerRequestContext = mock(ContainerRequestContext.class);
final byte[] recoveryPassword = TestRandomUtil.nextBytes(16);
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(containerRequestContext, PHONE_NUMBER))
.thenReturn(true);
when(registrationRecoveryPasswordsManager.verify(PHONE_NUMBER_IDENTIFIER, recoveryPassword))
.thenReturn(CompletableFuture.completedFuture(true));
assertDoesNotThrow(() -> phoneVerificationTokenManager.verify(containerRequestContext,
PHONE_NUMBER,
null,
recoveryPassword));
}
@Test
void verifyRecoveryCheckerDeclined() {
final ContainerRequestContext containerRequestContext = mock(ContainerRequestContext.class);
final byte[] recoveryPassword = TestRandomUtil.nextBytes(16);
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(containerRequestContext, PHONE_NUMBER))
.thenReturn(false);
when(registrationRecoveryPasswordsManager.verify(PHONE_NUMBER_IDENTIFIER, recoveryPassword))
.thenReturn(CompletableFuture.completedFuture(true));
assertThrows(ForbiddenException.class, () -> phoneVerificationTokenManager.verify(containerRequestContext,
PHONE_NUMBER,
null,
recoveryPassword));
}
@Test
void verifyRecoveryPasswordNotVerified() {
final ContainerRequestContext containerRequestContext = mock(ContainerRequestContext.class);
final byte[] recoveryPassword = TestRandomUtil.nextBytes(16);
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(containerRequestContext, PHONE_NUMBER))
.thenReturn(true);
when(registrationRecoveryPasswordsManager.verify(PHONE_NUMBER_IDENTIFIER, recoveryPassword))
.thenReturn(CompletableFuture.completedFuture(false));
assertThrows(ForbiddenException.class, () -> phoneVerificationTokenManager.verify(containerRequestContext,
PHONE_NUMBER,
null,
recoveryPassword));
}
@ParameterizedTest
@MethodSource
void verifyRecoveryPasswordManagerException(final Throwable recoveryPasswordManagerException)
throws ExecutionException, InterruptedException, TimeoutException {
final ContainerRequestContext containerRequestContext = mock(ContainerRequestContext.class);
final byte[] recoveryPassword = TestRandomUtil.nextBytes(16);
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(containerRequestContext, PHONE_NUMBER))
.thenReturn(true);
@SuppressWarnings("unchecked") final CompletableFuture<Boolean> mockFuture = mock(CompletableFuture.class);
when(mockFuture.get(anyLong(), any())).thenThrow(recoveryPasswordManagerException);
when(registrationRecoveryPasswordsManager.verify(PHONE_NUMBER_IDENTIFIER, recoveryPassword))
.thenReturn(mockFuture);
assertThrows(ServerErrorException.class, () -> phoneVerificationTokenManager.verify(containerRequestContext,
PHONE_NUMBER,
null,
recoveryPassword));
}
private static List<Throwable> verifyRecoveryPasswordManagerException() {
return List.of(new ExecutionException(new RuntimeException()), new TimeoutException());
}
}
}
@@ -76,10 +76,14 @@ class RegistrationLockVerificationManagerTest {
AccountsHelper.setupMockUpdate(accountsManager);
account = mock(Account.class);
when(account.getUuid()).thenReturn(UUID.randomUUID());
final UUID accountIdentifier = UUID.randomUUID();
when(account.getUuid()).thenReturn(accountIdentifier);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
when(account.getNumber()).thenReturn("+18005551212");
when(account.getDevices()).thenReturn(List.of(device));
AccountsHelper.setupMockGet(accountsManager, account);
existingRegistrationLock = mock(StoredRegistrationLock.class);
when(account.getRegistrationLock()).thenReturn(existingRegistrationLock);
}
@@ -55,6 +55,7 @@ import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
import org.whispersystems.textsecuregcm.auth.RedemptionRange;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiterConfig;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
@@ -62,6 +63,7 @@ import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
import org.whispersystems.textsecuregcm.tests.util.ExperimentHelper;
import org.whispersystems.textsecuregcm.util.TestClock;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
@@ -110,14 +112,10 @@ public class BackupAuthManagerTest {
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(aci);
when(accountsManager.update(any(), any()))
.thenAnswer(invocation -> {
final Account a = invocation.getArgument(0);
final Consumer<Account> updater = invocation.getArgument(1);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(aci);
updater.accept(a);
return a;
});
AccountsHelper.setupMockGet(accountsManager, account);
AccountsHelper.setupMockUpdate(accountsManager);
final BackupAuthCredentialRequest messagesCredentialRequest = backupAuthTestUtil.getRequest(messagesBackupKey, aci);
final BackupAuthCredentialRequest mediaCredentialRequest = backupAuthTestUtil.getRequest(mediaBackupKey, aci);
@@ -135,7 +133,7 @@ public class BackupAuthManagerTest {
void commitOnAnyBackupLevel(final BackupLevel backupLevel) {
final BackupAuthManager authManager = create();
final Account account = new MockAccountBuilder().backupLevel(backupLevel).build();
when(accountsManager.update(any(), any())).thenReturn(account);
when(accountsManager.update(any(Account.class), any())).thenReturn(account);
final ThrowableAssert.ThrowingCallable commit = () ->
authManager.commitBackupId(account,
@@ -149,7 +147,7 @@ public class BackupAuthManagerTest {
void commitRequiresPrimary() {
final BackupAuthManager authManager = create();
final Account account = new MockAccountBuilder().build();
when(accountsManager.update(any(), any())).thenReturn(account);
when(accountsManager.update(any(Account.class), any())).thenReturn(account);
final ThrowableAssert.ThrowingCallable commit = () ->
authManager.commitBackupId(account,
@@ -306,7 +304,7 @@ public class BackupAuthManagerTest {
.backupVoucher(null)
.build();
when(accountsManager.update(any(), any())).thenReturn(updated);
when(accountsManager.update(any(Account.class), any())).thenReturn(updated);
clock.pin(day2.plus(Duration.ofSeconds(1)));
assertThat(authManager
@@ -316,7 +314,7 @@ public class BackupAuthManagerTest {
@SuppressWarnings("unchecked") final ArgumentCaptor<Consumer<Account>> accountUpdater = ArgumentCaptor.forClass(
Consumer.class);
verify(accountsManager, times(1)).update(any(), accountUpdater.capture());
verify(accountsManager, times(1)).update(any(Account.class), accountUpdater.capture());
// If the account is not expired when we go to update it, we shouldn't wipe it out
final Account alreadyUpdated = mock(Account.class);
@@ -341,11 +339,11 @@ public class BackupAuthManagerTest {
.mediaCredential(Optional.of(new byte[0]))
.build();
clock.pin(Instant.EPOCH.plus(Duration.ofDays(1)));
when(accountsManager.update(any(), any())).thenReturn(account);
when(accountsManager.update(any(Account.class), any())).thenReturn(account);
when(redeemedReceiptsManager.put(any(), eq(expirationTime.getEpochSecond()), eq(201L), eq(aci)))
.thenReturn(CompletableFuture.completedFuture(true));
authManager.redeemReceipt(account, receiptPresentation(201, expirationTime));
verify(accountsManager, times(1)).update(any(), any());
verify(accountsManager, times(1)).update(any(Account.class), any());
}
@Test
@@ -375,13 +373,13 @@ public class BackupAuthManagerTest {
.build();
clock.pin(Instant.EPOCH.plus(Duration.ofDays(1)));
when(accountsManager.update(any(), any())).thenReturn(account);
when(accountsManager.update(any(Account.class), any())).thenReturn(account);
when(redeemedReceiptsManager.put(any(), eq(newExpirationTime.getEpochSecond()), eq(201L), eq(aci)))
.thenReturn(CompletableFuture.completedFuture(true));
authManager.redeemReceipt(account, receiptPresentation(201, newExpirationTime));
final ArgumentCaptor<Consumer<Account>> updaterCaptor = ArgumentCaptor.captor();
verify(accountsManager, times(1)).update(any(), updaterCaptor.capture());
verify(accountsManager, times(1)).update(any(Account.class), updaterCaptor.capture());
updaterCaptor.getValue().accept(account);
// Should select the voucher with the later expiration time
@@ -430,7 +428,7 @@ public class BackupAuthManagerTest {
.build();
clock.pin(Instant.EPOCH.plus(Duration.ofDays(1)));
when(accountsManager.update(any(), any())).thenReturn(account);
when(accountsManager.update(any(Account.class), any())).thenReturn(account);
when(redeemedReceiptsManager.put(any(), eq(expirationTime.getEpochSecond()), eq(201L), eq(aci)))
.thenReturn(CompletableFuture.completedFuture(false));
@@ -510,7 +508,7 @@ public class BackupAuthManagerTest {
.backupVoucher(backupVoucher)
.build();
when(accountsManager.update(any(), any())).thenReturn(account);
when(accountsManager.update(any(Account.class), any())).thenReturn(account);
final Optional<BackupAuthCredentialRequest> newMessagesCredential = switch (messageChange) {
case MATCH -> Optional.of(storedMessagesCredential);
@@ -36,6 +36,7 @@ import java.security.SecureRandom;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
import java.util.HexFormat;
import java.util.List;
@@ -291,7 +292,7 @@ class AccountControllerTest {
assertThat(response.getStatus()).isEqualTo(204);
verify(AuthHelper.VALID_DEVICE_3_PRIMARY, times(1)).setGcmId(eq("z000"));
verify(accountsManager, times(1)).updateDevice(eq(AuthHelper.VALID_ACCOUNT_3), anyByte(), any());
verify(accountsManager, times(1)).updateDevice(eq(AuthHelper.VALID_UUID_3), anyByte(), any());
}
}
@@ -320,7 +321,7 @@ class AccountControllerTest {
assertThat(response.getStatus()).isEqualTo(204);
verify(AuthHelper.VALID_DEVICE_3_PRIMARY, times(1)).setApnId(eq("first"));
verify(accountsManager, times(1)).updateDevice(eq(AuthHelper.VALID_ACCOUNT_3), anyByte(), any());
verify(accountsManager, times(1)).updateDevice(eq(AuthHelper.VALID_UUID_3), anyByte(), any());
}
}
@@ -404,7 +405,7 @@ class AccountControllerTest {
}
// make sure `update()` works
doReturn(AuthHelper.VALID_ACCOUNT).when(accountsManager).update(any(), any());
doReturn(AuthHelper.VALID_ACCOUNT).when(accountsManager).update(any(UUID.class), any());
try (final Response response =
builder.put(Entity.json(new EncryptedUsername(TestRandomUtil.nextBytes(payloadSize))))) {
@@ -447,7 +448,7 @@ class AccountControllerTest {
}
// make sure `update()` works
doReturn(AuthHelper.VALID_ACCOUNT).when(accountsManager).update(any(), any());
doReturn(AuthHelper.VALID_ACCOUNT).when(accountsManager).update(any(UUID.class), any());
try (final Response delete = builder.delete()) {
assertEquals(expectedStatus, delete.getStatus());
@@ -751,7 +752,7 @@ class AccountControllerTest {
@Test
void testDeleteUsername() {
when(accountsManager.clearUsernameHash(any()))
.thenAnswer(invocation -> invocation.getArgument(0));
.thenAnswer(invocation -> accountsManager.getByAccountIdentifier(invocation.getArgument(0)).orElseThrow());
try (final Response response = resources.getJerseyTest()
.target("/v1/accounts/username_hash/")
@@ -760,7 +761,7 @@ class AccountControllerTest {
.delete()) {
assertThat(response.getStatus()).isEqualTo(204);
verify(accountsManager).clearUsernameHash(AuthHelper.VALID_ACCOUNT);
verify(accountsManager).clearUsernameHash(AuthHelper.VALID_UUID);
}
}
@@ -776,13 +777,40 @@ class AccountControllerTest {
}
}
@ParameterizedTest
@MethodSource
void testSetAccountAttributesUnrestrictedUnidentifiedAccess(final boolean unrestrictedUnidentifiedAccess, final byte[] unidentifiedAccessKey, final int expectedStatus) {
try (final Response response = resources.getJerseyTest()
.target("/v1/accounts/attributes/")
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.json(new AccountAttributes(false, 2222, 3333, null, null, true, null)
.setUnidentifiedAccessKey(unidentifiedAccessKey)
.setUnrestrictedUnidentifiedAccess(unrestrictedUnidentifiedAccess)))) {
assertThat(response.getStatus()).isEqualTo(expectedStatus);
}
}
static Collection<Arguments> testSetAccountAttributesUnrestrictedUnidentifiedAccess() {
return List.of(
Arguments.argumentSet("restricted, non-empty UAK", false, new byte[16], 204),
Arguments.argumentSet("unrestricted, empty UAK", true, new byte[0], 204),
Arguments.argumentSet("restricted, empty UAK", false, new byte[0], 422),
Arguments.argumentSet("unrestricted, non-empty UAK", true, new byte[16], 204)
);
}
@Test
void testSetAccountAttributesNoDiscoverabilityChange() {
try (final Response response = resources.getJerseyTest()
.target("/v1/accounts/attributes/")
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.json(new AccountAttributes(false, 2222, 3333, null, null, true, null)))) {
.put(Entity.json(new AccountAttributes(false, 2222, 3333, null, null, true, null)
.setUnidentifiedAccessKey(new byte[16])))) {
assertThat(response.getStatus()).isEqualTo(204);
}
@@ -794,7 +822,8 @@ class AccountControllerTest {
.target("/v1/accounts/attributes/")
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getAuthHeader(AuthHelper.UNDISCOVERABLE_UUID, AuthHelper.UNDISCOVERABLE_PASSWORD))
.put(Entity.json(new AccountAttributes(false, 2222, 3333, null, null, true, null)))) {
.put(Entity.json(new AccountAttributes(false, 2222, 3333, null, null, true, null)
.setUnidentifiedAccessKey(new byte[16])))) {
assertThat(response.getStatus()).isEqualTo(204);
}
@@ -811,7 +840,8 @@ class AccountControllerTest {
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getAuthHeader(AuthHelper.UNDISCOVERABLE_UUID, AuthHelper.UNDISCOVERABLE_PASSWORD))
.put(Entity.json(new AccountAttributes(false, 2222, 3333, null, null, true, null)
.withRecoveryPassword(recoveryPassword)))) {
.setUnidentifiedAccessKey(new byte[16])
.setRecoveryPassword(recoveryPassword)))) {
assertThat(response.getStatus()).isEqualTo(204);
verify(registrationRecoveryPasswordsManager).store(AuthHelper.UNDISCOVERABLE_PNI, recoveryPassword);
@@ -824,7 +854,8 @@ class AccountControllerTest {
.target("/v1/accounts/attributes/")
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.json(new AccountAttributes(false, 2222, 3333, null, null, false, null)))) {
.put(Entity.json(new AccountAttributes(false, 2222, 3333, null, null, false, null)
.setUnidentifiedAccessKey(new byte[16])))) {
assertThat(response.getStatus()).isEqualTo(204);
}
@@ -837,7 +868,7 @@ class AccountControllerTest {
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.json(new AccountAttributes(false, 2222, 3333, null, null, false, null)
.withUnidentifiedAccessKey(new byte[7])))) {
.setUnidentifiedAccessKey(new byte[7])))) {
assertThat(response.getStatus()).isEqualTo(422);
}
@@ -852,7 +883,7 @@ class AccountControllerTest {
.delete()) {
assertThat(response.getStatus()).isEqualTo(204);
verify(accountsManager).delete(AuthHelper.VALID_ACCOUNT, AccountsManager.DeletionReason.USER_REQUEST);
verify(accountsManager).delete(AuthHelper.VALID_UUID, AccountsManager.DeletionReason.USER_REQUEST);
}
}
@@ -868,7 +899,7 @@ class AccountControllerTest {
.delete()) {
assertThat(response.getStatus()).isEqualTo(500);
verify(accountsManager).delete(AuthHelper.VALID_ACCOUNT, AccountsManager.DeletionReason.USER_REQUEST);
verify(accountsManager).delete(AuthHelper.VALID_UUID, AccountsManager.DeletionReason.USER_REQUEST);
}
}
@@ -1039,7 +1070,7 @@ class AccountControllerTest {
.put(Entity.json(new DeviceName(TestRandomUtil.nextBytes(64))))) {
assertThat(response.getStatus()).isEqualTo(204);
verify(accountsManager).updateDevice(eq(AuthHelper.VALID_ACCOUNT_3), eq(Device.PRIMARY_ID), any());
verify(accountsManager).updateDevice(eq(AuthHelper.VALID_UUID_3), eq(Device.PRIMARY_ID), any());
}
}
@@ -1053,7 +1084,7 @@ class AccountControllerTest {
.put(Entity.json(new DeviceName(TestRandomUtil.nextBytes(64))))) {
assertThat(response.getStatus()).isEqualTo(204);
verify(accountsManager).updateDevice(eq(AuthHelper.VALID_ACCOUNT_3), eq(AuthHelper.VALID_DEVICE_3_LINKED_ID), any());
verify(accountsManager).updateDevice(eq(AuthHelper.VALID_UUID_3), eq(AuthHelper.VALID_DEVICE_3_LINKED_ID), any());
}
}
@@ -1067,7 +1098,7 @@ class AccountControllerTest {
.put(Entity.json(new DeviceName(TestRandomUtil.nextBytes(64))))) {
assertThat(response.getStatus()).isEqualTo(204);
verify(accountsManager).updateDevice(eq(AuthHelper.VALID_ACCOUNT_3), eq(AuthHelper.VALID_DEVICE_3_LINKED_ID), any());
verify(accountsManager).updateDevice(eq(AuthHelper.VALID_UUID_3), eq(AuthHelper.VALID_DEVICE_3_LINKED_ID), any());
}
}
@@ -11,7 +11,6 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
@@ -25,7 +24,10 @@ 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.WebApplicationException;
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;
@@ -44,7 +46,6 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
@@ -57,16 +58,13 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.mockito.stubbing.Answer;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
import org.whispersystems.textsecuregcm.auth.RegistrationLockError;
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.entities.AccountDataReportResponse;
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
@@ -74,23 +72,16 @@ import org.whispersystems.textsecuregcm.entities.ChangeNumberRequest;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.entities.PhoneNumberDiscoverabilityRequest;
import org.whispersystems.textsecuregcm.entities.RegistrationServiceSession;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.mappers.ImpossiblePhoneNumberExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.NonNormalizedPhoneNumberExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
import org.whispersystems.textsecuregcm.spam.RegistrationRecoveryChecker;
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.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
@@ -100,8 +91,6 @@ import org.whispersystems.textsecuregcm.util.Util;
@ExtendWith(DropwizardExtensionsSupport.class)
class AccountControllerV2Test {
private static final long SESSION_EXPIRATION_SECONDS = Duration.ofMinutes(10).toSeconds();
private static final ECKeyPair IDENTITY_KEY_PAIR = ECKeyPair.generate();
private static final IdentityKey IDENTITY_KEY = new IdentityKey(IDENTITY_KEY_PAIR.getPublicKey());
@@ -111,15 +100,6 @@ class AccountControllerV2Test {
private final AccountsManager accountsManager = mock(AccountsManager.class);
private final ChangeNumberManager changeNumberManager = mock(ChangeNumberManager.class);
private final PhoneNumberIdentifiers phoneNumberIdentifiers = mock(PhoneNumberIdentifiers.class);
private final RegistrationServiceClient registrationServiceClient = mock(RegistrationServiceClient.class);
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager = mock(
RegistrationRecoveryPasswordsManager.class);
private final RegistrationLockVerificationManager registrationLockVerificationManager = mock(
RegistrationLockVerificationManager.class);
private final RateLimiters rateLimiters = mock(RateLimiters.class);
private final RateLimiter registrationLimiter = mock(RateLimiter.class);
private final RegistrationRecoveryChecker registrationRecoveryChecker = mock(RegistrationRecoveryChecker.class);
private final ResourceExtension resources = ResourceExtension.builder()
.addProperty(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE)
@@ -130,11 +110,7 @@ class AccountControllerV2Test {
.addProvider(new NonNormalizedPhoneNumberExceptionMapper())
.setMapper(SystemMapper.jsonMapper())
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
.addResource(
new AccountControllerV2(accountsManager, changeNumberManager,
new PhoneVerificationTokenManager(phoneNumberIdentifiers, registrationServiceClient,
registrationRecoveryPasswordsManager, registrationRecoveryChecker),
registrationLockVerificationManager, rateLimiters))
.addResource(new AccountControllerV2(accountsManager, changeNumberManager))
.build();
@Nested
@@ -142,17 +118,18 @@ class AccountControllerV2Test {
@BeforeEach
void setUp() throws Exception {
when(rateLimiters.getRegistrationLimiter()).thenReturn(registrationLimiter);
reset(changeNumberManager);
when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID)).thenReturn(Optional.of(AuthHelper.VALID_ACCOUNT));
when(changeNumberManager.changeNumber(any(), any(), any(), any(), any(), any(), any(), any())).thenAnswer(
when(changeNumberManager.changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any())).thenAnswer(
(Answer<Account>) invocation -> {
final Account account = invocation.getArgument(0);
final String number = invocation.getArgument(1);
final IdentityKey pniIdentityKey = invocation.getArgument(2);
final UUID uuid = invocation.getArgument(0);
final Account account = accountsManager.getByAccountIdentifier(uuid).orElseThrow();
final String number = invocation.getArgument(4);
final IdentityKey pniIdentityKey = invocation.getArgument(5);
final UUID uuid = account.getUuid();
final List<Device> devices = account.getDevices();
final Account updatedAccount = mock(Account.class);
@@ -175,13 +152,11 @@ class AccountControllerV2Test {
});
}
@Test
void changeNumberSuccess() throws Exception {
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(new RegistrationServiceSession(new byte[16], NEW_NUMBER, true, null, null, null,
SESSION_EXPIRATION_SECONDS))));
@ParameterizedTest
@ValueSource(booleans = {true, false})
void changeNumberSuccess(final boolean useSessionVerification) throws Exception {
@Nullable final String sessionId = useSessionVerification ? encodeSessionId("session") : null;
@Nullable final byte[] recoveryPassword = useSessionVerification ? null : "recovery-password".getBytes(StandardCharsets.UTF_8);
final AccountIdentityResponse accountIdentityResponse =
resources.getJerseyTest()
@@ -190,45 +165,21 @@ class AccountControllerV2Test {
.header(HttpHeaders.AUTHORIZATION,
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.entity(
new ChangeNumberRequest(encodeSessionId("session"), null, NEW_NUMBER, "123", IDENTITY_KEY,
new ChangeNumberRequest(sessionId, recoveryPassword, NEW_NUMBER, "123", IDENTITY_KEY,
Collections.emptyList(),
Map.of(Device.PRIMARY_ID, KeysHelper.signedECPreKey(1, IDENTITY_KEY_PAIR)),
Map.of(Device.PRIMARY_ID, KeysHelper.signedKEMPreKey(2, IDENTITY_KEY_PAIR)),
Map.of(Device.PRIMARY_ID, 17)),
MediaType.APPLICATION_JSON_TYPE), AccountIdentityResponse.class);
verify(changeNumberManager).changeNumber(eq(AuthHelper.VALID_ACCOUNT), eq(NEW_NUMBER), any(), any(), any(),
any(), any(), any());
verify(changeNumberManager).changeNumber(eq(AuthHelper.VALID_UUID), any(), any(), any(), eq(NEW_NUMBER), any(),
any(), any(), any(), any(), any());
assertEquals(AuthHelper.VALID_UUID, accountIdentityResponse.uuid());
assertEquals(NEW_NUMBER, accountIdentityResponse.number());
assertNotEquals(AuthHelper.VALID_PNI, accountIdentityResponse.pni());
}
@Test
void changeNumberSameNumber() throws Exception {
final AccountIdentityResponse accountIdentityResponse =
resources.getJerseyTest()
.target("/v2/accounts/number")
.request()
.header(HttpHeaders.AUTHORIZATION,
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.entity(
new ChangeNumberRequest(encodeSessionId("session"), null, AuthHelper.VALID_NUMBER, null, IDENTITY_KEY,
Collections.emptyList(),
Map.of(Device.PRIMARY_ID, KeysHelper.signedECPreKey(1, IDENTITY_KEY_PAIR)),
Map.of(Device.PRIMARY_ID, KeysHelper.signedKEMPreKey(2, IDENTITY_KEY_PAIR)),
Map.of(Device.PRIMARY_ID, 17)),
MediaType.APPLICATION_JSON_TYPE), AccountIdentityResponse.class);
verify(changeNumberManager).changeNumber(eq(AuthHelper.VALID_ACCOUNT), eq(AuthHelper.VALID_NUMBER), any(), any(), any(),
any(), any(), any());
assertEquals(AuthHelper.VALID_UUID, accountIdentityResponse.uuid());
assertEquals(AuthHelper.VALID_NUMBER, accountIdentityResponse.number());
assertEquals(AuthHelper.VALID_PNI, accountIdentityResponse.pni());
}
@Test
void changeNumberNonNormalizedNumber() {
try (Response response = resources.getJerseyTest()
@@ -295,10 +246,6 @@ class AccountControllerV2Test {
@ParameterizedTest
@MethodSource
void invalidRegistrationId(final Integer pniRegistrationId, final int expectedStatusCode) {
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(new RegistrationServiceSession(new byte[16], NEW_NUMBER, true, null, null, null,
SESSION_EXPIRATION_SECONDS))));
final ChangeNumberRequest changeNumberRequest = new ChangeNumberRequest(encodeSessionId("session"), null, NEW_NUMBER, "123", IDENTITY_KEY,
Collections.emptyList(),
Map.of(Device.PRIMARY_ID, KeysHelper.signedECPreKey(1, IDENTITY_KEY_PAIR)),
@@ -329,183 +276,50 @@ class AccountControllerV2Test {
@Test
void rateLimitedNumber() throws Exception {
doThrow(new RateLimitExceededException(null))
.when(registrationLimiter).validate(anyString());
.when(changeNumberManager).changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
final Invocation.Builder request = resources.getJerseyTest()
.target("/v2/accounts/number")
.request()
.header(HttpHeaders.AUTHORIZATION,
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD));
try (Response response = request.put(Entity.json(requestJson("sessionId", NEW_NUMBER)))) {
assertEquals(429, response.getStatus());
}
}
@Test
void registrationServiceTimeout() {
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.failedFuture(new RuntimeException()));
final Invocation.Builder request = resources.getJerseyTest()
.target("/v2/accounts/number")
.request()
.header(HttpHeaders.AUTHORIZATION,
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD));
try (Response response = request.put(Entity.json(requestJson("sessionId", NEW_NUMBER)))) {
assertEquals(HttpStatus.SC_SERVICE_UNAVAILABLE, response.getStatus());
}
}
@ParameterizedTest
@MethodSource
void registrationServiceSessionCheck(@Nullable final RegistrationServiceSession session, final int expectedStatus,
final String message) {
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.ofNullable(session)));
void phoneVerificationException(final Exception exception, final int expectedStatus)
throws InterruptedException, MessageTooLargeException, MismatchedDevicesException, RateLimitExceededException {
doThrow(exception)
.when(changeNumberManager).changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
final Invocation.Builder request = resources.getJerseyTest()
.target("/v2/accounts/number")
.request()
.header(HttpHeaders.AUTHORIZATION,
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD));
try (Response response = request.put(Entity.json(requestJson("sessionId", NEW_NUMBER)))) {
assertEquals(expectedStatus, response.getStatus(), message);
assertEquals(expectedStatus, response.getStatus());
}
}
static Stream<Arguments> registrationServiceSessionCheck() {
return Stream.of(
Arguments.of(null, 401, "session not found"),
Arguments.of(new RegistrationServiceSession(new byte[16], "+18005551234", false, null, null, null,
SESSION_EXPIRATION_SECONDS), 400,
"session number mismatch"),
Arguments.of(
new RegistrationServiceSession(new byte[16], NEW_NUMBER, false, null, null, null,
SESSION_EXPIRATION_SECONDS),
401,
"session not verified")
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)
);
}
@ParameterizedTest
@EnumSource(RegistrationLockError.class)
void registrationLock(final RegistrationLockError error) throws Exception {
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(
CompletableFuture.completedFuture(
Optional.of(new RegistrationServiceSession(new byte[16], NEW_NUMBER, true, null, null, null,
SESSION_EXPIRATION_SECONDS))));
when(accountsManager.getByE164(any())).thenReturn(Optional.of(mock(Account.class)));
final Exception e = switch (error) {
case MISMATCH -> new WebApplicationException(error.getExpectedStatus());
case RATE_LIMITED -> new RateLimitExceededException(null);
};
doThrow(e)
.when(registrationLockVerificationManager).verifyRegistrationLock(any(), any(), any(), any(), any());
final Invocation.Builder request = resources.getJerseyTest()
.target("/v2/accounts/number")
.request()
.header(HttpHeaders.AUTHORIZATION,
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD));
try (Response response = request.put(Entity.json(requestJson("sessionId", NEW_NUMBER)))) {
assertEquals(error.getExpectedStatus(), response.getStatus());
}
}
@Test
void recoveryPasswordManagerVerificationTrue() throws Exception {
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(any()))
.thenReturn(CompletableFuture.completedFuture(UUID.randomUUID()));
when(registrationRecoveryPasswordsManager.verify(any(), any()))
.thenReturn(CompletableFuture.completedFuture(true));
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(any(), any()))
.thenReturn(true);
final Invocation.Builder request = resources.getJerseyTest()
.target("/v2/accounts/number")
.request()
.header(HttpHeaders.AUTHORIZATION,
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD));
final byte[] recoveryPassword = new byte[32];
try (Response response = request.put(Entity.json(requestJsonRecoveryPassword(recoveryPassword, NEW_NUMBER)))) {
assertEquals(200, response.getStatus());
final AccountIdentityResponse accountIdentityResponse = response.readEntity(AccountIdentityResponse.class);
verify(changeNumberManager).changeNumber(eq(AuthHelper.VALID_ACCOUNT), eq(NEW_NUMBER), any(), any(), any(),
any(), any(), any());
assertEquals(AuthHelper.VALID_UUID, accountIdentityResponse.uuid());
assertEquals(NEW_NUMBER, accountIdentityResponse.number());
assertNotEquals(AuthHelper.VALID_PNI, accountIdentityResponse.pni());
}
}
@Test
void recoveryPasswordManagerVerificationFalse() {
when(registrationRecoveryPasswordsManager.verify(any(), any()))
.thenReturn(CompletableFuture.completedFuture(false));
final Invocation.Builder request = resources.getJerseyTest()
.target("/v2/accounts/number")
.request()
.header(HttpHeaders.AUTHORIZATION,
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD));
try (Response response = request.put(Entity.json(requestJsonRecoveryPassword(new byte[32], NEW_NUMBER)))) {
assertEquals(403, response.getStatus());
}
}
@Test
void registrationRecoveryCheckerAllowsAttempt() {
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(any()))
.thenReturn(CompletableFuture.completedFuture(UUID.randomUUID()));
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(any(), any())).thenReturn(true);
when(registrationRecoveryPasswordsManager.verify(any(), any()))
.thenReturn(CompletableFuture.completedFuture(true));
final Invocation.Builder request = resources.getJerseyTest()
.target("/v2/accounts/number")
.request()
.header(HttpHeaders.AUTHORIZATION,
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD));
final byte[] recoveryPassword = new byte[32];
try (Response response = request.put(Entity.json(requestJsonRecoveryPassword(recoveryPassword, NEW_NUMBER)))) {
assertEquals(200, response.getStatus());
}
}
@Test
void registrationRecoveryCheckerDisallowsAttempt() {
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(any(), any())).thenReturn(false);
when(registrationRecoveryPasswordsManager.verify(any(), any()))
.thenReturn(CompletableFuture.completedFuture(true));
final Invocation.Builder request = resources.getJerseyTest()
.target("/v2/accounts/number")
.request()
.header(HttpHeaders.AUTHORIZATION,
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD));
final byte[] recoveryPassword = new byte[32];
try (Response response = request.put(Entity.json(requestJsonRecoveryPassword(recoveryPassword, NEW_NUMBER)))) {
assertEquals(403, response.getStatus());
}
}
@Test
void deviceMessageTooLarge() throws Exception {
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(new RegistrationServiceSession(new byte[16], NEW_NUMBER, true, null, null, null,
SESSION_EXPIRATION_SECONDS))));
reset(changeNumberManager);
when(changeNumberManager.changeNumber(any(), any(), any(), any(), any(), any(), any(), any()))
.thenThrow(MessageTooLargeException.class);
doThrow(MessageTooLargeException.class)
.when(changeNumberManager).changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
try (final Response response = resources.getJerseyTest()
.target("/v2/accounts/number")
@@ -22,6 +22,7 @@ import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collection;
import java.util.List;
@@ -46,6 +47,7 @@ import org.signal.libsignal.zkgroup.auth.ServerZkAuthOperations;
import org.signal.libsignal.zkgroup.calllinks.CallLinkAuthCredentialResponse;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.entities.DeliveryCertificate;
import org.whispersystems.textsecuregcm.entities.GroupCredentials;
import org.whispersystems.textsecuregcm.entities.MessageProtos.SenderCertificate;
@@ -214,7 +216,9 @@ class CertificateControllerTest {
Response response = resources.getJerseyTest()
.target("/v1/certificate/delivery")
.request()
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, AuthHelper.getUnidentifiedAccessHeader("1234".getBytes()))
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY,
AuthHelper.getUnidentifiedAccessHeader(
Arrays.copyOf("1234".getBytes(), UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH)))
.get();
assertEquals(401, response.getStatus());
@@ -30,14 +30,10 @@ import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Base64;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
@@ -62,9 +58,9 @@ import org.mockito.ArgumentCaptor;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.entities.ApnRegistrationId;
import org.whispersystems.textsecuregcm.entities.DeviceActivationRequest;
import org.whispersystems.textsecuregcm.entities.DeviceAttributes;
import org.whispersystems.textsecuregcm.entities.DeviceInfo;
import org.whispersystems.textsecuregcm.entities.DeviceInfoList;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
@@ -111,7 +107,6 @@ class DeviceControllerTest {
private static final Account account = mock(Account.class);
private static final Account maxedAccount = mock(Account.class);
private static final Device primaryDevice = mock(Device.class);
private static final Map<String, Integer> deviceConfiguration = new HashMap<>();
private static final TestClock testClock = TestClock.now();
private static final byte NEXT_DEVICE_ID = 42;
@@ -119,8 +114,7 @@ class DeviceControllerTest {
private static final DeviceController deviceController = new DeviceController(
accountsManager,
rateLimiters,
persistentTimer,
deviceConfiguration);
persistentTimer);
private static final ResourceExtension resources = ResourceExtension.builder()
.addProperty(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE)
@@ -145,7 +139,9 @@ class DeviceControllerTest {
when(account.getNextDeviceId()).thenReturn(NEXT_DEVICE_ID);
when(account.getNumber()).thenReturn(AuthHelper.VALID_NUMBER);
when(account.getUuid()).thenReturn(AuthHelper.VALID_UUID);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(AuthHelper.VALID_UUID);
when(account.getPhoneNumberIdentifier()).thenReturn(AuthHelper.VALID_PNI);
when(account.getIdentifier(IdentityType.PNI)).thenReturn(AuthHelper.VALID_PNI);
when(account.getPrimaryDevice()).thenReturn(primaryDevice);
when(account.getDevice(anyByte())).thenReturn(Optional.empty());
when(account.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(primaryDevice));
@@ -248,7 +244,7 @@ class DeviceControllerTest {
when(accountsManager.checkDeviceLinkingToken(anyString())).thenReturn(Optional.of(AuthHelper.VALID_UUID));
when(accountsManager.addDevice(any(), any(), any())).thenAnswer(invocation -> {
final Account a = invocation.getArgument(0);
final Account a = accountsManager.getByAccountIdentifier(invocation.getArgument(0)).orElseThrow();
final DeviceSpec deviceSpec = invocation.getArgument(1);
return new Pair<>(a, deviceSpec.toDevice(NEXT_DEVICE_ID, testClock, aciIdentityKey));
@@ -256,11 +252,11 @@ class DeviceControllerTest {
when(asyncCommands.set(any(), any(), any())).thenReturn(MockRedisFuture.completedFuture(null));
final AccountAttributes accountAttributes = new AccountAttributes(fetchesMessages, 1234, 5678, null,
null, true, DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES);
final DeviceAttributes deviceAttributes = new DeviceAttributes(fetchesMessages, 1234, 5678, null,
DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES);
final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token",
accountAttributes,
deviceAttributes,
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, apnRegistrationId, gcmRegistrationId));
final LinkDeviceResponse response = resources.getJerseyTest()
@@ -272,7 +268,7 @@ class DeviceControllerTest {
assertThat(response.deviceId()).isEqualTo(NEXT_DEVICE_ID);
final ArgumentCaptor<DeviceSpec> deviceSpecCaptor = ArgumentCaptor.forClass(DeviceSpec.class);
verify(accountsManager).addDevice(eq(account), deviceSpecCaptor.capture(), any());
verify(accountsManager).addDevice(eq(AuthHelper.VALID_UUID), deviceSpecCaptor.capture(), any());
final Device device = deviceSpecCaptor.getValue().toDevice(NEXT_DEVICE_ID, testClock, aciIdentityKey);
@@ -339,7 +335,7 @@ class DeviceControllerTest {
}
final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token",
new AccountAttributes(false, 1234, 5678, null, null, true, requestCapabilities),
new DeviceAttributes(false, 1234, 5678, null, requestCapabilities),
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.of(new GcmRegistrationId("gcm-id"))));
final int expectedStatus =
@@ -392,7 +388,7 @@ class DeviceControllerTest {
.collect(Collectors.toSet());
final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token",
new AccountAttributes(false, 1234, 5678, null, null, true, requestCapabilities),
new DeviceAttributes(false, 1234, 5678, null, requestCapabilities),
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.of(new GcmRegistrationId("gcm-id"))));
try (final Response response = resources.getJerseyTest()
@@ -430,7 +426,7 @@ class DeviceControllerTest {
when(account.getIdentityKey(IdentityType.PNI)).thenReturn(new IdentityKey(pniIdentityKeyPair.getPublicKey()));
final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token",
new AccountAttributes(false, 1234, 5678, null, null, true, null),
new DeviceAttributes(false, 1234, 5678, null, null),
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.of(new GcmRegistrationId("gcm-id"))));
try (final Response response = resources.getJerseyTest()
@@ -472,11 +468,11 @@ class DeviceControllerTest {
when(asyncCommands.set(any(), any(), any())).thenReturn(MockRedisFuture.completedFuture(null));
final AccountAttributes accountAttributes = new AccountAttributes(true, 1234, 5678, null,
null, true, DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES);
final DeviceAttributes deviceAttributes = new DeviceAttributes(true, 1234, 5678, null,
DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES);
final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token",
accountAttributes,
deviceAttributes,
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.empty()));
try (final Response response = resources.getJerseyTest()
@@ -517,7 +513,7 @@ class DeviceControllerTest {
when(commands.get(anyString())).thenReturn("");
final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token",
new AccountAttributes(false, 1234, 5678, null, null, true, null),
new DeviceAttributes(false, 1234, 5678, null, null),
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.of(new GcmRegistrationId("gcm-id"))));
try (final Response response = resources.getJerseyTest()
@@ -566,7 +562,7 @@ class DeviceControllerTest {
when(account.getIdentityKey(IdentityType.PNI)).thenReturn(new IdentityKey(pniIdentityKeyPair.getPublicKey()));
final LinkDeviceRequest request = new LinkDeviceRequest(deviceCode.token(),
new AccountAttributes(fetchesMessages, 1234, 5678, null, null, true, null),
new DeviceAttributes(fetchesMessages, 1234, 5678, null, null),
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, apnRegistrationId, gcmRegistrationId));
try (final Response response = resources.getJerseyTest()
@@ -614,7 +610,7 @@ class DeviceControllerTest {
when(account.getIdentityKey(IdentityType.PNI)).thenReturn(pniIdentityKey);
final LinkDeviceRequest request = new LinkDeviceRequest(deviceCode.token(),
new AccountAttributes(true, 1234, 5678, null, null, true, null),
new DeviceAttributes(true, 1234, 5678, null, null),
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.empty()));
try (final Response response = resources.getJerseyTest()
@@ -674,7 +670,7 @@ class DeviceControllerTest {
when(accountsManager.checkDeviceLinkingToken(anyString())).thenReturn(Optional.of(AuthHelper.VALID_UUID));
final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token",
new AccountAttributes(true, 1234, 5678, null, null, true, null),
new DeviceAttributes(true, 1234, 5678, null, null),
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.empty()));
try (final Response response = resources.getJerseyTest()
@@ -707,7 +703,7 @@ class DeviceControllerTest {
when(accountsManager.checkDeviceLinkingToken(anyString())).thenReturn(Optional.of(AuthHelper.VALID_UUID));
final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token",
new AccountAttributes(true, 1234, 5678, null, null, true, null),
new DeviceAttributes(true, 1234, 5678, null, null),
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.empty()));
try (final Response response = resources.getJerseyTest()
@@ -766,7 +762,7 @@ class DeviceControllerTest {
when(account.getIdentityKey(IdentityType.PNI)).thenReturn(new IdentityKey(pniIdentityKeyPair.getPublicKey()));
final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token",
new AccountAttributes(false, 1234, 5678, TestRandomUtil.nextBytes(512), null, true, null),
new DeviceAttributes(false, 1234, 5678, TestRandomUtil.nextBytes(512), null),
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.of(new GcmRegistrationId("gcm-id"))));
try (final Response response = resources.getJerseyTest()
@@ -800,7 +796,7 @@ class DeviceControllerTest {
when(account.getIdentityKey(IdentityType.PNI)).thenReturn(new IdentityKey(pniIdentityKeyPair.getPublicKey()));
when(accountsManager.addDevice(any(), any(), any())).thenAnswer(invocation -> {
final Account a = invocation.getArgument(0);
final Account a = accountsManager.getByAccountIdentifier(invocation.getArgument(0)).orElseThrow();
final DeviceSpec deviceSpec = invocation.getArgument(1);
return new Pair<>(a, deviceSpec.toDevice(NEXT_DEVICE_ID, testClock, aciIdentityKey));
@@ -811,7 +807,7 @@ class DeviceControllerTest {
when(asyncCommands.set(any(), any(), any())).thenReturn(MockRedisFuture.completedFuture(null));
final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token",
new AccountAttributes(false, registrationId, pniRegistrationId, null, null, true, DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES),
new DeviceAttributes(false, registrationId, pniRegistrationId, null, DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES),
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.of(new ApnRegistrationId("apn")), Optional.empty()));
try (final Response response = resources.getJerseyTest()
@@ -890,7 +886,7 @@ class DeviceControllerTest {
@Test
void maxDevicesTest() throws LinkDeviceTokenAlreadyUsedException {
final List<Device> devices = IntStream.range(0, DeviceController.MAX_DEVICES + 1)
.mapToObj(i -> mock(Device.class))
.mapToObj(_ -> mock(Device.class))
.toList();
when(account.getDevices()).thenReturn(devices);
@@ -943,7 +939,7 @@ class DeviceControllerTest {
final byte deviceId = 2;
when(accountsManager.removeDevice(account, deviceId))
when(accountsManager.removeDevice(AuthHelper.VALID_UUID, deviceId))
.thenReturn(account);
try (final Response response = resources
@@ -957,7 +953,7 @@ class DeviceControllerTest {
assertThat(response.getStatus()).isEqualTo(204);
assertThat(response.hasEntity()).isFalse();
verify(accountsManager).removeDevice(account, deviceId);
verify(accountsManager).removeDevice(AuthHelper.VALID_UUID, deviceId);
}
}
@@ -984,7 +980,7 @@ class DeviceControllerTest {
void removeDeviceBySelf() {
final byte deviceId = 2;
when(accountsManager.removeDevice(AuthHelper.VALID_ACCOUNT_3, deviceId))
when(accountsManager.removeDevice(AuthHelper.VALID_UUID_3, deviceId))
.thenReturn(account);
when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID_3))
@@ -1001,7 +997,7 @@ class DeviceControllerTest {
assertThat(response.getStatus()).isEqualTo(204);
assertThat(response.hasEntity()).isFalse();
verify(accountsManager).removeDevice(AuthHelper.VALID_ACCOUNT_3, deviceId);
verify(accountsManager).removeDevice(AuthHelper.VALID_UUID_3, deviceId);
}
}
@@ -1177,7 +1173,6 @@ class DeviceControllerTest {
void recordTransferArchiveFailed() {
final byte deviceId = Device.PRIMARY_ID + 1;
final int registrationId = 123;
final Instant deviceCreated = Instant.now().truncatedTo(ChronoUnit.MILLIS);
final RemoteAttachmentError transferFailure = new RemoteAttachmentError(RemoteAttachmentError.ErrorType.CONTINUE_WITHOUT_UPLOAD);
when(rateLimiter.validateAsync(AuthHelper.VALID_UUID)).thenReturn(CompletableFuture.completedFuture(null));
@@ -1465,14 +1460,14 @@ class DeviceControllerTest {
@NullSource
@ValueSource(strings = {""})
void linkDeviceMissingVerificationCode(final String verificationCode) {
final AccountAttributes accountAttributes = new AccountAttributes(true, 1234, 5678, null,
null, true, Set.of());
final DeviceAttributes deviceAttributes = new DeviceAttributes(true, 1234, 5678, null,
Set.of());
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
final LinkDeviceRequest request = new LinkDeviceRequest(verificationCode,
accountAttributes,
deviceAttributes,
new DeviceActivationRequest(
KeysHelper.signedECPreKey(1, aciIdentityKeyPair),
KeysHelper.signedECPreKey(2, pniIdentityKeyPair),
@@ -37,6 +37,7 @@ import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
@@ -59,6 +60,7 @@ import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.entities.CheckKeysRequest;
import org.whispersystems.textsecuregcm.entities.ECPreKey;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
@@ -93,20 +95,22 @@ import org.whispersystems.textsecuregcm.util.TestClock;
class KeysControllerTest {
private static final String EXISTS_NUMBER = "+14152222222";
private static final UUID EXISTS_UUID = UUID.randomUUID();
private static final UUID EXISTS_PNI = UUID.randomUUID();
private static final UUID EXISTS_UUID = UUID.randomUUID();
private static final UUID EXISTS_PNI = UUID.randomUUID();
private static final AciServiceIdentifier EXISTS_ACI = new AciServiceIdentifier(EXISTS_UUID);
private static final PniServiceIdentifier EXISTS_PNI_SERVICE_ID = new PniServiceIdentifier(EXISTS_PNI);
private static final byte[] EXISTS_UAK = Arrays.copyOf(
"1337".getBytes(), UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
private static final UUID OTHER_UUID = UUID.randomUUID();
private static final UUID OTHER_UUID = UUID.randomUUID();
private static final AciServiceIdentifier OTHER_ACI = new AciServiceIdentifier(OTHER_UUID);
private static final UUID NOT_EXISTS_UUID = UUID.randomUUID();
private static final UUID NOT_EXISTS_UUID = UUID.randomUUID();
private static final AciServiceIdentifier NOT_EXISTS_ACI = new AciServiceIdentifier(NOT_EXISTS_UUID);
private static final byte SAMPLE_DEVICE_ID = 1;
private static final int SAMPLE_REGISTRATION_ID = 999;
private static final int SAMPLE_REGISTRATION_ID = 999;
private static final int SAMPLE_PNI_REGISTRATION_ID = 1717;
private final ECKeyPair IDENTITY_KEY_PAIR = ECKeyPair.generate();
@@ -218,7 +222,7 @@ class KeysControllerTest {
when(existsAccount.getIdentityKey(IdentityType.ACI)).thenReturn(IDENTITY_KEY);
when(existsAccount.getIdentityKey(IdentityType.PNI)).thenReturn(PNI_IDENTITY_KEY);
when(existsAccount.getNumber()).thenReturn(EXISTS_NUMBER);
when(existsAccount.getUnidentifiedAccessKey()).thenReturn(Optional.of("1337".getBytes()));
when(existsAccount.getUnidentifiedAccessKey()).thenReturn(Optional.of(EXISTS_UAK));
when(accounts.getByServiceIdentifier(any())).thenReturn(Optional.empty());
when(accounts.getByServiceIdentifierAsync(any())).thenReturn(CompletableFuture.completedFuture(Optional.empty()));
@@ -389,7 +393,7 @@ class KeysControllerTest {
.target(String.format("/v2/keys/%s/1", EXISTS_UUID))
.queryParam("pq", "true")
.request()
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, AuthHelper.getUnidentifiedAccessHeader("1337".getBytes()))
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, AuthHelper.getUnidentifiedAccessHeader(EXISTS_UAK))
.get(PreKeyResponse.class);
assertThat(result.getIdentityKey()).isEqualTo(existsAccount.getIdentityKey(IdentityType.ACI));
@@ -448,7 +452,7 @@ class KeysControllerTest {
.header(HeaderUtils.GROUP_SEND_TOKEN, AuthHelper.validGroupSendTokenHeader(serverSecretParams, List.of(authorizedTarget), expiration));
if (includeUak) {
builder = builder.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, AuthHelper.getUnidentifiedAccessHeader("1337".getBytes()));
builder = builder.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, AuthHelper.getUnidentifiedAccessHeader(EXISTS_UAK));
}
Response response = builder.get();
@@ -501,7 +505,7 @@ class KeysControllerTest {
Response result = resources.getJerseyTest()
.target(String.format("/v2/keys/%s/*", EXISTS_UUID))
.request()
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, AuthHelper.getUnidentifiedAccessHeader("1337".getBytes()))
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, AuthHelper.getUnidentifiedAccessHeader(EXISTS_UAK))
.get();
assertThat(result).isNotNull();
@@ -513,7 +517,7 @@ class KeysControllerTest {
Response response = resources.getJerseyTest()
.target(String.format("/v2/keys/%s/1", EXISTS_UUID))
.request()
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, AuthHelper.getUnidentifiedAccessHeader("9999".getBytes()))
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, AuthHelper.getUnidentifiedAccessHeader(Arrays.copyOf("9999".getBytes(), UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH)))
.get();
assertThat(response.getStatus()).isEqualTo(401);
@@ -39,6 +39,7 @@ import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.HexFormat;
@@ -76,6 +77,7 @@ import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequestContext;
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.configuration.BadgeConfiguration;
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
@@ -104,7 +106,7 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.tests.util.ProfileTestHelper;
@@ -195,6 +197,7 @@ class ProfileControllerTest {
when(profileAccount.getIdentityKey(IdentityType.ACI)).thenReturn(ACCOUNT_TWO_IDENTITY_KEY);
when(profileAccount.getIdentityKey(IdentityType.PNI)).thenReturn(ACCOUNT_TWO_PHONE_NUMBER_IDENTITY_KEY);
when(profileAccount.getUuid()).thenReturn(AuthHelper.VALID_UUID_TWO);
when(profileAccount.getIdentifier(IdentityType.ACI)).thenReturn(AuthHelper.VALID_UUID_TWO);
when(profileAccount.getPhoneNumberIdentifier()).thenReturn(AuthHelper.VALID_PNI_TWO);
when(profileAccount.getCurrentProfileVersion()).thenReturn(Optional.empty());
when(profileAccount.getUsernameHash()).thenReturn(Optional.of(USERNAME_HASH));
@@ -205,6 +208,7 @@ class ProfileControllerTest {
capabilitiesAccount = mock(Account.class);
when(capabilitiesAccount.getUuid()).thenReturn(AuthHelper.VALID_UUID);
when(capabilitiesAccount.getIdentifier(IdentityType.ACI)).thenReturn(AuthHelper.VALID_UUID);
when(capabilitiesAccount.getIdentityKey(IdentityType.ACI)).thenReturn(ACCOUNT_IDENTITY_KEY);
when(capabilitiesAccount.getIdentityKey(IdentityType.PNI)).thenReturn(ACCOUNT_PHONE_NUMBER_IDENTITY_KEY);
@@ -228,8 +232,8 @@ class ProfileControllerTest {
final byte[] about = TestRandomUtil.nextBytes(156);
final byte[] phoneNumberSharing = TestRandomUtil.nextBytes(29);
when(profilesManager.get(eq(AuthHelper.VALID_UUID), eq(versionHex("someversion")))).thenReturn(Optional.empty());
when(profilesManager.get(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion")))).thenReturn(Optional.of(new VersionedProfile(
when(profilesManager.getV1(eq(AuthHelper.VALID_UUID), eq(versionHex("someversion")))).thenReturn(Optional.empty());
when(profilesManager.getV1(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion")))).thenReturn(Optional.of(new VersionedProfileV1(
versionHex("validversion"), name, "profiles/validavatar", emoji, about, null, phoneNumberSharing, "validcommitment".getBytes())));
when(profilesManager.deleteAvatar(anyString())).thenReturn(CompletableFuture.completedFuture(null));
@@ -291,7 +295,9 @@ class ProfileControllerTest {
final Response response = resources.getJerseyTest()
.target("/v1/profile/" + AuthHelper.VALID_UUID_TWO)
.request()
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, AuthHelper.getUnidentifiedAccessHeader("incorrect".getBytes()))
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY,
AuthHelper.getUnidentifiedAccessHeader(
Arrays.copyOf("incorrect".getBytes(), UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH)))
.get();
assertThat(response.getStatus()).isEqualTo(401);
@@ -418,7 +424,8 @@ class ProfileControllerTest {
final Response response = resources.getJerseyTest()
.target("/v1/profile/" + AuthHelper.VALID_PNI_TWO)
.request()
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, AuthHelper.getUnidentifiedAccessHeader("incorrect".getBytes()))
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, AuthHelper.getUnidentifiedAccessHeader(
Arrays.copyOf("incorrect".getBytes(), UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH)))
.get();
assertThat(response.getStatus()).isEqualTo(401);
@@ -460,10 +467,10 @@ class ProfileControllerTest {
name, null, null,
null, true, false, Optional.of(List.of()), null), MediaType.APPLICATION_JSON_TYPE), ProfileAvatarUploadAttributes.class);
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID), eq(versionHex("someversion")));
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID), profileArgumentCaptor.capture());
verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID), eq(versionHex("someversion")));
verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID), profileArgumentCaptor.capture());
verifyNoMoreInteractions(profilesManager);
@@ -509,10 +516,10 @@ class ProfileControllerTest {
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.hasEntity()).isFalse();
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("anotherversion")));
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("anotherversion")));
verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verifyNoMoreInteractions(profilesManager);
@@ -539,10 +546,10 @@ class ProfileControllerTest {
name, null, null,
null, true, false, Optional.of(List.of()), null), MediaType.APPLICATION_JSON_TYPE), ProfileAvatarUploadAttributes.class);
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion")));
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion")));
verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(profilesManager, times(1)).deleteAvatar("profiles/validavatar");
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
@@ -568,10 +575,10 @@ class ProfileControllerTest {
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.hasEntity()).isFalse();
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion")));
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion")));
verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(profilesManager, times(1)).deleteAvatar(eq("profiles/validavatar"));
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
@@ -598,10 +605,10 @@ class ProfileControllerTest {
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.hasEntity()).isFalse();
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion")));
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion")));
verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(profilesManager, never()).deleteAvatar(anyString());
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
@@ -626,10 +633,10 @@ class ProfileControllerTest {
null, null,
null, false, true, Optional.of(List.of()), null), MediaType.APPLICATION_JSON_TYPE))) {
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion")));
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion")));
verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(profilesManager, times(1)).deleteAvatar(eq("profiles/validavatar"));
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
@@ -656,10 +663,10 @@ class ProfileControllerTest {
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.hasEntity()).isFalse();
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID), eq(version));
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID), profileArgumentCaptor.capture());
verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID), eq(version));
verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID), profileArgumentCaptor.capture());
verify(profilesManager, never()).deleteAvatar(anyString());
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
@@ -687,10 +694,10 @@ class ProfileControllerTest {
null, null, null, true, false, Optional.of(List.of()), null),
MediaType.APPLICATION_JSON_TYPE), ProfileAvatarUploadAttributes.class);
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq(version));
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(version));
verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(profilesManager, times(1)).deleteAvatar("profiles/validavatar");
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
@@ -724,14 +731,14 @@ class ProfileControllerTest {
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.hasEntity()).isFalse();
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq(version));
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(version));
verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verifyNoMoreInteractions(profilesManager);
final VersionedProfile profile = profileArgumentCaptor.getValue();
final VersionedProfileV1 profile = profileArgumentCaptor.getValue();
assertThat(profile.commitment()).isEqualTo(commitment.serialize());
assertThat(profile.avatar()).isNull();
assertThat(profile.version()).isEqualTo(version);
@@ -764,14 +771,14 @@ class ProfileControllerTest {
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.hasEntity()).isFalse();
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
verify(profilesManager).get(eq(AuthHelper.VALID_UUID_TWO), eq(version));
verify(profilesManager).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(profilesManager).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(version));
verify(profilesManager).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verifyNoMoreInteractions(profilesManager);
final VersionedProfile profile = profileArgumentCaptor.getValue();
final VersionedProfileV1 profile = profileArgumentCaptor.getValue();
assertThat(profile.commitment()).isEqualTo(commitment.serialize());
assertThat(profile.avatar()).isNull();
assertThat(profile.version()).isEqualTo(version);
@@ -806,7 +813,7 @@ class ProfileControllerTest {
assertThat(response.getStatus()).isEqualTo(403);
assertThat(response.hasEntity()).isFalse();
verify(profilesManager, never()).set(any(), any());
verify(profilesManager, never()).setV1(any(), any());
}
}
@@ -824,9 +831,9 @@ class ProfileControllerTest {
clearInvocations(AuthHelper.VALID_ACCOUNT_TWO);
when(profilesManager.get(eq(AuthHelper.VALID_UUID_TWO), any()))
when(profilesManager.getV1(eq(AuthHelper.VALID_UUID_TWO), any()))
.thenReturn(Optional.of(
new VersionedProfile("1", name, null, null, null,
new VersionedProfileV1("1", name, null, null, null,
existingPaymentAddressOnProfile ? TestRandomUtil.nextBytes(582) : null,
phoneNumberSharing,
commitment.serialize())));
@@ -845,14 +852,14 @@ class ProfileControllerTest {
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.hasEntity()).isFalse();
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
verify(profilesManager).get(eq(AuthHelper.VALID_UUID_TWO), eq(version));
verify(profilesManager).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(profilesManager).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(version));
verify(profilesManager).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verifyNoMoreInteractions(profilesManager);
final VersionedProfile profile = profileArgumentCaptor.getValue();
final VersionedProfileV1 profile = profileArgumentCaptor.getValue();
assertThat(profile.commitment()).isEqualTo(commitment.serialize());
assertThat(profile.avatar()).isNull();
assertThat(profile.version()).isEqualTo(version);
@@ -864,7 +871,7 @@ class ProfileControllerTest {
assertThat(response.getStatus()).isEqualTo(403);
assertThat(response.hasEntity()).isFalse();
verify(profilesManager, never()).set(any(), any());
verify(profilesManager, never()).setV1(any(), any());
}
}
}
@@ -888,10 +895,10 @@ class ProfileControllerTest {
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.hasEntity()).isFalse();
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq(version));
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(version));
verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verifyNoMoreInteractions(profilesManager);
@@ -912,7 +919,7 @@ class ProfileControllerTest {
final byte[] phoneNumberSharing = TestRandomUtil.nextBytes(29);
final String version = versionHex("validversion");
when(profilesManager.get(eq(AuthHelper.VALID_UUID_TWO), eq(version))).thenReturn(Optional.of(new VersionedProfile(
when(profilesManager.getV1(eq(AuthHelper.VALID_UUID_TWO), eq(version))).thenReturn(Optional.of(new VersionedProfileV1(
version, name, "profiles/validavatar", emoji, about, null, phoneNumberSharing, "validcommitment".getBytes())));
final VersionedProfileResponse profile = resources.getJerseyTest()
@@ -963,8 +970,8 @@ class ProfileControllerTest {
void testGetProfileReturnsNoPaymentAddressIfCurrentVersionMismatch() {
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
final String version = versionHex("validversion");
when(profilesManager.get(AuthHelper.VALID_UUID_TWO, version)).thenReturn(
Optional.of(new VersionedProfile(null, null, null, null, null, paymentAddress, null, null)));
when(profilesManager.getV1(AuthHelper.VALID_UUID_TWO, version)).thenReturn(
Optional.of(new VersionedProfileV1(version, null, null, null, null, paymentAddress, null, null)));
{
final VersionedProfileResponse profile = resources.getJerseyTest()
@@ -1005,10 +1012,11 @@ class ProfileControllerTest {
void testGetProfileWithExpiringProfileKeyCredentialVersionNotFound() throws VerificationFailedException {
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(AuthHelper.VALID_UUID);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(AuthHelper.VALID_UUID);
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(versionHex("version")));
when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID)).thenReturn(Optional.of(account));
when(profilesManager.get(any(), any())).thenReturn(Optional.empty());
when(profilesManager.getV1(any(), any())).thenReturn(Optional.empty());
final ExpiringProfileKeyCredentialProfileResponse profile = resources.getJerseyTest()
.target(String.format("/v1/profile/%s/%s/%s", AuthHelper.VALID_UUID, versionHex("version-that-does-not-exist"), "credential-request"))
@@ -1203,7 +1211,7 @@ class ProfileControllerTest {
final ProfileKey profileKey = new ProfileKey(profileKeyBytes);
final ProfileKeyCommitment profileKeyCommitment = profileKey.getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID));
final VersionedProfile versionedProfile = mock(VersionedProfile.class);
final VersionedProfileV1 versionedProfile = mock(VersionedProfileV1.class);
when(versionedProfile.commitment()).thenReturn(profileKeyCommitment.serialize());
final ProfileKeyCredentialRequestContext profileKeyCredentialRequestContext =
@@ -1213,6 +1221,7 @@ class ProfileControllerTest {
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(AuthHelper.VALID_UUID);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(AuthHelper.VALID_UUID);
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version));
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(UNIDENTIFIED_ACCESS_KEY));
when(account.isIdentifiedBy(new AciServiceIdentifier(AuthHelper.VALID_UUID))).thenReturn(true);
@@ -1224,7 +1233,7 @@ class ProfileControllerTest {
serverZkProfile.issueExpiringProfileKeyCredential(credentialRequest, new ServiceId.Aci(AuthHelper.VALID_UUID), profileKeyCommitment, expiration);
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(AuthHelper.VALID_UUID))).thenReturn(Optional.of(account));
when(profilesManager.get(AuthHelper.VALID_UUID, version)).thenReturn(Optional.of(versionedProfile));
when(profilesManager.getV1(AuthHelper.VALID_UUID, version)).thenReturn(Optional.of(versionedProfile));
when(zkProfileOperations.issueExpiringProfileKeyCredential(eq(credentialRequest), eq(new ServiceId.Aci(AuthHelper.VALID_UUID)), eq(profileKeyCommitment), any()))
.thenReturn(credentialResponse);
@@ -1270,7 +1279,7 @@ class ProfileControllerTest {
final ProfileKey profileKey = new ProfileKey(profileKeyBytes);
final ProfileKeyCommitment profileKeyCommitment = profileKey.getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID));
final VersionedProfile versionedProfile = mock(VersionedProfile.class);
final VersionedProfileV1 versionedProfile = mock(VersionedProfileV1.class);
when(versionedProfile.commitment()).thenReturn(profileKeyCommitment.serialize());
final ProfileKeyCredentialRequestContext profileKeyCredentialRequestContext =
@@ -1285,7 +1294,7 @@ class ProfileControllerTest {
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version));
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(AuthHelper.VALID_UUID))).thenReturn(Optional.of(account));
when(profilesManager.get(AuthHelper.VALID_UUID, version)).thenReturn(Optional.of(versionedProfile));
when(profilesManager.getV1(AuthHelper.VALID_UUID, version)).thenReturn(Optional.of(versionedProfile));
when(zkProfileOperations.issueExpiringProfileKeyCredential(any(), any(), any(), any()))
.thenThrow(new VerificationFailedException());
@@ -1315,7 +1324,7 @@ class ProfileControllerTest {
final ProfileKey profileKey = new ProfileKey(profileKeyBytes);
final ProfileKeyCommitment profileKeyCommitment = profileKey.getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID));
final VersionedProfile versionedProfile = mock(VersionedProfile.class);
final VersionedProfileV1 versionedProfile = mock(VersionedProfileV1.class);
when(versionedProfile.commitment()).thenReturn(profileKeyCommitment.serialize());
final String avatar = "avatar";
when(versionedProfile.avatar()).thenReturn(avatar);
@@ -1332,7 +1341,7 @@ class ProfileControllerTest {
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(versionHex("the-current-version")));
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(AuthHelper.VALID_UUID))).thenReturn(Optional.of(account));
when(profilesManager.get(AuthHelper.VALID_UUID, version)).thenReturn(Optional.of(versionedProfile));
when(profilesManager.getV1(AuthHelper.VALID_UUID, version)).thenReturn(Optional.of(versionedProfile));
final Response response = resources.getJerseyTest()
.target(String.format("/v1/profile/%s/%s/%s", AuthHelper.VALID_UUID, version,
@@ -6,6 +6,7 @@
package org.whispersystems.textsecuregcm.controllers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
@@ -19,6 +20,10 @@ 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;
@@ -26,7 +31,6 @@ import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.Response;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
@@ -37,7 +41,6 @@ import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.stream.Stream;
import javax.annotation.Nullable;
@@ -68,34 +71,28 @@ import org.whispersystems.textsecuregcm.entities.DeviceActivationRequest;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.GcmRegistrationId;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
import org.whispersystems.textsecuregcm.entities.RegistrationRequest;
import org.whispersystems.textsecuregcm.entities.RegistrationServiceSession;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.mappers.ImpossiblePhoneNumberExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.NonNormalizedPhoneNumberExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
import org.whispersystems.textsecuregcm.spam.RegistrationRecoveryChecker;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.DeviceSpec;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
import org.whispersystems.textsecuregcm.util.MockUtils;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
@ExtendWith(DropwizardExtensionsSupport.class)
class RegistrationControllerTest {
private static final long SESSION_EXPIRATION_SECONDS = Duration.ofMinutes(10).toSeconds();
private static final String NUMBER = PhoneNumberUtil.getInstance().format(
PhoneNumberUtil.getInstance().getExampleNumber("US"),
PhoneNumberUtil.PhoneNumberFormat.E164);
@@ -103,15 +100,11 @@ class RegistrationControllerTest {
private static final String REGLOCK = RandomStringUtils.insecure().nextAlphanumeric(64);
private final AccountsManager accountsManager = mock(AccountsManager.class);
private final PhoneNumberIdentifiers phoneNumberIdentifiers = mock(PhoneNumberIdentifiers.class);
private final RegistrationServiceClient registrationServiceClient = mock(RegistrationServiceClient.class);
private final RegistrationLockVerificationManager registrationLockVerificationManager = mock(
RegistrationLockVerificationManager.class);
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager = mock(
RegistrationRecoveryPasswordsManager.class);
private final RegistrationRecoveryChecker registrationRecoveryChecker = mock(RegistrationRecoveryChecker.class);
private final RegistrationLockVerificationManager registrationLockVerificationManager
= mock(RegistrationLockVerificationManager.class);
private final RateLimiters rateLimiters = mock(RateLimiters.class);
private final RegistrationFraudChecker registrationFraudChecker = mock(RegistrationFraudChecker.class);
private final PhoneVerificationTokenManager phoneVerificationTokenManager = mock(PhoneVerificationTokenManager.class);
private final RateLimiter registrationLimiter = mock(RateLimiter.class);
@@ -122,18 +115,15 @@ class RegistrationControllerTest {
.addProvider(new NonNormalizedPhoneNumberExceptionMapper())
.setMapper(SystemMapper.jsonMapper())
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
.addResource(
new RegistrationController(accountsManager,
new PhoneVerificationTokenManager(phoneNumberIdentifiers, registrationServiceClient,
registrationRecoveryPasswordsManager, registrationRecoveryChecker),
registrationLockVerificationManager, rateLimiters, registrationFraudChecker))
.addResource(new RegistrationController(accountsManager, phoneVerificationTokenManager,
registrationLockVerificationManager, rateLimiters, registrationFraudChecker))
.build();
@BeforeEach
void setUp() {
void setUp() throws InterruptedException {
when(rateLimiters.getRegistrationLimiter()).thenReturn(registrationLimiter);
when(accountsManager.update(any(), any())).thenAnswer(invocation -> {
when(accountsManager.update(any(UUID.class), any())).thenAnswer(invocation -> {
final Account account = invocation.getArgument(0);
final Consumer<Account> accountUpdater = invocation.getArgument(1);
@@ -143,6 +133,15 @@ class RegistrationControllerTest {
});
reset(registrationFraudChecker);
reset(phoneVerificationTokenManager);
when(phoneVerificationTokenManager.verify(any(), any(), any(), any())).thenAnswer(invocation -> {
final byte[] sessionId = invocation.getArgument(2);
return sessionId != null
? PhoneVerificationRequest.VerificationType.SESSION
: PhoneVerificationRequest.VerificationType.RECOVERY_PASSWORD;
});
}
@Test
@@ -175,12 +174,6 @@ class RegistrationControllerTest {
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD));
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(
CompletableFuture.completedFuture(
Optional.of(new RegistrationServiceSession(new byte[16], NUMBER, true, null, null, null,
SESSION_EXPIRATION_SECONDS))));
final Account account = mock(Account.class);
when(account.getPrimaryDevice()).thenReturn(mock(Device.class));
@@ -240,163 +233,36 @@ class RegistrationControllerTest {
}
}
@Test
void registrationServiceTimeout() {
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.failedFuture(new RuntimeException()));
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/registration")
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD));
try (Response response = request.post(Entity.json(requestJson("sessionId")))) {
assertEquals(HttpStatus.SC_SERVICE_UNAVAILABLE, response.getStatus());
}
}
@Test
void recoveryPasswordManagerVerificationFailureOrTimeout() {
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(any()))
.thenReturn(CompletableFuture.completedFuture(UUID.randomUUID()));
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(any(), any())).thenReturn(true);
when(registrationRecoveryPasswordsManager.verify(any(), any()))
.thenReturn(CompletableFuture.failedFuture(new RuntimeException()));
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/registration")
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD));
try (Response response = request.post(Entity.json(requestJsonRecoveryPassword(new byte[32])))) {
assertEquals(HttpStatus.SC_SERVICE_UNAVAILABLE, response.getStatus());
}
}
@ParameterizedTest
@MethodSource
void registrationServiceSessionCheck(@Nullable final RegistrationServiceSession session, final int expectedStatus,
final String message) {
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.ofNullable(session)));
void phoneVerificationException(final Exception exception, final int expectedStatus) throws InterruptedException {
doThrow(exception)
.when(phoneVerificationTokenManager).verify(any(), any(), any(), any());
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/registration")
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD));
try (Response response = request.post(Entity.json(requestJson("sessionId")))) {
assertEquals(expectedStatus, response.getStatus(), message);
assertEquals(expectedStatus, response.getStatus());
}
}
static Stream<Arguments> registrationServiceSessionCheck() {
return Stream.of(
Arguments.of(null, 401, "session not found"),
Arguments.of(
new RegistrationServiceSession(new byte[16], "+18005551234", false, null, null, null,
SESSION_EXPIRATION_SECONDS),
400,
"session number mismatch"),
Arguments.of(
new RegistrationServiceSession(new byte[16], NUMBER, false, null, null, null, SESSION_EXPIRATION_SECONDS),
401,
"session not verified")
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)
);
}
@Test
void recoveryPasswordManagerVerificationTrue() throws InterruptedException {
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(any()))
.thenReturn(CompletableFuture.completedFuture(UUID.randomUUID()));
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(any(), any())).thenReturn(true);
when(registrationRecoveryPasswordsManager.verify(any(), any()))
.thenReturn(CompletableFuture.completedFuture(true));
final Account account = mock(Account.class);
when(account.getPrimaryDevice()).thenReturn(mock(Device.class));
when(accountsManager.create(any(), any(), any(), any(), any(), any(), any()))
.thenReturn(account);
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/registration")
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD));
final byte[] recoveryPassword = new byte[32];
try (Response response = request.post(Entity.json(requestJsonRecoveryPassword(recoveryPassword)))) {
assertEquals(200, response.getStatus());
}
}
@Test
void recoveryPasswordManagerVerificationFalse() {
when(registrationRecoveryPasswordsManager.verify(any(), any()))
.thenReturn(CompletableFuture.completedFuture(false));
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/registration")
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD));
try (Response response = request.post(Entity.json(requestJsonRecoveryPassword(new byte[32])))) {
assertEquals(403, response.getStatus());
}
}
@Test
void registrationRecoveryCheckerAllowsAttempt() throws InterruptedException {
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(any()))
.thenReturn(CompletableFuture.completedFuture(UUID.randomUUID()));
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(any(), any())).thenReturn(true);
when(registrationRecoveryPasswordsManager.verify(any(), any()))
.thenReturn(CompletableFuture.completedFuture(true));
final Account account = mock(Account.class);
when(account.getPrimaryDevice()).thenReturn(mock(Device.class));
when(accountsManager.create(any(), any(), any(), any(), any(), any(), any()))
.thenReturn(account);
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/registration")
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD));
final byte[] recoveryPassword = new byte[32];
try (Response response = request.post(Entity.json(requestJsonRecoveryPassword(recoveryPassword)))) {
assertEquals(200, response.getStatus());
}
}
@Test
void registrationRecoveryCheckerDisallowsAttempt() throws InterruptedException {
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(any(), any())).thenReturn(false);
when(registrationRecoveryPasswordsManager.verify(any(), any()))
.thenReturn(CompletableFuture.completedFuture(true));
final Account account = mock(Account.class);
when(account.getPrimaryDevice()).thenReturn(mock(Device.class));
when(accountsManager.create(any(), any(), any(), any(), any(), any(), any()))
.thenReturn(account);
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/registration")
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD));
final byte[] recoveryPassword = new byte[32];
try (Response response = request.post(Entity.json(requestJsonRecoveryPassword(recoveryPassword)))) {
assertEquals(403, response.getStatus());
}
}
@CartesianTest
@CartesianTest.MethodFactory("registrationLockAndDeviceTransfer")
void registrationLockAndDeviceTransfer(
final boolean deviceTransferSupported,
@Nullable final RegistrationLockError error)
throws Exception {
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(
CompletableFuture.completedFuture(
Optional.of(new RegistrationServiceSession(new byte[16], NUMBER, true, null, null, null,
SESSION_EXPIRATION_SECONDS))));
@Nullable final RegistrationLockError error) throws Exception {
final Account account = mock(Account.class);
when(accountsManager.getByE164(any())).thenReturn(Optional.of(account));
@@ -447,16 +313,11 @@ class RegistrationControllerTest {
.format(PhoneNumberUtil.getInstance().getExampleNumber("BJ"), PhoneNumberUtil.PhoneNumberFormat.E164);
final String oldFormatBeninNumber = newFormatBeninNumber.replaceFirst("01", "");
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(
CompletableFuture.completedFuture(
Optional.of(new RegistrationServiceSession(new byte[16], newFormatBeninNumber, true, null, null, null,
SESSION_EXPIRATION_SECONDS))));
assertNotEquals(newFormatBeninNumber, oldFormatBeninNumber);
final Account account = mock(Account.class);
when(accountsManager.getByE164(oldFormatBeninNumber)).thenReturn(Optional.of(account));
when(accountsManager.getByE164(newFormatBeninNumber)).thenReturn(Optional.empty());
when(account.hasCapability(DeviceCapability.TRANSFER)).thenReturn(false);
doThrow(new WebApplicationException(RegistrationLockError.MISMATCH.getExpectedStatus()))
.when(registrationLockVerificationManager).verifyRegistrationLock(any(), any(), any(), any(), any());
@@ -465,13 +326,12 @@ class RegistrationControllerTest {
.target("/v1/registration")
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(newFormatBeninNumber, PASSWORD));
try (final Response response = request.post(Entity.json(requestJson("sessionId")))) {
assertEquals(RegistrationLockError.MISMATCH.getExpectedStatus(), response.getStatus());
}
}
@ParameterizedTest
@CsvSource({
"false, false, false, 200",
@@ -482,11 +342,6 @@ class RegistrationControllerTest {
})
void deviceTransferAvailable(final boolean existingAccount, final boolean transferSupported,
final boolean skipDeviceTransfer, final int expectedStatus) throws Exception {
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(
CompletableFuture.completedFuture(
Optional.of(new RegistrationServiceSession(new byte[16], NUMBER, true, null, null, null,
SESSION_EXPIRATION_SECONDS))));
final Optional<Account> maybeAccount;
if (existingAccount) {
@@ -514,14 +369,9 @@ class RegistrationControllerTest {
}
// this is functionally the same as deviceTransferAvailable(existingAccount=false)
@Test
void registrationSuccess() throws Exception {
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(
CompletableFuture.completedFuture(
Optional.of(new RegistrationServiceSession(new byte[16], NUMBER, true, null, null, null,
SESSION_EXPIRATION_SECONDS))));
@ParameterizedTest
@ValueSource(booleans = {true, false})
void registrationSuccess(final boolean useSessionVerification) throws Exception {
final Account account = mock(Account.class);
when(account.getPrimaryDevice()).thenReturn(mock(Device.class));
@@ -533,24 +383,24 @@ class RegistrationControllerTest {
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD));
try (Response response = request.post(Entity.json(requestJson("sessionId")))) {
final String requestJson = useSessionVerification
? requestJson("sessionId")
: requestJsonRecoveryPassword("recovery-password".getBytes(StandardCharsets.UTF_8));
try (Response response = request.post(Entity.json(requestJson))) {
assertEquals(200, response.getStatus());
}
verify(registrationFraudChecker)
.handleVerificationCompleted(Base64.getEncoder().encodeToString("sessionId".getBytes(StandardCharsets.UTF_8)),
account);
if (useSessionVerification) {
verify(registrationFraudChecker)
.handleVerificationCompleted(Base64.getEncoder().encodeToString("sessionId".getBytes(StandardCharsets.UTF_8)),
account);
}
}
@ParameterizedTest
@MethodSource
void atomicAccountCreationConflictingChannel(final RegistrationRequest conflictingChannelRequest) {
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(
CompletableFuture.completedFuture(
Optional.of(new RegistrationServiceSession(new byte[16], NUMBER, true, null, null, null,
SESSION_EXPIRATION_SECONDS))));
try (final Response response = resources.getJerseyTest()
.target("/v1/registration")
.request()
@@ -636,12 +486,6 @@ class RegistrationControllerTest {
@ParameterizedTest
@MethodSource
void atomicAccountCreationPartialSignedPreKeys(final RegistrationRequest partialSignedPreKeyRequest) {
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(
CompletableFuture.completedFuture(
Optional.of(new RegistrationServiceSession(new byte[16], NUMBER, true, null, null, null,
SESSION_EXPIRATION_SECONDS))));
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/registration")
.request()
@@ -770,12 +614,6 @@ class RegistrationControllerTest {
final IdentityKey expectedPniIdentityKey,
final DeviceSpec expectedDeviceSpec) throws InterruptedException {
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(
CompletableFuture.completedFuture(
Optional.of(new RegistrationServiceSession(new byte[16], NUMBER, true, null, null, null,
SESSION_EXPIRATION_SECONDS))));
final UUID accountIdentifier = UUID.randomUUID();
final UUID phoneNumberIdentifier = UUID.randomUUID();
final Device device = mock(Device.class);
@@ -813,11 +651,6 @@ class RegistrationControllerTest {
@ParameterizedTest
@ValueSource(booleans = {true, false})
void reregistrationFlag(final boolean existingAccount) throws InterruptedException {
final RegistrationServiceSession registrationSession =
new RegistrationServiceSession(new byte[16], NUMBER, true, null, null, null, SESSION_EXPIRATION_SECONDS);
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.of(registrationSession)));
final Optional<Account> maybeAccount = Optional.ofNullable(existingAccount ? mock(Account.class) : null);
when(accountsManager.getByE164(any())).thenReturn(maybeAccount);
@@ -831,6 +664,7 @@ class RegistrationControllerTest {
.target("/v1/registration")
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD));
try (Response response = request.post(Entity.json(requestJson("sessionId")))) {
assertEquals(200, response.getStatus());
final AccountCreationResponse creationResponse = response.readEntity(AccountCreationResponse.class);
@@ -840,12 +674,6 @@ class RegistrationControllerTest {
@Test
void registrationMissingSpqrCapability() throws Exception {
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(
CompletableFuture.completedFuture(
Optional.of(new RegistrationServiceSession(new byte[16], NUMBER, true, null, null, null,
SESSION_EXPIRATION_SECONDS))));
final Account account = mock(Account.class);
when(account.getPrimaryDevice()).thenReturn(mock(Device.class));
@@ -901,10 +729,12 @@ class RegistrationControllerTest {
final Set<DeviceCapability> deviceCapabilities = DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES;
final AccountAttributes fetchesMessagesAccountAttributes =
new AccountAttributes(true, registrationId, pniRegistrationId, "test".getBytes(StandardCharsets.UTF_8), null, true, deviceCapabilities);
new AccountAttributes(true, registrationId, pniRegistrationId, "test".getBytes(StandardCharsets.UTF_8), null, true, deviceCapabilities)
.setUnidentifiedAccessKey(TestRandomUtil.nextBytes(16));
final AccountAttributes pushAccountAttributes =
new AccountAttributes(false, registrationId, pniRegistrationId, "test".getBytes(StandardCharsets.UTF_8), null, true, deviceCapabilities);
new AccountAttributes(false, registrationId, pniRegistrationId, "test".getBytes(StandardCharsets.UTF_8), null, true, deviceCapabilities)
.setUnidentifiedAccessKey(TestRandomUtil.nextBytes(16));
final String apnsToken = "apns-token";
final String gcmToken = "gcm-token";
@@ -1017,7 +847,8 @@ class RegistrationControllerTest {
final AccountAttributes accountAttributes = new AccountAttributes(true, registrationId, pniRegistrationId,
"name".getBytes(StandardCharsets.UTF_8), REGLOCK,
true, deviceCapabilities);
true, deviceCapabilities)
.setUnidentifiedAccessKey(TestRandomUtil.nextBytes(16));
return new RegistrationRequest(
Base64.getEncoder().encodeToString(sessionId.getBytes(StandardCharsets.UTF_8)),
@@ -0,0 +1,53 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.entities;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Base64;
import org.junit.jupiter.api.Test;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
class AccountAttributesTest {
private static final ObjectMapper mapper = SystemMapper.jsonMapper();
@Test
void testSerializationDeserializationRoundTrip() throws Exception {
final String originalJson = testJson();
final AccountAttributes attributes = mapper.readValue(originalJson, AccountAttributes.class);
assertEquals(originalJson, mapper.writerWithDefaultPrettyPrinter().writeValueAsString(attributes));
}
private static String testJson() {
return String.format("""
{
"fetchesMessages" : false,
"registrationId" : 123,
"pniRegistrationId" : 456,
"name" : "%s",
"capabilities" : {
"storage" : true
},
"registrationLock" : null,
"unidentifiedAccessKey" : "%s",
"unrestrictedUnidentifiedAccess" : false,
"discoverableByPhoneNumber" : true,
"recoveryPassword" : "%s"
}
""",
Base64.getEncoder().withoutPadding().encodeToString(TestRandomUtil.nextBytes(128)), // name
Base64.getEncoder().encodeToString(TestRandomUtil.nextBytes(16)), // unidentifiedAccessKey
Base64.getEncoder().encodeToString(TestRandomUtil.nextBytes(32)) // recoveryPassword
).trim();
}
}
@@ -8,11 +8,13 @@ package org.whispersystems.textsecuregcm.grpc;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.AdditionalMatchers.aryEq;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -25,7 +27,6 @@ import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
@@ -54,6 +55,7 @@ import org.signal.chat.account.SetRegistrationLockResponse;
import org.signal.chat.account.SetRegistrationRecoveryPasswordRequest;
import org.signal.chat.account.SetUsernameLinkRequest;
import org.signal.chat.account.SetUsernameLinkResponse;
import org.signal.chat.account.SetZkCredentialKeyRequest;
import org.signal.chat.account.UsernameNotAvailable;
import org.signal.chat.common.AccountIdentifiers;
import org.signal.chat.errors.FailedPrecondition;
@@ -74,6 +76,7 @@ import org.whispersystems.textsecuregcm.storage.Device;
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.TestRandomUtil;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
@@ -94,21 +97,15 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
@Override
protected AccountsGrpcService createServiceBeforeEachTest() {
when(accountsManager.update(any(), any()))
.thenAnswer(invocation -> {
final Account account = invocation.getArgument(0);
final Consumer<Account> updater = invocation.getArgument(1);
updater.accept(account);
return account;
});
AccountsHelper.setupMockUpdate(accountsManager);
final RateLimiters rateLimiters = mock(RateLimiters.class);
when(rateLimiters.getUsernameReserveLimiter()).thenReturn(rateLimiter);
when(rateLimiters.getUsernameSetLimiter()).thenReturn(rateLimiter);
when(rateLimiters.getUsernameLinkOperationLimiter()).thenReturn(rateLimiter);
when(rateLimiters.getSetZkCredentialKeyLimiter()).thenReturn(rateLimiter);
when(registrationRecoveryPasswordsManager.store(any(), any()))
.thenReturn(CompletableFuture.completedFuture(null));
@@ -149,15 +146,10 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
@Test
void deleteAccount() {
final Account account = mock(Account.class);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
final DeleteAccountResponse ignored =
authenticatedServiceStub().deleteAccount(DeleteAccountRequest.newBuilder().build());
verify(accountsManager).delete(account, AccountsManager.DeletionReason.USER_REQUEST);
verify(accountsManager).delete(AUTHENTICATED_ACI, AccountsManager.DeletionReason.USER_REQUEST);
}
@Test
@@ -201,7 +193,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
() -> authenticatedServiceStub().setRegistrationLock(SetRegistrationLockRequest.newBuilder()
.build()));
verify(accountsManager, never()).update(any(), any());
verify(accountsManager, never()).update(any(UUID.class), any());
}
@Test
@@ -214,7 +206,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
.setRegistrationLock(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
.build()));
verify(accountsManager, never()).update(any(), any());
verify(accountsManager, never()).update(any(UUID.class), any());
}
@Test
@@ -238,12 +230,13 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT,
() -> authenticatedServiceStub().clearRegistrationLock(ClearRegistrationLockRequest.newBuilder().build()));
verify(accountsManager, never()).update(any(), any());
verify(accountsManager, never()).update(any(UUID.class), any());
}
@Test
void reserveUsernameHash() throws UsernameHashNotAvailableException {
final Account account = mock(Account.class);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(AUTHENTICATED_ACI);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
@@ -254,7 +247,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
.thenAnswer(invocation -> {
final List<byte[]> usernameHashes = invocation.getArgument(1);
return new AccountsManager.UsernameReservation(invocation.getArgument(0), usernameHashes.getFirst());
return new AccountsManager.UsernameReservation(accountsManager.getByAccountIdentifier(invocation.getArgument(0)).orElseThrow(), usernameHashes.getFirst());
});
final ReserveUsernameHashResponse expectedResponse = ReserveUsernameHashResponse.newBuilder()
@@ -358,7 +351,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
when(accountsManager.confirmReservedUsernameHash(account, usernameHash, usernameCiphertext))
when(accountsManager.confirmReservedUsernameHash(AUTHENTICATED_ACI, usernameHash, usernameCiphertext))
.thenAnswer(_ -> {
final Account updatedAccount = mock(Account.class);
@@ -497,12 +490,12 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
when(accountsManager.clearUsernameHash(account)).thenReturn(account);
when(accountsManager.clearUsernameHash(AUTHENTICATED_ACI)).thenReturn(account);
assertDoesNotThrow(() ->
authenticatedServiceStub().deleteUsernameHash(DeleteUsernameHashRequest.newBuilder().build()));
verify(accountsManager).clearUsernameHash(account);
verify(accountsManager).clearUsernameHash(AUTHENTICATED_ACI);
}
@ParameterizedTest
@@ -510,6 +503,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
void setUsernameLink(final boolean keepLink) {
final Account account = mock(Account.class);
final UUID oldHandle = UUID.randomUUID();
when(account.getIdentifier(IdentityType.ACI)).thenReturn(AUTHENTICATED_ACI);
when(account.getUsernameHash()).thenReturn(Optional.of(new byte[AccountController.USERNAME_HASH_LENGTH]));
when(account.getUsernameLinkHandle()).thenReturn(oldHandle);
@@ -712,4 +706,53 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
() -> authenticatedServiceStub().setRegistrationRecoveryPassword(
SetRegistrationRecoveryPasswordRequest.newBuilder().build()));
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void setZkCredentialKey(final boolean matchesCurrentZkCredentialKey) {
final byte[] publicKey = TestRandomUtil.nextBytes(33);
final Account account = mock(Account.class);
if (matchesCurrentZkCredentialKey) {
when(account.getZkCredentialKey()).thenReturn(publicKey);
}
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
assertDoesNotThrow(() ->
authenticatedServiceStub().setZkCredentialKey(SetZkCredentialKeyRequest.newBuilder()
.setPublicKey(ByteString.copyFrom(publicKey))
.build()));
final int updateMethodCalls = matchesCurrentZkCredentialKey ? 0 : 1;
verify(accountsManager, times(updateMethodCalls)).update(eq(AUTHENTICATED_ACI), any());
verify(account, times(updateMethodCalls)).setZkCredentialKey(aryEq(publicKey));
}
@Test
void setZkCredentialKeyRateLimited() throws Exception {
final byte[] publicKey = TestRandomUtil.nextBytes(33);
final Duration retryDuration = Duration.ofDays(1);
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(AUTHENTICATED_ACI);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
doThrow(new RateLimitExceededException(retryDuration))
.when(rateLimiter).validate(AUTHENTICATED_ACI);
GrpcTestUtils.assertRateLimitExceeded(retryDuration, () ->
authenticatedServiceStub().setZkCredentialKey(SetZkCredentialKeyRequest.newBuilder()
.setPublicKey(ByteString.copyFrom(publicKey))
.build()));
verify(accountsManager, never()).update(any(UUID.class), any());
verify(account, never()).setZkCredentialKey(any());
}
}
@@ -25,7 +25,6 @@ import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.junit.jupiter.api.Test;
@@ -53,6 +52,7 @@ import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, DevicesGrpc.DevicesBlockingStub> {
@@ -66,6 +66,7 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
@Override
protected DevicesGrpcService createServiceBeforeEachTest() {
when(authenticatedAccount.getUuid()).thenReturn(AUTHENTICATED_ACI);
when(authenticatedAccount.getIdentifier(IdentityType.ACI)).thenReturn(AUTHENTICATED_ACI);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(authenticatedAccount));
@@ -73,26 +74,7 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
when(accountsManager.removeDevice(any(), anyByte()))
.thenReturn(authenticatedAccount);
when(accountsManager.update(any(), any()))
.thenAnswer(invocation -> {
final Account account = invocation.getArgument(0);
final Consumer<Account> updater = invocation.getArgument(1);
updater.accept(account);
return account;
});
when(accountsManager.updateDevice(any(), anyByte(), any()))
.thenAnswer(invocation -> {
final Account account = invocation.getArgument(0);
final Device device = account.getDevice(invocation.getArgument(1)).orElseThrow();
final Consumer<Device> updater = invocation.getArgument(2);
updater.accept(device);
return account;
});
AccountsHelper.setupMockUpdate(accountsManager);
return new DevicesGrpcService(accountsManager);
}
@@ -154,7 +136,7 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
.setId(deviceId)
.build());
verify(accountsManager).removeDevice(authenticatedAccount, deviceId);
verify(accountsManager).removeDevice(AUTHENTICATED_ACI, deviceId);
}
@Test
@@ -176,7 +158,7 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
.setId(deviceId)
.build());
verify(accountsManager).removeDevice(authenticatedAccount, deviceId);
verify(accountsManager).removeDevice(AUTHENTICATED_ACI, deviceId);
}
@Test
@@ -10,23 +10,15 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.verifyNoInteractions;
import com.google.protobuf.Any;
import com.google.protobuf.Message;
import com.google.rpc.ErrorInfo;
import com.google.rpc.RetryInfo;
import io.grpc.BindableService;
import io.grpc.ServerInterceptors;
import io.grpc.Status;
import io.grpc.StatusException;
import io.grpc.StatusRuntimeException;
import java.time.Duration;
import java.util.List;
import java.util.UUID;
import io.grpc.protobuf.StatusProto;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.function.Executable;
import org.whispersystems.textsecuregcm.auth.grpc.MockAuthenticationInterceptor;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
public final class GrpcTestUtils {
@@ -34,9 +26,11 @@ public final class GrpcTestUtils {
// noop
}
public static void assertStatusException(final Status expected, final Executable serviceCall) {
public static StatusRuntimeException assertStatusException(final Status expected, final Executable serviceCall) {
final StatusRuntimeException exception = Assertions.assertThrows(StatusRuntimeException.class, serviceCall);
assertEquals(expected.getCode(), exception.getStatus().getCode());
return exception;
}
public static void assertStatusException(final Status expected, final String expectedReason, final Executable serviceCall) {
@@ -45,16 +39,16 @@ public final class GrpcTestUtils {
assertEquals(expectedReason, extractErrorInfo(exception).getReason());
}
public static void assertStatusInvalidArgument(final Executable serviceCall) {
assertStatusException(Status.INVALID_ARGUMENT, serviceCall);
public static StatusRuntimeException assertStatusInvalidArgument(final Executable serviceCall) {
return assertStatusException(Status.INVALID_ARGUMENT, serviceCall);
}
public static void assertStatusUnauthenticated(final Executable serviceCall) {
assertStatusException(Status.UNAUTHENTICATED, serviceCall);
public static StatusRuntimeException assertStatusUnauthenticated(final Executable serviceCall) {
return assertStatusException(Status.UNAUTHENTICATED, serviceCall);
}
public static void assertStatusPermissionDenied(final Executable serviceCall) {
assertStatusException(Status.PERMISSION_DENIED, serviceCall);
public static StatusRuntimeException assertStatusPermissionDenied(final Executable serviceCall) {
return assertStatusException(Status.PERMISSION_DENIED, serviceCall);
}
public static void assertRateLimitExceeded(
@@ -68,8 +62,8 @@ public final class GrpcTestUtils {
final ErrorInfo errorInfo = extractErrorInfo(exception);
final RetryInfo retryInfo = extractDetail(RetryInfo.class, exception);
final Duration actual = Duration.ofSeconds(retryInfo.getRetryDelay().getSeconds(), retryInfo.getRetryDelay().getNanos());
assertEquals(errorInfo.getDomain(), GrpcExceptions.DOMAIN);
assertEquals(errorInfo.getReason(), "RESOURCE_EXHAUSTED");
assertEquals(GrpcExceptions.DOMAIN, errorInfo.getDomain());
assertEquals("RESOURCE_EXHAUSTED", errorInfo.getReason());
assertEquals(expectedRetryAfter, actual);
for (final Object mock: mocksToCheckForNoInteraction) {
@@ -7,9 +7,16 @@ package org.whispersystems.textsecuregcm.grpc;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatNoException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.AdditionalMatchers.aryEq;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
@@ -20,12 +27,15 @@ import com.google.protobuf.ByteString;
import io.grpc.ServerInterceptor;
import io.grpc.Status;
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.Collection;
import java.util.Collections;
import java.util.HexFormat;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Stream;
@@ -34,24 +44,28 @@ 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.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.Mock;
import org.signal.chat.common.IdentityType;
import org.signal.chat.common.ServiceIdentifier;
import org.signal.chat.profile.CredentialType;
import org.signal.chat.profile.DataEtag;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousRequest;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousResponse;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialRequest;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResponse;
import org.signal.chat.profile.GetUnversionedProfileAnonymousRequest;
import org.signal.chat.profile.GetUnversionedProfileAnonymousResponse;
import org.signal.chat.profile.GetUnversionedProfileRequest;
import org.signal.chat.profile.GetUnversionedProfileResponse;
import org.signal.chat.profile.GetUnversionedProfileResult;
import org.signal.chat.profile.GetVersionedProfileAnonymousRequest;
import org.signal.chat.profile.GetVersionedProfileAnonymousResponse;
import org.signal.chat.profile.GetVersionedProfileRequest;
import org.signal.chat.profile.GetVersionedProfileResponse;
import org.signal.chat.profile.GetVersionedProfileResult;
import org.signal.chat.profile.GetVersionedProfileV1Response;
import org.signal.chat.profile.ProfileAnonymousGrpc;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.profiles.ClientZkProfileOperations;
@@ -60,6 +74,7 @@ import org.signal.libsignal.zkgroup.profiles.ProfileKey;
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCommitment;
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequestContext;
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
@@ -71,6 +86,7 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.tests.util.ProfileTestHelper;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
@@ -78,7 +94,7 @@ import org.whispersystems.textsecuregcm.util.UUIDUtil;
public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileAnonymousGrpcService, ProfileAnonymousGrpc.ProfileAnonymousBlockingStub> {
private final ServerSecretParams SERVER_SECRET_PARAMS = ServerSecretParams.generate();
private static final ServerSecretParams SERVER_SECRET_PARAMS = ServerSecretParams.generate();
@Mock
private Account account;
@@ -92,17 +108,22 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
@Mock
private ProfileBadgeConverter profileBadgeConverter;
private ServerZkProfileOperations zkProfileOperations;
@Override
protected ProfileAnonymousGrpcService createServiceBeforeEachTest() {
getMockRequestAttributesInterceptor().setRequestAttributes(new RequestAttributes(InetAddresses.forString("127.0.0.1"),
"Signal-Android/1.2.3",
"en-us"));
zkProfileOperations = spy(new ServerZkProfileOperations(SERVER_SECRET_PARAMS));
return new ProfileAnonymousGrpcService(
accountsManager,
profilesManager,
profileBadgeConverter,
SERVER_SECRET_PARAMS
zkProfileOperations,
new GroupSendTokenUtil(SERVER_SECRET_PARAMS, Clock.systemUTC())
);
}
@@ -134,6 +155,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(account.getIdentityKey(org.whispersystems.textsecuregcm.identity.IdentityType.ACI)).thenReturn(identityKey);
when(account.hasCapability(any())).thenReturn(false);
when(account.hasCapability(DeviceCapability.SPARSE_POST_QUANTUM_RATCHET)).thenReturn(true);
when(accountsManager.getByServiceIdentifier(serviceIdentifier)).thenReturn(Optional.of(account));
final GetUnversionedProfileAnonymousRequest request = GetUnversionedProfileAnonymousRequest.newBuilder()
@@ -146,14 +168,18 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
.build())
.build();
final GetUnversionedProfileResponse response = unauthenticatedServiceStub().getUnversionedProfile(request);
final GetUnversionedProfileAnonymousResponse response = unauthenticatedServiceStub().getUnversionedProfile(request);
final byte[] unidentifiedAccessChecksum = UnidentifiedAccessChecksum.generateFor(unidentifiedAccessKey);
final GetUnversionedProfileResponse expectedResponse = GetUnversionedProfileResponse.newBuilder()
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
.setUnidentifiedAccess(ByteString.copyFrom(unidentifiedAccessChecksum))
.setUnrestrictedUnidentifiedAccess(false)
.addAllBadges(ProfileGrpcHelper.buildBadges(badges))
final GetUnversionedProfileAnonymousResponse expectedResponse = GetUnversionedProfileAnonymousResponse.newBuilder()
.setResult(GetUnversionedProfileResult.newBuilder()
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
.setUnidentifiedAccess(ByteString.copyFrom(unidentifiedAccessChecksum))
.setUnrestrictedUnidentifiedAccess(false)
.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET)
.addAllBadges(ProfileGrpcHelper.buildBadges(badges))
.build()
)
.build();
verify(accountsManager).getByServiceIdentifier(serviceIdentifier);
@@ -199,17 +225,18 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
.build())
.build();
final GetUnversionedProfileResponse response = unauthenticatedServiceStub().getUnversionedProfile(request);
final GetUnversionedProfileAnonymousResponse response = unauthenticatedServiceStub().getUnversionedProfile(request);
final GetUnversionedProfileResponse expectedResponse = GetUnversionedProfileResponse.newBuilder()
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
.setUnrestrictedUnidentifiedAccess(false)
.addAllCapabilities(ProfileGrpcHelper.buildAccountCapabilities(account))
.addAllBadges(ProfileGrpcHelper.buildBadges(badges))
.build();
final GetUnversionedProfileResult expectedResult = GetUnversionedProfileResult.newBuilder()
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
.setUnrestrictedUnidentifiedAccess(false)
.addAllCapabilities(ProfileGrpcHelper.buildAccountCapabilities(account))
.addAllBadges(ProfileGrpcHelper.buildBadges(badges))
.build();
verify(accountsManager).getByServiceIdentifier(serviceIdentifier);
assertEquals(expectedResponse, response);
assertTrue(response.hasResult());
assertEquals(expectedResult, response.getResult());
}
@Test
@@ -243,7 +270,14 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))))
.build();
assertStatusException(Status.UNAUTHENTICATED, () -> unauthenticatedServiceStub().getUnversionedProfile(request));
if (IdentityType.IDENTITY_TYPE_PNI.equals(identityType)) {
assertStatusException(Status.INVALID_ARGUMENT, () -> unauthenticatedServiceStub().getUnversionedProfile(request));
} else {
final GetUnversionedProfileAnonymousResponse response = unauthenticatedServiceStub().getUnversionedProfile(request);
assertTrue(response.hasFailedUnidentifiedAuthorization());
}
}
private static Stream<Arguments> getUnversionedProfileIncorrectUnidentifiedAccessKey() {
@@ -254,9 +288,13 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
);
}
@Test
void getUnversionedProfileExpiredGroupSendEndorsement() throws Exception {
@ParameterizedTest
@ValueSource(booleans = {true, false})
void getUnversionedProfileExpiredGroupSendEndorsement(final boolean accountNotFound) throws Exception {
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
when(accountsManager.getByServiceIdentifier(serviceIdentifier))
.thenReturn(accountNotFound ? Optional.empty() : Optional.of(mock(Account.class)));
// Expirations must be on a day boundary; pick one in the recent past
final Instant expiration = Instant.now().truncatedTo(ChronoUnit.DAYS);
final byte[] token = AuthHelper.validGroupSendToken(SERVER_SECRET_PARAMS, List.of(serviceIdentifier), expiration);
@@ -268,7 +306,10 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
ServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier)))
.build();
assertStatusException(Status.UNAUTHENTICATED, () -> unauthenticatedServiceStub().getUnversionedProfile(request));
final GetUnversionedProfileAnonymousResponse response = unauthenticatedServiceStub().getUnversionedProfile(
request);
assertTrue(response.hasFailedUnidentifiedAuthorization());
}
@Test
@@ -281,7 +322,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
final byte[] token = AuthHelper.validGroupSendToken(SERVER_SECRET_PARAMS, List.of(authorizedServiceIdentifier), expiration);
when(accountsManager.getByServiceIdentifier(any())).thenReturn(
Optional.empty());
Optional.of(mock(Account.class)));
final GetUnversionedProfileAnonymousRequest request = GetUnversionedProfileAnonymousRequest.newBuilder()
.setGroupSendToken(ByteString.copyFrom(token))
.setRequest(GetUnversionedProfileRequest.newBuilder()
@@ -289,7 +330,9 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
ServiceIdentifierUtil.toGrpcServiceIdentifier(targetServiceIdentifier)))
.build();
assertStatusException(Status.UNAUTHENTICATED, () -> unauthenticatedServiceStub().getUnversionedProfile(request));
final GetUnversionedProfileAnonymousResponse response = unauthenticatedServiceStub().getUnversionedProfile(request);
assertTrue(response.hasFailedUnidentifiedAuthorization());
}
@Test
@@ -307,13 +350,16 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
.setServiceIdentifier(ServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier)))
.build();
assertStatusException(Status.NOT_FOUND, () -> unauthenticatedServiceStub().getUnversionedProfile(request));
final GetUnversionedProfileAnonymousResponse response = unauthenticatedServiceStub().getUnversionedProfile(
request);
assertTrue(response.hasNotFound());
}
@ParameterizedTest
@MethodSource
void getVersionedProfile(final String requestVersion,
@Nullable final String accountVersion,
void getVersionedProfile(final byte[] requestVersion,
@Nullable final byte[] accountVersion,
final boolean expectResponseHasPaymentAddress) {
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
@@ -324,14 +370,14 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
final byte[] phoneNumberSharing = TestRandomUtil.nextBytes(29);
final String avatar = "profiles/" + ProfileTestHelper.generateRandomBase64FromByteArray(16);
final VersionedProfile profile = new VersionedProfile(accountVersion, name, avatar, emoji, about, paymentAddress, phoneNumberSharing, new byte[0]);
final Optional<VersionedProfileV1> profile = Optional.of(new VersionedProfileV1(HexFormat.of().formatHex(requestVersion), name, avatar, emoji, about, paymentAddress, phoneNumberSharing, new byte[0]));
when(account.getCurrentProfileVersion()).thenReturn(Optional.ofNullable(accountVersion));
when(account.getCurrentProfileVersion()).thenReturn(Optional.ofNullable(accountVersion).map(v -> HexFormat.of().formatHex(v)));
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
when(profilesManager.get(any(), any())).thenReturn(Optional.of(profile));
when(profilesManager.getV1(any(), any())).thenReturn(profile);
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
@@ -340,34 +386,131 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
.build())
.setVersion(requestVersion)
.setVersion(ByteString.copyFrom(requestVersion))
.build())
.build();
final GetVersionedProfileResponse response = unauthenticatedServiceStub().getVersionedProfile(request);
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(request);
final GetVersionedProfileResponse.Builder expectedResponseBuilder = GetVersionedProfileResponse.newBuilder()
.setName(ByteString.copyFrom(name))
.setAbout(ByteString.copyFrom(about))
.setAboutEmoji(ByteString.copyFrom(emoji))
.setAvatar(avatar)
.setPhoneNumberSharing(ByteString.copyFrom(phoneNumberSharing));
final GetVersionedProfileResult.Builder expectedResultBuilder = GetVersionedProfileResult.newBuilder()
.setV1Response(GetVersionedProfileV1Response.newBuilder()
.setName(ByteString.copyFrom(name))
.setAbout(ByteString.copyFrom(about))
.setAboutEmoji(ByteString.copyFrom(emoji))
.setAvatar(avatar)
.setPhoneNumberSharing(ByteString.copyFrom(phoneNumberSharing))
);
if (expectResponseHasPaymentAddress) {
expectedResponseBuilder.setPaymentAddress(ByteString.copyFrom(paymentAddress));
expectedResultBuilder.setPaymentAddressDataEtag(DataEtag.newBuilder()
.setData(ByteString.copyFrom(paymentAddress))
.setEtag(ByteString.copyFrom(ProfileGrpcHelper.hash(paymentAddress)))
.build());
}
assertEquals(expectedResponseBuilder.build(), response);
assertEquals(expectedResultBuilder.build(), response.getResult());
}
private static Stream<Arguments> getVersionedProfile() {
return Stream.of(
Arguments.of("version1", "version1", true),
Arguments.of("version1", null, true),
Arguments.of("version1", "version2", false)
private static Collection<Arguments> getVersionedProfile() {
final byte[] version1 = TestRandomUtil.nextBytes(32);
final byte[] version2 = TestRandomUtil.nextBytes(32);
return List.of(
Arguments.argumentSet("current profile version matches", version1, version1, true),
Arguments.argumentSet("current profile version absent",version1, null, true),
Arguments.argumentSet("current profile version mismatch",version1, version2, false)
);
}
@Test
void getVersionedProfileV2() {
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final byte[] data = TestRandomUtil.nextBytes(128);
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
final byte[] commitment = TestRandomUtil.nextBytes(97);
final byte[] version = TestRandomUtil.nextBytes(32);
final String versionHex = HexFormat.of().formatHex(version);
final VersionedProfile v2Profile = new VersionedProfile(version, data, paymentAddress, commitment);
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(versionHex));
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
when(profilesManager.get(any(), any())).thenReturn(Optional.of(v2Profile));
when(profilesManager.getV1(any(), any())).thenReturn(Optional.empty());
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
.setRequest(GetVersionedProfileRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
.build())
.setVersion(ByteString.copyFrom(version))
.build())
.build();
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(request);
assertTrue(response.hasResult());
final GetVersionedProfileResult result = response.getResult();
assertTrue(result.hasDataEtag());
assertEquals(ByteString.copyFrom(data), result.getDataEtag().getData());
assertEquals(ByteString.copyFrom(v2Profile.dataHash()), result.getDataEtag().getEtag());
assertTrue(result.hasPaymentAddressDataEtag());
assertEquals(ByteString.copyFrom(paymentAddress), result.getPaymentAddressDataEtag().getData());
assertEquals(ByteString.copyFrom(Objects.requireNonNull(v2Profile.paymentAddressHash())), result.getPaymentAddressDataEtag().getEtag());
assertFalse(result.getDataEtagMatched());
assertFalse(result.getPaymentAddressEtagMatched());
assertFalse(result.hasV1Response());
}
@Test
void getVersionedProfileV2EtagMatched() {
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final byte[] data = TestRandomUtil.nextBytes(128);
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
final byte[] commitment = TestRandomUtil.nextBytes(97);
final byte[] version = TestRandomUtil.nextBytes(32);
final String versionHex = HexFormat.of().formatHex(version);
final VersionedProfile v2Profile = new VersionedProfile(version, data, paymentAddress, commitment);
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(versionHex));
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
when(profilesManager.get(any(), any())).thenReturn(Optional.of(v2Profile));
when(profilesManager.getV1(any(), any())).thenReturn(Optional.empty());
final GetVersionedProfileRequest.Builder builder = GetVersionedProfileRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
.build())
.setVersion(ByteString.copyFrom(version))
.setDataEtag(ByteString.copyFrom(v2Profile.dataHash()));
if (v2Profile.paymentAddressHash() != null) {
builder.setPaymentAddressEtag(ByteString.copyFrom(v2Profile.paymentAddressHash()));
}
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
.setRequest(builder.build())
.build();
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(request);
assertTrue(response.hasResult());
final GetVersionedProfileResult result = response.getResult();
assertTrue(result.getDataEtagMatched());
assertTrue(result.getPaymentAddressEtagMatched());
assertFalse(result.hasDataEtag());
assertFalse(result.hasPaymentAddressDataEtag());
assertFalse(result.hasV1Response());
}
@Test
void getVersionedProfileVersionNotFound() {
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
@@ -376,7 +519,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
when(profilesManager.get(any(), any())).thenReturn(Optional.empty());
when(profilesManager.getV1(any(), any())).thenReturn(Optional.empty());
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
@@ -385,17 +528,19 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
.build())
.setVersion("someVersion")
.setVersion(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
.build())
.build();
assertStatusException(Status.NOT_FOUND, () -> unauthenticatedServiceStub().getVersionedProfile(request));
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(
request);
assertTrue(response.hasNotFound());
}
@ParameterizedTest
@MethodSource
void getVersionedProfileUnauthenticated(final boolean missingUnidentifiedAccessKey,
final boolean accountNotFound) {
void getVersionedProfileUnauthenticated(final boolean missingUnidentifiedAccessKey, final boolean accountNotFound) {
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
@@ -409,14 +554,23 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
.build())
.setVersion("someVersion")
.setVersion(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
.build());
if (!missingUnidentifiedAccessKey) {
if (missingUnidentifiedAccessKey) {
assertStatusException(Status.INVALID_ARGUMENT,
() -> unauthenticatedServiceStub().getVersionedProfile(requestBuilder.build()));
} else {
requestBuilder.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey));
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(
requestBuilder.build());
assertEquals(accountNotFound, response.hasNotFound());
assertNotEquals(accountNotFound, response.hasFailedUnidentifiedAuthorization());
}
assertStatusException(Status.UNAUTHENTICATED, () -> unauthenticatedServiceStub().getVersionedProfile(requestBuilder.build()));
}
private static Stream<Arguments> getVersionedProfileUnauthenticated() {
return Stream.of(
@@ -436,7 +590,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
.setIdentityType(IdentityType.IDENTITY_TYPE_PNI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
.build())
.setVersion("someVersion")
.setVersion(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
.build())
.build();
@@ -444,7 +598,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
}
@Test
void getExpiringProfileKeyCredential() throws InvalidInputException, VerificationFailedException {
void getExpiringProfileKeyCredential() throws Exception {
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final UUID targetUuid = UUID.randomUUID();
@@ -456,19 +610,16 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
final ProfileKeyCredentialRequestContext profileKeyCredentialRequestContext =
clientZkProfile.createProfileKeyCredentialRequestContext(new ServiceId.Aci(targetUuid), profileKey);
final VersionedProfile profile = mock(VersionedProfile.class);
final VersionedProfileV1 profile = mock(VersionedProfileV1.class);
when(profile.commitment()).thenReturn(profileKeyCommitment.serialize());
when(account.getUuid()).thenReturn(targetUuid);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetUuid))).thenReturn(Optional.of(account));
when(profilesManager.get(targetUuid, "someVersion")).thenReturn(Optional.of(profile));
when(profilesManager.getV1(targetUuid, HexFormat.of().formatHex(profileKeyBytes))).thenReturn(Optional.of(profile));
final ProfileKeyCredentialRequest credentialRequest = profileKeyCredentialRequestContext.getRequest();
final Instant expiration = Instant.now().plus(org.whispersystems.textsecuregcm.util.ProfileHelper.EXPIRING_PROFILE_KEY_CREDENTIAL_EXPIRATION)
.truncatedTo(ChronoUnit.DAYS);
final GetExpiringProfileKeyCredentialAnonymousRequest request = GetExpiringProfileKeyCredentialAnonymousRequest.newBuilder()
.setRequest(GetExpiringProfileKeyCredentialRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
@@ -477,15 +628,20 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
.build())
.setCredentialRequest(ByteString.copyFrom(credentialRequest.serialize()))
.setCredentialType(CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY)
.setVersion("someVersion")
.setVersion(ByteString.copyFrom(profileKeyBytes))
.build())
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
.build();
final GetExpiringProfileKeyCredentialResponse response = unauthenticatedServiceStub().getExpiringProfileKeyCredential(request);
final GetExpiringProfileKeyCredentialAnonymousResponse response = unauthenticatedServiceStub().getExpiringProfileKeyCredential(request);
final Instant expectedExpiration = Instant.now().plus(org.whispersystems.textsecuregcm.util.ProfileHelper.EXPIRING_PROFILE_KEY_CREDENTIAL_EXPIRATION)
.truncatedTo(ChronoUnit.DAYS);
verify(zkProfileOperations).issueExpiringProfileKeyCredential(eq(credentialRequest), eq(ServiceId.Aci.parseFromString(targetUuid.toString())), eq(profileKeyCommitment), eq(expectedExpiration));
assertThatNoException().isThrownBy(() ->
clientZkProfile.receiveExpiringProfileKeyCredential(profileKeyCredentialRequestContext, new ExpiringProfileKeyCredentialResponse(response.getProfileKeyCredential().toByteArray())));
clientZkProfile.receiveExpiringProfileKeyCredential(profileKeyCredentialRequestContext,
new ExpiringProfileKeyCredentialResponse(response.getResult().getProfileKeyCredential().toByteArray())));
}
@ParameterizedTest
@@ -507,14 +663,22 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
.build())
.setCredentialRequest(ByteString.copyFrom("credentialRequest".getBytes(StandardCharsets.UTF_8)))
.setCredentialType(CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY)
.setVersion("someVersion")
.setVersion(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
.build());
if (!missingUnidentifiedAccessKey) {
requestBuilder.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey));
}
if (missingUnidentifiedAccessKey) {
assertStatusException(Status.INVALID_ARGUMENT,
() -> unauthenticatedServiceStub().getExpiringProfileKeyCredential(requestBuilder.build()));
assertStatusException(Status.UNAUTHENTICATED, () -> unauthenticatedServiceStub().getExpiringProfileKeyCredential(requestBuilder.build()));
} else {
requestBuilder.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey));
final GetExpiringProfileKeyCredentialAnonymousResponse response = unauthenticatedServiceStub().getExpiringProfileKeyCredential(
requestBuilder.build());
assertEquals(missingAccount, response.hasNotFound());
assertNotEquals(missingAccount, response.hasFailedUnidentifiedAuthorization());
}
verifyNoInteractions(profilesManager);
}
@@ -522,7 +686,8 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
private static Stream<Arguments> getExpiringProfileKeyCredentialUnauthenticated() {
return Stream.of(
Arguments.of(true, false),
Arguments.of(false, true)
Arguments.of(false, true),
Arguments.of(true, true)
);
}
@@ -532,11 +697,15 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final UUID targetUuid = UUID.randomUUID();
final byte[] version = TestRandomUtil.nextBytes(32);
final String versionHex = HexFormat.of().formatHex(version);
when(account.getUuid()).thenReturn(targetUuid);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetUuid))).thenReturn(
Optional.of(account));
when(profilesManager.get(targetUuid, "someVersion")).thenReturn(Optional.empty());
when(profilesManager.getV1(targetUuid, versionHex)).thenReturn(Optional.empty());
when(profilesManager.get(eq(targetUuid), aryEq(version))).thenReturn(Optional.empty());
final GetExpiringProfileKeyCredentialAnonymousRequest request = GetExpiringProfileKeyCredentialAnonymousRequest.newBuilder()
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
@@ -547,26 +716,38 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
.build())
.setCredentialRequest(ByteString.copyFrom("credentialRequest".getBytes(StandardCharsets.UTF_8)))
.setCredentialType(CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY)
.setVersion("someVersion")
.setVersion(ByteString.copyFrom(version))
.build())
.build();
assertStatusException(Status.NOT_FOUND, () -> unauthenticatedServiceStub().getExpiringProfileKeyCredential(request));
final GetExpiringProfileKeyCredentialAnonymousResponse response = unauthenticatedServiceStub().getExpiringProfileKeyCredential(
request);
assertTrue(response.hasNotFound());
}
@ParameterizedTest
@MethodSource
void getExpiringProfileKeyCredentialInvalidArgument(final IdentityType identityType, final CredentialType credentialType,
final byte[] credentialRequest,
final boolean throwZkVerificationException) throws VerificationFailedException {
final UUID targetUuid = UUID.randomUUID();
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final VersionedProfile profile = mock(VersionedProfile.class);
final byte[] version = TestRandomUtil.nextBytes(32);
final String versionHex = HexFormat.of().formatHex(version);
final VersionedProfileV1 profile = mock(VersionedProfileV1.class);
when(profile.commitment()).thenReturn("commitment".getBytes(StandardCharsets.UTF_8));
when(account.getUuid()).thenReturn(targetUuid);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetUuid))).thenReturn(Optional.of(account));
when(profilesManager.get(targetUuid, "someVersion")).thenReturn(Optional.of(profile));
when(profilesManager.getV1(targetUuid, versionHex)).thenReturn(Optional.of(profile));
if (throwZkVerificationException) {
doThrow(VerificationFailedException.class)
.when(zkProfileOperations).issueExpiringProfileKeyCredential(any(), any(), any(), any());
}
final GetExpiringProfileKeyCredentialAnonymousRequest request = GetExpiringProfileKeyCredentialAnonymousRequest.newBuilder()
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
@@ -575,23 +756,37 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
.setIdentityType(identityType)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(targetUuid)))
.build())
.setCredentialRequest(ByteString.copyFrom("credentialRequest".getBytes(StandardCharsets.UTF_8)))
.setCredentialRequest(ByteString.copyFrom(credentialRequest))
.setCredentialType(credentialType)
.setVersion("someVersion")
.setVersion(ByteString.copyFrom(version))
.build())
.build();
assertStatusException(Status.INVALID_ARGUMENT, () -> unauthenticatedServiceStub().getExpiringProfileKeyCredential(request));
}
private static Stream<Arguments> getExpiringProfileKeyCredentialInvalidArgument() {
private static Stream<Arguments> getExpiringProfileKeyCredentialInvalidArgument() throws Exception {
final byte[] invalidCredentialRequest = "invalidRequest".getBytes();
final UUID targetUuid = UUID.randomUUID();
final ClientZkProfileOperations clientZkProfile = new ClientZkProfileOperations(SERVER_SECRET_PARAMS.getPublicParams());
final byte[] profileKeyBytes = TestRandomUtil.nextBytes(32);
final ProfileKey profileKey = new ProfileKey(profileKeyBytes);
final ProfileKeyCommitment profileKeyCommitment = profileKey.getCommitment(new ServiceId.Aci(targetUuid));
final ProfileKeyCredentialRequestContext profileKeyCredentialRequestContext =
clientZkProfile.createProfileKeyCredentialRequestContext(new ServiceId.Aci(targetUuid), profileKey);
final ProfileKeyCredentialRequest credentialRequest = profileKeyCredentialRequestContext.getRequest();
final byte[] validCredentialRequest = credentialRequest.serialize();
return Stream.of(
// Credential type unspecified
Arguments.of(IdentityType.IDENTITY_TYPE_ACI, CredentialType.CREDENTIAL_TYPE_UNSPECIFIED, false),
// Illegal identity type
Arguments.of(IdentityType.IDENTITY_TYPE_PNI, CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY, false),
// Artificially fails zero knowledge verification
Arguments.of(IdentityType.IDENTITY_TYPE_ACI, CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY, true)
Arguments.argumentSet("Credential type unspecified", IdentityType.IDENTITY_TYPE_ACI, CredentialType.CREDENTIAL_TYPE_UNSPECIFIED, validCredentialRequest, false),
Arguments.argumentSet("Illegal identity type", IdentityType.IDENTITY_TYPE_PNI, CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY, validCredentialRequest, false),
Arguments.argumentSet("Invalid credential request", IdentityType.IDENTITY_TYPE_ACI, CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY, invalidCredentialRequest, false),
Arguments.argumentSet("ZK verification failure", IdentityType.IDENTITY_TYPE_ACI, CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY, validCredentialRequest, true)
);
}
@@ -6,15 +6,15 @@
package org.whispersystems.textsecuregcm.grpc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatNoException;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.AdditionalMatchers.aryEq;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.ArgumentMatchers.refEq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
@@ -24,28 +24,29 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.whispersystems.textsecuregcm.grpc.GrpcTestUtils.assertRateLimitExceeded;
import static org.whispersystems.textsecuregcm.grpc.GrpcTestUtils.assertStatusException;
import static org.whispersystems.textsecuregcm.grpc.GrpcTestUtils.assertStatusInvalidArgument;
import com.google.common.net.InetAddresses;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import com.google.protobuf.ByteString;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import com.google.rpc.BadRequest;
import io.grpc.ServerInterceptor;
import io.grpc.Status;
import java.nio.charset.StandardCharsets;
import io.grpc.StatusRuntimeException;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Collection;
import java.util.Collections;
import java.util.HexFormat;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.junit.jupiter.api.Test;
@@ -58,32 +59,26 @@ import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.signal.chat.common.IdentityType;
import org.signal.chat.common.ServiceIdentifier;
import org.signal.chat.profile.CredentialType;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialRequest;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResponse;
import org.signal.chat.profile.DataEtag;
import org.signal.chat.profile.GetUnversionedProfileRequest;
import org.signal.chat.profile.GetUnversionedProfileResponse;
import org.signal.chat.profile.GetUnversionedProfileResult;
import org.signal.chat.profile.GetVersionedProfileRequest;
import org.signal.chat.profile.GetVersionedProfileResponse;
import org.signal.chat.profile.GetVersionedProfileResult;
import org.signal.chat.profile.GetVersionedProfileV1Response;
import org.signal.chat.profile.ProfileGrpc;
import org.signal.chat.profile.SetProfileRequest;
import org.signal.chat.profile.SetProfileRequest.AvatarChange;
import org.signal.chat.profile.SetProfileResponse;
import org.signal.chat.profile.SetProfileResult;
import org.signal.chat.profile.SetProfileV1Request;
import org.signal.chat.profile.SetProfileV1Request.AvatarChange;
import org.signal.chat.profile.test.PlaintextProfileData;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.ServerPublicParams;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.profiles.ClientZkProfileOperations;
import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialResponse;
import org.signal.libsignal.zkgroup.profiles.ProfileKey;
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCommitment;
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequestContext;
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
@@ -103,10 +98,12 @@ import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountBadge;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
import org.whispersystems.textsecuregcm.storage.WriteConflictException;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.tests.util.ProfileTestHelper;
import org.whispersystems.textsecuregcm.util.MockUtils;
@@ -115,10 +112,17 @@ import org.whispersystems.textsecuregcm.util.UUIDUtil;
public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcService, ProfileGrpc.ProfileBlockingStub> {
private static final String VERSION = "someVersion";
private static final byte[] VERSION = TestRandomUtil.nextBytes(32);
private static final byte[] VALID_DATA = new byte[128];
private static final byte[] VALID_NAME = new byte[81];
private static final SetProfileV1Request V1_REQUEST = SetProfileV1Request.newBuilder()
.setName(ByteString.copyFrom(VALID_NAME))
.setPhoneNumberSharing(ByteString.copyFrom(TestRandomUtil.nextBytes(29)))
.build();
@Mock
private AccountsManager accountsManager;
@@ -129,7 +133,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
private DynamicPaymentsConfiguration dynamicPaymentsConfiguration;
@Mock
private VersionedProfile profile;
private VersionedProfileV1 profile;
@Mock
private Account account;
@@ -140,9 +144,6 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
@Mock
private ProfileBadgeConverter profileBadgeConverter;
@Mock
private ServerZkProfileOperations serverZkProfileOperations;
private Clock clock;
@Override
@@ -181,16 +182,18 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
when(dynamicConfiguration.getPaymentsConfiguration()).thenReturn(dynamicPaymentsConfiguration);
when(account.getUuid()).thenReturn(AUTHENTICATED_ACI);
when(account.getIdentifier(org.whispersystems.textsecuregcm.identity.IdentityType.ACI)).thenReturn(AUTHENTICATED_ACI);
when(account.getNumber()).thenReturn(phoneNumber);
when(account.getBadges()).thenReturn(Collections.emptyList());
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
when(profile.paymentAddress()).thenReturn(null);
when(profile.avatar()).thenReturn("");
when(accountsManager.getByAccountIdentifier(any())).thenReturn(Optional.of(account));
when(accountsManager.update(any(), any())).thenReturn(null);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI)).thenReturn(Optional.of(account));
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(AUTHENTICATED_ACI))).thenReturn(Optional.of(account));
when(profilesManager.get(any(), any())).thenReturn(Optional.of(profile));
when(profilesManager.getV1(any(), any())).thenReturn(Optional.of(profile));
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
when(dynamicConfiguration.getPaymentsConfiguration()).thenReturn(dynamicPaymentsConfiguration);
@@ -209,13 +212,12 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
policyGenerator,
policySigner,
profileBadgeConverter,
rateLimiters,
serverZkProfileOperations
rateLimiters
);
}
@Test
void setProfile() throws InvalidInputException {
void setProfile() throws Exception {
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AUTHENTICATED_ACI)).serialize();
final byte[] validAboutEmoji = new byte[60];
final byte[] validAbout = new byte[540];
@@ -223,32 +225,60 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
final byte[] validPhoneNumberSharing = new byte[29];
final SetProfileRequest request = SetProfileRequest.newBuilder()
.setVersion(VERSION)
.setName(ByteString.copyFrom(VALID_NAME))
.setAvatarChange(AvatarChange.AVATAR_CHANGE_UNCHANGED)
.setAboutEmoji(ByteString.copyFrom(validAboutEmoji))
.setAbout(ByteString.copyFrom(validAbout))
.setVersion(ByteString.copyFrom(VERSION))
.setData(ByteString.copyFrom(VALID_DATA))
.setCommitment(ByteString.copyFrom(commitment)) // after v1 -> v2 migration, commitment can be null if expectedDataHash is present
.setPaymentAddress(ByteString.copyFrom(validPaymentAddress))
.setPhoneNumberSharing(ByteString.copyFrom(validPhoneNumberSharing))
.setCommitment(ByteString.copyFrom(commitment))
.setV1Request(V1_REQUEST.toBuilder()
.setAvatarChange(AvatarChange.AVATAR_CHANGE_UNCHANGED)
.setAboutEmoji(ByteString.copyFrom(validAboutEmoji))
.setAbout(ByteString.copyFrom(validAbout))
.setPhoneNumberSharing(ByteString.copyFrom(validPhoneNumberSharing))
)
.build();
authenticatedServiceStub().setProfile(request);
final ArgumentCaptor<VersionedProfileV1> profileV1ArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
verify(profilesManager).set(eq(account.getUuid()), profileArgumentCaptor.capture());
verify(profilesManager).set(eq(account.getUuid()), profileV1ArgumentCaptor.capture(), profileArgumentCaptor.capture(), isNull());
final VersionedProfile profile = profileArgumentCaptor.getValue();
assertThat(profile.commitment()).isEqualTo(commitment);
assertThat(profile.avatar()).isNull();
assertThat(profile.version()).isEqualTo(VERSION);
assertThat(profile.name()).isEqualTo(VALID_NAME);
assertThat(profile.aboutEmoji()).isEqualTo(validAboutEmoji);
assertThat(profile.about()).isEqualTo(validAbout);
assertThat(profile.data()).isEqualTo(VALID_DATA);
assertThat(profile.dataHash()).hasSize(32);
assertThat(profile.commitment()).isEqualTo(commitment);
assertThat(profile.paymentAddress()).isEqualTo(validPaymentAddress);
assertThat(profile.phoneNumberSharing()).isEqualTo(validPhoneNumberSharing);
assertThat(profile.paymentAddressHash()).hasSize(32);
final VersionedProfileV1 v1Profile = profileV1ArgumentCaptor.getValue();
assertThat(v1Profile.commitment()).isEqualTo(commitment);
assertThat(v1Profile.avatar()).isNull();
assertThat(v1Profile.version()).isEqualTo(HexFormat.of().formatHex(VERSION));
assertThat(v1Profile.name()).isEqualTo(VALID_NAME);
assertThat(v1Profile.aboutEmoji()).isEqualTo(validAboutEmoji);
assertThat(v1Profile.about()).isEqualTo(validAbout);
assertThat(v1Profile.paymentAddress()).isEqualTo(validPaymentAddress);
assertThat(v1Profile.phoneNumberSharing()).isEqualTo(validPhoneNumberSharing);
}
@Test
void setProfileWithoutCapability() {
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(false);
final SetProfileRequest request = SetProfileRequest.newBuilder()
.setVersion(ByteString.copyFrom(VERSION))
.setData(ByteString.copyFrom(VALID_DATA))
.setExpectedCurrentDataHash(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
.setV1Request(V1_REQUEST)
.build();
final SetProfileResponse response = authenticatedServiceStub().setProfile(request);
assertTrue(response.hasProfilesV2CapabilityRequired());
}
@ParameterizedTest
@@ -259,22 +289,25 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AUTHENTICATED_ACI)).serialize();
final SetProfileRequest request = SetProfileRequest.newBuilder()
.setVersion(VERSION)
.setName(ByteString.copyFrom(VALID_NAME))
.setAvatarChange(avatarChange)
.setVersion(ByteString.copyFrom(VERSION))
.setData(ByteString.copyFrom(VALID_DATA))
.setCommitment(ByteString.copyFrom(commitment))
.setV1Request(V1_REQUEST.toBuilder().setAvatarChange(avatarChange).build())
.build();
when(profile.avatar()).thenReturn(currentAvatar);
when(profilesManager.get(any(), anyString())).thenReturn(hasPreviousProfile ? Optional.of(profile) : Optional.empty());
when(profilesManager.getV1(any(), anyString())).thenReturn(hasPreviousProfile ? Optional.of(profile) : Optional.empty());
final SetProfileResponse response = authenticatedServiceStub().setProfile(request);
assertTrue(response.hasResult());
final SetProfileResult result = response.getResult();
if (expectHasS3UploadPath) {
assertTrue(response.getAttributes().getPath().startsWith("profiles/"));
assertTrue(result.getV1AvatarUploadForm().getPath().startsWith("profiles/"));
} else {
assertEquals(response.getAttributes().getPath(), "");
assertEquals("", result.getV1AvatarUploadForm().getPath());
}
if (expectDeleteS3Object) {
@@ -303,8 +336,19 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
@ParameterizedTest
@MethodSource
void setProfileInvalidRequestData(final SetProfileRequest request) {
assertStatusException(Status.INVALID_ARGUMENT, () -> authenticatedServiceStub().setProfile(request));
void setProfileInvalidRequestData(final SetProfileRequest request, final String invalidFieldOrMessageFragment, final boolean assertFieldViolation) {
assertStatusInvalidArgument(() -> authenticatedServiceStub().setProfile(request));
// com.google.rpc.Status.parseFrom(exception.getTrailers().valueAsBytes(0)).getDetailsList().get(1).unpack(BadRequest.class).getFieldViolationsList().getFirst().getField()
final StatusRuntimeException e = assertStatusInvalidArgument(() -> authenticatedServiceStub().setProfile(request));
if (assertFieldViolation) {
final List<BadRequest.FieldViolation> fieldViolations = GrpcTestUtils.extractDetail(BadRequest.class, e)
.getFieldViolationsList();
assertEquals(1, fieldViolations.size());
assertEquals(invalidFieldOrMessageFragment, fieldViolations.getFirst().getField());
} else {
assertThat(e.getMessage()).contains(invalidFieldOrMessageFragment);
}
}
private static Stream<Arguments> setProfileInvalidRequestData() throws InvalidInputException{
@@ -312,40 +356,49 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
final byte[] invalidValue = new byte[42];
final SetProfileRequest prototypeRequest = SetProfileRequest.newBuilder()
.setVersion(VERSION)
.setName(ByteString.copyFrom(VALID_NAME))
.setVersion(ByteString.copyFrom(VERSION))
.setData(ByteString.copyFrom(VALID_DATA))
.setCommitment(ByteString.copyFrom(commitment))
.setV1Request(V1_REQUEST)
.build();
return Stream.of(
// Missing version
Arguments.of(SetProfileRequest.newBuilder(prototypeRequest)
Arguments.argumentSet("Missing version", SetProfileRequest.newBuilder(prototypeRequest)
.clearVersion()
.build()),
// Missing name
Arguments.of(SetProfileRequest.newBuilder(prototypeRequest)
.clearName()
.build()),
// Invalid name length
Arguments.of(SetProfileRequest.newBuilder(prototypeRequest)
.setName(ByteString.copyFrom(invalidValue))
.build()),
// Invalid about emoji length
Arguments.of(SetProfileRequest.newBuilder(prototypeRequest)
.setAboutEmoji(ByteString.copyFrom(invalidValue))
.build()),
// Invalid about length
Arguments.of(SetProfileRequest.newBuilder(prototypeRequest)
.setAbout(ByteString.copyFrom(invalidValue))
.build()),
// Invalid payment address
Arguments.of(SetProfileRequest.newBuilder(prototypeRequest)
.build(), "version", true),
Arguments.argumentSet("Invalid current data hash", SetProfileRequest.newBuilder(prototypeRequest)
.setExpectedCurrentDataHash(ByteString.copyFrom(invalidValue))
.build(), "expected_current_data_hash", true),
Arguments.argumentSet("Invalid current version", SetProfileRequest.newBuilder(prototypeRequest)
.setExpectedCurrentVersion(ByteString.copyFrom(new byte[1]))
.build(), "expected_current_version", true),
Arguments.argumentSet("Missing name", SetProfileRequest.newBuilder(prototypeRequest)
.setV1Request(prototypeRequest.getV1Request().toBuilder().clearName())
.build(), "name", true),
Arguments.argumentSet("Invalid name length", SetProfileRequest.newBuilder(prototypeRequest)
.setV1Request(prototypeRequest.getV1Request().toBuilder()
.setName(ByteString.copyFrom(invalidValue))
.build())
.build(), "name", true),
Arguments.argumentSet("Invalid about emoji length", SetProfileRequest.newBuilder(prototypeRequest)
.setV1Request(prototypeRequest.getV1Request().toBuilder()
.setAboutEmoji(ByteString.copyFrom(invalidValue)))
.build(), "about_emoji", true),
Arguments.argumentSet("Invalid about length", SetProfileRequest.newBuilder(prototypeRequest)
.setV1Request(prototypeRequest.getV1Request().toBuilder()
.setAbout(ByteString.copyFrom(invalidValue)))
.build(), "about", true),
Arguments.argumentSet("Invalid payment address", SetProfileRequest.newBuilder(prototypeRequest)
.setPaymentAddress(ByteString.copyFrom(invalidValue))
.build()),
// Missing profile commitment
Arguments.of(SetProfileRequest.newBuilder()
.build(), "payment_address", true),
Arguments.argumentSet("Missing v1 request", SetProfileRequest.newBuilder(prototypeRequest)
.clearV1Request()
.build(), "v1Request", true),
// this is an invalid request but not a field validation
Arguments.argumentSet("Missing profile commitment", SetProfileRequest.newBuilder(prototypeRequest)
.clearCommitment()
.build())
.build(), "commitment", false)
);
}
@@ -361,42 +414,43 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
}
final SetProfileRequest request = SetProfileRequest.newBuilder()
.setVersion(VERSION)
.setName(ByteString.copyFrom(VALID_NAME))
.setAvatarChange(AvatarChange.AVATAR_CHANGE_UNCHANGED)
.setVersion(ByteString.copyFrom(VERSION))
.setData(ByteString.copyFrom(VALID_DATA))
.setPaymentAddress(ByteString.copyFrom(validPaymentAddress))
.setCommitment(ByteString.copyFrom(commitment))
.setV1Request(V1_REQUEST)
.build();
final String disallowedCountryCode = String.format("+%d", disallowedPhoneNumber.getCountryCode());
when(dynamicPaymentsConfiguration.getDisallowedPrefixes()).thenReturn(List.of(disallowedCountryCode));
when(account.getNumber()).thenReturn(PhoneNumberUtil.getInstance().format(
disallowedPhoneNumber,
PhoneNumberUtil.PhoneNumberFormat.E164));
when(profilesManager.get(any(), anyString())).thenReturn(Optional.of(profile));
when(profilesManager.getV1(any(), anyString())).thenReturn(Optional.of(profile));
final SetProfileResponse response = authenticatedServiceStub().setProfile(request);
if (hasExistingPaymentAddress) {
assertDoesNotThrow(() -> authenticatedServiceStub().setProfile(request),
"Payment address changes in disallowed countries should still be allowed if the account already has a valid payment address");
assertTrue(response.hasResult(), "Payment address changes in disallowed countries should still be allowed if the account already has a valid payment address");
} else {
assertStatusException(Status.PERMISSION_DENIED, () -> authenticatedServiceStub().setProfile(request));
assertTrue(response.hasPaymentsForbiddenInRegion());
}
}
@Test
void setProfileBadges() throws InvalidInputException {
void setProfileBadges() throws Exception {
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AUTHENTICATED_ACI)).serialize();
final SetProfileRequest request = SetProfileRequest.newBuilder()
.setVersion(VERSION)
.setName(ByteString.copyFrom(VALID_NAME))
.setAvatarChange(AvatarChange.AVATAR_CHANGE_UNCHANGED)
.setVersion(ByteString.copyFrom(VERSION))
.setData(ByteString.copyFrom(VALID_DATA))
.addAllBadgeIds(List.of("TEST3"))
.setCommitment(ByteString.copyFrom(commitment))
.setV1Request(V1_REQUEST)
.build();
final int accountsManagerUpdateRetryCount = 2;
AccountsHelper.setupMockUpdateWithRetries(accountsManager, accountsManagerUpdateRetryCount);
setUpMockUpdateWithRetries(accountsManager, accountsManagerUpdateRetryCount);
// set up two invocations -- one for each AccountsManager#update try
when(account.getBadges())
.thenReturn(List.of(new AccountBadge("TEST3", Instant.ofEpochSecond(41), false)))
@@ -418,6 +472,36 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
badgeCaptor.getValue());
}
@Test
void setProfileBadgesEmptyListClearsAll() throws InvalidInputException {
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AUTHENTICATED_ACI)).serialize();
final SetProfileRequest request = SetProfileRequest.newBuilder()
.setVersion(ByteString.copyFrom(VERSION))
.setData(ByteString.copyFrom(VALID_DATA))
.setCommitment(ByteString.copyFrom(commitment))
.setV1Request(V1_REQUEST)
.build();
final List<AccountBadge> existingBadges = List.of(
new AccountBadge("TEST1", Instant.ofEpochSecond(41), true),
new AccountBadge("TEST2", Instant.ofEpochSecond(41), true));
when(account.getBadges()).thenReturn(existingBadges);
setUpMockUpdateWithRetries(accountsManager, 1);
authenticatedServiceStub().setProfile(request);
@SuppressWarnings("unchecked")
final ArgumentCaptor<List<AccountBadge>> badgeCaptor = ArgumentCaptor.forClass(List.class);
verify(account).setBadges(refEq(clock), badgeCaptor.capture());
assertEquals(List.of(
new AccountBadge("TEST1", Instant.ofEpochSecond(41), false),
new AccountBadge("TEST2", Instant.ofEpochSecond(41), false)),
badgeCaptor.getValue());
}
@ParameterizedTest
@EnumSource(value = org.signal.chat.common.IdentityType.class, names = {"IDENTITY_TYPE_ACI", "IDENTITY_TYPE_PNI"})
void getUnversionedProfile(final IdentityType identityType) throws Exception {
@@ -459,28 +543,29 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
final GetUnversionedProfileResponse response = authenticatedServiceStub().getUnversionedProfile(request);
final byte[] unidentifiedAccessChecksum = UnidentifiedAccessChecksum.generateFor(unidentifiedAccessKey);
final GetUnversionedProfileResponse prototypeExpectedResponse = GetUnversionedProfileResponse.newBuilder()
final GetUnversionedProfileResult prototypeExpectedResult = GetUnversionedProfileResult.newBuilder()
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
.setUnidentifiedAccess(ByteString.copyFrom(unidentifiedAccessChecksum))
.setUnrestrictedUnidentifiedAccess(true)
.addAllBadges(ProfileGrpcHelper.buildBadges(badges))
.build();
final GetUnversionedProfileResponse expectedResponse;
final GetUnversionedProfileResult expectedResponse;
if (identityType == IdentityType.IDENTITY_TYPE_PNI) {
expectedResponse = GetUnversionedProfileResponse.newBuilder(prototypeExpectedResponse)
expectedResponse = GetUnversionedProfileResult.newBuilder(prototypeExpectedResult)
.clearUnidentifiedAccess()
.clearBadges()
.setUnrestrictedUnidentifiedAccess(false)
.build();
} else {
expectedResponse = prototypeExpectedResponse;
expectedResponse = prototypeExpectedResult;
}
verify(rateLimiter).validate(AUTHENTICATED_ACI);
verify(accountsManager).getByServiceIdentifier(targetIdentifier);
assertEquals(expectedResponse, response);
assertTrue(response.hasResult());
assertEquals(expectedResponse, response.getResult());
}
@Test
@@ -494,7 +579,8 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
.build())
.build();
assertStatusException(Status.NOT_FOUND, () -> authenticatedServiceStub().getUnversionedProfile(request));
final GetUnversionedProfileResponse response = authenticatedServiceStub().getUnversionedProfile(request);
assertTrue(response.hasNotFound());
}
@ParameterizedTest
@@ -517,7 +603,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
@ParameterizedTest
@MethodSource
void getVersionedProfile(final String requestVersion, @Nullable final String accountVersion, final boolean expectResponseHasPaymentAddress) {
void getVersionedProfile(final byte[] requestVersion, @Nullable final byte[] accountVersion, final boolean expectResponseHasPaymentAddress) {
final byte[] name = TestRandomUtil.nextBytes(81);
final byte[] emoji = TestRandomUtil.nextBytes(60);
final byte[] about = TestRandomUtil.nextBytes(156);
@@ -525,44 +611,141 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
final byte[] phoneNumberSharing = TestRandomUtil.nextBytes(29);
final String avatar = "profiles/" + ProfileTestHelper.generateRandomBase64FromByteArray(16);
final VersionedProfile profile = new VersionedProfile(accountVersion, name, avatar, emoji, about, paymentAddress,
phoneNumberSharing, new byte[0]);
final Optional<VersionedProfileV1> profile = Optional.of(new VersionedProfileV1(HexFormat.of().formatHex(requestVersion), name, avatar, emoji, about, paymentAddress,
phoneNumberSharing, new byte[0]));
final GetVersionedProfileRequest request = GetVersionedProfileRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
.build())
.setVersion(requestVersion)
.setVersion(ByteString.copyFrom(requestVersion))
.build();
when(account.getCurrentProfileVersion()).thenReturn(Optional.ofNullable(accountVersion));
when(account.getCurrentProfileVersion()).thenReturn(Optional.ofNullable(accountVersion).map(v -> HexFormat.of().formatHex(v)));
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
when(profilesManager.get(any(), any())).thenReturn(Optional.of(profile));
when(profilesManager.getV1(any(), any())).thenReturn(profile);
final GetVersionedProfileResponse response = authenticatedServiceStub().getVersionedProfile(request);
final GetVersionedProfileResponse.Builder expectedResponseBuilder = GetVersionedProfileResponse.newBuilder()
.setName(ByteString.copyFrom(name))
.setAbout(ByteString.copyFrom(about))
.setAboutEmoji(ByteString.copyFrom(emoji))
.setAvatar(avatar)
.setPhoneNumberSharing(ByteString.copyFrom(phoneNumberSharing));
final GetVersionedProfileResult.Builder expectedResultBuilder = GetVersionedProfileResult.newBuilder()
.setV1Response(GetVersionedProfileV1Response.newBuilder()
.setName(ByteString.copyFrom(name))
.setAbout(ByteString.copyFrom(about))
.setAboutEmoji(ByteString.copyFrom(emoji))
.setAvatar(avatar)
.setPhoneNumberSharing(ByteString.copyFrom(phoneNumberSharing))
.build());
if (expectResponseHasPaymentAddress) {
expectedResponseBuilder.setPaymentAddress(ByteString.copyFrom(paymentAddress));
expectedResultBuilder.setPaymentAddressDataEtag(
DataEtag.newBuilder().setData(ByteString.copyFrom(paymentAddress))
.setEtag(ByteString.copyFrom(ProfileGrpcHelper.hash(paymentAddress)))
.build());
}
assertEquals(expectedResponseBuilder.build(), response);
assertTrue(response.hasResult());
assertEquals(expectedResultBuilder.build(), response.getResult());
}
private static Stream<Arguments> getVersionedProfile() {
return Stream.of(
Arguments.of("version1", "version1", true),
Arguments.of("version1", null, true),
Arguments.of("version1", "version2", false)
private static Collection<Arguments> getVersionedProfile() {
final byte[] version1 = TestRandomUtil.nextBytes(32);
final byte[] version2 = TestRandomUtil.nextBytes(32);
return List.of(
Arguments.argumentSet("current profile version matches", version1, version1, true),
Arguments.argumentSet("current profile version absent",version1, null, true),
Arguments.argumentSet("current profile version mismatch",version1, version2, false)
);
}
@Test
void getVersionedProfileV2() {
final byte[] data = TestRandomUtil.nextBytes(128);
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
final byte[] commitment = TestRandomUtil.nextBytes(97);
final byte[] version = TestRandomUtil.nextBytes(32);
final String versionHex = HexFormat.of().formatHex(version);
final UUID targetAci = UUID.randomUUID();
final VersionedProfile v2Profile = new VersionedProfile(version, data, paymentAddress, commitment);
final Account targetAccount = mock(Account.class);
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetAci)))
.thenReturn(Optional.of(targetAccount));
when(targetAccount.getUuid()).thenReturn(targetAci);
when(targetAccount.getCurrentProfileVersion()).thenReturn(Optional.of(versionHex));
when(targetAccount.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
when(profilesManager.get(eq(targetAci), aryEq(version))).thenReturn(Optional.of(v2Profile));
when(profilesManager.getV1(any(), any())).thenReturn(Optional.empty());
final GetVersionedProfileRequest request = GetVersionedProfileRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(targetAci)))
.build())
.setVersion(ByteString.copyFrom(version))
.build();
final GetVersionedProfileResponse response = authenticatedServiceStub().getVersionedProfile(request);
assertTrue(response.hasResult());
final GetVersionedProfileResult result = response.getResult();
assertTrue(result.hasDataEtag());
assertEquals(ByteString.copyFrom(data), result.getDataEtag().getData());
assertEquals(ByteString.copyFrom(v2Profile.dataHash()), result.getDataEtag().getEtag());
assertTrue(result.hasPaymentAddressDataEtag());
assertEquals(ByteString.copyFrom(paymentAddress), result.getPaymentAddressDataEtag().getData());
assertEquals(ByteString.copyFrom(v2Profile.paymentAddressHash()), result.getPaymentAddressDataEtag().getEtag());
assertFalse(result.getDataEtagMatched());
assertFalse(result.getPaymentAddressEtagMatched());
assertFalse(result.hasV1Response());
}
@Test
void getVersionedProfileV2EtagMatched() {
final byte[] data = TestRandomUtil.nextBytes(128);
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
final byte[] commitment = TestRandomUtil.nextBytes(97);
final byte[] version = TestRandomUtil.nextBytes(32);
final String versionHex = HexFormat.of().formatHex(version);
final VersionedProfile v2Profile = new VersionedProfile(version, data, paymentAddress, commitment);
final UUID targetAci = UUID.randomUUID();
final Account targetAccount = mock(Account.class);
when(targetAccount.getUuid()).thenReturn(targetAci);
when(targetAccount.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetAci))).thenReturn(Optional.of(targetAccount));
when(targetAccount.getCurrentProfileVersion()).thenReturn(Optional.of(versionHex));
when(profilesManager.get(targetAci, version)).thenReturn(Optional.of(v2Profile));
when(profilesManager.getV1(any(), any())).thenReturn(Optional.empty());
final GetVersionedProfileRequest.Builder builder = GetVersionedProfileRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(targetAci)))
.build())
.setVersion(ByteString.copyFrom(version))
.setDataEtag(ByteString.copyFrom(v2Profile.dataHash()));
if (v2Profile.paymentAddressHash() != null) {
builder.setPaymentAddressEtag(ByteString.copyFrom(v2Profile.paymentAddressHash()));
}
final GetVersionedProfileRequest request = builder.build();
final GetVersionedProfileResponse response = authenticatedServiceStub().getVersionedProfile(request);
assertTrue(response.hasResult());
final GetVersionedProfileResult result = response.getResult();
assertTrue(result.getDataEtagMatched());
assertTrue(result.getPaymentAddressEtagMatched());
assertFalse(result.hasDataEtag());
assertFalse(result.hasPaymentAddressDataEtag());
assertFalse(result.hasV1Response());
}
@ParameterizedTest
@MethodSource
void getVersionedProfileAccountOrProfileNotFound(final boolean missingAccount, final boolean missingProfile) {
@@ -571,12 +754,13 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
.build())
.setVersion("versionWithNoProfile")
.setVersion(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
.build();
when(accountsManager.getByServiceIdentifier(any())).thenReturn(missingAccount ? Optional.empty() : Optional.of(account));
when(profilesManager.get(any(), any())).thenReturn(missingProfile ? Optional.empty() : Optional.of(profile));
when(profilesManager.getV1(any(), any())).thenReturn(missingProfile ? Optional.empty() : Optional.of(profile));
assertStatusException(Status.NOT_FOUND, () -> authenticatedServiceStub().getVersionedProfile(request));
final GetVersionedProfileResponse response = authenticatedServiceStub().getVersionedProfile(request);
assertTrue(response.hasNotFound());
}
private static Stream<Arguments> getVersionedProfileAccountOrProfileNotFound() {
@@ -595,7 +779,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
.build())
.setVersion("someVersion")
.setVersion(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
.build();
assertRateLimitExceeded(retryAfterDuration, () -> authenticatedServiceStub().getVersionedProfile(request), accountsManager, profilesManager);
@@ -608,155 +792,12 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
.setIdentityType(IdentityType.IDENTITY_TYPE_PNI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
.build())
.setVersion("someVersion")
.setVersion(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
.build();
assertStatusException(Status.INVALID_ARGUMENT, () -> authenticatedServiceStub().getVersionedProfile(request));
}
@Test
void getExpiringProfileKeyCredential() throws InvalidInputException, VerificationFailedException {
final UUID targetUuid = UUID.randomUUID();
final ServerSecretParams serverSecretParams = ServerSecretParams.generate();
final ServerPublicParams serverPublicParams = serverSecretParams.getPublicParams();
final ServerZkProfileOperations serverZkProfile = new ServerZkProfileOperations(serverSecretParams);
final ClientZkProfileOperations clientZkProfile = new ClientZkProfileOperations(serverPublicParams);
final byte[] profileKeyBytes = TestRandomUtil.nextBytes(32);
final ProfileKey profileKey = new ProfileKey(profileKeyBytes);
final ProfileKeyCommitment profileKeyCommitment = profileKey.getCommitment(new ServiceId.Aci(targetUuid));
final ProfileKeyCredentialRequestContext profileKeyCredentialRequestContext =
clientZkProfile.createProfileKeyCredentialRequestContext(new ServiceId.Aci(targetUuid), profileKey);
when(account.getUuid()).thenReturn(targetUuid);
when(profile.commitment()).thenReturn(profileKeyCommitment.serialize());
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetUuid))).thenReturn(Optional.of(account));
when(profilesManager.get(targetUuid, "someVersion")).thenReturn(Optional.of(profile));
final ProfileKeyCredentialRequest credentialRequest = profileKeyCredentialRequestContext.getRequest();
final Instant expiration = Instant.now().plus(org.whispersystems.textsecuregcm.util.ProfileHelper.EXPIRING_PROFILE_KEY_CREDENTIAL_EXPIRATION)
.truncatedTo(ChronoUnit.DAYS);
final ExpiringProfileKeyCredentialResponse credentialResponse =
serverZkProfile.issueExpiringProfileKeyCredential(credentialRequest, new ServiceId.Aci(targetUuid), profileKeyCommitment, expiration);
when(serverZkProfileOperations.issueExpiringProfileKeyCredential(credentialRequest, new ServiceId.Aci(targetUuid), profileKeyCommitment, expiration))
.thenReturn(credentialResponse);
final GetExpiringProfileKeyCredentialRequest request = GetExpiringProfileKeyCredentialRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(targetUuid)))
.build())
.setCredentialRequest(ByteString.copyFrom(credentialRequest.serialize()))
.setCredentialType(CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY)
.setVersion("someVersion")
.build();
final GetExpiringProfileKeyCredentialResponse response = authenticatedServiceStub().getExpiringProfileKeyCredential(request);
assertArrayEquals(credentialResponse.serialize(), response.getProfileKeyCredential().toByteArray());
verify(serverZkProfileOperations).issueExpiringProfileKeyCredential(credentialRequest, new ServiceId.Aci(targetUuid), profileKeyCommitment, expiration);
final ClientZkProfileOperations clientZkProfileCipher = new ClientZkProfileOperations(serverPublicParams);
assertThatNoException().isThrownBy(() ->
clientZkProfileCipher.receiveExpiringProfileKeyCredential(profileKeyCredentialRequestContext, new ExpiringProfileKeyCredentialResponse(response.getProfileKeyCredential().toByteArray())));
}
@Test
void getExpiringProfileKeyCredentialRateLimited() {
final Duration retryAfterDuration = MockUtils.updateRateLimiterResponseToFail(
rateLimiter, AUTHENTICATED_ACI, Duration.ofMinutes(5));
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
final GetExpiringProfileKeyCredentialRequest request = GetExpiringProfileKeyCredentialRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
.build())
.setCredentialRequest(ByteString.copyFrom("credentialRequest".getBytes(StandardCharsets.UTF_8)))
.setCredentialType(CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY)
.setVersion("someVersion")
.build();
assertRateLimitExceeded(retryAfterDuration, () -> authenticatedServiceStub().getExpiringProfileKeyCredential(request), profilesManager);
}
@ParameterizedTest
@MethodSource
void getExpiringProfileKeyCredentialAccountOrProfileNotFound(final boolean missingAccount,
final boolean missingProfile) {
final UUID targetUuid = UUID.randomUUID();
when(account.getUuid()).thenReturn(targetUuid);
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetUuid)))
.thenReturn(missingAccount ? Optional.empty() : Optional.of(account));
when(profilesManager.get(targetUuid, "someVersion"))
.thenReturn(missingProfile ? Optional.empty() : Optional.of(profile));
final GetExpiringProfileKeyCredentialRequest request = GetExpiringProfileKeyCredentialRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(targetUuid)))
.build())
.setCredentialRequest(ByteString.copyFrom("credentialRequest".getBytes(StandardCharsets.UTF_8)))
.setCredentialType(CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY)
.setVersion("someVersion")
.build();
assertStatusException(Status.NOT_FOUND, () -> authenticatedServiceStub().getExpiringProfileKeyCredential(request));
}
private static Stream<Arguments> getExpiringProfileKeyCredentialAccountOrProfileNotFound() {
return Stream.of(
Arguments.of(true, false),
Arguments.of(false, true)
);
}
@ParameterizedTest
@MethodSource
void getExpiringProfileKeyCredentialInvalidArgument(final IdentityType identityType, final CredentialType credentialType,
final boolean throwZkVerificationException) throws VerificationFailedException {
final UUID targetUuid = UUID.randomUUID();
if (throwZkVerificationException) {
when(serverZkProfileOperations.issueExpiringProfileKeyCredential(any(), any(), any(), any())).thenThrow(new VerificationFailedException());
}
when(account.getUuid()).thenReturn(targetUuid);
when(profile.commitment()).thenReturn("commitment".getBytes(StandardCharsets.UTF_8));
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetUuid))).thenReturn(Optional.of(account));
when(profilesManager.get(targetUuid, "someVersion")).thenReturn(Optional.of(profile));
final GetExpiringProfileKeyCredentialRequest request = GetExpiringProfileKeyCredentialRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(identityType)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(targetUuid)))
.build())
.setCredentialRequest(ByteString.copyFrom("credentialRequest".getBytes(StandardCharsets.UTF_8)))
.setCredentialType(credentialType)
.setVersion("someVersion")
.build();
assertStatusException(Status.INVALID_ARGUMENT, () -> authenticatedServiceStub().getExpiringProfileKeyCredential(request));
}
private static Stream<Arguments> getExpiringProfileKeyCredentialInvalidArgument() {
return Stream.of(
// Credential type unspecified
Arguments.of(IdentityType.IDENTITY_TYPE_ACI, CredentialType.CREDENTIAL_TYPE_UNSPECIFIED, false),
// Illegal identity type
Arguments.of(IdentityType.IDENTITY_TYPE_PNI, CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY, false),
// Artificially fails zero knowledge verification
Arguments.of(IdentityType.IDENTITY_TYPE_ACI, CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY, true)
);
}
@Override
protected List<ServerInterceptor> customizeInterceptors(List<ServerInterceptor> serverInterceptors) {
return serverInterceptors.stream()
@@ -765,4 +806,55 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
.filter(interceptor -> !(interceptor instanceof ErrorConformanceInterceptor))
.toList();
}
@ParameterizedTest
@ValueSource(ints = {0, 1, 16, 32})
void testProfileSerialized(int aboutEmojiLength) {
// This test demonstrates the calculation for the (require.size).max = 909 + 28
// in profiles.proto, as well as how padding calculation results in a constant size.
//
// This should be largely integrated into libsignal in the future.
// in gRPC, field + varint length encoding has:
// field number: 1 byte per field < number 16
// varint: 1 byte for length < 128, 2 bytes for < 16,384
final int serializedSize =
1 + 257 + 2 +
1 + 512 + 2 +
1 + aboutEmojiLength + 1 +
1 + 64 + 1 +
1 + 1 +
1 + (64 - (257 + 512 + aboutEmojiLength + 64 + 1) % 64) + 1;
assertEquals(909, serializedSize);
final PlaintextProfileData data = PlaintextProfileData.newBuilder()
.setNameBytes(ByteString.copyFrom(new byte[257]))
.setAboutBytes(ByteString.copyFrom(new byte[512]))
.setAboutEmojiBytes(ByteString.copyFrom(new byte[aboutEmojiLength]))
.setAvatarBytes(ByteString.copyFrom(new byte[64]))
.setPhoneNumberSharing(true)
.setPadding(ByteString.copyFrom(new byte[64 - (257 + 512 + aboutEmojiLength + 64 + 1) % 64]))
.build();
assertEquals(serializedSize, data.getSerializedSize());
}
static void setUpMockUpdateWithRetries(final AccountsManager accountsManager, final int retryCount) {
try {
when(accountsManager.updateCurrentProfileVersion(any(), any(), any(), any()))
.thenAnswer(a -> {
final Account account = accountsManager.getByAccountIdentifier(a.getArgument(0, UUID.class)).orElseThrow();
for (int i = 0; i < retryCount; i++) {
//noinspection unchecked
a.getArgument(3, Consumer.class).accept(account);
}
return account;
});
} catch (final WriteConflictException e) {
throw new RuntimeException(e);
}
}
}
@@ -16,6 +16,7 @@ import io.grpc.StatusRuntimeException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
@@ -29,8 +30,11 @@ import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.function.Executable;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.signal.chat.common.IdentityType;
import org.signal.chat.common.ServiceIdentifier;
import org.signal.chat.require.Auth;
import org.signal.chat.rpc.Color;
import org.signal.chat.rpc.NestedMessage;
@@ -43,6 +47,7 @@ import org.signal.chat.rpc.ValidationsRequest;
import org.signal.chat.rpc.ValidationsResponse;
import org.whispersystems.textsecuregcm.grpc.validators.ValidatorUtils;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
public class ValidatingInterceptorTest {
@@ -122,6 +127,51 @@ public class ValidatingInterceptorTest {
.build()));
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
public void serviceIdentifierIdentityTypeFieldValidator(final boolean messagePresent) {
final ValidationsRequest.Builder builder = builderWithValidDefaults();
if (messagePresent) {
builder.setAciServiceIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(UUIDUtil.toByteString(UUID.randomUUID()))
.build())
.setPniServiceIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_PNI)
.setUuid(UUIDUtil.toByteString(UUID.randomUUID()))
.build());
} else {
builder.clearAciServiceIdentifier()
.clearPniServiceIdentifier();
}
assertDoesNotThrow(() -> stub.validationsEndpoint(builder.build()));
}
@ParameterizedTest
@EnumSource(value = org.signal.chat.common.IdentityType.class, names = {"IDENTITY_TYPE_UNSPECIFIED", "IDENTITY_TYPE_PNI"})
public void testServiceIdentifierIdentityTypeAciValidationFailure(final IdentityType identityType) {
assertStatusException(Status.INVALID_ARGUMENT, () -> stub.validationsEndpoint(builderWithValidDefaults()
.setAciServiceIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(identityType)
.setUuid(UUIDUtil.toByteString(UUID.randomUUID())))
.build()));
}
@ParameterizedTest
@EnumSource(value = org.signal.chat.common.IdentityType.class, names = {"IDENTITY_TYPE_UNSPECIFIED", "IDENTITY_TYPE_ACI"})
public void testServiceIdentifierIdentityTypePniValidationFailure(final IdentityType identityType) {
assertStatusException(Status.INVALID_ARGUMENT, () -> stub.validationsEndpoint(builderWithValidDefaults()
.setPniServiceIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(identityType)
.setUuid(UUIDUtil.toByteString(UUID.randomUUID())))
.build()));
}
@ParameterizedTest
@ValueSource(ints = {0, 1, 2, 3, 4, 6, 1000})
public void testExactlySizeValidationFailure(final int size) throws Exception {
@@ -470,7 +520,15 @@ public class ValidatingInterceptorTest {
.setNested(NestedMessage.getDefaultInstance())
.addRepeatedNested(NestedMessage.getDefaultInstance())
.putMapNested("test", NestedMessage.getDefaultInstance())
.setBase64Url("123aBc_-");
.setBase64Url("123aBc_-")
.setAciServiceIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(UUIDUtil.toByteString(UUID.randomUUID()))
.build())
.setPniServiceIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_PNI)
.setUuid(UUIDUtil.toByteString(UUID.randomUUID()))
.build());
}
private static void assertStatusException(final Status expected, final Executable serviceCall) {
@@ -576,7 +576,7 @@ class MessageSenderTest {
when(account.getDevices()).thenReturn(List.of(device));
when(account.isIdentifiedBy(serviceIdentifier)).thenReturn(true);
assertThrows(MismatchedDevicesException.class, () -> messageSender.sendMessages(account,
assertThrows(IllegalArgumentException.class, () -> messageSender.sendMessages(account,
serviceIdentifier,
Collections.emptyMap(),
Collections.emptyMap(),
@@ -24,6 +24,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.junitpioneer.jupiter.cartesian.CartesianTest;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
@@ -150,12 +151,17 @@ class PushNotificationManagerTest {
@Test
void testSendNotificationFcm() {
final UUID accountIdentifier = UUID.randomUUID();
final Account account = mock(Account.class);
final Device device = mock(Device.class);
when(device.getId()).thenReturn(Device.PRIMARY_ID);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
when(account.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(device));
AccountsHelper.setupMockGet(accountsManager, account);
final PushNotification pushNotification = new PushNotification(
"token", PushNotification.TokenType.FCM, PushNotification.NotificationType.NOTIFICATION, null, account, device, true);
@@ -166,7 +172,7 @@ class PushNotificationManagerTest {
verify(fcmSender).sendNotification(pushNotification);
verifyNoInteractions(apnSender);
verify(accountsManager, never()).updateDevice(eq(account), eq(Device.PRIMARY_ID), any());
verify(accountsManager, never()).updateDevice(eq(accountIdentifier), eq(Device.PRIMARY_ID), any());
verify(device, never()).setGcmId(any());
verifyNoInteractions(pushNotificationScheduler);
}
@@ -221,6 +227,7 @@ class PushNotificationManagerTest {
when(device.getGcmId()).thenReturn("token");
when(account.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(device));
when(account.getUuid()).thenReturn(aci);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(aci);
when(accountsManager.getByAccountIdentifier(aci)).thenReturn(Optional.of(account));
final PushNotification pushNotification = new PushNotification(
@@ -231,7 +238,7 @@ class PushNotificationManagerTest {
pushNotificationManager.sendNotification(pushNotification);
verify(accountsManager).updateDevice(eq(account), eq(Device.PRIMARY_ID), any());
verify(accountsManager).updateDevice(eq(aci), eq(Device.PRIMARY_ID), any());
verify(device).setGcmId(null);
verifyNoInteractions(apnSender);
verifyNoInteractions(pushNotificationScheduler);
@@ -246,6 +253,7 @@ class PushNotificationManagerTest {
when(device.getApnId()).thenReturn("apns-token");
when(account.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(device));
when(account.getUuid()).thenReturn(aci);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(aci);
when(accountsManager.getByAccountIdentifier(aci)).thenReturn(Optional.of(account));
final PushNotification pushNotification = new PushNotification(
@@ -260,7 +268,7 @@ class PushNotificationManagerTest {
pushNotificationManager.sendNotification(pushNotification);
verifyNoInteractions(fcmSender);
verify(accountsManager).updateDevice(eq(account), eq(Device.PRIMARY_ID), any());
verify(accountsManager).updateDevice(eq(aci), eq(Device.PRIMARY_ID), any());
verify(device).setApnId(null);
verify(pushNotificationScheduler).cancelScheduledNotifications(account, device);
}
@@ -291,7 +299,7 @@ class PushNotificationManagerTest {
pushNotificationManager.sendNotification(pushNotification);
verifyNoInteractions(fcmSender);
verify(accountsManager, never()).updateDevice(eq(account), eq(Device.PRIMARY_ID), any());
verify(accountsManager, never()).updateDevice(eq(aci), eq(Device.PRIMARY_ID), any());
verify(device, never()).setApnId(any());
verify(pushNotificationScheduler, never()).cancelScheduledNotifications(account, device);
}
@@ -463,7 +463,7 @@ public class AccountCreationDeletionIntegrationTest {
assertTrue(accountsManager.getByAccountIdentifier(aci).isPresent());
accountsManager.delete(account, AccountsManager.DeletionReason.ADMIN_DELETED);
accountsManager.delete(account.getIdentifier(IdentityType.ACI), AccountsManager.DeletionReason.ADMIN_DELETED);
assertFalse(accountsManager.getByAccountIdentifier(aci).isPresent());
assertFalse(keysManager.getEcSignedPreKey(account.getUuid(), Device.PRIMARY_ID).join().isPresent());
@@ -471,7 +471,8 @@ public class AccountCreationDeletionIntegrationTest {
assertFalse(keysManager.getLastResort(account.getUuid(), Device.PRIMARY_ID).join().isPresent());
assertFalse(keysManager.getLastResort(account.getPhoneNumberIdentifier(), Device.PRIMARY_ID).join().isPresent());
verify(disconnectionRequestManager).requestDisconnection(account);
verify(disconnectionRequestManager).requestDisconnection(argThat(disconnectedAccount ->
disconnectedAccount.getIdentifier(IdentityType.ACI).equals(account.getIdentifier(IdentityType.ACI))));
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@@ -169,7 +169,7 @@ class AccountsManagerChangeNumberIntegrationTest {
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
accountsManager.changeNumber(account,
accountsManager.changeNumber(originalUuid,
secondNumber,
new IdentityKey(pniIdentityKeyPair.getPublicKey()),
Map.of(Device.PRIMARY_ID, KeysHelper.signedECPreKey(1, pniIdentityKeyPair)),
@@ -197,7 +197,7 @@ class AccountsManagerChangeNumberIntegrationTest {
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
accountsManager.changeNumber(account,
accountsManager.changeNumber(originalUuid,
originalNumber,
new IdentityKey(pniIdentityKeyPair.getPublicKey()),
Map.of(Device.PRIMARY_ID, KeysHelper.signedECPreKey(1, pniIdentityKeyPair)),
@@ -235,7 +235,7 @@ class AccountsManagerChangeNumberIntegrationTest {
final Map<Byte, KEMSignedPreKey> kemSignedPreKeys = Map.of(Device.PRIMARY_ID, rotatedKemSignedPreKey);
final Map<Byte, Integer> registrationIds = Map.of(Device.PRIMARY_ID, rotatedPniRegistrationId);
final Account updatedAccount = accountsManager.changeNumber(account, secondNumber, pniIdentityKey, preKeys, kemSignedPreKeys, registrationIds);
final Account updatedAccount = accountsManager.changeNumber(originalUuid, secondNumber, pniIdentityKey, preKeys, kemSignedPreKeys, registrationIds);
final UUID secondPni = updatedAccount.getPhoneNumberIdentifier();
assertTrue(accountsManager.getByE164(originalNumber).isEmpty());
@@ -270,7 +270,7 @@ class AccountsManagerChangeNumberIntegrationTest {
final ECKeyPair originalIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair secondIdentityKeyPair = ECKeyPair.generate();
account = accountsManager.changeNumber(account,
account = accountsManager.changeNumber(originalUuid,
secondNumber,
new IdentityKey(secondIdentityKeyPair.getPublicKey()),
Map.of(Device.PRIMARY_ID, KeysHelper.signedECPreKey(1, secondIdentityKeyPair)),
@@ -279,7 +279,7 @@ class AccountsManagerChangeNumberIntegrationTest {
final UUID secondPni = account.getPhoneNumberIdentifier();
accountsManager.changeNumber(account,
accountsManager.changeNumber(originalUuid,
originalNumber,
new IdentityKey(originalIdentityKeyPair.getPublicKey()),
Map.of(Device.PRIMARY_ID, KeysHelper.signedECPreKey(3, originalIdentityKeyPair)),
@@ -315,7 +315,7 @@ class AccountsManagerChangeNumberIntegrationTest {
final UUID existingAccountUuid = existingAccount.getUuid();
accountsManager.changeNumber(account,
accountsManager.changeNumber(originalUuid,
secondNumber,
new IdentityKey(secondIdentityKeyPair.getPublicKey()),
Map.of(Device.PRIMARY_ID, KeysHelper.signedECPreKey(1, secondIdentityKeyPair)),
@@ -337,7 +337,7 @@ class AccountsManagerChangeNumberIntegrationTest {
assertEquals(Optional.of(existingAccountUuid), accountsManager.findRecentlyDeletedAccountIdentifier(originalPni));
assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(secondPni));
accountsManager.changeNumber(accountsManager.getByAccountIdentifier(originalUuid).orElseThrow(),
accountsManager.changeNumber(originalUuid,
originalNumber,
new IdentityKey(originalIdentityKeyPair.getPublicKey()),
Map.of(Device.PRIMARY_ID, KeysHelper.signedECPreKey(1, originalIdentityKeyPair)),
@@ -364,7 +364,7 @@ class AccountsManagerChangeNumberIntegrationTest {
final UUID existingAccountUuid = existingAccount.getUuid();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
final Account changedNumberAccount = accountsManager.changeNumber(account,
final Account changedNumberAccount = accountsManager.changeNumber(originalUuid,
secondNumber,
new IdentityKey(pniIdentityKeyPair.getPublicKey()),
Map.of(Device.PRIMARY_ID, KeysHelper.signedECPreKey(1, pniIdentityKeyPair)),
@@ -383,7 +383,7 @@ class AccountsManagerChangeNumberIntegrationTest {
final ECKeyPair reRegisteredPniIdentityKeyPair = ECKeyPair.generate();
final Account changedNumberReRegisteredAccount = accountsManager.changeNumber(reRegisteredAccount,
final Account changedNumberReRegisteredAccount = accountsManager.changeNumber(reRegisteredAccount.getIdentifier(IdentityType.ACI),
secondNumber,
new IdentityKey(reRegisteredPniIdentityKeyPair.getPublicKey()),
Map.of(Device.PRIMARY_ID, KeysHelper.signedECPreKey(1, reRegisteredPniIdentityKeyPair)),
@@ -159,7 +159,7 @@ class AccountsManagerConcurrentModificationIntegrationTest {
KeysHelper.signedECPreKey(2, pniKeyPair),
KeysHelper.signedKEMPreKey(3, aciKeyPair),
KeysHelper.signedKEMPreKey(4, pniKeyPair)),
null),
null).getIdentifier(IdentityType.ACI),
a -> {
a.setUnidentifiedAccessKey(new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
a.removeDevice(Device.PRIMARY_ID);
@@ -226,18 +226,10 @@ class AccountsManagerConcurrentModificationIntegrationTest {
}
private CompletableFuture<?> modifyAccount(final UUID uuid, final Consumer<Account> accountMutation) {
return CompletableFuture.runAsync(() -> {
final Account account = accountsManager.getByAccountIdentifier(uuid).orElseThrow();
accountsManager.update(account, accountMutation);
}, mutationExecutor);
return CompletableFuture.runAsync(() -> accountsManager.update(uuid, accountMutation), mutationExecutor);
}
private CompletableFuture<?> modifyDevice(final UUID uuid, final byte deviceId, final Consumer<Device> deviceMutation) {
return CompletableFuture.runAsync(() -> {
final Account account = accountsManager.getByAccountIdentifier(uuid).orElseThrow();
accountsManager.updateDevice(account, deviceId, deviceMutation);
}, mutationExecutor);
return CompletableFuture.runAsync(() -> accountsManager.updateDevice(uuid, deviceId, deviceMutation), mutationExecutor);
}
}
@@ -44,9 +44,12 @@ import java.security.InvalidKeyException;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@@ -603,6 +606,7 @@ class AccountsManagerTest {
UUID uuid = UUID.randomUUID();
UUID pni = UUID.randomUUID();
Account account = AccountsHelper.generateTestAccount("+14152222222", uuid, pni, new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
addRetrievableAccount(account);
when(clusterCommands.get(eq("Account3::" + uuid))).thenReturn(null);
@@ -614,40 +618,21 @@ class AccountsManagerTest {
final IdentityKey identityKey = new IdentityKey(ECKeyPair.generate().getPublicKey());
account = accountsManager.update(account, a -> a.setIdentityKey(identityKey));
account = accountsManager.update(uuid, a -> a.setIdentityKey(identityKey));
assertEquals(1, account.getVersion());
assertEquals(identityKey, account.getIdentityKey(IdentityType.ACI));
verify(accounts, times(1)).getByAccountIdentifier(uuid);
verify(accounts, times(2)).getByAccountIdentifier(uuid);
verify(accounts, times(2)).update(any());
verifyNoMoreInteractions(accounts);
}
@Test
void testUpdate_dynamoOptimisticLockingFailureDuringCreate() throws AccountAlreadyExistsException {
UUID uuid = UUID.randomUUID();
Account account = AccountsHelper.generateTestAccount("+14152222222", uuid, UUID.randomUUID(), new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
when(clusterCommands.get(eq("Account3::" + uuid))).thenReturn(null);
when(accounts.getByAccountIdentifier(uuid)).thenReturn(Optional.empty())
.thenReturn(Optional.of(account));
when(accounts.create(any(), any())).thenThrow(ContestedOptimisticLockException.class);
accountsManager.update(account, a -> {
});
verify(accounts, times(1)).update(account);
verifyNoMoreInteractions(accounts);
}
@Test
void testUpdateDevice() {
final UUID uuid = UUID.randomUUID();
Account account = AccountsHelper.generateTestAccount("+14152222222", uuid, UUID.randomUUID(), new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
when(accounts.getByAccountIdentifier(uuid)).thenReturn(
Optional.of(AccountsHelper.generateTestAccount("+14152222222", uuid, UUID.randomUUID(), new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH])));
addRetrievableAccount(account);
assertTrue(account.getDevices().isEmpty());
@@ -661,14 +646,14 @@ class AccountsManagerTest {
@SuppressWarnings("unchecked") Consumer<Device> deviceUpdater = mock(Consumer.class);
@SuppressWarnings("unchecked") Consumer<Device> unknownDeviceUpdater = mock(Consumer.class);
account = accountsManager.updateDevice(account, deviceId, deviceUpdater);
account = accountsManager.updateDevice(account, deviceId, d -> d.setName("deviceName".getBytes(StandardCharsets.UTF_8)));
account = accountsManager.updateDevice(uuid, deviceId, deviceUpdater);
account = accountsManager.updateDevice(uuid, deviceId, d -> d.setName("deviceName".getBytes(StandardCharsets.UTF_8)));
assertArrayEquals("deviceName".getBytes(StandardCharsets.UTF_8), account.getDevice(deviceId).orElseThrow().getName());
verify(deviceUpdater, times(1)).accept(any(Device.class));
accountsManager.updateDevice(account, account.getNextDeviceId(), unknownDeviceUpdater);
accountsManager.updateDevice(uuid, account.getNextDeviceId(), unknownDeviceUpdater);
verify(unknownDeviceUpdater, never()).accept(any(Device.class));
}
@@ -689,7 +674,7 @@ class AccountsManagerTest {
assertTrue(account.getDevice(linkedDevice.getId()).isPresent());
account = accountsManager.removeDevice(account, linkedDevice.getId());
account = accountsManager.removeDevice(account.getIdentifier(IdentityType.ACI), linkedDevice.getId());
assertFalse(account.getDevice(linkedDevice.getId()).isPresent());
verify(messagesManager, times(2)).clear(account.getUuid(), linkedDevice.getId());
@@ -708,7 +693,8 @@ class AccountsManagerTest {
when(keysManager.deleteSingleUsePreKeys(any(), anyByte())).thenReturn(CompletableFuture.completedFuture(null));
when(messagesManager.clear(any(), anyByte())).thenReturn(CompletableFuture.completedFuture(null));
assertThrows(IllegalArgumentException.class, () -> accountsManager.removeDevice(account, Device.PRIMARY_ID));
assertThrows(IllegalArgumentException.class,
() -> accountsManager.removeDevice(account.getIdentifier(IdentityType.ACI), Device.PRIMARY_ID));
assertDoesNotThrow(account::getPrimaryDevice);
verify(messagesManager, never()).clear(any(), anyByte());
@@ -876,7 +862,7 @@ class AccountsManagerTest {
CLOCK.pin(CLOCK.instant().plusSeconds(60));
final Pair<Account, Device> updatedAccountAndDevice = accountsManager.addDevice(account, new DeviceSpec(
final Pair<Account, Device> updatedAccountAndDevice = accountsManager.addDevice(aci, new DeviceSpec(
deviceNameCiphertext,
password,
signalAgent,
@@ -922,10 +908,12 @@ class AccountsManagerTest {
@MethodSource
void testUpdateDeviceLastSeen(final boolean expectUpdate, final long initialLastSeen, final long updatedLastSeen) {
final Account account = AccountsHelper.generateTestAccount("+14152222222", UUID.randomUUID(), UUID.randomUUID(), new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
addRetrievableAccount(account);
final Device device = generateTestDevice(initialLastSeen);
account.addDevice(device);
accountsManager.updateDeviceLastSeen(account, device, updatedLastSeen);
accountsManager.updateDeviceLastSeen(account.getIdentifier(IdentityType.ACI), device, updatedLastSeen);
assertEquals(expectUpdate ? updatedLastSeen : initialLastSeen, device.getLastSeen());
verify(accounts, expectUpdate ? times(1) : never()).update(account);
@@ -957,7 +945,8 @@ class AccountsManagerTest {
final KEMSignedPreKey kemLastResortPreKey = KeysHelper.signedKEMPreKey(2, pniIdentityKeyPair);
Account account = AccountsHelper.generateTestAccount(originalNumber, uuid, originalPni, List.of(DevicesHelper.createDevice(Device.PRIMARY_ID)), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
account = accountsManager.changeNumber(account,
addRetrievableAccount(account);
account = accountsManager.changeNumber(uuid,
targetNumber,
new IdentityKey(pniIdentityKeyPair.getPublicKey()),
Map.of(Device.PRIMARY_ID, ecSignedPreKey),
@@ -985,9 +974,11 @@ class AccountsManagerTest {
Account account = AccountsHelper.generateTestAccount(originalNumber, UUID.randomUUID(), phoneNumberIdentifier,
List.of(DevicesHelper.createDevice(Device.PRIMARY_ID)), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
addRetrievableAccount(account);
phoneNumberIdentifiersByE164.put(originalNumber, account.getPhoneNumberIdentifier());
phoneNumberIdentifiersByE164.put(newNumber, account.getPhoneNumberIdentifier());
account = accountsManager.changeNumber(account,
account = accountsManager.changeNumber(account.getIdentifier(IdentityType.ACI),
newNumber,
new IdentityKey(pniIdentityKeyPair.getPublicKey()),
Map.of(Device.PRIMARY_ID, KeysHelper.signedECPreKey(1, pniIdentityKeyPair)),
@@ -1016,7 +1007,9 @@ class AccountsManagerTest {
final KEMSignedPreKey kemLastResoryPreKey = KeysHelper.signedKEMPreKey(2, pniIdentityKeyPair);
Account account = AccountsHelper.generateTestAccount(originalNumber, uuid, originalPni, List.of(DevicesHelper.createDevice(Device.PRIMARY_ID)), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
account = accountsManager.changeNumber(account,
addRetrievableAccount(account);
account = accountsManager.changeNumber(uuid,
targetNumber,
new IdentityKey(pniIdentityKeyPair.getPublicKey()),
Map.of(Device.PRIMARY_ID, ecSignedPreKey),
@@ -1064,8 +1057,9 @@ class AccountsManagerTest {
DevicesHelper.createDevice(Device.PRIMARY_ID, 0L, 101),
DevicesHelper.createDevice(deviceId2, 0L, 102));
final Account account = AccountsHelper.generateTestAccount(originalNumber, uuid, originalPni, devices, new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
addRetrievableAccount(account);
final Account updatedAccount = accountsManager.changeNumber(
account, targetNumber, new IdentityKey(ECKeyPair.generate().getPublicKey()), newSignedKeys, newSignedPqKeys, newRegistrationIds);
uuid, targetNumber, new IdentityKey(ECKeyPair.generate().getPublicKey()), newSignedKeys, newSignedPqKeys, newRegistrationIds);
assertEquals(targetNumber, updatedAccount.getNumber());
@@ -1102,11 +1096,12 @@ class AccountsManagerTest {
final List<Device> devices = List.of(DevicesHelper.createDevice(Device.PRIMARY_ID, 0L, 101),
DevicesHelper.createDevice(deviceId2, 0L, 102));
final Account account = AccountsHelper.generateTestAccount(originalNumber, uuid, originalPni, devices, new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
addRetrievableAccount(account);
assertThrows(MismatchedDevicesException.class,
() -> accountsManager.changeNumber(
account, targetNumber, new IdentityKey(ECKeyPair.generate().getPublicKey()), newSignedKeys, newSignedPqKeys, newRegistrationIds));
uuid, targetNumber, new IdentityKey(ECKeyPair.generate().getPublicKey()), newSignedKeys, newSignedPqKeys, newRegistrationIds));
verifyNoInteractions(accounts);
verify(accounts, never()).changeNumber(any(), any(), any(), any(), any());
verifyNoInteractions(keysManager);
}
@@ -1117,8 +1112,9 @@ class AccountsManagerTest {
final UUID uuid = UUID.randomUUID();
final Account account = AccountsHelper.generateTestAccount(originalNumber, uuid, UUID.randomUUID(), new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
addRetrievableAccount(account);
assertThrows(AssertionError.class, () -> accountsManager.update(account, a -> a.setNumber(targetNumber, UUID.randomUUID())));
assertThrows(AssertionError.class, () -> accountsManager.update(uuid, a -> a.setNumber(targetNumber, UUID.randomUUID())));
}
@Test
@@ -1128,7 +1124,7 @@ class AccountsManagerTest {
final List<byte[]> usernameHashes = List.of(TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(32));
final UsernameReservation result = accountsManager.reserveUsernameHash(account, usernameHashes);
final UsernameReservation result = accountsManager.reserveUsernameHash(account.getIdentifier(IdentityType.ACI), usernameHashes);
assertArrayEquals(usernameHashes.getFirst(), result.reservedUsernameHash());
verify(accounts, times(1)).reserveUsernameHash(eq(account), any(), eq(Duration.ofMinutes(5)));
}
@@ -1142,7 +1138,7 @@ class AccountsManagerTest {
final List<byte[]> usernameHashes = List.of(TestRandomUtil.nextBytes(32), oldUsernameHash, TestRandomUtil.nextBytes(32));
final UsernameReservation result = accountsManager.reserveUsernameHash(account, usernameHashes);
final UsernameReservation result = accountsManager.reserveUsernameHash(account.getIdentifier(IdentityType.ACI), usernameHashes);
assertArrayEquals(oldUsernameHash, result.reservedUsernameHash());
verify(accounts, never()).reserveUsernameHash(any(), any(), any());
}
@@ -1158,7 +1154,7 @@ class AccountsManagerTest {
.doNothing()
.when(accounts).reserveUsernameHash(any(), any(), any());
final UsernameReservation result = accountsManager.reserveUsernameHash(account, usernameHashes);
final UsernameReservation result = accountsManager.reserveUsernameHash(account.getIdentifier(IdentityType.ACI), usernameHashes);
assertArrayEquals(usernameHashes.getFirst(), result.reservedUsernameHash());
verify(accounts, times(2)).reserveUsernameHash(eq(account), any(), eq(Duration.ofMinutes(5)));
}
@@ -1166,21 +1162,23 @@ class AccountsManagerTest {
@Test
void testReserveUsernameHashAsyncNotAvailable() throws UsernameHashNotAvailableException {
final Account account = AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(), new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
when(accounts.getByAccountIdentifierAsync(account.getUuid())).thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
addRetrievableAccount(account);
doThrow(new UsernameHashNotAvailableException())
.when(accounts).reserveUsernameHash(any(), any(), any());
assertThrows(UsernameHashNotAvailableException.class, () ->
accountsManager.reserveUsernameHash(account, List.of(USERNAME_HASH_1, USERNAME_HASH_2)));
accountsManager.reserveUsernameHash(account.getIdentifier(IdentityType.ACI), List.of(USERNAME_HASH_1, USERNAME_HASH_2)));
}
@Test
void testConfirmReservedUsernameHash() throws UsernameHashNotAvailableException, UsernameReservationNotFoundException {
final Account account = AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(), new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
addRetrievableAccount(account);
setReservationHash(account, USERNAME_HASH_1);
accountsManager.confirmReservedUsernameHash(account, USERNAME_HASH_1, ENCRYPTED_USERNAME_1);
accountsManager.confirmReservedUsernameHash(account.getIdentifier(IdentityType.ACI), USERNAME_HASH_1, ENCRYPTED_USERNAME_1);
verify(accounts).confirmUsernameHash(eq(account), eq(USERNAME_HASH_1), eq(ENCRYPTED_USERNAME_1));
}
@@ -1194,62 +1192,72 @@ class AccountsManagerTest {
.doNothing()
.when(accounts).confirmUsernameHash(account, USERNAME_HASH_1, ENCRYPTED_USERNAME_1);
accountsManager.confirmReservedUsernameHash(account, USERNAME_HASH_1, ENCRYPTED_USERNAME_1);
accountsManager.confirmReservedUsernameHash(account.getIdentifier(IdentityType.ACI), USERNAME_HASH_1, ENCRYPTED_USERNAME_1);
verify(accounts, times(2)).confirmUsernameHash(eq(account), eq(USERNAME_HASH_1), eq(ENCRYPTED_USERNAME_1));
}
@Test
void testConfirmReservedHashNameMismatch() {
final Account account = AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(), new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
addRetrievableAccount(account);
setReservationHash(account, USERNAME_HASH_1);
assertThrows(UsernameReservationNotFoundException.class,
() -> accountsManager.confirmReservedUsernameHash(account, USERNAME_HASH_2, ENCRYPTED_USERNAME_2));
() -> accountsManager.confirmReservedUsernameHash(account.getIdentifier(IdentityType.ACI), USERNAME_HASH_2, ENCRYPTED_USERNAME_2));
}
@Test
void testConfirmReservedLapsed() throws UsernameHashNotAvailableException {
final Account account = AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(), new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
addRetrievableAccount(account);
// hash was reserved, but the reservation lapsed and another account took it
setReservationHash(account, USERNAME_HASH_1);
doThrow(new UsernameHashNotAvailableException())
.when(accounts).confirmUsernameHash(account, USERNAME_HASH_1, ENCRYPTED_USERNAME_1);
assertThrows(UsernameHashNotAvailableException.class,
() -> accountsManager.confirmReservedUsernameHash(account, USERNAME_HASH_1, ENCRYPTED_USERNAME_1));
() -> accountsManager.confirmReservedUsernameHash(account.getIdentifier(IdentityType.ACI), USERNAME_HASH_1, ENCRYPTED_USERNAME_1));
assertTrue(account.getUsernameHash().isEmpty());
}
@Test
void testConfirmReservedRetry() throws UsernameHashNotAvailableException, UsernameReservationNotFoundException {
final Account account = AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(), new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
addRetrievableAccount(account);
account.setUsernameHash(USERNAME_HASH_1);
// reserved username already set, should be treated as a replay
accountsManager.confirmReservedUsernameHash(account, USERNAME_HASH_1, ENCRYPTED_USERNAME_1);
verifyNoInteractions(accounts);
accountsManager.confirmReservedUsernameHash(account.getIdentifier(IdentityType.ACI), USERNAME_HASH_1, ENCRYPTED_USERNAME_1);
verify(accounts, never()).confirmUsernameHash(any(), any(), any());
}
@Test
void testConfirmReservedUsernameHashWithNoReservation() throws UsernameHashNotAvailableException {
final Account account = AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(),
new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
addRetrievableAccount(account);
assertThrows(UsernameReservationNotFoundException.class,
() -> accountsManager.confirmReservedUsernameHash(account, USERNAME_HASH_1, ENCRYPTED_USERNAME_1));
() -> accountsManager.confirmReservedUsernameHash(account.getIdentifier(IdentityType.ACI), USERNAME_HASH_1, ENCRYPTED_USERNAME_1));
verify(accounts, never()).confirmUsernameHash(any(), any(), any());
}
@Test
void testClearUsernameHash() {
final Account account = AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(), new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
addRetrievableAccount(account);
account.setUsernameHash(USERNAME_HASH_1);
accountsManager.clearUsernameHash(account);
accountsManager.clearUsernameHash(account.getIdentifier(IdentityType.ACI));
verify(accounts).clearUsernameHash(eq(account));
}
@Test
void testSetUsernameViaUpdate() {
final Account account = AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(), new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
addRetrievableAccount(account);
assertThrows(AssertionError.class, () -> accountsManager.update(account, a -> a.setUsernameHash(USERNAME_HASH_1)));
assertThrows(AssertionError.class, () ->
accountsManager.update(account.getIdentifier(IdentityType.ACI), a -> a.setUsernameHash(USERNAME_HASH_1)));
}
@Test
@@ -1440,4 +1448,54 @@ class AccountsManagerTest {
new MismatchedDevices(Set.of(deviceId), Set.of((byte) (extraDeviceId)), Collections.emptySet())))
);
}
@ParameterizedTest
@MethodSource
void updateCurrentProfileVersion(final byte[] currentVersion, final byte[] expectedVersion, final byte[] newVersion, final boolean expectException) throws Exception {
final Account account = AccountsHelper.generateTestAccount("+14152222222", UUID.randomUUID(), UUID.randomUUID(), new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
final UUID accountIdentifier = account.getIdentifier(IdentityType.ACI);
addRetrievableAccount(account);
account.setCurrentProfileVersion(HexFormat.of().formatHex(currentVersion));
final AccountBadge badge = new AccountBadge("test", CLOCK.instant().plusSeconds(60), true);
assertTrue(account.getBadges().isEmpty());
if (expectException) {
assertThrows(WriteConflictException.class, () -> accountsManager.updateCurrentProfileVersion(accountIdentifier, newVersion, HexFormat.of().formatHex(expectedVersion), _ -> {}));
} else {
final Account updatedAccount = accountsManager.updateCurrentProfileVersion(accountIdentifier, newVersion,
HexFormat.of().formatHex(expectedVersion), a -> {
a.setBadges(CLOCK, new ArrayList<>(List.of(badge)));
});
assertArrayEquals(newVersion, HexFormat.of().parseHex(updatedAccount.getCurrentProfileVersion().orElseThrow()));
assertEquals(List.of(badge), updatedAccount.getBadges());
}
}
static Collection<Arguments> updateCurrentProfileVersion() {
final byte[] empty = new byte[0];
final byte[] version1 = TestRandomUtil.nextBytes(16);
final byte[] version2 = Arrays.copyOf(version1, version1.length);
version2[0] = (byte) (version2[0] + 1);
return List.of(
Arguments.argumentSet("no current version - matches", empty, empty, version1, false),
Arguments.argumentSet("no current version - conflict", empty, version1, version1, true),
Arguments.argumentSet("current version - empty conflict", version1, empty, version2, true),
Arguments.argumentSet("current version - matches", version1, version1, version2, false)
);
}
private void addRetrievableAccount(final Account account) {
when(accounts.getByAccountIdentifier(account.getIdentifier(IdentityType.ACI)))
.thenReturn(Optional.of(account));
when(accounts.getByAccountIdentifierAsync(account.getIdentifier(IdentityType.ACI)))
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
}
}
@@ -37,6 +37,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.Mockito;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
@@ -176,7 +177,7 @@ class AccountsManagerUsernameIntegrationTest {
}
assertThrows(UsernameHashNotAvailableException.class,
() -> accountsManager.reserveUsernameHash(account, usernameHashes));
() -> accountsManager.reserveUsernameHash(account.getIdentifier(IdentityType.ACI), usernameHashes));
assertThat(accountsManager.getByAccountIdentifier(account.getUuid()).orElseThrow().getUsernameHash()).isEmpty();
}
@@ -201,7 +202,7 @@ class AccountsManagerUsernameIntegrationTest {
usernameHashes.add(TestRandomUtil.nextBytes(32));
final byte[] username = accountsManager
.reserveUsernameHash(account, usernameHashes)
.reserveUsernameHash(account.getIdentifier(IdentityType.ACI), usernameHashes)
.reservedUsernameHash();
assertArrayEquals(username, availableHash);
@@ -214,14 +215,14 @@ class AccountsManagerUsernameIntegrationTest {
// reserve
AccountsManager.UsernameReservation reservation =
accountsManager.reserveUsernameHash(account, List.of(USERNAME_HASH_1));
accountsManager.reserveUsernameHash(account.getIdentifier(IdentityType.ACI), List.of(USERNAME_HASH_1));
assertArrayEquals(reservation.account().getReservedUsernameHash().orElseThrow(), USERNAME_HASH_1);
assertThat(accountsManager.getByUsernameHash(reservation.reservedUsernameHash()).join()).isEmpty();
// confirm
account = accountsManager.confirmReservedUsernameHash(
reservation.account(),
reservation.account().getIdentifier(IdentityType.ACI),
reservation.reservedUsernameHash(),
ENCRYPTED_USERNAME_1);
assertArrayEquals(account.getUsernameHash().orElseThrow(), USERNAME_HASH_1);
@@ -232,7 +233,7 @@ class AccountsManagerUsernameIntegrationTest {
.isEqualTo(account.getUuid());
// clear
account = accountsManager.clearUsernameHash(account);
account = accountsManager.clearUsernameHash(account.getIdentifier(IdentityType.ACI));
assertThat(accountsManager.getByUsernameHash(USERNAME_HASH_1).join()).isEmpty();
assertThat(accountsManager.getByAccountIdentifier(account.getUuid()).orElseThrow().getUsernameHash()).isEmpty();
}
@@ -243,16 +244,16 @@ class AccountsManagerUsernameIntegrationTest {
Account account = AccountsHelper.createAccount(accountsManager, "+18005551111");
AccountsManager.UsernameReservation reservation =
accountsManager.reserveUsernameHash(account, List.of(USERNAME_HASH_1));
accountsManager.reserveUsernameHash(account.getIdentifier(IdentityType.ACI), List.of(USERNAME_HASH_1));
// confirm
account = accountsManager.confirmReservedUsernameHash(
reservation.account(),
reservation.account().getIdentifier(IdentityType.ACI),
reservation.reservedUsernameHash(),
ENCRYPTED_USERNAME_1);
// clear
account = accountsManager.clearUsernameHash(account);
account = accountsManager.clearUsernameHash(account.getIdentifier(IdentityType.ACI));
assertThat(accountsManager.getByUsernameHash(USERNAME_HASH_1).join()).isEmpty();
assertThat(accountsManager.getByAccountIdentifier(account.getUuid()).orElseThrow().getUsernameHash()).isEmpty();
@@ -260,7 +261,7 @@ class AccountsManagerUsernameIntegrationTest {
Account account2 = AccountsHelper.createAccount(accountsManager, "+18005552222");
assertThrows(UsernameHashNotAvailableException.class,
() -> accountsManager.reserveUsernameHash(account2, List.of(USERNAME_HASH_1)),
() -> accountsManager.reserveUsernameHash(account2.getIdentifier(IdentityType.ACI), List.of(USERNAME_HASH_1)),
"account2 should not be able to reserve a held hash");
}
@@ -270,7 +271,7 @@ class AccountsManagerUsernameIntegrationTest {
final Account account = AccountsHelper.createAccount(accountsManager, "+18005551111");
AccountsManager.UsernameReservation reservation1 =
accountsManager.reserveUsernameHash(account, List.of(USERNAME_HASH_1));
accountsManager.reserveUsernameHash(account.getIdentifier(IdentityType.ACI), List.of(USERNAME_HASH_1));
long past = Instant.now().minus(Duration.ofMinutes(1)).getEpochSecond();
// force expiration
@@ -286,12 +287,12 @@ class AccountsManagerUsernameIntegrationTest {
Account account2 = AccountsHelper.createAccount(accountsManager, "+18005552222");
final AccountsManager.UsernameReservation reservation2 =
accountsManager.reserveUsernameHash(account2, List.of(USERNAME_HASH_1));
accountsManager.reserveUsernameHash(account2.getIdentifier(IdentityType.ACI), List.of(USERNAME_HASH_1));
assertArrayEquals(reservation2.reservedUsernameHash(), USERNAME_HASH_1);
assertThrows(UsernameHashNotAvailableException.class,
() -> accountsManager.confirmReservedUsernameHash(reservation1.account(), USERNAME_HASH_1, ENCRYPTED_USERNAME_1));
account2 = accountsManager.confirmReservedUsernameHash(reservation2.account(), USERNAME_HASH_1, ENCRYPTED_USERNAME_1);
() -> accountsManager.confirmReservedUsernameHash(reservation1.account().getIdentifier(IdentityType.ACI), USERNAME_HASH_1, ENCRYPTED_USERNAME_1));
account2 = accountsManager.confirmReservedUsernameHash(reservation2.account().getIdentifier(IdentityType.ACI), USERNAME_HASH_1, ENCRYPTED_USERNAME_1);
assertEquals(accountsManager.getByUsernameHash(USERNAME_HASH_1).join().orElseThrow().getUuid(), account2.getUuid());
assertArrayEquals(account2.getUsernameHash().orElseThrow(), USERNAME_HASH_1);
}
@@ -303,13 +304,13 @@ class AccountsManagerUsernameIntegrationTest {
// Set username hash
final AccountsManager.UsernameReservation reservation1 =
accountsManager.reserveUsernameHash(account, List.of(USERNAME_HASH_1));
accountsManager.reserveUsernameHash(account.getIdentifier(IdentityType.ACI), List.of(USERNAME_HASH_1));
account = accountsManager.confirmReservedUsernameHash(reservation1.account(), USERNAME_HASH_1, ENCRYPTED_USERNAME_1);
account = accountsManager.confirmReservedUsernameHash(reservation1.account().getIdentifier(IdentityType.ACI), USERNAME_HASH_1, ENCRYPTED_USERNAME_1);
// Reserve another hash on the same account
final AccountsManager.UsernameReservation reservation2 =
accountsManager.reserveUsernameHash(account, List.of(USERNAME_HASH_2));
accountsManager.reserveUsernameHash(account.getIdentifier(IdentityType.ACI), List.of(USERNAME_HASH_2));
account = reservation2.account();
@@ -318,12 +319,12 @@ class AccountsManagerUsernameIntegrationTest {
assertArrayEquals(account.getEncryptedUsername().orElseThrow(), ENCRYPTED_USERNAME_1);
// Clear the set username hash but not the reserved one
account = accountsManager.clearUsernameHash(account);
account = accountsManager.clearUsernameHash(account.getIdentifier(IdentityType.ACI));
assertThat(account.getReservedUsernameHash()).isPresent();
assertThat(account.getUsernameHash()).isEmpty();
// Confirm second reservation
account = accountsManager.confirmReservedUsernameHash(account, reservation2.reservedUsernameHash(), ENCRYPTED_USERNAME_2);
account = accountsManager.confirmReservedUsernameHash(account.getIdentifier(IdentityType.ACI), reservation2.reservedUsernameHash(), ENCRYPTED_USERNAME_2);
assertArrayEquals(account.getUsernameHash().orElseThrow(), USERNAME_HASH_2);
assertArrayEquals(account.getEncryptedUsername().orElseThrow(), ENCRYPTED_USERNAME_2);
}
@@ -333,8 +334,8 @@ class AccountsManagerUsernameIntegrationTest {
throws InterruptedException, UsernameHashNotAvailableException, UsernameReservationNotFoundException {
Account account = AccountsHelper.createAccount(accountsManager, "+18005551111");
final AccountsManager.UsernameReservation reservation1 =
accountsManager.reserveUsernameHash(account, List.of(USERNAME_HASH_1));
account = accountsManager.confirmReservedUsernameHash(reservation1.account(), USERNAME_HASH_1, ENCRYPTED_USERNAME_1);
accountsManager.reserveUsernameHash(account.getIdentifier(IdentityType.ACI), List.of(USERNAME_HASH_1));
account = accountsManager.confirmReservedUsernameHash(reservation1.account().getIdentifier(IdentityType.ACI), USERNAME_HASH_1, ENCRYPTED_USERNAME_1);
// "reclaim" the account by re-registering
Account reclaimed = AccountsHelper.createAccount(accountsManager, "+18005551111");
@@ -346,20 +347,29 @@ class AccountsManagerUsernameIntegrationTest {
assertThat(accountsManager.getByUsernameHash(USERNAME_HASH_1).join()).isEmpty();
// confirm it again
accountsManager.confirmReservedUsernameHash(reclaimed, USERNAME_HASH_1, ENCRYPTED_USERNAME_1);
accountsManager.confirmReservedUsernameHash(reclaimed.getIdentifier(IdentityType.ACI), USERNAME_HASH_1, ENCRYPTED_USERNAME_1);
assertThat(accountsManager.getByUsernameHash(USERNAME_HASH_1).join()).isPresent();
}
@Test
public void testUsernameLinks() throws InterruptedException, AccountAlreadyExistsException {
final Account account = AccountsHelper.createAccount(accountsManager, "+18005551111");
public void testUsernameLinks()
throws InterruptedException, AccountAlreadyExistsException, UsernameHashNotAvailableException, UsernameReservationNotFoundException {
final UUID accountIdentifier;
{
final Account account = AccountsHelper.createAccount(accountsManager, "+18005551111");
accounts.create(account, Collections.emptyList());
account.setUsernameHash(TestRandomUtil.nextBytes(16));
accounts.create(account, Collections.emptyList());
accountIdentifier = account.getIdentifier(IdentityType.ACI);
}
final AccountsManager.UsernameReservation reservation =
accountsManager.reserveUsernameHash(accountIdentifier, List.of(USERNAME_HASH_1));
accountsManager.confirmReservedUsernameHash(accountIdentifier, reservation.reservedUsernameHash(), ENCRYPTED_USERNAME_1);
final UUID linkHandle = UUID.randomUUID();
final byte[] encryptedUsername = TestRandomUtil.nextBytes(32);
accountsManager.update(account, a -> a.setUsernameLinkDetails(linkHandle, encryptedUsername));
accountsManager.update(accountIdentifier, account -> account.setUsernameLinkDetails(linkHandle, encryptedUsername));
final Optional<Account> maybeAccount = accountsManager.getByUsernameLinkHandle(linkHandle).join();
assertTrue(maybeAccount.isPresent());
@@ -367,17 +377,17 @@ class AccountsManagerUsernameIntegrationTest {
assertArrayEquals(encryptedUsername, maybeAccount.get().getEncryptedUsername().get());
// making some unrelated change and updating account to check that username link data is still there
final Optional<Account> accountToChange = accountsManager.getByAccountIdentifier(account.getUuid());
final Optional<Account> accountToChange = accountsManager.getByAccountIdentifier(accountIdentifier);
assertTrue(accountToChange.isPresent());
accountsManager.update(accountToChange.get(), a -> a.setDiscoverableByPhoneNumber(!a.isDiscoverableByPhoneNumber()));
accountsManager.update(accountToChange.get().getIdentifier(IdentityType.ACI), a -> a.setDiscoverableByPhoneNumber(!a.isDiscoverableByPhoneNumber()));
final Optional<Account> accountAfterChange = accountsManager.getByUsernameLinkHandle(linkHandle).join();
assertTrue(accountAfterChange.isPresent());
assertTrue(accountAfterChange.get().getEncryptedUsername().isPresent());
assertArrayEquals(encryptedUsername, accountAfterChange.get().getEncryptedUsername().get());
// now deleting the link
final Optional<Account> accountToDeleteLink = accountsManager.getByAccountIdentifier(account.getUuid());
accountsManager.update(accountToDeleteLink.orElseThrow(), a -> a.setUsernameLinkDetails(null, null));
final Optional<Account> accountToDeleteLink = accountsManager.getByAccountIdentifier(accountIdentifier);
accountsManager.update(accountToDeleteLink.orElseThrow().getIdentifier(IdentityType.ACI), a -> a.setUsernameLinkDetails(null, null));
assertTrue(accounts.getByUsernameLinkHandle(linkHandle).join().isEmpty());
}
}
@@ -479,6 +479,7 @@ class AccountsTest {
// the backup credential request and share-set are always preserved across account reclaims
existingAccount.setBackupCredentialRequests(TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(32));
existingAccount.setZkCredentialKey(TestRandomUtil.nextBytes(32));
createAccount(existingAccount);
final Account secondAccount =
generateAccount(e164, UUID.randomUUID(), UUID.randomUUID(), List.of(generateDevice(DEVICE_ID_1)));
@@ -490,6 +491,7 @@ class AccountsTest {
.isEqualTo(existingAccount.getBackupCredentialRequest(BackupCredentialType.MESSAGES).orElseThrow());
assertThat(reclaimed.getBackupCredentialRequest(BackupCredentialType.MEDIA).orElseThrow())
.isEqualTo(existingAccount.getBackupCredentialRequest(BackupCredentialType.MEDIA).orElseThrow());
assertThat(reclaimed.getZkCredentialKey()).isEqualTo(existingAccount.getZkCredentialKey());
}
@Test
@@ -500,9 +502,11 @@ class AccountsTest {
final UUID existingPni = UUID.randomUUID();
final Account existingAccount = generateAccount(e164, existingUuid, existingPni, List.of(device));
// Backup vouchers should be carried over accross re-registration
// Backup vouchers should be carried over across re-registration
final Account.BackupVoucher bv = new Account.BackupVoucher(1, Instant.now().plus(Duration.ofDays(1)));
existingAccount.setBackupVoucher(bv);
// ZK credential keys should be carried over across re-registration
existingAccount.setZkCredentialKey(TestRandomUtil.nextBytes(32));
createAccount(existingAccount);
@@ -184,7 +184,7 @@ public class AddRemoveDeviceIntegrationTest {
assertEquals(1, accountsManager.getByAccountIdentifier(account.getUuid()).orElseThrow().getDevices().size());
final Pair<Account, Device> updatedAccountAndDevice =
accountsManager.addDevice(account, new DeviceSpec(
accountsManager.addDevice(account.getIdentifier(IdentityType.ACI), new DeviceSpec(
"device-name".getBytes(StandardCharsets.UTF_8),
"password",
"OWT",
@@ -234,7 +234,7 @@ public class AddRemoveDeviceIntegrationTest {
final String linkDeviceToken = accountsManager.generateLinkDeviceToken(account.getIdentifier(IdentityType.ACI));
final Pair<Account, Device> updatedAccountAndDevice =
accountsManager.addDevice(account, new DeviceSpec(
accountsManager.addDevice(account.getIdentifier(IdentityType.ACI), new DeviceSpec(
"device-name".getBytes(StandardCharsets.UTF_8),
"password",
"OWT",
@@ -255,7 +255,7 @@ public class AddRemoveDeviceIntegrationTest {
.size());
assertThrows(LinkDeviceTokenAlreadyUsedException.class,
() -> accountsManager.addDevice(account, new DeviceSpec(
() -> accountsManager.addDevice(account.getIdentifier(IdentityType.ACI), new DeviceSpec(
"device-name".getBytes(StandardCharsets.UTF_8),
"password",
"OWT",
@@ -289,7 +289,7 @@ public class AddRemoveDeviceIntegrationTest {
assertEquals(1, accountsManager.getByAccountIdentifier(account.getUuid()).orElseThrow().getDevices().size());
final Pair<Account, Device> updatedAccountAndDevice =
accountsManager.addDevice(account, new DeviceSpec(
accountsManager.addDevice(account.getIdentifier(IdentityType.ACI), new DeviceSpec(
"device-name".getBytes(StandardCharsets.UTF_8),
"password",
"OWT",
@@ -307,7 +307,7 @@ public class AddRemoveDeviceIntegrationTest {
final byte addedDeviceId = updatedAccountAndDevice.second().getId();
final Account updatedAccount = accountsManager.removeDevice(updatedAccountAndDevice.first(), addedDeviceId);
final Account updatedAccount = accountsManager.removeDevice(updatedAccountAndDevice.first().getIdentifier(IdentityType.ACI), addedDeviceId);
assertEquals(1, updatedAccount.getDevices().size());
@@ -340,7 +340,7 @@ public class AddRemoveDeviceIntegrationTest {
final UUID aci = account.getIdentifier(IdentityType.ACI);
final Pair<Account, Device> updatedAccountAndDevice =
accountsManager.addDevice(account, new DeviceSpec(
accountsManager.addDevice(account.getIdentifier(IdentityType.ACI), new DeviceSpec(
"device-name".getBytes(StandardCharsets.UTF_8),
"password",
"OWT",
@@ -362,7 +362,7 @@ public class AddRemoveDeviceIntegrationTest {
.thenReturn(CompletableFuture.failedFuture(new RuntimeException("OH NO")));
assertThrows(RuntimeException.class,
() -> accountsManager.removeDevice(updatedAccountAndDevice.first(), addedDeviceId));
() -> accountsManager.removeDevice(updatedAccountAndDevice.first().getIdentifier(IdentityType.ACI), addedDeviceId));
final Account retrievedAccount = accountsManager.getByAccountIdentifierAsync(aci).join().orElseThrow();
@@ -410,7 +410,7 @@ public class AddRemoveDeviceIntegrationTest {
assertEquals(Optional.empty(), displacedFuture.join());
final Pair<Account, Device> updatedAccountAndDevice =
accountsManager.addDevice(account, new DeviceSpec(
accountsManager.addDevice(account.getIdentifier(IdentityType.ACI), new DeviceSpec(
"device-name".getBytes(StandardCharsets.UTF_8),
"password",
"OWT",
@@ -451,7 +451,7 @@ public class AddRemoveDeviceIntegrationTest {
final String linkDeviceTokenIdentifier = AccountsManager.getLinkDeviceTokenIdentifier(linkDeviceToken);
final Pair<Account, Device> updatedAccountAndDevice =
accountsManager.addDevice(account, new DeviceSpec(
accountsManager.addDevice(account.getIdentifier(IdentityType.ACI), new DeviceSpec(
"device-name".getBytes(StandardCharsets.UTF_8),
"password",
"OWT",
@@ -520,7 +520,7 @@ public class AddRemoveDeviceIntegrationTest {
final String linkDeviceToken = accountsManager.generateLinkDeviceToken(UUID.randomUUID());
final String linkDeviceTokenIdentifier = AccountsManager.getLinkDeviceTokenIdentifier(linkDeviceToken);
accountsManager.addDevice(account, new DeviceSpec(
accountsManager.addDevice(account.getIdentifier(IdentityType.ACI), new DeviceSpec(
"device-name".getBytes(StandardCharsets.UTF_8),
"password",
"OWT",
@@ -563,7 +563,7 @@ public class AddRemoveDeviceIntegrationTest {
final String linkDeviceTokenIdentifier = AccountsManager.getLinkDeviceTokenIdentifier(linkDeviceToken);
clock.pin(Instant.ofEpochMilli(0));
accountsManager.addDevice(account, new DeviceSpec(
accountsManager.addDevice(account.getIdentifier(IdentityType.ACI), new DeviceSpec(
"device-name".getBytes(StandardCharsets.UTF_8),
"password",
"OWT",
@@ -4,17 +4,23 @@
*/
package org.whispersystems.textsecuregcm.storage;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyByte;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.protobuf.ByteString;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.container.ContainerRequestContext;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.HashMap;
@@ -27,20 +33,33 @@ import org.junit.jupiter.api.Test;
import org.mockito.stubbing.Answer;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.IncomingMessage;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.push.MessageSender;
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.TestClock;
public class ChangeNumberManagerTest {
private AccountsManager accountsManager;
private MessageSender messageSender;
private AccountsManager accountsManager;
private PhoneVerificationTokenManager phoneVerificationTokenManager;
private RegistrationLockVerificationManager registrationLockVerificationManager;
private RateLimiter rateLimiter;
private ChangeNumberManager changeNumberManager;
private Map<Account, UUID> updatedPhoneNumberIdentifiersByAccount;
@@ -49,15 +68,34 @@ public class ChangeNumberManagerTest {
@BeforeEach
void setUp() throws Exception {
accountsManager = mock(AccountsManager.class);
messageSender = mock(MessageSender.class);
changeNumberManager = new ChangeNumberManager(messageSender, accountsManager, CLOCK);
accountsManager = mock(AccountsManager.class);
registrationLockVerificationManager = mock(RegistrationLockVerificationManager.class);
rateLimiter = mock(RateLimiter.class);
phoneVerificationTokenManager = mock(PhoneVerificationTokenManager.class);
when(phoneVerificationTokenManager.verify(any(), any(), any(), any())).thenAnswer(invocation -> {
final byte[] sessionId = invocation.getArgument(2);
return sessionId != null
? PhoneVerificationRequest.VerificationType.SESSION
: PhoneVerificationRequest.VerificationType.RECOVERY_PASSWORD;
});
final RateLimiters rateLimiters = mock(RateLimiters.class);
when(rateLimiters.getRegistrationLimiter()).thenReturn(rateLimiter);
changeNumberManager = new ChangeNumberManager(messageSender, accountsManager,
phoneVerificationTokenManager, registrationLockVerificationManager, rateLimiters, CLOCK);
updatedPhoneNumberIdentifiersByAccount = new HashMap<>();
when(accountsManager.changeNumber(any(), any(), any(), any(), any(), any())).thenAnswer((Answer<Account>)invocation -> {
final Account account = invocation.getArgument(0, Account.class);
final String number = invocation.getArgument(1, String.class);
final UUID accountIdentifier = invocation.getArgument(0);
final String number = invocation.getArgument(1);
final Account account =
accountsManager.getAccountsForChangeNumber(accountIdentifier, number).first();
final UUID uuid = account.getIdentifier(IdentityType.ACI);
final List<Device> devices = account.getDevices();
@@ -84,6 +122,9 @@ public class ChangeNumberManagerTest {
@Test
void changeNumberSingleDevice() throws Exception {
final String originalNumber = PhoneNumberUtil.getInstance().format(
PhoneNumberUtil.getInstance().getExampleNumber("DE"), PhoneNumberUtil.PhoneNumberFormat.E164);
final String targetNumber = PhoneNumberUtil.getInstance().format(
PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164);
@@ -99,16 +140,24 @@ public class ChangeNumberManagerTest {
final UUID accountIdentifier = UUID.randomUUID();
final Account account = mock(Account.class);
when(account.getNumber()).thenReturn(originalNumber);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
when(account.isIdentifiedBy(any())).thenReturn(false);
when(account.isIdentifiedBy(new AciServiceIdentifier(accountIdentifier))).thenReturn(true);
changeNumberManager.changeNumber(account, targetNumber, pniIdentityKey, ecSignedPreKeys, kemLastResortPreKeys, Collections.emptyList(), Collections.emptyMap(), null);
verify(accountsManager).changeNumber(account, targetNumber, pniIdentityKey, ecSignedPreKeys, kemLastResortPreKeys, Collections.emptyMap());
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));
verify(accountsManager).changeNumber(accountIdentifier, targetNumber, pniIdentityKey, ecSignedPreKeys, kemLastResortPreKeys, Collections.emptyMap());
verify(messageSender, never()).sendMessages(eq(account), any(), any(), any(), any(), any());
}
@Test
void changeNumberLinkedDevices() throws Exception {
final String originalNumber = PhoneNumberUtil.getInstance().format(
PhoneNumberUtil.getInstance().getExampleNumber("DE"), PhoneNumberUtil.PhoneNumberFormat.E164);
final String targetNumber = PhoneNumberUtil.getInstance().format(
PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164);
@@ -129,6 +178,7 @@ public class ChangeNumberManagerTest {
when(linkedDevice.getRegistrationId(IdentityType.ACI)).thenReturn(linkedDeviceRegistrationId);
final Account account = mock(Account.class);
when(account.getNumber()).thenReturn(originalNumber);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(aci);
when(account.isIdentifiedBy(any())).thenReturn(false);
when(account.isIdentifiedBy(new AciServiceIdentifier(aci))).thenReturn(true);
@@ -154,16 +204,22 @@ public class ChangeNumberManagerTest {
final IncomingMessage incomingMessage =
new IncomingMessage(1, linkedDeviceId, linkedDeviceRegistrationId, new byte[] { 1 });
changeNumberManager.changeNumber(account,
when(accountsManager.getAccountsForChangeNumber(eq(aci), any()))
.thenReturn(new Pair<>(account, Optional.empty()));
changeNumberManager.changeNumber(aci,
null,
null,
null,
targetNumber,
pniIdentityKey,
ecSignedPreKeys,
kemLastResortPreKeys,
List.of(incomingMessage),
registrationIds,
null);
mock(ContainerRequestContext.class));
verify(accountsManager).changeNumber(account,
verify(accountsManager).changeNumber(aci,
targetNumber,
pniIdentityKey,
ecSignedPreKeys,
@@ -190,4 +246,138 @@ public class ChangeNumberManagerTest {
eq(Optional.of(primaryDeviceId)),
any());
}
@Test
void changeNumberSameNumber() throws Exception {
final String targetNumber = PhoneNumberUtil.getInstance().format(
PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164);
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
final IdentityKey pniIdentityKey = new IdentityKey(ECKeyPair.generate().getPublicKey());
final Map<Byte, ECSignedPreKey> ecSignedPreKeys =
Map.of(Device.PRIMARY_ID, KeysHelper.signedECPreKey(1, pniIdentityKeyPair));
final Map<Byte, KEMSignedPreKey> kemLastResortPreKeys =
Map.of(Device.PRIMARY_ID, KeysHelper.signedKEMPreKey(2, pniIdentityKeyPair));
final UUID accountIdentifier = UUID.randomUUID();
final Account account = mock(Account.class);
when(account.getNumber()).thenReturn(targetNumber);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
when(account.isIdentifiedBy(any())).thenReturn(false);
when(account.isIdentifiedBy(new AciServiceIdentifier(accountIdentifier))).thenReturn(true);
when(accountsManager.getAccountsForChangeNumber(eq(accountIdentifier), any()))
.thenReturn(new Pair<>(account, Optional.empty()));
changeNumberManager.changeNumber(accountIdentifier, null, null, null, targetNumber, pniIdentityKey, ecSignedPreKeys, kemLastResortPreKeys, Collections.emptyList(), Collections.emptyMap(), mock(ContainerRequestContext.class));
verifyNoInteractions(rateLimiter);
verifyNoInteractions(phoneVerificationTokenManager);
verifyNoInteractions(registrationLockVerificationManager);
verify(accountsManager).changeNumber(accountIdentifier, targetNumber, pniIdentityKey, ecSignedPreKeys, kemLastResortPreKeys, Collections.emptyMap());
verify(messageSender, never()).sendMessages(eq(account), any(), any(), any(), any(), any());
}
@Test
void changeNumberRateLimited()
throws MismatchedDevicesException, InterruptedException, MessageTooLargeException, RateLimitExceededException {
final String originalNumber = PhoneNumberUtil.getInstance().format(
PhoneNumberUtil.getInstance().getExampleNumber("DE"), PhoneNumberUtil.PhoneNumberFormat.E164);
final String targetNumber = PhoneNumberUtil.getInstance().format(
PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164);
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
final IdentityKey pniIdentityKey = new IdentityKey(ECKeyPair.generate().getPublicKey());
final Map<Byte, ECSignedPreKey> ecSignedPreKeys =
Map.of(Device.PRIMARY_ID, KeysHelper.signedECPreKey(1, pniIdentityKeyPair));
final Map<Byte, KEMSignedPreKey> kemLastResortPreKeys =
Map.of(Device.PRIMARY_ID, KeysHelper.signedKEMPreKey(2, pniIdentityKeyPair));
final UUID accountIdentifier = UUID.randomUUID();
final Account account = mock(Account.class);
when(account.getNumber()).thenReturn(originalNumber);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
when(account.isIdentifiedBy(any())).thenReturn(false);
when(account.isIdentifiedBy(new AciServiceIdentifier(accountIdentifier))).thenReturn(true);
when(accountsManager.getAccountsForChangeNumber(eq(accountIdentifier), any()))
.thenReturn(new Pair<>(account, Optional.empty()));
doThrow(new RateLimitExceededException(Duration.ofMinutes(1)))
.when(rateLimiter).validate(targetNumber);
assertThrows(RateLimitExceededException.class, () -> changeNumberManager.changeNumber(accountIdentifier,
null,
null,
null,
targetNumber,
pniIdentityKey,
ecSignedPreKeys,
kemLastResortPreKeys,
Collections.emptyList(),
Collections.emptyMap(),
mock(ContainerRequestContext.class)));
verify(accountsManager, never()).changeNumber(any(), any(), any(), any(), any(), any());
verify(messageSender, never()).sendMessages(any(), any(), any(), any(), any(), any());
}
@Test
void changeNumberRegistrationLockFailed()
throws MismatchedDevicesException, InterruptedException, MessageTooLargeException, RateLimitExceededException {
final String originalNumber = PhoneNumberUtil.getInstance().format(
PhoneNumberUtil.getInstance().getExampleNumber("DE"), PhoneNumberUtil.PhoneNumberFormat.E164);
final String targetNumber = PhoneNumberUtil.getInstance().format(
PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164);
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
final IdentityKey pniIdentityKey = new IdentityKey(ECKeyPair.generate().getPublicKey());
final Map<Byte, ECSignedPreKey> ecSignedPreKeys =
Map.of(Device.PRIMARY_ID, KeysHelper.signedECPreKey(1, pniIdentityKeyPair));
final Map<Byte, KEMSignedPreKey> kemLastResortPreKeys =
Map.of(Device.PRIMARY_ID, KeysHelper.signedKEMPreKey(2, pniIdentityKeyPair));
final UUID accountIdentifier = UUID.randomUUID();
final Account account = mock(Account.class);
when(account.getNumber()).thenReturn(originalNumber);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
when(account.isIdentifiedBy(any())).thenReturn(false);
when(account.isIdentifiedBy(new AciServiceIdentifier(accountIdentifier))).thenReturn(true);
final Account existingAccount = mock(Account.class);
when(existingAccount.getNumber()).thenReturn(targetNumber);
when(accountsManager.getAccountsForChangeNumber(eq(accountIdentifier), any()))
.thenReturn(new Pair<>(account, Optional.of(existingAccount)));
doThrow(new WebApplicationException(423))
.when(registrationLockVerificationManager).verifyRegistrationLock(eq(existingAccount), any(), any(), any(), any());
assertThrows(WebApplicationException.class, () -> changeNumberManager.changeNumber(accountIdentifier,
null,
null,
null,
targetNumber,
pniIdentityKey,
ecSignedPreKeys,
kemLastResortPreKeys,
Collections.emptyList(),
Collections.emptyMap(),
mock(ContainerRequestContext.class)));
verify(accountsManager, never()).changeNumber(any(), any(), any(), any(), any(), any());
verify(messageSender, never()).sendMessages(any(), any(), any(), any(), any(), any());
}
}
@@ -258,6 +258,20 @@ public final class DynamoDbExtensionSchema {
.build()),
List.of(), List.of()),
PROFILES_V2("profilesV2_test",
ProfilesV2.KEY_ACCOUNT_UUID,
ProfilesV2.KEY_VERSION,
List.of(
AttributeDefinition.builder()
.attributeName(ProfilesV2.KEY_ACCOUNT_UUID)
.attributeType(ScalarAttributeType.B)
.build(),
AttributeDefinition.builder()
.attributeName(ProfilesV2.KEY_VERSION)
.attributeType(ScalarAttributeType.B)
.build()),
List.of(), List.of()),
PUSH_CHALLENGES("push_challenge_test",
PushChallengeDynamoDb.KEY_ACCOUNT_UUID,
null,
@@ -31,7 +31,6 @@ import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
@@ -115,7 +115,7 @@ class MessagePersisterTest {
when(accountsManager.getByAccountIdentifierAsync(DESTINATION_ACCOUNT_UUID))
.thenReturn(CompletableFuture.completedFuture(Optional.of(destinationAccount)));
when(accountsManager.removeDevice(any(), anyByte()))
.thenAnswer(invocation -> invocation.getArgument(0));
.thenAnswer(invocation -> accountsManager.getByAccountIdentifier(invocation.getArgument(0)).orElseThrow());
when(destinationAccount.getUuid()).thenReturn(DESTINATION_ACCOUNT_UUID);
when(destinationAccount.getIdentifier(IdentityType.ACI)).thenReturn(DESTINATION_ACCOUNT_UUID);
@@ -465,7 +465,7 @@ class MessagePersisterTest {
assertTimeoutPreemptively(Duration.ofSeconds(1), () ->
messagePersister.persistQueue(destinationAccount, DESTINATION_DEVICE, Tags.empty()).block());
verify(accountsManager, exactly()).removeDevice(destinationAccount, DESTINATION_DEVICE_ID);
verify(accountsManager, exactly()).removeDevice(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID);
}
@Test
@@ -552,7 +552,7 @@ class MessagePersisterTest {
when(destinationAccount.getDevices()).thenReturn(List.of(primary, activeA, inactiveB, inactiveC, activeD, destination));
when(messagesManager.persistMessages(any(UUID.class), any(), anyList())).thenThrow(ItemCollectionSizeLimitExceededException.builder().build());
when(accountsManager.removeDevice(destinationAccount, DESTINATION_DEVICE_ID)).thenThrow(new RuntimeException());
when(accountsManager.removeDevice(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID)).thenThrow(new RuntimeException());
assertThrows(RuntimeException.class, () -> messagePersister.persistQueue(destinationAccount, DESTINATION_DEVICE, Tags.empty()).block());
}
@@ -7,11 +7,13 @@ package org.whispersystems.textsecuregcm.storage;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.AdditionalMatchers.aryEq;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -22,238 +24,203 @@ import static org.mockito.Mockito.when;
import io.lettuce.core.RedisException;
import io.lettuce.core.cluster.api.async.RedisAdvancedClusterAsyncCommands;
import io.lettuce.core.cluster.api.sync.RedisAdvancedClusterCommands;
import java.util.Arrays;
import java.util.Collection;
import java.util.HexFormat;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import javax.annotation.Nullable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.profiles.ProfileKey;
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
import org.whispersystems.textsecuregcm.tests.util.MockRedisFuture;
import org.whispersystems.textsecuregcm.tests.util.ProfileTestHelper;
import org.whispersystems.textsecuregcm.tests.util.RedisClusterHelper;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
@Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
public class ProfilesManagerTest {
private Profiles profiles;
private RedisAdvancedClusterCommands<byte[], byte[]> binaryCommands;
private RedisAdvancedClusterAsyncCommands<byte[], byte[]> binaryAsyncCommands;
private Profiles profilesV1;
private ProfilesV2 profilesV2;
private RedisAdvancedClusterCommands<byte[], byte[]> commands;
private RedisAdvancedClusterAsyncCommands<byte[], byte[]> asyncCommands;
private S3AsyncClient s3Client;
private ClusterLuaScript setLuaScript;
private ProfilesManager profilesManager;
private static final String BUCKET = "bucket";
@BeforeEach
void setUp() {
void setUp() throws Exception {
//noinspection unchecked
binaryCommands = mock(RedisAdvancedClusterCommands.class);
commands = mock(RedisAdvancedClusterCommands.class);
//noinspection unchecked
binaryAsyncCommands = mock(RedisAdvancedClusterAsyncCommands.class);
asyncCommands = mock(RedisAdvancedClusterAsyncCommands.class);
final FaultTolerantRedisClusterClient cacheCluster = RedisClusterHelper.builder()
.binaryCommands(binaryCommands)
.binaryAsyncCommands(binaryAsyncCommands)
.binaryCommands(commands)
.binaryAsyncCommands(asyncCommands)
.build();
profiles = mock(Profiles.class);
profilesV1 = mock(Profiles.class);
profilesV2 = mock(ProfilesV2.class);
s3Client = mock(S3AsyncClient.class);
setLuaScript = mock(ClusterLuaScript.class);
profilesManager = new ProfilesManager(profiles, cacheCluster, mock(ScheduledExecutorService.class), s3Client, BUCKET);
profilesManager = new ProfilesManager(profilesV1, profilesV2, cacheCluster, mock(ScheduledExecutorService.class),
s3Client, BUCKET, setLuaScript);
}
@Test
public void testGetProfileInCache() throws InvalidInputException {
public void testGetV1ProfileInCache() throws InvalidInputException {
final UUID uuid = UUID.randomUUID();
final byte[] version = TestRandomUtil.nextBytes(32);
final String versionHex = HexFormat.of().formatHex(version);
final byte[] name = TestRandomUtil.nextBytes(81);
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(uuid)).serialize();
when(binaryCommands.hget(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes())))
when(commands.hget(eq(ProfilesManager.getCacheKeyV1(uuid)), eq(versionHex.getBytes())))
.thenReturn(String.format(
"{\"version\": \"someversion\", \"name\": \"%s\", \"avatar\": \"someavatar\", \"commitment\":\"%s\"}",
"{\"version\": \"%s\", \"name\": \"%s\", \"avatar\": \"someavatar\", \"commitment\":\"%s\"}",
versionHex,
ProfileTestHelper.encodeToBase64(name),
ProfileTestHelper.encodeToBase64(commitment)).getBytes());
Optional<VersionedProfile> profile = profilesManager.get(uuid, "someversion");
Optional<VersionedProfileV1> profile = profilesManager.getV1(uuid, versionHex);
assertTrue(profile.isPresent());
assertArrayEquals(profile.get().name(), name);
assertEquals("someavatar", profile.get().avatar());
assertArrayEquals(profile.get().commitment(), commitment);
verify(binaryCommands, times(1)).hget(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes()));
verifyNoMoreInteractions(binaryCommands);
verifyNoMoreInteractions(profiles);
verify(commands, times(1)).hget(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq(versionHex.getBytes()));
verifyNoMoreInteractions(commands);
verifyNoMoreInteractions(profilesV1);
}
@Test
public void testGetProfileAsyncInCache() throws InvalidInputException {
public void testGetV1ProfileNotInCache() throws Exception {
final UUID uuid = UUID.randomUUID();
final byte[] version = TestRandomUtil.nextBytes(32);
final String versionHex = HexFormat.of().formatHex(version);
final byte[] name = TestRandomUtil.nextBytes(81);
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(uuid)).serialize();
when(binaryAsyncCommands.hget(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes())))
.thenReturn(MockRedisFuture.completedFuture(String.format("{\"version\": \"someversion\", \"name\": \"%s\", \"avatar\": \"someavatar\", \"commitment\":\"%s\"}",
ProfileTestHelper.encodeToBase64(name),
ProfileTestHelper.encodeToBase64(commitment)).getBytes()));
Optional<VersionedProfile> profile = profilesManager.getAsync(uuid, "someversion").join();
assertTrue(profile.isPresent());
assertArrayEquals(profile.get().name(), name);
assertEquals("someavatar", profile.get().avatar());
assertArrayEquals(profile.get().commitment(), commitment);
verify(binaryAsyncCommands, times(1)).hget(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes()));
verifyNoMoreInteractions(binaryAsyncCommands);
verifyNoMoreInteractions(profiles);
}
@Test
public void testGetProfileNotInCache() {
final UUID uuid = UUID.randomUUID();
final byte[] name = TestRandomUtil.nextBytes(81);
final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null,
final VersionedProfileV1 profile = new VersionedProfileV1(versionHex, name, "someavatar", null, null,
null, null, "somecommitment".getBytes());
when(binaryCommands.hget(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes()))).thenReturn(null);
when(profiles.get(eq(uuid), eq("someversion"))).thenReturn(Optional.of(profile));
when(commands.hget(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq(versionHex.getBytes()))).thenReturn(null);
when(profilesV1.get(eq(uuid), eq(versionHex))).thenReturn(Optional.of(profile));
Optional<VersionedProfile> retrieved = profilesManager.get(uuid, "someversion");
Optional<VersionedProfileV1> retrieved = profilesManager.getV1(uuid, versionHex);
assertTrue(retrieved.isPresent());
assertSame(retrieved.get(), profile);
assertEquals(retrieved.get(), profile);
verify(binaryCommands, times(1)).hget(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes()));
verify(binaryCommands, times(1)).hset(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes()), any(byte[].class));
verifyNoMoreInteractions(binaryCommands);
final byte[] v1ProfileBytes = SystemMapper.jsonMapper().writeValueAsBytes(profile);
verify(profiles, times(1)).get(eq(uuid), eq("someversion"));
verifyNoMoreInteractions(profiles);
}
verify(commands, times(1)).hget(eq(ProfilesManager.getCacheKeyV1(uuid)), eq(versionHex.getBytes()));
verify(setLuaScript, times(1)).executeBinary(
argThat(keys ->
Arrays.equals(keys.get(0), ProfilesManager.getCacheKeyV1(uuid))
&& Arrays.equals(keys.get(1), ProfilesManager.getCacheKeyV2(uuid))),
argThat(args ->
Arrays.equals(args.get(0), versionHex.getBytes())
&& Arrays.equals(args.get(1), v1ProfileBytes)
&& args.get(2).length == 0));
@Test
public void testGetProfileAsyncNotInCache() {
final UUID uuid = UUID.randomUUID();
final byte[] name = TestRandomUtil.nextBytes(81);
final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null,
null, null, "somecommitment".getBytes());
verify(commands, times(1)).hget(aryEq(ProfilesManager.getCacheKeyV1(uuid)), aryEq(versionHex.getBytes()));
verifyNoMoreInteractions(commands);
verifyNoMoreInteractions(setLuaScript);
when(binaryAsyncCommands.hget(eq(ProfilesManager.getCacheKeyV1(uuid)), eq("someversion".getBytes()))).thenReturn(MockRedisFuture.completedFuture(null));
when(binaryAsyncCommands.hset(eq(ProfilesManager.getCacheKeyV1(uuid)), eq("someversion".getBytes()), any(byte[].class))).thenReturn(MockRedisFuture.completedFuture(null));
when(profiles.getAsync(eq(uuid), eq("someversion"))).thenReturn(CompletableFuture.completedFuture(Optional.of(profile)));
Optional<VersionedProfile> retrieved = profilesManager.getAsync(uuid, "someversion").join();
assertTrue(retrieved.isPresent());
assertSame(retrieved.get(), profile);
verify(binaryAsyncCommands, times(1)).hget(eq(ProfilesManager.getCacheKeyV1(uuid)), eq("someversion".getBytes()));
verify(binaryAsyncCommands, times(1)).hset(eq(ProfilesManager.getCacheKeyV1(uuid)), eq("someversion".getBytes()), any(byte[].class));
verifyNoMoreInteractions(binaryAsyncCommands);
verify(profiles, times(1)).getAsync(eq(uuid), eq("someversion"));
verifyNoMoreInteractions(profiles);
verify(profilesV1, times(1)).get(eq(uuid), eq(versionHex));
verifyNoMoreInteractions(profilesV1);
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
public void testGetProfileBrokenCache(final boolean failUpdateCache) {
public void testGetV1ProfileBrokenCache(final boolean failUpdateCache) {
final UUID uuid = UUID.randomUUID();
final byte[] version = TestRandomUtil.nextBytes(32);
final String versionHex = HexFormat.of().formatHex(version);
final byte[] name = TestRandomUtil.nextBytes(81);
final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null,
final VersionedProfileV1 profile = new VersionedProfileV1(versionHex, name, "someavatar", null, null,
null, null, "somecommitment".getBytes());
when(binaryCommands.hget(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes()))).thenThrow(new RedisException("Connection lost"));
when(commands.hget(eq(ProfilesManager.getCacheKeyV1(uuid)), eq(versionHex.getBytes()))).thenThrow(new RedisException("Connection lost"));
if (failUpdateCache) {
when(binaryCommands.hset(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes()), any(byte[].class)))
when(commands.hset(eq(ProfilesManager.getCacheKeyV1(uuid)), eq(versionHex.getBytes()), any(byte[].class)))
.thenThrow(new RedisException("Connection lost"));
}
when(profiles.get(eq(uuid), eq("someversion"))).thenReturn(Optional.of(profile));
when(profilesV1.get(eq(uuid), eq(versionHex))).thenReturn(Optional.of(profile));
Optional<VersionedProfile> retrieved = profilesManager.get(uuid, "someversion");
Optional<VersionedProfileV1> retrieved = profilesManager.getV1(uuid, versionHex);
assertTrue(retrieved.isPresent());
assertSame(retrieved.get(), profile);
assertEquals(retrieved.get(), profile);
verify(binaryCommands, times(1)).hget(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes()));
verify(binaryCommands, times(1)).hset(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes()), any(byte[].class));
verifyNoMoreInteractions(binaryCommands);
verify(commands, times(1)).hget(eq(ProfilesManager.getCacheKeyV1(uuid)), eq(versionHex.getBytes()));
verify(setLuaScript, times(1)).executeBinary(
argThat(keys ->
Arrays.equals(keys.get(0), ProfilesManager.getCacheKeyV1(uuid))
&& Arrays.equals(keys.get(1), ProfilesManager.getCacheKeyV2(uuid))),
argThat(args ->
Arrays.equals(args.get(0), versionHex.getBytes())
&& args.get(1).length > 0
&& args.get(2).length == 0));
verifyNoMoreInteractions(commands);
verifyNoMoreInteractions(setLuaScript);
verify(profiles, times(1)).get(eq(uuid), eq("someversion"));
verifyNoMoreInteractions(profiles);
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
public void testGetProfileAsyncBrokenCache(final boolean failUpdateCache) {
final UUID uuid = UUID.randomUUID();
final byte[] name = TestRandomUtil.nextBytes(81);
final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null,
null, null, "somecommitment".getBytes());
when(binaryAsyncCommands.hget(eq(ProfilesManager.getCacheKeyV1(uuid)), eq("someversion".getBytes()))).thenReturn(MockRedisFuture.failedFuture(new RedisException("Connection lost")));
when(binaryAsyncCommands.hset(eq(ProfilesManager.getCacheKeyV1(uuid)), eq("someversion".getBytes()), any(byte[].class)))
.thenReturn(failUpdateCache
? MockRedisFuture.failedFuture(new RedisException("Connection lost"))
: MockRedisFuture.completedFuture(null));
when(profiles.getAsync(eq(uuid), eq("someversion"))).thenReturn(CompletableFuture.completedFuture(Optional.of(profile)));
Optional<VersionedProfile> retrieved = profilesManager.getAsync(uuid, "someversion").join();
assertTrue(retrieved.isPresent());
assertSame(retrieved.get(), profile);
verify(binaryAsyncCommands, times(1)).hget(eq(ProfilesManager.getCacheKeyV1(uuid)), eq("someversion".getBytes()));
verify(binaryAsyncCommands, times(1)).hset(eq(ProfilesManager.getCacheKeyV1(uuid)), eq("someversion".getBytes()), any(byte[].class));
verifyNoMoreInteractions(binaryAsyncCommands);
verify(profiles, times(1)).getAsync(eq(uuid), eq("someversion"));
verifyNoMoreInteractions(profiles);
verify(profilesV1, times(1)).get(eq(uuid), eq(versionHex));
verifyNoMoreInteractions(profilesV1);
}
@Test
public void testSet() {
public void testSetV1() throws Exception {
final UUID uuid = UUID.randomUUID();
final byte[] version = TestRandomUtil.nextBytes(32);
final String versionHex = HexFormat.of().formatHex(version);
final byte[] name = TestRandomUtil.nextBytes(81);
final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null,
final VersionedProfileV1 profile = new VersionedProfileV1(versionHex, name, "someavatar", null, null,
null, null, "somecommitment".getBytes());
profilesManager.set(uuid, profile);
profilesManager.setV1(uuid, profile);
verify(binaryCommands, times(1)).hset(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes()), any(byte[].class));
verifyNoMoreInteractions(binaryCommands);
final byte[] v1ProfileBytes = SystemMapper.jsonMapper().writeValueAsBytes(profile);
verify(profiles, times(1)).set(eq(uuid), eq(profile));
verifyNoMoreInteractions(profiles);
}
verify(setLuaScript, times(1)).executeBinary(
argThat(keys ->
Arrays.equals(keys.get(0), ProfilesManager.getCacheKeyV1(uuid))
&& Arrays.equals(keys.get(1), ProfilesManager.getCacheKeyV2(uuid))),
argThat(args ->
Arrays.equals(args.get(0), versionHex.getBytes())
&& Arrays.equals(args.get(1), v1ProfileBytes)
&& args.get(2).length == 0
&& args.get(3).length == 0));
verifyNoMoreInteractions(setLuaScript);
@Test
public void testSetAsync() {
final UUID uuid = UUID.randomUUID();
final byte[] name = TestRandomUtil.nextBytes(81);
final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null,
null, null, "somecommitment".getBytes());
when(binaryAsyncCommands.hset(eq(ProfilesManager.getCacheKeyV1(uuid)), eq("someversion".getBytes()), any(byte[].class))).thenReturn(MockRedisFuture.completedFuture(null));
when(profiles.setAsync(eq(uuid), eq(profile))).thenReturn(CompletableFuture.completedFuture(null));
profilesManager.setAsync(uuid, profile).join();
verify(binaryAsyncCommands, times(1)).hset(eq(ProfilesManager.getCacheKeyV1(uuid)), eq("someversion".getBytes()), any());
verifyNoMoreInteractions(binaryAsyncCommands);
verify(profiles, times(1)).setAsync(eq(uuid), eq(profile));
verifyNoMoreInteractions(profiles);
verify(profilesV1, times(1)).set(eq(uuid), eq(profile));
verifyNoMoreInteractions(profilesV1);
verify(commands).del(aryEq(ProfilesManager.getCacheKeyV1(uuid)), aryEq(ProfilesManager.getCacheKeyV2(uuid)));
verify(profilesV2).deleteAll(uuid);
}
@ParameterizedTest
@@ -263,16 +230,18 @@ public class ProfilesManagerTest {
final String avatarOne = "avatar1";
final String avatarTwo = "avatar2";
when(profiles.deleteAll(uuid)).thenReturn(CompletableFuture.completedFuture(List.of(avatarOne, avatarTwo)));
when(binaryAsyncCommands.del(ProfilesManager.getCacheKeyV1(uuid))).thenReturn(MockRedisFuture.completedFuture(null));
when(profilesV1.deleteAll(uuid)).thenReturn(CompletableFuture.completedFuture(List.of(avatarOne, avatarTwo)));
when(profilesV2.deleteAll(uuid)).thenReturn(CompletableFuture.completedFuture(null));
when(asyncCommands.del(ProfilesManager.getCacheKeyV1(uuid), ProfilesManager.getCacheKeyV2(uuid))).thenReturn(MockRedisFuture.completedFuture(null));
when(s3Client.deleteObject(any(DeleteObjectRequest.class)))
.thenReturn(CompletableFuture.completedFuture(null))
.thenReturn(CompletableFuture.failedFuture(new RuntimeException("some error")));
profilesManager.deleteAll(uuid, includeAvatar).join();
verify(profiles).deleteAll(uuid);
verify(binaryAsyncCommands).del(ProfilesManager.getCacheKeyV1(uuid));
verify(profilesV1).deleteAll(uuid);
verify(profilesV2).deleteAll(uuid);
verify(asyncCommands).del(ProfilesManager.getCacheKeyV1(uuid), ProfilesManager.getCacheKeyV2(uuid));
if (includeAvatar) {
verify(s3Client).deleteObject(DeleteObjectRequest.builder()
.bucket(BUCKET)
@@ -286,4 +255,257 @@ public class ProfilesManagerTest {
verifyNoInteractions(s3Client);
}
}
@Test
public void testGetProfileInCache() {
final UUID uuid = UUID.randomUUID();
final byte[] version = TestRandomUtil.nextBytes(32);
final byte[] data = TestRandomUtil.nextBytes(128);
final byte[] dataHash = TestRandomUtil.nextBytes(32);
final byte[] commitment = TestRandomUtil.nextBytes(32);
final byte[] paymentAddress = TestRandomUtil.nextBytes(64);
final byte[] paymentAddressHash = TestRandomUtil.nextBytes(32);
when(commands.hget(aryEq(ProfilesManager.getCacheKeyV2(uuid)), aryEq(version))).thenReturn(String.format(
"""
{
"version":"%s",
"data":"%s",
"dataHash":"%s",
"paymentAddress":"%s",
"paymentAddressHash":"%s",
"commitment":"%s"
}
""",
ProfileTestHelper.encodeToBase64(version),
ProfileTestHelper.encodeToBase64(data),
ProfileTestHelper.encodeToBase64(dataHash),
ProfileTestHelper.encodeToBase64(paymentAddress),
ProfileTestHelper.encodeToBase64(paymentAddressHash),
ProfileTestHelper.encodeToBase64(commitment)).getBytes());
Optional<VersionedProfile> profile = profilesManager.get(uuid, version);
assertTrue(profile.isPresent());
assertArrayEquals(profile.get().data(), data);
assertArrayEquals(profile.get().dataHash(), dataHash);
assertArrayEquals(profile.get().commitment(), commitment);
assertArrayEquals(profile.get().paymentAddress(), paymentAddress);
assertArrayEquals(profile.get().paymentAddressHash(), paymentAddressHash);
verify(commands, times(1)).hget(aryEq(ProfilesManager.getCacheKeyV2(uuid)), aryEq(version));
verifyNoMoreInteractions(commands);
verifyNoMoreInteractions(profilesV2);
}
@Test
public void testGetProfileNotInCache() throws Exception {
final UUID uuid = UUID.randomUUID();
final byte[] version = TestRandomUtil.nextBytes(32);
final VersionedProfile profile = new VersionedProfile(version, TestRandomUtil.nextBytes(128),
TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(64),
TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(32));
when(commands.hget(aryEq(ProfilesManager.getCacheKeyV2(uuid)), aryEq(version))).thenReturn(null);
when(profilesV2.get(eq(uuid), aryEq(version))).thenReturn(Optional.of(profile));
final Optional<VersionedProfile> retrieved = profilesManager.get(uuid, version);
assertTrue(retrieved.isPresent());
assertEquals(retrieved.get(), profile);
final byte[] v2ProfileBytes = SystemMapper.jsonMapper().writeValueAsBytes(profile);
verify(commands, times(1)).hget(aryEq(ProfilesManager.getCacheKeyV2(uuid)), aryEq(version));
verify(setLuaScript, times(1)).executeBinary(
argThat(keys ->
Arrays.equals(keys.get(0), ProfilesManager.getCacheKeyV1(uuid))
&& Arrays.equals(keys.get(1), ProfilesManager.getCacheKeyV2(uuid))),
argThat(args ->
args.get(0).length == 0
&& args.get(1).length == 0
&& Arrays.equals(args.get(2), version)
&& Arrays.equals(args.get(3), v2ProfileBytes)));
verifyNoMoreInteractions(commands);
verify(profilesV2, times(1)).get(eq(uuid), aryEq(version));
verifyNoMoreInteractions(profilesV2);
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
public void testGetProfileBrokenCache(final boolean failUpdateCache) throws Exception {
final UUID uuid = UUID.randomUUID();
final byte[] version = TestRandomUtil.nextBytes(32);
final VersionedProfile profile = new VersionedProfile(version, TestRandomUtil.nextBytes(128),
TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(64),
TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(32));
when(commands.hget(aryEq(ProfilesManager.getCacheKeyV2(uuid)), aryEq(version))).thenThrow(new RedisException("Connection lost"));
if (failUpdateCache) {
when(commands.hset(aryEq(ProfilesManager.getCacheKeyV2(uuid)), aryEq(version), any(byte[].class)))
.thenThrow(new RedisException("Connection lost"));
}
when(profilesV2.get(eq(uuid), aryEq(version))).thenReturn(Optional.of(profile));
final Optional<VersionedProfile> retrieved = profilesManager.get(uuid, version);
assertTrue(retrieved.isPresent());
assertEquals(retrieved.get(), profile);
final byte[] v2ProfileBytes = SystemMapper.jsonMapper().writeValueAsBytes(profile);
verify(commands, times(1)).hget(aryEq(ProfilesManager.getCacheKeyV2(uuid)), aryEq(version));
verify(setLuaScript, times(1)).executeBinary(
argThat(keys ->
Arrays.equals(keys.get(0), ProfilesManager.getCacheKeyV1(uuid))
&& Arrays.equals(keys.get(1), ProfilesManager.getCacheKeyV2(uuid))),
argThat(args ->
args.get(0).length == 0
&& args.get(1).length == 0
&& Arrays.equals(args.get(2), version)
&& Arrays.equals(args.get(3), v2ProfileBytes))); verifyNoMoreInteractions(commands);
verify(profilesV2, times(1)).get(eq(uuid), aryEq(version));
verifyNoMoreInteractions(profilesV2);
}
@Test
public void testSet() throws Exception {
final UUID uuid = UUID.randomUUID();
final byte[] version = TestRandomUtil.nextBytes(32);
final String versionHex = HexFormat.of().formatHex(version);
final byte[] name = TestRandomUtil.nextBytes(81);
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(uuid)).serialize();
final VersionedProfileV1 profileV1 = new VersionedProfileV1(versionHex, name, null, null, null, null, null, commitment);
final byte[] expectedCurrentDataHash = TestRandomUtil.nextBytes(32);
final VersionedProfile profileV2 = new VersionedProfile(version, TestRandomUtil.nextBytes(128),
TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(64),
TestRandomUtil.nextBytes(32), commitment);
final TransactWriteItem v1Item = TransactWriteItem.builder().build();
when(profilesV1.getTransactWriteItem(eq(uuid), eq(profileV1))).thenReturn(v1Item);
profilesManager.set(uuid, profileV1, profileV2, expectedCurrentDataHash);
final byte[] v1ProfileBytes = SystemMapper.jsonMapper().writeValueAsBytes(profileV1);
final byte[] v2ProfileBytes = SystemMapper.jsonMapper().writeValueAsBytes(profileV2);
verify(setLuaScript, times(1)).executeBinary(
argThat(keys ->
Arrays.equals(keys.get(0), ProfilesManager.getCacheKeyV1(uuid))
&& Arrays.equals(keys.get(1), ProfilesManager.getCacheKeyV2(uuid))),
argThat(args ->
Arrays.equals(args.get(0), versionHex.getBytes())
&& Arrays.equals(args.get(1), v1ProfileBytes)
&& Arrays.equals(args.get(2), version)
&& Arrays.equals(args.get(3), v2ProfileBytes)));
verify(commands).del(aryEq(ProfilesManager.getCacheKeyV1(uuid)), aryEq(ProfilesManager.getCacheKeyV2(uuid)));
verifyNoMoreInteractions(commands);
verifyNoMoreInteractions(setLuaScript);
verify(profilesV1).getTransactWriteItem(eq(uuid), eq(profileV1));
verifyNoMoreInteractions(profilesV1);
verify(profilesV2).set(eq(uuid), aryEq(version), aryEq(profileV2.data()), aryEq(profileV2.dataHash()), aryEq(profileV2.commitment()), aryEq(profileV2.paymentAddress()), aryEq(profileV2.paymentAddressHash()), aryEq(expectedCurrentDataHash), eq(v1Item));
verifyNoMoreInteractions(profilesV2);
}
@ParameterizedTest
@MethodSource
public void testSetExceptionCleansUpCache(final Class<? extends Exception> exceptionClass) throws WriteConflictException, InvalidInputException {
final UUID uuid = UUID.randomUUID();
final byte[] version = TestRandomUtil.nextBytes(32);
final String versionHex = HexFormat.of().formatHex(version);
final byte[] name = TestRandomUtil.nextBytes(81);
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(uuid)).serialize();
final VersionedProfileV1 profileV1 = new VersionedProfileV1(versionHex, name, null, null, null, null, null, commitment);
final byte[] wrongHash = TestRandomUtil.nextBytes(32);
final VersionedProfile profileV2 = new VersionedProfile(version, TestRandomUtil.nextBytes(128),
TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(64),
TestRandomUtil.nextBytes(32), commitment);
final TransactWriteItem v1Item = TransactWriteItem.builder().build();
when(profilesV1.getTransactWriteItem(eq(uuid), eq(profileV1))).thenReturn(v1Item);
when(asyncCommands.del(ProfilesManager.getCacheKeyV1(uuid), ProfilesManager.getCacheKeyV2(uuid))).thenReturn(MockRedisFuture.completedFuture(null));
doThrow(exceptionClass).when(profilesV2).set(eq(uuid), aryEq(version), aryEq(profileV2.data()), aryEq(profileV2.dataHash()), aryEq(profileV2.commitment()),
aryEq(profileV2.paymentAddress()), aryEq(profileV2.paymentAddressHash()), aryEq(wrongHash), eq(v1Item));
assertThrows(exceptionClass, () -> profilesManager.set(uuid, profileV1, profileV2, wrongHash));
verify(commands).del(aryEq(ProfilesManager.getCacheKeyV1(uuid)), aryEq(ProfilesManager.getCacheKeyV2(uuid)));
}
static Collection<Arguments> testSetExceptionCleansUpCache() {
return List.of(
Arguments.of(WriteConflictException.class),
Arguments.of(DynamoDbException.class)
);
}
@Nested
class Redis {
@RegisterExtension
private static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
@BeforeEach
void setUp() throws Exception {
profilesManager = new ProfilesManager(profilesV1, profilesV2, REDIS_CLUSTER_EXTENSION.getRedisCluster(), mock(ScheduledExecutorService.class),
s3Client, BUCKET);
}
@ParameterizedTest
@MethodSource
void testSetGet(@Nullable final VersionedProfileV1 v1Profile, @Nullable final VersionedProfile v2Profile) {
final UUID uuid = UUID.randomUUID();
profilesManager.redisSet(uuid, v2Profile, v1Profile);
if (v1Profile != null) {
final Optional<VersionedProfileV1> v1Actual = profilesManager.getV1(uuid, v1Profile.version());
assertTrue(v1Actual.isPresent());
assertEquals(v1Profile, v1Actual.get());
}
if (v2Profile != null) {
final Optional<VersionedProfile> v2Actual = profilesManager.get(uuid, v2Profile.version());
assertTrue(v2Actual.isPresent());
assertEquals(v2Profile, v2Actual.get());
}
}
static Collection<Arguments> testSetGet() throws Exception {
final UUID uuid = UUID.randomUUID();
final byte[] version = TestRandomUtil.nextBytes(32);
final String versionHex = HexFormat.of().formatHex(version);
final byte[] name = TestRandomUtil.nextBytes(81);
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(uuid)).serialize();
final VersionedProfileV1 profileV1 = new VersionedProfileV1(versionHex, name, null, null, null, null, null, commitment);
final VersionedProfile profileV2 = new VersionedProfile(version, TestRandomUtil.nextBytes(128),
TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(64),
TestRandomUtil.nextBytes(32), commitment);
return List.of(
Arguments.argumentSet("only v1", profileV1, null),
Arguments.argumentSet("only v2", null, profileV2),
Arguments.argumentSet("both", profileV1, profileV2)
);
}
}
}
@@ -28,6 +28,7 @@ import org.whispersystems.textsecuregcm.tests.util.ProfileTestHelper;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
@Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
public class ProfilesTest {
@@ -36,7 +37,7 @@ public class ProfilesTest {
static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(Tables.PROFILES);
private Profiles profiles;
private VersionedProfile validProfile;
private VersionedProfileV1 validProfile;
@BeforeEach
void setUp() throws InvalidInputException {
@@ -51,28 +52,14 @@ public class ProfilesTest {
final String avatar = "profiles/" + ProfileTestHelper.generateRandomBase64FromByteArray(16);
final byte[] phoneNumberSharing = TestRandomUtil.nextBytes(29);
validProfile = new VersionedProfile(version, name, avatar, validAboutEmoji, validAbout, null, phoneNumberSharing, commitment);
validProfile = new VersionedProfileV1(version, name, avatar, validAboutEmoji, validAbout, null, phoneNumberSharing, commitment);
}
@Test
void testSetGet() {
profiles.set(ACI, validProfile);
Optional<VersionedProfile> retrieved = profiles.get(ACI, validProfile.version());
assertThat(retrieved.isPresent()).isTrue();
assertThat(retrieved.get().name()).isEqualTo(validProfile.name());
assertThat(retrieved.get().avatar()).isEqualTo(validProfile.avatar());
assertThat(retrieved.get().commitment()).isEqualTo(validProfile.commitment());
assertThat(retrieved.get().about()).isEqualTo(validProfile.about());
assertThat(retrieved.get().aboutEmoji()).isEqualTo(validProfile.aboutEmoji());
}
@Test
void testSetGetAsync() {
profiles.setAsync(ACI, validProfile).join();
Optional<VersionedProfile> retrieved = profiles.getAsync(ACI, validProfile.version()).join();
Optional<VersionedProfileV1> retrieved = profiles.get(ACI, validProfile.version());
assertThat(retrieved.isPresent()).isTrue();
assertThat(retrieved.get().name()).isEqualTo(validProfile.name());
@@ -97,12 +84,12 @@ public class ProfilesTest {
final byte[] phoneNumberSharing = TestRandomUtil.nextBytes(29);
final byte[] commitment = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
VersionedProfile updatedProfile = new VersionedProfile(version, name, differentAvatar,
VersionedProfileV1 updatedProfile = new VersionedProfileV1(version, name, differentAvatar,
differentEmoji, differentAbout, paymentAddress, phoneNumberSharing, commitment);
profiles.set(ACI, updatedProfile);
Optional<VersionedProfile> retrieved = profiles.get(ACI, version);
Optional<VersionedProfileV1> retrieved = profiles.get(ACI, version);
assertThat(retrieved.isPresent()).isTrue();
assertThat(retrieved.get().name()).isEqualTo(updatedProfile.name());
@@ -118,11 +105,11 @@ public class ProfilesTest {
final byte[] name = TestRandomUtil.nextBytes(81);
final byte[] commitment = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
VersionedProfile profile = new VersionedProfile(version, name, null, null, null, null, null,
VersionedProfileV1 profile = new VersionedProfileV1(version, name, null, null, null, null, null,
commitment);
profiles.set(ACI, profile);
Optional<VersionedProfile> retrieved = profiles.get(ACI, version);
Optional<VersionedProfileV1> retrieved = profiles.get(ACI, version);
assertThat(retrieved.isPresent()).isTrue();
assertThat(retrieved.get().name()).isEqualTo(profile.name());
@@ -136,7 +123,7 @@ public class ProfilesTest {
void testSetReplace() throws InvalidInputException {
profiles.set(ACI, validProfile);
Optional<VersionedProfile> retrieved = profiles.get(ACI, validProfile.version());
Optional<VersionedProfileV1> retrieved = profiles.get(ACI, validProfile.version());
assertThat(retrieved.isPresent()).isTrue();
assertThat(retrieved.get().name()).isEqualTo(validProfile.name());
@@ -153,7 +140,7 @@ public class ProfilesTest {
final byte[] differentPhoneNumberSharing = TestRandomUtil.nextBytes(29);
final byte[] differentCommitment = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
VersionedProfile updated = new VersionedProfile(validProfile.version(), differentName, differentAvatar, differentEmoji, differentAbout, null,
VersionedProfileV1 updated = new VersionedProfileV1(validProfile.version(), differentName, differentAvatar, differentEmoji, differentAbout, null,
differentPhoneNumberSharing, differentCommitment);
profiles.set(ACI, updated);
@@ -187,14 +174,14 @@ public class ProfilesTest {
final byte[] commitmentOne = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
final byte[] commitmentTwo = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
VersionedProfile profileOne = new VersionedProfile(versionOne, nameOne, avatarOne, null, null,
VersionedProfileV1 profileOne = new VersionedProfileV1(versionOne, nameOne, avatarOne, null, null,
null, null, commitmentOne);
VersionedProfile profileTwo = new VersionedProfile(versionTwo, nameTwo, avatarTwo, aboutEmoji, about, null, null, commitmentTwo);
VersionedProfileV1 profileTwo = new VersionedProfileV1(versionTwo, nameTwo, avatarTwo, aboutEmoji, about, null, null, commitmentTwo);
profiles.set(ACI, profileOne);
profiles.set(ACI, profileTwo);
Optional<VersionedProfile> retrieved = profiles.get(ACI, versionOne);
Optional<VersionedProfileV1> retrieved = profiles.get(ACI, versionOne);
assertThat(retrieved.isPresent()).isTrue();
assertThat(retrieved.get().name()).isEqualTo(profileOne.name());
@@ -218,7 +205,7 @@ public class ProfilesTest {
profiles.set(ACI, validProfile);
final String missingVersion = "missingVersion";
Optional<VersionedProfile> retrieved = profiles.get(ACI, missingVersion);
Optional<VersionedProfileV1> retrieved = profiles.get(ACI, missingVersion);
assertThat(retrieved.isPresent()).isFalse();
}
@@ -242,10 +229,10 @@ public class ProfilesTest {
final byte[] commitmentTwo = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
final byte[] commitmentThree = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
VersionedProfile profileOne = new VersionedProfile(versionOne, nameOne, avatarOne, null, null,
VersionedProfileV1 profileOne = new VersionedProfileV1(versionOne, nameOne, avatarOne, null, null,
null, null, commitmentOne);
VersionedProfile profileTwo = new VersionedProfile(versionTwo, nameTwo, avatarTwo, aboutEmoji, about, null, null, commitmentTwo);
VersionedProfile profileThree = new VersionedProfile(versionThree, nameTwo, null, aboutEmoji, about, null, null,
VersionedProfileV1 profileTwo = new VersionedProfileV1(versionTwo, nameTwo, avatarTwo, aboutEmoji, about, null, null, commitmentTwo);
VersionedProfileV1 profileThree = new VersionedProfileV1(versionThree, nameTwo, null, aboutEmoji, about, null, null,
commitmentThree);
profiles.set(ACI, profileOne);
@@ -255,7 +242,7 @@ public class ProfilesTest {
final List<String> avatars = profiles.deleteAll(ACI).join();
for (String version : List.of(versionOne, versionTwo, versionThree)) {
final Optional<VersionedProfile> retrieved = profiles.get(ACI, version);
final Optional<VersionedProfileV1> retrieved = profiles.get(ACI, version);
assertThat(retrieved.isPresent()).isFalse();
}
@@ -263,9 +250,23 @@ public class ProfilesTest {
assertThat(avatars.containsAll(List.of(avatarOne, avatarTwo))).isTrue();
}
@Test
void testGetTransactWriteItem() {
final TransactWriteItem transactWriteItem = profiles.getTransactWriteItem(ACI, validProfile);
assertThat(transactWriteItem).isNotNull()
.extracting(TransactWriteItem::update).isNotNull();
assertThat(transactWriteItem.update().tableName()).isEqualTo(Tables.PROFILES.tableName());
assertThat(transactWriteItem.update().key()).isNotNull();
assertThat(transactWriteItem.update().updateExpression()).isEqualTo(Profiles.buildUpdateExpression(validProfile));
assertThat(transactWriteItem.update().expressionAttributeValues())
.isEqualTo(Profiles.buildUpdateExpressionAttributeValues(validProfile));
}
@ParameterizedTest
@MethodSource
void buildUpdateExpression(final VersionedProfile profile, final String expectedUpdateExpression) {
void buildUpdateExpression(final VersionedProfileV1 profile, final String expectedUpdateExpression) {
assertEquals(expectedUpdateExpression, Profiles.buildUpdateExpression(profile));
}
@@ -281,38 +282,38 @@ public class ProfilesTest {
return Stream.of(
Arguments.of(
new VersionedProfile(version, name, avatar, emoji, about, paymentAddress, phoneNumberSharing, commitment),
new VersionedProfileV1(version, name, avatar, emoji, about, paymentAddress, phoneNumberSharing, commitment),
"SET #commitment = if_not_exists(#commitment, :commitment), #name = :name, #avatar = :avatar, #about = :about, #aboutEmoji = :aboutEmoji, #paymentAddress = :paymentAddress, #phoneNumberSharing = :phoneNumberSharing"),
Arguments.of(
new VersionedProfile(version, name, avatar, emoji, about, paymentAddress, null, commitment),
new VersionedProfileV1(version, name, avatar, emoji, about, paymentAddress, null, commitment),
"SET #commitment = if_not_exists(#commitment, :commitment), #name = :name, #avatar = :avatar, #about = :about, #aboutEmoji = :aboutEmoji, #paymentAddress = :paymentAddress REMOVE #phoneNumberSharing"),
Arguments.of(
new VersionedProfile(version, name, avatar, emoji, about, null, null, commitment),
new VersionedProfileV1(version, name, avatar, emoji, about, null, null, commitment),
"SET #commitment = if_not_exists(#commitment, :commitment), #name = :name, #avatar = :avatar, #about = :about, #aboutEmoji = :aboutEmoji REMOVE #paymentAddress, #phoneNumberSharing"),
Arguments.of(
new VersionedProfile(version, name, avatar, emoji, null, null, null, commitment),
new VersionedProfileV1(version, name, avatar, emoji, null, null, null, commitment),
"SET #commitment = if_not_exists(#commitment, :commitment), #name = :name, #avatar = :avatar, #aboutEmoji = :aboutEmoji REMOVE #about, #paymentAddress, #phoneNumberSharing"),
Arguments.of(
new VersionedProfile(version, name, avatar, null, null, null, null, commitment),
new VersionedProfileV1(version, name, avatar, null, null, null, null, commitment),
"SET #commitment = if_not_exists(#commitment, :commitment), #name = :name, #avatar = :avatar REMOVE #about, #aboutEmoji, #paymentAddress, #phoneNumberSharing"),
Arguments.of(
new VersionedProfile(version, name, null, null, null, null, null, commitment),
new VersionedProfileV1(version, name, null, null, null, null, null, commitment),
"SET #commitment = if_not_exists(#commitment, :commitment), #name = :name REMOVE #avatar, #about, #aboutEmoji, #paymentAddress, #phoneNumberSharing"),
Arguments.of(
new VersionedProfile(version, null, null, null, null, null, null, commitment),
new VersionedProfileV1(version, null, null, null, null, null, null, commitment),
"SET #commitment = if_not_exists(#commitment, :commitment) REMOVE #name, #avatar, #about, #aboutEmoji, #paymentAddress, #phoneNumberSharing")
);
}
@ParameterizedTest
@MethodSource
void buildUpdateExpressionAttributeValues(final VersionedProfile profile, final Map<String, AttributeValue> expectedAttributeValues) {
void buildUpdateExpressionAttributeValues(final VersionedProfileV1 profile, final Map<String, AttributeValue> expectedAttributeValues) {
assertEquals(expectedAttributeValues, Profiles.buildUpdateExpressionAttributeValues(profile));
}
@@ -328,7 +329,7 @@ public class ProfilesTest {
return Stream.of(
Arguments.of(
new VersionedProfile(version, name, avatar, emoji, about, paymentAddress, phoneNumberSharing, commitment),
new VersionedProfileV1(version, name, avatar, emoji, about, paymentAddress, phoneNumberSharing, commitment),
Map.of(
":commitment", AttributeValues.fromByteArray(commitment),
":name", AttributeValues.fromByteArray(name),
@@ -339,7 +340,7 @@ public class ProfilesTest {
":phoneNumberSharing", AttributeValues.fromByteArray(phoneNumberSharing))),
Arguments.of(
new VersionedProfile(version, name, avatar, emoji, about, paymentAddress, null, commitment),
new VersionedProfileV1(version, name, avatar, emoji, about, paymentAddress, null, commitment),
Map.of(
":commitment", AttributeValues.fromByteArray(commitment),
":name", AttributeValues.fromByteArray(name),
@@ -349,7 +350,7 @@ public class ProfilesTest {
":paymentAddress", AttributeValues.fromByteArray(paymentAddress))),
Arguments.of(
new VersionedProfile(version, name, avatar, emoji, about, null, null, commitment),
new VersionedProfileV1(version, name, avatar, emoji, about, null, null, commitment),
Map.of(
":commitment", AttributeValues.fromByteArray(commitment),
":name", AttributeValues.fromByteArray(name),
@@ -358,7 +359,7 @@ public class ProfilesTest {
":about", AttributeValues.fromByteArray(about))),
Arguments.of(
new VersionedProfile(version, name, avatar, emoji, null, null, null, commitment),
new VersionedProfileV1(version, name, avatar, emoji, null, null, null, commitment),
Map.of(
":commitment", AttributeValues.fromByteArray(commitment),
":name",AttributeValues.fromByteArray(name),
@@ -366,20 +367,20 @@ public class ProfilesTest {
":aboutEmoji", AttributeValues.fromByteArray(emoji))),
Arguments.of(
new VersionedProfile(version, name, avatar, null, null, null, null, commitment),
new VersionedProfileV1(version, name, avatar, null, null, null, null, commitment),
Map.of(
":commitment", AttributeValues.fromByteArray(commitment),
":name", AttributeValues.fromByteArray(name),
":avatar", AttributeValues.fromString(avatar))),
Arguments.of(
new VersionedProfile(version, name, null, null, null, null, null, commitment),
new VersionedProfileV1(version, name, null, null, null, null, null, commitment),
Map.of(
":commitment", AttributeValues.fromByteArray(commitment),
":name", AttributeValues.fromByteArray(name))),
Arguments.of(
new VersionedProfile(version, null, null, null, null, null, null, commitment),
new VersionedProfileV1(version, null, null, null, null, null, null, commitment),
Map.of(":commitment", AttributeValues.fromByteArray(commitment)))
);
}
@@ -0,0 +1,467 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junitpioneer.jupiter.cartesian.CartesianTest;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.profiles.ProfileKey;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.CancellationReason;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsRequest;
import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledException;
@Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
public class ProfilesV2Test {
private static final UUID ACI = UUID.randomUUID();
@RegisterExtension
static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(Tables.PROFILES_V2);
private ProfilesV2 profilesV2;
private byte[] version;
private byte[] data;
private byte[] commitment;
private byte[] paymentAddress;
private VersionedProfile profile;
@BeforeEach
void setUp() throws InvalidInputException {
profilesV2 = new ProfilesV2(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
Tables.PROFILES_V2.tableName());
commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(ACI)).serialize();
version = TestRandomUtil.nextBytes(32);
data = TestRandomUtil.nextBytes(256);
paymentAddress = TestRandomUtil.nextBytes(582);
profile = new VersionedProfile(version, data, paymentAddress, commitment);
}
/// Generates a no-op transaction write item for tests that don’t need a real one
private TransactWriteItem getAdditionalTransactWriteItem() {
return TransactWriteItem.builder()
.conditionCheck(builder -> builder
.tableName(Tables.PROFILES_V2.tableName())
.key(Map.of(
ProfilesV2.KEY_ACCOUNT_UUID, AttributeValues.b(UUID.randomUUID()),
ProfilesV2.KEY_VERSION, AttributeValue.builder().b(SdkBytes.fromByteArray("not-a-real-version".getBytes())).build()))
.conditionExpression("attribute_not_exists(#uuid)")
.expressionAttributeNames(Map.of("#uuid", ProfilesV2.KEY_ACCOUNT_UUID)))
.build();
}
@Test
void testSetFirstWrite() throws WriteConflictException {
profilesV2.set(ACI, profile.version(), profile.data(), profile.dataHash(), profile.commitment(), profile.paymentAddress(), profile.paymentAddressHash(), null, getAdditionalTransactWriteItem());
final Optional<VersionedProfile> retrieved = profilesV2.get(ACI, version);
assertThat(retrieved.isPresent()).isTrue();
assertThat(retrieved.get().data()).isEqualTo(data);
assertThat(retrieved.get().commitment()).isEqualTo(commitment);
assertThat(retrieved.get().paymentAddress()).isEqualTo(paymentAddress);
assertThat(retrieved.get().dataHash()).isNotNull();
assertThat(retrieved.get().paymentAddressHash()).isNotNull();
}
@Test
void testSetWithoutPaymentAddress() throws WriteConflictException {
profilesV2.set(ACI, profile.version(), profile.data(), profile.dataHash(), profile.commitment(), null, null, null, getAdditionalTransactWriteItem());
final Optional<VersionedProfile> retrieved = profilesV2.get(ACI, version);
assertThat(retrieved.isPresent()).isTrue();
assertThat(retrieved.get().data()).isEqualTo(data);
assertThat(retrieved.get().commitment()).isEqualTo(commitment);
assertThat(retrieved.get().paymentAddress()).isNull();
assertThat(retrieved.get().paymentAddressHash()).isNull();
}
@Test
void testInitialSetRequiresCommitment() {
assertThrows(IllegalArgumentException.class, () -> {
profilesV2.set(ACI, profile.version(), profile.data(), profile.dataHash(), null, profile.paymentAddress(), profile.paymentAddressHash(), null, getAdditionalTransactWriteItem());
});
}
@Test
void testConditionalUpdateSuccess() throws WriteConflictException {
profilesV2.set(ACI, profile.version(), profile.data(), profile.dataHash(), profile.commitment(), profile.paymentAddress(), profile.paymentAddressHash(), null, getAdditionalTransactWriteItem());
Optional<VersionedProfile> retrieved = profilesV2.get(ACI, version);
assertThat(retrieved.isPresent()).isTrue();
// Update with correct expected hash
final byte[] newData = TestRandomUtil.nextBytes(256);
profilesV2.set(ACI, profile.version(), newData, VersionedProfile.hash(newData), profile.commitment(), profile.paymentAddress(), profile.paymentAddressHash(), retrieved.get().dataHash(), getAdditionalTransactWriteItem());
retrieved = profilesV2.get(ACI, version);
assertThat(retrieved.isPresent()).isTrue();
assertThat(retrieved.get().data()).isEqualTo(newData);
}
@Test
void testConditionalUpdateFailure() throws WriteConflictException {
profilesV2.set(ACI, profile.version(), profile.data(), profile.dataHash(), profile.commitment(), profile.paymentAddress(), profile.paymentAddressHash(),null, getAdditionalTransactWriteItem());
final byte[] wrongHash = TestRandomUtil.nextBytes(32);
assertThrows(WriteConflictException.class, () -> {
profilesV2.set(ACI, profile.version(), profile.data(), profile.dataHash(), profile.commitment(), profile.paymentAddress(), profile.paymentAddressHash(), wrongHash, getAdditionalTransactWriteItem());
});
// Verify data is unchanged
final Optional<VersionedProfile> retrieved = profilesV2.get(ACI, version);
assertThat(retrieved.isPresent()).isTrue();
assertThat(retrieved.get().data()).isEqualTo(data);
}
@Test
void testCommitmentImmutability() throws InvalidInputException, WriteConflictException {
profilesV2.set(ACI, profile.version(), profile.data(), profile.dataHash(), profile.commitment(), profile.paymentAddress(), profile.paymentAddressHash(),null, getAdditionalTransactWriteItem());
Optional<VersionedProfile> retrieved = profilesV2.get(ACI, version);
assertThat(retrieved.isPresent()).isTrue();
// Try to update with a different commitment
final byte[] newData = TestRandomUtil.nextBytes(256);
final byte[] differentCommitment = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
assertThrows(IllegalArgumentException.class,
() -> profilesV2.set(ACI, profile.version(), newData, VersionedProfile.hash(newData), differentCommitment, profile.paymentAddress(), profile.paymentAddressHash(), retrieved.get().dataHash(),
getAdditionalTransactWriteItem()));
}
@Test
void testUpdateWithNullCommitmentSucceeds() throws WriteConflictException {
profilesV2.set(ACI,profile.version(), profile.data(), profile.dataHash(), profile.commitment(), profile.paymentAddress(), profile.paymentAddressHash(),null, getAdditionalTransactWriteItem());
Optional<VersionedProfile> retrieved = profilesV2.get(ACI, version);
assertThat(retrieved.isPresent()).isTrue();
final byte[] originalCommitment = retrieved.get().commitment();
final byte[] newData = TestRandomUtil.nextBytes(256);
profilesV2.set(ACI, profile.version(), newData, VersionedProfile.hash(newData), null, profile.paymentAddress(), profile.paymentAddressHash(), retrieved.get().dataHash(), getAdditionalTransactWriteItem());
retrieved = profilesV2.get(ACI, version);
assertThat(retrieved.isPresent()).isTrue();
assertThat(retrieved.get().data()).isEqualTo(newData);
assertThat(retrieved.get().commitment()).isEqualTo(originalCommitment);
}
@Test
void testMultipleVersions() throws InvalidInputException, WriteConflictException {
final byte[] versionOne = TestRandomUtil.nextBytes(32);
final byte[] versionTwo = TestRandomUtil.nextBytes(32);
final byte[] dataOne = TestRandomUtil.nextBytes(256);
final byte[] dataTwo = TestRandomUtil.nextBytes(256);
final byte[] commitmentOne = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
final byte[] commitmentTwo = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
profilesV2.set(ACI, versionOne, dataOne, VersionedProfile.hash(dataOne), commitmentOne, paymentAddress,
VersionedProfile.hash(paymentAddress), null, getAdditionalTransactWriteItem());
profilesV2.set(ACI, versionTwo, dataTwo, VersionedProfile.hash(dataTwo), commitmentTwo, null, null,null, getAdditionalTransactWriteItem());
Optional<VersionedProfile> retrieved = profilesV2.get(ACI, versionOne);
assertThat(retrieved.isPresent()).isTrue();
assertThat(retrieved.get().data()).isEqualTo(dataOne);
assertThat(retrieved.get().commitment()).isEqualTo(commitmentOne);
assertThat(retrieved.get().paymentAddress()).isEqualTo(paymentAddress);
retrieved = profilesV2.get(ACI, versionTwo);
assertThat(retrieved.isPresent()).isTrue();
assertThat(retrieved.get().data()).isEqualTo(dataTwo);
assertThat(retrieved.get().commitment()).isEqualTo(commitmentTwo);
assertThat(retrieved.get().paymentAddress()).isNull();
}
@Test
void testMissing() throws WriteConflictException {
profilesV2.set(ACI, profile.version(), profile.data(), profile.dataHash(), profile.commitment(), profile.paymentAddress(), profile.paymentAddressHash(),null, getAdditionalTransactWriteItem());
final byte[] missingVersion = TestRandomUtil.nextBytes(32);
final Optional<VersionedProfile> retrieved = profilesV2.get(ACI, missingVersion);
assertThat(retrieved.isPresent()).isFalse();
}
@Test
void testDeleteAll() throws InvalidInputException, WriteConflictException {
final byte[] versionOne = TestRandomUtil.nextBytes(32);
final byte[] versionTwo = TestRandomUtil.nextBytes(32);
final byte[] versionThree = TestRandomUtil.nextBytes(32);
final byte[] dataOne = TestRandomUtil.nextBytes(256);
final byte[] dataTwo = TestRandomUtil.nextBytes(256);
final byte[] dataThree = TestRandomUtil.nextBytes(256);
final byte[] commitmentOne = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
final byte[] commitmentTwo = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
final byte[] commitmentThree = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
profilesV2.set(ACI, versionOne, dataOne, VersionedProfile.hash(dataOne), commitmentOne, paymentAddress, VersionedProfile.hash(paymentAddress), null, getAdditionalTransactWriteItem());
profilesV2.set(ACI, versionTwo, dataTwo, VersionedProfile.hash(dataTwo), commitmentTwo, paymentAddress, VersionedProfile.hash(paymentAddress), null, getAdditionalTransactWriteItem());
profilesV2.set(ACI, versionThree, dataThree, VersionedProfile.hash(dataThree), commitmentThree, null, null,null, getAdditionalTransactWriteItem());
profilesV2.deleteAll(ACI).join();
for (byte[] v : List.of(versionOne, versionTwo, versionThree)) {
final Optional<VersionedProfile> retrieved = profilesV2.get(ACI, v);
assertThat(retrieved.isPresent()).isFalse();
}
}
@Test
void testUpdatePaymentAddress() throws WriteConflictException {
profilesV2.set(ACI, profile.version(), profile.data(), profile.dataHash(), profile.commitment(), profile.paymentAddress(), profile.paymentAddressHash(),null, getAdditionalTransactWriteItem());
Optional<VersionedProfile> retrieved = profilesV2.get(ACI, version);
assertThat(retrieved.isPresent()).isTrue();
assertThat(retrieved.get().paymentAddress()).isEqualTo(paymentAddress);
// Update to remove payment address
final byte[] newData = TestRandomUtil.nextBytes(256);
profilesV2.set(ACI, version, newData, VersionedProfile.hash(newData), commitment, null, null, retrieved.get().dataHash(), getAdditionalTransactWriteItem());
retrieved = profilesV2.get(ACI, version);
assertThat(retrieved.isPresent()).isTrue();
assertThat(retrieved.get().data()).isEqualTo(newData);
assertThat(retrieved.get().paymentAddress()).isNull();
assertThat(retrieved.get().paymentAddressHash()).isNull();
}
@Test
void testSetWithAdditionalTransactWriteItemConflict() throws WriteConflictException {
profilesV2.set(ACI, version, data, VersionedProfile.hash(data), commitment, paymentAddress, VersionedProfile.hash(paymentAddress), null, getAdditionalTransactWriteItem());
final Optional<VersionedProfile> retrieved = profilesV2.get(ACI, version);
assertThat(retrieved.isPresent()).isTrue();
// write an update
final byte[] updatedData = TestRandomUtil.nextBytes(256);
profilesV2.set(ACI, version, updatedData, VersionedProfile.hash(updatedData), null, paymentAddress, VersionedProfile.hash(paymentAddress), retrieved.get().dataHash(), getAdditionalTransactWriteItem());
// attempt a second update with a stale hash
assertThrows(WriteConflictException.class, () -> {
final byte[] conflictedData = TestRandomUtil.nextBytes(256);
profilesV2.set(ACI, version, conflictedData, VersionedProfile.hash(conflictedData), null, paymentAddress, VersionedProfile.hash(paymentAddress), retrieved.get().dataHash(), getAdditionalTransactWriteItem());
});
// still has updatedData
final Optional<VersionedProfile> retrievedV2 = profilesV2.get(ACI, version);
assertThat(retrievedV2.isPresent()).isTrue();
assertThat(retrievedV2.get().data()).isEqualTo(updatedData);
}
@CartesianTest
void testGetTransactWriteItem(
@CartesianTest.Values(booleans = {true, false}) final boolean hasCommitment,
@CartesianTest.Values(booleans = {true, false}) final boolean hasExpectedDataHash) {
final byte[] commitment = hasCommitment ? profile.commitment() : null;
final byte[] expectedDataHash = hasExpectedDataHash ? TestRandomUtil.nextBytes(32) : null;
final TransactWriteItem transactWriteItem = profilesV2.getTransactWriteItem(
ACI, profile.version(), profile.data(), profile.dataHash(), commitment, profile.paymentAddress(), profile.paymentAddressHash(), expectedDataHash);
assertThat(transactWriteItem).isNotNull();
assertThat(transactWriteItem.update()).isNotNull();
assertThat(transactWriteItem.update().tableName()).isEqualTo(Tables.PROFILES_V2.tableName());
assertThat(transactWriteItem.update().key()).isNotNull();
assertThat(transactWriteItem.update().updateExpression()).isEqualTo(ProfilesV2.buildUpdateExpression(commitment != null, paymentAddress != null));
assertThat(transactWriteItem.update().conditionExpression()).isEqualTo(ProfilesV2.buildConditionExpression(commitment != null, expectedDataHash != null));
assertThat(transactWriteItem.update().expressionAttributeValues())
.isEqualTo(ProfilesV2.buildUpdateExpressionAttributeValues(data, profile.dataHash(), commitment, paymentAddress, profile.paymentAddressHash(), expectedDataHash));
}
@ParameterizedTest
@MethodSource
void testBuildUpdateExpression(final byte[] commitment, final byte[] paymentAddress, final String expectedUpdateExpression) {
assertEquals(expectedUpdateExpression, ProfilesV2.buildUpdateExpression(commitment != null, paymentAddress != null));
}
private static Stream<Arguments> testBuildUpdateExpression() {
final byte[] commitment = TestRandomUtil.nextBytes(32);
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
return Stream.of(
Arguments.argumentSet("with commitment and payment address",
commitment,
paymentAddress,
"SET #data = :data, #dataHash = :dataHash, #commitment = if_not_exists(#commitment, :commitment), #paymentAddress = :paymentAddress, #paymentAddressHash = :paymentAddressHash"),
Arguments.argumentSet("with commitment, without payment address",
commitment,
null,
"SET #data = :data, #dataHash = :dataHash, #commitment = if_not_exists(#commitment, :commitment) REMOVE #paymentAddress, #paymentAddressHash"),
Arguments.argumentSet("without commitment, with payment address",
null,
paymentAddress,
"SET #data = :data, #dataHash = :dataHash, #paymentAddress = :paymentAddress, #paymentAddressHash = :paymentAddressHash"),
Arguments.argumentSet("without commitment or payment address",
null,
null,
"SET #data = :data, #dataHash = :dataHash REMOVE #paymentAddress, #paymentAddressHash")
);
}
@ParameterizedTest
@MethodSource
void testBuildConditionExpression(final byte[] commitment, final byte[] expectedCurrentDataHash, final String expectedConditionExpression) {
assertEquals(expectedConditionExpression, ProfilesV2.buildConditionExpression(commitment != null, expectedCurrentDataHash != null));
}
private static Stream<Arguments> testBuildConditionExpression() {
final byte[] commitment = TestRandomUtil.nextBytes(97);
final byte[] dataHash = TestRandomUtil.nextBytes(32);
return Stream.of(
Arguments.argumentSet("initial write",
commitment,
null,
"(attribute_not_exists(#commitment) OR #commitment = :commitment) AND attribute_not_exists(#dataHash)"),
Arguments.argumentSet("update with commitment",
commitment,
dataHash,
"(attribute_not_exists(#commitment) OR #commitment = :commitment) AND #dataHash = :expectedDataHash"),
Arguments.argumentSet("update without commitment",
null,
dataHash,
"size(#commitment) = :commitment_length AND #dataHash = :expectedDataHash")
);
}
@ParameterizedTest
@MethodSource
void testBuildUpdateExpressionAttributeValues(
final byte[] data,
final byte[] dataHash,
final byte[] commitment,
final byte[] paymentAddress,
final byte[] paymentAddressHash,
final byte[] expectedCurrentDataHash,
final int expectedMapSize) {
final Map<String, AttributeValue> result = ProfilesV2.buildUpdateExpressionAttributeValues(
data, dataHash, commitment, paymentAddress, paymentAddressHash, expectedCurrentDataHash);
assertEquals(expectedMapSize, result.size());
assertThat(result.containsKey(":data")).isTrue();
assertThat(result.containsKey(":dataHash")).isTrue();
if (commitment != null) {
assertThat(result.containsKey(":commitment")).isTrue();
} else {
assertThat(result.containsKey(":commitment_length")).isTrue();
}
if (expectedCurrentDataHash != null) {
assertThat(result.containsKey(":expectedDataHash")).isTrue();
}
if (paymentAddress != null) {
assertThat(result.containsKey(":paymentAddress")).isTrue();
assertThat(result.containsKey(":paymentAddressHash")).isTrue();
}
}
private static Stream<Arguments> testBuildUpdateExpressionAttributeValues() throws InvalidInputException {
final byte[] data = TestRandomUtil.nextBytes(256);
final byte[] commitment = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
final byte[] dataHash = TestRandomUtil.nextBytes(32);
return Stream.of(
Arguments.argumentSet("all fields present",
data, VersionedProfile.hash(data), commitment, paymentAddress, VersionedProfile.hash(paymentAddress), dataHash, 6),
Arguments.argumentSet("no payment address",
data, VersionedProfile.hash(data), commitment, null, null, dataHash, 4),
Arguments.argumentSet("no commitment",
data, VersionedProfile.hash(data), null, paymentAddress, VersionedProfile.hash(paymentAddress), dataHash, 6),
Arguments.argumentSet("only data fields",
data, VersionedProfile.hash(data), null, null, null, dataHash, 4)
);
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@ParameterizedTest
@MethodSource
void testSetWithTransactionCanceledException(final Optional<List<String>> maybeCodes, final Class<? extends Exception> expectedException) throws InvalidInputException {
final DynamoDbClient dynamoDbClient = mock(DynamoDbClient.class);
final ProfilesV2 profilesV2 = new ProfilesV2(dynamoDbClient, mock(DynamoDbAsyncClient.class), Tables.PROFILES_V2.tableName());
final UUID uuid = UUID.randomUUID();
final byte[] version = TestRandomUtil.nextBytes(32);
final byte[] data = TestRandomUtil.nextBytes(256);
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(uuid)).serialize();
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
final byte[] expectedHash = TestRandomUtil.nextBytes(32);
final TransactionCanceledException.Builder exceptionBuilder = TransactionCanceledException.builder();
maybeCodes.ifPresent(codes -> {
final CancellationReason[] cancellationReasons = codes.stream().map(code ->
CancellationReason.builder().code(code).build())
.toArray(CancellationReason[]::new);
exceptionBuilder.cancellationReasons(cancellationReasons);
});
final TransactionCanceledException exception = exceptionBuilder.build();
when(dynamoDbClient.transactWriteItems(any(TransactWriteItemsRequest.class)))
.thenThrow(exception);
assertThrows(expectedException, () ->
profilesV2.set(uuid, version, data, VersionedProfile.hash(data), commitment, paymentAddress, VersionedProfile.hash(paymentAddress), expectedHash, getAdditionalTransactWriteItem()));
}
static Collection<Arguments> testSetWithTransactionCanceledException() {
return List.of(
Arguments.argumentSet("ConditionalCheckFailed throws WriteConflictException", Optional.of(List.of("ConditionalCheckFailed")), WriteConflictException.class),
Arguments.argumentSet("TransactionConflict throws WriteConflictException", Optional.of(List.of("TransactionConflict")), WriteConflictException.class),
Arguments.argumentSet("ConditionalCheckFailed throws WriteConflictException", Optional.of(List.of("ConditionalCheckFailed", "ThrottlingError")), WriteConflictException.class),
Arguments.argumentSet("ConditionalCheckFailed throws WriteConflictException", Optional.of(List.of("ThrottlingError", "ConditionalCheckFailed")), WriteConflictException.class),
Arguments.argumentSet("ThrottlingError throws TransactionCanceledException", Optional.of(List.of("ThrottlingError")), TransactionCanceledException.class),
Arguments.argumentSet("No code throws TransactionCanceledException", Optional.empty(), TransactionCanceledException.class)
);
}
}
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.tests.util;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyByte;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockingDetails;
import static org.mockito.Mockito.when;
@@ -16,16 +15,23 @@ import static org.mockito.Mockito.when;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import org.junit.platform.commons.util.StringUtils;
import org.mockito.MockingDetails;
import org.mockito.stubbing.Stubbing;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.entities.DeviceAttributes;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
@@ -62,8 +68,8 @@ public class AccountsHelper {
/**
* Sets up stubbing for:
* <ul>
* <li>{@link AccountsManager#update(Account, Consumer)}</li>
* <li>{@link AccountsManager#updateDevice(Account, byte, Consumer)}</li>
* <li>{@link AccountsManager#update(UUID, Consumer)}</li>
* <li>{@link AccountsManager#updateDevice(UUID, byte, Consumer)}</li>
* </ul>
*
* with multiple calls to the {@link Consumer<Account>}. This simulates retries from {@link org.whispersystems.textsecuregcm.storage.ContestedOptimisticLockException}.
@@ -78,67 +84,127 @@ public class AccountsHelper {
*/
@SuppressWarnings("unchecked")
public static void setupMockUpdateWithRetries(final AccountsManager mockAccountsManager, final int retryCount) {
when(mockAccountsManager.update(any(), any())).thenAnswer(answer -> {
final Account account = answer.getArgument(0, Account.class);
when(mockAccountsManager.update(any(UUID.class), any())).thenAnswer(invocation -> {
final UUID accountIdentifier = invocation.getArgument(0, UUID.class);
final Account account = mockAccountsManager.getByAccountIdentifier(accountIdentifier).orElseThrow();
for (int i = 0; i < retryCount; i++) {
answer.getArgument(1, Consumer.class).accept(account);
invocation.getArgument(1, Consumer.class).accept(account);
}
return account;
});
when(mockAccountsManager.update(any(Account.class), any())).thenAnswer(invocation -> {
final Account account = invocation.getArgument(0);
for (int i = 0; i < retryCount; i++) {
invocation.getArgument(1, Consumer.class).accept(account);
}
return copyAndMarkStale(account);
});
when(mockAccountsManager.updateDevice(any(), anyByte(), any())).thenAnswer(answer -> {
final Account account = answer.getArgument(0, Account.class);
when(mockAccountsManager.updateDevice(any(UUID.class), anyByte(), any())).thenAnswer(answer -> {
final UUID accountIdentifier = answer.getArgument(0, UUID.class);
final Account account = mockAccountsManager.getByAccountIdentifier(accountIdentifier).orElseThrow();
final byte deviceId = answer.getArgument(1, Byte.class);
for (int i = 0; i < retryCount; i++) {
account.getDevice(deviceId).ifPresent(answer.getArgument(2, Consumer.class));
}
return copyAndMarkStale(account);
return account;
});
}
@SuppressWarnings("unchecked")
private static void setupMockUpdate(final AccountsManager mockAccountsManager, final boolean markStale) {
when(mockAccountsManager.update(any(), any())).thenAnswer(answer -> {
final Account account = answer.getArgument(0, Account.class);
answer.getArgument(1, Consumer.class).accept(account);
when(mockAccountsManager.update(any(UUID.class), any())).thenAnswer(invocation -> {
final UUID accountIdentifier = invocation.getArgument(0, UUID.class);
final Account account = mockAccountsManager.getByAccountIdentifier(accountIdentifier).orElseThrow();
invocation.getArgument(1, Consumer.class).accept(account);
return account;
});
when(mockAccountsManager.update(any(Account.class), any())).thenAnswer(invocation -> {
final Account account = invocation.getArgument(0);
invocation.getArgument(1, Consumer.class).accept(account);
return markStale ? copyAndMarkStale(account) : account;
});
when(mockAccountsManager.updateDevice(any(), anyByte(), any())).thenAnswer(answer -> {
final Account account = answer.getArgument(0, Account.class);
final byte deviceId = answer.getArgument(1, Byte.class);
account.getDevice(deviceId).ifPresent(answer.getArgument(2, Consumer.class));
when(mockAccountsManager.updateDevice(any(), anyByte(), any())).thenAnswer(invocation -> {
final UUID accountIdentifier = invocation.getArgument(0, UUID.class);
final Account account = mockAccountsManager.getByAccountIdentifier(accountIdentifier).orElseThrow();
return markStale ? copyAndMarkStale(account) : account;
final byte deviceId = invocation.getArgument(1, Byte.class);
account.getDevice(deviceId).ifPresent(invocation.getArgument(2, Consumer.class));
return account;
});
when(mockAccountsManager.updateDeviceLastSeen(any(), any(), anyLong())).thenAnswer(answer -> {
answer.getArgument(1, Device.class).setLastSeen(answer.getArgument(2, Long.class));
return mockAccountsManager.update(answer.getArgument(0, Account.class), account -> {});
when(mockAccountsManager.updateDeviceLastSeen(any(), any(), anyLong())).thenAnswer(invocation -> {
final UUID accountIdentifier = invocation.getArgument(0, UUID.class);
final Account account = mockAccountsManager.getByAccountIdentifier(accountIdentifier).orElseThrow();
final Device device = account.getDevice(invocation.getArgument(1, Device.class).getId()).orElseThrow();
device.setLastSeen(invocation.getArgument(2, Long.class));
return mockAccountsManager.update(accountIdentifier, _ -> {});
});
}
public static void setupMockGet(final AccountsManager mockAccountsManager, final Set<Account> mockAccounts) {
when(mockAccountsManager.getByAccountIdentifier(any(UUID.class))).thenAnswer(answer -> {
public static void setupMockGet(final AccountsManager mockAccountsManager, final Account account) {
if (account.getUuid() != null || account.getIdentifier(IdentityType.ACI) != null) {
final UUID accountIdentifier =
Objects.requireNonNullElseGet(account.getIdentifier(IdentityType.ACI), account::getUuid);
final UUID uuid = answer.getArgument(0, UUID.class);
when(mockAccountsManager.getByAccountIdentifier(accountIdentifier))
.thenReturn(Optional.of(account));
return mockAccounts.stream()
.filter(account -> uuid.equals(account.getUuid()))
.findFirst()
.map(account -> {
try {
return copyAndMarkStale(account);
} catch (final Exception e) {
throw new RuntimeException(e);
}
});
});
when(mockAccountsManager.getByAccountIdentifierAsync(accountIdentifier))
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
when(mockAccountsManager.getByServiceIdentifier(new AciServiceIdentifier(accountIdentifier)))
.thenReturn(Optional.of(account));
when(mockAccountsManager.getByServiceIdentifierAsync(new AciServiceIdentifier(accountIdentifier)))
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
}
if (account.getPhoneNumberIdentifier() != null || account.getIdentifier(IdentityType.PNI) != null) {
final UUID phoneNumberIdentifier =
Objects.requireNonNullElseGet(account.getIdentifier(IdentityType.PNI), account::getPhoneNumberIdentifier);
when(mockAccountsManager.getByPhoneNumberIdentifier(phoneNumberIdentifier))
.thenReturn(Optional.of(account));
when(mockAccountsManager.getByPhoneNumberIdentifierAsync(phoneNumberIdentifier))
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
when(mockAccountsManager.getByServiceIdentifier(new PniServiceIdentifier(phoneNumberIdentifier)))
.thenReturn(Optional.of(account));
when(mockAccountsManager.getByServiceIdentifierAsync(new PniServiceIdentifier(phoneNumberIdentifier)))
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
}
if (StringUtils.isNotBlank(account.getNumber())) {
when(mockAccountsManager.getByE164(account.getNumber())).thenReturn(Optional.of(account));
}
account.getUsernameHash().ifPresent(usernameHash -> when(mockAccountsManager.getByUsernameHash(usernameHash))
.thenReturn(CompletableFuture.completedFuture(Optional.of(account))));
if (account.getUsernameLinkHandle() != null) {
when(mockAccountsManager.getByUsernameLinkHandle(account.getUsernameLinkHandle()))
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
}
}
private static Account copyAndMarkStale(Account account) throws IOException {
@@ -190,14 +256,11 @@ public class AccountsHelper {
return updatedAccount;
}
public static Account eqUuid(Account value) {
return argThat(other -> other.getUuid().equals(value.getUuid()));
}
public static Account createAccount(final AccountsManager accountsManager, final String e164)
throws InterruptedException {
return createAccount(accountsManager, e164, new AccountAttributes());
return createAccount(accountsManager, e164, new AccountAttributes().setDeviceAttributes(
new DeviceAttributes(false, 1, 1, new byte[0], Collections.emptySet())));
}
public static Account createAccount(final AccountsManager accountsManager, final String e164, final AccountAttributes accountAttributes)
@@ -166,7 +166,7 @@ public class AuthHelper {
when(VALID_ACCOUNT_TWO.getUuid()).thenReturn(VALID_UUID_TWO);
when(VALID_ACCOUNT_TWO.getPhoneNumberIdentifier()).thenReturn(VALID_PNI_TWO);
when(VALID_ACCOUNT_TWO.getIdentifier(IdentityType.ACI)).thenReturn(VALID_UUID_TWO);
when(VALID_ACCOUNT_TWO.getPhoneNumberIdentifier()).thenReturn(VALID_PNI_TWO);
when(VALID_ACCOUNT_TWO.getIdentifier(IdentityType.PNI)).thenReturn(VALID_PNI_TWO);
when(UNDISCOVERABLE_ACCOUNT.getNumber()).thenReturn(UNDISCOVERABLE_NUMBER);
when(UNDISCOVERABLE_ACCOUNT.getUuid()).thenReturn(UNDISCOVERABLE_UUID);
when(UNDISCOVERABLE_ACCOUNT.getPhoneNumberIdentifier()).thenReturn(UNDISCOVERABLE_PNI);
@@ -236,6 +236,7 @@ public class AuthHelper {
}
public static String getUnidentifiedAccessHeader(byte[] key) {
assert key.length == 16;
return Base64.getEncoder().encodeToString(key);
}
@@ -16,12 +16,14 @@ import static org.mockito.Mockito.when;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import java.util.UUID;
import java.util.stream.Stream;
import net.sourceforge.argparse4j.inf.Namespace;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import reactor.core.publisher.Flux;
@@ -64,10 +66,15 @@ class RemoveExpiredAccountsCommandTest {
final RemoveExpiredAccountsCommand removeExpiredAccountsCommand =
new TestRemoveExpiredAccountsCommand(clock, accountsManager, isDryRun);
final UUID activeAccountIdentifier = UUID.randomUUID();
final UUID expiredAccountIdentifier = UUID.randomUUID();
final Account activeAccount = mock(Account.class);
when(activeAccount.getIdentifier(IdentityType.ACI)).thenReturn(activeAccountIdentifier);
when(activeAccount.getLastSeen()).thenReturn(clock.instant().toEpochMilli());
final Account expiredAccount = mock(Account.class);
when(expiredAccount.getIdentifier(IdentityType.ACI)).thenReturn(expiredAccountIdentifier);
when(expiredAccount.getLastSeen())
.thenReturn(clock.instant().minus(RemoveExpiredAccountsCommand.MAX_IDLE_DURATION).minusMillis(1).toEpochMilli());
@@ -76,8 +83,8 @@ class RemoveExpiredAccountsCommandTest {
if (isDryRun) {
verify(accountsManager, never()).delete(any(), any());
} else {
verify(accountsManager).delete(expiredAccount, AccountsManager.DeletionReason.EXPIRED);
verify(accountsManager, never()).delete(eq(activeAccount), any());
verify(accountsManager).delete(expiredAccountIdentifier, AccountsManager.DeletionReason.EXPIRED);
verify(accountsManager, never()).delete(eq(activeAccountIdentifier), any());
}
}
@@ -23,6 +23,7 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Consumer;
import java.util.stream.IntStream;
@@ -31,6 +32,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.util.TestClock;
@@ -76,7 +78,10 @@ class RemoveExpiredUsernameHoldsCommandTest {
final RemoveExpiredUsernameHoldsCommand removeExpiredUsernameHoldsCommand =
new TestRemoveExpiredUsernameHoldsCommand(clock, accountsManager, isDryRun);
final UUID hasHoldsAccountIdentifier = UUID.randomUUID();
final Account hasHolds = mock(Account.class);
when(hasHolds.getIdentifier(IdentityType.ACI)).thenReturn(hasHoldsAccountIdentifier);
final List<Account.UsernameHold> originalHolds = List.of(
// expired
new Account.UsernameHold(TestRandomUtil.nextBytes(32), Instant.EPOCH.getEpochSecond()),
@@ -92,7 +97,7 @@ class RemoveExpiredUsernameHoldsCommandTest {
verifyNoInteractions(accountsManager);
} else {
ArgumentCaptor<Consumer<Account>> updaterCaptor = ArgumentCaptor.forClass(Consumer.class);
verify(accountsManager, times(1)).update(eq(hasHolds), updaterCaptor.capture());
verify(accountsManager, times(1)).update(eq(hasHoldsAccountIdentifier), updaterCaptor.capture());
final Consumer<Account> consumer = updaterCaptor.getValue();
consumer.accept(hasHolds);
verify(hasHolds, times(1)).setUsernameHolds(argThat(holds ->
Loaded 100 of 105 files, more files were not shown because too many files have changed in this diff. Show more