Compare commits

...
Author SHA1 Message Date
Jonathan Klabunde Tomer 6421438f64 Delete deleted-account records by PNI as well as e164 2024-11-22 15:36:15 -05:00
Jon Chambers 8a63682c16 Drop the unused PhoneNumberIdentifiers#getPhoneNumber method 2024-11-22 15:26:44 -05:00
Jon Chambers 13a8c6256d Delete registration recovery passwords by both phone number and PNI 2024-11-22 15:26:44 -05:00
Jon Chambers 8c9cc4cce5 Make PhoneNumberIdentifiers operations asynchronous 2024-11-22 15:26:44 -05:00
Jon Chambers 0023cb2521 Resolve minor warnings/suggestions 2024-11-22 15:10:00 -05:00
Jon Chambers 010ed77345 Use libphonenumber to get country codes 2024-11-22 15:10:00 -05:00
Jon Chambers 00c11f5dd0 Use a more conventional name for a static constant 2024-11-22 15:10:00 -05:00
Jon Chambers 637e424506 Remove an unused "get number prefix" method 2024-11-22 15:10:00 -05:00
Chris Eager eb55b80bdc Add PNI support to AccountLockManager 2024-11-22 14:09:52 -06:00
Chris Eager 73812b06be Fix class names in logger initialization 2024-11-21 16:09:41 -06:00
Ravi Khadiwala d135957f0d Cancel past_due subscriptions immediately 2024-11-21 16:09:17 -06:00
Chris Eager 815fd44ab3 Update to the latest version of the spam filter 2024-11-21 16:08:08 -06:00
Chris Eager 4e8a48ab3d Update MicrometerAwsSdkMetricPublisher maxConcurrency metric name 2024-11-21 16:07:24 -06:00
Chris Eager ea75c39b58 Use MRM shared data views 2024-11-19 15:31:31 -06:00
Jon Chambers 085f013bf9 Update to libphonenumber 8.13.50 in preparation for Benin phone number format changes 2024-11-19 16:20:43 -05:00
Ameya Lokare c6b8d890e5 Update to the latest version of the spam filter 2024-11-15 12:30:38 -08:00
Jon Chambers 66783c9381 Include new/previous push token types as dimensions on "account created" counter 2024-11-15 15:28:46 -05:00
Jon Chambers b32e67ff9e Resolve minor warnings/suggestions in AccountsManager 2024-11-15 15:28:46 -05:00
Alex Konradi ba55d6caeb Only vend new credential format
Remove the flag that controlled which format was requested, and always return
the new thing.
2024-11-15 12:27:56 -08:00
Ravi Khadiwala 1eba04d37b Fix incorrect update target 2024-11-15 14:11:55 -06:00
Chris Eager ecbb2f1399 Updates for org.apache.commons.lang3.RandomStringUtils deprecations 2024-11-15 14:11:41 -06:00
Chris Eager 93f4a91ebf Remove some deprecated/unused code 2024-11-15 14:11:41 -06:00
Chris Eager a1ac5bd74c Bind maven-dependency-plugin properties goal to the process-test-classes phase 2024-11-15 14:11:04 -06:00
Chris Eager 0ca9e973ad Add ephemeral tag to MRM error retrieval counter 2024-11-12 15:00:36 -06:00
Chris Eager ee5df0e11c Always store and fetch shared MRM data 2024-11-12 10:57:30 -06:00
Chris Eager d53a6e4c42 Add counter for skipped stale ephemeral MRM fetches 2024-11-12 10:56:12 -06:00
Chris Eager 744042e8c8 Address some warnings in maven execution 2024-11-12 10:55:10 -06:00
Jon Chambers 444f6ca826 Consolidate "closed connection" errors, but add an "exception" dimension 2024-11-12 11:54:47 -05:00
Jon Chambers 0ea13ec528 Handle static "closed" exceptions 2024-11-12 11:54:47 -05:00
Jon Chambers 6845ba9b90 Remove legacy DisconnectRequested protobuf entity 2024-11-12 11:54:36 -05:00
61 changed files with 596 additions and 644 deletions

No files matched your search

@@ -12,6 +12,7 @@ import java.util.concurrent.CompletableFuture;
import org.signal.integration.config.Config;
import org.whispersystems.textsecuregcm.metrics.NoopAwsSdkMetricPublisher;
import org.whispersystems.textsecuregcm.registration.VerificationSession;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswords;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
@@ -37,6 +38,9 @@ public class IntegrationTools {
final DynamoDbClient dynamoDbClient =
config.dynamoDbClient().buildSyncClient(credentialsProvider, new NoopAwsSdkMetricPublisher());
final PhoneNumberIdentifiers phoneNumberIdentifiers =
new PhoneNumberIdentifiers(dynamoDbAsyncClient, config.dynamoDbTables().phoneNumberIdentifiers());
final RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
config.dynamoDbTables().registrationRecovery(), Duration.ofDays(1), dynamoDbClient, dynamoDbAsyncClient);
@@ -44,7 +48,7 @@ public class IntegrationTools {
dynamoDbAsyncClient, config.dynamoDbTables().verificationSessions(), Clock.systemUTC());
return new IntegrationTools(
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords),
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords, phoneNumberIdentifiers),
new VerificationSessionManager(verificationSessions)
);
}
@@ -8,5 +8,6 @@ package org.signal.integration.config;
import jakarta.validation.constraints.NotBlank;
public record DynamoDbTables(@NotBlank String registrationRecovery,
@NotBlank String verificationSessions) {
@NotBlank String verificationSessions,
@NotBlank String phoneNumberIdentifiers) {
}
+16 -2
View File
@@ -58,7 +58,7 @@
<kotlin.version>1.9.24</kotlin.version>
<kotlinx-serialization.version>1.5.1</kotlinx-serialization.version>
<lettuce.version>6.4.1.RELEASE</lettuce.version>
<libphonenumber.version>8.13.49</libphonenumber.version>
<libphonenumber.version>8.13.50</libphonenumber.version>
<logstash.logback.version>7.3</logstash.logback.version>
<log4j-bom.version>2.23.1</log4j-bom.version>
<luajava.version>3.4.0</luajava.version>
@@ -481,7 +481,21 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.7.1</version>
<version>3.8.1</version>
<executions>
<execution>
<!--
Set dependencies as properties for use in argLine property for mockito jar.
The property isn't needed until the test phase, and deferring it from the default
`initialize` addresses issues running lifecycle phases that precede `test` in isolation.
-->
<phase>process-test-classes</phase>
<goals>
<goal>properties</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
+2 -2
View File
@@ -698,8 +698,8 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<!-- work around PATCH not being a supported method on HttpUrlConnection -->
<argLine>--add-opens=java.base/java.net=ALL-UNNAMED</argLine>
<!-- add-opens: work around PATCH not being a supported method on HttpUrlConnection -->
<argLine>-javaagent:${org.mockito:mockito-core:jar} --add-opens=java.base/java.net=ALL-UNNAMED</argLine>
</configuration>
</plugin>
@@ -404,7 +404,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getDynamoDbTables().getAccounts().getUsedLinkDeviceTokensTableName());
ClientReleases clientReleases = new ClientReleases(dynamoDbAsyncClient,
config.getDynamoDbTables().getClientReleases().getTableName());
PhoneNumberIdentifiers phoneNumberIdentifiers = new PhoneNumberIdentifiers(dynamoDbClient,
PhoneNumberIdentifiers phoneNumberIdentifiers = new PhoneNumberIdentifiers(dynamoDbAsyncClient,
config.getDynamoDbTables().getPhoneNumberIdentifiers().getTableName());
Profiles profiles = new Profiles(dynamoDbClient, dynamoDbAsyncClient,
config.getDynamoDbTables().getProfiles().getTableName());
@@ -583,8 +583,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
ExperimentEnrollmentManager experimentEnrollmentManager = new ExperimentEnrollmentManager(
dynamicConfigurationManager);
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager = new RegistrationRecoveryPasswordsManager(
registrationRecoveryPasswords);
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager =
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords, phoneNumberIdentifiers);
UsernameHashZkProofVerifier usernameHashZkProofVerifier = new UsernameHashZkProofVerifier();
RegistrationServiceClient registrationServiceClient = config.getRegistrationServiceConfiguration()
@@ -603,7 +603,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient, disconnectionRequestListenerExecutor);
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster);
MessagesCache messagesCache = new MessagesCache(messagesCluster, messageDeliveryScheduler,
messageDeletionAsyncExecutor, clock, dynamicConfigurationManager);
messageDeletionAsyncExecutor, clock);
ClientReleaseManager clientReleaseManager = new ClientReleaseManager(clientReleases,
recurringJobExecutor,
config.getClientReleaseConfiguration().refreshInterval(),
@@ -27,7 +27,6 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
@@ -48,7 +48,7 @@ import org.whispersystems.textsecuregcm.util.Util;
*/
public class BackupAuthManager {
private static final Logger logger = LoggerFactory.getLogger(BackupManager.class);
private static final Logger logger = LoggerFactory.getLogger(BackupAuthManager.class);
final static Duration MAX_REDEMPTION_DURATION = Duration.ofDays(7);
@@ -238,7 +238,7 @@ public class BackupAuthManager {
return accountsManager.updateAsync(account, a -> {
final Account.BackupVoucher newPayment = new Account.BackupVoucher(receiptLevel, receiptExpiration);
final Account.BackupVoucher existingPayment = a.getBackupVoucher();
account.setBackupVoucher(merge(existingPayment, newPayment));
a.setBackupVoucher(merge(existingPayment, newPayment));
});
})
.thenRun(Util.NOOP);
@@ -1,22 +0,0 @@
/*
* Copyright 2021 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.databind.util.StdConverter;
import java.net.MalformedURLException;
import java.net.URL;
final class URLDeserializationConverter extends StdConverter<String, URL> {
@Override
public URL convert(final String value) {
try {
return new URL(value);
} catch (MalformedURLException e) {
throw new IllegalArgumentException(e);
}
}
}
@@ -68,10 +68,6 @@ public class DynamicConfiguration {
@Valid
DynamicMetricsConfiguration metricsConfiguration = new DynamicMetricsConfiguration(false);
@JsonProperty
@Valid
DynamicMessagesConfiguration messagesConfiguration = new DynamicMessagesConfiguration();
@JsonProperty
@Valid
List<String> svrStatusCodesToIgnoreForAccountDeletion = Collections.emptyList();
@@ -130,10 +126,6 @@ public class DynamicConfiguration {
return metricsConfiguration;
}
public DynamicMessagesConfiguration getMessagesConfiguration() {
return messagesConfiguration;
}
public List<String> getSvrStatusCodesToIgnoreForAccountDeletion() {
return svrStatusCodesToIgnoreForAccountDeletion;
}
@@ -1,14 +0,0 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration.dynamic;
public record DynamicMessagesConfiguration(boolean storeSharedMrmData, boolean fetchSharedMrmData,
boolean useSharedMrmData) {
public DynamicMessagesConfiguration() {
this(false, false, false);
}
}
@@ -11,7 +11,6 @@ import com.google.common.annotations.VisibleForTesting;
import com.google.common.net.HttpHeaders;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.ws.rs.BadRequestException;
import jakarta.ws.rs.DefaultValue;
@@ -39,7 +38,6 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
import org.whispersystems.textsecuregcm.entities.DeliveryCertificate;
import org.whispersystems.textsecuregcm.entities.GroupCredentials;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.websocket.auth.ReadOnly;
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@@ -56,8 +54,6 @@ public class CertificateController {
public static final Duration MAX_REDEMPTION_DURATION = Duration.ofDays(7);
private static final String GENERATE_DELIVERY_CERTIFICATE_COUNTER_NAME = name(CertificateGenerator.class, "generateCertificate");
private static final String INCLUDE_E164_TAG_NAME = "includeE164";
private static final String GET_GROUP_AUTHENTICATION_CREDENTIALS_COUNTER_NAME = name(CertificateController.class,
"getGroupAuthenticationCredentials");
public CertificateController(
@Nonnull CertificateGenerator certificateGenerator,
@@ -91,8 +87,7 @@ public class CertificateController {
@ReadOnly @Auth AuthenticatedDevice auth,
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent,
@QueryParam("redemptionStartSeconds") long startSeconds,
@QueryParam("redemptionEndSeconds") long endSeconds,
@QueryParam("zkcCredential") boolean zkcCredential) {
@QueryParam("redemptionEndSeconds") long endSeconds) {
final Instant startOfDay = clock.instant().truncatedTo(ChronoUnit.DAYS);
final Instant redemptionStart = Instant.ofEpochSecond(startSeconds);
@@ -107,11 +102,6 @@ public class CertificateController {
throw new BadRequestException();
}
Metrics
.counter(GET_GROUP_AUTHENTICATION_CREDENTIALS_COUNTER_NAME,
Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)).and("zkcCredential", String.valueOf(zkcCredential)))
.increment();
final List<GroupCredentials.GroupCredential> credentials = new ArrayList<>();
final List<GroupCredentials.CallLinkAuthCredential> callLinkAuthCredentials = new ArrayList<>();
@@ -121,12 +111,7 @@ public class CertificateController {
ServiceId.Pni pni = new ServiceId.Pni(auth.getAccount().getPhoneNumberIdentifier());
while (!redemption.isAfter(redemptionEnd)) {
AuthCredentialWithPniResponse authCredentialWithPni;
if (zkcCredential) {
authCredentialWithPni = serverZkAuthOperations.issueAuthCredentialWithPniZkc(aci, pni, redemption);
} else {
authCredentialWithPni = serverZkAuthOperations.issueAuthCredentialWithPniAsServiceId(aci, pni, redemption);
}
AuthCredentialWithPniResponse authCredentialWithPni = serverZkAuthOperations.issueAuthCredentialWithPniZkc(aci, pni, redemption);
credentials.add(new GroupCredentials.GroupCredential(
authCredentialWithPni.serialize(),
(int) redemption.getEpochSecond()));
@@ -655,10 +655,7 @@ public class MessageController {
}
try {
@Nullable final byte[] sharedMrmKey =
dynamicConfigurationManager.getConfiguration().getMessagesConfiguration().storeSharedMrmData()
? messagesManager.insertSharedMultiRecipientMessagePayload(multiRecipientMessage)
: null;
final byte[] sharedMrmKey = messagesManager.insertSharedMultiRecipientMessagePayload(multiRecipientMessage);
CompletableFuture.allOf(
recipients.values().stream()
@@ -941,7 +938,7 @@ public class MessageController {
boolean story,
boolean urgent,
byte[] payload,
@Nullable byte[] sharedMrmKey) {
byte[] sharedMrmKey) {
final Envelope.Builder messageBuilder = Envelope.newBuilder();
final long serverTimestamp = System.currentTimeMillis();
@@ -952,13 +949,8 @@ public class MessageController {
.setServerTimestamp(serverTimestamp)
.setStory(story)
.setUrgent(urgent)
.setDestinationServiceId(serviceIdentifier.toServiceIdentifierString());
if (sharedMrmKey != null) {
messageBuilder.setSharedMrmKey(ByteString.copyFrom(sharedMrmKey));
}
// mrm views phase 2: always set content
messageBuilder.setContent(ByteString.copyFrom(payload));
.setDestinationServiceId(serviceIdentifier.toServiceIdentifierString())
.setSharedMrmKey(ByteString.copyFrom(sharedMrmKey));
messageSender.sendMessage(destinationAccount, destinationDevice, messageBuilder.build(), online);
}
@@ -78,7 +78,7 @@ import org.whispersystems.websocket.auth.ReadOnly;
@io.swagger.v3.oas.annotations.tags.Tag(name = "OneTimeDonations")
public class OneTimeDonationController {
private static final Logger logger = LoggerFactory.getLogger(SubscriptionController.class);
private static final Logger logger = LoggerFactory.getLogger(OneTimeDonationController.class);
private static final String EURO_CURRENCY_CODE = "EUR";
@@ -4,16 +4,15 @@ import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.Timer;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.metrics.MetricPublisher;
import software.amazon.awssdk.metrics.MetricRecord;
import java.time.Duration;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.metrics.MetricPublisher;
import software.amazon.awssdk.metrics.MetricRecord;
/**
* A Micrometer AWS SDK metric publisher consumes {@link MetricCollection} instances provided by the AWS SDK when it
@@ -80,6 +79,9 @@ public class MicrometerAwsSdkMetricPublisher implements MetricPublisher {
private static final String CONCURRENT_REQUESTS_DISTRIBUTION_NAME =
MetricsUtil.name(MicrometerAwsSdkMetricPublisher.class, "concurrentRequests");
private static final String MAX_CONCURRENCY_GAUGE_NAME =
MetricsUtil.name(MicrometerAwsSdkMetricPublisher.class, "maxConcurrency");
private static final String CLIENT_NAME_TAG = "clientName";
/**
@@ -93,7 +95,7 @@ public class MicrometerAwsSdkMetricPublisher implements MetricPublisher {
this.recordMetricsExecutorService = recordMetricsExecutorService;
this.awsClientName = awsClientName;
mostRecentMaxConcurrency = Metrics.gauge("maxConcurrency",
mostRecentMaxConcurrency = Metrics.gauge(MAX_CONCURRENCY_GAUGE_NAME,
Tags.of(CLIENT_NAME_TAG, awsClientName),
new AtomicInteger(0));
}
@@ -333,10 +333,6 @@ public class WebSocketConnectionEventManager extends RedisClusterPubSubAdapter<b
}
}
case DISCONNECT_REQUESTED -> {
// Handle events from `DisconnectionRequestManager` instead
}
case MESSAGES_PERSISTED -> listenerEventExecutor.execute(listener::handleMessagesPersisted);
default -> logger.warn("Unexpected client event type: {}", clientEvent.getClass());
@@ -124,10 +124,6 @@ public class IdentityTokenCallCredentials extends CallCredentials implements Man
}
}
@Override
public void thisUsesUnstableApi() {
}
@Override
public void stop() {
synchronized (this) {
@@ -8,11 +8,13 @@ import com.amazonaws.services.dynamodbv2.ReleaseLockOptions;
import com.google.common.annotations.VisibleForTesting;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.Stream;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
public class AccountLockManager {
@@ -43,28 +45,35 @@ public class AccountLockManager {
* account lifecycle changes (like deleting an account or changing a phone number). The given task runs once locks for
* all given phone numbers have been acquired, and the locks are released as soon as the task completes by any means.
*
* @param e164s the phone numbers for which to acquire a distributed, pessimistic lock
* @param task the task to execute once locks have been acquired
* @param e164s the phone numbers for which to acquire a distributed, pessimistic lock
* @param phoneNumberIdentifiers the phone number identifiers for which to acquire a distributed, pessimistic lock
* @param task the task to execute once locks have been acquired
* @param lockAcquisitionExecutor the executor on which to run blocking lock acquire/release tasks. this executor
* should not use virtual threads.
*
* @throws InterruptedException if interrupted while acquiring a lock
*/
public void withLock(final List<String> e164s, final Runnable task, final Executor lockAcquisitionExecutor) {
public void withLock(final List<String> e164s, final List<UUID> phoneNumberIdentifiers, final Runnable task,
final Executor lockAcquisitionExecutor) {
if (e164s.isEmpty()) {
throw new IllegalArgumentException("List of e164s to lock must not be empty");
}
if (phoneNumberIdentifiers.isEmpty()) {
throw new IllegalArgumentException("List of PNIs to lock must not be empty");
}
final List<LockItem> lockItems = new ArrayList<>(e164s.size());
final List<String> allIdentifiers = Stream.concat(e164s.stream(),
phoneNumberIdentifiers.stream().map(UUID::toString))
.toList();
final List<LockItem> lockItems = new ArrayList<>(allIdentifiers.size());
try {
// Offload the acquire/release tasks to the dedicated lock acquisition executor. The lock client performs blocking
// operations while holding locks which forces thread pinning when this method runs on a virtual thread.
// https://github.com/awslabs/amazon-dynamodb-lock-client/issues/97
CompletableFuture.runAsync(() -> {
for (final String e164 : e164s) {
for (final String identifier : allIdentifiers) {
try {
lockItems.add(lockClient.acquireLock(AcquireLockOptions.builder(e164)
lockItems.add(lockClient.acquireLock(AcquireLockOptions.builder(identifier)
.withAcquireReleasedLocksConsistently(true)
.build()));
} catch (final InterruptedException e) {
@@ -91,27 +100,32 @@ public class AccountLockManager {
* account lifecycle changes (like deleting an account or changing a phone number). The given task runs once locks for
* all given phone numbers have been acquired, and the locks are released as soon as the task completes by any means.
*
* @param e164s the phone numbers for which to acquire a distributed, pessimistic lock
* @param taskSupplier a supplier for the task to execute once locks have been acquired
* @param executor the executor on which to acquire and release locks
*
* @param e164s the phone numbers for which to acquire a distributed, pessimistic lock
* @param phoneNumberIdentifiers the phone number identifiers for which to acquire a distributed, pessimistic lock
* @param taskSupplier a supplier for the task to execute once locks have been acquired
* @param executor the executor on which to acquire and release locks
* @return a future that completes normally when the given task has executed successfully and all locks have been
* released; the returned future may fail with an {@link InterruptedException} if interrupted while acquiring a lock
*/
public <T> CompletableFuture<T> withLockAsync(final List<String> e164s,
final Supplier<CompletableFuture<T>> taskSupplier,
final Executor executor) {
public <T> CompletableFuture<T> withLockAsync(final List<String> e164s, final List<UUID> phoneNumberIdentifiers,
final Supplier<CompletableFuture<T>> taskSupplier, final Executor executor) {
if (e164s.isEmpty()) {
throw new IllegalArgumentException("List of e164s to lock must not be empty");
}
if (phoneNumberIdentifiers.isEmpty()) {
throw new IllegalArgumentException("List of PNIs to lock must not be empty");
}
final List<LockItem> lockItems = new ArrayList<>(e164s.size());
final List<String> allIdentifiers = Stream.concat(e164s.stream(),
phoneNumberIdentifiers.stream().map(UUID::toString))
.toList();
final List<LockItem> lockItems = new ArrayList<>(allIdentifiers.size());
return CompletableFuture.runAsync(() -> {
for (final String e164 : e164s) {
for (final String identifier : allIdentifiers) {
try {
lockItems.add(lockClient.acquireLock(AcquireLockOptions.builder(e164)
lockItems.add(lockClient.acquireLock(AcquireLockOptions.builder(identifier)
.withAcquireReleasedLocksConsistently(true)
.build()));
} catch (final InterruptedException e) {
@@ -240,9 +240,10 @@ public class Accounts extends AbstractDynamoDbStore {
// Clear any "recently deleted account" record for this number since, if it existed, we've used its old ACI for
// the newly-created account.
final TransactWriteItem deletedAccountDelete = buildRemoveDeletedAccount(account.getNumber());
final TransactWriteItem deletedAccountDeletePNI = buildRemoveDeletedAccount(account.getPhoneNumberIdentifier());
final Collection<TransactWriteItem> writeItems = new ArrayList<>(
List.of(phoneNumberConstraintPut, phoneNumberIdentifierConstraintPut, accountPut, deletedAccountDelete));
List.of(phoneNumberConstraintPut, phoneNumberIdentifierConstraintPut, accountPut, deletedAccountDeletePNI, deletedAccountDelete));
writeItems.addAll(additionalWriteItems);
@@ -436,6 +437,7 @@ public class Accounts extends AbstractDynamoDbStore {
writeItems.add(buildDelete(phoneNumberIdentifierConstraintTableName, ATTR_PNI_UUID, originalPni));
writeItems.add(buildConstraintTablePut(phoneNumberIdentifierConstraintTableName, uuidAttr, ATTR_PNI_UUID, pniAttr));
writeItems.add(buildRemoveDeletedAccount(number));
writeItems.add(buildRemoveDeletedAccount(phoneNumberIdentifier));
maybeDisplacedAccountIdentifier.ifPresent(displacedAccountIdentifier ->
writeItems.add(buildPutDeletedAccount(displacedAccountIdentifier, originalNumber)));
@@ -1174,6 +1176,15 @@ public class Accounts extends AbstractDynamoDbStore {
.build();
}
private TransactWriteItem buildRemoveDeletedAccount(final UUID pni) {
return TransactWriteItem.builder()
.delete(Delete.builder()
.tableName(deletedAccountsTableName)
.key(Map.of(DELETED_ACCOUNTS_KEY_ACCOUNT_E164, AttributeValues.fromString(pni.toString())))
.build())
.build();
}
@Nonnull
public CompletableFuture<Optional<Account>> getByAccountIdentifierAsync(final UUID uuid) {
return AsyncTimerUtil.record(GET_BY_UUID_TIMER, () -> itemByKeyAsync(accountsTableName, KEY_ACCOUNT_UUID, AttributeValues.fromUUID(uuid))
@@ -163,8 +163,8 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
private static final ObjectWriter ACCOUNT_REDIS_JSON_WRITER = SystemMapper.jsonMapper()
.writer(SystemMapper.excludingField(Account.class, List.of("uuid")));
private static Duration MESSAGE_POLL_INTERVAL = Duration.ofSeconds(1);
private static Duration MAX_SERVER_CLOCK_DRIFT = Duration.ofSeconds(5);
private static final Duration MESSAGE_POLL_INTERVAL = Duration.ofSeconds(1);
private static final Duration MAX_SERVER_CLOCK_DRIFT = Duration.ofSeconds(5);
// An account that's used at least daily will get reset in the cache at least once per day when its "last seen"
// timestamp updates; expiring entries after two days will help clear out "zombie" cache entries that are read
@@ -271,15 +271,16 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
@Nullable final String userAgent) throws InterruptedException {
final Account account = new Account();
final UUID phoneNumberIdentifier = phoneNumberIdentifiers.getPhoneNumberIdentifier(number).join();
return createTimer.record(() -> {
accountLockManager.withLock(List.of(number), () -> {
accountLockManager.withLock(List.of(number), List.of(phoneNumberIdentifier), () -> {
final Optional<UUID> maybeRecentlyDeletedAccountIdentifier =
accounts.findRecentlyDeletedAccountIdentifier(number);
// Reuse the ACI from any recently-deleted account with this number to cover cases where somebody is
// re-registering.
account.setNumber(number, phoneNumberIdentifiers.getPhoneNumberIdentifier(number));
account.setNumber(number, phoneNumberIdentifier);
account.setUuid(maybeRecentlyDeletedAccountIdentifier.orElseGet(UUID::randomUUID));
account.setIdentityKey(aciIdentityKey);
account.setPhoneNumberIdentityKey(pniIdentityKey);
@@ -292,6 +293,18 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
String accountCreationType = maybeRecentlyDeletedAccountIdentifier.isPresent() ? "recently-deleted" : "new";
final String pushTokenType;
if (primaryDeviceSpec.apnRegistrationId().isPresent()) {
pushTokenType = "apns";
} else if (primaryDeviceSpec.gcmRegistrationId().isPresent()) {
pushTokenType = "fcm";
} else {
pushTokenType = "none";
}
String previousPushTokenType = null;
try {
accounts.create(account, keysManager.buildWriteItemsForNewDevice(account.getIdentifier(IdentityType.ACI),
account.getIdentifier(IdentityType.PNI),
@@ -303,6 +316,14 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
} catch (final AccountAlreadyExistsException e) {
accountCreationType = "re-registration";
if (StringUtils.isNotBlank(e.getExistingAccount().getPrimaryDevice().getApnId())) {
previousPushTokenType = "apns";
} else if (StringUtils.isNotBlank(e.getExistingAccount().getPrimaryDevice().getGcmId())) {
previousPushTokenType = "fcm";
} else {
previousPushTokenType = "none";
}
final UUID aci = e.getExistingAccount().getIdentifier(IdentityType.ACI);
final UUID pni = e.getExistingAccount().getIdentifier(IdentityType.PNI);
@@ -343,23 +364,31 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
// We exclude the primary device's repeated-use keys from deletion because new keys were provided as
// part of the account creation process, and we don't want to delete the keys that just got added.
return CompletableFuture.allOf(keysManager.deleteSingleUsePreKeys(aci),
keysManager.deleteSingleUsePreKeys(pni),
messagesManager.clear(aci),
profilesManager.deleteAll(aci));
keysManager.deleteSingleUsePreKeys(pni),
messagesManager.clear(aci),
profilesManager.deleteAll(aci));
})
.join();
}
redisSet(account);
Metrics.counter(CREATE_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of("type", accountCreationType),
Tag.of("hasPushToken", String.valueOf(
primaryDeviceSpec.apnRegistrationId().isPresent() || primaryDeviceSpec.gcmRegistrationId().isPresent()))))
.increment();
Tags tags = Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of("type", accountCreationType),
Tag.of("hasPushToken", String.valueOf(
primaryDeviceSpec.apnRegistrationId().isPresent() || primaryDeviceSpec.gcmRegistrationId()
.isPresent())),
Tag.of("pushTokenType", pushTokenType));
if (StringUtils.isNotBlank(previousPushTokenType)) {
tags = tags.and(Tag.of("previousPushTokenType", previousPushTokenType));
}
Metrics.counter(CREATE_COUNTER_NAME, tags).increment();
accountAttributes.recoveryPassword().ifPresent(registrationRecoveryPassword ->
registrationRecoveryPasswordsManager.storeForCurrentNumber(account.getNumber(), registrationRecoveryPassword));
registrationRecoveryPasswordsManager.storeForCurrentNumber(account.getNumber(),
registrationRecoveryPassword));
}, accountLockExecutor);
return account;
@@ -368,6 +397,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
public CompletableFuture<Pair<Account, Device>> addDevice(final Account account, final DeviceSpec deviceSpec, final String linkDeviceToken) {
return accountLockManager.withLockAsync(List.of(account.getNumber()),
List.of(account.getPhoneNumberIdentifier()),
() -> addDevice(account.getIdentifier(IdentityType.ACI), deviceSpec, linkDeviceToken, MAX_UPDATE_ATTEMPTS),
accountLockExecutor);
}
@@ -555,7 +585,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
throw new IllegalArgumentException("Cannot remove primary device");
}
return accountLockManager.withLockAsync(List.of(account.getNumber()),
return accountLockManager.withLockAsync(List.of(account.getNumber()), List.of(account.getPhoneNumberIdentifier()),
() -> removeDevice(account.getIdentifier(IdentityType.ACI), deviceId, MAX_UPDATE_ATTEMPTS),
accountLockExecutor);
}
@@ -621,8 +651,10 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
validateDevices(account, pniSignedPreKeys, pniPqLastResortPreKeys, pniRegistrationIds);
final AtomicReference<Account> updatedAccount = new AtomicReference<>();
final UUID targetPhoneNumberIdentifier = phoneNumberIdentifiers.getPhoneNumberIdentifier(targetNumber).join();
accountLockManager.withLock(List.of(account.getNumber(), targetNumber), () -> {
accountLockManager.withLock(List.of(account.getNumber(), targetNumber),
List.of(account.getPhoneNumberIdentifier(), targetPhoneNumberIdentifier), () -> {
redisDelete(account);
// There are three possible states for accounts associated with the target phone number:
@@ -648,15 +680,14 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
final UUID uuid = account.getUuid();
final UUID phoneNumberIdentifier = phoneNumberIdentifiers.getPhoneNumberIdentifier(targetNumber);
CompletableFuture.allOf(
keysManager.deleteSingleUsePreKeys(phoneNumberIdentifier),
keysManager.deleteSingleUsePreKeys(targetPhoneNumberIdentifier),
keysManager.deleteSingleUsePreKeys(originalPhoneNumberIdentifier))
.join();
final Collection<TransactWriteItem> keyWriteItems =
buildPniKeyWriteItems(uuid, phoneNumberIdentifier, pniSignedPreKeys, pniPqLastResortPreKeys);
buildPniKeyWriteItems(uuid, targetPhoneNumberIdentifier, pniSignedPreKeys, pniPqLastResortPreKeys);
final Account numberChangedAccount = updateWithRetries(
account,
@@ -664,7 +695,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
setPniKeys(account, pniIdentityKey, pniRegistrationIds);
return true;
},
a -> accounts.changeNumber(a, targetNumber, phoneNumberIdentifier, maybeDisplacedUuid, keyWriteItems),
a -> accounts.changeNumber(a, targetNumber, targetPhoneNumberIdentifier, maybeDisplacedUuid, keyWriteItems),
() -> accounts.getByAccountIdentifier(uuid).orElseThrow(),
AccountChangeValidator.NUMBER_CHANGE_VALIDATOR);
@@ -738,7 +769,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
account.getDevices()
.stream()
.forEach(device -> device.setPhoneNumberIdentityRegistrationId(pniRegistrationIds.get(device.getId())));
account.setPhoneNumberIdentityKey(pniIdentityKey);
@@ -1177,7 +1207,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
public UUID getPhoneNumberIdentifier(String e164) {
return phoneNumberIdentifiers.getPhoneNumberIdentifier(e164);
return phoneNumberIdentifiers.getPhoneNumberIdentifier(e164).join();
}
public Optional<UUID> findRecentlyDeletedAccountIdentifier(final String e164) {
@@ -1195,7 +1225,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
public CompletableFuture<Void> delete(final Account account, final DeletionReason deletionReason) {
final Timer.Sample sample = Timer.start();
return accountLockManager.withLockAsync(List.of(account.getNumber()), () -> delete(account), accountLockExecutor)
return accountLockManager.withLockAsync(List.of(account.getNumber()), List.of(account.getPhoneNumberIdentifier()),
() -> delete(account),
accountLockExecutor)
.whenComplete((ignored, throwable) -> {
sample.stop(deleteTimer);
@@ -16,7 +16,6 @@ import org.apache.commons.lang3.ObjectUtils;
import org.signal.libsignal.protocol.IdentityKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.controllers.AccountController;
import org.whispersystems.textsecuregcm.controllers.MessageController;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.controllers.StaleDevicesException;
@@ -29,7 +28,8 @@ import org.whispersystems.textsecuregcm.push.MessageSender;
import org.whispersystems.textsecuregcm.util.DestinationDeviceValidator;
public class ChangeNumberManager {
private static final Logger logger = LoggerFactory.getLogger(AccountController.class);
private static final Logger logger = LoggerFactory.getLogger(ChangeNumberManager.class);
private final MessageSender messageSender;
private final AccountsManager accountsManager;
@@ -42,6 +42,7 @@ public class ClientPublicKeysManager {
*/
public CompletableFuture<Void> setPublicKey(final Account account, final byte deviceId, final ECPublicKey publicKey) {
return accountLockManager.withLockAsync(List.of(account.getNumber()),
List.of(account.getPhoneNumberIdentifier()),
() -> clientPublicKeys.setPublicKey(account.getIdentifier(IdentityType.ACI), deviceId, publicKey),
accountLockExecutor);
}
@@ -36,10 +36,7 @@ import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
import org.signal.libsignal.protocol.ServiceId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicMessagesConfiguration;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.experiment.Experiment;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
@@ -116,8 +113,6 @@ public class MessagesCache {
// messageDeletionExecutorService wrapped into a reactor Scheduler
private final Scheduler messageDeletionScheduler;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private final MessagesCacheInsertScript insertScript;
private final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript;
private final MessagesCacheRemoveByGuidScript removeByGuidScript;
@@ -137,17 +132,16 @@ public class MessagesCache {
private final Counter staleEphemeralMessagesCounter = Metrics.counter(
name(MessagesCache.class, "staleEphemeralMessages"));
private final Counter mrmContentRetrievedCounter = Metrics.counter(name(MessagesCache.class, "mrmViewRetrieved"));
private final Counter mrmRetrievalErrorCounter = Metrics.counter(name(MessagesCache.class, "mrmRetrievalError"));
private final Counter mrmPhaseTwoMissingContentCounter = Metrics.counter(
name(MessagesCache.class, "mrmPhaseTwoMissingContent"));
private final String MRM_RETRIEVAL_ERROR_COUNTER_NAME = name(MessagesCache.class, "mrmRetrievalError");
private final String EPHEMERAL_TAG_NAME = "ephemeral";
private final Counter skippedStaleEphemeralMrmCounter = Metrics.counter(
name(MessagesCache.class, "skippedStaleEphemeralMrm"));
private final Counter sharedMrmDataKeyRemovedCounter = Metrics.counter(
name(MessagesCache.class, "sharedMrmKeyRemoved"));
static final String NEXT_SLOT_TO_PERSIST_KEY = "user_queue_persist_slot";
private static final byte[] LOCK_VALUE = "1".getBytes(StandardCharsets.UTF_8);
private static final String MRM_VIEWS_EXPERIMENT_NAME = "mrmViews";
@VisibleForTesting
static final Duration MAX_EPHEMERAL_MESSAGE_DELAY = Duration.ofSeconds(10);
@@ -161,8 +155,7 @@ public class MessagesCache {
public MessagesCache(final FaultTolerantRedisClusterClient redisCluster,
final Scheduler messageDeliveryScheduler,
final ExecutorService messageDeletionExecutorService,
final Clock clock,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager)
final Clock clock)
throws IOException {
this(
@@ -170,7 +163,6 @@ public class MessagesCache {
messageDeliveryScheduler,
messageDeletionExecutorService,
clock,
dynamicConfigurationManager,
new MessagesCacheInsertScript(redisCluster),
new MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript(redisCluster),
new MessagesCacheGetItemsScript(redisCluster),
@@ -186,7 +178,6 @@ public class MessagesCache {
MessagesCache(final FaultTolerantRedisClusterClient redisCluster,
final Scheduler messageDeliveryScheduler,
final ExecutorService messageDeletionExecutorService, final Clock clock,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final MessagesCacheInsertScript insertScript,
final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript,
final MessagesCacheGetItemsScript getItemsScript, final MessagesCacheRemoveByGuidScript removeByGuidScript,
@@ -202,8 +193,6 @@ public class MessagesCache {
this.messageDeletionExecutorService = messageDeletionExecutorService;
this.messageDeletionScheduler = Schedulers.fromExecutorService(messageDeletionExecutorService, "messageDeletion");
this.dynamicConfigurationManager = dynamicConfigurationManager;
this.insertScript = insertScript;
this.insertMrmScript = insertMrmScript;
this.removeByGuidScript = removeByGuidScript;
@@ -366,9 +355,8 @@ public class MessagesCache {
if (isStaleEphemeralMessage(message, earliestAllowableEphemeralTimestamp)) {
// skip fetching content for message that will be discarded
messageMono = Mono.just(message.toBuilder().clearSharedMrmKey().build());
skippedStaleEphemeralMrmCounter.increment();
} else {
// mrm views phase 2: fetch shared MRM data -- internally depends on dynamic config that
// enables fetching and using it (the stored messages still always have `content` set upstream)
messageMono = getMessageWithSharedMrmData(message, destinationDevice);
}
@@ -389,71 +377,48 @@ public class MessagesCache {
/**
* Returns the given message with its shared MRM data.
*
* @see DynamicMessagesConfiguration#fetchSharedMrmData()
* @see DynamicMessagesConfiguration#useSharedMrmData()
*/
private Mono<MessageProtos.Envelope> getMessageWithSharedMrmData(final MessageProtos.Envelope mrmMessage,
final byte destinationDevice) {
assert mrmMessage.hasSharedMrmKey();
// mrm views phase 2: messages have content
if (!mrmMessage.hasContent()) {
mrmPhaseTwoMissingContentCounter.increment();
}
final byte[] key = mrmMessage.getSharedMrmKey().toByteArray();
final byte[] sharedMrmViewKey = MessagesCache.getSharedMrmViewKey(
// the message might be addressed to the account's PNI, so use the service ID from the envelope
ServiceIdentifier.valueOf(mrmMessage.getDestinationServiceId()), destinationDevice);
if (dynamicConfigurationManager.getConfiguration().getMessagesConfiguration().fetchSharedMrmData()
|| !mrmMessage.hasContent()) {
return Mono.from(redisCluster.withBinaryClusterReactive(
conn -> conn.reactive().hmget(key, "data".getBytes(StandardCharsets.UTF_8), sharedMrmViewKey)
.collectList()
.publishOn(messageDeliveryScheduler)))
.<MessageProtos.Envelope>handle((mrmDataAndView, sink) -> {
try {
assert mrmDataAndView.size() == 2;
final Experiment experiment = new Experiment(MRM_VIEWS_EXPERIMENT_NAME);
final byte[] content = SealedSenderMultiRecipientMessage.messageForRecipient(
mrmDataAndView.getFirst().getValue(),
mrmDataAndView.getLast().getValue());
final byte[] key = mrmMessage.getSharedMrmKey().toByteArray();
final byte[] sharedMrmViewKey = MessagesCache.getSharedMrmViewKey(
// the message might be addressed to the account's PNI, so use the service ID from the envelope
ServiceIdentifier.valueOf(mrmMessage.getDestinationServiceId()), destinationDevice);
sink.next(mrmMessage.toBuilder()
.clearSharedMrmKey()
.setContent(ByteString.copyFrom(content))
.build());
final Mono<MessageProtos.Envelope> messageFromRedisMono = Mono.from(redisCluster.withBinaryClusterReactive(
conn -> conn.reactive().hmget(key, "data".getBytes(StandardCharsets.UTF_8), sharedMrmViewKey)
.collectList()
.publishOn(messageDeliveryScheduler)))
.<MessageProtos.Envelope>handle((mrmDataAndView, sink) -> {
try {
assert mrmDataAndView.size() == 2;
mrmContentRetrievedCounter.increment();
} catch (Exception e) {
sink.error(e);
}
})
.onErrorResume(throwable -> {
logger.warn("Failed to retrieve shared mrm data", throwable);
Metrics.counter(MRM_RETRIEVAL_ERROR_COUNTER_NAME,
EPHEMERAL_TAG_NAME, String.valueOf(mrmMessage.getEphemeral()))
.increment();
final byte[] content = SealedSenderMultiRecipientMessage.messageForRecipient(
mrmDataAndView.getFirst().getValue(),
mrmDataAndView.getLast().getValue());
sink.next(mrmMessage.toBuilder()
.clearSharedMrmKey()
.setContent(ByteString.copyFrom(content))
.build());
mrmContentRetrievedCounter.increment();
} catch (Exception e) {
sink.error(e);
}
})
.onErrorResume(throwable -> {
logger.warn("Failed to retrieve shared mrm data", throwable);
mrmRetrievalErrorCounter.increment();
return Mono.empty();
})
.share();
if (mrmMessage.hasContent()) {
experiment.compareMonoResult(mrmMessage.toBuilder().clearSharedMrmKey().build(), messageFromRedisMono);
}
if (dynamicConfigurationManager.getConfiguration().getMessagesConfiguration().useSharedMrmData()
|| !mrmMessage.hasContent()) {
return messageFromRedisMono;
}
}
// if fetching or using shared data is disabled, fallback to just() with the existing message
return Mono.just(mrmMessage.toBuilder().clearSharedMrmKey().build());
return Mono.empty();
})
.share();
}
/**
@@ -527,8 +492,6 @@ public class MessagesCache {
.concatMap(message -> {
final Mono<MessageProtos.Envelope> messageMono;
if (message.hasSharedMrmKey()) {
// mrm views phase 2: fetch shared MRM data -- internally depends on dynamic config that
// enables fetching and using it (the stored messages still always have `content` set upstream)
messageMono = getMessageWithSharedMrmData(message, destinationDevice);
} else {
messageMono = Mono.just(message);
@@ -11,17 +11,13 @@ import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
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.QueryResponse;
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;
/**
* Manages a global, persistent mapping of phone numbers to phone number identifiers regardless of whether those
@@ -29,7 +25,7 @@ import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;
*/
public class PhoneNumberIdentifiers {
private final DynamoDbClient dynamoDbClient;
private final DynamoDbAsyncClient dynamoDbClient;
private final String tableName;
@VisibleForTesting
@@ -42,7 +38,7 @@ public class PhoneNumberIdentifiers {
private static final Timer GET_PNI_TIMER = Metrics.timer(name(PhoneNumberIdentifiers.class, "get"));
private static final Timer SET_PNI_TIMER = Metrics.timer(name(PhoneNumberIdentifiers.class, "set"));
public PhoneNumberIdentifiers(final DynamoDbClient dynamoDbClient, final String tableName) {
public PhoneNumberIdentifiers(final DynamoDbAsyncClient dynamoDbClient, final String tableName) {
this.dynamoDbClient = dynamoDbClient;
this.tableName = tableName;
}
@@ -53,67 +49,33 @@ public class PhoneNumberIdentifiers {
* @param phoneNumber the phone number for which to retrieve a phone number identifier
* @return the phone number identifier associated with the given phone number
*/
public UUID getPhoneNumberIdentifier(final String phoneNumber) {
final GetItemResponse response = GET_PNI_TIMER.record(() -> dynamoDbClient.getItem(GetItemRequest.builder()
public CompletableFuture<UUID> getPhoneNumberIdentifier(final String phoneNumber) {
final Timer.Sample sample = Timer.start();
return dynamoDbClient.getItem(GetItemRequest.builder()
.tableName(tableName)
.key(Map.of(KEY_E164, AttributeValues.fromString(phoneNumber)))
.projectionExpression(ATTR_PHONE_NUMBER_IDENTIFIER)
.build()));
final UUID phoneNumberIdentifier;
if (response.hasItem()) {
phoneNumberIdentifier = AttributeValues.getUUID(response.item(), ATTR_PHONE_NUMBER_IDENTIFIER, null);
} else {
phoneNumberIdentifier = generatePhoneNumberIdentifierIfNotExists(phoneNumber);
}
if (phoneNumberIdentifier == null) {
throw new RuntimeException("Could not retrieve phone number identifier from stored item");
}
return phoneNumberIdentifier;
.build())
.thenCompose(response -> response.hasItem()
? CompletableFuture.completedFuture(AttributeValues.getUUID(response.item(), ATTR_PHONE_NUMBER_IDENTIFIER, null))
: generatePhoneNumberIdentifierIfNotExists(phoneNumber))
.whenComplete((ignored, throwable) -> sample.stop(GET_PNI_TIMER));
}
public Optional<String> getPhoneNumber(final UUID phoneNumberIdentifier) {
final QueryResponse response = dynamoDbClient.query(QueryRequest.builder()
.tableName(tableName)
.indexName(INDEX_NAME)
.keyConditionExpression("#pni = :pni")
.projectionExpression("#phone_number")
.expressionAttributeNames(Map.of(
"#phone_number", KEY_E164,
"#pni", ATTR_PHONE_NUMBER_IDENTIFIER
))
.expressionAttributeValues(Map.of(
":pni", AttributeValues.fromUUID(phoneNumberIdentifier)
))
.build());
if (response.count() == 0) {
return Optional.empty();
}
if (response.count() > 1) {
throw new RuntimeException(
"Impossible result: more than one phone number returned for PNI: " + phoneNumberIdentifier);
}
return Optional.ofNullable(response.items().get(0).get(KEY_E164).s());
}
@VisibleForTesting
UUID generatePhoneNumberIdentifierIfNotExists(final String phoneNumber) {
final UpdateItemResponse response = SET_PNI_TIMER.record(() -> dynamoDbClient.updateItem(UpdateItemRequest.builder()
.tableName(tableName)
.key(Map.of(KEY_E164, AttributeValues.fromString(phoneNumber)))
.updateExpression("SET #pni = if_not_exists(#pni, :pni)")
.expressionAttributeNames(Map.of("#pni", ATTR_PHONE_NUMBER_IDENTIFIER))
.expressionAttributeValues(Map.of(":pni", AttributeValues.fromUUID(UUID.randomUUID())))
.returnValues(ReturnValue.ALL_NEW)
.build()));
CompletableFuture<UUID> generatePhoneNumberIdentifierIfNotExists(final String phoneNumber) {
final Timer.Sample sample = Timer.start();
return AttributeValues.getUUID(response.attributes(), ATTR_PHONE_NUMBER_IDENTIFIER, null);
return dynamoDbClient.updateItem(UpdateItemRequest.builder()
.tableName(tableName)
.key(Map.of(KEY_E164, AttributeValues.fromString(phoneNumber)))
.updateExpression("SET #pni = if_not_exists(#pni, :pni)")
.expressionAttributeNames(Map.of("#pni", ATTR_PHONE_NUMBER_IDENTIFIER))
.expressionAttributeValues(Map.of(":pni", AttributeValues.fromUUID(UUID.randomUUID())))
.returnValues(ReturnValue.ALL_NEW)
.build())
.thenApply(response -> AttributeValues.getUUID(response.attributes(), ATTR_PHONE_NUMBER_IDENTIFIER, null))
.whenComplete((ignored, throwable) -> sample.stop(SET_PNI_TIMER));
}
}
@@ -11,6 +11,7 @@ import java.time.Clock;
import java.time.Duration;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.util.AttributeValues;
@@ -18,12 +19,16 @@ import org.whispersystems.textsecuregcm.util.Util;
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.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.Delete;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.Put;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsRequest;
public class RegistrationRecoveryPasswords extends AbstractDynamoDbStore {
// As a temporary transitional measure, this can be either a string representation of an E164-formatted phone number
// or a UUID (PNI) string
static final String KEY_E164 = "P";
static final String ATTR_EXP = "E";
static final String ATTR_SALT = "S";
@@ -75,26 +80,57 @@ public class RegistrationRecoveryPasswords extends AbstractDynamoDbStore {
});
}
public CompletableFuture<Void> addOrReplace(final String number, final SaltedTokenHash data) {
return asyncClient.putItem(PutItemRequest.builder()
.tableName(tableName)
.item(Map.of(
KEY_E164, AttributeValues.fromString(number),
ATTR_EXP, AttributeValues.fromLong(expirationSeconds()),
ATTR_SALT, AttributeValues.fromString(data.salt()),
ATTR_HASH, AttributeValues.fromString(data.hash())))
.build())
public CompletableFuture<Optional<SaltedTokenHash>> lookup(final UUID phoneNumberIdentifier) {
return lookup(phoneNumberIdentifier.toString());
}
public CompletableFuture<Void> addOrReplace(final String number, final UUID phoneNumberIdentifier, final SaltedTokenHash data) {
final long expirationSeconds = expirationSeconds();
return asyncClient.transactWriteItems(TransactWriteItemsRequest.builder()
.transactItems(
buildPutRecoveryPasswordWriteItem(number, expirationSeconds, data.salt(), data.hash())
// buildPutRecoveryPasswordWriteItem(phoneNumberIdentifier.toString(), expirationSeconds, data.salt(), data.hash())
)
.build())
.thenRun(Util.NOOP);
}
public CompletableFuture<Void> removeEntry(final String number) {
return asyncClient.deleteItem(DeleteItemRequest.builder()
private TransactWriteItem buildPutRecoveryPasswordWriteItem(final String key,
final long expirationSeconds,
final String salt,
final String hash) {
return TransactWriteItem.builder()
.put(Put.builder()
.tableName(tableName)
.key(Map.of(KEY_E164, AttributeValues.fromString(number)))
.item(Map.of(
KEY_E164, AttributeValues.fromString(key),
ATTR_EXP, AttributeValues.fromLong(expirationSeconds),
ATTR_SALT, AttributeValues.fromString(salt),
ATTR_HASH, AttributeValues.fromString(hash)))
.build())
.build();
}
public CompletableFuture<Void> removeEntry(final String number, final UUID phoneNumberIdentifier) {
return asyncClient.transactWriteItems(TransactWriteItemsRequest.builder()
.transactItems(
buildDeleteRecoveryPasswordWriteItem(number),
buildDeleteRecoveryPasswordWriteItem(phoneNumberIdentifier.toString()))
.build())
.thenRun(Util.NOOP);
}
private TransactWriteItem buildDeleteRecoveryPasswordWriteItem(final String key) {
return TransactWriteItem.builder()
.delete(Delete.builder()
.tableName(tableName)
.key(Map.of(KEY_E164, AttributeValues.fromString(key)))
.build())
.build();
}
private long expirationSeconds() {
return clock.instant().plus(expiration).getEpochSecond();
}
@@ -21,10 +21,13 @@ public class RegistrationRecoveryPasswordsManager {
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private final RegistrationRecoveryPasswords registrationRecoveryPasswords;
private final PhoneNumberIdentifiers phoneNumberIdentifiers;
public RegistrationRecoveryPasswordsManager(final RegistrationRecoveryPasswords registrationRecoveryPasswords,
final PhoneNumberIdentifiers phoneNumberIdentifiers) {
public RegistrationRecoveryPasswordsManager(final RegistrationRecoveryPasswords registrationRecoveryPasswords) {
this.registrationRecoveryPasswords = requireNonNull(registrationRecoveryPasswords);
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
}
public CompletableFuture<Boolean> verify(final String number, final byte[] password) {
@@ -41,26 +44,27 @@ public class RegistrationRecoveryPasswordsManager {
public CompletableFuture<Void> storeForCurrentNumber(final String number, final byte[] password) {
final String token = bytesToString(password);
final SaltedTokenHash tokenHash = SaltedTokenHash.generateFor(token);
return registrationRecoveryPasswords.addOrReplace(number, tokenHash)
.whenComplete((result, error) -> {
if (error != null) {
logger.warn("Failed to store Registration Recovery Password", error);
}
});
return phoneNumberIdentifiers.getPhoneNumberIdentifier(number)
.thenCompose(phoneNumberIdentifier -> registrationRecoveryPasswords.addOrReplace(number, phoneNumberIdentifier, tokenHash)
.whenComplete((result, error) -> {
if (error != null) {
logger.warn("Failed to store Registration Recovery Password", error);
}
}));
}
public CompletableFuture<Void> removeForNumber(final String number) {
// remove is a "fire-and-forget" operation,
// there is no action to be taken on its completion
return registrationRecoveryPasswords.removeEntry(number)
.whenComplete((ignored, error) -> {
if (error instanceof ResourceNotFoundException) {
// These will naturally happen if a recovery password is already deleted. Since we can remove
// the recovery password through many flows, we avoid creating log messages for these exceptions
} else if (error != null) {
logger.warn("Failed to remove Registration Recovery Password", error);
}
});
return phoneNumberIdentifiers.getPhoneNumberIdentifier(number)
.thenCompose(phoneNumberIdentifier -> registrationRecoveryPasswords.removeEntry(number, phoneNumberIdentifier)
.whenComplete((ignored, error) -> {
if (error instanceof ResourceNotFoundException) {
// These will naturally happen if a recovery password is already deleted. Since we can remove
// the recovery password through many flows, we avoid creating log messages for these exceptions
} else if (error != null) {
logger.warn("Failed to remove Registration Recovery Password", error);
}
}));
}
private static String bytesToString(final byte[] bytes) {
@@ -453,7 +453,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
// since badge redemption is untrackable by design and unrevokable, subscription changes must be immediate and
// not prorated. Braintree subscriptions cannot change their next billing date,
// so we must end the existing one and create a new one
return cancelSubscriptionAtEndOfCurrentPeriod(subscription)
return endSubscription(subscription)
.thenCompose(ignored -> {
final Transaction transaction = getLatestTransactionForSubscription(subscription)
@@ -504,19 +504,9 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
final Instant anchor = subscription.getFirstBillingDate().toInstant();
final Instant endOfCurrentPeriod = subscription.getBillingPeriodEndDate().toInstant();
boolean paymentProcessing = false;
ChargeFailure chargeFailure = null;
final Optional<Transaction> latestTransaction = getLatestTransactionForSubscription(subscription);
boolean latestTransactionFailed = false;
if (latestTransaction.isPresent()){
paymentProcessing = isPaymentProcessing(latestTransaction.get().getStatus());
if (getPaymentStatus(latestTransaction.get().getStatus()) != PaymentStatus.SUCCEEDED) {
latestTransactionFailed = true;
chargeFailure = createChargeFailure(latestTransaction.get());
}
}
final TransactionInfo latestTransactionInfo = getLatestTransactionForSubscription(subscription)
.map(this::getTransactionInfo)
.orElse(new TransactionInfo(PaymentMethod.PAYPAL, false, false, null));
return new SubscriptionInformation(
new SubscriptionPrice(plan.getCurrencyIsoCode().toUpperCase(Locale.ROOT),
@@ -526,16 +516,31 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
endOfCurrentPeriod,
Subscription.Status.ACTIVE == subscription.getStatus(),
!subscription.neverExpires(),
getSubscriptionStatus(subscription.getStatus(), latestTransactionFailed),
getSubscriptionStatus(subscription.getStatus(), latestTransactionInfo.transactionFailed()),
PaymentProvider.BRAINTREE,
latestTransaction.map(this::getPaymentMethodFromTransaction).orElse(PaymentMethod.PAYPAL),
paymentProcessing,
chargeFailure
latestTransactionInfo.paymentMethod(),
latestTransactionInfo.paymentProcessing(),
latestTransactionInfo.chargeFailure()
);
}, executor);
}
private record TransactionInfo(
PaymentMethod paymentMethod,
boolean paymentProcessing,
boolean transactionFailed,
@Nullable ChargeFailure chargeFailure) {}
private TransactionInfo getTransactionInfo(final Transaction transaction) {
final boolean paymentProcessing = isPaymentProcessing(transaction.getStatus());
final PaymentMethod paymentMethod = getPaymentMethodFromTransaction(transaction);
if (getPaymentStatus(transaction.getStatus()) != PaymentStatus.SUCCEEDED) {
return new TransactionInfo(paymentMethod, paymentProcessing, true, createChargeFailure(transaction));
}
return new TransactionInfo(paymentMethod, paymentProcessing, false, null);
}
private PaymentMethod getPaymentMethodFromTransaction(Transaction transaction) {
if (transaction.getPayPalDetails() != null) {
return PaymentMethod.PAYPAL;
@@ -583,19 +588,37 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
.map(com.braintreegateway.PaymentMethod::getSubscriptions)
.orElse(Collections.emptyList())
.stream()
.map(this::cancelSubscriptionAtEndOfCurrentPeriod)
.map(this::endSubscription)
.toList();
return CompletableFuture.allOf(subscriptionCancelFutures.toArray(new CompletableFuture[0]));
});
}
private CompletableFuture<Void> endSubscription(Subscription subscription) {
final boolean latestTransactionFailed = getLatestTransactionForSubscription(subscription)
.map(this::getTransactionInfo)
.map(TransactionInfo::transactionFailed)
.orElse(false);
return switch (getSubscriptionStatus(subscription.getStatus(), latestTransactionFailed)) {
// The payment for this period has not processed yet, we should immediately cancel to prevent any payment from
// going through.
case INCOMPLETE, PAST_DUE, UNPAID -> cancelSubscriptionImmediately(subscription);
// Otherwise, set the subscription to cancel at the current period end. If the subscription is active, it may
// continue to be used until the end of the period.
default -> cancelSubscriptionAtEndOfCurrentPeriod(subscription);
};
}
private CompletableFuture<Void> cancelSubscriptionAtEndOfCurrentPeriod(Subscription subscription) {
return CompletableFuture.supplyAsync(() -> {
braintreeGateway.subscription().update(subscription.getId(),
new SubscriptionRequest().numberOfBillingCycles(subscription.getCurrentBillingCycle()));
return null;
}, executor);
return CompletableFuture.runAsync(() -> braintreeGateway
.subscription()
.update(subscription.getId(),
new SubscriptionRequest().numberOfBillingCycles(subscription.getCurrentBillingCycle())), executor);
}
private CompletableFuture<Void> cancelSubscriptionImmediately(Subscription subscription) {
return CompletableFuture.runAsync(() -> braintreeGateway.subscription().cancel(subscription.getId()), executor);
}
@@ -385,7 +385,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
}).thenCompose(subscriptions -> {
@SuppressWarnings("unchecked")
CompletableFuture<Subscription>[] futures = (CompletableFuture<Subscription>[]) subscriptions.stream()
.map(this::cancelSubscriptionAtEndOfCurrentPeriod).toArray(CompletableFuture[]::new);
.map(this::endSubscription).toArray(CompletableFuture[]::new);
return CompletableFuture.allOf(futures);
});
}
@@ -404,7 +404,19 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
}, executor);
}
public CompletableFuture<Subscription> cancelSubscriptionImmediately(Subscription subscription) {
private CompletableFuture<Subscription> endSubscription(Subscription subscription) {
final SubscriptionStatus status = SubscriptionStatus.forApiValue(subscription.getStatus());
return switch (status) {
// The payment for this period has not processed yet, we should immediately cancel to prevent any payment from
// going through.
case UNPAID, PAST_DUE, INCOMPLETE -> cancelSubscriptionImmediately(subscription);
// Otherwise, set the subscription to cancel at the current period end. If the subscription is active, it may
// continue to be used until the end of the period.
default -> cancelSubscriptionAtEndOfCurrentPeriod(subscription);
};
}
private CompletableFuture<Subscription> cancelSubscriptionImmediately(Subscription subscription) {
return CompletableFuture.supplyAsync(() -> {
SubscriptionCancelParams params = SubscriptionCancelParams.builder().build();
try {
@@ -415,7 +427,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
}, executor);
}
public CompletableFuture<Subscription> cancelSubscriptionAtEndOfCurrentPeriod(Subscription subscription) {
private CompletableFuture<Subscription> cancelSubscriptionAtEndOfCurrentPeriod(Subscription subscription) {
return CompletableFuture.supplyAsync(() -> {
SubscriptionUpdateParams params = SubscriptionUpdateParams.builder()
.setCancelAtPeriodEnd(true)
@@ -24,15 +24,11 @@ import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.random.RandomGenerator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
public class Util {
private static final RandomGenerator rng = new Random();
private static final Pattern COUNTRY_CODE_PATTERN = Pattern.compile("^\\+([17]|2[07]|3[0123469]|4[013456789]|5[12345678]|6[0123456]|8[1246]|9[0123458]|\\d{3})");
private static final RandomGenerator RANDOM_GENERATOR = new Random();
private static final PhoneNumberUtil PHONE_NUMBER_UTIL = PhoneNumberUtil.getInstance();
@@ -89,10 +85,11 @@ public class Util {
}
public static String getCountryCode(String number) {
Matcher matcher = COUNTRY_CODE_PATTERN.matcher(number);
if (matcher.find()) return matcher.group(1);
else return "0";
try {
return String.valueOf(PHONE_NUMBER_UTIL.parse(number, null).getCountryCode());
} catch (final NumberParseException e) {
return "0";
}
}
public static String getRegion(final String number) {
@@ -104,14 +101,6 @@ public class Util {
}
}
public static String getNumberPrefix(String number) {
String countryCode = getCountryCode(number);
int remaining = number.length() - (1 + countryCode.length());
int prefixLength = Math.min(4, remaining);
return number.substring(0, 1 + countryCode.length() + prefixLength);
}
public static byte[] truncate(byte[] element, int length) {
byte[] result = new byte[length];
System.arraycopy(element, 0, result, 0, result.length);
@@ -122,7 +111,8 @@ public class Util {
public static void sleep(long i) {
try {
Thread.sleep(i);
} catch (InterruptedException ie) {}
} catch (final InterruptedException ignored) {
}
}
public static long todayInMillis() {
@@ -196,8 +186,8 @@ public class Util {
return values;
}
Set<Integer> indices = new HashSet<>(rng.ints(0, values.size()).distinct().limit(n).boxed().toList());
List<E> result = new ArrayList<E>(n);
Set<Integer> indices = new HashSet<>(RANDOM_GENERATOR.ints(0, values.size()).distinct().limit(n).boxed().toList());
List<E> result = new ArrayList<>(n);
for(int i = 0; i < values.size() && result.size() < n; i++) {
if(indices.contains(i)) {
result.add(values.get(i));
@@ -32,6 +32,7 @@ import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.LongAdder;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.util.StaticException;
import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -92,6 +93,7 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
private static final String STATUS_CODE_TAG = "status";
private static final String STATUS_MESSAGE_TAG = "message";
private static final String ERROR_TYPE_TAG = "errorType";
private static final String EXCEPTION_TYPE_TAG = "exceptionType";
private static final long SLOW_DRAIN_THRESHOLD = 10_000;
@@ -435,24 +437,26 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
return queueCleared;
}
private void measureSendMessageErrors(Throwable e, final boolean terminal) {
private void measureSendMessageErrors(final Throwable e, final boolean terminal) {
final String errorType;
if (e instanceof TimeoutException) {
errorType = "timeout";
} else if (e instanceof java.nio.channels.ClosedChannelException) {
errorType = "closedChannel";
} else if (e == WebSocketResourceProvider.CONNECTION_CLOSED_EXCEPTION) {
} else if (e instanceof java.nio.channels.ClosedChannelException ||
e == WebSocketResourceProvider.CONNECTION_CLOSED_EXCEPTION ||
e instanceof org.eclipse.jetty.io.EofException ||
(e instanceof StaticException staticException && "Closed".equals(staticException.getMessage()))) {
errorType = "connectionClosed";
} else if (e instanceof org.eclipse.jetty.io.EofException) {
errorType = "connectionEof";
} else {
logger.warn(terminal ? "Send message failure terminated stream" : "Send message failed", e);
errorType = "other";
}
final Tags tags = Tags.of(
UserAgentTagUtil.getPlatformTag(client.getUserAgent()),
Tag.of(ERROR_TYPE_TAG, errorType));
Metrics.counter(SEND_MESSAGE_ERROR_COUNTER, tags).increment();
Metrics.counter(SEND_MESSAGE_ERROR_COUNTER, Tags.of(
UserAgentTagUtil.getPlatformTag(client.getUserAgent()),
Tag.of(ERROR_TYPE_TAG, errorType),
Tag.of(EXCEPTION_TYPE_TAG, e.getClass().getSimpleName())))
.increment();
}
private CompletableFuture<Void> sendMessage(Envelope envelope) {
@@ -170,9 +170,6 @@ record CommandDependencies(
dynamoDbAsyncClient
);
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager = new RegistrationRecoveryPasswordsManager(
registrationRecoveryPasswords);
ClientPublicKeys clientPublicKeys =
new ClientPublicKeys(dynamoDbAsyncClient, configuration.getDynamoDbTables().getClientPublicKeys().getTableName());
@@ -185,7 +182,7 @@ record CommandDependencies(
configuration.getDynamoDbTables().getAccounts().getUsernamesTableName(),
configuration.getDynamoDbTables().getDeletedAccounts().getTableName(),
configuration.getDynamoDbTables().getAccounts().getUsedLinkDeviceTokensTableName());
PhoneNumberIdentifiers phoneNumberIdentifiers = new PhoneNumberIdentifiers(dynamoDbClient,
PhoneNumberIdentifiers phoneNumberIdentifiers = new PhoneNumberIdentifiers(dynamoDbAsyncClient,
configuration.getDynamoDbTables().getPhoneNumberIdentifiers().getTableName());
Profiles profiles = new Profiles(dynamoDbClient, dynamoDbAsyncClient,
configuration.getDynamoDbTables().getProfiles().getTableName());
@@ -212,7 +209,7 @@ record CommandDependencies(
storageServiceExecutor, storageServiceRetryExecutor, configuration.getSecureStorageServiceConfiguration());
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient, disconnectionRequestListenerExecutor);
MessagesCache messagesCache = new MessagesCache(messagesCluster,
messageDeliveryScheduler, messageDeletionExecutor, Clock.systemUTC(), dynamicConfigurationManager);
messageDeliveryScheduler, messageDeletionExecutor, Clock.systemUTC());
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster);
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbClient,
configuration.getDynamoDbTables().getReportMessage().getTableName(),
@@ -225,6 +222,8 @@ record CommandDependencies(
configuration.getDynamoDbTables().getDeletedAccountsLock().getTableName());
ClientPublicKeysManager clientPublicKeysManager =
new ClientPublicKeysManager(clientPublicKeys, accountLockManager, accountLockExecutor);
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager =
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords, phoneNumberIdentifiers);
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
pubsubClient, accountLockManager, keys, messagesManager, profilesManager,
secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
@@ -10,10 +10,10 @@ option java_package = "org.whispersystems.textsecuregcm.push";
option java_multiple_files = true;
message ClientEvent {
reserved 3;
oneof event {
NewMessageAvailableEvent new_message_available = 1;
ClientConnectedEvent client_connected = 2;
DisconnectRequested disconnect_requested = 3;
MessagesPersistedEvent messages_persisted = 4;
}
}
@@ -31,13 +31,6 @@ message ClientConnectedEvent {
bytes server_id = 1;
}
/**
* Indicates that the server has requested that the client disconnect due to
* (for example) account lifecycle events.
*/
message DisconnectRequested {
}
/**
* Indicates that messages for the client have been persisted from short-term
* storage to long-term storage.
@@ -64,14 +64,14 @@ public class BufferingInterceptorIntegrationTest {
@Path("/virtual/{size}")
@ManagedAsync
public String getVirtual(@PathParam("size") int size) {
return RandomStringUtils.randomAscii(size);
return RandomStringUtils.secure().nextAscii(size);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/platform/{size}")
public String getPlatform(@PathParam("size") int size) {
return RandomStringUtils.randomAscii(size);
return RandomStringUtils.secure().nextAscii(size);
}
}
}
@@ -123,7 +123,7 @@ public class WebsocketResourceProviderIntegrationTest {
@Path("/{size}")
@ManagedAsync
public String get(@PathParam("size") int size) {
return RandomStringUtils.randomAscii(size);
return RandomStringUtils.secure().nextAscii(size);
}
@PUT
@@ -51,7 +51,7 @@ class OptionalAccessTest {
}
private static List<Arguments> verify() {
final String unidentifiedAccessKey = RandomStringUtils.randomAlphanumeric(16);
final String unidentifiedAccessKey = RandomStringUtils.secure().nextAlphanumeric(16);
final Anonymous correctUakHeader =
new Anonymous(Base64.getEncoder().encodeToString(unidentifiedAccessKey.getBytes()));
@@ -180,7 +180,7 @@ class OptionalAccessTest {
@Test
void testTargetIdentifierIllegalArgument() {
final String unidentifiedAccessKey = RandomStringUtils.randomAlphanumeric(16);
final String unidentifiedAccessKey = RandomStringUtils.secure().nextAlphanumeric(16);
final Anonymous correctUakHeader =
new Anonymous(Base64.getEncoder().encodeToString(unidentifiedAccessKey.getBytes()));
@@ -1005,8 +1005,8 @@ class DeviceControllerTest {
}
private static List<String> waitForLinkedDeviceBadTokenIdentifierLength() {
return List.of(RandomStringUtils.randomAlphanumeric(DeviceController.MIN_TOKEN_IDENTIFIER_LENGTH - 1),
RandomStringUtils.randomAlphanumeric(DeviceController.MAX_TOKEN_IDENTIFIER_LENGTH + 1));
return List.of(RandomStringUtils.secure().nextAlphanumeric(DeviceController.MIN_TOKEN_IDENTIFIER_LENGTH - 1),
RandomStringUtils.secure().nextAlphanumeric(DeviceController.MAX_TOKEN_IDENTIFIER_LENGTH + 1));
}
@Test
@@ -1177,7 +1177,7 @@ class DeviceControllerTest {
@Test
void recordRestoreAccountRequest() {
final String token = RandomStringUtils.randomAlphanumeric(16);
final String token = RandomStringUtils.secure().nextAlphanumeric(16);
final RestoreAccountRequest restoreAccountRequest =
new RestoreAccountRequest(RestoreAccountRequest.Method.LOCAL_BACKUP);
@@ -1195,7 +1195,7 @@ class DeviceControllerTest {
@Test
void recordRestoreAccountRequestBadToken() {
final String token = RandomStringUtils.randomAlphanumeric(128);
final String token = RandomStringUtils.secure().nextAlphanumeric(128);
final RestoreAccountRequest restoreAccountRequest =
new RestoreAccountRequest(RestoreAccountRequest.Method.LOCAL_BACKUP);
@@ -1210,7 +1210,7 @@ class DeviceControllerTest {
@Test
void recordRestoreAccountRequestInvalidRequest() {
final String token = RandomStringUtils.randomAlphanumeric(16);
final String token = RandomStringUtils.secure().nextAlphanumeric(16);
final RestoreAccountRequest restoreAccountRequest = new RestoreAccountRequest(null);
try (final Response response = resources.getJerseyTest()
@@ -1224,7 +1224,7 @@ class DeviceControllerTest {
@Test
void waitForDeviceTransferRequest() {
final String token = RandomStringUtils.randomAlphanumeric(16);
final String token = RandomStringUtils.secure().nextAlphanumeric(16);
final RestoreAccountRequest restoreAccountRequest =
new RestoreAccountRequest(RestoreAccountRequest.Method.LOCAL_BACKUP);
@@ -1243,7 +1243,7 @@ class DeviceControllerTest {
@Test
void waitForDeviceTransferRequestNoRequestIssued() {
final String token = RandomStringUtils.randomAlphanumeric(16);
final String token = RandomStringUtils.secure().nextAlphanumeric(16);
when(accountsManager.waitForRestoreAccountRequest(eq(token), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.empty()));
@@ -1260,7 +1260,7 @@ class DeviceControllerTest {
@ParameterizedTest
@ValueSource(ints = {0, -1, 3601})
void waitForDeviceTransferRequestBadTimeout(final int timeoutSeconds) {
final String token = RandomStringUtils.randomAlphanumeric(16);
final String token = RandomStringUtils.secure().nextAlphanumeric(16);
try (final Response response = resources.getJerseyTest()
.target("/v1/devices/restore_account/" + token)
@@ -82,12 +82,12 @@ import org.junit.jupiter.params.provider.ValueSource;
import org.junitpioneer.jupiter.cartesian.ArgumentSets;
import org.junitpioneer.jupiter.cartesian.CartesianTest;
import org.mockito.ArgumentCaptor;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicInboundMessageByteLimitConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicMessagesConfiguration;
import org.whispersystems.textsecuregcm.entities.AccountMismatchedDevices;
import org.whispersystems.textsecuregcm.entities.AccountStaleDevices;
import org.whispersystems.textsecuregcm.entities.IncomingMessage;
@@ -252,8 +252,6 @@ class MessageControllerTest {
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
when(dynamicConfiguration.getInboundMessageByteLimitConfiguration()).thenReturn(inboundMessageByteLimitConfiguration);
when(dynamicConfiguration.getMessagesConfiguration()).thenReturn(
new DynamicMessagesConfiguration(true, true, true));
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
@@ -1141,6 +1139,10 @@ class MessageControllerTest {
@Test
void testManyRecipientMessage() throws Exception {
when(messagesManager.insertSharedMultiRecipientMessagePayload(any(SealedSenderMultiRecipientMessage.class)))
.thenReturn(new byte[]{1});
final int nRecipients = 999;
final int devicesPerRecipient = 5;
final List<Recipient> recipients = new ArrayList<>();
@@ -1152,8 +1154,8 @@ class MessageControllerTest {
d -> generateTestDevice(
(byte) d, 100 + d, 10 * d, true))
.collect(Collectors.toList());
final UUID aci = new UUID(0L, (long) i);
final UUID pni = new UUID(1L, (long) i);
final UUID aci = new UUID(0L, i);
final UUID pni = new UUID(1L, i);
final String e164 = String.format("+1408555%04d", i);
final Account account = AccountsHelper.generateTestAccount(e164, aci, pni, devices, UNIDENTIFIED_ACCESS_BYTES);
@@ -1186,13 +1188,12 @@ class MessageControllerTest {
// see testMultiRecipientMessageNoPni and testMultiRecipientMessagePni below for actual invocations
private void testMultiRecipientMessage(
Map<ServiceIdentifier, Map<Byte, Integer>> destinations,
boolean authorize,
boolean isStory,
boolean urgent,
boolean explicitIdentifier,
int expectedStatus,
int expectedMessagesSent) throws Exception {
Map<ServiceIdentifier, Map<Byte, Integer>> destinations, boolean authorize, boolean isStory, boolean urgent,
boolean explicitIdentifier, int expectedStatus, int expectedMessagesSent) throws Exception {
when(messagesManager.insertSharedMultiRecipientMessagePayload(any(SealedSenderMultiRecipientMessage.class)))
.thenReturn(new byte[]{1});
final List<Recipient> recipients = new ArrayList<>();
destinations.forEach(
(serviceIdentifier, deviceToRegistrationId) ->
@@ -1383,6 +1384,10 @@ class MessageControllerTest {
@Test
void testMultiRecipientMessageWithGroupSendEndorsements() throws Exception {
when(messagesManager.insertSharedMultiRecipientMessagePayload(any(SealedSenderMultiRecipientMessage.class)))
.thenReturn(new byte[]{1});
final List<Recipient> recipients = List.of(
new Recipient(SINGLE_DEVICE_ACI_ID, SINGLE_DEVICE_ID1, SINGLE_DEVICE_REG_ID1, new byte[48]),
new Recipient(MULTI_DEVICE_ACI_ID, MULTI_DEVICE_ID1, MULTI_DEVICE_REG_ID1, new byte[48]),
@@ -1550,6 +1555,9 @@ class MessageControllerTest {
@MethodSource
void testSendMultiRecipientMessageToUnknownAccounts(boolean story, boolean known, boolean useExplicitIdentifier) {
when(messagesManager.insertSharedMultiRecipientMessagePayload(any(SealedSenderMultiRecipientMessage.class)))
.thenReturn(new byte[]{1});
final Recipient r1;
if (known) {
r1 = new Recipient(SINGLE_DEVICE_ACI_ID, SINGLE_DEVICE_ID1, SINGLE_DEVICE_REG_ID1, new byte[48]);
@@ -104,7 +104,7 @@ public class ValidatingInterceptorTest {
@ParameterizedTest
@ValueSource(ints = {0, 1, 2, 3, 4, 6, 1000})
public void testExactlySizeValidationFailure(final int size) throws Exception {
final String stringValue = RandomStringUtils.randomAlphanumeric(size);
final String stringValue = RandomStringUtils.secure().nextAlphanumeric(size);
assertStatusException(Status.INVALID_ARGUMENT, () -> stub.validationsEndpoint(
builderWithValidDefaults()
.setFixedSizeString(stringValue)
@@ -119,7 +119,7 @@ public class ValidatingInterceptorTest {
));
final List<String> listValue = IntStream.range(0, size)
.mapToObj(i -> RandomStringUtils.randomAlphabetic(10))
.mapToObj(i -> RandomStringUtils.secure().nextAlphabetic(10))
.toList();
assertStatusException(Status.INVALID_ARGUMENT, () -> stub.validationsEndpoint(
builderWithValidDefaults()
@@ -181,7 +181,7 @@ public class ValidatingInterceptorTest {
@ParameterizedTest
@MethodSource
public void testRangeSizeValidationFailure(final int size, final Status expectedStatus) throws Exception {
final String stringValue = RandomStringUtils.randomAlphanumeric(size);
final String stringValue = RandomStringUtils.secure().nextAlphanumeric(size);
assertEquals(expectedStatus.getCode(), requestStatus(() -> stub.validationsEndpoint(
builderWithValidDefaults()
.setRangeSizeString(stringValue)
@@ -196,7 +196,7 @@ public class ValidatingInterceptorTest {
)).getCode());
final List<String> listValue = IntStream.range(0, size)
.mapToObj(i -> RandomStringUtils.randomAlphabetic(10))
.mapToObj(i -> RandomStringUtils.secure().nextAlphabetic(10))
.toList();
assertEquals(expectedStatus.getCode(), requestStatus(() -> stub.validationsEndpoint(
builderWithValidDefaults()
@@ -101,7 +101,7 @@ class NoiseWebSocketTunnelServerIntegrationTest extends AbstractLeakDetectionTes
private static final UUID ACCOUNT_IDENTIFIER = UUID.randomUUID();
private static final byte DEVICE_ID = Device.PRIMARY_ID;
private static final String RECOGNIZED_PROXY_SECRET = RandomStringUtils.randomAlphanumeric(16);
private static final String RECOGNIZED_PROXY_SECRET = RandomStringUtils.secure().nextAlphanumeric(16);
// Please note that this certificate/key are used only for testing and are not used anywhere outside of this test.
// They were generated with:
@@ -38,7 +38,7 @@ class WebsocketHandshakeCompleteHandlerTest extends AbstractLeakDetectionTest {
private UserEventRecordingHandler userEventRecordingHandler;
private MutableRemoteAddressEmbeddedChannel embeddedChannel;
private static final String RECOGNIZED_PROXY_SECRET = RandomStringUtils.randomAlphanumeric(16);
private static final String RECOGNIZED_PROXY_SECRET = RandomStringUtils.secure().nextAlphanumeric(16);
private static class UserEventRecordingHandler extends ChannelInboundHandlerAdapter {
@@ -37,7 +37,7 @@ import org.whispersystems.textsecuregcm.tests.util.SynchronousExecutorService;
class APNSenderTest {
private static final String DESTINATION_DEVICE_TOKEN = RandomStringUtils.randomAlphanumeric(32);
private static final String DESTINATION_DEVICE_TOKEN = RandomStringUtils.secure().nextAlphanumeric(32);
private static final String BUNDLE_ID = "org.signal.test";
private Account destinationAccount;
@@ -128,7 +128,7 @@ class MessageSenderTest {
return MessageProtos.Envelope.newBuilder()
.setClientTimestamp(System.currentTimeMillis())
.setServerTimestamp(System.currentTimeMillis())
.setContent(ByteString.copyFromUtf8(RandomStringUtils.randomAlphanumeric(256)))
.setContent(ByteString.copyFromUtf8(RandomStringUtils.secure().nextAlphanumeric(256)))
.setType(MessageProtos.Envelope.Type.CIPHERTEXT)
.setServerGuid(UUID.randomUUID().toString())
.build();
@@ -55,7 +55,7 @@ class PushNotificationSchedulerTest {
private static final UUID ACCOUNT_UUID = UUID.randomUUID();
private static final String ACCOUNT_NUMBER = "+18005551234";
private static final byte DEVICE_ID = 1;
private static final String APN_ID = RandomStringUtils.randomAlphanumeric(32);
private static final String APN_ID = RandomStringUtils.secure().nextAlphanumeric(32);
@BeforeEach
void setUp() throws Exception {
@@ -122,8 +122,8 @@ class SecureStorageClientTest {
@Test
void deleteStoredData() {
final String username = RandomStringUtils.randomAlphabetic(16);
final String password = RandomStringUtils.randomAlphanumeric(32);
final String username = RandomStringUtils.secure().nextAlphabetic(16);
final String password = RandomStringUtils.secure().nextAlphanumeric(32);
when(credentialsGenerator.generateForUuid(accountUuid)).thenReturn(
new ExternalServiceCredentials(username, password));
@@ -139,8 +139,8 @@ class SecureStorageClientTest {
@Test
void deleteStoredDataFailure() {
final String username = RandomStringUtils.randomAlphabetic(16);
final String password = RandomStringUtils.randomAlphanumeric(32);
final String username = RandomStringUtils.secure().nextAlphabetic(16);
final String password = RandomStringUtils.secure().nextAlphanumeric(32);
when(credentialsGenerator.generateForUuid(accountUuid)).thenReturn(
new ExternalServiceCredentials(username, password));
@@ -121,8 +121,8 @@ class SecureValueRecovery2ClientTest {
@Test
void deleteStoredData() {
final String username = RandomStringUtils.randomAlphabetic(16);
final String password = RandomStringUtils.randomAlphanumeric(32);
final String username = RandomStringUtils.secure().nextAlphabetic(16);
final String password = RandomStringUtils.secure().nextAlphanumeric(32);
when(credentialsGenerator.generateForUuid(accountUuid)).thenReturn(
new ExternalServiceCredentials(username, password));
@@ -136,8 +136,8 @@ class SecureValueRecovery2ClientTest {
@Test
void deleteStoredDataFailure() {
final String username = RandomStringUtils.randomAlphabetic(16);
final String password = RandomStringUtils.randomAlphanumeric(32);
final String username = RandomStringUtils.secure().nextAlphabetic(16);
final String password = RandomStringUtils.secure().nextAlphanumeric(32);
when(credentialsGenerator.generateForUuid(accountUuid)).thenReturn(
new ExternalServiceCredentials(username, password));
@@ -23,7 +23,6 @@ import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadLocalRandom;
@@ -126,7 +125,7 @@ public class AccountCreationDeletionIntegrationTest {
when(svr2Client.deleteBackups(any())).thenReturn(CompletableFuture.completedFuture(null));
final PhoneNumberIdentifiers phoneNumberIdentifiers =
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
DynamoDbExtensionSchema.Tables.PNI.tableName());
final MessagesManager messagesManager = mock(MessagesManager.class);
@@ -182,12 +181,12 @@ public class AccountCreationDeletionIntegrationTest {
PhoneNumberUtil.getInstance().getExampleNumber("US"),
PhoneNumberUtil.PhoneNumberFormat.E164);
final String password = RandomStringUtils.randomAlphanumeric(16);
final String signalAgent = RandomStringUtils.randomAlphabetic(3);
final String password = RandomStringUtils.secure().nextAlphanumeric(16);
final String signalAgent = RandomStringUtils.secure().nextAlphabetic(3);
final int registrationId = ThreadLocalRandom.current().nextInt(Device.MAX_REGISTRATION_ID);
final int pniRegistrationId = ThreadLocalRandom.current().nextInt(Device.MAX_REGISTRATION_ID);
final byte[] deviceName = RandomStringUtils.randomAlphabetic(16).getBytes(StandardCharsets.UTF_8);
final String registrationLockSecret = RandomStringUtils.randomAlphanumeric(16);
final byte[] deviceName = RandomStringUtils.secure().nextAlphabetic(16).getBytes(StandardCharsets.UTF_8);
final String registrationLockSecret = RandomStringUtils.secure().nextAlphanumeric(16);
final Set<DeviceCapability> deviceCapabilities = Set.of();
@@ -200,7 +199,7 @@ public class AccountCreationDeletionIntegrationTest {
deviceCapabilities);
final List<AccountBadge> badges = new ArrayList<>(List.of(new AccountBadge(
RandomStringUtils.randomAlphabetic(8),
RandomStringUtils.secure().nextAlphabetic(8),
CLOCK.instant().plus(Duration.ofDays(7)),
true)));
@@ -323,12 +322,12 @@ public class AccountCreationDeletionIntegrationTest {
existingAccountUuid = originalAccount.getUuid();
}
final String password = RandomStringUtils.randomAlphanumeric(16);
final String signalAgent = RandomStringUtils.randomAlphabetic(3);
final String password = RandomStringUtils.secure().nextAlphanumeric(16);
final String signalAgent = RandomStringUtils.secure().nextAlphabetic(3);
final int registrationId = ThreadLocalRandom.current().nextInt(Device.MAX_REGISTRATION_ID);
final int pniRegistrationId = ThreadLocalRandom.current().nextInt(Device.MAX_REGISTRATION_ID);
final byte[] deviceName = RandomStringUtils.randomAlphabetic(16).getBytes(StandardCharsets.UTF_8);
final String registrationLockSecret = RandomStringUtils.randomAlphanumeric(16);
final byte[] deviceName = RandomStringUtils.secure().nextAlphabetic(16).getBytes(StandardCharsets.UTF_8);
final String registrationLockSecret = RandomStringUtils.secure().nextAlphanumeric(16);
final Set<DeviceCapability> deviceCapabilities = Set.of();
@@ -341,7 +340,7 @@ public class AccountCreationDeletionIntegrationTest {
deviceCapabilities);
final List<AccountBadge> badges = new ArrayList<>(List.of(new AccountBadge(
RandomStringUtils.randomAlphabetic(8),
RandomStringUtils.secure().nextAlphabetic(8),
CLOCK.instant().plus(Duration.ofDays(7)),
true)));
@@ -412,12 +411,12 @@ public class AccountCreationDeletionIntegrationTest {
PhoneNumberUtil.getInstance().getExampleNumber("US"),
PhoneNumberUtil.PhoneNumberFormat.E164);
final String password = RandomStringUtils.randomAlphanumeric(16);
final String signalAgent = RandomStringUtils.randomAlphabetic(3);
final String password = RandomStringUtils.secure().nextAlphanumeric(16);
final String signalAgent = RandomStringUtils.secure().nextAlphabetic(3);
final int registrationId = ThreadLocalRandom.current().nextInt(Device.MAX_REGISTRATION_ID);
final int pniRegistrationId = ThreadLocalRandom.current().nextInt(Device.MAX_REGISTRATION_ID);
final byte[] deviceName = RandomStringUtils.randomAlphabetic(16).getBytes(StandardCharsets.UTF_8);
final String registrationLockSecret = RandomStringUtils.randomAlphanumeric(16);
final byte[] deviceName = RandomStringUtils.secure().nextAlphabetic(16).getBytes(StandardCharsets.UTF_8);
final String registrationLockSecret = RandomStringUtils.secure().nextAlphanumeric(16);
final Set<DeviceCapability> deviceCapabilities = Set.of();
@@ -430,7 +429,7 @@ public class AccountCreationDeletionIntegrationTest {
deviceCapabilities);
final List<AccountBadge> badges = new ArrayList<>(List.of(new AccountBadge(
RandomStringUtils.randomAlphabetic(8),
RandomStringUtils.secure().nextAlphabetic(8),
CLOCK.instant().plus(Duration.ofDays(7)),
true)));
@@ -12,6 +12,7 @@ import com.amazonaws.services.dynamodbv2.ReleaseLockOptions;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -33,6 +34,9 @@ class AccountLockManagerTest {
private static final String SECOND_NUMBER = PhoneNumberUtil.getInstance().format(
PhoneNumberUtil.getInstance().getExampleNumber("JP"), PhoneNumberUtil.PhoneNumberFormat.E164);
private static final UUID FIRST_PNI = UUID.randomUUID();
private static final UUID SECOND_PNI = UUID.randomUUID();
@BeforeEach
void setUp() {
lockClient = mock(AmazonDynamoDBLockClient.class);
@@ -51,47 +55,53 @@ class AccountLockManagerTest {
@Test
void withLock() throws InterruptedException {
accountLockManager.withLock(List.of(FIRST_NUMBER, SECOND_NUMBER), () -> {}, executor);
accountLockManager.withLock(List.of(FIRST_NUMBER, SECOND_NUMBER), List.of(FIRST_PNI, SECOND_PNI), () -> {
}, executor);
verify(lockClient, times(2)).acquireLock(any());
verify(lockClient, times(2)).releaseLock(any(ReleaseLockOptions.class));
verify(lockClient, times(4)).acquireLock(any());
verify(lockClient, times(4)).releaseLock(any(ReleaseLockOptions.class));
}
@Test
void withLockTaskThrowsException() throws InterruptedException {
assertThrows(RuntimeException.class, () -> accountLockManager.withLock(List.of(FIRST_NUMBER, SECOND_NUMBER), () -> {
assertThrows(RuntimeException.class,
() -> accountLockManager.withLock(List.of(FIRST_NUMBER, SECOND_NUMBER), List.of(FIRST_PNI, SECOND_PNI), () -> {
throw new RuntimeException();
}, executor));
verify(lockClient, times(2)).acquireLock(any());
verify(lockClient, times(2)).releaseLock(any(ReleaseLockOptions.class));
verify(lockClient, times(4)).acquireLock(any());
verify(lockClient, times(4)).releaseLock(any(ReleaseLockOptions.class));
}
@Test
void withLockEmptyList() {
final Runnable task = mock(Runnable.class);
assertThrows(IllegalArgumentException.class, () -> accountLockManager.withLock(Collections.emptyList(), () -> {}, executor));
assertThrows(IllegalArgumentException.class,
() -> accountLockManager.withLock(Collections.emptyList(), Collections.emptyList(), () -> {
},
executor));
verify(task, never()).run();
}
@Test
void withLockAsync() throws InterruptedException {
accountLockManager.withLockAsync(List.of(FIRST_NUMBER, SECOND_NUMBER),
() -> CompletableFuture.completedFuture(null), executor).join();
List.of(FIRST_PNI, SECOND_PNI), () -> CompletableFuture.completedFuture(null), executor).join();
verify(lockClient, times(2)).acquireLock(any());
verify(lockClient, times(2)).releaseLock(any(ReleaseLockOptions.class));
verify(lockClient, times(4)).acquireLock(any());
verify(lockClient, times(4)).releaseLock(any(ReleaseLockOptions.class));
}
@Test
void withLockAsyncTaskThrowsException() throws InterruptedException {
assertThrows(RuntimeException.class,
() -> accountLockManager.withLockAsync(List.of(FIRST_NUMBER, SECOND_NUMBER),
() -> CompletableFuture.failedFuture(new RuntimeException()), executor).join());
List.of(FIRST_PNI, SECOND_PNI), () -> CompletableFuture.failedFuture(new RuntimeException()), executor)
.join());
verify(lockClient, times(2)).acquireLock(any());
verify(lockClient, times(2)).releaseLock(any(ReleaseLockOptions.class));
verify(lockClient, times(4)).acquireLock(any());
verify(lockClient, times(4)).releaseLock(any(ReleaseLockOptions.class));
}
@Test
@@ -100,7 +110,7 @@ class AccountLockManagerTest {
assertThrows(IllegalArgumentException.class,
() -> accountLockManager.withLockAsync(Collections.emptyList(),
() -> CompletableFuture.completedFuture(null), executor));
Collections.emptyList(), () -> CompletableFuture.completedFuture(null), executor));
verify(task, never()).run();
}
@@ -119,7 +119,7 @@ class AccountsManagerChangeNumberIntegrationTest {
disconnectionRequestManager = mock(DisconnectionRequestManager.class);
final PhoneNumberIdentifiers phoneNumberIdentifiers =
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbClient(), Tables.PNI.tableName());
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), Tables.PNI.tableName());
final MessagesManager messagesManager = mock(MessagesManager.class);
when(messagesManager.clear(any())).thenReturn(CompletableFuture.completedFuture(null));
@@ -10,6 +10,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.atLeast;
@@ -50,7 +51,6 @@ import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
@@ -107,14 +107,14 @@ class AccountsManagerConcurrentModificationIntegrationTest {
final AccountLockManager accountLockManager = mock(AccountLockManager.class);
doAnswer(invocation -> {
final Runnable task = invocation.getArgument(1);
final Runnable task = invocation.getArgument(2);
task.run();
return null;
}).when(accountLockManager).withLock(any(), any(), any());
}).when(accountLockManager).withLock(any(), anyList(), any(), any());
when(accountLockManager.withLockAsync(any(), any(), any())).thenAnswer(invocation -> {
final Supplier<CompletableFuture<?>> taskSupplier = invocation.getArgument(1);
when(accountLockManager.withLockAsync(any(), anyList(), any(), any())).thenAnswer(invocation -> {
final Supplier<CompletableFuture<?>> taskSupplier = invocation.getArgument(2);
taskSupplier.get().join();
return CompletableFuture.completedFuture(null);
@@ -122,7 +122,7 @@ class AccountsManagerConcurrentModificationIntegrationTest {
final PhoneNumberIdentifiers phoneNumberIdentifiers = mock(PhoneNumberIdentifiers.class);
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(anyString()))
.thenAnswer((Answer<UUID>) invocation -> UUID.randomUUID());
.thenAnswer((Answer<CompletableFuture<UUID>>) invocation -> CompletableFuture.completedFuture(UUID.randomUUID()));
accountsManager = new AccountsManager(
accounts,
@@ -151,7 +151,7 @@ public class AccountsManagerDeviceTransferIntegrationTest {
@Test
void waitForRestoreAccountRequest() {
final String token = RandomStringUtils.randomAlphanumeric(16);
final String token = RandomStringUtils.secure().nextAlphanumeric(16);
final RestoreAccountRequest restoreAccountRequest =
new RestoreAccountRequest(RestoreAccountRequest.Method.DEVICE_TRANSFER);
@@ -170,7 +170,7 @@ public class AccountsManagerDeviceTransferIntegrationTest {
@Test
void waitForRestoreAccountRequestAlreadyRequested() {
final String token = RandomStringUtils.randomAlphanumeric(16);
final String token = RandomStringUtils.secure().nextAlphanumeric(16);
final RestoreAccountRequest restoreAccountRequest =
new RestoreAccountRequest(RestoreAccountRequest.Method.DEVICE_TRANSFER);
@@ -183,6 +183,7 @@ public class AccountsManagerDeviceTransferIntegrationTest {
@Test
void waitForRestoreAccountRequestTimeout() {
assertEquals(Optional.empty(),
accountsManager.waitForRestoreAccountRequest(RandomStringUtils.randomAlphanumeric(16), Duration.ofMillis(1)).join());
accountsManager.waitForRestoreAccountRequest(RandomStringUtils.secure().nextAlphanumeric(16),
Duration.ofMillis(1)).join());
}
}
@@ -15,6 +15,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyByte;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
@@ -194,9 +195,9 @@ class AccountsManagerTest {
final PhoneNumberIdentifiers phoneNumberIdentifiers = mock(PhoneNumberIdentifiers.class);
phoneNumberIdentifiersByE164 = new HashMap<>();
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(anyString())).thenAnswer((Answer<UUID>) invocation -> {
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(anyString())).thenAnswer((Answer<CompletableFuture<UUID>>) invocation -> {
final String number = invocation.getArgument(0, String.class);
return phoneNumberIdentifiersByE164.computeIfAbsent(number, n -> UUID.randomUUID());
return CompletableFuture.completedFuture(phoneNumberIdentifiersByE164.computeIfAbsent(number, n -> UUID.randomUUID()));
});
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
@@ -208,14 +209,14 @@ class AccountsManagerTest {
final AccountLockManager accountLockManager = mock(AccountLockManager.class);
doAnswer(invocation -> {
final Runnable task = invocation.getArgument(1);
final Runnable task = invocation.getArgument(2);
task.run();
return null;
}).when(accountLockManager).withLock(any(), any(), any());
}).when(accountLockManager).withLock(any(), anyList(), any(), any());
when(accountLockManager.withLockAsync(any(), any(), any())).thenAnswer(invocation -> {
final Supplier<CompletableFuture<?>> taskSupplier = invocation.getArgument(1);
when(accountLockManager.withLockAsync(any(), anyList(), any(), any())).thenAnswer(invocation -> {
final Supplier<CompletableFuture<?>> taskSupplier = invocation.getArgument(2);
return taskSupplier.get();
});
@@ -853,6 +854,7 @@ class AccountsManagerTest {
when(existingAccount.getNumber()).thenReturn(e164);
when(existingAccount.getPhoneNumberIdentifier()).thenReturn(requestedAccount.getIdentifier(IdentityType.PNI));
when(existingAccount.getIdentifier(IdentityType.PNI)).thenReturn(requestedAccount.getIdentifier(IdentityType.PNI));
when(existingAccount.getPrimaryDevice()).thenReturn(mock(Device.class));
throw new AccountAlreadyExistsException(existingAccount);
});
@@ -10,6 +10,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -113,21 +114,21 @@ class AccountsManagerUsernameIntegrationTest {
final AccountLockManager accountLockManager = mock(AccountLockManager.class);
doAnswer(invocation -> {
final Runnable task = invocation.getArgument(1);
final Runnable task = invocation.getArgument(2);
task.run();
return null;
}).when(accountLockManager).withLock(any(), any(), any());
}).when(accountLockManager).withLock(any(), anyList(), any(), any());
when(accountLockManager.withLockAsync(any(), any(), any())).thenAnswer(invocation -> {
final Supplier<CompletableFuture<?>> taskSupplier = invocation.getArgument(1);
when(accountLockManager.withLockAsync(any(), anyList(), any(), any())).thenAnswer(invocation -> {
final Supplier<CompletableFuture<?>> taskSupplier = invocation.getArgument(2);
taskSupplier.get().join();
return CompletableFuture.completedFuture(null);
});
final PhoneNumberIdentifiers phoneNumberIdentifiers =
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbClient(), Tables.PNI.tableName());
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), Tables.PNI.tableName());
final MessagesManager messageManager = mock(MessagesManager.class);
final ProfilesManager profileManager = mock(ProfilesManager.class);
@@ -125,7 +125,7 @@ public class AddRemoveDeviceIntegrationTest {
when(svr2Client.deleteBackups(any())).thenReturn(CompletableFuture.completedFuture(null));
final PhoneNumberIdentifiers phoneNumberIdentifiers =
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
DynamoDbExtensionSchema.Tables.PNI.tableName());
messagesManager = mock(MessagesManager.class);
@@ -81,7 +81,7 @@ class MessagePersisterIntegrationTest {
final AccountsManager accountsManager = mock(AccountsManager.class);
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
messageDeliveryScheduler, messageDeletionExecutorService, Clock.systemUTC(), dynamicConfigurationManager);
messageDeliveryScheduler, messageDeletionExecutorService, Clock.systemUTC());
messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, mock(ReportMessageManager.class),
messageDeletionExecutorService);
@@ -197,7 +197,7 @@ class MessagePersisterIntegrationTest {
return MessageProtos.Envelope.newBuilder()
.setClientTimestamp(serverTimestamp * 2) // client timestamp may not be accurate
.setServerTimestamp(serverTimestamp)
.setContent(ByteString.copyFromUtf8(RandomStringUtils.randomAlphanumeric(256)))
.setContent(ByteString.copyFromUtf8(RandomStringUtils.secure().nextAlphanumeric(256)))
.setType(MessageProtos.Envelope.Type.CIPHERTEXT)
.setServerGuid(messageGuid.toString())
.setDestinationServiceId(UUID.randomUUID().toString())
@@ -99,7 +99,7 @@ class MessagePersisterTest {
resubscribeRetryExecutorService = Executors.newSingleThreadScheduledExecutor();
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
messageDeliveryScheduler, sharedExecutorService, Clock.systemUTC(), dynamicConfigurationManager);
messageDeliveryScheduler, sharedExecutorService, Clock.systemUTC());
messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager,
dynamicConfigurationManager, PERSIST_DELAY, 1);
@@ -353,7 +353,7 @@ class MessagePersisterTest {
.setDestinationServiceId(accountUuid.toString())
.setClientTimestamp(firstMessageTimestamp.toEpochMilli() + i)
.setServerTimestamp(firstMessageTimestamp.toEpochMilli() + i)
.setContent(ByteString.copyFromUtf8(RandomStringUtils.randomAlphanumeric(256)))
.setContent(ByteString.copyFromUtf8(RandomStringUtils.secure().nextAlphanumeric(256)))
.setType(MessageProtos.Envelope.Type.CIPHERTEXT)
.setServerGuid(messageGuid.toString())
.build();
@@ -64,12 +64,8 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.junitpioneer.jupiter.cartesian.CartesianTest;
import org.reactivestreams.Publisher;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
import org.signal.libsignal.protocol.ServiceId;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicMessagesConfiguration;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
@@ -98,26 +94,17 @@ class MessagesCacheTest {
private Scheduler messageDeliveryScheduler;
private MessagesCache messagesCache;
private DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private DynamicConfiguration dynamicConfiguration;
private static final UUID DESTINATION_UUID = UUID.randomUUID();
private static final byte DESTINATION_DEVICE_ID = 7;
@BeforeEach
void setUp() throws Exception {
dynamicConfiguration = mock(DynamicConfiguration.class);
when(dynamicConfiguration.getMessagesConfiguration()).thenReturn(
new DynamicMessagesConfiguration(true, true, true));
dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
sharedExecutorService = Executors.newSingleThreadExecutor();
resubscribeRetryExecutorService = Executors.newSingleThreadScheduledExecutor();
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
messageDeliveryScheduler, sharedExecutorService, Clock.systemUTC(), dynamicConfigurationManager);
messageDeliveryScheduler, sharedExecutorService, Clock.systemUTC());
}
@AfterEach
@@ -321,7 +308,7 @@ class MessagesCacheTest {
}
final MessagesCache messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
messageDeliveryScheduler, sharedExecutorService, cacheClock, dynamicConfigurationManager);
messageDeliveryScheduler, sharedExecutorService, cacheClock);
final List<MessageProtos.Envelope> actualMessages = Flux.from(
messagesCache.get(DESTINATION_UUID, DESTINATION_DEVICE_ID))
@@ -429,12 +416,9 @@ class MessagesCacheTest {
assertEquals(DESTINATION_DEVICE_ID, MessagesCache.getDeviceIdFromQueueName(queues.getFirst()));
}
@CartesianTest
void testMultiRecipientMessage(@CartesianTest.Values(booleans = {true, false}) final boolean sharedMrmKeyPresent,
@CartesianTest.Values(booleans = {true, false}) final boolean useSharedMrmData) {
when(dynamicConfiguration.getMessagesConfiguration())
.thenReturn(new DynamicMessagesConfiguration(true, true, useSharedMrmData));
@ParameterizedTest
@ValueSource(booleans = {true, false})
void testMultiRecipientMessage(final boolean sharedMrmKeyPresent) {
final ServiceIdentifier destinationServiceId = new AciServiceIdentifier(UUID.randomUUID());
final byte deviceId = 1;
@@ -453,10 +437,8 @@ class MessagesCacheTest {
.toBuilder()
// clear some things added by the helper
.clearServerGuid()
// mrm views phase 2: messages have content
.setContent(
ByteString.copyFrom(mrm.messageForRecipient(mrm.getRecipients().get(destinationServiceId.toLibsignal()))))
.setSharedMrmKey(ByteString.copyFrom(sharedMrmDataKey))
.clearContent()
.build();
messagesCache.insert(guid, destinationServiceId.uuid(), deviceId, message);
@@ -464,7 +446,7 @@ class MessagesCacheTest {
.withBinaryCluster(conn -> conn.sync().exists(sharedMrmDataKey)));
final List<MessageProtos.Envelope> messages = get(destinationServiceId.uuid(), deviceId, 1);
if (useSharedMrmData && !sharedMrmKeyPresent) {
if (!sharedMrmKeyPresent) {
assertTrue(messages.isEmpty());
} else {
@@ -493,68 +475,9 @@ class MessagesCacheTest {
}, "Shared MRM data should be deleted asynchronously");
}
@CartesianTest
void testMultiRecipientMessagePhase2MissingContentSafeguard(
@CartesianTest.Values(booleans = {true, false}) final boolean useSharedMrmData,
@CartesianTest.Values(booleans = {true, false}) final boolean fetchSharedMrmData) {
when(dynamicConfiguration.getMessagesConfiguration())
.thenReturn(new DynamicMessagesConfiguration(true, fetchSharedMrmData, useSharedMrmData));
final ServiceIdentifier destinationServiceId = new AciServiceIdentifier(UUID.randomUUID());
final byte deviceId = 1;
final SealedSenderMultiRecipientMessage mrm = generateRandomMrmMessage(destinationServiceId, deviceId);
final byte[] sharedMrmDataKey = messagesCache.insertSharedMultiRecipientMessagePayload(mrm);
final UUID guid = UUID.randomUUID();
final MessageProtos.Envelope message = generateRandomMessage(guid, destinationServiceId, true)
.toBuilder()
// clear some things added by the helper
.clearServerGuid()
// mrm views phase 2: there is a safeguard against missing content, even if the dynamic configuration
// is to not fetch or use shared MRM data
.clearContent()
.setSharedMrmKey(ByteString.copyFrom(sharedMrmDataKey))
.build();
messagesCache.insert(guid, destinationServiceId.uuid(), deviceId, message);
assertEquals(1, (long) REDIS_CLUSTER_EXTENSION.getRedisCluster()
.withBinaryCluster(conn -> conn.sync().exists(sharedMrmDataKey)));
final List<MessageProtos.Envelope> messages = get(destinationServiceId.uuid(), deviceId, 1);
assertEquals(1, messages.size());
assertEquals(guid, UUID.fromString(messages.getFirst().getServerGuid()));
assertFalse(messages.getFirst().hasSharedMrmKey());
final SealedSenderMultiRecipientMessage.Recipient recipient = mrm.getRecipients()
.get(destinationServiceId.toLibsignal());
assertArrayEquals(mrm.messageForRecipient(recipient), messages.getFirst().getContent().toByteArray());
final Optional<RemovedMessage> removedMessage = messagesCache.remove(destinationServiceId.uuid(), deviceId, guid)
.join();
assertTrue(removedMessage.isPresent());
assertEquals(guid, UUID.fromString(removedMessage.get().serverGuid().toString()));
assertTrue(get(destinationServiceId.uuid(), deviceId, 1).isEmpty());
// updating the shared MRM data is purely async, so we just wait for it
assertTimeoutPreemptively(Duration.ofSeconds(1), () -> {
boolean exists;
do {
exists = 1 == REDIS_CLUSTER_EXTENSION.getRedisCluster()
.withBinaryCluster(conn -> conn.sync().exists(sharedMrmDataKey));
} while (exists);
}, "Shared MRM data should be deleted asynchronously");
}
@CartesianTest
void testGetMessagesToPersist(@CartesianTest.Values(booleans = {true, false}) final boolean sharedMrmKeyPresent,
@CartesianTest.Values(booleans = {true, false}) final boolean useSharedMrmData) {
when(dynamicConfiguration.getMessagesConfiguration())
.thenReturn(new DynamicMessagesConfiguration(true, true, useSharedMrmData));
@ParameterizedTest
@ValueSource(booleans = {true, false})
void testGetMessagesToPersist(final boolean sharedMrmKeyPresent) {
final UUID destinationUuid = UUID.randomUUID();
final ServiceIdentifier destinationServiceId = new AciServiceIdentifier(destinationUuid);
@@ -579,24 +502,22 @@ class MessagesCacheTest {
final MessageProtos.Envelope mrmMessage = generateRandomMessage(mrmMessageGuid, destinationServiceId, true)
.toBuilder()
// clear some things added by the helper
.clearServerGuid()
// mrm views phase 2: messages have content
.setContent(
ByteString.copyFrom(mrm.messageForRecipient(mrm.getRecipients().get(new ServiceId.Aci(destinationUuid)))))
.clearContent()
.setSharedMrmKey(ByteString.copyFrom(sharedMrmDataKey))
.build();
messagesCache.insert(mrmMessageGuid, destinationUuid, deviceId, mrmMessage);
final List<MessageProtos.Envelope> messages = messagesCache.getMessagesToPersist(destinationUuid, deviceId, 100);
if (useSharedMrmData && !sharedMrmKeyPresent) {
if (!sharedMrmKeyPresent) {
assertEquals(1, messages.size());
} else {
assertEquals(2, messages.size());
assertEquals(mrmMessage.toBuilder().
clearSharedMrmKey().
setServerGuid(mrmMessageGuid.toString())
assertEquals(mrmMessage.toBuilder()
.clearSharedMrmKey()
.setContent(ByteString.copyFrom(
mrm.messageForRecipient(mrm.getRecipients().get(destinationServiceId.toLibsignal()))))
.build(),
messages.getLast());
}
@@ -637,7 +558,7 @@ class MessagesCacheTest {
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
messagesCache = new MessagesCache(mockCluster, messageDeliveryScheduler,
Executors.newSingleThreadExecutor(), Clock.systemUTC(), mock(DynamicConfigurationManager.class));
Executors.newSingleThreadExecutor(), Clock.systemUTC());
}
@AfterEach
@@ -823,12 +744,11 @@ class MessagesCacheTest {
}
private MessageProtos.Envelope generateRandomMessage(final UUID messageGuid,
final ServiceIdentifier destinationServiceId, final boolean sealedSender,
final long timestamp) {
final ServiceIdentifier destinationServiceId, final boolean sealedSender, final long timestamp) {
final MessageProtos.Envelope.Builder envelopeBuilder = MessageProtos.Envelope.newBuilder()
.setClientTimestamp(timestamp)
.setServerTimestamp(timestamp)
.setContent(ByteString.copyFromUtf8(RandomStringUtils.randomAlphanumeric(256)))
.setContent(ByteString.copyFromUtf8(RandomStringUtils.secure().nextAlphanumeric(256)))
.setType(MessageProtos.Envelope.Type.CIPHERTEXT)
.setServerGuid(messageGuid.toString())
.setDestinationServiceId(destinationServiceId.toServiceIdentifierString());
@@ -25,7 +25,7 @@ class PhoneNumberIdentifiersTest {
@BeforeEach
void setUp() {
phoneNumberIdentifiers = new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
phoneNumberIdentifiers = new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
Tables.PNI.tableName());
}
@@ -34,28 +34,18 @@ class PhoneNumberIdentifiersTest {
final String number = "+18005551234";
final String differentNumber = "+18005556789";
final UUID firstPni = phoneNumberIdentifiers.getPhoneNumberIdentifier(number);
final UUID secondPni = phoneNumberIdentifiers.getPhoneNumberIdentifier(number);
final UUID firstPni = phoneNumberIdentifiers.getPhoneNumberIdentifier(number).join();
final UUID secondPni = phoneNumberIdentifiers.getPhoneNumberIdentifier(number).join();
assertEquals(firstPni, secondPni);
assertNotEquals(firstPni, phoneNumberIdentifiers.getPhoneNumberIdentifier(differentNumber));
assertNotEquals(firstPni, phoneNumberIdentifiers.getPhoneNumberIdentifier(differentNumber).join());
}
@Test
void generatePhoneNumberIdentifierIfNotExists() {
final String number = "+18005551234";
assertEquals(phoneNumberIdentifiers.generatePhoneNumberIdentifierIfNotExists(number),
phoneNumberIdentifiers.generatePhoneNumberIdentifierIfNotExists(number));
}
@Test
void getPhoneNumber() {
final String number = "+18005551234";
assertFalse(phoneNumberIdentifiers.getPhoneNumber(UUID.randomUUID()).isPresent());
final UUID pni = phoneNumberIdentifiers.getPhoneNumberIdentifier(number);
assertEquals(Optional.of(number), phoneNumberIdentifiers.getPhoneNumber(pni));
assertEquals(phoneNumberIdentifiers.generatePhoneNumberIdentifierIfNotExists(number).join(),
phoneNumberIdentifiers.generatePhoneNumberIdentifierIfNotExists(number).join());
}
}
@@ -5,6 +5,7 @@
package org.whispersystems.textsecuregcm.storage;
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;
@@ -14,6 +15,7 @@ import java.time.Clock;
import java.time.Duration;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.BeforeEach;
@@ -34,6 +36,7 @@ public class RegistrationRecoveryTest {
private static final Duration EXPIRATION = Duration.ofSeconds(1000);
private static final String NUMBER = "+18005555555";
private static final UUID PNI = UUID.randomUUID();
private static final SaltedTokenHash ORIGINAL_HASH = SaltedTokenHash.generateFor("pass1");
@@ -41,72 +44,106 @@ public class RegistrationRecoveryTest {
@RegisterExtension
private static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(
Tables.PNI,
Tables.REGISTRATION_RECOVERY_PASSWORDS);
private RegistrationRecoveryPasswords store;
private RegistrationRecoveryPasswords registrationRecoveryPasswords;
private RegistrationRecoveryPasswordsManager manager;
@BeforeEach
public void before() throws Exception {
CLOCK.setTimeMillis(Clock.systemUTC().millis());
store = new RegistrationRecoveryPasswords(
registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
Tables.REGISTRATION_RECOVERY_PASSWORDS.tableName(),
EXPIRATION,
DYNAMO_DB_EXTENSION.getDynamoDbClient(),
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
CLOCK
);
manager = new RegistrationRecoveryPasswordsManager(store);
final PhoneNumberIdentifiers phoneNumberIdentifiers =
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), Tables.PNI.tableName());
manager = new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords, phoneNumberIdentifiers);
}
@Test
public void testLookupAfterWrite() throws Exception {
store.addOrReplace(NUMBER, ORIGINAL_HASH).get();
registrationRecoveryPasswords.addOrReplace(NUMBER, PNI, ORIGINAL_HASH).get();
final long initialExp = fetchTimestamp(NUMBER);
final long expectedExpiration = CLOCK.instant().getEpochSecond() + EXPIRATION.getSeconds();
assertEquals(expectedExpiration, initialExp);
final Optional<SaltedTokenHash> saltedTokenHash = store.lookup(NUMBER).get();
assertTrue(saltedTokenHash.isPresent());
assertEquals(ORIGINAL_HASH.salt(), saltedTokenHash.get().salt());
assertEquals(ORIGINAL_HASH.hash(), saltedTokenHash.get().hash());
{
final Optional<SaltedTokenHash> saltedTokenHashByNumber = registrationRecoveryPasswords.lookup(NUMBER).get();
assertTrue(saltedTokenHashByNumber.isPresent());
assertEquals(ORIGINAL_HASH.salt(), saltedTokenHashByNumber.get().salt());
assertEquals(ORIGINAL_HASH.hash(), saltedTokenHashByNumber.get().hash());
}
/* {
final Optional<SaltedTokenHash> saltedTokenHashByPni = registrationRecoveryPasswords.lookup(PNI).get();
assertTrue(saltedTokenHashByPni.isPresent());
assertEquals(ORIGINAL_HASH.salt(), saltedTokenHashByPni.get().salt());
assertEquals(ORIGINAL_HASH.hash(), saltedTokenHashByPni.get().hash());
} */
}
@Test
public void testLookupAfterRefresh() throws Exception {
store.addOrReplace(NUMBER, ORIGINAL_HASH).get();
registrationRecoveryPasswords.addOrReplace(NUMBER, PNI, ORIGINAL_HASH).get();
CLOCK.increment(50, TimeUnit.SECONDS);
store.addOrReplace(NUMBER, ORIGINAL_HASH).get();
registrationRecoveryPasswords.addOrReplace(NUMBER, PNI, ORIGINAL_HASH).get();
final long updatedExp = fetchTimestamp(NUMBER);
final long expectedExp = CLOCK.instant().getEpochSecond() + EXPIRATION.getSeconds();
assertEquals(expectedExp, updatedExp);
final Optional<SaltedTokenHash> saltedTokenHash = store.lookup(NUMBER).get();
assertTrue(saltedTokenHash.isPresent());
assertEquals(ORIGINAL_HASH.salt(), saltedTokenHash.get().salt());
assertEquals(ORIGINAL_HASH.hash(), saltedTokenHash.get().hash());
{
final Optional<SaltedTokenHash> saltedTokenHashByNumber = registrationRecoveryPasswords.lookup(NUMBER).get();
assertTrue(saltedTokenHashByNumber.isPresent());
assertEquals(ORIGINAL_HASH.salt(), saltedTokenHashByNumber.get().salt());
assertEquals(ORIGINAL_HASH.hash(), saltedTokenHashByNumber.get().hash());
}
/* {
final Optional<SaltedTokenHash> saltedTokenHashByPni = registrationRecoveryPasswords.lookup(PNI).get();
assertTrue(saltedTokenHashByPni.isPresent());
assertEquals(ORIGINAL_HASH.salt(), saltedTokenHashByPni.get().salt());
assertEquals(ORIGINAL_HASH.hash(), saltedTokenHashByPni.get().hash());
} */
}
@Test
public void testReplace() throws Exception {
store.addOrReplace(NUMBER, ORIGINAL_HASH).get();
store.addOrReplace(NUMBER, ANOTHER_HASH).get();
registrationRecoveryPasswords.addOrReplace(NUMBER, PNI, ORIGINAL_HASH).get();
registrationRecoveryPasswords.addOrReplace(NUMBER, PNI, ANOTHER_HASH).get();
final Optional<SaltedTokenHash> saltedTokenHash = store.lookup(NUMBER).get();
assertTrue(saltedTokenHash.isPresent());
assertEquals(ANOTHER_HASH.salt(), saltedTokenHash.get().salt());
assertEquals(ANOTHER_HASH.hash(), saltedTokenHash.get().hash());
{
final Optional<SaltedTokenHash> saltedTokenHashByNumber = registrationRecoveryPasswords.lookup(NUMBER).get();
assertTrue(saltedTokenHashByNumber.isPresent());
assertEquals(ANOTHER_HASH.salt(), saltedTokenHashByNumber.get().salt());
assertEquals(ANOTHER_HASH.hash(), saltedTokenHashByNumber.get().hash());
}
/* {
final Optional<SaltedTokenHash> saltedTokenHashByPni = registrationRecoveryPasswords.lookup(PNI).get();
assertTrue(saltedTokenHashByPni.isPresent());
assertEquals(ANOTHER_HASH.salt(), saltedTokenHashByPni.get().salt());
assertEquals(ANOTHER_HASH.hash(), saltedTokenHashByPni.get().hash());
} */
}
@Test
public void testRemove() throws Exception {
store.addOrReplace(NUMBER, ORIGINAL_HASH).get();
assertTrue(store.lookup(NUMBER).get().isPresent());
assertDoesNotThrow(() -> registrationRecoveryPasswords.removeEntry(NUMBER, PNI).join());
store.removeEntry(NUMBER).get();
assertTrue(store.lookup(NUMBER).get().isEmpty());
registrationRecoveryPasswords.addOrReplace(NUMBER, PNI, ORIGINAL_HASH).get();
assertTrue(registrationRecoveryPasswords.lookup(NUMBER).get().isPresent());
registrationRecoveryPasswords.removeEntry(NUMBER, PNI).get();
assertTrue(registrationRecoveryPasswords.lookup(NUMBER).get().isEmpty());
}
@Test
@@ -1,22 +0,0 @@
/*
* Copyright 2013 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.util;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import org.junit.jupiter.api.Test;
class NumberPrefixTest {
@Test
void testPrefixes() {
assertThat(Util.getNumberPrefix("+14151234567")).isEqualTo("+14151");
assertThat(Util.getNumberPrefix("+22587654321")).isEqualTo("+2258765");
assertThat(Util.getNumberPrefix("+298654321")).isEqualTo("+2986543");
assertThat(Util.getNumberPrefix("+12")).isEqualTo("+12");
}
}
@@ -99,7 +99,7 @@ class WebSocketConnectionIntegrationTest {
dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
when(dynamicConfigurationManager.getConfiguration()).thenReturn(new DynamicConfiguration());
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
messageDeliveryScheduler, sharedExecutorService, Clock.systemUTC(), dynamicConfigurationManager);
messageDeliveryScheduler, sharedExecutorService, Clock.systemUTC());
messagesDynamoDb = new MessagesDynamoDb(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), Tables.MESSAGES.tableName(), Duration.ofDays(7),
sharedExecutorService);
@@ -389,7 +389,7 @@ class WebSocketConnectionIntegrationTest {
return MessageProtos.Envelope.newBuilder()
.setClientTimestamp(timestamp)
.setServerTimestamp(timestamp)
.setContent(ByteString.copyFromUtf8(RandomStringUtils.randomAlphanumeric(256)))
.setContent(ByteString.copyFromUtf8(RandomStringUtils.secure().nextAlphanumeric(256)))
.setType(MessageProtos.Envelope.Type.CIPHERTEXT)
.setServerGuid(messageGuid.toString())
.setDestinationServiceId(UUID.randomUUID().toString())
+17
View File
@@ -101,6 +101,23 @@
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>-javaagent:${org.mockito:mockito-core:jar}</argLine>
</configuration>
</plugin>
</plugins>
</build>
</project>