Compare commits

..
Author SHA1 Message Date
Jonathan Klabunde Tomer 552edbc1eb update to the latest revision of the spam filter 2025-08-21 15:25:40 -07:00
Jon Chambers 7f5ea6608c Add plumbing to roll out binary service IDs/UUIDs on envelopes to internal users 2025-08-21 14:53:41 -07:00
Jonathan Klabunde Tomer 78a7112675 Use native exponential histograms 2025-08-21 14:53:21 -07:00
Ravi Khadiwala be8b44d645 Add noise tunnel connection metrics 2025-08-21 10:32:11 -05:00
Ravi Khadiwala 7ca3604601 Augment gRPC metrics with UA 2025-08-21 10:32:11 -05:00
Ravi Khadiwala c5af8f3a9e Adjust default backup level configuration 2025-08-19 12:43:51 -05:00
Ravi Khadiwala d67847e5b1 Make s3 endpoints configurable 2025-08-19 12:29:42 -05:00
Jon Chambers 3a5704a5cc Fix a flaky MessageCacheInsertScript test by calling .join() on async operations 2025-08-19 13:14:20 -04:00
Katherine Yen 50a54136e8 Update to the latest version of the spam filter 2025-08-18 14:59:07 -04:00
ameya-signal a1d9c4c062 Check presence before updating last message versionstamp 2025-08-18 10:16:00 -07:00
Katherine 4acb3b5ac7 Use the target device's registration ID in the GET /v1/keys/identifier/deviceId ratelimit 2025-08-18 10:15:45 -07:00
ravi-signal b76eaa1098 Add a bounded virtual executor service 2025-08-15 15:49:50 -05:00
Ravi Khadiwala c883cd8148 Encourage PQ prekey upload to new store 2025-08-15 15:48:57 -05:00
Ravi Khadiwala 1e77d0471e Remove paged prekey experiment configuration 2025-08-15 15:48:57 -05:00
Jon Chambers a94ce72894 Revert "Use MessageStream in WebSocketConnection"
This reverts commit 470e17963a.
2025-08-13 16:13:50 -04:00
Jon Chambers 0f2a4d02e0 Revert "Add a (failing!) test for dropped errors during WebSocketConnectionTest"
This reverts commit fc8d180f7c.
2025-08-13 16:13:50 -04:00
Jon Chambers 4d521cea42 Revert "Move error/entry handling to subscribe handlers"
This reverts commit 7d10209198.
2025-08-13 16:13:50 -04:00
Jon Chambers 7d10209198 Move error/entry handling to subscribe handlers 2025-08-13 14:38:53 -04:00
Jon Chambers fc8d180f7c Add a (failing!) test for dropped errors during WebSocketConnectionTest 2025-08-13 14:38:53 -04:00
Jon Chambers 470e17963a Use MessageStream in WebSocketConnection 2025-08-13 10:22:55 -04:00
Chris Eager 4c5dc118aa Use nanoTime for queue drain metric 2025-08-11 18:26:40 -04:00
Chris Eager ad84cd848a Fix potential NullPointerException in StripeManager#createPaymentIntent 2025-08-11 18:26:21 -04:00
Katherine 127bd56f73 Don't require ALWAYS_CAPABLE capabilities when linking a device 2025-08-11 18:25:55 -04:00
Jon Chambers ad3721acf1 Count "send sync message" attempts with incorrect registration IDs 2025-08-11 18:24:38 -04:00
Jon Chambers 085127326b Improve thread synchronization in RedisDynamoDbMessagePublisherTest 2025-08-11 18:24:10 -04:00
Jon Chambers 2e32ab3282 Extend the Redis command timeout in FaultTolerantRedisClusterClientTest 2025-08-11 18:23:51 -04:00
ameya-signal 8bb125597b Add initial version of FoundationDB message store 2025-08-11 18:23:27 -04:00
Jonathan Klabunde Tomer 8ca7f85bf0 fix NPE in MetricsUtil#configureHistogramFilters 2025-08-11 14:11:17 -07:00
Jonathan Klabunde Tomer 9d4d36939c Update to the latest revision of the spam filter 2025-08-11 12:30:40 -07:00
Jonathan Klabunde Tomer dabe1c157b remove unnecessary MessageMetrics default constructor 2025-08-11 12:28:28 -07:00
Jonathan Klabunde TomerandJon Chambers 36d0c4422e Configure Micrometer distribution buckets for OpenTelemetry
Co-authored-by: Jon Chambers <63609320+jon-signal@users.noreply.github.com>
2025-08-11 11:45:33 -07:00
Jon Chambers 1429efd573 Retire duplicative "message delivery time" metrics 2025-08-08 13:52:20 -04:00
Katherine 93c03c5676 Hardcode ssre2 and deleteSync capabilities to true from GET /v1/profile/{identifier} 2025-08-08 09:28:13 -04:00
Katherine Yen bd1bd007c0 Count successful timezone parsing to get a ratio of success to failures 2025-08-08 09:27:46 -04:00
Katherine Yen f485406c4d Stop using device creation timestamp as a fallback in getting a recommended notification time 2025-08-08 09:27:46 -04:00
Jon Chambers d96c360016 Introduce MessageStream and RedisDynamoDbMessagePublisher 2025-08-08 09:27:05 -04:00
Jon Chambers 6d71f43b6c Update to the latest version of the spam filter 2025-08-08 09:26:21 -04:00
Katherine d6824fcaf6 Remove EncryptDeviceCreationTimestampCommand 2025-08-04 12:51:07 -04:00
Katherine 61f388f5f4 Rename registrationId field on TransferArchiveUploadedRequest 2025-08-04 12:50:56 -04:00
Jon Chambers 6955e1ee20 Retire RedisClusterHealthCheck 2025-08-04 09:59:28 -04:00
Jon Chambers 7bb4a4bc90 Remove an unused hasMessages method 2025-08-04 09:59:17 -04:00
Jon Chambers 6fa01a5d48 Remove unused Lua scripts 2025-08-04 09:59:17 -04:00
Jon Chambers 5a65a46fc1 Remove an unused constant 2025-08-04 09:59:17 -04:00
Jon Chambers c255355e5c Make internal Redis connection management methods private 2025-08-04 09:59:17 -04:00
Jon Chambers 8d3781db90 Remove the "send message" timeout 2025-08-04 09:58:56 -04:00
ravi-signal f6a87b2ec0 Always elide devices missing required PreKeys 2025-08-01 12:01:35 -05:00
ravi-signal e8a1854c5e Move /v1/svrb/auth to /v1/archives/auth/svrb 2025-08-01 12:00:44 -05:00
Katherine f8d27d8fab "encrypt timestamps" crawler optimizations 2025-08-01 12:31:09 -04:00
Jon Chambers 94dd2712b1 Extent timeout in WebSocketConnectionTest 2025-07-31 17:09:02 -04:00
Jon Chambers a4804f6501 Don't retry "connection closed" errors 2025-07-31 16:37:19 -04:00
Jon Chambers 5cb3a053fb Add a timer for sendMessage calls 2025-07-31 16:37:19 -04:00
Jon Chambers 4923b6da68 Measure only errors that terminate a message stream 2025-07-31 16:37:19 -04:00
Jon Chambers b7e64e09a3 Add an already-passing, disabled-by-default test for client WebSocket timeouts 2025-07-31 16:37:19 -04:00
Jon Chambers 76e65a47a2 Represent timeouts as Durations rather than bare millis 2025-07-31 16:37:19 -04:00
Jon Chambers ef644ce319 Drop WhisperServerServiceTest#testOtlpConfig 2025-07-31 16:27:29 -04:00
Jon Chambers 08c4179a7a Disable OpenTelemetry in tests 2025-07-31 16:27:29 -04:00
Jon Chambers 5c3be9c3d6 Use error-specific retry mechanisms in WebSocketConnection and associated classes 2025-07-31 10:53:11 -04:00
Jonathan Klabunde Tomer 8fc0b49994 tweak OpenTelemetry configuration 2025-07-30 14:42:20 -07:00
Katherine db4c71368c Use registration ID or creation timestamp in the transfer archive flow 2025-07-30 15:32:49 -04:00
Jon Chambers 30774bbc40 Remove special-case handling for an extremely narrow message delivery edge case 2025-07-29 16:52:19 -04:00
Ravi Khadiwala 3b48c82c72 Update to the latest version of the spam filter 2025-07-29 15:51:22 -05:00
Jon Chambers 038c68c594 Rename WebSocketConnectionEventManager/Listener to MessageAvailabilityManager/Listener 2025-07-29 11:29:17 -04:00
Jon Chambers cf222e1105 Scope disconnection request listeners to a single connection 2025-07-29 11:17:48 -04:00
Jon Chambers 541c87e262 Always specify a list of device IDs when disconnecting all devices for an account 2025-07-29 11:17:48 -04:00
Katherine 5f5c345f94 Use one thread per account in the "encrypt timestamps" crawler 2025-07-29 09:51:36 -04:00
129 changed files with 3943 additions and 2190 deletions

No files matched your search

@@ -316,7 +316,7 @@ public class WhisperServerConfiguration extends Configuration {
@Valid
@NotNull
@JsonProperty
private VirtualThreadConfiguration virtualThread = new VirtualThreadConfiguration(Duration.ofMillis(1));
private VirtualThreadConfiguration virtualThread = new VirtualThreadConfiguration();
@Valid
@NotNull
@@ -27,7 +27,6 @@ import io.lettuce.core.metrics.MicrometerCommandLatencyRecorder;
import io.lettuce.core.metrics.MicrometerOptions;
import io.lettuce.core.resource.ClientResources;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.binder.grpc.MetricCollectingServerInterceptor;
import io.micrometer.core.instrument.binder.jvm.ExecutorServiceMetrics;
import io.netty.channel.local.LocalAddress;
import io.netty.channel.socket.nio.NioDatagramChannel;
@@ -93,6 +92,7 @@ import org.whispersystems.textsecuregcm.backup.BackupManager;
import org.whispersystems.textsecuregcm.backup.BackupsDb;
import org.whispersystems.textsecuregcm.backup.Cdn3BackupCredentialGenerator;
import org.whispersystems.textsecuregcm.backup.Cdn3RemoteStorageManager;
import org.whispersystems.textsecuregcm.backup.SecureValueRecoveryBCredentialsGeneratorFactory;
import org.whispersystems.textsecuregcm.badges.ConfiguredProfileBadgeConverter;
import org.whispersystems.textsecuregcm.captcha.CaptchaChecker;
import org.whispersystems.textsecuregcm.captcha.CaptchaClient;
@@ -126,7 +126,6 @@ import org.whispersystems.textsecuregcm.controllers.RemoteConfigController;
import org.whispersystems.textsecuregcm.controllers.RemoteConfigControllerV1;
import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery2Controller;
import org.whispersystems.textsecuregcm.controllers.SecureValueRecoveryBController;
import org.whispersystems.textsecuregcm.controllers.StickerController;
import org.whispersystems.textsecuregcm.controllers.SubscriptionController;
import org.whispersystems.textsecuregcm.controllers.VerificationController;
@@ -147,6 +146,7 @@ import org.whispersystems.textsecuregcm.grpc.ExternalServiceCredentialsAnonymous
import org.whispersystems.textsecuregcm.grpc.ExternalServiceCredentialsGrpcService;
import org.whispersystems.textsecuregcm.grpc.KeysAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.KeysGrpcService;
import org.whispersystems.textsecuregcm.grpc.MetricServerInterceptor;
import org.whispersystems.textsecuregcm.grpc.PaymentsGrpcService;
import org.whispersystems.textsecuregcm.grpc.ProfileAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.ProfileGrpcService;
@@ -191,7 +191,6 @@ import org.whispersystems.textsecuregcm.metrics.ReportedMessageMetricsListener;
import org.whispersystems.textsecuregcm.metrics.TlsCertificateExpirationUtil;
import org.whispersystems.textsecuregcm.metrics.TrafficSource;
import org.whispersystems.textsecuregcm.providers.MultiRecipientMessageProvider;
import org.whispersystems.textsecuregcm.providers.RedisClusterHealthCheck;
import org.whispersystems.textsecuregcm.push.APNSender;
import org.whispersystems.textsecuregcm.push.FcmSender;
import org.whispersystems.textsecuregcm.push.MessageSender;
@@ -199,7 +198,7 @@ import org.whispersystems.textsecuregcm.push.ProvisioningManager;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
import org.whispersystems.textsecuregcm.push.ReceiptSender;
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
import org.whispersystems.textsecuregcm.redis.ConnectionEventLogger;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
@@ -259,6 +258,7 @@ import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
import org.whispersystems.textsecuregcm.util.BufferingInterceptor;
import org.whispersystems.textsecuregcm.util.ManagedAwsCrt;
import org.whispersystems.textsecuregcm.util.ManagedExecutors;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
import org.whispersystems.textsecuregcm.util.VirtualExecutorServiceProvider;
@@ -273,7 +273,6 @@ import org.whispersystems.textsecuregcm.workers.BackupUsageRecalculationCommand;
import org.whispersystems.textsecuregcm.workers.CertificateCommand;
import org.whispersystems.textsecuregcm.workers.CheckDynamicConfigurationCommand;
import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
import org.whispersystems.textsecuregcm.workers.EncryptDeviceCreationTimestampCommand;
import org.whispersystems.textsecuregcm.workers.IdleDeviceNotificationSchedulerFactory;
import org.whispersystems.textsecuregcm.workers.MessagePersisterServiceCommand;
import org.whispersystems.textsecuregcm.workers.NotifyIdleDevicesCommand;
@@ -348,7 +347,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new IdleDeviceNotificationSchedulerFactory()));
bootstrap.addCommand(new RegenerateSecondaryDynamoDbTableDataCommand());
bootstrap.addCommand(new EncryptDeviceCreationTimestampCommand());
}
@Override
@@ -398,8 +396,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
environment.lifecycle().manage(new ManagedAwsCrt());
final ExecutorService awsSdkMetricsExecutor = environment.lifecycle()
.virtualExecutorService(name(getClass(), "awsSdkMetrics-%d"));
final ExecutorService awsSdkMetricsExecutor = ManagedExecutors.newVirtualThreadPerTaskExecutor(
"awsSdkMetrics",
config.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor(),
environment);
final DynamoDbAsyncClient dynamoDbAsyncClient = config.getDynamoDbClientConfiguration()
.buildAsyncClient(awsCredentialsProvider, new MicrometerAwsSdkMetricPublisher(awsSdkMetricsExecutor, "dynamoDbAsync"));
@@ -411,6 +411,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final S3AsyncClient asyncCdnS3Client = S3AsyncClient.builder()
.credentialsProvider(cdnCredentialsProvider)
.region(Region.of(config.getCdnConfiguration().region()))
.endpointOverride(config.getCdnConfiguration().endpointOverride())
.build();
BlockingQueue<Runnable> messageDeletionQueue = new LinkedBlockingQueue<>();
@@ -442,6 +443,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
S3AsyncClient asyncKeysS3Client = S3AsyncClient.builder()
.credentialsProvider(awsCredentialsProvider)
.region(Region.of(config.getPagedSingleUseKEMPreKeyStore().region()))
.endpointOverride(config.getPagedSingleUseKEMPreKeyStore().endpointOverride())
.build();
KeysManager keysManager = new KeysManager(
new SingleUseECPreKeyStore(dynamoDbAsyncClient, config.getDynamoDbTables().getEcKeys().getTableName()),
@@ -452,12 +454,11 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getDynamoDbTables().getPagedKemKeys().getTableName(),
config.getPagedSingleUseKEMPreKeyStore().bucket()),
new RepeatedUseECSignedPreKeyStore(dynamoDbAsyncClient, config.getDynamoDbTables().getEcSignedPreKeys().getTableName()),
new RepeatedUseKEMSignedPreKeyStore(dynamoDbAsyncClient, config.getDynamoDbTables().getKemLastResortKeys().getTableName()),
experimentEnrollmentManager);
new RepeatedUseKEMSignedPreKeyStore(dynamoDbAsyncClient, config.getDynamoDbTables().getKemLastResortKeys().getTableName()));
MessagesDynamoDb messagesDynamoDb = new MessagesDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
config.getDynamoDbTables().getMessages().getTableName(),
config.getDynamoDbTables().getMessages().getExpiration(),
messageDeletionAsyncExecutor);
messageDeletionAsyncExecutor, experimentEnrollmentManager);
RemoteConfigs remoteConfigs = new RemoteConfigs(dynamoDbClient,
config.getDynamoDbTables().getRemoteConfig().getTableName());
PushChallengeDynamoDb pushChallengeDynamoDb = new PushChallengeDynamoDb(dynamoDbClient,
@@ -504,7 +505,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
messageDeliveryQueue);
ScheduledExecutorService recurringJobExecutor = ScheduledExecutorServiceBuilder.of(environment, "recurringJob").threads(6).build();
ScheduledExecutorService websocketScheduledExecutor = ScheduledExecutorServiceBuilder.of(environment, "websocket").threads(8).build();
ExecutorService apnSenderExecutor = ExecutorServiceBuilder.of(environment, "apnSender")
.maxThreads(1).minThreads(1).build();
ExecutorService fcmSenderExecutor = ExecutorServiceBuilder.of(environment, "fcmSender")
@@ -566,14 +566,23 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
.maxThreads(2)
.minThreads(2)
.build();
ExecutorService googlePlayBillingExecutor = environment.lifecycle()
.virtualExecutorService(name(getClass(), "googlePlayBilling-%d"));
ExecutorService appleAppStoreExecutor = environment.lifecycle()
.virtualExecutorService(name(getClass(), "appleAppStore-%d"));
ExecutorService clientEventExecutor = environment.lifecycle()
.virtualExecutorService(name(getClass(), "clientEvent-%d"));
ExecutorService disconnectionRequestListenerExecutor = environment.lifecycle()
.virtualExecutorService(name(getClass(), "disconnectionRequest-%d"));
ExecutorService googlePlayBillingExecutor = ManagedExecutors.newVirtualThreadPerTaskExecutor(
"googlePlayBilling",
config.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor(),
environment);
ExecutorService appleAppStoreExecutor = ManagedExecutors.newVirtualThreadPerTaskExecutor(
"appleAppStore",
config.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor(),
environment);
ExecutorService clientEventExecutor = ManagedExecutors.newVirtualThreadPerTaskExecutor(
"clientEvent",
config.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor(),
environment);
ExecutorService disconnectionRequestListenerExecutor = ManagedExecutors.newVirtualThreadPerTaskExecutor(
"disconnectionRequest",
config.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor(),
environment);
ScheduledExecutorService appleAppStoreRetryExecutor = ScheduledExecutorServiceBuilder.of(environment, "appleAppStoreRetry").threads(1).build();
ScheduledExecutorService subscriptionProcessorRetryExecutor = ScheduledExecutorServiceBuilder.of(environment, "subscriptionProcessorRetry").threads(1).build();
@@ -596,9 +605,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
ExternalServiceCredentialsGenerator paymentsCredentialsGenerator = PaymentsController.credentialsGenerator(
config.getPaymentsServiceConfiguration());
ExternalServiceCredentialsGenerator svr2CredentialsGenerator = SecureValueRecovery2Controller.credentialsGenerator(
config.getSvr2Configuration());
ExternalServiceCredentialsGenerator svrbCredentialsGenerator = SecureValueRecoveryBController.credentialsGenerator(
config.getSvrbConfiguration());
config.getSvr2Configuration());
ExternalServiceCredentialsGenerator svrbCredentialsGenerator =
SecureValueRecoveryBCredentialsGeneratorFactory.svrbCredentialsGenerator(config.getSvrbConfiguration());
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager =
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords);
@@ -626,25 +635,28 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
() -> dynamicConfigurationManager.getConfiguration().getSvrbStatusCodesToIgnoreForAccountDeletion());
SecureStorageClient secureStorageClient = new SecureStorageClient(storageCredentialsGenerator,
storageServiceExecutor, storageServiceRetryExecutor, config.getSecureStorageServiceConfiguration());
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient, disconnectionRequestListenerExecutor);
final GrpcClientConnectionManager grpcClientConnectionManager = new GrpcClientConnectionManager();
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient, grpcClientConnectionManager, disconnectionRequestListenerExecutor);
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster, asyncCdnS3Client, config.getCdnConfiguration().bucket());
MessagesCache messagesCache = new MessagesCache(messagesCluster, messageDeliveryScheduler,
messageDeletionAsyncExecutor, clock);
messageDeletionAsyncExecutor, clock, experimentEnrollmentManager);
ClientReleaseManager clientReleaseManager = new ClientReleaseManager(clientReleases,
recurringJobExecutor,
config.getClientReleaseConfiguration().refreshInterval(),
Clock.systemUTC());
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster,
config.getReportMessageConfiguration().getCounterTtl());
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager,
messageDeletionAsyncExecutor, Clock.systemUTC());
RedisMessageAvailabilityManager redisMessageAvailabilityManager =
new RedisMessageAvailabilityManager(messagesCluster, clientEventExecutor, asyncOperationQueueingExecutor);
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
reportMessageManager, messageDeletionAsyncExecutor, Clock.systemUTC());
AccountLockManager accountLockManager = new AccountLockManager(dynamoDbClient,
config.getDynamoDbTables().getDeletedAccountsLock().getTableName());
ClientPublicKeysManager clientPublicKeysManager =
new ClientPublicKeysManager(clientPublicKeys, accountLockManager, accountLockExecutor);
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
pubsubClient, accountLockManager, keysManager, messagesManager, profilesManager,
secureStorageClient, secureValueRecovery2Client, secureValueRecoveryBClient, disconnectionRequestManager,
secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
registrationRecoveryPasswordsManager, clientPublicKeysManager, accountLockExecutor, messagePollExecutor,
clock, config.getLinkDeviceSecretConfiguration().secret().value(), dynamicConfigurationManager);
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs);
@@ -654,8 +666,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
apnSender, fcmSender, accountsManager, 0, 0);
PushNotificationManager pushNotificationManager =
new PushNotificationManager(accountsManager, apnSender, fcmSender, pushNotificationScheduler);
WebSocketConnectionEventManager webSocketConnectionEventManager =
new WebSocketConnectionEventManager(accountsManager, pushNotificationManager, messagesCluster, clientEventExecutor, asyncOperationQueueingExecutor);
RateLimiters rateLimiters = RateLimiters.create(dynamicConfigurationManager, rateLimitersCluster);
ProvisioningManager provisioningManager = new ProvisioningManager(pubsubClient);
IssuedReceiptsManager issuedReceiptsManager = new IssuedReceiptsManager(
@@ -675,8 +685,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
MessageDeliveryLoopMonitor messageDeliveryLoopMonitor =
config.logMessageDeliveryLoops() ? new RedisMessageDeliveryLoopMonitor(rateLimitersCluster) : new NoopMessageDeliveryLoopMonitor();
disconnectionRequestManager.addListener(webSocketConnectionEventManager);
final RegistrationLockVerificationManager registrationLockVerificationManager = new RegistrationLockVerificationManager(
accountsManager, disconnectionRequestManager, svr2CredentialsGenerator, registrationRecoveryPasswordsManager,
pushNotificationManager, rateLimiters);
@@ -753,7 +761,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
environment.lifecycle().manage(pushNotificationScheduler);
environment.lifecycle().manage(provisioningManager);
environment.lifecycle().manage(disconnectionRequestManager);
environment.lifecycle().manage(webSocketConnectionEventManager);
environment.lifecycle().manage(redisMessageAvailabilityManager);
environment.lifecycle().manage(currencyManager);
environment.lifecycle().manage(registrationServiceClient);
environment.lifecycle().manage(keyTransparencyServiceClient);
@@ -800,6 +808,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
tusAttachmentGenerator,
cdn3BackupCredentialGenerator,
cdn3RemoteStorageManager,
svrbCredentialsGenerator,
secureValueRecoveryBClient,
clock);
final AppleDeviceChecks appleDeviceChecks = new AppleDeviceChecks(
@@ -816,15 +826,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getAppleDeviceCheck().teamId(),
config.getAppleDeviceCheck().bundleId());
final GrpcClientConnectionManager grpcClientConnectionManager = new GrpcClientConnectionManager();
disconnectionRequestManager.addListener(grpcClientConnectionManager);
final ManagedDefaultEventLoopGroup localEventLoopGroup = new ManagedDefaultEventLoopGroup();
final RemoteDeprecationFilter remoteDeprecationFilter = new RemoteDeprecationFilter(dynamicConfigurationManager);
final MetricCollectingServerInterceptor metricCollectingServerInterceptor =
new MetricCollectingServerInterceptor(Metrics.globalRegistry);
final MetricServerInterceptor metricServerInterceptor = new MetricServerInterceptor(Metrics.globalRegistry, clientReleaseManager);
final ErrorMappingInterceptor errorMappingInterceptor = new ErrorMappingInterceptor();
final RequestAttributesInterceptor requestAttributesInterceptor =
@@ -846,8 +851,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new ExternalRequestFilter(config.getExternalRequestFilterConfiguration().permittedInternalRanges(),
config.getExternalRequestFilterConfiguration().grpcMethods()))
.intercept(validatingInterceptor)
// TODO: specialize metrics with user-agent platform
.intercept(metricCollectingServerInterceptor)
.intercept(metricServerInterceptor)
.intercept(errorMappingInterceptor)
.intercept(remoteDeprecationFilter)
.intercept(requestAttributesInterceptor)
@@ -867,9 +871,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
// depends on the user-agent context so it has to come first here!
// http://grpc.github.io/grpc-java/javadoc/io/grpc/ServerBuilder.html#intercept-io.grpc.ServerInterceptor-
serverBuilder
// TODO: specialize metrics with user-agent platform
.intercept(validatingInterceptor)
.intercept(metricCollectingServerInterceptor)
.intercept(metricServerInterceptor)
.intercept(errorMappingInterceptor)
.intercept(remoteDeprecationFilter)
.intercept(requestAttributesInterceptor)
@@ -984,7 +987,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
environment.jersey().register(new BufferingInterceptor());
environment.jersey().register(new RestDeprecationFilter(dynamicConfigurationManager, experimentEnrollmentManager));
environment.jersey().register(new VirtualExecutorServiceProvider("managed-async-virtual-thread-"));
environment.jersey().register(new VirtualExecutorServiceProvider(
"managed-async-virtual-thread",
config.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor()));
environment.jersey().register(new RateLimitByIpFilter(rateLimiters));
environment.jersey().register(new RequestStatisticsFilter(TrafficSource.HTTP));
environment.jersey().register(MultiRecipientMessageProvider.class);
@@ -995,19 +1000,21 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
///
WebSocketEnvironment<AuthenticatedDevice> webSocketEnvironment = new WebSocketEnvironment<>(environment,
config.getWebSocketConfiguration(), Duration.ofMillis(90000));
webSocketEnvironment.jersey().register(new VirtualExecutorServiceProvider("managed-async-websocket-virtual-thread-"));
webSocketEnvironment.jersey().register(new VirtualExecutorServiceProvider(
"managed-async-websocket-virtual-thread",
config.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor()));
webSocketEnvironment.setAuthenticator(new WebSocketAccountAuthenticator(accountAuthenticator));
webSocketEnvironment.setAuthenticatedWebSocketUpgradeFilter(new IdlePrimaryDeviceAuthenticatedWebSocketUpgradeFilter(
config.idlePrimaryDeviceReminderConfiguration().minIdleDuration(), Clock.systemUTC()));
webSocketEnvironment.setConnectListener(
new AuthenticatedConnectListener(accountsManager, receiptSender, messagesManager, messageMetrics, pushNotificationManager,
pushNotificationScheduler, webSocketConnectionEventManager, websocketScheduledExecutor,
pushNotificationScheduler, redisMessageAvailabilityManager, disconnectionRequestManager,
messageDeliveryScheduler, clientReleaseManager, messageDeliveryLoopMonitor, experimentEnrollmentManager));
webSocketEnvironment.jersey().register(new RateLimitByIpFilter(rateLimiters));
webSocketEnvironment.jersey().register(new RequestStatisticsFilter(TrafficSource.WEBSOCKET));
webSocketEnvironment.jersey().register(MultiRecipientMessageProvider.class);
webSocketEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET, clientReleaseManager));
webSocketEnvironment.jersey().register(new KeepAliveController(webSocketConnectionEventManager));
webSocketEnvironment.jersey().register(new KeepAliveController(redisMessageAvailabilityManager));
webSocketEnvironment.jersey().register(new TimestampResponseFilter());
final List<SpamFilter> spamFilters = ServiceLoader.load(SpamFilter.class)
@@ -1121,7 +1128,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new RemoteConfigController(remoteConfigsManager, config.getRemoteConfigConfiguration().globalConfig(), clock),
new SecureStorageController(storageCredentialsGenerator),
new SecureValueRecovery2Controller(svr2CredentialsGenerator, accountsManager),
new SecureValueRecoveryBController(svrbCredentialsGenerator),
new StickerController(rateLimiters, config.getCdnConfiguration().credentials().accessKeyId().value(),
config.getCdnConfiguration().credentials().secretAccessKey().value(), config.getCdnConfiguration().region(),
config.getCdnConfiguration().bucket()),
@@ -1150,7 +1156,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
webSocketEnvironment.getRequestLog(), Duration.ofMillis(60000));
provisioningEnvironment.setConnectListener(new ProvisioningConnectListener(provisioningManager, provisioningWebsocketTimeoutExecutor, Duration.ofSeconds(90)));
provisioningEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET, clientReleaseManager));
provisioningEnvironment.jersey().register(new KeepAliveController(webSocketConnectionEventManager));
provisioningEnvironment.jersey().register(new KeepAliveController(redisMessageAvailabilityManager));
provisioningEnvironment.jersey().register(new TimestampResponseFilter());
registerExceptionMappers(environment, webSocketEnvironment, provisioningEnvironment);
@@ -1179,9 +1185,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
environment.admin().addTask(new SetRequestLoggingEnabledTask());
// healthcheck, admin port
environment.healthChecks().register("cacheCluster", new RedisClusterHealthCheck(cacheCluster));
MetricsUtil.registerSystemResourceMetrics(environment);
}
@@ -6,8 +6,6 @@
package org.whispersystems.textsecuregcm.auth;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;
import io.netty.resolver.dns.DnsNameResolver;
import jakarta.ws.rs.core.Response;
import java.io.IOException;
@@ -26,7 +24,6 @@ import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.SystemMapper;
@@ -34,9 +31,6 @@ public class CloudflareTurnCredentialsManager {
private static final Logger logger = LoggerFactory.getLogger(CloudflareTurnCredentialsManager.class);
private static final String CREDENTIAL_FETCH_TIMER_NAME = MetricsUtil.name(CloudflareTurnCredentialsManager.class,
"credentialFetchLatency");
private final List<String> cloudflareTurnUrls;
private final List<String> cloudflareTurnUrlsWithIps;
private final String cloudflareTurnHostname;
@@ -119,20 +113,11 @@ public class CloudflareTurnCredentialsManager {
throw new IOException(e);
}
final Timer.Sample sample = Timer.start();
final HttpResponse<String> response;
try {
response = cloudflareTurnClient.sendAsync(getCredentialsRequest, HttpResponse.BodyHandlers.ofString()).join();
sample.stop(Timer.builder(CREDENTIAL_FETCH_TIMER_NAME)
.publishPercentileHistogram(true)
.tags("outcome", "success")
.register(Metrics.globalRegistry));
} catch (CompletionException e) {
logger.warn("failed to make http request to Cloudflare Turn: {}", e.getMessage());
sample.stop(Timer.builder(CREDENTIAL_FETCH_TIMER_NAME)
.publishPercentileHistogram(true)
.tags("outcome", "failure")
.register(Metrics.globalRegistry));
throw new IOException(ExceptionUtils.unwrap(e));
}
@@ -5,20 +5,15 @@
package org.whispersystems.textsecuregcm.auth;
import java.util.Collection;
import java.util.UUID;
/**
* A disconnection request listener receives and handles requests to close authenticated client network connections.
* A disconnection request listener receives and handles a request to close an authenticated network connection for a
* specific client.
*/
public interface DisconnectionRequestListener {
/**
* Handles a request to close authenticated network connections for one or more authenticated devices. Requests are
* Handles a request to close an authenticated network connection for a specific authenticated device. Requests are
* dispatched on dedicated threads, and implementations may safely block.
*
* @param accountIdentifier the account identifier for which to close authenticated connections
* @param deviceIds the device IDs within the identified account for which to close authenticated connections
*/
void handleDisconnectionRequest(UUID accountIdentifier, Collection<Byte> deviceIds);
void handleDisconnectionRequest();
}
@@ -5,25 +5,32 @@
package org.whispersystems.textsecuregcm.auth;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.InvalidProtocolBufferException;
import io.dropwizard.lifecycle.Managed;
import io.lettuce.core.pubsub.RedisPubSubAdapter;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import javax.annotation.Nullable;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.grpc.net.GrpcClientConnectionManager;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubConnection;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
@@ -36,11 +43,11 @@ import org.whispersystems.textsecuregcm.util.UUIDUtil;
public class DisconnectionRequestManager extends RedisPubSubAdapter<byte[], byte[]> implements Managed {
private final FaultTolerantRedisClient pubSubClient;
private final GrpcClientConnectionManager grpcClientConnectionManager;
private final Executor listenerEventExecutor;
// We expect just a couple listeners to get added at startup time and not at all at steady-state. There are several
// reasonable ways to model this, but a copy-on-write list gives us good flexibility with minimal performance cost.
private final List<DisconnectionRequestListener> listeners = new CopyOnWriteArrayList<>();
private final Map<AccountIdentifierAndDeviceId, List<DisconnectionRequestListener>> listeners =
new ConcurrentHashMap<>();
@Nullable
private FaultTolerantPubSubConnection<byte[], byte[]> pubSubConnection;
@@ -55,10 +62,14 @@ public class DisconnectionRequestManager extends RedisPubSubAdapter<byte[], byte
private static final Logger logger = LoggerFactory.getLogger(DisconnectionRequestManager.class);
private record AccountIdentifierAndDeviceId(UUID accountIdentifier, byte deviceId) {}
public DisconnectionRequestManager(final FaultTolerantRedisClient pubSubClient,
final GrpcClientConnectionManager grpcClientConnectionManager,
final Executor listenerEventExecutor) {
this.pubSubClient = pubSubClient;
this.grpcClientConnectionManager = grpcClientConnectionManager;
this.listenerEventExecutor = listenerEventExecutor;
}
@@ -84,24 +95,53 @@ public class DisconnectionRequestManager extends RedisPubSubAdapter<byte[], byte
}
/**
* Adds a listener for disconnection requests. Listeners will receive all broadcast disconnection requests regardless
* of whether the device in connection is connected to this server.
* Adds a listener for disconnection requests for a specific authenticated device.
*
* @param accountIdentifier TODO
* @param deviceId TODO
* @param listener the listener to register
*/
public void addListener(final DisconnectionRequestListener listener) {
listeners.add(listener);
public void addListener(final UUID accountIdentifier, final byte deviceId, final DisconnectionRequestListener listener) {
listeners.compute(new AccountIdentifierAndDeviceId(accountIdentifier, deviceId), (_, existingListeners) -> {
final List<DisconnectionRequestListener> listeners =
existingListeners == null ? new ArrayList<>() : existingListeners;
listeners.add(listener);
return listeners;
});
}
/**
* Removes a listener for disconnection requests for a specific authenticated device.
*
* @param accountIdentifier TODO
* @param deviceId TODO
* @param listener the listener to remove
*/
public void removeListener(final UUID accountIdentifier, final byte deviceId, final DisconnectionRequestListener listener) {
listeners.computeIfPresent(new AccountIdentifierAndDeviceId(accountIdentifier, deviceId), (_, existingListeners) -> {
existingListeners.remove(listener);
return existingListeners.isEmpty() ? null : existingListeners;
});
}
@VisibleForTesting
List<DisconnectionRequestListener> getListeners(final UUID accountIdentifier, final byte deviceId) {
return listeners.getOrDefault(new AccountIdentifierAndDeviceId(accountIdentifier, deviceId), Collections.emptyList());
}
/**
* Broadcasts a request to close all connections associated with the given account identifier to all servers.
*
* @param accountIdentifier the account for which to close connections
* @param account the account for which to close connections
*
* @return a future that completes when the request has been broadcast
*/
public CompletionStage<Void> requestDisconnection(final UUID accountIdentifier) {
return requestDisconnection(accountIdentifier, Collections.emptyList());
public CompletionStage<Void> requestDisconnection(final Account account) {
return requestDisconnection(account.getIdentifier(IdentityType.ACI),
account.getDevices().stream().map(Device::getId).toList());
}
/**
@@ -135,8 +175,7 @@ public class DisconnectionRequestManager extends RedisPubSubAdapter<byte[], byte
DISCONNECTION_REQUESTS_RECEIVED_COUNTER.increment();
accountIdentifier = UUIDUtil.fromByteString(disconnectionRequest.getAccountIdentifier());
deviceIds = disconnectionRequest.getDeviceIdsCount() > 0
? disconnectionRequest.getDeviceIdsList().stream()
deviceIds = disconnectionRequest.getDeviceIdsList().stream()
.map(deviceIdInt -> {
if (deviceIdInt == null || deviceIdInt < Device.PRIMARY_ID || deviceIdInt > Byte.MAX_VALUE) {
throw new IllegalArgumentException("Invalid device ID: " + deviceIdInt);
@@ -144,8 +183,7 @@ public class DisconnectionRequestManager extends RedisPubSubAdapter<byte[], byte
return deviceIdInt.byteValue();
})
.toList()
: Device.ALL_POSSIBLE_DEVICE_IDS;
.toList();
} catch (final InvalidProtocolBufferException e) {
logger.error("Could not parse disconnection request protobuf", e);
return;
@@ -154,12 +192,17 @@ public class DisconnectionRequestManager extends RedisPubSubAdapter<byte[], byte
return;
}
for (final DisconnectionRequestListener listener : listeners) {
try {
listenerEventExecutor.execute(() -> listener.handleDisconnectionRequest(accountIdentifier, deviceIds));
} catch (final Exception e) {
logger.warn("Listener failed to handle disconnection request", e);
}
}
deviceIds.forEach(deviceId -> {
grpcClientConnectionManager.closeConnection(new AuthenticatedDevice(accountIdentifier, deviceId));
listeners.getOrDefault(new AccountIdentifierAndDeviceId(accountIdentifier, deviceId), Collections.emptyList())
.forEach(listener -> listenerEventExecutor.execute(() -> {
try {
listener.handleDisconnectionRequest();
} catch (final Exception e) {
logger.warn("Listener failed to handle disconnection request", e);
}
}));
});
}
}
@@ -54,7 +54,6 @@ public class BackupAuthManager {
final static Duration MAX_REDEMPTION_DURATION = Duration.ofDays(7);
final static String BACKUP_EXPERIMENT_NAME = "backup";
final static String BACKUP_MEDIA_EXPERIMENT_NAME = "backupMedia";
private final ExperimentEnrollmentManager experimentEnrollmentManager;
@@ -99,9 +98,6 @@ public class BackupAuthManager {
final Device device,
final BackupAuthCredentialRequest messagesBackupCredentialRequest,
final BackupAuthCredentialRequest mediaBackupCredentialRequest) {
if (configuredBackupLevel(account).isEmpty()) {
throw Status.PERMISSION_DENIED.withDescription("Backups not allowed on account").asRuntimeException();
}
if (!device.isPrimary()) {
throw Status.PERMISSION_DENIED.withDescription("Only primary device can set backup-id").asRuntimeException();
}
@@ -172,10 +168,6 @@ public class BackupAuthManager {
}).thenCompose(updated -> getBackupAuthCredentials(updated, credentialType, redemptionStart, redemptionEnd));
}
// If this account isn't allowed some level of backup access via configuration, don't continue
final BackupLevel configuredBackupLevel = configuredBackupLevel(account).orElseThrow(() ->
Status.PERMISSION_DENIED.withDescription("Backups not allowed on account").asRuntimeException());
final Instant startOfDay = clock.instant().truncatedTo(ChronoUnit.DAYS);
if (redemptionStart.isAfter(redemptionEnd) ||
redemptionStart.isBefore(startOfDay) ||
@@ -191,6 +183,8 @@ public class BackupAuthManager {
.orElseThrow(() -> Status.NOT_FOUND.withDescription("No blinded backup-id has been added to the account").asRuntimeException());
try {
final BackupLevel defaultBackupLevel = configuredBackupLevel(account);
// create a credential for every day in the requested period
final BackupAuthCredentialRequest credentialReq = new BackupAuthCredentialRequest(committedBytes);
return CompletableFuture.completedFuture(Stream
@@ -198,7 +192,7 @@ public class BackupAuthManager {
.map(redemptionTime -> {
// Check if the account has a voucher that's good for a certain receiptLevel at redemption time, otherwise
// use the default receipt level
final BackupLevel backupLevel = storedBackupLevel(account, redemptionTime).orElse(configuredBackupLevel);
final BackupLevel backupLevel = storedBackupLevel(account, redemptionTime).orElse(defaultBackupLevel);
return new Credential(
credentialReq.issueCredential(redemptionTime, backupLevel, credentialType, serverSecretParams),
redemptionTime);
@@ -328,20 +322,12 @@ public class BackupAuthManager {
* Get the backup receipt level that should be used by default for this account determined via configuration.
*
* @param account the account to check
* @return If present, the default receipt level that should be used for the account if the account does not have a
* BackupVoucher. Empty if the account should never have backup access
* @return The default receipt level that should be used for the account if the account does not have a
* BackupVoucher.
*/
private Optional<BackupLevel> configuredBackupLevel(final Account account) {
if (inExperiment(BACKUP_MEDIA_EXPERIMENT_NAME, account)) {
return Optional.of(BackupLevel.PAID);
}
if (inExperiment(BACKUP_EXPERIMENT_NAME, account)) {
return Optional.of(BackupLevel.FREE);
}
return Optional.empty();
}
private boolean inExperiment(final String experimentName, final Account account) {
return this.experimentEnrollmentManager.isEnrolled(account.getUuid(), experimentName);
private BackupLevel configuredBackupLevel(final Account account) {
return this.experimentEnrollmentManager.isEnrolled(account.getUuid(), BACKUP_MEDIA_EXPERIMENT_NAME)
? BackupLevel.PAID
: BackupLevel.FREE;
}
}
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.backup;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.util.DataSize;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
@@ -19,6 +18,7 @@ import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -38,9 +38,12 @@ import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient;
import org.whispersystems.textsecuregcm.util.AsyncTimerUtil;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.Pair;
@@ -94,9 +97,10 @@ public class BackupManager {
private final Cdn3BackupCredentialGenerator cdn3BackupCredentialGenerator;
private final RemoteStorageManager remoteStorageManager;
private final SecureRandom secureRandom = new SecureRandom();
private final ExternalServiceCredentialsGenerator secureValueRecoveryBCredentialsGenerator;
private final SecureValueRecoveryClient secureValueRecoveryBClient;
private final Clock clock;
public BackupManager(
final BackupsDb backupsDb,
final GenericServerSecretParams serverSecretParams,
@@ -104,6 +108,8 @@ public class BackupManager {
final TusAttachmentGenerator tusAttachmentGenerator,
final Cdn3BackupCredentialGenerator cdn3BackupCredentialGenerator,
final RemoteStorageManager remoteStorageManager,
final ExternalServiceCredentialsGenerator secureValueRecoveryBCredentialsGenerator,
final SecureValueRecoveryClient secureValueRecoveryBClient,
final Clock clock) {
this.backupsDb = backupsDb;
this.serverSecretParams = serverSecretParams;
@@ -111,7 +117,9 @@ public class BackupManager {
this.tusAttachmentGenerator = tusAttachmentGenerator;
this.cdn3BackupCredentialGenerator = cdn3BackupCredentialGenerator;
this.remoteStorageManager = remoteStorageManager;
this.secureValueRecoveryBClient = secureValueRecoveryBClient;
this.clock = clock;
this.secureValueRecoveryBCredentialsGenerator = secureValueRecoveryBCredentialsGenerator;
}
@@ -387,6 +395,26 @@ public class BackupManager {
return cdn3BackupCredentialGenerator.readHeaders(backupUser.backupDir());
}
/**
* Generate credentials that can be used with SVRB
*
* @param backupUser an already ZK authenticated backup user
* @return the credential that may be used with SVRB
*/
public ExternalServiceCredentials generateSvrbAuth(final AuthenticatedBackupUser backupUser) {
checkBackupLevel(backupUser, BackupLevel.FREE);
// Clients may only use SVRB with their messages backup-id
checkBackupCredentialType(backupUser, BackupCredentialType.MESSAGES);
return secureValueRecoveryBCredentialsGenerator.generateFor(svrbIdentifier(backupUser));
}
private static String svrbIdentifier(final AuthenticatedBackupUser backupUser) {
return svrbIdentifier(BackupsDb.hashedBackupId(backupUser.backupId()));
}
private static String svrbIdentifier(final byte[] hashedBackupId) {
return HexFormat.of().formatHex(hashedBackupId);
}
/**
* List of media stored for a particular backup id
@@ -427,13 +455,19 @@ public class BackupManager {
public CompletableFuture<Void> deleteEntireBackup(final AuthenticatedBackupUser backupUser) {
checkBackupLevel(backupUser, BackupLevel.FREE);
return backupsDb
// Clients only include SVRB data with their messages backup-id
final CompletableFuture<Void> svrbRemoval = switch(backupUser.credentialType()) {
case BackupCredentialType.MESSAGES -> secureValueRecoveryBClient.removeData(svrbIdentifier(backupUser));
case BackupCredentialType.MEDIA -> CompletableFuture.completedFuture(null);
};
return svrbRemoval.thenCompose(_ -> backupsDb
// Try to swap out the backupDir for the user
.scheduleBackupDeletion(backupUser)
// If there was already a pending swap, try to delete the cdn objects directly
.exceptionallyCompose(ExceptionUtils.exceptionallyHandler(BackupsDb.PendingDeletionException.class, e ->
AsyncTimerUtil.record(SYNCHRONOUS_DELETE_TIMER, () ->
deletePrefix(backupUser.backupDir(), DELETION_CONCURRENCY))));
deletePrefix(backupUser.backupDir(), DELETION_CONCURRENCY)))));
}
@@ -617,12 +651,17 @@ public class BackupManager {
* @return A stage that completes when the deletion operation is finished
*/
public CompletableFuture<Void> expireBackup(final ExpiredBackup expiredBackup) {
return backupsDb.startExpiration(expiredBackup)
// Clients only include SVRB data with their messages backup-id
final CompletableFuture<Void> svrbRemoval = switch(expiredBackup.expirationType()) {
case ALL -> secureValueRecoveryBClient.removeData(svrbIdentifier(expiredBackup.hashedBackupId()));
case MEDIA, GARBAGE_COLLECTION -> CompletableFuture.completedFuture(null);
};
return svrbRemoval.thenCompose(_ -> backupsDb.startExpiration(expiredBackup)
// the deletion operation is effectively single threaded -- it's expected that the caller can increase
// concurrency by deleting more backups at once, rather than increasing concurrency deleting an individual
// backup
.thenCompose(ignored -> deletePrefix(expiredBackup.prefixToDelete(), 1))
.thenCompose(ignored -> backupsDb.finishExpiration(expiredBackup));
.thenCompose(ignored -> backupsDb.finishExpiration(expiredBackup)));
}
/**
@@ -0,0 +1,33 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.backup;
import com.google.common.annotations.VisibleForTesting;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
import org.whispersystems.textsecuregcm.configuration.SecureValueRecoveryConfiguration;
import java.time.Clock;
public class SecureValueRecoveryBCredentialsGeneratorFactory {
private SecureValueRecoveryBCredentialsGeneratorFactory() {}
@VisibleForTesting
static ExternalServiceCredentialsGenerator svrbCredentialsGenerator(
final SecureValueRecoveryConfiguration cfg,
final Clock clock) {
return ExternalServiceCredentialsGenerator
.builder(cfg.userAuthenticationTokenSharedSecret())
.withUserDerivationKey(cfg.userIdTokenSharedSecret().value())
.prependUsername(false)
.withDerivedUsernameTruncateLength(16)
.withClock(clock)
.build();
}
public static ExternalServiceCredentialsGenerator svrbCredentialsGenerator(final SecureValueRecoveryConfiguration cfg) {
return svrbCredentialsGenerator(cfg, Clock.systemUTC());
}
}
@@ -8,8 +8,11 @@ package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import javax.annotation.Nullable;
import java.net.URI;
public record CdnConfiguration(@NotNull @Valid StaticAwsCredentialsFactory credentials,
@NotBlank String bucket,
@NotBlank String region) {
@NotBlank String region,
@Nullable URI endpointOverride) {
}
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.micrometer.registry.otlp.HistogramFlavor;
import io.micrometer.registry.otlp.OtlpConfig;
import java.time.Duration;
import java.util.Map;
@@ -15,6 +16,8 @@ import java.util.Map;
public record OpenTelemetryConfiguration(
@JsonProperty boolean enabled,
@JsonProperty Duration shutdownWaitDuration,
@JsonProperty int maxBucketCount,
@JsonProperty Map<String, Integer> maxBucketsPerMeter,
@JsonAnyGetter @JsonAnySetter Map<String, String> otlpConfig
) implements OtlpConfig {
@@ -23,6 +26,19 @@ public record OpenTelemetryConfiguration(
return otlpConfig.get(key.split("\\.", 2)[1]);
}
@Override
public Map<String, Integer> maxBucketsPerMeter() {
if (maxBucketsPerMeter == null) {
return Map.of();
}
return maxBucketsPerMeter;
}
@Override
public HistogramFlavor histogramFlavor() {
return HistogramFlavor.BASE2_EXPONENTIAL_BUCKET_HISTOGRAM;
}
public Duration shutdownWaitDuration() {
if (shutdownWaitDuration == null) {
return step().plus(step().dividedBy(2));
@@ -5,11 +5,12 @@
package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import javax.annotation.Nullable;
import java.net.URI;
public record PagedSingleUseKEMPreKeyStoreConfiguration(
@NotBlank String bucket,
@NotBlank String region) {
@NotBlank String region,
@Nullable URI endpointOverride) {
}
@@ -6,4 +6,20 @@ package org.whispersystems.textsecuregcm.configuration;
import java.time.Duration;
public record VirtualThreadConfiguration(Duration pinEventThreshold) {}
public record VirtualThreadConfiguration(
Duration pinEventThreshold,
Integer maxConcurrentThreadsPerExecutor) {
public VirtualThreadConfiguration() {
this(null, null);
}
public VirtualThreadConfiguration {
if (maxConcurrentThreadsPerExecutor == null) {
maxConcurrentThreadsPerExecutor = 1_000_000;
}
if (pinEventThreshold == null) {
pinEventThreshold = Duration.ofMillis(1);
}
}
}
@@ -64,6 +64,7 @@ import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialRequest;
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
import org.whispersystems.textsecuregcm.backup.BackupManager;
import org.whispersystems.textsecuregcm.backup.CopyParameters;
@@ -389,6 +390,35 @@ public class ArchiveController {
.thenApply(ReadAuthResponse::new);
}
@GET
@Path("/auth/svrb")
@Produces(MediaType.APPLICATION_JSON)
@Operation(
summary = "Generate credentials for SVRB",
description = """
Generate SVRB service credentials. Generated credentials have an expiration time of 1 day (subject to change)
""")
@ApiResponse(responseCode = "200", description = "`JSON` with generated credentials.", useReturnTypeSchema = true)
@ApiResponseZkAuth
public CompletionStage<ExternalServiceCredentials> svrbAuth(
@Auth final Optional<AuthenticatedDevice> account,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@Parameter(description = BackupAuthCredentialPresentationHeader.DESCRIPTION, schema = @Schema(implementation = String.class))
@NotNull
@HeaderParam(X_SIGNAL_ZK_AUTH) final ArchiveController.BackupAuthCredentialPresentationHeader presentation,
@Parameter(description = BackupAuthCredentialPresentationSignature.DESCRIPTION, schema = @Schema(implementation = String.class))
@NotNull
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature) {
if (account.isPresent()) {
throw new BadRequestException("must not use authenticated connection for anonymous operations");
}
return backupManager
.authenticateBackupUser(presentation.presentation, signature.signature, userAgent)
.thenApply(backupManager::generateSvrbAuth);
}
public record BackupInfoResponse(
@Schema(description = "The CDN type where the message backup is stored. Media may be stored elsewhere.")
int cdn,
@@ -115,6 +115,8 @@ public class DeviceController {
private static final String WAIT_FOR_TRANSFER_ARCHIVE_TIMER_NAME =
MetricsUtil.name(DeviceController.class, "waitForTransferArchiveDuration");
private static final String RECORD_TRANSFER_ARCHIVE_UPLOADED_COUNTER_NAME = MetricsUtil.name(DeviceController.class, "recordTransferArchiveUploaded");
private static final String HAS_REGISTRATION_ID_TAG_NAME = "hasRegistrationId";
@VisibleForTesting
static final int MIN_TOKEN_IDENTIFIER_LENGTH = 32;
@@ -446,6 +448,8 @@ public class DeviceController {
private static boolean isCapabilityDowngrade(final Account account, final Set<DeviceCapability> capabilities) {
final Set<DeviceCapability> requiredCapabilities = Arrays.stream(DeviceCapability.values())
// `ALWAYS_CAPABLE` capabilities are always assumed to be present, so we don't require callers to specify them
.filter(capability -> capability.getAccountCapabilityMode() != DeviceCapability.AccountCapabilityMode.ALWAYS_CAPABLE)
.filter(DeviceCapability::preventDowngrade)
.filter(account::hasCapability)
.collect(Collectors.toSet());
@@ -533,8 +537,14 @@ public class DeviceController {
@ApiResponse(responseCode = "422", description = "The request object could not be parsed or was otherwise invalid")
@ApiResponse(responseCode = "429", description = "Rate-limited; try again after the prescribed delay")
public CompletionStage<Void> recordTransferArchiveUploaded(@Auth final AuthenticatedDevice authenticatedDevice,
@NotNull @Valid final TransferArchiveUploadedRequest transferArchiveUploadedRequest) {
@NotNull @Valid final TransferArchiveUploadedRequest transferArchiveUploadedRequest,
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable String userAgent) {
Metrics.counter(RECORD_TRANSFER_ARCHIVE_UPLOADED_COUNTER_NAME, Tags.of(
UserAgentTagUtil.getPlatformTag(userAgent),
io.micrometer.core.instrument.Tag.of(
HAS_REGISTRATION_ID_TAG_NAME,
String.valueOf(transferArchiveUploadedRequest.destinationDeviceRegistrationId().isPresent()))
)).increment();
return rateLimiters.getUploadTransferArchiveLimiter()
.validateAsync(authenticatedDevice.accountIdentifier())
.thenCompose(ignored -> accounts.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
@@ -544,7 +554,8 @@ public class DeviceController {
return accounts.recordTransferArchiveUpload(account,
transferArchiveUploadedRequest.destinationDeviceId(),
Instant.ofEpochMilli(transferArchiveUploadedRequest.destinationDeviceCreated()),
transferArchiveUploadedRequest.destinationDeviceCreated().map(Instant::ofEpochMilli),
transferArchiveUploadedRequest.destinationDeviceRegistrationId(),
transferArchiveUploadedRequest.transferArchive());
});
}
@@ -22,7 +22,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
import org.whispersystems.websocket.session.WebSocketSession;
import org.whispersystems.websocket.session.WebSocketSessionContext;
@@ -33,14 +33,14 @@ public class KeepAliveController {
private final Logger logger = LoggerFactory.getLogger(KeepAliveController.class);
private final WebSocketConnectionEventManager webSocketConnectionEventManager;
private final RedisMessageAvailabilityManager redisMessageAvailabilityManager;
private static final String CLOSED_CONNECTION_AGE_DISTRIBUTION_NAME = name(KeepAliveController.class,
"closedConnectionAge");
public KeepAliveController(final WebSocketConnectionEventManager webSocketConnectionEventManager) {
this.webSocketConnectionEventManager = webSocketConnectionEventManager;
public KeepAliveController(final RedisMessageAvailabilityManager redisMessageAvailabilityManager) {
this.redisMessageAvailabilityManager = redisMessageAvailabilityManager;
}
@GET
@@ -48,7 +48,7 @@ public class KeepAliveController {
@WebSocketSession WebSocketSessionContext context) {
maybeAuth.ifPresent(auth -> {
if (!webSocketConnectionEventManager.isLocallyPresent(auth.accountIdentifier(), auth.deviceId())) {
if (!redisMessageAvailabilityManager.isLocallyPresent(auth.accountIdentifier(), auth.deviceId())) {
final Duration age = Duration.between(context.getClient().getCreated(), Instant.now());
@@ -6,7 +6,6 @@ package org.whispersystems.textsecuregcm.controllers;
import com.google.common.net.HttpHeaders;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
@@ -34,7 +33,6 @@ import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@@ -57,7 +55,6 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.GroupSendTokenHeader;
import org.whispersystems.textsecuregcm.auth.OptionalAccess;
import org.whispersystems.textsecuregcm.entities.CheckKeysRequest;
import org.whispersystems.textsecuregcm.entities.ECPreKey;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.entities.PreKeyCount;
@@ -92,10 +89,7 @@ public class KeysController {
private final ServerSecretParams serverSecretParams;
private final Clock clock;
private static final String GET_KEYS_COUNTER_NAME = MetricsUtil.name(KeysController.class, "getKeys");
private static final String STORE_KEYS_COUNTER_NAME = MetricsUtil.name(KeysController.class, "storeKeys");
private static final String STORE_KEY_BUNDLE_SIZE_DISTRIBUTION_NAME =
MetricsUtil.name(KeysController.class, "storeKeyBundleSize");
private static final String PRIMARY_DEVICE_TAG_NAME = "isPrimary";
private static final String IDENTITY_TYPE_TAG_NAME = "identityType";
private static final String KEY_TYPE_TAG_NAME = "keyType";
@@ -176,12 +170,6 @@ public class KeysController {
Metrics.counter(STORE_KEYS_COUNTER_NAME, tags).increment();
DistributionSummary.builder(STORE_KEY_BUNDLE_SIZE_DISTRIBUTION_NAME)
.tags(tags)
.publishPercentileHistogram()
.register(Metrics.globalRegistry)
.record(setKeysRequest.preKeys().size());
storeFutures.add(keysManager.storeEcOneTimePreKeys(identifier, device.getId(), setKeysRequest.preKeys()));
}
@@ -197,12 +185,6 @@ public class KeysController {
final Tags tags = Tags.of(platformTag, primaryDeviceTag, identityTypeTag, Tag.of(KEY_TYPE_TAG_NAME, "kyber"));
Metrics.counter(STORE_KEYS_COUNTER_NAME, tags).increment();
DistributionSummary.builder(STORE_KEY_BUNDLE_SIZE_DISTRIBUTION_NAME)
.tags(tags)
.publishPercentileHistogram()
.register(Metrics.globalRegistry)
.record(setKeysRequest.pqPreKeys().size());
storeFutures.add(keysManager.storeKemOneTimePreKeys(identifier, device.getId(), setKeysRequest.pqPreKeys()));
}
@@ -388,58 +370,20 @@ public class KeysController {
final Account target = maybeTarget.orElseThrow(NotFoundException::new);
if (account.isPresent()) {
rateLimiters.getPreKeysLimiter().validate(
account.get().getUuid() + "." + maybeAuthenticatedDevice.get().deviceId() + "__" + targetIdentifier.uuid()
+ "." + deviceId);
rateLimiters.getPreKeysLimiter().validate(getPreKeysLimiterKey(account.get(), maybeAuthenticatedDevice.get(),
targetIdentifier, target, deviceId));
}
final List<Device> devices = parseDeviceId(deviceId, target);
final List<PreKeyResponseItem> responseItems = Flux.fromIterable(devices)
.flatMap(device -> Mono.zip(
Mono.just(device),
Mono.fromFuture(keysManager.takeEC(targetIdentifier.uuid(), device.getId())),
Mono.fromFuture(keysManager.getEcSignedPreKey(targetIdentifier.uuid(), device.getId())),
Mono.fromFuture(keysManager.takePQ(targetIdentifier.uuid(), device.getId()))))
.flatMap(deviceAndPreKeys -> {
final Device device = deviceAndPreKeys.getT1();
final KEMSignedPreKey pqPreKey = deviceAndPreKeys.getT4().orElse(null);
final ECPreKey unsignedEcPreKey = deviceAndPreKeys.getT2().orElse(null);
final ECSignedPreKey signedEcPreKey = deviceAndPreKeys.getT3().orElse(null);
final int registrationId = device.getRegistrationId(targetIdentifier.identityType());
Metrics.counter(GET_KEYS_COUNTER_NAME, Tags.of(
UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(IDENTITY_TYPE_TAG_NAME, targetIdentifier.identityType().name()),
Tag.of("oneTimeEcKeyAvailable", String.valueOf(unsignedEcPreKey != null)),
Tag.of("signedEcKeyAvailable", String.valueOf(signedEcPreKey != null)),
Tag.of("pqKeyAvailable", String.valueOf(pqPreKey != null))))
.increment();
if (pqPreKey == null) {
// The PQ prekey should never be null. This should only happen if the account or device has been
// removed.
return Mono.fromCompletionStage(() -> accounts.getByServiceIdentifierAsync(targetIdentifier))
.flatMap(maybeAccount -> maybeAccount
.flatMap(rereadAccount -> rereadAccount.getDevice(device.getId()))
.filter(rereadDevice ->
registrationId == rereadDevice.getRegistrationId(targetIdentifier.identityType()))
.map(rereadDevice -> {
// The account and device still exist, and the device we originally read matches the current
// registrationId, so the lastResort key should have existed
log.error(
"Target {}, Account {}, DeviceId {}, RegistrationId {} was missing a last resort prekey",
targetIdentifier,
target.getIdentifier(IdentityType.ACI),
rereadDevice.getId(),
rereadDevice.getRegistrationId(targetIdentifier.identityType()));
return Mono.<PreKeyResponseItem>error(new IOException("Device missing last resort prekey"));
})
.orElse(Mono.empty()));
}
return Mono.just(new PreKeyResponseItem(
device.getId(), registrationId, signedEcPreKey, unsignedEcPreKey, pqPreKey));
})
final List<PreKeyResponseItem> responseItems = Flux.fromIterable(devices).flatMap(device -> Mono
.fromCompletionStage(keysManager.takeDevicePreKeys(device.getId(), targetIdentifier, userAgent))
.flatMap(Mono::justOrEmpty)
.map(devicePreKeys -> new PreKeyResponseItem(
device.getId(), device.getRegistrationId(targetIdentifier.identityType()),
devicePreKeys.ecSignedPreKey(),
devicePreKeys.ecPreKey().orElse(null),
devicePreKeys.kemSignedPreKey())))
.collectList()
.block();
@@ -463,4 +407,24 @@ public class KeysController {
throw new WebApplicationException(Response.status(422).build());
}
}
private String getPreKeysLimiterKey(
final Account account,
final AuthenticatedDevice authenticatedDevice,
final ServiceIdentifier targetIdentifier,
final Account targetAccount,
final String targetDeviceId) {
final String targetRegistrationId = targetDeviceId.equals("*")
? "*"
: String.valueOf(
parseDeviceId(targetDeviceId, targetAccount).getFirst().getRegistrationId(targetIdentifier.identityType()));
return String.format("%s.%s__%s.%s.%s",
account.getUuid(),
authenticatedDevice.deviceId(),
targetIdentifier.uuid(),
targetDeviceId,
targetRegistrationId
);
}
}
@@ -110,7 +110,6 @@ import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.Util;
import org.whispersystems.textsecuregcm.websocket.WebSocketConnection;
import org.whispersystems.websocket.WebsocketHeaders;
import reactor.core.scheduler.Scheduler;
@@ -161,6 +160,9 @@ public class MessageController {
.register(Metrics.globalRegistry);
}
private static final String INCORRECT_SYNC_MESSAGE_REGISTRATION_IDS_COUNTER_NAME =
MetricsUtil.name(MessageController.class, "incorrectSyncMessageRegistrationIds");
// The Signal desktop client (really, JavaScript in general) can handle message timestamps at most 100,000,000 days
// past the epoch; please see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date
// for additional details.
@@ -452,6 +454,12 @@ public class MessageController {
userAgent);
} catch (final MismatchedDevicesException e) {
if (!e.getMismatchedDevices().staleDeviceIds().isEmpty()) {
if (messageType == MessageType.SYNC) {
Metrics.counter(INCORRECT_SYNC_MESSAGE_REGISTRATION_IDS_COUNTER_NAME,
Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)))
.increment();
}
throw new WebApplicationException(Response.status(410)
.type(MediaType.APPLICATION_JSON)
.entity(new StaleDevicesResponse(e.getMismatchedDevices().staleDeviceIds()))
@@ -841,15 +849,8 @@ public class MessageController {
final Device device = account.getDevice(auth.deviceId())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
return messagesManager.delete(
auth.accountIdentifier(),
device,
uuid,
null)
return messagesManager.delete(auth.accountIdentifier(), device, uuid, null)
.thenAccept(maybeRemovedMessage -> maybeRemovedMessage.ifPresent(removedMessage -> {
WebSocketConnection.recordMessageDeliveryDuration(removedMessage.serverTimestamp(), device);
if (removedMessage.sourceServiceId().isPresent()
&& removedMessage.envelopeType() != Type.SERVER_DELIVERY_RECEIPT) {
if (removedMessage.sourceServiceId().get() instanceof AciServiceIdentifier aciServiceIdentifier) {
@@ -1,63 +0,0 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.controllers;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.auth.Auth;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import java.time.Clock;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
import org.whispersystems.textsecuregcm.configuration.SecureValueRecoveryConfiguration;
@Path("/v1/svrb")
@Tag(name = "Secure Value Recovery B")
public class SecureValueRecoveryBController {
public static ExternalServiceCredentialsGenerator credentialsGenerator(final SecureValueRecoveryConfiguration cfg) {
return credentialsGenerator(cfg, Clock.systemUTC());
}
@VisibleForTesting
public static ExternalServiceCredentialsGenerator credentialsGenerator(final SecureValueRecoveryConfiguration cfg,
final Clock clock) {
return ExternalServiceCredentialsGenerator
.builder(cfg.userAuthenticationTokenSharedSecret())
.withUserDerivationKey(cfg.userIdTokenSharedSecret().value())
.prependUsername(false)
.withDerivedUsernameTruncateLength(16)
.withClock(clock)
.build();
}
private final ExternalServiceCredentialsGenerator svrbCredentialGenerator;
public SecureValueRecoveryBController(final ExternalServiceCredentialsGenerator svrbCredentialGenerator) {
this.svrbCredentialGenerator = svrbCredentialGenerator;
}
@GET
@Path("/auth")
@Produces(MediaType.APPLICATION_JSON)
@Operation(
summary = "Generate credentials for SVRB",
description = """
Generate SVRB service credentials. Generated credentials have an expiration time of 1 day (subject to change)
"""
)
@ApiResponse(responseCode = "200", description = "`JSON` with generated credentials.", useReturnTypeSchema = true)
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
public ExternalServiceCredentials getAuth(@Auth final AuthenticatedDevice auth) {
return svrbCredentialGenerator.generateFor(auth.accountIdentifier().toString());
}
}
@@ -19,7 +19,7 @@ public class PreKeyResponseItem {
private int registrationId;
@JsonProperty
@Schema(description="the signed elliptic-curve prekey for the device, if one has been set")
@Schema(description="the signed elliptic-curve prekey for the device")
private ECSignedPreKey signedPreKey;
@JsonProperty
@@ -28,7 +28,7 @@ public class PreKeyResponseItem {
@JsonProperty
@Schema(description="a signed post-quantum prekey for the device " +
"(a one-time prekey if any remain, otherwise the last-resort prekey if one has been set)")
"(a one-time prekey if any remain, otherwise the last-resort prekey)")
private KEMSignedPreKey pqPreKey;
public PreKeyResponseItem() {}
@@ -7,21 +7,30 @@ package org.whispersystems.textsecuregcm.entities;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import org.whispersystems.textsecuregcm.storage.Device;
import java.util.Optional;
public record TransferArchiveUploadedRequest(
@Min(1)
@Max(Device.MAXIMUM_DEVICE_ID)
@Schema(description = "The ID of the device for which the transfer archive has been prepared")
byte destinationDeviceId,
@Positive
@Schema(description = "The timestamp, in milliseconds since the epoch, at which the destination device was created")
long destinationDeviceCreated,
@Schema(description = """
The timestamp, in milliseconds since the epoch, at which the destination device was created.
Deprecated in favor of `destinationDeviceRegistrationId`.
""", deprecated = true)
@Deprecated
Optional<@Positive Long> destinationDeviceCreated,
@Schema(description = "The registration ID of the destination device")
Optional<@Min(0) @Max(Device.MAX_REGISTRATION_ID) Integer> destinationDeviceRegistrationId,
@NotNull
@Valid
@@ -29,4 +38,10 @@ public record TransferArchiveUploadedRequest(
The location of the transfer archive if the archive was successfully uploaded, otherwise a error indicating that
the upload has failed and the destination device should stop waiting
""", oneOf = {RemoteAttachment.class, RemoteAttachmentError.class})
TransferArchiveResult transferArchive) {}
TransferArchiveResult transferArchive) {
@AssertTrue
@Schema(hidden = true)
public boolean isExactlyOneDisambiguatorProvided() {
return destinationDeviceCreated.isPresent() ^ destinationDeviceRegistrationId.isPresent();
}
}
@@ -21,6 +21,8 @@ import org.signal.chat.backup.GetBackupInfoRequest;
import org.signal.chat.backup.GetBackupInfoResponse;
import org.signal.chat.backup.GetCdnCredentialsRequest;
import org.signal.chat.backup.GetCdnCredentialsResponse;
import org.signal.chat.backup.GetSvrBCredentialsRequest;
import org.signal.chat.backup.GetSvrBCredentialsResponse;
import org.signal.chat.backup.GetUploadFormRequest;
import org.signal.chat.backup.GetUploadFormResponse;
import org.signal.chat.backup.ListMediaRequest;
@@ -64,6 +66,16 @@ public class BackupsAnonymousGrpcService extends ReactorBackupsAnonymousGrpc.Bac
.map(credentials -> GetCdnCredentialsResponse.newBuilder().putAllHeaders(credentials).build());
}
@Override
public Mono<GetSvrBCredentialsResponse> getSvrBCredentials(final GetSvrBCredentialsRequest request) {
return authenticateBackupUserMono(request.getSignedPresentation())
.map(backupManager::generateSvrbAuth)
.map(credentials -> GetSvrBCredentialsResponse.newBuilder()
.setUsername(credentials.username())
.setPassword(credentials.password())
.build());
}
@Override
public Mono<GetBackupInfoResponse> getBackupInfo(final GetBackupInfoRequest request) {
return Mono.fromFuture(() ->
@@ -47,16 +47,6 @@ enum ExternalServiceDefinitions {
.withClock(clock)
.build();
}),
SVRB(ExternalServiceType.EXTERNAL_SERVICE_TYPE_SVRB, (chatConfig, clock) -> {
final SecureValueRecoveryConfiguration cfg = chatConfig.getSvrbConfiguration();
return ExternalServiceCredentialsGenerator
.builder(cfg.userAuthenticationTokenSharedSecret())
.withUserDerivationKey(cfg.userIdTokenSharedSecret().value())
.prependUsername(false)
.withDerivedUsernameTruncateLength(16)
.withClock(clock)
.build();
}),
STORAGE(ExternalServiceType.EXTERNAL_SERVICE_TYPE_STORAGE, (chatConfig, clock) -> {
final PaymentsServiceConfiguration cfg = chatConfig.getPaymentsServiceConfiguration();
return ExternalServiceCredentialsGenerator
@@ -56,7 +56,7 @@ public class KeysAnonymousGrpcService extends ReactorKeysAnonymousGrpc.KeysAnony
groupSendTokenUtil.checkGroupSendToken(request.getGroupSendToken(), serviceIdentifier);
yield lookUpAccount(serviceIdentifier, Status.NOT_FOUND)
.flatMap(targetAccount -> KeysGrpcHelper.getPreKeys(targetAccount, serviceIdentifier.identityType(), deviceId, keysManager));
.flatMap(targetAccount -> KeysGrpcHelper.getPreKeys(targetAccount, serviceIdentifier, deviceId, keysManager));
} catch (final StatusException e) {
yield Mono.error(e);
}
@@ -66,7 +66,7 @@ public class KeysAnonymousGrpcService extends ReactorKeysAnonymousGrpc.KeysAnony
lookUpAccount(serviceIdentifier, Status.UNAUTHENTICATED)
.flatMap(targetAccount ->
UnidentifiedAccessUtil.checkUnidentifiedAccess(targetAccount, request.getUnidentifiedAccessKey().toByteArray())
? KeysGrpcHelper.getPreKeys(targetAccount, serviceIdentifier.identityType(), deviceId, keysManager)
? KeysGrpcHelper.getPreKeys(targetAccount, serviceIdentifier, deviceId, keysManager)
: Mono.error(Status.UNAUTHENTICATED.asException()));
default -> Mono.error(Status.INVALID_ARGUMENT.asException());
@@ -11,10 +11,7 @@ import org.signal.chat.common.EcPreKey;
import org.signal.chat.common.EcSignedPreKey;
import org.signal.chat.common.KemSignedPreKey;
import org.signal.chat.keys.GetPreKeysResponse;
import org.whispersystems.textsecuregcm.entities.ECPreKey;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.KeysManager;
@@ -28,7 +25,7 @@ class KeysGrpcHelper {
static final byte ALL_DEVICES = 0;
static Mono<GetPreKeysResponse> getPreKeys(final Account targetAccount,
final IdentityType identityType,
final ServiceIdentifier targetServiceIdentifier,
final byte targetDeviceId,
final KeysManager keysManager) {
@@ -36,42 +33,37 @@ class KeysGrpcHelper {
? Flux.fromIterable(targetAccount.getDevices())
: Flux.from(Mono.justOrEmpty(targetAccount.getDevice(targetDeviceId)));
final String userAgent = RequestAttributesUtil.getUserAgent().orElse(null);
return devices
.switchIfEmpty(Mono.error(Status.NOT_FOUND.asException()))
.flatMap(device -> Flux.merge(
Mono.fromFuture(() -> keysManager.takeEC(targetAccount.getIdentifier(identityType), device.getId())),
Mono.fromFuture(() -> keysManager.getEcSignedPreKey(targetAccount.getIdentifier(identityType), device.getId())),
Mono.fromFuture(() -> keysManager.takePQ(targetAccount.getIdentifier(identityType), device.getId())))
.flatMap(device -> Mono
.fromFuture(keysManager.takeDevicePreKeys(device.getId(), targetServiceIdentifier, userAgent))
.flatMap(Mono::justOrEmpty)
.reduce(GetPreKeysResponse.PreKeyBundle.newBuilder(), (builder, preKey) -> {
if (preKey instanceof ECPreKey ecPreKey) {
builder.setEcOneTimePreKey(EcPreKey.newBuilder()
.map(devicePreKeys -> {
final GetPreKeysResponse.PreKeyBundle.Builder builder = GetPreKeysResponse.PreKeyBundle.newBuilder()
.setEcSignedPreKey(EcSignedPreKey.newBuilder()
.setKeyId(devicePreKeys.ecSignedPreKey().keyId())
.setPublicKey(ByteString.copyFrom(devicePreKeys.ecSignedPreKey().serializedPublicKey()))
.setSignature(ByteString.copyFrom(devicePreKeys.ecSignedPreKey().signature()))
.build())
.setKemOneTimePreKey(KemSignedPreKey.newBuilder()
.setKeyId(devicePreKeys.kemSignedPreKey().keyId())
.setPublicKey(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().serializedPublicKey()))
.setSignature(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().signature()))
.build());
devicePreKeys.ecPreKey().ifPresent(ecPreKey -> builder.setEcOneTimePreKey(EcPreKey.newBuilder()
.setKeyId(ecPreKey.keyId())
.setPublicKey(ByteString.copyFrom(ecPreKey.serializedPublicKey()))
.build());
} else if (preKey instanceof ECSignedPreKey ecSignedPreKey) {
builder.setEcSignedPreKey(EcSignedPreKey.newBuilder()
.setKeyId(ecSignedPreKey.keyId())
.setPublicKey(ByteString.copyFrom(ecSignedPreKey.serializedPublicKey()))
.setSignature(ByteString.copyFrom(ecSignedPreKey.signature()))
.build());
} else if (preKey instanceof KEMSignedPreKey kemSignedPreKey) {
builder.setKemOneTimePreKey(KemSignedPreKey.newBuilder()
.setKeyId(kemSignedPreKey.keyId())
.setPublicKey(ByteString.copyFrom(kemSignedPreKey.serializedPublicKey()))
.setSignature(ByteString.copyFrom(kemSignedPreKey.signature()))
.build());
} else {
throw new AssertionError("Unexpected pre-key type: " + preKey.getClass());
}
return builder;
})
// Cast device IDs to `int` to match data types in the response object’s protobuf definition
.map(builder -> Tuples.of((int) device.getId(), builder.build())))
.build()));
// Cast device IDs to `int` to match data types in the response object’s protobuf definition
return Tuples.of((int) device.getId(), builder.build());
}))
// If there were no devices with valid prekey bundles in the account, the account is gone
.switchIfEmpty(Mono.error(Status.NOT_FOUND.asException()))
.collectMap(Tuple2::getT1, Tuple2::getT2)
.map(preKeyBundles -> GetPreKeysResponse.newBuilder()
.setIdentityKey(ByteString.copyFrom(targetAccount.getIdentityKey(identityType).serialize()))
.setIdentityKey(ByteString
.copyFrom(targetAccount.getIdentityKey(targetServiceIdentifier.identityType())
.serialize()))
.putAllPreKeys(preKeyBundles)
.build());
}
@@ -136,7 +136,7 @@ public class KeysGrpcService extends ReactorKeysGrpc.KeysImplBase {
.flatMap(Mono::justOrEmpty))
.switchIfEmpty(Mono.error(Status.NOT_FOUND.asException()))
.flatMap(targetAccount ->
KeysGrpcHelper.getPreKeys(targetAccount, targetIdentifier.identityType(), deviceId, keysManager));
KeysGrpcHelper.getPreKeys(targetAccount, targetIdentifier, deviceId, keysManager));
}
@Override
@@ -0,0 +1,134 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import com.google.common.annotations.VisibleForTesting;
import io.grpc.*;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.Timer;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
public class MetricServerInterceptor implements ServerInterceptor {
private static final String TAG_SERVICE_NAME = "grpcService";
private static final String TAG_METHOD_NAME = "method";
private static final String TAG_METHOD_TYPE = "methodType";
private static final String TAG_STATUS_CODE = "statusCode";
@VisibleForTesting
static final String REQUEST_MESSAGE_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "requestMessage");
@VisibleForTesting
static final String RESPONSE_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "responseMessage");
@VisibleForTesting
static final String RPC_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "rpc");
@VisibleForTesting
static final String DURATION_TIMER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "processingDuration");
private final MeterRegistry meterRegistry;
private final ClientReleaseManager clientReleaseManager;
public MetricServerInterceptor(final MeterRegistry meterRegistry, final ClientReleaseManager clientReleaseManager) {
this.meterRegistry = meterRegistry;
this.clientReleaseManager = clientReleaseManager;
}
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
final ServerCall<ReqT, RespT> call,
final Metadata headers,
final ServerCallHandler<ReqT, RespT> next) {
final Optional<String> userAgentString = RequestAttributesUtil.getUserAgent();
final List<Tag> tagList = new ArrayList<>(6);
tagList.add(Tag.of(TAG_SERVICE_NAME, call.getMethodDescriptor().getServiceName()));
tagList.add(Tag.of(TAG_METHOD_NAME, call.getMethodDescriptor().getBareMethodName()));
tagList.add(Tag.of(TAG_METHOD_TYPE, call.getMethodDescriptor().getType().name()));
RequestAttributesUtil.getUserAgent()
.map(UserAgentTagUtil::getLibsignalAndPlatformTags)
.ifPresent(tagList::addAll);
userAgentString
.flatMap(ua -> UserAgentTagUtil.getClientVersionTag(ua, clientReleaseManager))
.ifPresent(tagList::add);
final Tags tags = Tags.of(tagList);
final MetricServerCall<ReqT, RespT> monitoringServerCall = new MetricServerCall<>(call, tags);
return new MetricServerCallListener<>(next.startCall(monitoringServerCall, headers), tags);
}
/**
* A ServerCall delegator that updates metrics on response messages and the final RPC status
*/
private class MetricServerCall<ReqT, RespT> extends ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT> {
private final Counter responseMessageCounter;
private final Tags tags;
MetricServerCall(final ServerCall<ReqT, RespT> delegate, final Tags tags) {
super(delegate);
this.responseMessageCounter = meterRegistry.counter(RESPONSE_COUNTER_NAME, tags);
this.tags = tags;
}
@Override
public void close(final Status status, final Metadata responseHeaders) {
meterRegistry.counter(RPC_COUNTER_NAME, tags.and(TAG_STATUS_CODE, status.getCode().name())).increment();
super.close(status, responseHeaders);
}
@Override
public void sendMessage(final RespT responseMessage) {
this.responseMessageCounter.increment();
super.sendMessage(responseMessage);
}
}
/**
* A ServerCallListener delegator that updates metrics on requests and measures the RPC time on completion
*/
private class MetricServerCallListener<ReqT> extends ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT> {
private final Counter requestCounter;
private final Timer responseTimer;
private final Timer.Sample sample;
MetricServerCallListener(final ServerCall.Listener<ReqT> delegate, final Tags tags) {
super(delegate);
this.requestCounter = meterRegistry.counter(REQUEST_MESSAGE_COUNTER_NAME, tags);
this.responseTimer = meterRegistry.timer(DURATION_TIMER_NAME, tags);
this.sample = Timer.start(meterRegistry);
}
@Override
public void onMessage(final ReqT requestMessage) {
this.requestCounter.increment();
super.onMessage(requestMessage);
}
@Override
public void onComplete() {
this.sample.stop(responseTimer);
super.onComplete();
}
@Override
public void onCancel() {
this.sample.stop(responseTimer);
super.onCancel();
}
}
}
@@ -1,5 +1,8 @@
package org.whispersystems.textsecuregcm.grpc.net;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
@@ -15,6 +18,8 @@ import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
/**
* An "establish local connection" handler waits for a Noise handshake to complete upstream in the pipeline, buffering
@@ -22,24 +27,28 @@ import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
* server.
*/
public class EstablishLocalGrpcConnectionHandler extends ChannelInboundHandlerAdapter {
private static final Logger log = LoggerFactory.getLogger(EstablishLocalGrpcConnectionHandler.class);
private final GrpcClientConnectionManager grpcClientConnectionManager;
private final LocalAddress authenticatedGrpcServerAddress;
private final LocalAddress anonymousGrpcServerAddress;
private final FramingType framingType;
private final List<Object> pendingReads = new ArrayList<>();
private static final Logger log = LoggerFactory.getLogger(EstablishLocalGrpcConnectionHandler.class);
private static final String CONNECTION_ESTABLISHED_COUNTER_NAME = MetricsUtil.name(EstablishLocalGrpcConnectionHandler.class, "established");
public EstablishLocalGrpcConnectionHandler(final GrpcClientConnectionManager grpcClientConnectionManager,
final LocalAddress authenticatedGrpcServerAddress,
final LocalAddress anonymousGrpcServerAddress) {
final LocalAddress anonymousGrpcServerAddress,
final FramingType framingType) {
this.grpcClientConnectionManager = grpcClientConnectionManager;
this.authenticatedGrpcServerAddress = authenticatedGrpcServerAddress;
this.anonymousGrpcServerAddress = anonymousGrpcServerAddress;
this.framingType = framingType;
}
@Override
@@ -63,6 +72,12 @@ public class EstablishLocalGrpcConnectionHandler extends ChannelInboundHandlerAd
GrpcClientConnectionManager.handleHandshakeInitiated(
remoteChannelContext.channel(), remoteAddress, userAgent, acceptLanguage);
final List<Tag> tags = UserAgentTagUtil.getLibsignalAndPlatformTags(userAgent);
Metrics.counter(CONNECTION_ESTABLISHED_COUNTER_NAME, Tags.of(tags)
.and("authenticated", Boolean.toString(authenticatedDevice.isPresent()))
.and("framingType", framingType.name()))
.increment();
new Bootstrap()
.remoteAddress(grpcServerAddress)
.channel(LocalChannel.class)
@@ -0,0 +1,6 @@
package org.whispersystems.textsecuregcm.grpc.net;
public enum FramingType {
NOISE_DIRECT,
WEBSOCKET
}
@@ -10,19 +10,16 @@ import io.netty.channel.local.LocalChannel;
import io.netty.util.AttributeKey;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestListener;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.grpc.ChannelNotFoundException;
import org.whispersystems.textsecuregcm.grpc.RequestAttributes;
@@ -45,7 +42,7 @@ import org.whispersystems.textsecuregcm.util.ClosableEpoch;
* Methods for requesting connection closure accept an {@link AuthenticatedDevice} to identify the connection and may
* be called from any application code.
*/
public class GrpcClientConnectionManager implements DisconnectionRequestListener {
public class GrpcClientConnectionManager {
private final Map<LocalAddress, Channel> remoteChannelsByLocalAddress = new ConcurrentHashMap<>();
private final Map<AuthenticatedDevice, List<Channel>> remoteChannelsByAuthenticatedDevice = new ConcurrentHashMap<>();
@@ -62,7 +59,7 @@ public class GrpcClientConnectionManager implements DisconnectionRequestListener
static final AttributeKey<ClosableEpoch> EPOCH_ATTRIBUTE_KEY =
AttributeKey.valueOf(GrpcClientConnectionManager.class, "epoch");
private static OutboundCloseErrorMessage SERVER_CLOSED =
private static final OutboundCloseErrorMessage SERVER_CLOSED =
new OutboundCloseErrorMessage(OutboundCloseErrorMessage.Code.SERVER_CLOSED, "server closed");
private static final Logger log = LoggerFactory.getLogger(GrpcClientConnectionManager.class);
@@ -268,11 +265,4 @@ public class GrpcClientConnectionManager implements DisconnectionRequestListener
}));
});
}
@Override
public void handleDisconnectionRequest(final UUID accountIdentifier, final Collection<Byte> deviceIds) {
deviceIds.stream()
.map(deviceId -> new AuthenticatedDevice(accountIdentifier, deviceId))
.forEach(this::closeConnection);
}
}
@@ -18,4 +18,5 @@ public record NoiseIdentityDeterminedEvent(
Optional<AuthenticatedDevice> authenticatedDevice,
InetAddress remoteAddress,
String userAgent,
String acceptLanguage) {}
String acceptLanguage) {
}
@@ -16,7 +16,7 @@ import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
* Watches for inbound close frames and closes the connection in response
*/
public class NoiseDirectInboundCloseHandler extends ChannelInboundHandlerAdapter {
private static String CLIENT_CLOSE_COUNTER_NAME = MetricsUtil.name(ChannelInboundHandlerAdapter.class, "clientClose");
private static String CLIENT_CLOSE_COUNTER_NAME = MetricsUtil.name(NoiseDirectInboundCloseHandler.class, "clientClose");
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
if (msg instanceof NoiseDirectFrame ndf && ndf.frameType() == NoiseDirectFrame.FrameType.CLOSE) {
@@ -1,5 +1,6 @@
package org.whispersystems.textsecuregcm.grpc.net.noisedirect;
import io.micrometer.core.instrument.Metrics;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufOutputStream;
import io.netty.channel.ChannelFutureListener;
@@ -7,12 +8,14 @@ import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import org.whispersystems.textsecuregcm.grpc.net.OutboundCloseErrorMessage;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
/**
* Translates {@link OutboundCloseErrorMessage}s into {@link NoiseDirectFrame} error frames. After error frames are
* written, the channel is closed
*/
class NoiseDirectOutboundErrorHandler extends ChannelOutboundHandlerAdapter {
private static String SERVER_CLOSE_COUNTER_NAME = MetricsUtil.name(NoiseDirectInboundCloseHandler.class, "serverClose");
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
@@ -23,6 +26,8 @@ class NoiseDirectOutboundErrorHandler extends ChannelOutboundHandlerAdapter {
case NOISE_HANDSHAKE_ERROR -> NoiseDirectProtos.CloseReason.Code.HANDSHAKE_ERROR;
case INTERNAL_SERVER_ERROR -> NoiseDirectProtos.CloseReason.Code.INTERNAL_ERROR;
};
Metrics.counter(SERVER_CLOSE_COUNTER_NAME, "reason", code.name()).increment();
final NoiseDirectProtos.CloseReason proto = NoiseDirectProtos.CloseReason.newBuilder()
.setCode(code)
.setMessage(err.message())
@@ -17,6 +17,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.grpc.net.ErrorHandler;
import org.whispersystems.textsecuregcm.grpc.net.EstablishLocalGrpcConnectionHandler;
import org.whispersystems.textsecuregcm.grpc.net.FramingType;
import org.whispersystems.textsecuregcm.grpc.net.GrpcClientConnectionManager;
import org.whispersystems.textsecuregcm.grpc.net.HAProxyMessageHandler;
import org.whispersystems.textsecuregcm.grpc.net.NoiseHandshakeHandler;
@@ -68,7 +69,9 @@ public class NoiseDirectTunnelServer implements Managed {
// This handler will open a local connection to the appropriate gRPC server and install a ProxyHandler
// once the Noise handshake has completed
.addLast(new EstablishLocalGrpcConnectionHandler(
grpcClientConnectionManager, authenticatedGrpcServerAddress, anonymousGrpcServerAddress))
grpcClientConnectionManager,
authenticatedGrpcServerAddress, anonymousGrpcServerAddress,
FramingType.NOISE_DIRECT))
.addLast(new ErrorHandler());
}
});
@@ -104,6 +104,8 @@ public class NoiseWebSocketTunnelServer implements Managed {
// request and passed it down the pipeline
.addLast(new WebSocketOpeningHandshakeHandler(AUTHENTICATED_SERVICE_PATH, ANONYMOUS_SERVICE_PATH, HEALTH_CHECK_PATH))
.addLast(new WebSocketServerProtocolHandler("/", true))
// Metrics on inbound/outbound Close frames
.addLast(new WebSocketCloseMetricHandler())
// Turn generic OutboundCloseErrorMessages into websocket close frames
.addLast(new WebSocketOutboundErrorHandler())
.addLast(new RejectUnsupportedMessagesHandler())
@@ -116,7 +118,10 @@ public class NoiseWebSocketTunnelServer implements Managed {
.addLast(new NoiseHandshakeHandler(clientPublicKeysManager, ecKeyPair))
// This handler will open a local connection to the appropriate gRPC server and install a ProxyHandler
// once the Noise handshake has completed
.addLast(new EstablishLocalGrpcConnectionHandler(grpcClientConnectionManager, authenticatedGrpcServerAddress, anonymousGrpcServerAddress))
.addLast(new EstablishLocalGrpcConnectionHandler(
grpcClientConnectionManager,
authenticatedGrpcServerAddress, anonymousGrpcServerAddress,
FramingType.WEBSOCKET))
.addLast(new ErrorHandler());
}
});
@@ -0,0 +1,50 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc.net.websocket;
import io.micrometer.core.instrument.Metrics;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
public class WebSocketCloseMetricHandler extends ChannelDuplexHandler {
private static String CLIENT_CLOSE_COUNTER_NAME = MetricsUtil.name(WebSocketCloseMetricHandler.class, "clientClose");
private static String SERVER_CLOSE_COUNTER_NAME = MetricsUtil.name(WebSocketCloseMetricHandler.class, "serverClose");
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
if (msg instanceof CloseWebSocketFrame closeFrame) {
Metrics.counter(CLIENT_CLOSE_COUNTER_NAME, "closeCode", validatedCloseCode(closeFrame.statusCode())).increment();
}
ctx.fireChannelRead(msg);
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (msg instanceof CloseWebSocketFrame closeFrame) {
Metrics.counter(SERVER_CLOSE_COUNTER_NAME, "closeCode", Integer.toString(closeFrame.statusCode())).increment();
}
ctx.write(msg, promise);
}
private static String validatedCloseCode(int closeCode) {
if (closeCode >= 1000 && closeCode <= 1015) {
// RFC-6455 pre-defined status codes
return Integer.toString(closeCode);
} else if (closeCode >= 4000 && closeCode <= 4100) {
// Application status codes
return Integer.toString(closeCode);
} else {
return "unknown";
}
}
}
@@ -10,11 +10,13 @@ import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.grpc.net.OutboundCloseErrorMessage;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
/**
* Converts {@link OutboundCloseErrorMessage}s written to the pipeline into WebSocket close frames
*/
class WebSocketOutboundErrorHandler extends ChannelDuplexHandler {
private static String SERVER_CLOSE_COUNTER_NAME = MetricsUtil.name(WebSocketOutboundErrorHandler.class, "serverClose");
private boolean websocketHandshakeComplete = false;
@@ -21,9 +21,7 @@ import io.micrometer.core.instrument.config.MeterFilter;
import io.micrometer.core.instrument.distribution.DistributionStatisticConfig;
import io.micrometer.registry.otlp.OtlpMeterRegistry;
import io.micrometer.statsd.StatsdMeterRegistry;
import java.time.Duration;
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
import org.whispersystems.textsecuregcm.WhisperServerVersion;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
@@ -65,7 +63,7 @@ public class MetricsUtil {
Duration shutdownWaitDuration = Duration.ZERO;
if (config.getDatadogConfiguration() != null && config.getDatadogConfiguration().enabled()) {
if (config.getDatadogConfiguration().enabled()) {
final StatsdMeterRegistry dogstatsdMeterRegistry = new StatsdMeterRegistry(
config.getDatadogConfiguration(), io.micrometer.core.instrument.Clock.SYSTEM);
@@ -81,7 +79,7 @@ public class MetricsUtil {
shutdownWaitDuration = config.getDatadogConfiguration().getShutdownWaitDuration();
}
if (config.getOpenTelemetryConfiguration() != null && config.getOpenTelemetryConfiguration().enabled()) {
if (config.getOpenTelemetryConfiguration().enabled()) {
final OtlpMeterRegistry otlpMeterRegistry = new OtlpMeterRegistry(
config.getOpenTelemetryConfiguration(), io.micrometer.core.instrument.Clock.SYSTEM);
@@ -105,6 +103,7 @@ public class MetricsUtil {
static void configureMeterFilters(MeterRegistry.Config config,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
final DistributionStatisticConfig defaultDistributionStatisticConfig = DistributionStatisticConfig.builder()
.percentilesHistogram(true)
.percentiles(.75, .95, .99, .999)
.build();
@@ -83,7 +83,7 @@ public class OpenWebSocketCounter {
Metrics.counter(newConnectionCounterName, tagsWithClientPlatform).increment();
context.addWebsocketClosedListener((context1, statusCode, reason) -> {
context.addWebsocketClosedListener((_, statusCode, _) -> {
sample.stop(Timer.builder(durationTimerName)
.publishPercentileHistogram(true)
.tags(tagsWithClientPlatform)
@@ -1,24 +0,0 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.providers;
import com.codahale.metrics.health.HealthCheck;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
public class RedisClusterHealthCheck extends HealthCheck {
private final FaultTolerantRedisClusterClient redisCluster;
public RedisClusterHealthCheck(final FaultTolerantRedisClusterClient redisCluster) {
this.redisCluster = redisCluster;
}
@Override
protected Result check() {
redisCluster.withCluster(connection -> connection.sync().upstream().commands().ping());
return Result.healthy();
}
}
@@ -0,0 +1,33 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.push;
import java.util.UUID;
/**
* A message availability listener handles message availability and presence events related to a client's open message
* stream. Handler methods are run on dedicated threads and may safely perform blocking operations.
*
* @see RedisMessageAvailabilityManager#handleClientConnected(UUID, byte, MessageAvailabilityListener)
*/
public interface MessageAvailabilityListener {
/**
* Indicates that a new message is available in the connected client's message queue.
*/
void handleNewMessageAvailable();
/**
* Indicates that messages for the client have been persisted from short-term storage to long-term storage.
*/
void handleMessagesPersisted();
/**
* Indicates a newer instance of this client has started reading messages and the listener should close this client's
* underlying network connection.
*/
void handleConflictingMessageConsumer();
}
@@ -78,8 +78,6 @@ public class PushNotificationScheduler implements Managed {
private final int maxConcurrency;
private static final int PAGE_SIZE = 128;
NotificationWorker(final int maxConcurrency) {
this.maxConcurrency = maxConcurrency;
}
@@ -17,11 +17,9 @@ import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
@@ -32,37 +30,31 @@ import java.util.function.Function;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestListener;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubClusterConnection;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.util.RedisClusterUtil;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import org.whispersystems.textsecuregcm.util.Util;
/**
* The WebSocket connection event manager distributes events related to client presence and message availability to
* The Redis message availability manager distributes events related to client presence and message availability to
* registered listeners. In the current Signal server implementation, clients generally interact with the service by
* opening a dual-purpose WebSocket. The WebSocket serves as both a delivery mechanism for messages and as a channel
* for the client to issue API requests to the server. Clients are considered "present" if they have an open WebSocket
* connection and are therefore likely to receive messages as soon as they're delivered to the server. WebSocket
* connection managers make a best effort to ensure that clients have at most one active message delivery channel at
* a time.
* connection and are therefore likely to receive messages as soon as they're delivered to the server. Redis message
* availability managers ensure that clients have at most one active message delivery channel at a time on a
* best-effort basis.
*
* @implNote The WebSocket connection event manager uses the Redis 7 sharded pub/sub system to distribute events. This
* @implNote The Redis message availability manager uses the Redis 7 sharded pub/sub system to distribute events. This
* system makes a best effort to ensure that a given client has only a single open connection across the fleet of
* servers, but cannot guarantee at-most-one behavior.
*
* @see WebSocketConnectionEventListener
* @see org.whispersystems.textsecuregcm.storage.MessagesManager#insert(UUID, byte, MessageProtos.Envelope)
* @see MessageAvailabilityListener
* @see org.whispersystems.textsecuregcm.storage.MessagesManager#insert(UUID, Map)
*/
public class WebSocketConnectionEventManager extends RedisClusterPubSubAdapter<byte[], byte[]> implements Managed,
DisconnectionRequestListener {
public class RedisMessageAvailabilityManager extends RedisClusterPubSubAdapter<byte[], byte[]> implements Managed {
private final AccountsManager accountsManager;
private final PushNotificationManager pushNotificationManager;
private final FaultTolerantRedisClusterClient clusterClient;
private final Executor listenerEventExecutor;
@@ -73,7 +65,7 @@ public class WebSocketConnectionEventManager extends RedisClusterPubSubAdapter<b
@Nullable
private FaultTolerantPubSubClusterConnection<byte[], byte[]> pubSubConnection;
private final Map<AccountAndDeviceIdentifier, WebSocketConnectionEventListener> listenersByAccountAndDeviceIdentifier;
private final Map<AccountAndDeviceIdentifier, MessageAvailabilityListener> listenersByAccountAndDeviceIdentifier;
private final UUID serverId = UUID.randomUUID();
@@ -85,35 +77,30 @@ public class WebSocketConnectionEventManager extends RedisClusterPubSubAdapter<b
.toByteArray();
private static final Counter PUBLISH_CLIENT_CONNECTION_EVENT_ERROR_COUNTER =
Metrics.counter(MetricsUtil.name(WebSocketConnectionEventManager.class, "publishClientConnectionEventError"));
Metrics.counter(MetricsUtil.name(RedisMessageAvailabilityManager.class, "publishClientConnectionEventError"));
private static final Counter UNSUBSCRIBE_ERROR_COUNTER =
Metrics.counter(MetricsUtil.name(WebSocketConnectionEventManager.class, "unsubscribeError"));
Metrics.counter(MetricsUtil.name(RedisMessageAvailabilityManager.class, "unsubscribeError"));
private static final Counter PUB_SUB_EVENT_WITHOUT_LISTENER_COUNTER =
Metrics.counter(MetricsUtil.name(WebSocketConnectionEventManager.class, "pubSubEventWithoutListener"));
Metrics.counter(MetricsUtil.name(RedisMessageAvailabilityManager.class, "pubSubEventWithoutListener"));
private static final Counter MESSAGE_AVAILABLE_WITHOUT_LISTENER_COUNTER =
Metrics.counter(MetricsUtil.name(WebSocketConnectionEventManager.class, "messageAvailableWithoutListener"));
Metrics.counter(MetricsUtil.name(RedisMessageAvailabilityManager.class, "messageAvailableWithoutListener"));
private static final String LISTENER_GAUGE_NAME =
MetricsUtil.name(WebSocketConnectionEventManager.class, "listeners");
MetricsUtil.name(RedisMessageAvailabilityManager.class, "listeners");
private static final Logger logger = LoggerFactory.getLogger(WebSocketConnectionEventManager.class);
private static final Logger logger = LoggerFactory.getLogger(RedisMessageAvailabilityManager.class);
@VisibleForTesting
record AccountAndDeviceIdentifier(UUID accountIdentifier, byte deviceId) {
}
public WebSocketConnectionEventManager(final AccountsManager accountsManager,
final PushNotificationManager pushNotificationManager,
final FaultTolerantRedisClusterClient clusterClient,
public RedisMessageAvailabilityManager(final FaultTolerantRedisClusterClient clusterClient,
final Executor listenerEventExecutor,
final Executor asyncOperationQueueingExecutor) {
this.accountsManager = accountsManager;
this.pushNotificationManager = pushNotificationManager;
this.clusterClient = clusterClient;
this.listenerEventExecutor = listenerEventExecutor;
this.asyncOperationQueueingExecutor = asyncOperationQueueingExecutor;
@@ -145,7 +132,7 @@ public class WebSocketConnectionEventManager extends RedisClusterPubSubAdapter<b
/**
* Marks the given device as "present" for message delivery and registers a listener for new messages and conflicting
* connections. If the given device already has a presence registered with this manager, that presence is displaced
* immediately and the listener's {@link WebSocketConnectionEventListener#handleConnectionDisplaced(boolean)} method is called.
* immediately and the listener's {@link MessageAvailabilityListener#handleConflictingMessageConsumer()} method is called.
*
* @param accountIdentifier the account identifier for the newly-connected device
* @param deviceId the ID of the newly-connected device within the given account
@@ -156,13 +143,13 @@ public class WebSocketConnectionEventManager extends RedisClusterPubSubAdapter<b
* pub/sub subscription could not be established, in which case callers should close the client's connection to the
* server
*/
public CompletionStage<Void> handleClientConnected(final UUID accountIdentifier, final byte deviceId, final WebSocketConnectionEventListener listener) {
public CompletionStage<Void> handleClientConnected(final UUID accountIdentifier, final byte deviceId, final MessageAvailabilityListener listener) {
if (pubSubConnection == null) {
throw new IllegalStateException("WebSocket connection event manager not started");
}
final byte[] eventChannel = getClientEventChannel(accountIdentifier, deviceId);
final AtomicReference<WebSocketConnectionEventListener> displacedListener = new AtomicReference<>();
final AtomicReference<MessageAvailabilityListener> displacedListener = new AtomicReference<>();
final AtomicReference<CompletionStage<Void>> subscribeFuture = new AtomicReference<>();
// Note that we're relying on some specific implementation details of `ConcurrentHashMap#compute(...)`. In
@@ -189,7 +176,7 @@ public class WebSocketConnectionEventManager extends RedisClusterPubSubAdapter<b
});
if (displacedListener.get() != null) {
listenerEventExecutor.execute(() -> displacedListener.get().handleConnectionDisplaced(true));
listenerEventExecutor.execute(() -> displacedListener.get().handleConflictingMessageConsumer());
}
return subscribeFuture.get()
@@ -260,14 +247,6 @@ public class WebSocketConnectionEventManager extends RedisClusterPubSubAdapter<b
return listenersByAccountAndDeviceIdentifier.containsKey(new AccountAndDeviceIdentifier(accountUuid, deviceId));
}
@Override
public void handleDisconnectionRequest(final UUID accountIdentifier, final Collection<Byte> deviceIds) {
deviceIds.stream()
.map(deviceId -> listenersByAccountAndDeviceIdentifier.get(new AccountAndDeviceIdentifier(accountIdentifier, deviceId)))
.filter(Objects::nonNull)
.forEach(listener -> listener.handleConnectionDisplaced(false));
}
@VisibleForTesting
void resubscribe(final ClusterTopologyChangedEvent clusterTopologyChangedEvent) {
final boolean[] changedSlots = RedisClusterUtil.getChangedSlots(clusterTopologyChangedEvent);
@@ -328,7 +307,7 @@ public class WebSocketConnectionEventManager extends RedisClusterPubSubAdapter<b
final AccountAndDeviceIdentifier accountAndDeviceIdentifier = parseClientEventChannel(shardChannel);
@Nullable final WebSocketConnectionEventListener listener =
@Nullable final MessageAvailabilityListener listener =
listenersByAccountAndDeviceIdentifier.get(accountAndDeviceIdentifier);
if (listener != null) {
@@ -339,7 +318,7 @@ public class WebSocketConnectionEventManager extends RedisClusterPubSubAdapter<b
// Only act on new connections to other event manager instances; we'll learn about displacements in THIS
// instance when we update the listener map in `handleClientConnected`
if (!this.serverId.equals(UUIDUtil.fromByteString(clientEvent.getClientConnected().getServerId()))) {
listenerEventExecutor.execute(() -> listener.handleConnectionDisplaced(true));
listenerEventExecutor.execute(listener::handleConflictingMessageConsumer);
}
}
@@ -354,22 +333,6 @@ public class WebSocketConnectionEventManager extends RedisClusterPubSubAdapter<b
if (clientEvent.getEventCase() == ClientEvent.EventCase.NEW_MESSAGE_AVAILABLE) {
MESSAGE_AVAILABLE_WITHOUT_LISTENER_COUNTER.increment();
// If we have an active subscription but no registered listener, it's likely that the publisher of this event
// believes that the receiving client was present when it really wasn't. Send a push notification as a
// just-in-case measure.
accountsManager.getByAccountIdentifierAsync(accountAndDeviceIdentifier.accountIdentifier())
.thenAccept(maybeAccount -> maybeAccount.ifPresent(account -> {
try {
pushNotificationManager.sendNewMessageNotification(account, accountAndDeviceIdentifier.deviceId(), true);
} catch (final NotPushRegisteredException ignored) {
}
}))
.whenComplete((ignored, throwable) -> {
if (throwable != null) {
logger.warn("Failed to send follow-up notification to {}:{}", accountAndDeviceIdentifier.accountIdentifier(), accountAndDeviceIdentifier.deviceId());
}
});
}
}
}
@@ -1,32 +0,0 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.push;
/**
* A WebSocket connection event listener handles message availability and presence events related to a client's open
* WebSocket connection. Handler methods are run on dedicated threads and may safely perform blocking operations.
*/
public interface WebSocketConnectionEventListener {
/**
* Indicates that a new message is available in the connected client's message queue.
*/
void handleNewMessageAvailable();
/**
* Indicates that messages for the client have been persisted from short-term storage to long-term storage.
*/
void handleMessagesPersisted();
/**
* Indicates that the client's presence has been displaced and the listener should close the client's underlying
* network connection.
*
* @param connectedElsewhere if {@code true}, indicates that the client's presence has been displaced by another
* connection from the same client
*/
void handleConnectionDisplaced(boolean connectedElsewhere);
}
@@ -21,7 +21,6 @@ import java.util.concurrent.CompletableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public class ClusterLuaScript {
@@ -133,13 +132,7 @@ public class ClusterLuaScript {
final T[] keys, final T[] args) {
return connection.reactive().evalsha(sha, scriptOutputType, keys, args)
.onErrorResume(e -> {
if (e instanceof RedisNoScriptException) {
return connection.reactive().eval(script, scriptOutputType, keys, args);
}
log.warn("Failed to execute script", e);
return Mono.error(e);
});
.onErrorResume(RedisNoScriptException.class, _ -> connection.reactive().eval(script, scriptOutputType, keys, args))
.doOnError(throwable -> log.warn("Failed to execute script", throwable));
}
}
@@ -128,7 +128,7 @@ public class FaultTolerantRedisClient {
return withConnection(binaryConnection, function);
}
public <K, V> void useConnection(final StatefulRedisConnection<K, V> connection,
private <K, V> void useConnection(final StatefulRedisConnection<K, V> connection,
final Consumer<StatefulRedisConnection<K, V>> consumer) {
try {
circuitBreaker.executeRunnable(() -> retry.executeRunnable(() -> consumer.accept(connection)));
@@ -141,7 +141,7 @@ public class FaultTolerantRedisClient {
}
}
public <T, K, V> T withConnection(final StatefulRedisConnection<K, V> connection,
private <T, K, V> T withConnection(final StatefulRedisConnection<K, V> connection,
final Function<StatefulRedisConnection<K, V>, T> function) {
try {
return circuitBreaker.executeCallable(() -> retry.executeCallable(() -> function.apply(connection)));
@@ -165,7 +165,7 @@ public class FaultTolerantRedisClusterClient {
return withConnectionReactive(binaryConnection, function);
}
public <K, V> void useConnection(final StatefulRedisClusterConnection<K, V> connection,
private <K, V> void useConnection(final StatefulRedisClusterConnection<K, V> connection,
final Consumer<StatefulRedisClusterConnection<K, V>> consumer) {
try {
retry.executeRunnable(() -> consumer.accept(connection));
@@ -178,7 +178,7 @@ public class FaultTolerantRedisClusterClient {
}
}
public <T, K, V> T withConnection(final StatefulRedisClusterConnection<K, V> connection,
private <T, K, V> T withConnection(final StatefulRedisClusterConnection<K, V> connection,
final Function<StatefulRedisClusterConnection<K, V>, T> function) {
try {
return retry.executeCallable(() -> function.apply(connection));
@@ -191,7 +191,7 @@ public class FaultTolerantRedisClusterClient {
}
}
public <T, K, V> Publisher<T> withConnectionReactive(
private <T, K, V> Publisher<T> withConnectionReactive(
final StatefulRedisClusterConnection<K, V> connection,
final Function<StatefulRedisClusterConnection<K, V>, Publisher<T>> function) {
@@ -9,7 +9,6 @@ import java.time.Clock;
import java.time.Instant;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.zone.ZoneRules;
import java.util.Comparator;
@@ -19,19 +18,21 @@ import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import io.micrometer.core.instrument.Metrics;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.storage.Account;
public class SchedulingUtil {
private static final String PARSED_TIMEZONE_COUNTER_NAME = MetricsUtil.name(SchedulingUtil.class, "parsedTimezone");
private static final String HAS_TIMEZONE_TAG_NAME = "hasTimezone";
/**
* Gets a present or future time at which to send a notification to a device associated with the given account. This
* is mainly intended to facilitate scheduling notifications such that they arrive during a recipient's waking hours.
* <p/>
* This method will attempt to use a timezone derived from the account's phone number to choose an appropriate time
* to send a notification. If a timezone cannot be derived from the account's phone number, then this method will use
* the account's creation time as a hint. As an example, if the account was created at 07:17 in the server's local
* time, we can assume that the account holder was awake at that time of day, and it's likely a safe time to send a
* notification in the absence of other hints.
* to send a notification. If a timezone cannot be derived from the account's phone number, then this method will
* default to the preferred time in the server's timezone.
*
* @param account the account that will receive the notification
* @param preferredTime the preferred local time (e.g. "noon") at which to deliver the notification
@@ -44,14 +45,13 @@ public class SchedulingUtil {
final Clock clock) {
final ZonedDateTime candidateNotificationTime = getZoneId(account, clock)
.map(zoneId -> ZonedDateTime.now(clock.withZone(zoneId)).with(preferredTime))
.map(zoneId -> {
Metrics.counter(PARSED_TIMEZONE_COUNTER_NAME, HAS_TIMEZONE_TAG_NAME, String.valueOf(true)).increment();
return ZonedDateTime.now(clock.withZone(zoneId)).with(preferredTime);
})
.orElseGet(() -> {
// We couldn't find a reasonable timezone for the account for some reason, so make an educated guess at a
// reasonable time to send a notification based on the account's creation time.
final Instant accountCreation = Instant.ofEpochMilli(account.getPrimaryDevice().getCreated());
final LocalTime accountCreationLocalTime = LocalTime.ofInstant(accountCreation, ZoneId.systemDefault());
return ZonedDateTime.now(ZoneId.systemDefault()).with(accountCreationLocalTime);
Metrics.counter(PARSED_TIMEZONE_COUNTER_NAME, HAS_TIMEZONE_TAG_NAME, String.valueOf(false)).increment();
return ZonedDateTime.now(ZoneId.systemDefault()).with(preferredTime);
});
if (candidateNotificationTime.toInstant().isBefore(clock.instant())) {
@@ -30,9 +30,10 @@ import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
import org.whispersystems.textsecuregcm.util.HttpUtils;
/**
* A client for sending requests to Signal's secure value recovery v2 service on behalf of authenticated users.
* A client for sending requests to Signal's secure value recovery service on behalf of authenticated users.
*/
public class SecureValueRecoveryClient {
private static final Logger logger = LoggerFactory.getLogger(SecureValueRecoveryClient.class);
private final ExternalServiceCredentialsGenerator secureValueRecoveryCredentialsGenerator;
@@ -67,8 +68,12 @@ public class SecureValueRecoveryClient {
}
public CompletableFuture<Void> removeData(final UUID accountUuid) {
return removeData(accountUuid.toString());
}
final ExternalServiceCredentials credentials = secureValueRecoveryCredentialsGenerator.generateForUuid(accountUuid);
public CompletableFuture<Void> removeData(final String userIdentifier) {
final ExternalServiceCredentials credentials = secureValueRecoveryCredentialsGenerator.generateFor(userIdentifier);
final HttpRequest request = HttpRequest.newBuilder()
.uri(deleteUri)
@@ -83,11 +88,11 @@ public class SecureValueRecoveryClient {
final List<Integer> allowedErrors = allowedDeletionErrorStatusCodes.get();
if (allowedErrors.contains(response.statusCode())) {
logger.warn("Ignoring failure to delete svr entry for account {} with status {}",
accountUuid, response.statusCode());
logger.warn("Ignoring failure to delete svr entry for identifier {} with status {}",
userIdentifier, response.statusCode());
return null;
}
logger.warn("Failed to delete svr entry for account {} with status {}", accountUuid, response.statusCode());
logger.warn("Failed to delete svr entry for identifier {} with status {}", userIdentifier, response.statusCode());
throw new SecureValueRecoveryException("Failed to delete backup", String.valueOf(response.statusCode()));
});
}
@@ -271,6 +271,7 @@ public class Account {
case PRIMARY_DEVICE -> getPrimaryDevice().hasCapability(capability);
case ANY_DEVICE -> devices.stream().anyMatch(device -> device.hasCapability(capability));
case ALL_DEVICES -> devices.stream().allMatch(device -> device.hasCapability(capability));
case ALWAYS_CAPABLE -> true;
};
}
@@ -50,6 +50,7 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
@@ -85,6 +86,7 @@ import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.RegistrationIdValidator;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Flux;
@@ -111,6 +113,8 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
private static final String DELETE_COUNTER_NAME = name(AccountsManager.class, "deleteCounter");
private static final String COUNTRY_CODE_TAG_NAME = "country";
private static final String DELETION_REASON_TAG_NAME = "reason";
private static final String TIMESTAMP_BASED_TRANSFER_ARCHIVE_KEY_COUNTER_NAME = name(AccountsManager.class, "timestampRedisKeyCounter");
private static final String REGISTRATION_ID_BASED_TRANSFER_ARCHIVE_KEY_COUNTER_NAME = name(AccountsManager.class,"registrationIdRedisKeyCounter");
private static final Logger logger = LoggerFactory.getLogger(AccountsManager.class);
@@ -124,7 +128,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
private final ProfilesManager profilesManager;
private final SecureStorageClient secureStorageClient;
private final SecureValueRecoveryClient secureValueRecovery2Client;
private final SecureValueRecoveryClient secureValueRecoveryBClient;
private final DisconnectionRequestManager disconnectionRequestManager;
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
private final ClientPublicKeysManager clientPublicKeysManager;
@@ -140,7 +143,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
private final Map<String, CompletableFuture<Optional<DeviceInfo>>> waitForDeviceFuturesByTokenIdentifier =
new ConcurrentHashMap<>();
private final Map<TimestampedDeviceIdentifier, CompletableFuture<Optional<TransferArchiveResult>>> waitForTransferArchiveFuturesByDeviceIdentifier =
private final Map<DeviceIdentifier, CompletableFuture<Optional<TransferArchiveResult>>> waitForTransferArchiveFuturesByDeviceIdentifier =
new ConcurrentHashMap<>();
private final Map<String, CompletableFuture<Optional<RestoreAccountRequest>>> waitForRestoreAccountRequestFuturesByToken =
@@ -155,6 +158,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
private static final Duration RECENTLY_ADDED_TRANSFER_ARCHIVE_TTL = Duration.ofHours(1);
private static final String TRANSFER_ARCHIVE_PREFIX = "transfer_archive::";
private static final String TRANSFER_ARCHIVE_KEYSPACE_PATTERN = "__keyspace@0__:" + TRANSFER_ARCHIVE_PREFIX + "*";
private static final String TRANSFER_ARCHIVE_REGISTRATION_ID_PATTERN = "registrationId";
private static final Duration RESTORE_ACCOUNT_REQUEST_TTL = Duration.ofHours(1);
private static final String RESTORE_ACCOUNT_REQUEST_PREFIX = "restore_account::";
@@ -194,7 +198,14 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
}
private record TimestampedDeviceIdentifier(UUID accountIdentifier, byte deviceId, Instant deviceCreationTimestamp) {
private interface DeviceIdentifier {}
private record TimestampDeviceIdentifier(UUID accountIdentifier, byte deviceId, Instant deviceCreationTimestamp)
implements DeviceIdentifier {
}
private record RegistrationIdDeviceIdentifier(UUID accountIdentifier, byte deviceId,
int registrationId) implements DeviceIdentifier {
}
public AccountsManager(final Accounts accounts,
@@ -207,7 +218,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final ProfilesManager profilesManager,
final SecureStorageClient secureStorageClient,
final SecureValueRecoveryClient secureValueRecovery2Client,
final SecureValueRecoveryClient secureValueRecoveryBClient,
final DisconnectionRequestManager disconnectionRequestManager,
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
final ClientPublicKeysManager clientPublicKeysManager,
@@ -226,7 +236,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
this.profilesManager = profilesManager;
this.secureStorageClient = secureStorageClient;
this.secureValueRecovery2Client = secureValueRecovery2Client;
this.secureValueRecoveryBClient = secureValueRecoveryBClient;
this.disconnectionRequestManager = disconnectionRequestManager;
this.registrationRecoveryPasswordsManager = requireNonNull(registrationRecoveryPasswordsManager);
this.clientPublicKeysManager = clientPublicKeysManager;
@@ -374,7 +383,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
keysManager.deleteSingleUsePreKeys(pni),
messagesManager.clear(aci),
profilesManager.deleteAll(aci, false))
.thenCompose(ignored -> disconnectionRequestManager.requestDisconnection(aci))
.thenCompose(ignored -> disconnectionRequestManager.requestDisconnection(e.getExistingAccount()))
.thenCompose(ignored -> accounts.reclaimAccount(e.getExistingAccount(), account, additionalWriteItems))
.thenCompose(ignored -> {
// We should have cleared all messages before overwriting the old account, but more may have arrived
@@ -1220,7 +1229,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
return CompletableFuture.allOf(
secureStorageClient.deleteStoredData(account.getUuid()),
secureValueRecovery2Client.removeData(account.getUuid()),
secureValueRecoveryBClient.removeData(account.getUuid()),
keysManager.deleteSingleUsePreKeys(account.getUuid()),
keysManager.deleteSingleUsePreKeys(account.getPhoneNumberIdentifier()),
messagesManager.clear(account.getUuid()),
@@ -1228,7 +1236,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
registrationRecoveryPasswordsManager.remove(account.getIdentifier(IdentityType.PNI)))
.thenCompose(ignored -> accounts.delete(account.getUuid(), additionalWriteItems))
.thenCompose(ignored -> redisDeleteAsync(account))
.thenRun(() -> disconnectionRequestManager.requestDisconnection(account.getUuid()));
.thenRun(() -> disconnectionRequestManager.requestDisconnection(account));
}
private String getAccountMapKey(String key) {
@@ -1509,34 +1517,66 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
public CompletableFuture<Optional<TransferArchiveResult>> waitForTransferArchive(final Account account, final Device device, final Duration timeout) {
final TimestampedDeviceIdentifier deviceIdentifier =
new TimestampedDeviceIdentifier(account.getIdentifier(IdentityType.ACI),
device.getId(),
Instant.ofEpochMilli(device.getCreated()));
final DeviceIdentifier timestampDeviceIdentifier = new TimestampDeviceIdentifier(account.getIdentifier(IdentityType.ACI), device.getId(), Instant.ofEpochMilli(device.getCreated()));
final String timestampTransferArchiveKey = getTimestampTransferArchiveKey(account.getIdentifier(IdentityType.ACI), device.getId(), Instant.ofEpochMilli(device.getCreated()));
return waitForPubSubKey(waitForTransferArchiveFuturesByDeviceIdentifier,
deviceIdentifier,
getTransferArchiveKey(account.getIdentifier(IdentityType.ACI), device.getId(), Instant.ofEpochMilli(device.getCreated())),
final DeviceIdentifier registrationIdDeviceIdentifier = new RegistrationIdDeviceIdentifier(account.getIdentifier(IdentityType.ACI), device.getId(), device.getRegistrationId(IdentityType.ACI));
final String registrationIdTransferArchiveKey = getRegistrationIdTransferArchiveKey(account.getIdentifier(IdentityType.ACI), device.getId(), device.getRegistrationId(IdentityType.ACI));
final CompletableFuture<Optional<TransferArchiveResult>> timestampFuture = waitForPubSubKey(waitForTransferArchiveFuturesByDeviceIdentifier,
timestampDeviceIdentifier,
timestampTransferArchiveKey,
timeout,
this::handleTransferArchiveAdded);
final CompletableFuture<Optional<TransferArchiveResult>> registrationIdFuture = waitForPubSubKey(waitForTransferArchiveFuturesByDeviceIdentifier,
registrationIdDeviceIdentifier,
registrationIdTransferArchiveKey,
timeout,
this::handleTransferArchiveAdded);
return firstSuccessfulTransferArchiveFuture(List.of(timestampFuture, registrationIdFuture));
}
@VisibleForTesting
static CompletableFuture<Optional<TransferArchiveResult>> firstSuccessfulTransferArchiveFuture(
final List<CompletableFuture<Optional<TransferArchiveResult>>> futures) {
final CompletableFuture<Optional<TransferArchiveResult>> result = new CompletableFuture<>();
final AtomicInteger remaining = new AtomicInteger(futures.size());
for (CompletableFuture<Optional<TransferArchiveResult>> future : futures) {
future.whenComplete((value, _) -> {
if (value.isPresent()) {
result.complete(value);
} else if (remaining.decrementAndGet() == 0) {
result.complete(Optional.empty());
}
});
}
return result;
}
public CompletableFuture<Void> recordTransferArchiveUpload(final Account account,
final byte destinationDeviceId,
final Instant destinationDeviceCreationTimestamp,
@SuppressWarnings("OptionalUsedAsFieldOrParameterType") final Optional<Instant> destinationDeviceCreationTimestamp,
@SuppressWarnings("OptionalUsedAsFieldOrParameterType") final Optional<Integer> maybeRegistrationId,
final TransferArchiveResult transferArchiveResult) {
final String key = getTransferArchiveKey(account.getIdentifier(IdentityType.ACI),
destinationDeviceId,
destinationDeviceCreationTimestamp);
try {
final String transferArchiveJson = SystemMapper.jsonMapper().writeValueAsString(transferArchiveResult);
return pubSubRedisClient.withConnection(connection ->
connection.async().set(key, transferArchiveJson, SetArgs.Builder.ex(RECENTLY_ADDED_TRANSFER_ARCHIVE_TTL)))
.thenRun(Util.NOOP)
.toCompletableFuture();
return pubSubRedisClient.withConnection(connection -> {
final String key = destinationDeviceCreationTimestamp
.map(timestamp -> getTimestampTransferArchiveKey(account.getIdentifier(IdentityType.ACI), destinationDeviceId, timestamp))
.orElseGet(() -> maybeRegistrationId
.map(registrationId -> getRegistrationIdTransferArchiveKey(account.getIdentifier(IdentityType.ACI), destinationDeviceId, registrationId))
// We validate the request object so this should never happen
.orElseThrow(() -> new AssertionError("No creation timestamp or registration ID provided")));
return connection.async()
.set(key, transferArchiveJson, SetArgs.Builder.ex(RECENTLY_ADDED_TRANSFER_ARCHIVE_TTL))
.thenRun(Util.NOOP)
.toCompletableFuture();
});
} catch (final JsonProcessingException e) {
// This should never happen for well-defined objects we control
throw new UncheckedIOException(e);
@@ -1552,15 +1592,27 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
}
private static String getTransferArchiveKey(final UUID accountIdentifier,
private static String getTimestampTransferArchiveKey(final UUID accountIdentifier,
final byte destinationDeviceId,
final Instant destinationDeviceCreationTimestamp) {
Metrics.counter(TIMESTAMP_BASED_TRANSFER_ARCHIVE_KEY_COUNTER_NAME).increment();
return TRANSFER_ARCHIVE_PREFIX + accountIdentifier.toString() +
":" + destinationDeviceId +
":" + destinationDeviceCreationTimestamp.toEpochMilli();
}
private static String getRegistrationIdTransferArchiveKey(final UUID accountIdentifier,
final byte destinationDeviceId,
final int registrationId) {
Metrics.counter(REGISTRATION_ID_BASED_TRANSFER_ARCHIVE_KEY_COUNTER_NAME).increment();
return TRANSFER_ARCHIVE_PREFIX + accountIdentifier.toString() +
":" + destinationDeviceId +
":" + TRANSFER_ARCHIVE_REGISTRATION_ID_PATTERN +
":" + registrationId;
}
public CompletableFuture<Optional<RestoreAccountRequest>> waitForRestoreAccountRequest(final String token, final Duration timeout) {
return waitForPubSubKey(waitForRestoreAccountRequestFuturesByToken,
token,
@@ -1648,23 +1700,36 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
} else if (TRANSFER_ARCHIVE_KEYSPACE_PATTERN.equals(pattern) && "set".equalsIgnoreCase(message)) {
// The `- 1` here compensates for the '*' in the pattern
final String[] deviceIdentifierComponents =
channel.substring(TRANSFER_ARCHIVE_KEYSPACE_PATTERN.length() - 1).split(":", 3);
channel.substring(TRANSFER_ARCHIVE_KEYSPACE_PATTERN.length() - 1).split(":", 4);
if (deviceIdentifierComponents.length != 3) {
logger.error("Could not parse timestamped device identifier; unexpected component count");
if (deviceIdentifierComponents.length != 3 && deviceIdentifierComponents.length != 4) {
logger.error("Could not parse device identifier; unexpected component count");
return;
}
final DeviceIdentifier deviceIdentifier;
final String transferArchiveKey;
try {
final TimestampedDeviceIdentifier deviceIdentifier;
final String transferArchiveKey;
{
final UUID accountIdentifier = UUID.fromString(deviceIdentifierComponents[0]);
final byte deviceId = Byte.parseByte(deviceIdentifierComponents[1]);
final UUID accountIdentifier = UUID.fromString(deviceIdentifierComponents[0]);
final byte deviceId = Byte.parseByte(deviceIdentifierComponents[1]);
if (deviceIdentifierComponents.length == 3) {
// Parse the old transfer archive Redis key format
final Instant deviceCreationTimestamp = Instant.ofEpochMilli(Long.parseLong(deviceIdentifierComponents[2]));
deviceIdentifier = new TimestampedDeviceIdentifier(accountIdentifier, deviceId, deviceCreationTimestamp);
transferArchiveKey = getTransferArchiveKey(accountIdentifier, deviceId, deviceCreationTimestamp);
deviceIdentifier = new TimestampDeviceIdentifier(accountIdentifier, deviceId, deviceCreationTimestamp);
transferArchiveKey = getTimestampTransferArchiveKey(accountIdentifier, deviceId, deviceCreationTimestamp);
} else {
final String maybeRegistrationIdPattern = deviceIdentifierComponents[2];
if (!maybeRegistrationIdPattern.equals(TRANSFER_ARCHIVE_REGISTRATION_ID_PATTERN)) {
throw new IllegalArgumentException("Could not parse Redis key with pattern " + maybeRegistrationIdPattern);
}
final int registrationId = Integer.parseInt(deviceIdentifierComponents[3]);
if (!RegistrationIdValidator.validRegistrationId(registrationId)) {
throw new IllegalArgumentException("Invalid registration ID: " + registrationId);
}
deviceIdentifier = new RegistrationIdDeviceIdentifier(accountIdentifier, deviceId, registrationId);
transferArchiveKey = getRegistrationIdTransferArchiveKey(accountIdentifier, deviceId, registrationId);
}
Optional.ofNullable(waitForTransferArchiveFuturesByDeviceIdentifier.remove(deviceIdentifier))
@@ -1677,7 +1742,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
}));
} catch (final IllegalArgumentException e) {
logger.error("Could not parse timestamped device identifier", e);
logger.error("Could not parse device identifier", e);
}
} else if (RESTORE_ACCOUNT_REQUEST_KEYSPACE_PATTERN.equalsIgnoreCase(pattern) && "set".equalsIgnoreCase(message)) {
// The `- 1` here compensates for the '*' in the pattern
@@ -0,0 +1,12 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
/// Indicates that more than one consumer is trying to read a specific message queue at the same time.
public class ConflictingMessageConsumerException extends NoStackTraceException {
}
@@ -10,8 +10,10 @@ import java.util.Optional;
public enum DeviceCapability {
STORAGE("storage", AccountCapabilityMode.ANY_DEVICE, false, false),
TRANSFER("transfer", AccountCapabilityMode.PRIMARY_DEVICE, false, false),
DELETE_SYNC("deleteSync", AccountCapabilityMode.ALL_DEVICES, true, true),
STORAGE_SERVICE_RECORD_KEY_ROTATION("ssre2", AccountCapabilityMode.ALL_DEVICES, true, true),
@Deprecated(forRemoval = true) // Can be removed sometime after 11/10/2025
DELETE_SYNC("deleteSync", AccountCapabilityMode.ALWAYS_CAPABLE, true, true),
@Deprecated(forRemoval = true) // Can be removed sometime after 11/10/2025
STORAGE_SERVICE_RECORD_KEY_ROTATION("ssre2", AccountCapabilityMode.ALWAYS_CAPABLE, true, true),
ATTACHMENT_BACKFILL("attachmentBackfill", AccountCapabilityMode.PRIMARY_DEVICE, false, true),
SPARSE_POST_QUANTUM_RATCHET("spqr", AccountCapabilityMode.ALL_DEVICES, true, true);
@@ -28,6 +30,11 @@ public enum DeviceCapability {
* The account will have the capability iff all devices on the account have the capability
*/
ALL_DEVICES,
/**
* The account always has this capability, regardless of the constituent devices' capabilities.
* This supports retiring capabilities where older clients still need the field provided.
*/
ALWAYS_CAPABLE,
}
private final String name;
@@ -6,7 +6,9 @@
package org.whispersystems.textsecuregcm.storage;
import java.util.UUID;
import com.google.common.annotations.VisibleForTesting;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.grpc.ServiceIdentifierUtil;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
@@ -19,6 +21,9 @@ import org.whispersystems.textsecuregcm.util.UUIDUtil;
*/
public class EnvelopeUtil {
@VisibleForTesting
static final String INCLUDE_BINARY_SERVICE_ID_EXPERIMENT_NAME = "envelopeIncludeBinaryServiceIdentifier";
/**
* Converts all "compressible" UUID-like fields in the given envelope to more compact binary representations.
*
@@ -68,7 +73,22 @@ public class EnvelopeUtil {
*
* @return an envelope with binary representations of UUID-like fields expanded to string representations
*/
public static MessageProtos.Envelope expand(final MessageProtos.Envelope envelope) {
public static MessageProtos.Envelope expand(final MessageProtos.Envelope envelope,
final ExperimentEnrollmentManager experimentEnrollmentManager) {
final boolean includeBinaryServiceIdentifiers;
if (envelope.hasDestinationServiceIdBinary() || envelope.hasDestinationServiceId()) {
final ServiceIdentifier destinationIdentifier = envelope.hasDestinationServiceIdBinary()
? ServiceIdentifier.fromBytes(envelope.getDestinationServiceIdBinary().toByteArray())
: ServiceIdentifier.valueOf(envelope.getDestinationServiceId());
includeBinaryServiceIdentifiers =
experimentEnrollmentManager.isEnrolled(destinationIdentifier.uuid(), INCLUDE_BINARY_SERVICE_ID_EXPERIMENT_NAME);
} else {
includeBinaryServiceIdentifiers = false;
}
final MessageProtos.Envelope.Builder builder = envelope.toBuilder();
if (builder.hasSourceServiceIdBinary()) {
@@ -76,7 +96,10 @@ public class EnvelopeUtil {
ServiceIdentifierUtil.fromByteString(builder.getSourceServiceIdBinary());
builder.setSourceServiceId(sourceServiceId.toServiceIdentifierString());
builder.clearSourceServiceIdBinary();
if (!includeBinaryServiceIdentifiers) {
builder.clearSourceServiceIdBinary();
}
}
if (builder.hasDestinationServiceIdBinary()) {
@@ -84,14 +107,20 @@ public class EnvelopeUtil {
ServiceIdentifierUtil.fromByteString(builder.getDestinationServiceIdBinary());
builder.setDestinationServiceId(destinationServiceId.toServiceIdentifierString());
builder.clearDestinationServiceIdBinary();
if (!includeBinaryServiceIdentifiers) {
builder.clearDestinationServiceIdBinary();
}
}
if (builder.hasServerGuidBinary()) {
final UUID serverGuid = UUIDUtil.fromByteString(builder.getServerGuidBinary());
builder.setServerGuid(serverGuid.toString());
builder.clearServerGuidBinary();
if (!includeBinaryServiceIdentifiers) {
builder.clearServerGuidBinary();
}
}
if (builder.hasUpdatedPniBinary()) {
@@ -5,29 +5,36 @@
package org.whispersystems.textsecuregcm.storage;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Metrics;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import org.whispersystems.textsecuregcm.controllers.KeysController;
import org.whispersystems.textsecuregcm.entities.ECPreKey;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.util.Futures;
import org.whispersystems.textsecuregcm.util.Optionals;
import reactor.core.publisher.Flux;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
import javax.annotation.Nullable;
public class KeysManager {
// KeysController for backwards compatibility
private static final String GET_KEYS_COUNTER_NAME = MetricsUtil.name(KeysController.class, "getKeys");
private final SingleUseECPreKeyStore ecPreKeys;
private final SingleUseKEMPreKeyStore pqPreKeys;
private final PagedSingleUseKEMPreKeyStore pagedPqPreKeys;
private final RepeatedUseECSignedPreKeyStore ecSignedPreKeys;
private final RepeatedUseKEMSignedPreKeyStore pqLastResortKeys;
private final ExperimentEnrollmentManager experimentEnrollmentManager;
public static String PAGED_KEYS_EXPERIMENT_NAME = "pagedPreKeys";
private static final String TAKE_PQ_NAME = MetricsUtil.name(KeysManager.class, "takePq");
@@ -36,14 +43,12 @@ public class KeysManager {
final SingleUseKEMPreKeyStore pqPreKeys,
final PagedSingleUseKEMPreKeyStore pagedPqPreKeys,
final RepeatedUseECSignedPreKeyStore ecSignedPreKeys,
final RepeatedUseKEMSignedPreKeyStore pqLastResortKeys,
final ExperimentEnrollmentManager experimentEnrollmentManager) {
final RepeatedUseKEMSignedPreKeyStore pqLastResortKeys) {
this.ecPreKeys = ecPreKeys;
this.pqPreKeys = pqPreKeys;
this.pagedPqPreKeys = pagedPqPreKeys;
this.ecSignedPreKeys = ecSignedPreKeys;
this.pqLastResortKeys = pqLastResortKeys;
this.experimentEnrollmentManager = experimentEnrollmentManager;
}
public TransactWriteItem buildWriteItemForEcSignedPreKey(final UUID identifier,
@@ -105,29 +110,26 @@ public class KeysManager {
public CompletableFuture<Void> storeKemOneTimePreKeys(final UUID identifier, final byte deviceId,
final List<KEMSignedPreKey> preKeys) {
final boolean enrolledInPagedKeys = experimentEnrollmentManager.isEnrolled(identifier, PAGED_KEYS_EXPERIMENT_NAME);
final CompletableFuture<Void> deleteOtherKeys = enrolledInPagedKeys
? pqPreKeys.delete(identifier, deviceId)
: pagedPqPreKeys.delete(identifier, deviceId);
return deleteOtherKeys.thenCompose(ignored -> enrolledInPagedKeys
? pagedPqPreKeys.store(identifier, deviceId, preKeys)
: pqPreKeys.store(identifier, deviceId, preKeys));
// Unconditionally delete keys in old format keystore, then write to the pagedPqPreKeys store
return pqPreKeys.delete(identifier, deviceId)
.thenCompose(_ -> pagedPqPreKeys.store(identifier, deviceId, preKeys));
}
public CompletableFuture<Optional<ECPreKey>> takeEC(final UUID identifier, final byte deviceId) {
@VisibleForTesting
CompletableFuture<Optional<ECPreKey>> takeEC(final UUID identifier, final byte deviceId) {
return ecPreKeys.take(identifier, deviceId);
}
public CompletableFuture<Optional<KEMSignedPreKey>> takePQ(final UUID identifier, final byte deviceId) {
final boolean enrolledInPagedKeys = experimentEnrollmentManager.isEnrolled(identifier, PAGED_KEYS_EXPERIMENT_NAME);
return tagTakePQ(pagedPqPreKeys.take(identifier, deviceId), PQSource.PAGE, enrolledInPagedKeys)
@VisibleForTesting
CompletableFuture<Optional<KEMSignedPreKey>> takePQ(final UUID identifier, final byte deviceId) {
return tagTakePQ(pagedPqPreKeys.take(identifier, deviceId), PQSource.PAGE)
.thenCompose(maybeSingleUsePreKey -> maybeSingleUsePreKey
.map(ignored -> CompletableFuture.completedFuture(maybeSingleUsePreKey))
.orElseGet(() -> tagTakePQ(pqPreKeys.take(identifier, deviceId), PQSource.ROW, enrolledInPagedKeys)))
.orElseGet(() -> tagTakePQ(pqPreKeys.take(identifier, deviceId), PQSource.ROW)))
.thenCompose(maybeSingleUsePreKey -> maybeSingleUsePreKey
.map(singleUsePreKey -> CompletableFuture.completedFuture(maybeSingleUsePreKey))
.orElseGet(() -> tagTakePQ(pqLastResortKeys.find(identifier, deviceId), PQSource.LAST_RESORT, enrolledInPagedKeys)));
.orElseGet(() -> tagTakePQ(pqLastResortKeys.find(identifier, deviceId), PQSource.LAST_RESORT)));
}
private enum PQSource {
@@ -135,7 +137,7 @@ public class KeysManager {
ROW,
LAST_RESORT
}
private CompletableFuture<Optional<KEMSignedPreKey>> tagTakePQ(CompletableFuture<Optional<KEMSignedPreKey>> prekey, final PQSource source, final boolean enrolledInPagedKeys) {
private CompletableFuture<Optional<KEMSignedPreKey>> tagTakePQ(CompletableFuture<Optional<KEMSignedPreKey>> prekey, final PQSource source) {
return prekey.thenApply(maybeSingleUsePreKey -> {
final Optional<String> maybeSourceTag = maybeSingleUsePreKey
// If we found a PK, use this source tag
@@ -143,10 +145,7 @@ public class KeysManager {
// If we didn't and this is our last resort, we didn't find a PK
.or(() -> source == PQSource.LAST_RESORT ? Optional.of("absent") : Optional.empty());
maybeSourceTag.ifPresent(sourceTag -> {
Metrics.counter(TAKE_PQ_NAME,
"source", sourceTag,
"enrolled", Boolean.toString(enrolledInPagedKeys))
.increment();
Metrics.counter(TAKE_PQ_NAME, "source", sourceTag).increment();
});
return maybeSingleUsePreKey;
});
@@ -165,9 +164,9 @@ public class KeysManager {
}
public CompletableFuture<Integer> getPqCount(final UUID identifier, final byte deviceId) {
return pagedPqPreKeys.getCount(identifier, deviceId).thenCompose(count -> count == 0
? pqPreKeys.getCount(identifier, deviceId)
: CompletableFuture.completedFuture(count));
// We only return the paged prekey count to encourage clients to upload more prekeys if they only have prekeys
// stored in the previous key store format
return pagedPqPreKeys.getCount(identifier, deviceId);
}
public CompletableFuture<Void> deleteSingleUsePreKeys(final UUID identifier) {
@@ -209,4 +208,36 @@ public class KeysManager {
public CompletableFuture<Void> pruneDeadPage(final UUID identifier, final byte deviceId, final UUID pageId) {
return pagedPqPreKeys.deleteBundleFromS3(identifier, deviceId, pageId);
}
public record DevicePreKeys(
ECSignedPreKey ecSignedPreKey,
Optional<ECPreKey> ecPreKey,
KEMSignedPreKey kemSignedPreKey) {}
public CompletableFuture<Optional<DevicePreKeys>> takeDevicePreKeys(
final byte deviceId,
final ServiceIdentifier serviceIdentifier,
final @Nullable String userAgent) {
final UUID uuid = serviceIdentifier.uuid();
return Futures.zipWith(
this.takeEC(uuid, deviceId),
this.getEcSignedPreKey(uuid, deviceId),
this.takePQ(uuid, deviceId),
(maybeUnsignedEcPreKey, maybeSignedEcPreKey, maybePqPreKey) -> {
Metrics.counter(GET_KEYS_COUNTER_NAME, Tags.of(
UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of("identityType", serviceIdentifier.identityType().name()),
Tag.of("oneTimeEcKeyAvailable", String.valueOf(maybeUnsignedEcPreKey.isPresent())),
Tag.of("signedEcKeyAvailable", String.valueOf(maybeSignedEcPreKey.isPresent())),
Tag.of("pqKeyAvailable", String.valueOf(maybePqPreKey.isPresent()))))
.increment();
// The pq prekey and signed EC prekey should never be null for an existing account. This should only happen
// if the account or device has been removed and the read was split, so we can return empty in those cases.
return Optionals.zipWith(maybeSignedEcPreKey, maybePqPreKey, (signedEcPreKey, pqPreKey) ->
new DevicePreKeys(signedEcPreKey, maybeUnsignedEcPreKey, pqPreKey));
})
.toCompletableFuture();
}
}
@@ -22,6 +22,7 @@ import java.util.Locale;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.IntStream;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -58,16 +59,15 @@ public class MessagePersister implements Managed {
private static final Counter TRIMMED_MESSAGE_COUNTER = Metrics.counter(name(MessagePersister.class, "trimmedMessage"));
private static final Counter TRIMMED_MESSAGE_BYTES_COUNTER = Metrics.counter(name(MessagePersister.class, "trimmedMessageBytes"));
private static final DistributionSummary QUEUE_COUNT_DISTRIBUTION_SUMMARY = DistributionSummary.builder(
name(MessagePersister.class, "queueCount"))
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry);
private static final String QUEUE_SIZE_DISTRIBUTION_SUMMARY_NAME = name(MessagePersister.class, "queueSize");
static final int QUEUE_BATCH_LIMIT = 100;
static final int MESSAGE_BATCH_LIMIT = 100;
private static final DistributionSummary QUEUE_COUNT_DISTRIBUTION_SUMMARY = DistributionSummary.builder(
name(MessagePersister.class, "queueCount"))
.register(Metrics.globalRegistry);
private static final long EXCEPTION_PAUSE_MILLIS = Duration.ofSeconds(3).toMillis();
private static final int CONSECUTIVE_EMPTY_CACHE_REMOVAL_LIMIT = 3;
@@ -0,0 +1,29 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Flow;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
/// A message stream publishes an ordered stream of Signal messages from a destination device's queue and provides a
/// mechanism for consumers to acknowledge receipt of delivered messages.
public interface MessageStream {
/// Publishes a non-terminating stream of [MessageStreamEntry.Envelope] entities and at most one
/// [MessageStreamEntry.QueueEmpty].
///
/// @return a non-terminating stream of message stream entries
Flow.Publisher<MessageStreamEntry> getMessages();
/// Acknowledges receipt of the given message. Implementations may delete the message immediately or defer deletion for
/// inclusion in a more efficient batch deletion.
///
/// @param message the message to acknowledge
///
/// @return a future that completes when the message stream has processed the acknowledgement
CompletableFuture<Void> acknowledgeMessage(MessageProtos.Envelope message);
}
@@ -0,0 +1,26 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
/// A `MessageStreamEntr` is an entity that can be emitted by the publisher returned by [MessageStream#getMessages()].
/// Message stream entries either produce an individual message (see [Envelope]) or that the initial contents of a
/// message queue have been drained (see [QueueEmpty]).
public sealed interface MessageStreamEntry permits MessageStreamEntry.Envelope, MessageStreamEntry.QueueEmpty {
/// A message stream entry that carries a single message.
///
/// @param message the message emitted by the publisher
record Envelope(MessageProtos.Envelope message) implements MessageStreamEntry {
}
/// A message stream entry that indicates that the initial contents of a message queue have been emitted by the
/// publisher; any [Envelope] entries after a `QueueEmpty` entry arrived after caller started reading
/// messages from the queue.
record QueueEmpty() implements MessageStreamEntry {
}
}
@@ -42,6 +42,7 @@ import org.signal.libsignal.protocol.ServiceId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
@@ -52,6 +53,7 @@ import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;
import reactor.util.retry.RetrySpec;
/**
* Manages short-term storage of messages in Redis. Messages are frequently delivered to their destination and deleted
@@ -117,6 +119,7 @@ public class MessagesCache {
private final ExecutorService messageDeletionExecutorService;
// messageDeletionExecutorService wrapped into a reactor Scheduler
private final Scheduler messageDeletionScheduler;
private final ExperimentEnrollmentManager experimentEnrollmentManager;
private final MessagesCacheInsertScript insertScript;
private final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript;
@@ -166,7 +169,8 @@ public class MessagesCache {
public MessagesCache(final FaultTolerantRedisClusterClient redisCluster,
final Scheduler messageDeliveryScheduler,
final ExecutorService messageDeletionExecutorService,
final Clock clock)
final Clock clock,
final ExperimentEnrollmentManager experimentEnrollmentManager)
throws IOException {
this(
@@ -174,6 +178,7 @@ public class MessagesCache {
messageDeliveryScheduler,
messageDeletionExecutorService,
clock,
experimentEnrollmentManager,
new MessagesCacheInsertScript(redisCluster),
new MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript(redisCluster),
new MessagesCacheGetItemsScript(redisCluster),
@@ -189,6 +194,7 @@ public class MessagesCache {
MessagesCache(final FaultTolerantRedisClusterClient redisCluster,
final Scheduler messageDeliveryScheduler,
final ExecutorService messageDeletionExecutorService, final Clock clock,
final ExperimentEnrollmentManager experimentEnrollmentManager,
final MessagesCacheInsertScript insertScript,
final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript,
final MessagesCacheGetItemsScript getItemsScript, final MessagesCacheRemoveByGuidScript removeByGuidScript,
@@ -203,6 +209,7 @@ public class MessagesCache {
this.messageDeliveryScheduler = messageDeliveryScheduler;
this.messageDeletionExecutorService = messageDeletionExecutorService;
this.messageDeletionScheduler = Schedulers.fromExecutorService(messageDeletionExecutorService, "messageDeletion");
this.experimentEnrollmentManager = experimentEnrollmentManager;
this.insertScript = insertScript;
this.insertMrmScript = insertMrmScript;
@@ -284,11 +291,6 @@ public class MessagesCache {
}
public boolean hasMessages(final UUID destinationUuid, final byte destinationDevice) {
return redisCluster.withBinaryCluster(
connection -> connection.sync().zcard(getMessageQueueKey(destinationUuid, destinationDevice)) > 0);
}
public CompletableFuture<Boolean> hasMessagesAsync(final UUID destinationUuid, final byte destinationDevice) {
return redisCluster.withBinaryCluster(connection ->
connection.async().zcard(getMessageQueueKey(destinationUuid, destinationDevice))
@@ -521,6 +523,7 @@ public class MessagesCache {
long messageId, int pageSize) {
return getItemsScript.execute(destinationUuid, destinationDevice, pageSize, messageId)
.retryWhen(RetrySpec.backoff(4, Duration.ofSeconds(1)).maxBackoff(Duration.ofSeconds(4)))
.map(queueItems -> {
logger.trace("Processing page: {}", messageId);
@@ -753,9 +756,9 @@ public class MessagesCache {
return Byte.parseByte(queueName.substring(queueName.lastIndexOf("::") + 2, queueName.lastIndexOf('}')));
}
private static MessageProtos.Envelope parseEnvelope(final byte[] envelopeBytes)
private MessageProtos.Envelope parseEnvelope(final byte[] envelopeBytes)
throws InvalidProtocolBufferException {
return EnvelopeUtil.expand(MessageProtos.Envelope.parseFrom(envelopeBytes));
return EnvelopeUtil.expand(MessageProtos.Envelope.parseFrom(envelopeBytes), experimentEnrollmentManager);
}
}
@@ -16,7 +16,7 @@ import java.util.concurrent.CompletableFuture;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.push.ClientEvent;
import org.whispersystems.textsecuregcm.push.NewMessageAvailableEvent;
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
@@ -53,7 +53,7 @@ class MessagesCacheInsertScript {
MessagesCache.getMessageQueueKey(destinationUuid, destinationDevice), // queueKey
MessagesCache.getMessageQueueMetadataKey(destinationUuid, destinationDevice), // queueMetadataKey
MessagesCache.getQueueIndexKey(destinationUuid, destinationDevice), // queueTotalIndexKey
WebSocketConnectionEventManager.getClientEventChannel(destinationUuid, destinationDevice) // eventChannelKey
RedisMessageAvailabilityManager.getClientEventChannel(destinationUuid, destinationDevice) // eventChannelKey
);
final List<byte[]> args = new ArrayList<>(Arrays.asList(
@@ -8,7 +8,7 @@ package org.whispersystems.textsecuregcm.storage;
import io.lettuce.core.ScriptOutputType;
import org.whispersystems.textsecuregcm.push.ClientEvent;
import org.whispersystems.textsecuregcm.push.MessagesPersistedEvent;
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import java.io.IOException;
@@ -35,7 +35,7 @@ class MessagesCacheUnlockQueueScript {
void execute(final UUID accountIdentifier, final byte deviceId) {
final List<byte[]> keys = List.of(
MessagesCache.getPersistInProgressKey(accountIdentifier, deviceId), // persistInProgressKey
WebSocketConnectionEventManager.getClientEventChannel(accountIdentifier, deviceId) // eventChannelKey
RedisMessageAvailabilityManager.getClientEventChannel(accountIdentifier, deviceId) // eventChannelKey
);
unlockQueueScript.executeBinary(keys, MESSAGES_PERSISTED_EVENT_ARGS);
@@ -27,6 +27,7 @@ import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@@ -69,11 +70,13 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
private final Duration timeToLive;
private final ExecutorService messageDeletionExecutor;
private final Scheduler messageDeletionScheduler;
private final ExperimentEnrollmentManager experimentEnrollmentManager;
private static final Logger logger = LoggerFactory.getLogger(MessagesDynamoDb.class);
public MessagesDynamoDb(DynamoDbClient dynamoDb, DynamoDbAsyncClient dynamoDbAsyncClient, String tableName,
Duration timeToLive, ExecutorService messageDeletionExecutor) {
Duration timeToLive, ExecutorService messageDeletionExecutor,
final ExperimentEnrollmentManager experimentEnrollmentManager) {
super(dynamoDb);
this.dbAsyncClient = dynamoDbAsyncClient;
@@ -82,6 +85,7 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
this.messageDeletionExecutor = messageDeletionExecutor;
this.messageDeletionScheduler = Schedulers.fromExecutor(messageDeletionExecutor);
this.experimentEnrollmentManager = experimentEnrollmentManager;
}
public void store(final List<MessageProtos.Envelope> messages, final UUID destinationAccountUuid,
@@ -151,7 +155,7 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
return dbAsyncClient.queryPaginator(queryRequest).items()
.map(message -> {
try {
return convertItemToEnvelope(message);
return convertItemToEnvelope(message, experimentEnrollmentManager);
} catch (final InvalidProtocolBufferException e) {
logger.error("Failed to parse envelope", e);
return null;
@@ -189,7 +193,7 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
.mapNotNull(deleteItemResponse -> {
try {
if (deleteItemResponse.attributes() != null && deleteItemResponse.attributes().containsKey(KEY_PARTITION)) {
return convertItemToEnvelope(deleteItemResponse.attributes());
return convertItemToEnvelope(deleteItemResponse.attributes(), experimentEnrollmentManager);
}
} catch (final InvalidProtocolBufferException e) {
logger.error("Failed to parse envelope", e);
@@ -213,7 +217,7 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
.thenApplyAsync(deleteItemResponse -> {
if (deleteItemResponse.attributes() != null && deleteItemResponse.attributes().containsKey(KEY_PARTITION)) {
try {
return Optional.of(convertItemToEnvelope(deleteItemResponse.attributes()));
return Optional.of(convertItemToEnvelope(deleteItemResponse.attributes(), experimentEnrollmentManager));
} catch (final InvalidProtocolBufferException e) {
logger.error("Failed to parse envelope", e);
}
@@ -224,10 +228,11 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
}
@VisibleForTesting
static MessageProtos.Envelope convertItemToEnvelope(final Map<String, AttributeValue> item)
throws InvalidProtocolBufferException {
static MessageProtos.Envelope convertItemToEnvelope(final Map<String, AttributeValue> item,
final ExperimentEnrollmentManager experimentEnrollmentManager) throws InvalidProtocolBufferException {
return EnvelopeUtil.expand(MessageProtos.Envelope.parseFrom(item.get(KEY_ENVELOPE_BYTES).b().asByteArray()));
return EnvelopeUtil.expand(MessageProtos.Envelope.parseFrom(item.get(KEY_ENVELOPE_BYTES).b().asByteArray()),
experimentEnrollmentManager);
}
private long getTtlForMessage(MessageProtos.Envelope message) {
@@ -33,6 +33,7 @@ import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
import org.whispersystems.textsecuregcm.util.Pair;
import reactor.core.observability.micrometer.Micrometer;
import reactor.core.publisher.Flux;
@@ -56,6 +57,7 @@ public class MessagesManager {
private final MessagesDynamoDb messagesDynamoDb;
private final MessagesCache messagesCache;
private final RedisMessageAvailabilityManager redisMessageAvailabilityManager;
private final ReportMessageManager reportMessageManager;
private final ExecutorService messageDeletionExecutor;
private final Clock clock;
@@ -63,12 +65,14 @@ public class MessagesManager {
public MessagesManager(
final MessagesDynamoDb messagesDynamoDb,
final MessagesCache messagesCache,
final RedisMessageAvailabilityManager redisMessageAvailabilityManager,
final ReportMessageManager reportMessageManager,
final ExecutorService messageDeletionExecutor,
final Clock clock) {
this.messagesDynamoDb = messagesDynamoDb;
this.messagesCache = messagesCache;
this.redisMessageAvailabilityManager = redisMessageAvailabilityManager;
this.reportMessageManager = reportMessageManager;
this.messageDeletionExecutor = messageDeletionExecutor;
this.clock = clock;
@@ -82,7 +86,7 @@ public class MessagesManager {
*
* @return a map of device IDs to a device's presence state (i.e. if the device has an active event listener)
*
* @see org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager
* @see RedisMessageAvailabilityManager
*/
public Map<Byte, Boolean> insert(final UUID accountIdentifier, final Map<Byte, Envelope> messagesByDeviceId) {
return insertAsync(accountIdentifier, messagesByDeviceId).join();
@@ -127,7 +131,7 @@ public class MessagesManager {
* @return a map of accounts to maps of device IDs to a device's presence state (i.e. if the device has an active
* event listener)
*
* @see org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager
* @see RedisMessageAvailabilityManager
*/
public CompletableFuture<Map<Account, Map<Byte, Boolean>>> insertMultiRecipientMessage(
final SealedSenderMultiRecipientMessage multiRecipientMessage,
@@ -220,6 +224,10 @@ public class MessagesManager {
return getMessagesForDevice(destinationUuid, destinationDevice, null, cachedMessagesOnly);
}
public MessageStream getMessages(final UUID destinationUuid, final Device destinationDevice) {
return new RedisDynamoDbMessageStream(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, destinationUuid, destinationDevice);
}
private Publisher<Envelope> getMessagesForDevice(UUID destinationUuid, Device destinationDevice,
@Nullable Integer limit, final boolean cachedMessagesOnly) {
@@ -0,0 +1,327 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import io.micrometer.core.instrument.Metrics;
import java.util.UUID;
import java.util.concurrent.Flow;
import javax.annotation.Nullable;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscription;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.push.MessageAvailabilityListener;
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
import reactor.core.observability.micrometer.Micrometer;
import reactor.core.publisher.BaseSubscriber;
import reactor.core.publisher.Flux;
/// A Redis/DynamoDB message publisher produces a non-terminating stream of messages for a specific device. It listens
/// for message availability signals from [RedisMessageAvailabilityManager] and emits new messages to its subscriber
/// when available.
///
/// This publisher supports only a single subscriber. It assumes that subscribers acknowledge (delete) messages as they
/// read the messages, and may emit duplicate messages if subscribers do not acknowledge messages before requesting more
/// messages.
class RedisDynamoDbMessagePublisher implements MessageAvailabilityListener, Flow.Publisher<MessageStreamEntry> {
private final MessagesDynamoDb messagesDynamoDb;
private final MessagesCache messagesCache;
private final RedisMessageAvailabilityManager redisMessageAvailabilityManager;
private final UUID accountIdentifier;
private final Device device;
// Indicates which data source(s) we think might contain messages for the destination device. Messages initially land
// in Redis, but are eventually "persisted" to DynamoDB. This state changes in response to signals this publisher
// receives as a MessageAvailabilityListener. As an initial state, we assume that we have messages in both DynamoDB
// and Redis.
private StoredMessageState storedMessageState = StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE;
// The number of messages the downstream subscriber is ready to receive. This changes in response to new requests from
// the downstream subscriber and gets decremented every time we publish a message.
private long unmetDemand = 0;
// Although technically nullable, operation of this publisher really begins once we get a subscriber. This publisher
// supports only a single subscriber.
@Nullable private Flow.Subscriber<? super MessageStreamEntry> subscriber;
// If terminated (i.e. by an error or by downstream cancellation), this publisher will stop emitting signals. Once
// terminated, a publisher cannot be un-terminated.
private boolean terminated = false;
// This publisher will emit exactly one "queue empty" signal once the initial contents of the message queue have been
// drained. Once emitted, this flag is set to `true` and will never change again.
private boolean publishedQueueEmptySignal = false;
// …but we may not be able to send the "queue empty" signal downstream immediately if there's no demand. This flag
// tracks whether we're ready to publish a "queue empty" signal, regardless of whether we've actually sent it. Once
// this flag is set to `true`, it will never change again.
private boolean readyToPublishQueueEmptySignal = false;
// A message source subscriber subscribes to messages from upstream data sources (i.e. DynamoDB and Redis), and this
// publisher relays signals the message source subscriber to the downstream subscriber. The message source subscriber
// may be null if we're not actively fetching messages from an upstream source and changes every time an upstream
// publisher completes.
@Nullable private MessageSourceSubscriber messageSourceSubscriber;
private static final String GET_MESSAGES_FOR_DEVICE_FLUX_NAME =
name(RedisDynamoDbMessagePublisher.class, "getMessagesForDevice");
private enum StoredMessageState {
// Indicates that stored messages are available in at least DynamoDB and possibly also Redis
PERSISTED_NEW_MESSAGES_AVAILABLE,
// Indicates that messages are available in Redis, but have not yet been persisted to DynamoDB
CACHED_NEW_MESSAGES_AVAILABLE,
// Indicates that no new messages are available in either Redis or DynamoDB
EMPTY
}
/// A message source subscriber subscribes to upstream message source publishers and relays signals to the downstream
/// subscriber via the parent `RedisDynamoDbMessagePublisher`.
private static class MessageSourceSubscriber extends BaseSubscriber<MessageProtos.Envelope> {
private final RedisDynamoDbMessagePublisher redisDynamoDbMessagePublisher;
private MessageSourceSubscriber(RedisDynamoDbMessagePublisher redisDynamoDbMessagePublisher) {
this.redisDynamoDbMessagePublisher = redisDynamoDbMessagePublisher;
}
@Override
protected void hookOnSubscribe(final Subscription subscription) {
final long unmetDemand = redisDynamoDbMessagePublisher.getUnmetDemand();
// If we already have some unmet demand, pass that on to the upstream publisher immediately on subscribing
if (unmetDemand > 0) {
subscription.request(unmetDemand);
}
}
@Override
protected void hookOnNext(final MessageProtos.Envelope message) {
redisDynamoDbMessagePublisher.handleNextMessage(message);
}
@Override
protected void hookOnComplete() {
redisDynamoDbMessagePublisher.handleMessageSourceComplete();
}
@Override
protected void hookOnError(final Throwable throwable) {
redisDynamoDbMessagePublisher.handleMessageSourceError(throwable);
}
}
RedisDynamoDbMessagePublisher(final MessagesDynamoDb messagesDynamoDb,
final MessagesCache messagesCache,
final RedisMessageAvailabilityManager redisMessageAvailabilityManager,
final UUID accountIdentifier,
final Device device) {
this.messagesDynamoDb = messagesDynamoDb;
this.messagesCache = messagesCache;
this.redisMessageAvailabilityManager = redisMessageAvailabilityManager;
this.accountIdentifier = accountIdentifier;
this.device = device;
}
@Override
public synchronized void subscribe(final Flow.Subscriber<? super MessageStreamEntry> subscriber) {
if (this.subscriber != null) {
subscriber.onError(new IllegalStateException("Redis/DynamoDB message publisher only allows one subscriber"));
return;
}
this.subscriber = subscriber;
// Listen for signals indicating that new messages are available in Redis, that messages have been persisted from
// Redis to DynamoDB, or that there's a conflicting message reader connected somewhere else
redisMessageAvailabilityManager.handleClientConnected(accountIdentifier, device.getId(), this);
subscriber.onSubscribe(new Flow.Subscription() {
@Override
public void request(final long n) {
addDemand(n);
}
@Override
public void cancel() {
terminate();
}
});
}
@Override
public synchronized void handleNewMessageAvailable() {
// We only need to take action if we think there aren't already messages to pass downstream. Any other stored
// message state implies that we're either actively sending messages downstream or we're waiting for demand from the
// downstream subscriber and don't need to take any action now. We'll call `maybeGenerateMessageSource` either when
// we receive a request for more messages or when the current upstream publisher completes.
if (storedMessageState == StoredMessageState.EMPTY) {
storedMessageState = StoredMessageState.CACHED_NEW_MESSAGES_AVAILABLE;
maybeGenerateMessageSource();
}
}
@Override
public synchronized void handleMessagesPersisted() {
// We only need to take action if we think there aren't already messages in DynamoDB. If we're already aware of
// messages in DynamoDB, then we're either actively sending messages downstream or we're waiting for demand from the
// downstream subscriber and don't need to take any action now. We'll call `maybeGenerateMessageSource` either when
// we receive a request for more messages or when the current upstream publisher completes.
if (storedMessageState != StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE) {
storedMessageState = StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE;
maybeGenerateMessageSource();
}
}
@Override
public synchronized void handleConflictingMessageConsumer() {
// We don't register as a listener for conflicting consumer signals until we have a subscriber
assert subscriber != null;
if (!terminated) {
subscriber.onError(new ConflictingMessageConsumerException());
}
terminate();
}
private synchronized boolean maybeSendQueueEmptySignal() {
// Regardless of any other state, don't do anything if terminated
if (terminated) {
return false;
}
// The machinery that produces messages won't activate until we have a subscriber
assert subscriber != null;
if (readyToPublishQueueEmptySignal && !publishedQueueEmptySignal && getUnmetDemand() > 0) {
subscriber.onNext(new MessageStreamEntry.QueueEmpty());
unmetDemand -= 1;
assert unmetDemand >= 0;
publishedQueueEmptySignal = true;
return true;
}
return false;
}
private synchronized void maybeGenerateMessageSource() {
// Regardless of any other state, don't do anything if terminated
if (terminated) {
return;
}
if (storedMessageState == StoredMessageState.EMPTY || unmetDemand == 0) {
// We don't think there are any messages in either source or there's no demand for messages; either way, wait for
// things to change before trying to generate a message source
return;
}
// We maybe be able to skip reading from DynamoDB entirely if we think messages are only stored in Redis
final Publisher<MessageProtos.Envelope> dynamoPublisher =
storedMessageState == StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE
? messagesDynamoDb.load(accountIdentifier, device, null)
: Flux.empty();
final Publisher<MessageProtos.Envelope> redisPublisher = messagesCache.get(accountIdentifier, device.getId());
final Flux<MessageProtos.Envelope> messageSource = Flux.concat(dynamoPublisher, redisPublisher)
.name(GET_MESSAGES_FOR_DEVICE_FLUX_NAME)
.tap(Micrometer.metrics(Metrics.globalRegistry));
messageSourceSubscriber = new MessageSourceSubscriber(this);
messageSource.subscribe(messageSourceSubscriber);
// If nothing else happens before the DynamoDB/Redis publisher completes, then we'll have emptied all stored
// messages; new signals about persisted messages or newly-arrived messages will change this state
storedMessageState = StoredMessageState.EMPTY;
}
private synchronized void handleNextMessage(final MessageProtos.Envelope message) {
// The machinery that produces messages won't activate until we have a subscriber
assert subscriber != null;
if (!terminated) {
unmetDemand -= 1;
assert unmetDemand >= 0;
subscriber.onNext(new MessageStreamEntry.Envelope(message));
}
}
private synchronized void handleMessageSourceComplete() {
// The machinery that produces messages won't activate until we have a subscriber
assert subscriber != null;
messageSourceSubscriber = null;
// Attempt to send a "queue empty" signal if we haven't already
readyToPublishQueueEmptySignal = true;
maybeSendQueueEmptySignal();
// New messages may have arrived already; fetch them if possible
maybeGenerateMessageSource();
}
private synchronized void handleMessageSourceError(final Throwable throwable) {
// The machinery that produces messages won't activate until we have a subscriber
assert subscriber != null;
if (!terminated) {
subscriber.onError(throwable);
terminate();
}
}
private synchronized void addDemand(final long demand) {
if (demand <= 0) {
throw new IllegalArgumentException("Demand must be positive");
}
unmetDemand += demand;
// We may have been waiting for non-zero demand before sending a "queue empty" signal
final boolean sentQueueEmptySignal = maybeSendQueueEmptySignal();
// This is a little tricky; if we already have a subscriber, we only want to request NEW demand, not the total
// outstanding demand. On top of that, we may have consumed some demand by sending a "queue empty" message.
final long newDemand = demand - (sentQueueEmptySignal ? 1 : 0);
if (newDemand > 0) {
if (messageSourceSubscriber != null) {
messageSourceSubscriber.request(newDemand);
} else {
maybeGenerateMessageSource();
}
}
}
private synchronized long getUnmetDemand() {
return unmetDemand;
}
private synchronized void terminate() {
if (!terminated) {
terminated = true;
// Stop receiving signals about new messages/conflicting consumers
redisMessageAvailabilityManager.handleClientDisconnected(accountIdentifier, device.getId());
if (messageSourceSubscriber != null) {
messageSourceSubscriber.dispose();
}
}
}
}
@@ -0,0 +1,59 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Flow;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
import org.whispersystems.textsecuregcm.util.Util;
/// A [MessageStream] implementation that produces message from a joint DynamoDB/Redis message store.
public class RedisDynamoDbMessageStream implements MessageStream {
private final MessagesDynamoDb messagesDynamoDb;
private final MessagesCache messagesCache;
private final UUID accountIdentifier;
private final Device device;
private final RedisDynamoDbMessagePublisher messagePublisher;
public RedisDynamoDbMessageStream(final MessagesDynamoDb messagesDynamoDb,
final MessagesCache messagesCache,
final RedisMessageAvailabilityManager redisMessageAvailabilityManager,
final UUID accountIdentifier,
final Device device) {
this.messagesDynamoDb = messagesDynamoDb;
this.messagesCache = messagesCache;
this.accountIdentifier = accountIdentifier;
this.device = device;
this.messagePublisher = new RedisDynamoDbMessagePublisher(messagesDynamoDb,
messagesCache,
redisMessageAvailabilityManager,
accountIdentifier,
device);
}
@Override
public Flow.Publisher<MessageStreamEntry> getMessages() {
return messagePublisher;
}
@Override
public CompletableFuture<Void> acknowledgeMessage(final MessageProtos.Envelope message) {
final UUID guid = UUID.fromString(message.getServerGuid());
return messagesCache.remove(accountIdentifier, device.getId(), guid)
.thenCompose(removed -> removed.map(_ -> CompletableFuture.<Void>completedFuture(null))
.orElseGet(() ->
messagesDynamoDb.deleteMessage(accountIdentifier, device, guid, message.getServerTimestamp())
.thenRun(Util.NOOP)));
}
}
@@ -0,0 +1,157 @@
package org.whispersystems.textsecuregcm.storage.foundationdb;
import com.apple.foundationdb.Database;
import com.apple.foundationdb.MutationType;
import com.apple.foundationdb.Transaction;
import com.apple.foundationdb.subspace.Subspace;
import com.apple.foundationdb.tuple.Tuple;
import com.apple.foundationdb.tuple.Versionstamp;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.hash.Hashing;
import java.time.Clock;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.Function;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.util.Conversions;
import org.whispersystems.textsecuregcm.util.Pair;
/// An implementation of a message store backed by FoundationDB.
///
/// @implNote The layout of elements in FoundationDB is as follows:
/// * messages
/// * {aci}
/// * messageAvailableWatch => versionstamp
/// * {deviceId}
/// * presence => server_id | last_seen_seconds_since_epoch
/// * queue
/// * {versionstamp_1} => envelope_1
/// * {versionstamp_2} => envelope_2
public class FoundationDbMessageStore {
private final Database[] databases;
private final Executor executor;
private final Clock clock;
private static final Subspace MESSAGES_SUBSPACE = new Subspace(Tuple.from("M"));
private static final int MAX_SECONDS_SINCE_UPDATE_FOR_PRESENCE = 300;
public FoundationDbMessageStore(final Database[] databases, final Executor executor, final Clock clock) {
this.databases = databases;
this.executor = executor;
this.clock = clock;
}
/// Insert a message bundle for a set of devices belonging to a single recipient. A message may not be inserted if the
/// device is not present (as determined from its presence key) and the message is ephemeral. If all messages in the
/// bundle don't end up being inserted, we won't return a versionstamp since the transaction was read-only.
///
/// @param aci destination account identifier
/// @param messagesByDeviceId a map of deviceId => message envelope
/// @return a future that completes with a [Versionstamp] of the committed transaction if at least one message was
/// inserted
public CompletableFuture<Optional<Versionstamp>> insert(final AciServiceIdentifier aci,
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId) {
// We use Database#runAsync and not Database#run here because the latter would commit the transaction synchronously
// and we would like to avoid any potential blocking in native code that could unexpectedly pin virtual threads. See https://forums.foundationdb.org/t/fdbdatabase-usage-from-java-api/593/2
// for details.
return getShardForAci(aci).runAsync(transaction -> insert(aci, messagesByDeviceId, transaction)
.thenApply(hasMutations -> {
if (hasMutations) {
return transaction.getVersionstamp();
}
return CompletableFuture.completedFuture((byte[]) null);
}))
.thenComposeAsync(Function.identity(), executor)
.thenApply(versionstampBytes -> Optional.ofNullable(versionstampBytes).map(Versionstamp::complete));
}
private CompletableFuture<Boolean> insert(final AciServiceIdentifier aci,
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId,
final Transaction transaction) {
final List<CompletableFuture<Pair<Boolean, Boolean>>> messageInsertFutures = messagesByDeviceId.entrySet()
.stream()
.map(e -> {
final byte deviceId = e.getKey();
final MessageProtos.Envelope message = e.getValue();
final byte[] presenceKey = getPresenceKey(aci, deviceId);
return transaction.get(presenceKey)
.thenApply(this::isClientPresent)
.thenApply(isPresent -> {
boolean hasMutations = false;
if (isPresent || !message.getEphemeral()) {
final Subspace deviceQueueSubspace = getDeviceQueueSubspace(aci, deviceId);
transaction.mutate(MutationType.SET_VERSIONSTAMPED_KEY,
deviceQueueSubspace.packWithVersionstamp(Tuple.from(
Versionstamp.incomplete())), message.toByteArray());
hasMutations = true;
}
return new Pair<>(isPresent, hasMutations);
});
})
.toList();
return CompletableFuture.allOf(messageInsertFutures.toArray(CompletableFuture[]::new))
.thenApply(_ -> {
final boolean anyClientPresent = messageInsertFutures
.stream()
.anyMatch(future -> future.join().first());
final boolean hasMutations = messageInsertFutures
.stream()
.anyMatch(future -> future.join().second());
if (anyClientPresent && hasMutations) {
transaction.mutate(MutationType.SET_VERSIONSTAMPED_VALUE, getMessagesAvailableWatchKey(aci),
Tuple.from(Versionstamp.incomplete()).packWithVersionstamp());
}
return hasMutations;
});
}
private Database getShardForAci(final AciServiceIdentifier aci) {
return databases[hashAciToShardNumber(aci)];
}
private int hashAciToShardNumber(final AciServiceIdentifier aci) {
// We use a consistent hash here to reduce the number of key remappings if we increase the number of shards
return Hashing.consistentHash(aci.uuid().getLeastSignificantBits(), databases.length);
}
@VisibleForTesting
Subspace getDeviceQueueSubspace(final AciServiceIdentifier aci, final byte deviceId) {
return getDeviceSubspace(aci, deviceId).get("Q");
}
private Subspace getDeviceSubspace(final AciServiceIdentifier aci, final byte deviceId) {
return getAccountSubspace(aci).get(deviceId);
}
private Subspace getAccountSubspace(final AciServiceIdentifier aci) {
return MESSAGES_SUBSPACE.get(aci.uuid());
}
@VisibleForTesting
byte[] getMessagesAvailableWatchKey(final AciServiceIdentifier aci) {
return getAccountSubspace(aci).pack("l");
}
@VisibleForTesting
byte[] getPresenceKey(final AciServiceIdentifier aci, final byte deviceId) {
return getDeviceQueueSubspace(aci, deviceId).pack("p");
}
@VisibleForTesting
boolean isClientPresent(final byte[] presenceValueBytes) {
if (presenceValueBytes == null) {
return false;
}
final long presenceValue = Conversions.byteArrayToLong(presenceValueBytes);
// The presence value is a long with the higher order 16 bits containing a server id, and the lower 48 bits
// containing the timestamp (seconds since epoch) that the client updates periodically.
final long lastSeenSecondsSinceEpoch = presenceValue & 0x0000ffffffffffffL;
return (clock.instant().getEpochSecond() - lastSeenSecondsSinceEpoch) <= MAX_SECONDS_SINCE_UPDATE_FOR_PRESENCE;
}
}
@@ -229,7 +229,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
try {
return stripeClient.paymentIntents().create(builder.build(), commonOptions());
} catch (StripeException e) {
final String errorCode = e.getCode().toLowerCase(Locale.ROOT);
final String errorCode = StringUtils.lowerCase(e.getCode(), Locale.ROOT);
switch (errorCode) {
case "amount_too_small","amount_too_large" ->
throw ExceptionUtils.wrap(new SubscriptionException.InvalidAmount(errorCode));
@@ -0,0 +1,94 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.util;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
/**
* A thread factory that creates virtual threads but limits the total number of virtual threads created.
*/
public class BoundedVirtualThreadFactory implements ThreadFactory {
private static final Logger logger = LoggerFactory.getLogger(BoundedVirtualThreadFactory.class);
private final AtomicInteger runningThreads = new AtomicInteger();
private final ThreadFactory delegate;
private final int maxConcurrentThreads;
private final Counter created;
private final Counter completed;
public BoundedVirtualThreadFactory(final String threadPoolName, final int maxConcurrentThreads) {
this.maxConcurrentThreads = maxConcurrentThreads;
final Tags tags = Tags.of("pool", threadPoolName);
Metrics.gauge(
MetricsUtil.name(BoundedVirtualThreadFactory.class, "active"),
tags, runningThreads, (rt) -> (double) rt.get());
this.created = Metrics.counter(MetricsUtil.name(BoundedVirtualThreadFactory.class, "created"), tags);
this.completed = Metrics.counter(MetricsUtil.name(BoundedVirtualThreadFactory.class, "completed"), tags);
// The virtual thread factory will initialize thread names by appending the thread index to the provided prefix
this.delegate = Thread.ofVirtual().name(threadPoolName + "-", 0).factory();
}
@Override
public Thread newThread(final Runnable r) {
if (!tryAcquire()) {
return null;
}
Thread thread = null;
try {
final Runnable wrapped = () -> {
try {
r.run();
} finally {
release();
}
};
thread = delegate.newThread(wrapped);
} finally {
if (thread == null) {
release();
}
}
return thread;
}
@VisibleForTesting
int getRunningThreads() {
return runningThreads.get();
}
private boolean tryAcquire() {
int old;
do {
old = runningThreads.get();
if (old >= maxConcurrentThreads) {
return false;
}
} while (!runningThreads.compareAndSet(old, old + 1));
created.increment();
return true;
}
private void release() {
int updated = runningThreads.decrementAndGet();
if (updated < 0) {
logger.error("Released a thread and count was {}, which should never happen", updated);
}
completed.increment();
}
}
@@ -0,0 +1,21 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.util;
import java.util.concurrent.CompletionStage;
import org.apache.commons.lang3.function.TriFunction;
public class Futures {
public static <T, U, V, R> CompletionStage<R> zipWith(
CompletionStage<T> futureT,
CompletionStage<U> futureU,
CompletionStage<V> futureV,
TriFunction<T, U, V, R> fun) {
return futureT.thenCompose(t -> futureU.thenCombine(futureV, (u, v) -> fun.apply(t, u, v)));
}
}
@@ -0,0 +1,40 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.util;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import io.dropwizard.core.setup.Environment;
import io.dropwizard.lifecycle.ExecutorServiceManager;
import io.dropwizard.util.Duration;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.binder.jvm.ExecutorServiceMetrics;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Build Executor Services managed by dropwizard, supplementing executors provided by
* {@link io.dropwizard.lifecycle.setup.LifecycleEnvironment#executorService}
*/
public class ManagedExecutors {
private static final Duration SHUTDOWN_DURATION = Duration.seconds(5);
private ManagedExecutors() {
}
public static ExecutorService newVirtualThreadPerTaskExecutor(
final String threadNamePrefix,
final int maxConcurrentThreads,
final Environment environment) {
final BoundedVirtualThreadFactory threadFactory =
new BoundedVirtualThreadFactory(threadNamePrefix, maxConcurrentThreads);
final ExecutorService virtualThreadExecutor = Executors.newThreadPerTaskExecutor(threadFactory);
environment.lifecycle()
.manage(new ExecutorServiceManager(virtualThreadExecutor, SHUTDOWN_DURATION, threadNamePrefix));
return virtualThreadExecutor;
}
}
@@ -15,6 +15,7 @@ import org.slf4j.LoggerFactory;
@ManagedAsyncExecutor
public class VirtualExecutorServiceProvider implements ExecutorServiceProvider {
private static final Logger logger = LoggerFactory.getLogger(VirtualExecutorServiceProvider.class);
@@ -22,17 +23,24 @@ public class VirtualExecutorServiceProvider implements ExecutorServiceProvider {
* Default thread pool executor termination timeout in milliseconds.
*/
public static final int TERMINATION_TIMEOUT = 5000;
private final String virtualThreadNamePrefix;
public VirtualExecutorServiceProvider(final String virtualThreadNamePrefix) {
private final String virtualThreadNamePrefix;
private final int maxConcurrentThreads;
public VirtualExecutorServiceProvider(
final String virtualThreadNamePrefix,
final int maxConcurrentThreads) {
this.virtualThreadNamePrefix = virtualThreadNamePrefix;
this.maxConcurrentThreads = maxConcurrentThreads;
}
@Override
public ExecutorService getExecutorService() {
logger.info("Creating executor service with virtual thread per task");
return Executors.newThreadPerTaskExecutor(Thread.ofVirtual().name(virtualThreadNamePrefix, 0).factory());
final ExecutorService executor = Executors.newThreadPerTaskExecutor(
new BoundedVirtualThreadFactory(virtualThreadNamePrefix, maxConcurrentThreads));
return executor;
}
@Override
@@ -9,18 +9,19 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import io.micrometer.core.instrument.Tags;
import java.util.Optional;
import java.util.concurrent.ScheduledExecutorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor;
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
import org.whispersystems.textsecuregcm.metrics.OpenWebSocketCounter;
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
import org.whispersystems.textsecuregcm.push.ReceiptSender;
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
@@ -47,8 +48,8 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
private final MessageMetrics messageMetrics;
private final PushNotificationManager pushNotificationManager;
private final PushNotificationScheduler pushNotificationScheduler;
private final WebSocketConnectionEventManager webSocketConnectionEventManager;
private final ScheduledExecutorService scheduledExecutorService;
private final RedisMessageAvailabilityManager redisMessageAvailabilityManager;
private final DisconnectionRequestManager disconnectionRequestManager;
private final Scheduler messageDeliveryScheduler;
private final ClientReleaseManager clientReleaseManager;
private final MessageDeliveryLoopMonitor messageDeliveryLoopMonitor;
@@ -58,17 +59,17 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
private final OpenWebSocketCounter openUnauthenticatedWebSocketCounter;
public AuthenticatedConnectListener(
AccountsManager accountsManager,
ReceiptSender receiptSender,
MessagesManager messagesManager,
MessageMetrics messageMetrics,
PushNotificationManager pushNotificationManager,
PushNotificationScheduler pushNotificationScheduler,
WebSocketConnectionEventManager webSocketConnectionEventManager,
ScheduledExecutorService scheduledExecutorService,
Scheduler messageDeliveryScheduler,
ClientReleaseManager clientReleaseManager,
MessageDeliveryLoopMonitor messageDeliveryLoopMonitor,
final AccountsManager accountsManager,
final ReceiptSender receiptSender,
final MessagesManager messagesManager,
final MessageMetrics messageMetrics,
final PushNotificationManager pushNotificationManager,
final PushNotificationScheduler pushNotificationScheduler,
final RedisMessageAvailabilityManager redisMessageAvailabilityManager,
final DisconnectionRequestManager disconnectionRequestManager,
final Scheduler messageDeliveryScheduler,
final ClientReleaseManager clientReleaseManager,
final MessageDeliveryLoopMonitor messageDeliveryLoopMonitor,
final ExperimentEnrollmentManager experimentEnrollmentManager) {
this.accountsManager = accountsManager;
@@ -77,8 +78,8 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
this.messageMetrics = messageMetrics;
this.pushNotificationManager = pushNotificationManager;
this.pushNotificationScheduler = pushNotificationScheduler;
this.webSocketConnectionEventManager = webSocketConnectionEventManager;
this.scheduledExecutorService = scheduledExecutorService;
this.redisMessageAvailabilityManager = redisMessageAvailabilityManager;
this.disconnectionRequestManager = disconnectionRequestManager;
this.messageDeliveryScheduler = messageDeliveryScheduler;
this.clientReleaseManager = clientReleaseManager;
this.messageDeliveryLoopMonitor = messageDeliveryLoopMonitor;
@@ -104,7 +105,7 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
final AuthenticatedDevice auth = context.getAuthenticated(AuthenticatedDevice.class);
final Optional<Account> maybeAuthenticatedAccount = accountsManager.getByAccountIdentifier(auth.accountIdentifier());
final Optional<Device> maybeAuthenticatedDevice = maybeAuthenticatedAccount.flatMap(account -> account.getDevice(auth.deviceId()));;
final Optional<Device> maybeAuthenticatedDevice = maybeAuthenticatedAccount.flatMap(account -> account.getDevice(auth.deviceId()));
if (maybeAuthenticatedAccount.isEmpty() || maybeAuthenticatedDevice.isEmpty()) {
log.warn("{}:{} not found when opening authenticated WebSocket", auth.accountIdentifier(), auth.deviceId());
@@ -121,18 +122,25 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
maybeAuthenticatedAccount.get(),
maybeAuthenticatedDevice.get(),
context.getClient(),
scheduledExecutorService,
messageDeliveryScheduler,
clientReleaseManager,
messageDeliveryLoopMonitor,
experimentEnrollmentManager);
context.addWebsocketClosedListener((closingContext, statusCode, reason) -> {
disconnectionRequestManager.addListener(maybeAuthenticatedAccount.get().getIdentifier(IdentityType.ACI),
maybeAuthenticatedDevice.get().getId(),
connection);
context.addWebsocketClosedListener((_, _, _) -> {
disconnectionRequestManager.removeListener(maybeAuthenticatedAccount.get().getIdentifier(IdentityType.ACI),
maybeAuthenticatedDevice.get().getId(),
connection);
// We begin the shutdown process by removing this client's "presence," which means it will again begin to
// receive push notifications for inbound messages. We should do this first because, at this point, the
// connection has already closed and attempts to actually deliver a message via the connection will not succeed.
// It's preferable to start sending push notifications as soon as possible.
webSocketConnectionEventManager.handleClientDisconnected(auth.accountIdentifier(), auth.deviceId());
redisMessageAvailabilityManager.handleClientDisconnected(auth.accountIdentifier(), auth.deviceId());
// Finally, stop trying to deliver messages and send a push notification if the connection is aware of any
// undelivered messages.
@@ -148,7 +156,7 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
// Finally, we register this client's presence, which suppresses push notifications. We do this last because
// receiving extra push notifications is generally preferable to missing out on a push notification.
webSocketConnectionEventManager.handleClientConnected(auth.accountIdentifier(), auth.deviceId(), connection);
redisMessageAvailabilityManager.handleClientConnected(auth.accountIdentifier(), auth.deviceId(), connection);
} catch (final Exception e) {
log.warn("Failed to initialize websocket", e);
context.getClient().close(1011, "Unexpected error initializing connection");
@@ -9,35 +9,30 @@ import static com.codahale.metrics.MetricRegistry.name;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.Timer;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.LongAdder;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.util.StaticException;
import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.controllers.MessageController;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestListener;
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
@@ -47,10 +42,10 @@ import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor;
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.MessageAvailabilityListener;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
import org.whispersystems.textsecuregcm.push.ReceiptSender;
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventListener;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import org.whispersystems.textsecuregcm.storage.Device;
@@ -64,13 +59,10 @@ import reactor.core.observability.micrometer.Micrometer;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
import reactor.util.retry.Retry;
public class WebSocketConnection implements WebSocketConnectionEventListener {
public class WebSocketConnection implements MessageAvailabilityListener, DisconnectionRequestListener {
private static final DistributionSummary messageTime = Metrics.summary(
name(MessageController.class, "messageDeliveryDuration"));
private static final DistributionSummary primaryDeviceMessageTime = Metrics.summary(
name(MessageController.class, "primaryDeviceMessageDeliveryDuration"));
private static final Counter sendMessageCounter = Metrics.counter(name(WebSocketConnection.class, "sendMessage"));
private static final Counter bytesSentCounter = Metrics.counter(name(WebSocketConnection.class, "bytesSent"));
private static final Counter sendFailuresCounter = Metrics.counter(name(WebSocketConnection.class, "sendFailures"));
@@ -79,7 +71,6 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
"initialQueueLength");
private static final String INITIAL_QUEUE_DRAIN_TIMER_NAME = name(WebSocketConnection.class, "drainInitialQueue");
private static final String SLOW_QUEUE_DRAIN_COUNTER_NAME = name(WebSocketConnection.class, "slowQueueDrain");
private static final String QUEUE_DRAIN_RETRY_COUNTER_NAME = name(WebSocketConnection.class, "queueDrainRetry");
private static final String DISPLACEMENT_COUNTER_NAME = name(WebSocketConnection.class, "displacement");
private static final String NON_SUCCESS_RESPONSE_COUNTER_NAME = name(WebSocketConnection.class,
"clientNonSuccessResponse");
@@ -89,6 +80,7 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
"sendMessageError");
private static final String MESSAGE_AVAILABLE_COUNTER_NAME = name(WebSocketConnection.class, "messagesAvailable");
private static final String MESSAGES_PERSISTED_COUNTER_NAME = name(WebSocketConnection.class, "messagesPersisted");
private static final String SEND_MESSAGE_DURATION_TIMER_NAME = name(WebSocketConnection.class, "sendMessageDuration");
private static final String PRESENCE_MANAGER_TAG = "presenceManager";
private static final String STATUS_CODE_TAG = "status";
@@ -104,13 +96,6 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
@VisibleForTesting
static final int MESSAGE_SENDER_MAX_CONCURRENCY = 256;
@VisibleForTesting
static final int MAX_CONSECUTIVE_RETRIES = 5;
private static final long RETRY_DELAY_MILLIS = 1_000;
private static final int RETRY_DELAY_JITTER_MILLIS = 500;
private static final int DEFAULT_SEND_FUTURES_TIMEOUT_MILLIS = 5 * 60 * 1000;
private static final Duration CLOSE_WITH_PENDING_MESSAGES_NOTIFICATION_DELAY = Duration.ofMinutes(1);
private static final Logger logger = LoggerFactory.getLogger(WebSocketConnection.class);
@@ -127,21 +112,14 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
private final Device authenticatedDevice;
private final WebSocketClient client;
private final int sendFuturesTimeoutMillis;
private final ScheduledExecutorService scheduledExecutorService;
private final Semaphore processStoredMessagesSemaphore = new Semaphore(1);
private final AtomicReference<StoredMessageState> storedMessageState = new AtomicReference<>(
StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE);
private final AtomicBoolean sentInitialQueueEmptyMessage = new AtomicBoolean(false);
private final LongAdder sentMessageCounter = new LongAdder();
private final AtomicLong queueDrainStartTime = new AtomicLong();
private final AtomicInteger consecutiveRetries = new AtomicInteger();
private final AtomicReference<ScheduledFuture<?>> retryFuture = new AtomicReference<>();
private final AtomicLong queueDrainStartNanoTime = new AtomicLong();
private final AtomicReference<Disposable> messageSubscription = new AtomicReference<>();
private final Random random = new Random();
private final Scheduler messageDeliveryScheduler;
private final ClientReleaseManager clientReleaseManager;
@@ -152,50 +130,18 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
PERSISTED_NEW_MESSAGES_AVAILABLE
}
public WebSocketConnection(ReceiptSender receiptSender,
MessagesManager messagesManager,
MessageMetrics messageMetrics,
PushNotificationManager pushNotificationManager,
PushNotificationScheduler pushNotificationScheduler,
Account authenticatedAccount,
Device authenticatedDevice,
WebSocketClient client,
ScheduledExecutorService scheduledExecutorService,
Scheduler messageDeliveryScheduler,
ClientReleaseManager clientReleaseManager,
MessageDeliveryLoopMonitor messageDeliveryLoopMonitor,
ExperimentEnrollmentManager experimentEnrollmentManager) {
this(receiptSender,
messagesManager,
messageMetrics,
pushNotificationManager,
pushNotificationScheduler,
authenticatedAccount,
authenticatedDevice,
client,
DEFAULT_SEND_FUTURES_TIMEOUT_MILLIS,
scheduledExecutorService,
messageDeliveryScheduler,
clientReleaseManager,
messageDeliveryLoopMonitor, experimentEnrollmentManager);
}
@VisibleForTesting
WebSocketConnection(ReceiptSender receiptSender,
MessagesManager messagesManager,
MessageMetrics messageMetrics,
PushNotificationManager pushNotificationManager,
PushNotificationScheduler pushNotificationScheduler,
Account authenticatedAccount,
Device authenticatedDevice,
WebSocketClient client,
int sendFuturesTimeoutMillis,
ScheduledExecutorService scheduledExecutorService,
Scheduler messageDeliveryScheduler,
ClientReleaseManager clientReleaseManager,
MessageDeliveryLoopMonitor messageDeliveryLoopMonitor,
ExperimentEnrollmentManager experimentEnrollmentManager) {
public WebSocketConnection(final ReceiptSender receiptSender,
final MessagesManager messagesManager,
final MessageMetrics messageMetrics,
final PushNotificationManager pushNotificationManager,
final PushNotificationScheduler pushNotificationScheduler,
final Account authenticatedAccount,
final Device authenticatedDevice,
final WebSocketClient client,
final Scheduler messageDeliveryScheduler,
final ClientReleaseManager clientReleaseManager,
final MessageDeliveryLoopMonitor messageDeliveryLoopMonitor,
final ExperimentEnrollmentManager experimentEnrollmentManager) {
this.receiptSender = receiptSender;
this.messagesManager = messagesManager;
@@ -205,8 +151,6 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
this.authenticatedAccount = authenticatedAccount;
this.authenticatedDevice = authenticatedDevice;
this.client = client;
this.sendFuturesTimeoutMillis = sendFuturesTimeoutMillis;
this.scheduledExecutorService = scheduledExecutorService;
this.messageDeliveryScheduler = messageDeliveryScheduler;
this.clientReleaseManager = clientReleaseManager;
this.messageDeliveryLoopMonitor = messageDeliveryLoopMonitor;
@@ -215,17 +159,11 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
public void start() {
pushNotificationManager.handleMessagesRetrieved(authenticatedAccount, authenticatedDevice, client.getUserAgent());
queueDrainStartTime.set(System.currentTimeMillis());
queueDrainStartNanoTime.set(System.nanoTime());
processStoredMessages();
}
public void stop() {
final ScheduledFuture<?> future = retryFuture.get();
if (future != null) {
future.cancel(false);
}
final Disposable subscription = messageSubscription.get();
if (subscription != null) {
subscription.dispose();
@@ -249,6 +187,8 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
bytesSentCounter.increment(body.map(bytes -> bytes.length).orElse(0));
messageMetrics.measureAccountEnvelopeUuidMismatches(authenticatedAccount, message);
final Timer.Sample sample = Timer.start();
// X-Signal-Key: false must be sent until Android stops assuming it missing means true
return client.sendRequest("PUT", "/api/v1/message",
List.of(HeaderUtils.X_SIGNAL_KEY + ": false", HeaderUtils.getTimestampHeader()), body)
@@ -273,7 +213,6 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
.thenApply(ignored -> null);
if (message.getType() != Envelope.Type.SERVER_DELIVERY_RECEIPT) {
recordMessageDeliveryDuration(message.getServerTimestamp(), authenticatedDevice);
sendDeliveryReceiptFor(message);
}
} else {
@@ -294,15 +233,11 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
}
return result;
});
}
public static void recordMessageDeliveryDuration(long timestamp, Device messageDestinationDevice) {
final long messageDeliveryDuration = System.currentTimeMillis() - timestamp;
messageTime.record(messageDeliveryDuration);
if (messageDestinationDevice.isPrimary()) {
primaryDeviceMessageTime.record(messageDeliveryDuration);
}
})
.thenRun(() -> sample.stop(Timer.builder(SEND_MESSAGE_DURATION_TIMER_NAME)
.publishPercentileHistogram(true)
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(client.getUserAgent())))
.register(Metrics.globalRegistry)));
}
private void sendDeliveryReceiptFor(Envelope message) {
@@ -341,15 +276,14 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
}
// Cleared the queue! Send a queue empty message if we need to
consecutiveRetries.set(0);
if (sentInitialQueueEmptyMessage.compareAndSet(false, true)) {
final Tags tags = Tags.of(UserAgentTagUtil.getPlatformTag(client.getUserAgent()));
final long drainDuration = System.currentTimeMillis() - queueDrainStartTime.get();
final long drainDurationNanos = System.nanoTime() - queueDrainStartNanoTime.get();
Metrics.summary(INITIAL_QUEUE_LENGTH_DISTRIBUTION_NAME, tags).record(sentMessageCounter.sum());
Metrics.timer(INITIAL_QUEUE_DRAIN_TIMER_NAME, tags).record(drainDuration, TimeUnit.MILLISECONDS);
Metrics.timer(INITIAL_QUEUE_DRAIN_TIMER_NAME, tags).record(drainDurationNanos, TimeUnit.NANOSECONDS);
if (drainDuration > SLOW_DRAIN_THRESHOLD) {
if (drainDurationNanos > SLOW_DRAIN_THRESHOLD) {
Metrics.counter(SLOW_QUEUE_DRAIN_COUNTER_NAME, tags).increment();
}
@@ -361,44 +295,25 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
}
})
// Potentially kick off more work, must happen after we release the semaphore
.whenComplete((ignored, cause) -> processMoreIfRequested(cause));
.whenComplete((ignored, cause) -> {
if (cause != null) {
if (!client.isOpen()) {
logger.debug("Client disconnected before queue cleared");
return;
}
client.close(1011, "Failed to retrieve messages");
return;
}
// Success, but check if more messages came in while we were processing
if (storedMessageState.get() != StoredMessageState.EMPTY) {
processStoredMessages();
}
});
}
}
/**
* After processing messages, kick off another processing job if more messages came in or if there was an error
*
* @param cause An error that was encountered when processing the message queue, if there was one
*/
private void processMoreIfRequested(final @Nullable Throwable cause) {
if (cause == null) {
// Success, but check if more messages came in while we were processing
if (storedMessageState.get() != StoredMessageState.EMPTY) {
processStoredMessages();
}
return;
}
if (!client.isOpen()) {
logger.debug("Client disconnected before queue cleared");
return;
}
if (consecutiveRetries.incrementAndGet() > MAX_CONSECUTIVE_RETRIES) {
logger.warn("Max consecutive retries exceeded", cause);
client.close(1011, "Failed to retrieve messages");
return;
}
logger.debug("Failed to clear queue", cause);
final Tags tags = Tags.of(UserAgentTagUtil.getPlatformTag(client.getUserAgent()));
Metrics.counter(QUEUE_DRAIN_RETRY_COUNTER_NAME, tags).increment();
final long delay = RETRY_DELAY_MILLIS + random.nextInt(RETRY_DELAY_JITTER_MILLIS);
retryFuture.set(scheduledExecutorService.schedule(this::processStoredMessages, delay, TimeUnit.MILLISECONDS));
}
private CompletableFuture<Void> sendMessages(final boolean cachedMessagesOnly) {
final CompletableFuture<Void> queueCleared = new CompletableFuture<>();
@@ -406,7 +321,6 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
messagesManager.getMessagesForDeviceReactive(authenticatedAccount.getIdentifier(IdentityType.ACI), authenticatedDevice, cachedMessagesOnly);
final AtomicBoolean hasSentFirstMessage = new AtomicBoolean();
final AtomicBoolean hasErrored = new AtomicBoolean();
final Disposable subscription = Flux.from(messages)
.name(SEND_MESSAGES_FLUX_NAME)
@@ -421,20 +335,10 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
"websocket");
}
})
.flatMapSequential(envelope ->
Mono.fromFuture(() -> sendMessage(envelope)
.orTimeout(sendFuturesTimeoutMillis, TimeUnit.MILLISECONDS))
.onErrorResume(
// let the first error pass through to terminate the subscription
e -> {
final boolean firstError = !hasErrored.getAndSet(true);
measureSendMessageErrors(e, firstError);
return !firstError;
},
// otherwise just emit nothing
e -> Mono.empty()
), MESSAGE_SENDER_MAX_CONCURRENCY)
.flatMapSequential(envelope -> Mono.fromFuture(() -> sendMessage(envelope))
.retryWhen(Retry.backoff(4, Duration.ofSeconds(1)).filter(throwable -> !isConnectionClosedException(throwable))),
MESSAGE_SENDER_MAX_CONCURRENCY)
.doOnError(this::measureSendMessageErrors)
.subscribeOn(messageDeliveryScheduler)
.subscribe(
// no additional consumer of values - it is Flux<Void> by now
@@ -449,18 +353,15 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
return queueCleared;
}
private void measureSendMessageErrors(final Throwable e, final boolean terminal) {
private void measureSendMessageErrors(final Throwable e) {
final String errorType;
if (e instanceof TimeoutException) {
errorType = "timeout";
} 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()))) {
} else if (isConnectionClosedException(e)) {
errorType = "connectionClosed";
} else {
logger.warn(terminal ? "Send message failure terminated stream" : "Send message failed", e);
logger.warn("Send message failed", e);
errorType = "other";
}
@@ -471,6 +372,13 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
.increment();
}
private static boolean isConnectionClosedException(final Throwable throwable) {
return throwable instanceof java.nio.channels.ClosedChannelException ||
throwable == WebSocketResourceProvider.CONNECTION_CLOSED_EXCEPTION ||
throwable instanceof org.eclipse.jetty.io.EofException ||
(throwable instanceof StaticException staticException && "Closed".equals(staticException.getMessage()));
}
private CompletableFuture<Void> sendMessage(Envelope envelope) {
final UUID messageGuid = UUID.fromString(envelope.getServerGuid());
@@ -506,24 +414,23 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
}
@Override
public void handleConnectionDisplaced(final boolean connectedElsewhere) {
public void handleConflictingMessageConsumer() {
closeConnection(4409, "Connected elsewhere");
}
@Override
public void handleDisconnectionRequest() {
closeConnection(4401, "Reauthentication required");
}
private void closeConnection(final int code, final String message) {
final Tags tags = Tags.of(
UserAgentTagUtil.getPlatformTag(client.getUserAgent()),
Tag.of("connectedElsewhere", String.valueOf(connectedElsewhere)));
// TODO We should probably just use the status code directly
Tag.of("connectedElsewhere", String.valueOf(code == 4409)));
Metrics.counter(DISPLACEMENT_COUNTER_NAME, tags).increment();
final int code;
final String message;
if (connectedElsewhere) {
code = 4409;
message = "Connected elsewhere";
} else {
code = 4401;
message = "Reauthentication required";
}
client.close(code, message);
}
@@ -30,19 +30,20 @@ import org.whispersystems.textsecuregcm.backup.BackupManager;
import org.whispersystems.textsecuregcm.backup.BackupsDb;
import org.whispersystems.textsecuregcm.backup.Cdn3BackupCredentialGenerator;
import org.whispersystems.textsecuregcm.backup.Cdn3RemoteStorageManager;
import org.whispersystems.textsecuregcm.backup.SecureValueRecoveryBCredentialsGeneratorFactory;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery2Controller;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.controllers.SecureValueRecoveryBController;
import org.whispersystems.textsecuregcm.experiment.PushNotificationExperimentSamples;
import org.whispersystems.textsecuregcm.grpc.net.GrpcClientConnectionManager;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.MicrometerAwsSdkMetricPublisher;
import org.whispersystems.textsecuregcm.push.APNSender;
import org.whispersystems.textsecuregcm.push.FcmSender;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
@@ -173,8 +174,8 @@ record CommandDependencies(
configuration.getSecureStorageServiceConfiguration());
ExternalServiceCredentialsGenerator secureValueRecovery2CredentialsGenerator = SecureValueRecovery2Controller.credentialsGenerator(
configuration.getSvr2Configuration());
ExternalServiceCredentialsGenerator secureValueRecoveryBCredentialsGenerator = SecureValueRecoveryBController.credentialsGenerator(
configuration.getSvrbConfiguration());
ExternalServiceCredentialsGenerator secureValueRecoveryBCredentialsGenerator =
SecureValueRecoveryBCredentialsGeneratorFactory.svrbCredentialsGenerator(configuration.getSvrbConfiguration());
final ExecutorService awsSdkMetricsExecutor = environment.lifecycle()
.virtualExecutorService(MetricRegistry.name(WhisperServerService.class, "awsSdkMetrics-%d"));
@@ -230,12 +231,11 @@ record CommandDependencies(
new RepeatedUseECSignedPreKeyStore(dynamoDbAsyncClient,
configuration.getDynamoDbTables().getEcSignedPreKeys().getTableName()),
new RepeatedUseKEMSignedPreKeyStore(dynamoDbAsyncClient,
configuration.getDynamoDbTables().getKemLastResortKeys().getTableName()),
experimentEnrollmentManager);
configuration.getDynamoDbTables().getKemLastResortKeys().getTableName()));
MessagesDynamoDb messagesDynamoDb = new MessagesDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
configuration.getDynamoDbTables().getMessages().getTableName(),
configuration.getDynamoDbTables().getMessages().getExpiration(),
messageDeletionExecutor);
messageDeletionExecutor, experimentEnrollmentManager);
FaultTolerantRedisClusterClient messagesCluster = configuration.getMessageCacheConfiguration()
.getRedisClusterConfiguration().build("messages", redisClientResourcesBuilder);
FaultTolerantRedisClusterClient rateLimitersCluster = configuration.getRateLimitersCluster().build("rate_limiters",
@@ -254,9 +254,10 @@ record CommandDependencies(
() -> dynamicConfigurationManager.getConfiguration().getSvrbStatusCodesToIgnoreForAccountDeletion());
SecureStorageClient secureStorageClient = new SecureStorageClient(storageCredentialsGenerator,
storageServiceExecutor, storageServiceRetryExecutor, configuration.getSecureStorageServiceConfiguration());
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient, disconnectionRequestListenerExecutor);
GrpcClientConnectionManager grpcClientConnectionManager = new GrpcClientConnectionManager();
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient, grpcClientConnectionManager, disconnectionRequestListenerExecutor);
MessagesCache messagesCache = new MessagesCache(messagesCluster,
messageDeliveryScheduler, messageDeletionExecutor, Clock.systemUTC());
messageDeliveryScheduler, messageDeletionExecutor, Clock.systemUTC(), experimentEnrollmentManager);
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster, asyncCdnS3Client,
configuration.getCdnConfiguration().bucket());
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
@@ -264,7 +265,9 @@ record CommandDependencies(
configuration.getReportMessageConfiguration().getReportTtl());
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster,
configuration.getReportMessageConfiguration().getCounterTtl());
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache,
RedisMessageAvailabilityManager redisMessageAvailabilityManager =
new RedisMessageAvailabilityManager(messagesCluster, clientEventExecutor, asyncOperationQueueingExecutor);
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
reportMessageManager, messageDeletionExecutor, Clock.systemUTC());
AccountLockManager accountLockManager = new AccountLockManager(dynamoDbClient,
configuration.getDynamoDbTables().getDeletedAccountsLock().getTableName());
@@ -274,7 +277,7 @@ record CommandDependencies(
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords);
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
pubsubClient, accountLockManager, keys, messagesManager, profilesManager,
secureStorageClient, secureValueRecovery2Client, secureValueRecoveryBClient, disconnectionRequestManager,
secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
registrationRecoveryPasswordsManager, clientPublicKeysManager, accountLockExecutor, messagePollExecutor,
clock, configuration.getLinkDeviceSecretConfiguration().secret().value(), dynamicConfigurationManager);
RateLimiters rateLimiters = RateLimiters.create(dynamicConfigurationManager, rateLimitersCluster);
@@ -297,6 +300,8 @@ record CommandDependencies(
remoteStorageHttpExecutor,
remoteStorageRetryExecutor,
configuration.getCdn3StorageManagerConfiguration()),
secureValueRecoveryBCredentialsGenerator,
secureValueRecoveryBClient,
clock);
final IssuedReceiptsManager issuedReceiptsManager = new IssuedReceiptsManager(
@@ -317,15 +322,12 @@ record CommandDependencies(
configuration.getDynamoDbTables().getPushNotificationExperimentSamples().getTableName(),
Clock.systemUTC());
WebSocketConnectionEventManager webSocketConnectionEventManager =
new WebSocketConnectionEventManager(accountsManager, pushNotificationManager, messagesCluster, clientEventExecutor, asyncOperationQueueingExecutor);
final DynamoDbRecoveryManager dynamoDbRecoveryManager =
new DynamoDbRecoveryManager(accounts, phoneNumberIdentifiers);
environment.lifecycle().manage(apnSender);
environment.lifecycle().manage(disconnectionRequestManager);
environment.lifecycle().manage(webSocketConnectionEventManager);
environment.lifecycle().manage(redisMessageAvailabilityManager);
environment.lifecycle().manage(new ManagedAwsCrt());
return new CommandDependencies(
@@ -1,88 +0,0 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.workers;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import java.time.Duration;
import net.sourceforge.argparse4j.inf.Subparser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.util.EncryptDeviceCreationTimestampUtil;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Flux;
import reactor.util.retry.Retry;
public class EncryptDeviceCreationTimestampCommand extends AbstractSinglePassCrawlAccountsCommand {
@VisibleForTesting
static final String DRY_RUN_ARGUMENT = "dry-run";
private static final int MAX_CONCURRENCY = 16;
private static final String ENCRYPTED_CREATION_TIMESTAMP_COUNTER_NAME =
name(EncryptDeviceCreationTimestampCommand.class, "encryptedCreationTimestamp");
private static final String PROCESSED_ACCOUNT_COUNTER_NAME =
name(EncryptDeviceCreationTimestampCommand.class, "processedAccount");
private static final Logger log = LoggerFactory.getLogger(EncryptDeviceCreationTimestampCommand.class);
public EncryptDeviceCreationTimestampCommand() {
super("encrypt-device-creation-timestamps", "Encrypts the creation timestamp of devices on accounts");
}
@Override
public void configure(final Subparser subparser) {
super.configure(subparser);
subparser.addArgument("--dry-run")
.type(Boolean.class)
.dest(DRY_RUN_ARGUMENT)
.required(false)
.setDefault(true)
.help("If true, don't actually update device records");
}
@Override
protected void crawlAccounts(final Flux<Account> accounts) {
final boolean isDryRun = getNamespace().getBoolean(DRY_RUN_ARGUMENT);
final Counter encryptedTimestampCounter =
Metrics.counter(ENCRYPTED_CREATION_TIMESTAMP_COUNTER_NAME, "dryRun", String.valueOf(isDryRun));
final Counter processedAccountCounter =
Metrics.counter(PROCESSED_ACCOUNT_COUNTER_NAME, "dryRun", String.valueOf(isDryRun));
accounts
.flatMap(account ->
Flux.fromIterable(account.getDevices())
.flatMap(device -> {
final byte[] createdAtCiphertext = EncryptDeviceCreationTimestampUtil.encrypt(
device.getCreated(), account.getIdentityKey(IdentityType.ACI),
device.getId(), device.getRegistrationId(IdentityType.ACI));
final Mono<Void> encryptTimestampMono = isDryRun
? Mono.empty()
: Mono.fromFuture(() -> getCommandDependencies().accountsManager().updateDeviceAsync(
account, device.getId(), d -> d.setCreatedAtCiphertext(createdAtCiphertext))
.thenRun(Util.NOOP));
return encryptTimestampMono
.doOnSuccess(_ -> encryptedTimestampCounter.increment())
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1)).maxBackoff(Duration.ofSeconds(4)))
.onErrorResume(throwable -> {
log.warn("Failed to encrypt creation timestamp on device {}, account {}", device.getId(), account.getUuid(), throwable);
return Mono.empty();
});
}, MAX_CONCURRENCY)
.then()
.doOnSuccess(_ -> processedAccountCounter.increment()),
MAX_CONCURRENCY)
.then()
.block();
}
}
@@ -188,6 +188,11 @@ service BackupsAnonymous {
*/
rpc GetCdnCredentials(GetCdnCredentialsRequest) returns (GetCdnCredentialsResponse) {}
/**
* Retrieve credentials used to interact with the SecureValueRecoveryB service
*/
rpc GetSvrBCredentials(GetSvrBCredentialsRequest) returns (GetSvrBCredentialsResponse) {}
/**
* Retrieve information about the currently stored backup
*/
@@ -291,6 +296,21 @@ message GetCdnCredentialsResponse {
map<string, string> headers = 1;
}
message GetSvrBCredentialsRequest {
SignedPresentation signed_presentation = 1;
}
message GetSvrBCredentialsResponse {
/**
* A username that can be presented to authenticate with SVRB
*/
string username = 1;
/**
* A password that can be presented to authenticate with SVRB
*/
string password = 2;
}
message GetBackupInfoRequest {
SignedPresentation signed_presentation = 1;
}
@@ -53,7 +53,6 @@ enum ExternalServiceType {
EXTERNAL_SERVICE_TYPE_PAYMENTS = 2;
EXTERNAL_SERVICE_TYPE_STORAGE = 3;
EXTERNAL_SERVICE_TYPE_SVR = 4;
EXTERNAL_SERVICE_TYPE_SVRB = 5;
}
message GetExternalServiceCredentialsRequest {
@@ -195,8 +195,7 @@ message GetPreKeysResponse {
/**
* A one-time KEM pre-key (or a last-resort KEM pre-key) for the targeted
* account/device/identity. May not be set if the targeted device has not
* yet uploaded any KEM pre-keys.
* account/device/identity.
*/
common.KemSignedPreKey kem_one_time_pre_key = 3;
}
@@ -1,8 +0,0 @@
-- keys: lock_key
-- argv: lock_value
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
else
return 0
end
@@ -1,9 +0,0 @@
local presenceKey = KEYS[1]
local presenceUuid = ARGV[1]
if redis.call("GET", presenceKey) == presenceUuid then
redis.call("DEL", presenceKey)
return true
end
return false
@@ -1,7 +0,0 @@
local presenceKey = KEYS[1]
local presenceUuid = ARGV[1]
local expireSeconds = ARGV[2]
if redis.call("GET", presenceKey) == presenceUuid then
redis.call("EXPIRE", presenceKey, expireSeconds)
end
@@ -34,7 +34,7 @@ public class BufferingInterceptorIntegrationTest {
final TestController testController = new TestController();
environment.jersey().register(testController);
environment.jersey().register(new BufferingInterceptor());
environment.jersey().register(new VirtualExecutorServiceProvider("virtual-thread-"));
environment.jersey().register(new VirtualExecutorServiceProvider("virtual-thread-", 10));
JettyWebSocketServletContainerInitializer.configure(environment.getApplicationContext(), null);
}
}
@@ -18,10 +18,17 @@ import jakarta.ws.rs.core.Response;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import org.eclipse.jetty.util.component.LifeCycle;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.StatusCode;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
@@ -34,6 +41,7 @@ import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema;
import org.whispersystems.textsecuregcm.tests.util.TestWebsocketListener;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.Util;
import org.whispersystems.websocket.messages.WebSocketResponseMessage;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
@@ -177,13 +185,6 @@ class WhisperServerServiceTest {
.build());
}
@Test
void testOtlpConfig() {
final OpenTelemetryConfiguration otelConfig =EXTENSION.getConfiguration().getOpenTelemetryConfiguration();
assertTrue(otelConfig.enabled());
assertEquals("http://127.0.0.1:4318/", otelConfig.url());
}
private static DynamoDbClient getDynamoDbClient() {
final AwsCredentialsProvider awsCredentialsProvider = EXTENSION.getConfiguration().getAwsCredentialsConfiguration()
.build();
@@ -6,58 +6,42 @@
package org.whispersystems.textsecuregcm.auth;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.grpc.net.GrpcClientConnectionManager;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.redis.RedisServerExtension;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
@Timeout(value = 5, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
class DisconnectionRequestManagerTest {
private GrpcClientConnectionManager grpcClientConnectionManager;
private DisconnectionRequestManager disconnectionRequestManager;
@RegisterExtension
static final RedisServerExtension REDIS_EXTENSION = RedisServerExtension.builder().build();
private static class DisconnectionRequestTestListener implements DisconnectionRequestListener {
private final CountDownLatch requestLatch = new CountDownLatch(1);
private UUID accountIdentifier;
private Collection<Byte> deviceIds;
@Override
public void handleDisconnectionRequest(final UUID accountIdentifier, final Collection<Byte> deviceIds) {
this.accountIdentifier = accountIdentifier;
this.deviceIds = deviceIds;
requestLatch.countDown();
}
public UUID getAccountIdentifier() {
return accountIdentifier;
}
public Collection<Byte> getDeviceIds() {
return deviceIds;
}
public void waitForRequest() throws InterruptedException {
requestLatch.await();
}
}
@BeforeEach
void setUp() {
disconnectionRequestManager = new DisconnectionRequestManager(REDIS_EXTENSION.getRedisClient(), Runnable::run);
grpcClientConnectionManager = mock(GrpcClientConnectionManager.class);
disconnectionRequestManager =
new DisconnectionRequestManager(REDIS_EXTENSION.getRedisClient(), grpcClientConnectionManager, Runnable::run);
disconnectionRequestManager.start();
}
@@ -67,33 +51,98 @@ class DisconnectionRequestManagerTest {
}
@Test
void requestDisconnection() throws InterruptedException {
void addRemoveListener() {
final UUID accountIdentifier = UUID.randomUUID();
final List<Byte> deviceIds = List.of(Device.PRIMARY_ID, (byte) (Device.PRIMARY_ID + 1));
final byte deviceId = Device.PRIMARY_ID;
final DisconnectionRequestTestListener listener = new DisconnectionRequestTestListener();
final DisconnectionRequestListener firstListener = mock(DisconnectionRequestListener.class);
final DisconnectionRequestListener secondListener = mock(DisconnectionRequestListener.class);
disconnectionRequestManager.addListener(listener);
disconnectionRequestManager.requestDisconnection(accountIdentifier, deviceIds).toCompletableFuture().join();
assertTrue(disconnectionRequestManager.getListeners(accountIdentifier, deviceId).isEmpty());
listener.waitForRequest();
disconnectionRequestManager.addListener(accountIdentifier, deviceId, firstListener);
assertEquals(accountIdentifier, listener.getAccountIdentifier());
assertEquals(deviceIds, listener.getDeviceIds());
assertEquals(List.of(firstListener), disconnectionRequestManager.getListeners(accountIdentifier, deviceId));
disconnectionRequestManager.addListener(accountIdentifier, deviceId, secondListener);
assertEquals(List.of(firstListener, secondListener),
disconnectionRequestManager.getListeners(accountIdentifier, deviceId));
disconnectionRequestManager.removeListener(accountIdentifier, deviceId, mock(DisconnectionRequestListener.class));
assertEquals(List.of(firstListener, secondListener),
disconnectionRequestManager.getListeners(accountIdentifier, deviceId));
disconnectionRequestManager.removeListener(accountIdentifier, deviceId, firstListener);
assertEquals(List.of(secondListener), disconnectionRequestManager.getListeners(accountIdentifier, deviceId));
}
@Test
void requestDisconnectionAllDevices() throws InterruptedException {
void requestDisconnection() {
final UUID accountIdentifier = UUID.randomUUID();
final byte primaryDeviceId = Device.PRIMARY_ID;
final byte linkedDeviceId = primaryDeviceId + 1;
final DisconnectionRequestTestListener listener = new DisconnectionRequestTestListener();
final UUID otherAccountIdentifier = UUID.randomUUID();
final byte otherDeviceId = linkedDeviceId + 1;
disconnectionRequestManager.addListener(listener);
disconnectionRequestManager.requestDisconnection(accountIdentifier).toCompletableFuture().join();
final List<Byte> deviceIds = List.of(primaryDeviceId, linkedDeviceId);
listener.waitForRequest();
final DisconnectionRequestListener primaryDeviceListener = mock(DisconnectionRequestListener.class);
final DisconnectionRequestListener linkedDeviceListener = mock(DisconnectionRequestListener.class);
assertEquals(accountIdentifier, listener.getAccountIdentifier());
assertEquals(Device.ALL_POSSIBLE_DEVICE_IDS, listener.getDeviceIds());
disconnectionRequestManager.addListener(accountIdentifier, primaryDeviceId, primaryDeviceListener);
disconnectionRequestManager.addListener(accountIdentifier, linkedDeviceId, linkedDeviceListener);
disconnectionRequestManager.requestDisconnection(accountIdentifier, deviceIds).toCompletableFuture().join();
verify(primaryDeviceListener, timeout(1_000)).handleDisconnectionRequest();
verify(linkedDeviceListener, timeout(1_000)).handleDisconnectionRequest();
verify(grpcClientConnectionManager, timeout(1_000))
.closeConnection(new AuthenticatedDevice(accountIdentifier, primaryDeviceId));
verify(grpcClientConnectionManager, timeout(1_000))
.closeConnection(new AuthenticatedDevice(accountIdentifier, linkedDeviceId));
disconnectionRequestManager.requestDisconnection(otherAccountIdentifier, List.of(otherDeviceId));
verify(grpcClientConnectionManager, timeout(1_000))
.closeConnection(new AuthenticatedDevice(otherAccountIdentifier, otherDeviceId));
}
@Test
void requestDisconnectionAllDevices() {
final UUID accountIdentifier = UUID.randomUUID();
final byte primaryDeviceId = Device.PRIMARY_ID;
final byte linkedDeviceId = primaryDeviceId + 1;
final Device primaryDevice = mock(Device.class);
when(primaryDevice.getId()).thenReturn(primaryDeviceId);
final Device linkedDevice = mock(Device.class);
when(linkedDevice.getId()).thenReturn(linkedDeviceId);
final Account account = mock(Account.class);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
when(account.getDevices()).thenReturn(List.of(primaryDevice, linkedDevice));
final DisconnectionRequestListener primaryDeviceListener = mock(DisconnectionRequestListener.class);
final DisconnectionRequestListener linkedDeviceListener = mock(DisconnectionRequestListener.class);
disconnectionRequestManager.addListener(accountIdentifier, primaryDeviceId, primaryDeviceListener);
disconnectionRequestManager.addListener(accountIdentifier, linkedDeviceId, linkedDeviceListener);
disconnectionRequestManager.requestDisconnection(account).toCompletableFuture().join();
verify(primaryDeviceListener, timeout(1_000)).handleDisconnectionRequest();
verify(linkedDeviceListener, timeout(1_000)).handleDisconnectionRequest();
verify(grpcClientConnectionManager, timeout(1_000))
.closeConnection(new AuthenticatedDevice(accountIdentifier, primaryDeviceId));
verify(grpcClientConnectionManager, timeout(1_000))
.closeConnection(new AuthenticatedDevice(accountIdentifier, linkedDeviceId));
}
}
@@ -29,7 +29,6 @@ import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.assertj.core.api.Assertions;
import org.assertj.core.api.ThrowableAssert;
import org.junit.jupiter.api.BeforeEach;
@@ -38,7 +37,6 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.NullSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.junitpioneer.jupiter.cartesian.CartesianTest;
import org.mockito.ArgumentCaptor;
@@ -57,6 +55,7 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.Account;
@@ -86,13 +85,16 @@ public class BackupAuthManagerTest {
reset(redeemedReceiptsManager);
}
BackupAuthManager create(@Nullable BackupLevel backupLevel) {
return create(backupLevel, rateLimiter(aci, false, false));
BackupAuthManager create() {
return create(BackupLevel.FREE, rateLimiter(aci, false, false));
}
BackupAuthManager create(@Nullable BackupLevel backupLevel, RateLimiters rateLimiters) {
BackupAuthManager create(BackupLevel defaultBackupLevel, RateLimiters rateLimiters) {
return new BackupAuthManager(
ExperimentHelper.withEnrollment(experimentName(backupLevel), aci),
switch (defaultBackupLevel) {
case FREE -> mock(ExperimentEnrollmentManager.class);
case PAID -> ExperimentHelper.withEnrollment(BackupAuthManager.BACKUP_MEDIA_EXPERIMENT_NAME, aci);
},
rateLimiters,
accountsManager,
new ServerZkReceiptOperations(receiptParams),
@@ -103,7 +105,7 @@ public class BackupAuthManagerTest {
@Test
void commitBackupId() {
final BackupAuthManager authManager = create(BackupLevel.FREE);
final BackupAuthManager authManager = create();
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(aci);
@@ -122,16 +124,15 @@ public class BackupAuthManagerTest {
authManager.commitBackupId(account, primaryDevice(), messagesCredentialRequest, mediaCredentialRequest).join();
verify(account).setBackupCredentialRequests(messagesCredentialRequest.serialize(), mediaCredentialRequest.serialize());
verify(account).setBackupCredentialRequests(messagesCredentialRequest.serialize(),
mediaCredentialRequest.serialize());
}
@ParameterizedTest
@EnumSource
@NullSource
void commitRequiresBackupLevel(final BackupLevel backupLevel) {
final BackupAuthManager authManager = create(backupLevel);
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(aci);
void commitOnAnyBackupLevel(final BackupLevel backupLevel) {
final BackupAuthManager authManager = create();
final Account account = new MockAccountBuilder().backupLevel(backupLevel).build();
when(accountsManager.updateAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(account));
final ThrowableAssert.ThrowingCallable commit = () ->
@@ -139,21 +140,13 @@ public class BackupAuthManagerTest {
primaryDevice(),
backupAuthTestUtil.getRequest(messagesBackupKey, aci),
backupAuthTestUtil.getRequest(mediaBackupKey, aci)).join();
if (backupLevel == null) {
assertThatExceptionOfType(StatusRuntimeException.class)
.isThrownBy(commit)
.extracting(ex -> ex.getStatus().getCode())
.isEqualTo(Status.Code.PERMISSION_DENIED);
} else {
Assertions.assertThatNoException().isThrownBy(commit);
}
Assertions.assertThatNoException().isThrownBy(commit);
}
@Test
void commitRequiresPrimary() {
final BackupAuthManager authManager = create(BackupLevel.FREE);
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(aci);
final BackupAuthManager authManager = create();
final Account account = new MockAccountBuilder().build();
when(accountsManager.updateAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(account));
final ThrowableAssert.ThrowingCallable commit = () ->
@@ -167,18 +160,47 @@ public class BackupAuthManagerTest {
.isEqualTo(Status.Code.PERMISSION_DENIED);
}
@CartesianTest
void paidTierCredentialViaConfiguration(@CartesianTest.Enum final BackupCredentialType credentialType)
throws VerificationFailedException {
final BackupAuthManager authManager = create(BackupLevel.PAID, rateLimiter(aci, false, false));
final byte[] backupKey = switch (credentialType) {
case MESSAGES -> messagesBackupKey;
case MEDIA -> mediaBackupKey;
};
// Account does not have PAID tier set
final Account account = new MockAccountBuilder()
.messagesCredential(backupAuthTestUtil.getRequest(messagesBackupKey, aci))
.mediaCredential(backupAuthTestUtil.getRequest(mediaBackupKey, aci))
.build();
final BackupAuthCredentialRequestContext requestContext =
BackupAuthCredentialRequestContext.create(backupKey, aci);
final Instant start = clock.instant().truncatedTo(ChronoUnit.DAYS);
final List<BackupAuthManager.Credential> creds = authManager.getBackupAuthCredentials(account,
credentialType, start, start.plus(Duration.ofDays(1))).join();
assertThat(creds).hasSize(2);
assertThat(requestContext
.receiveResponse(creds.getFirst().credential(), start, backupAuthTestUtil.params.getPublicParams())
.getBackupLevel())
.isEqualTo(BackupLevel.PAID);
}
@CartesianTest
void getBackupAuthCredentials(@CartesianTest.Enum final BackupLevel backupLevel,
@CartesianTest.Enum final BackupCredentialType credentialType) {
final BackupAuthManager authManager = create(backupLevel);
final BackupAuthManager authManager = create();
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(aci);
when(account.getBackupCredentialRequest(BackupCredentialType.MESSAGES))
.thenReturn(Optional.of(backupAuthTestUtil.getRequest(messagesBackupKey, aci).serialize()));
when(account.getBackupCredentialRequest(BackupCredentialType.MEDIA))
.thenReturn(Optional.of(backupAuthTestUtil.getRequest(mediaBackupKey, aci).serialize()));
final Account account = new MockAccountBuilder()
.backupLevel(backupLevel)
.messagesCredential(backupAuthTestUtil.getRequest(messagesBackupKey, aci))
.mediaCredential(backupAuthTestUtil.getRequest(mediaBackupKey, aci))
.build();
assertThat(authManager.getBackupAuthCredentials(account,
credentialType,
@@ -189,15 +211,10 @@ public class BackupAuthManagerTest {
@ParameterizedTest
@EnumSource
void getBackupAuthCredentialsNoBackupLevel(final BackupCredentialType credentialType) {
final BackupAuthManager authManager = create(null);
void getBackupAuthCredentialsNoCommittedId(final BackupCredentialType credentialType) {
final BackupAuthManager authManager = create();
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(aci);
when(account.getBackupCredentialRequest(BackupCredentialType.MESSAGES))
.thenReturn(Optional.of(backupAuthTestUtil.getRequest(messagesBackupKey, aci).serialize()));
when(account.getBackupCredentialRequest(BackupCredentialType.MEDIA))
.thenReturn(Optional.of(backupAuthTestUtil.getRequest(mediaBackupKey, aci).serialize()));
final Account account = new MockAccountBuilder().build();
assertThatExceptionOfType(StatusRuntimeException.class)
.isThrownBy(() -> authManager.getBackupAuthCredentials(account,
@@ -205,13 +222,13 @@ public class BackupAuthManagerTest {
clock.instant().truncatedTo(ChronoUnit.DAYS),
clock.instant().plus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS)).join())
.extracting(ex -> ex.getStatus().getCode())
.isEqualTo(Status.Code.PERMISSION_DENIED);
.isEqualTo(Status.Code.NOT_FOUND);
}
@CartesianTest
void getReceiptCredentials(@CartesianTest.Enum final BackupLevel backupLevel,
@CartesianTest.Enum final BackupCredentialType credentialType) throws VerificationFailedException {
final BackupAuthManager authManager = create(backupLevel);
final BackupAuthManager authManager = create();
final byte[] backupKey = switch (credentialType) {
case MESSAGES -> messagesBackupKey;
@@ -221,12 +238,11 @@ public class BackupAuthManagerTest {
final BackupAuthCredentialRequestContext requestContext =
BackupAuthCredentialRequestContext.create(backupKey, aci);
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(aci);
when(account.getBackupCredentialRequest(BackupCredentialType.MESSAGES))
.thenReturn(Optional.of(backupAuthTestUtil.getRequest(messagesBackupKey, aci).serialize()));
when(account.getBackupCredentialRequest(BackupCredentialType.MEDIA))
.thenReturn(Optional.of(backupAuthTestUtil.getRequest(mediaBackupKey, aci).serialize()));
final Account account = new MockAccountBuilder()
.backupLevel(backupLevel)
.mediaCredential(backupAuthTestUtil.getRequest(mediaBackupKey, aci))
.messagesCredential(backupAuthTestUtil.getRequest(messagesBackupKey, aci))
.build();
final Instant start = clock.instant().truncatedTo(ChronoUnit.DAYS);
final List<BackupAuthManager.Credential> creds = authManager.getBackupAuthCredentials(account,
@@ -268,14 +284,12 @@ public class BackupAuthManagerTest {
@MethodSource
void invalidCredentialTimeWindows(final Instant requestRedemptionStart, final Instant requestRedemptionEnd,
final Instant now) {
final BackupAuthManager authManager = create(BackupLevel.FREE);
final BackupAuthManager authManager = create();
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(aci);
when(account.getBackupCredentialRequest(BackupCredentialType.MESSAGES))
.thenReturn(Optional.of(backupAuthTestUtil.getRequest(messagesBackupKey, aci).serialize()));
when(account.getBackupCredentialRequest(BackupCredentialType.MEDIA))
.thenReturn(Optional.of(backupAuthTestUtil.getRequest(mediaBackupKey, aci).serialize()));
final Account account = new MockAccountBuilder()
.messagesCredential(backupAuthTestUtil.getRequest(messagesBackupKey, aci))
.mediaCredential(backupAuthTestUtil.getRequest(mediaBackupKey, aci))
.build();
clock.pin(now);
assertThatExceptionOfType(StatusRuntimeException.class)
@@ -292,15 +306,13 @@ public class BackupAuthManagerTest {
final Instant day4 = Instant.EPOCH.plus(Duration.ofDays(4));
final Instant dayMax = day0.plus(BackupAuthManager.MAX_REDEMPTION_DURATION);
final BackupAuthManager authManager = create(BackupLevel.FREE);
final BackupAuthManager authManager = create();
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(aci);
when(account.getBackupCredentialRequest(BackupCredentialType.MESSAGES))
.thenReturn(Optional.of(backupAuthTestUtil.getRequest(messagesBackupKey, aci).serialize()));
when(account.getBackupCredentialRequest(BackupCredentialType.MEDIA))
.thenReturn(Optional.of(backupAuthTestUtil.getRequest(mediaBackupKey, aci).serialize()));
when(account.getBackupVoucher()).thenReturn(new Account.BackupVoucher(201, day4));
final Account account = new MockAccountBuilder()
.messagesCredential(backupAuthTestUtil.getRequest(messagesBackupKey, aci))
.mediaCredential(backupAuthTestUtil.getRequest(mediaBackupKey, aci))
.backupVoucher(new Account.BackupVoucher(201, day4))
.build();
final List<BackupAuthManager.Credential> creds = authManager.getBackupAuthCredentials(account, BackupCredentialType.MESSAGES, day0, dayMax).join();
Instant redemptionTime = day0;
@@ -325,19 +337,19 @@ public class BackupAuthManagerTest {
final Instant day2 = Instant.EPOCH.plus(Duration.ofDays(2));
final Instant day3 = Instant.EPOCH.plus(Duration.ofDays(3));
final BackupAuthManager authManager = create(BackupLevel.FREE);
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(aci);
when(account.getBackupVoucher()).thenReturn(new Account.BackupVoucher(3, day1));
final BackupAuthManager authManager = create();
final Account account = new MockAccountBuilder()
.messagesCredential(backupAuthTestUtil.getRequest(messagesBackupKey, aci))
.mediaCredential(backupAuthTestUtil.getRequest(mediaBackupKey, aci))
.backupVoucher(new Account.BackupVoucher(3, day1))
.build();
final Account updated = mock(Account.class);
when(updated.getUuid()).thenReturn(aci);
when(updated.getBackupCredentialRequest(BackupCredentialType.MESSAGES))
.thenReturn(Optional.of(backupAuthTestUtil.getRequest(messagesBackupKey, aci).serialize()));
when(updated.getBackupCredentialRequest(BackupCredentialType.MEDIA))
.thenReturn(Optional.of(backupAuthTestUtil.getRequest(mediaBackupKey, aci).serialize()));
final Account updated = new MockAccountBuilder()
.messagesCredential(backupAuthTestUtil.getRequest(messagesBackupKey, aci))
.mediaCredential(backupAuthTestUtil.getRequest(mediaBackupKey, aci))
.backupVoucher(null)
.build();
when(updated.getBackupVoucher()).thenReturn(null);
when(accountsManager.updateAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(updated));
clock.pin(day2.plus(Duration.ofSeconds(1)));
@@ -365,11 +377,10 @@ public class BackupAuthManagerTest {
@Test
void redeemReceipt() throws InvalidInputException, VerificationFailedException {
final Instant expirationTime = Instant.EPOCH.plus(Duration.ofDays(1));
final BackupAuthManager authManager = create(BackupLevel.FREE);
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(aci);
when(account.getBackupCredentialRequest(BackupCredentialType.MEDIA)).thenReturn(Optional.of(new byte[0]));
final BackupAuthManager authManager = create();
final Account account = new MockAccountBuilder()
.mediaCredential(Optional.of(new byte[0]))
.build();
clock.pin(Instant.EPOCH.plus(Duration.ofDays(1)));
when(accountsManager.updateAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(account));
when(redeemedReceiptsManager.put(any(), eq(expirationTime.getEpochSecond()), eq(201L), eq(aci)))
@@ -381,10 +392,8 @@ public class BackupAuthManagerTest {
@Test
void redeemReceiptNoBackupRequest() {
final Instant expirationTime = Instant.EPOCH.plus(Duration.ofDays(1));
final BackupAuthManager authManager = create(BackupLevel.FREE);
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(aci);
when(account.getBackupCredentialRequest(BackupCredentialType.MEDIA)).thenReturn(Optional.empty());
final BackupAuthManager authManager = create();
final Account account = new MockAccountBuilder().mediaCredential(Optional.empty()).build();
clock.pin(Instant.EPOCH.plus(Duration.ofDays(1)));
when(redeemedReceiptsManager.put(any(), eq(expirationTime.getEpochSecond()), eq(201L), eq(aci)))
@@ -401,13 +410,12 @@ public class BackupAuthManagerTest {
final Instant newExpirationTime = Instant.EPOCH.plus(Duration.ofDays(1));
final Instant existingExpirationTime = Instant.EPOCH.plus(Duration.ofDays(1)).plus(Duration.ofSeconds(1));
final BackupAuthManager authManager = create(BackupLevel.FREE);
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(aci);
when(account.getBackupCredentialRequest(BackupCredentialType.MEDIA)).thenReturn(Optional.of(new byte[0]));
// The account has an existing voucher with a later expiration date
when(account.getBackupVoucher()).thenReturn(new Account.BackupVoucher(201, existingExpirationTime));
final BackupAuthManager authManager = create();
final Account account = new MockAccountBuilder()
.mediaCredential(Optional.of(new byte[0]))
// The account has an existing voucher with a later expiration date
.backupVoucher(new Account.BackupVoucher(201, existingExpirationTime))
.build();
clock.pin(Instant.EPOCH.plus(Duration.ofDays(1)));
when(accountsManager.updateAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(account));
@@ -427,7 +435,7 @@ public class BackupAuthManagerTest {
void redeemExpiredReceipt() {
final Instant expirationTime = Instant.EPOCH.plus(Duration.ofDays(1));
clock.pin(expirationTime.plus(Duration.ofSeconds(1)));
final BackupAuthManager authManager = create(BackupLevel.FREE);
final BackupAuthManager authManager = create();
assertThatExceptionOfType(StatusRuntimeException.class)
.isThrownBy(() -> authManager.redeemReceipt(mock(Account.class), receiptPresentation(3, expirationTime)).join())
.extracting(ex -> ex.getStatus().getCode())
@@ -441,7 +449,7 @@ public class BackupAuthManagerTest {
void redeemInvalidLevel(long level) {
final Instant expirationTime = Instant.EPOCH.plus(Duration.ofDays(1));
clock.pin(expirationTime.plus(Duration.ofSeconds(1)));
final BackupAuthManager authManager = create(BackupLevel.FREE);
final BackupAuthManager authManager = create();
assertThatExceptionOfType(StatusRuntimeException.class)
.isThrownBy(() ->
authManager.redeemReceipt(mock(Account.class), receiptPresentation(level, expirationTime)).join())
@@ -453,7 +461,7 @@ public class BackupAuthManagerTest {
@Test
void redeemInvalidPresentation() throws InvalidInputException, VerificationFailedException {
final BackupAuthManager authManager = create(BackupLevel.FREE);
final BackupAuthManager authManager = create();
final ReceiptCredentialPresentation invalid = receiptPresentation(ServerSecretParams.generate(), 3L, Instant.EPOCH);
assertThatExceptionOfType(StatusRuntimeException.class)
.isThrownBy(() -> authManager.redeemReceipt(mock(Account.class), invalid).join())
@@ -466,10 +474,10 @@ public class BackupAuthManagerTest {
@Test
void receiptAlreadyRedeemed() throws InvalidInputException, VerificationFailedException {
final Instant expirationTime = Instant.EPOCH.plus(Duration.ofDays(1));
final BackupAuthManager authManager = create(BackupLevel.FREE);
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(aci);
when(account.getBackupCredentialRequest(BackupCredentialType.MEDIA)).thenReturn(Optional.of(new byte[0]));
final BackupAuthManager authManager = create();
final Account account = new MockAccountBuilder()
.mediaCredential(Optional.of(new byte[0]))
.build();
clock.pin(Instant.EPOCH.plus(Duration.ofDays(1)));
when(accountsManager.updateAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(account));
@@ -513,7 +521,12 @@ public class BackupAuthManagerTest {
final BackupAuthManager authManager = create(BackupLevel.FREE, rateLimiter(aci, rateLimitBackupId, false));
final BackupAuthCredentialRequest storedMessagesCredential = backupAuthTestUtil.getRequest(messagesBackupKey, aci);
final BackupAuthCredentialRequest storedMediaCredential = backupAuthTestUtil.getRequest(mediaBackupKey, aci);
final Account account = mockAccount(storedMessagesCredential, storedMediaCredential, null);
final Account account = new MockAccountBuilder()
.mediaCredential(storedMediaCredential)
.messagesCredential(storedMessagesCredential)
.backupVoucher(null)
.build();
when(accountsManager.updateAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(account));
final BackupAuthCredentialRequest newMessagesCredential = changeMessage
? backupAuthTestUtil.getRequest(TestRandomUtil.nextBytes(32), aci)
@@ -546,7 +559,12 @@ public class BackupAuthManagerTest {
final Account.BackupVoucher backupVoucher = new Account.BackupVoucher(1, Instant.ofEpochSecond(100));
clock.pin(paid ? Instant.ofEpochSecond(99) : Instant.ofEpochSecond(101));
final Account account = mockAccount(storedMessagesCredential, storedMediaCredential, backupVoucher);
final Account account = new MockAccountBuilder()
.mediaCredential(storedMediaCredential)
.messagesCredential(storedMessagesCredential)
.backupVoucher(backupVoucher)
.build();
when(accountsManager.updateAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(account));
final BackupAuthCredentialRequest newMessagesCredential = changeMessage
? backupAuthTestUtil.getRequest(TestRandomUtil.nextBytes(32), aci)
@@ -566,22 +584,6 @@ public class BackupAuthManagerTest {
}
}
private Account mockAccount(final BackupAuthCredentialRequest storedMessagesCredential, final BackupAuthCredentialRequest storedMediaCredential, Account.BackupVoucher backupVoucher) {
final Account account = mock(Account.class);
when(accountsManager.updateAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(account));
if (storedMessagesCredential != null) {
when(account.getBackupCredentialRequest(BackupCredentialType.MESSAGES))
.thenReturn(Optional.of(storedMessagesCredential.serialize()));
}
if (storedMediaCredential != null) {
when(account.getBackupCredentialRequest(BackupCredentialType.MEDIA))
.thenReturn(Optional.of(storedMediaCredential.serialize()));
}
when(account.getUuid()).thenReturn(aci);
when(account.getBackupVoucher()).thenReturn(backupVoucher);
return account;
}
private Device primaryDevice() {
final Device device = mock(Device.class);
when(device.isPrimary()).thenReturn(true);
@@ -594,14 +596,48 @@ public class BackupAuthManagerTest {
return device;
}
private static String experimentName(@Nullable BackupLevel backupLevel) {
return switch (backupLevel) {
case FREE -> BackupAuthManager.BACKUP_EXPERIMENT_NAME;
case PAID -> BackupAuthManager.BACKUP_MEDIA_EXPERIMENT_NAME;
case null -> "fake_experiment";
};
private class MockAccountBuilder {
private Account account = mock(Account.class);
MockAccountBuilder() {
when(account.getUuid()).thenReturn(aci);
}
MockAccountBuilder backupLevel(BackupLevel backupLevel) {
if (backupLevel == BackupLevel.PAID) {
return backupVoucher(new Account.BackupVoucher(201L, clock.instant().plus(Duration.ofDays(8))));
}
return this;
}
MockAccountBuilder backupVoucher(Account.BackupVoucher backupVoucher) {
when(account.getBackupVoucher()).thenReturn(backupVoucher);
return this;
}
MockAccountBuilder mediaCredential(final BackupAuthCredentialRequest storedMediaCredential) {
return mediaCredential(Optional.of(storedMediaCredential.serialize()));
}
MockAccountBuilder mediaCredential(final Optional<byte[]> serializedMediaCredential) {
when(account.getBackupCredentialRequest(BackupCredentialType.MEDIA))
.thenReturn(serializedMediaCredential);
return this;
}
MockAccountBuilder messagesCredential(final BackupAuthCredentialRequest storedMessagesCredential) {
when(account.getBackupCredentialRequest(BackupCredentialType.MESSAGES))
.thenReturn(Optional.of(storedMessagesCredential.serialize()));
return this;
}
Account build() {
return account;
}
}
private static RateLimiters rateLimiter(final UUID aci, boolean rateLimitBackupId,
boolean rateLimitPaidMediaBackupId) {
final RateLimiters limiters = mock(RateLimiters.class);
@@ -21,8 +21,8 @@ import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialRequest;
import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialRequestContext;
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
import org.signal.libsignal.zkgroup.backups.BackupLevel;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.tests.util.ExperimentHelper;
public class BackupAuthTestUtil {
@@ -64,15 +64,15 @@ public class BackupAuthTestUtil {
final Instant redemptionEnd) {
final UUID aci = UUID.randomUUID();
final String experimentName = switch (backupLevel) {
case FREE -> BackupAuthManager.BACKUP_EXPERIMENT_NAME;
case PAID -> BackupAuthManager.BACKUP_MEDIA_EXPERIMENT_NAME;
};
final BackupAuthManager issuer = new BackupAuthManager(
ExperimentHelper.withEnrollment(experimentName, aci), null, null, null, null, params, clock);
mock(ExperimentEnrollmentManager.class), null, null, null, null, params, clock);
Account account = mock(Account.class);
when(account.getUuid()).thenReturn(aci);
when(account.getBackupCredentialRequest(credentialType)).thenReturn(Optional.of(request.serialize()));
when(account.getBackupVoucher()).thenReturn(switch (backupLevel) {
case FREE -> null;
case PAID -> new Account.BackupVoucher(201L, redemptionEnd.plus(1, ChronoUnit.SECONDS));
});
return issuer.getBackupAuthCredentials(account, credentialType, redemptionStart, redemptionEnd).join();
}
}
@@ -20,6 +20,7 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.whispersystems.textsecuregcm.util.MockUtils.randomSecretBytes;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
@@ -36,6 +37,7 @@ import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.HashSet;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -43,11 +45,8 @@ import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javax.annotation.Nullable;
import org.apache.commons.lang3.RandomStringUtils;
@@ -71,9 +70,13 @@ import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
import org.signal.libsignal.zkgroup.backups.BackupLevel;
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
import org.whispersystems.textsecuregcm.configuration.SecureValueRecoveryConfiguration;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtension;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema;
import org.whispersystems.textsecuregcm.util.AttributeValues;
@@ -107,6 +110,18 @@ public class BackupManagerTest {
private final byte[] backupKey = TestRandomUtil.nextBytes(32);
private final UUID aci = UUID.randomUUID();
private static final SecureValueRecoveryConfiguration CFG = new SecureValueRecoveryConfiguration(
"",
randomSecretBytes(32),
randomSecretBytes(32),
null,
null,
null);
private final ExternalServiceCredentialsGenerator svrbCredentialGenerator =
SecureValueRecoveryBCredentialsGeneratorFactory.svrbCredentialsGenerator(CFG, testClock);
private final SecureValueRecoveryClient svrbClient = mock(SecureValueRecoveryClient.class);
private BackupManager backupManager;
private BackupsDb backupsDb;
@@ -131,6 +146,8 @@ public class BackupManagerTest {
tusAttachmentGenerator,
tusCredentialGenerator,
remoteStorageManager,
svrbCredentialGenerator,
svrbClient,
testClock);
}
@@ -697,9 +714,13 @@ public class BackupManagerTest {
testClock.pin(Instant.ofEpochSecond(10));
when(svrbClient.removeData(anyString())).thenReturn(CompletableFuture.completedFuture(null));
// Deleting should swap the backupDir for the user
backupManager.deleteEntireBackup(original).join();
verifyNoInteractions(remoteStorageManager);
verify(svrbClient).removeData(HexFormat.of().formatHex(BackupsDb.hashedBackupId(original.backupId())));
final AuthenticatedBackupUser after = retrieveBackupUser(original.backupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID);
assertThat(original.backupDir()).isNotEqualTo(after.backupDir());
assertThat(original.mediaDir()).isNotEqualTo(after.mediaDir());
@@ -959,11 +980,15 @@ public class BackupManagerTest {
new RemoteStorageManager.ListResult.Entry("ghi", 1)), Optional.empty())));
when(remoteStorageManager.delete(anyString())).thenReturn(CompletableFuture.completedFuture(1L));
when(svrbClient.removeData(anyString())).thenReturn(CompletableFuture.completedFuture(null));
backupManager.expireBackup(expiredBackup(expirationType, backupUser)).join();
verify(remoteStorageManager, times(1)).list(anyString(), any(), anyLong());
verify(remoteStorageManager, times(1)).delete(expectedPrefixToDelete + "abc");
verify(remoteStorageManager, times(1)).delete(expectedPrefixToDelete + "def");
verify(remoteStorageManager, times(1)).delete(expectedPrefixToDelete + "ghi");
verify(svrbClient, times(expirationType == ExpiredBackup.ExpirationType.ALL ? 1 : 0))
.removeData(HexFormat.of().formatHex(BackupsDb.hashedBackupId(backupUser.backupId())));
verifyNoMoreInteractions(remoteStorageManager);
final BackupsDb.TimestampedUsageInfo usage = backupsDb.getMediaUsage(backupUser).join();
@@ -1020,6 +1045,32 @@ public class BackupManagerTest {
verifyNoMoreInteractions(remoteStorageManager);
}
@ParameterizedTest
@EnumSource(BackupLevel.class)
void svrbAuthValid(BackupLevel backupLevel) {
testClock.pin(Instant.ofEpochSecond(123));
final AuthenticatedBackupUser backupUser =
backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MESSAGES, backupLevel);
final ExternalServiceCredentials creds = backupManager.generateSvrbAuth(backupUser);
assertThat(HexFormat.of().parseHex(creds.username())).hasSize(16);
final String[] split = creds.password().split(":", 2);
assertThat(Long.parseLong(split[0])).isEqualTo(123);
}
@ParameterizedTest
@EnumSource(BackupLevel.class)
void svrbAuthInvalid(BackupLevel backupLevel) {
// Can't use MEDIA for svrb auth
final AuthenticatedBackupUser backupUser =
backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MEDIA, backupLevel);
assertThatExceptionOfType(StatusRuntimeException.class)
.isThrownBy(() -> backupManager.generateSvrbAuth(backupUser))
.extracting(StatusRuntimeException::getStatus)
.extracting(Status::getCode)
.isEqualTo(Status.Code.UNAUTHENTICATED);
}
private CopyResult copyError(final AuthenticatedBackupUser backupUser, Throwable copyException) {
when(tusCredentialGenerator.generateUpload(any()))
.thenReturn(new BackupUploadDescriptor(3, "def", Collections.emptyMap(), ""));
@@ -63,6 +63,7 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
import org.whispersystems.textsecuregcm.backup.BackupAuthTestUtil;
import org.whispersystems.textsecuregcm.backup.BackupManager;
@@ -116,6 +117,7 @@ public class ArchiveControllerTest {
@ParameterizedTest
@CsvSource(textBlock = """
GET, v1/archives/auth/read,
GET, v1/archives/auth/svrb,
GET, v1/archives/,
GET, v1/archives/upload/form,
GET, v1/archives/media/upload/form,
@@ -663,6 +665,24 @@ public class ArchiveControllerTest {
assertThat(response.headers()).containsExactlyEntriesOf(Map.of("key", "value"));
}
@Test
public void svrbAuth() throws VerificationFailedException {
final BackupAuthCredentialPresentation presentation =
backupAuthTestUtil.getPresentation(BackupLevel.PAID, messagesBackupKey, aci);
when(backupManager.authenticateBackupUser(any(), any(), any()))
.thenReturn(CompletableFuture.completedFuture(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID)));
final ExternalServiceCredentials credentials = new ExternalServiceCredentials("username", "password");
when(backupManager.generateSvrbAuth(any())).thenReturn(credentials);
final ExternalServiceCredentials response = resources.getJerseyTest()
.target("v1/archives/auth/svrb")
.request()
.header("X-Signal-ZK-Auth", Base64.getEncoder().encodeToString(presentation.serialize()))
.header("X-Signal-ZK-Auth-Signature", "aaa")
.get(ExternalServiceCredentials.class);
assertThat(response).isEqualTo(credentials);
}
@Test
public void readAuthInvalidParam() throws VerificationFailedException {
final BackupAuthCredentialPresentation presentation =
@@ -348,7 +348,8 @@ class DeviceControllerTest {
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.of(new GcmRegistrationId("gcm-id"))));
final int expectedStatus =
capability.preventDowngrade() && accountHasCapability && !requestHasCapability ? 409 : 200;
capability.getAccountCapabilityMode() != DeviceCapability.AccountCapabilityMode.ALWAYS_CAPABLE
&& capability.preventDowngrade() && accountHasCapability && !requestHasCapability ? 409 : 200;
try (final Response response = resources.getJerseyTest()
.target("/v1/devices/link")
@@ -1082,31 +1083,39 @@ class DeviceControllerTest {
}
}
@Test
void recordTransferArchiveUploaded() {
@ParameterizedTest
@MethodSource
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
void recordTransferArchiveUploaded(final Optional<Instant> deviceCreated, final Optional<Integer> registrationId) {
final byte deviceId = Device.PRIMARY_ID + 1;
final Instant deviceCreated = Instant.now().truncatedTo(ChronoUnit.MILLIS);
final RemoteAttachment transferArchive =
new RemoteAttachment(3, Base64.getUrlEncoder().encodeToString("test".getBytes(StandardCharsets.UTF_8)));
when(rateLimiter.validateAsync(AuthHelper.VALID_UUID)).thenReturn(CompletableFuture.completedFuture(null));
when(accountsManager.recordTransferArchiveUpload(account, deviceId, deviceCreated, transferArchive))
when(accountsManager.recordTransferArchiveUpload(account, deviceId, deviceCreated, registrationId, transferArchive))
.thenReturn(CompletableFuture.completedFuture(null));
try (final Response response = resources.getJerseyTest()
.target("/v1/devices/transfer_archive")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.entity(new TransferArchiveUploadedRequest(deviceId, deviceCreated.toEpochMilli(), transferArchive),
.put(Entity.entity(new TransferArchiveUploadedRequest(deviceId, deviceCreated.map(Instant::toEpochMilli), registrationId, transferArchive),
MediaType.APPLICATION_JSON_TYPE))) {
assertEquals(204, response.getStatus());
verify(accountsManager)
.recordTransferArchiveUpload(account, deviceId, deviceCreated, transferArchive);
.recordTransferArchiveUpload(account, deviceId, deviceCreated, registrationId, transferArchive);
}
}
private static List<Arguments> recordTransferArchiveUploaded() {
return List.of(
Arguments.of(Optional.empty(), Optional.of(123)),
Arguments.of(Optional.of(Instant.now().truncatedTo(ChronoUnit.MILLIS)), Optional.empty())
);
}
@Test
void recordTransferArchiveFailed() {
final byte deviceId = Device.PRIMARY_ID + 1;
@@ -1114,20 +1123,20 @@ class DeviceControllerTest {
final RemoteAttachmentError transferFailure = new RemoteAttachmentError(RemoteAttachmentError.ErrorType.CONTINUE_WITHOUT_UPLOAD);
when(rateLimiter.validateAsync(AuthHelper.VALID_UUID)).thenReturn(CompletableFuture.completedFuture(null));
when(accountsManager.recordTransferArchiveUpload(account, deviceId, deviceCreated, transferFailure))
when(accountsManager.recordTransferArchiveUpload(account, deviceId, Optional.of(deviceCreated), Optional.empty(), transferFailure))
.thenReturn(CompletableFuture.completedFuture(null));
try (final Response response = resources.getJerseyTest()
.target("/v1/devices/transfer_archive")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.entity(new TransferArchiveUploadedRequest(deviceId, deviceCreated.toEpochMilli(), transferFailure),
.put(Entity.entity(new TransferArchiveUploadedRequest(deviceId, Optional.of(deviceCreated.toEpochMilli()), Optional.empty(), transferFailure),
MediaType.APPLICATION_JSON_TYPE))) {
assertEquals(204, response.getStatus());
verify(accountsManager)
.recordTransferArchiveUpload(account, deviceId, deviceCreated, transferFailure);
.recordTransferArchiveUpload(account, deviceId, Optional.of(deviceCreated), Optional.empty(), transferFailure);
}
}
@@ -1145,29 +1154,33 @@ class DeviceControllerTest {
assertEquals(422, response.getStatus());
verify(accountsManager, never())
.recordTransferArchiveUpload(any(), anyByte(), any(), any());
.recordTransferArchiveUpload(any(), anyByte(), any(), any(), any());
}
}
@SuppressWarnings("DataFlowIssue")
private static List<TransferArchiveUploadedRequest> recordTransferArchiveUploadedBadRequest() {
private static List<Arguments> recordTransferArchiveUploadedBadRequest() {
final RemoteAttachment validTransferArchive =
new RemoteAttachment(3, Base64.getUrlEncoder().encodeToString("archive".getBytes(StandardCharsets.UTF_8)));
return List.of(
// Invalid device ID
new TransferArchiveUploadedRequest((byte) -1, System.currentTimeMillis(), validTransferArchive),
// Invalid "created at" timestamp
new TransferArchiveUploadedRequest(Device.PRIMARY_ID, -1, validTransferArchive),
// Missing CDN number
new TransferArchiveUploadedRequest(Device.PRIMARY_ID, System.currentTimeMillis(),
new RemoteAttachment(null, Base64.getUrlEncoder().encodeToString("archive".getBytes(StandardCharsets.UTF_8)))),
// Bad attachment key
new TransferArchiveUploadedRequest(Device.PRIMARY_ID, System.currentTimeMillis(),
new RemoteAttachment(3, "This is not a valid base64 string"))
Arguments.argumentSet("Invalid device ID", new TransferArchiveUploadedRequest((byte) -1, Optional.of(System.currentTimeMillis()), Optional.empty(), validTransferArchive)),
Arguments.argumentSet("Invalid \"created at\" timestamp",
new TransferArchiveUploadedRequest(Device.PRIMARY_ID, Optional.of((long) -1), Optional.empty(), validTransferArchive)),
Arguments.argumentSet("Invalid registration ID - negative",
new TransferArchiveUploadedRequest(Device.PRIMARY_ID, Optional.empty(), Optional.of(-1), validTransferArchive)),
Arguments.argumentSet("Invalid registration ID - too large",
new TransferArchiveUploadedRequest(Device.PRIMARY_ID, Optional.empty(), Optional.of(0x4000), validTransferArchive)),
Arguments.argumentSet("Exactly one of \"created at\" timestamp and registration ID must be present - neither provided",
new TransferArchiveUploadedRequest(Device.PRIMARY_ID, Optional.empty(), Optional.empty(), validTransferArchive)),
Arguments.argumentSet("Exactly one of \"created at\" timestamp and registration ID must be present - both provided",
new TransferArchiveUploadedRequest(Device.PRIMARY_ID, Optional.of(System.currentTimeMillis()), Optional.of(123), validTransferArchive)),
Arguments.argumentSet("Missing CDN number",
new TransferArchiveUploadedRequest(Device.PRIMARY_ID, Optional.of(System.currentTimeMillis()), Optional.empty(),
new RemoteAttachment(null, Base64.getUrlEncoder().encodeToString("archive".getBytes(StandardCharsets.UTF_8))))),
Arguments.argumentSet("Bad attachment key",
new TransferArchiveUploadedRequest(Device.PRIMARY_ID, Optional.of(System.currentTimeMillis()), Optional.empty(),
new RemoteAttachment(3, "This is not a valid base64 string")))
);
}
@@ -1180,14 +1193,14 @@ class DeviceControllerTest {
.target("/v1/devices/transfer_archive")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.entity(new TransferArchiveUploadedRequest(Device.PRIMARY_ID, System.currentTimeMillis(),
.put(Entity.entity(new TransferArchiveUploadedRequest(Device.PRIMARY_ID, Optional.of(System.currentTimeMillis()), Optional.empty(),
new RemoteAttachment(3, Base64.getUrlEncoder().encodeToString("test".getBytes(StandardCharsets.UTF_8)))),
MediaType.APPLICATION_JSON_TYPE))) {
assertEquals(429, response.getStatus());
verify(accountsManager, never())
.recordTransferArchiveUpload(any(), anyByte(), any(), any());
.recordTransferArchiveUpload(any(), anyByte(), any(), any(), any());
}
}
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.controllers;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyByte;
import static org.mockito.ArgumentMatchers.anyString;
@@ -35,6 +36,7 @@ import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
@@ -63,6 +65,7 @@ import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.entities.PreKeyCount;
import org.whispersystems.textsecuregcm.entities.PreKeyResponse;
import org.whispersystems.textsecuregcm.entities.PreKeyResponseItem;
import org.whispersystems.textsecuregcm.entities.SetKeysRequest;
import org.whispersystems.textsecuregcm.entities.SignedPreKey;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
@@ -93,6 +96,7 @@ class KeysControllerTest {
private static final UUID EXISTS_UUID = UUID.randomUUID();
private static final UUID EXISTS_PNI = UUID.randomUUID();
private static final AciServiceIdentifier EXISTS_ACI = new AciServiceIdentifier(EXISTS_UUID);
private static final PniServiceIdentifier EXISTS_PNI_SERVICE_ID = new PniServiceIdentifier(EXISTS_PNI);
private static final UUID OTHER_UUID = UUID.randomUUID();
private static final AciServiceIdentifier OTHER_ACI = new AciServiceIdentifier(OTHER_UUID);
@@ -101,16 +105,9 @@ class KeysControllerTest {
private static final AciServiceIdentifier NOT_EXISTS_ACI = new AciServiceIdentifier(NOT_EXISTS_UUID);
private static final byte SAMPLE_DEVICE_ID = 1;
private static final byte SAMPLE_DEVICE_ID2 = 2;
private static final byte SAMPLE_DEVICE_ID3 = 3;
private static final byte SAMPLE_DEVICE_ID4 = 4;
private static final int SAMPLE_REGISTRATION_ID = 999;
private static final int SAMPLE_REGISTRATION_ID2 = 1002;
private static final int SAMPLE_REGISTRATION_ID4 = 1555;
private static final int SAMPLE_PNI_REGISTRATION_ID = 1717;
private static final int SAMPLE_PNI_REGISTRATION_ID2 = 1718;
private final ECKeyPair IDENTITY_KEY_PAIR = ECKeyPair.generate();
private final IdentityKey IDENTITY_KEY = new IdentityKey(IDENTITY_KEY_PAIR.getPublicKey());
@@ -119,34 +116,21 @@ class KeysControllerTest {
private final IdentityKey PNI_IDENTITY_KEY = new IdentityKey(PNI_IDENTITY_KEY_PAIR.getPublicKey());
private final ECPreKey SAMPLE_KEY = KeysHelper.ecPreKey(1234);
private final ECPreKey SAMPLE_KEY2 = KeysHelper.ecPreKey(5667);
private final ECPreKey SAMPLE_KEY3 = KeysHelper.ecPreKey(334);
private final ECPreKey SAMPLE_KEY4 = KeysHelper.ecPreKey(336);
private final ECPreKey SAMPLE_KEY_PNI = KeysHelper.ecPreKey(7777);
private final KEMSignedPreKey SAMPLE_PQ_KEY = KeysHelper.signedKEMPreKey(2424, ECKeyPair.generate());
private final KEMSignedPreKey SAMPLE_PQ_KEY2 = KeysHelper.signedKEMPreKey(6868, ECKeyPair.generate());
private final KEMSignedPreKey SAMPLE_PQ_KEY3 = KeysHelper.signedKEMPreKey(1313, ECKeyPair.generate());
private final KEMSignedPreKey SAMPLE_PQ_KEY4 = KeysHelper.signedKEMPreKey(7676, ECKeyPair.generate());
private final KEMSignedPreKey SAMPLE_PQ_KEY_PNI = KeysHelper.signedKEMPreKey(8888, ECKeyPair.generate());
private final ECSignedPreKey SAMPLE_SIGNED_KEY = KeysHelper.signedECPreKey(1111, IDENTITY_KEY_PAIR);
private final ECSignedPreKey SAMPLE_SIGNED_KEY2 = KeysHelper.signedECPreKey(2222, IDENTITY_KEY_PAIR);
private final ECSignedPreKey SAMPLE_SIGNED_KEY3 = KeysHelper.signedECPreKey(3333, IDENTITY_KEY_PAIR);
private final ECSignedPreKey SAMPLE_SIGNED_PNI_KEY = KeysHelper.signedECPreKey(4444, PNI_IDENTITY_KEY_PAIR);
private final ECSignedPreKey SAMPLE_SIGNED_PNI_KEY2 = KeysHelper.signedECPreKey(5555, PNI_IDENTITY_KEY_PAIR);
private final ECSignedPreKey SAMPLE_SIGNED_PNI_KEY3 = KeysHelper.signedECPreKey(6666, PNI_IDENTITY_KEY_PAIR);
private final ECSignedPreKey VALID_DEVICE_SIGNED_KEY = KeysHelper.signedECPreKey(89898, IDENTITY_KEY_PAIR);
private final ECSignedPreKey VALID_DEVICE_PNI_SIGNED_KEY = KeysHelper.signedECPreKey(7777, PNI_IDENTITY_KEY_PAIR);
private final ECSignedPreKey SAMPLE_SIGNED_PNI_KEY = KeysHelper.signedECPreKey(5555, PNI_IDENTITY_KEY_PAIR);
private final static KeysManager KEYS = mock(KeysManager.class );
private final static AccountsManager accounts = mock(AccountsManager.class );
private final static Account existsAccount = mock(Account.class );
private static final RateLimiters rateLimiters = mock(RateLimiters.class);
private static final RateLimiter rateLimiter = mock(RateLimiter.class );
private final static KeysManager KEYS = mock(KeysManager.class);
private final static AccountsManager accounts = mock(AccountsManager.class);
private final static Account existsAccount = mock(Account.class);
private static final RateLimiters rateLimiters = mock(RateLimiters.class);
private static final RateLimiter rateLimiter = mock(RateLimiter.class);
private static final ServerSecretParams serverSecretParams = ServerSecretParams.generate();
@@ -163,9 +147,6 @@ class KeysControllerTest {
.addResource(new RateLimitExceededExceptionMapper())
.build();
private Device sampleDevice;
private Device sampleDevice2;
private record WeaklyTypedPreKey(long keyId,
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@@ -198,34 +179,33 @@ class KeysControllerTest {
byte[] identityKey) {
}
private Device createSampleDevice(byte deviceId, int registrationId, int pniRegistrationId) {
final Device sampleDevice = mock(Device.class);
when(sampleDevice.getRegistrationId(IdentityType.ACI)).thenReturn(registrationId);
when(sampleDevice.getRegistrationId(IdentityType.PNI)).thenReturn(pniRegistrationId);
when(sampleDevice.getId()).thenReturn(deviceId);
return sampleDevice;
}
@BeforeEach
void setup() {
clock.unpin();
sampleDevice = mock(Device.class);
sampleDevice2 = mock(Device.class);
final Device sampleDevice3 = mock(Device.class);
final Device sampleDevice4 = mock(Device.class);
final List<Device> allDevices = List.of(sampleDevice, sampleDevice2, sampleDevice3, sampleDevice4);
final byte sampleDeviceId = 1;
final byte sampleDevice2Id = 2;
final byte sampleDevice3Id = 3;
final byte sampleDevice4Id = 4;
AccountsHelper.setupMockUpdate(accounts);
when(sampleDevice.getRegistrationId(IdentityType.ACI)).thenReturn(SAMPLE_REGISTRATION_ID);
when(sampleDevice2.getRegistrationId(IdentityType.ACI)).thenReturn(SAMPLE_REGISTRATION_ID2);
when(sampleDevice3.getRegistrationId(IdentityType.ACI)).thenReturn(SAMPLE_REGISTRATION_ID2);
when(sampleDevice4.getRegistrationId(IdentityType.ACI)).thenReturn(SAMPLE_REGISTRATION_ID4);
when(sampleDevice.getRegistrationId(IdentityType.PNI)).thenReturn(SAMPLE_PNI_REGISTRATION_ID);
when(sampleDevice2.getRegistrationId(IdentityType.PNI)).thenReturn(SAMPLE_PNI_REGISTRATION_ID2);
when(sampleDevice.getId()).thenReturn(sampleDeviceId);
when(sampleDevice2.getId()).thenReturn(sampleDevice2Id);
when(sampleDevice3.getId()).thenReturn(sampleDevice3Id);
when(sampleDevice4.getId()).thenReturn(sampleDevice4Id);
final Device sampleDevice =
createSampleDevice(SAMPLE_DEVICE_ID, SAMPLE_REGISTRATION_ID, SAMPLE_PNI_REGISTRATION_ID);
final KeysManager.DevicePreKeys aciKeys =
new KeysManager.DevicePreKeys(SAMPLE_SIGNED_KEY, Optional.of(SAMPLE_KEY), SAMPLE_PQ_KEY);
final KeysManager.DevicePreKeys pniKeys =
new KeysManager.DevicePreKeys(SAMPLE_SIGNED_PNI_KEY, Optional.of(SAMPLE_KEY_PNI), SAMPLE_PQ_KEY_PNI);
when(KEYS.takeDevicePreKeys(eq(SAMPLE_DEVICE_ID), eq(EXISTS_ACI), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.of(aciKeys)));
when(KEYS.takeDevicePreKeys(eq(SAMPLE_DEVICE_ID), eq(EXISTS_PNI_SERVICE_ID), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.of(pniKeys)));
when(existsAccount.getUuid()).thenReturn(EXISTS_UUID);
when(existsAccount.isIdentifiedBy(new AciServiceIdentifier(EXISTS_UUID))).thenReturn(true);
@@ -233,12 +213,8 @@ class KeysControllerTest {
when(existsAccount.isIdentifiedBy(new PniServiceIdentifier(EXISTS_PNI))).thenReturn(true);
when(existsAccount.getIdentifier(IdentityType.ACI)).thenReturn(EXISTS_UUID);
when(existsAccount.getIdentifier(IdentityType.PNI)).thenReturn(EXISTS_PNI);
when(existsAccount.getDevice(sampleDeviceId)).thenReturn(Optional.of(sampleDevice));
when(existsAccount.getDevice(sampleDevice2Id)).thenReturn(Optional.of(sampleDevice2));
when(existsAccount.getDevice(sampleDevice3Id)).thenReturn(Optional.of(sampleDevice3));
when(existsAccount.getDevice(sampleDevice4Id)).thenReturn(Optional.of(sampleDevice4));
when(existsAccount.getDevice((byte) 22)).thenReturn(Optional.empty());
when(existsAccount.getDevices()).thenReturn(allDevices);
when(existsAccount.getDevice(SAMPLE_DEVICE_ID)).thenReturn(Optional.of(sampleDevice));
when(existsAccount.getDevices()).thenReturn(List.of(sampleDevice));
when(existsAccount.getIdentityKey(IdentityType.ACI)).thenReturn(IDENTITY_KEY);
when(existsAccount.getIdentityKey(IdentityType.PNI)).thenReturn(PNI_IDENTITY_KEY);
when(existsAccount.getNumber()).thenReturn(EXISTS_NUMBER);
@@ -264,51 +240,12 @@ class KeysControllerTest {
when(KEYS.storeEcOneTimePreKeys(any(), anyByte(), any()))
.thenReturn(CompletableFutureTestUtil.almostCompletedFuture(null));
when(KEYS.storeKemOneTimePreKeys(any(), anyByte(), any()))
.thenReturn(CompletableFutureTestUtil.almostCompletedFuture(null));
when(KEYS.storePqLastResort(any(), anyByte(), any()))
.thenReturn(CompletableFutureTestUtil.almostCompletedFuture(null));
when(KEYS.getEcSignedPreKey(any(), anyByte())).thenReturn(CompletableFuture.completedFuture(Optional.empty()));
when(KEYS.storeEcSignedPreKeys(any(), anyByte(), any())).thenReturn(CompletableFutureTestUtil.almostCompletedFuture(null));
when(KEYS.getEcSignedPreKey(EXISTS_UUID, sampleDeviceId))
.thenReturn(CompletableFuture.completedFuture(Optional.of(SAMPLE_SIGNED_KEY)));
when(KEYS.getEcSignedPreKey(EXISTS_UUID, sampleDevice2Id))
.thenReturn(CompletableFuture.completedFuture(Optional.of(SAMPLE_SIGNED_KEY2)));
when(KEYS.getEcSignedPreKey(EXISTS_UUID, sampleDevice3Id))
.thenReturn(CompletableFuture.completedFuture(Optional.of(SAMPLE_SIGNED_KEY3)));
when(KEYS.getEcSignedPreKey(EXISTS_PNI, sampleDeviceId))
.thenReturn(CompletableFuture.completedFuture(Optional.of(SAMPLE_SIGNED_PNI_KEY)));
when(KEYS.getEcSignedPreKey(EXISTS_PNI, sampleDevice2Id))
.thenReturn(CompletableFuture.completedFuture(Optional.of(SAMPLE_SIGNED_PNI_KEY2)));
when(KEYS.getEcSignedPreKey(EXISTS_PNI, sampleDevice3Id))
.thenReturn(CompletableFuture.completedFuture(Optional.of(SAMPLE_SIGNED_PNI_KEY3)));
when(KEYS.takeEC(EXISTS_UUID, sampleDeviceId)).thenReturn(
CompletableFuture.completedFuture(Optional.of(SAMPLE_KEY)));
when(KEYS.takePQ(EXISTS_UUID, sampleDeviceId)).thenReturn(
CompletableFuture.completedFuture(Optional.of(SAMPLE_PQ_KEY)));
when(KEYS.takeEC(EXISTS_PNI, sampleDeviceId)).thenReturn(
CompletableFuture.completedFuture(Optional.of(SAMPLE_KEY_PNI)));
when(KEYS.takePQ(EXISTS_PNI, sampleDeviceId)).thenReturn(
CompletableFuture.completedFuture(Optional.of(SAMPLE_PQ_KEY_PNI)));
when(KEYS.getEcCount(AuthHelper.VALID_UUID, sampleDeviceId)).thenReturn(CompletableFuture.completedFuture(5));
when(KEYS.getPqCount(AuthHelper.VALID_UUID, sampleDeviceId)).thenReturn(CompletableFuture.completedFuture(5));
when(KEYS.getEcSignedPreKey(AuthHelper.VALID_UUID, AuthHelper.VALID_DEVICE.getId()))
.thenReturn(CompletableFuture.completedFuture(Optional.of(VALID_DEVICE_SIGNED_KEY)));
when(KEYS.getEcSignedPreKey(AuthHelper.VALID_PNI, AuthHelper.VALID_DEVICE.getId()))
.thenReturn(CompletableFuture.completedFuture(Optional.of(VALID_DEVICE_PNI_SIGNED_KEY)));
when(KEYS.storeEcSignedPreKeys(any(), anyByte(), any()))
.thenReturn(CompletableFutureTestUtil.almostCompletedFuture(null));
}
@AfterEach
@@ -326,6 +263,11 @@ class KeysControllerTest {
@Test
void validKeyStatusTest() {
when(KEYS.getEcCount(AuthHelper.VALID_UUID, SAMPLE_DEVICE_ID)).thenReturn(CompletableFuture.completedFuture(5));
when(KEYS.getPqCount(AuthHelper.VALID_UUID, SAMPLE_DEVICE_ID)).thenReturn(CompletableFuture.completedFuture(5));
when(KEYS.getEcSignedPreKey(AuthHelper.VALID_UUID, AuthHelper.VALID_DEVICE.getId()))
.thenReturn(CompletableFuture.completedFuture(Optional.of(KeysHelper.signedECPreKey(123, IDENTITY_KEY_PAIR))));
PreKeyCount result = resources.getJerseyTest()
.target("/v2/keys")
.request()
@@ -355,9 +297,7 @@ class KeysControllerTest {
assertThat(result.getDevice(SAMPLE_DEVICE_ID).getRegistrationId()).isEqualTo(SAMPLE_REGISTRATION_ID);
assertEquals(SAMPLE_SIGNED_KEY, result.getDevice(SAMPLE_DEVICE_ID).getSignedPreKey());
verify(KEYS).takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID);
verify(KEYS).takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID);
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, SAMPLE_DEVICE_ID);
verify(KEYS).takeDevicePreKeys(eq(SAMPLE_DEVICE_ID), eq(EXISTS_ACI), any());
verifyNoMoreInteractions(KEYS);
}
@@ -377,9 +317,7 @@ class KeysControllerTest {
assertThat(result.getDevice(SAMPLE_DEVICE_ID).getRegistrationId()).isEqualTo(SAMPLE_REGISTRATION_ID);
assertEquals(SAMPLE_SIGNED_KEY, result.getDevice(SAMPLE_DEVICE_ID).getSignedPreKey());
verify(KEYS).takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID);
verify(KEYS).takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID);
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, SAMPLE_DEVICE_ID);
verify(KEYS).takeDevicePreKeys(eq(SAMPLE_DEVICE_ID), eq(EXISTS_ACI), any());
verifyNoMoreInteractions(KEYS);
}
@@ -398,9 +336,7 @@ class KeysControllerTest {
assertThat(result.getDevice(SAMPLE_DEVICE_ID).getRegistrationId()).isEqualTo(SAMPLE_PNI_REGISTRATION_ID);
assertEquals(SAMPLE_SIGNED_PNI_KEY, result.getDevice(SAMPLE_DEVICE_ID).getSignedPreKey());
verify(KEYS).takeEC(EXISTS_PNI, SAMPLE_DEVICE_ID);
verify(KEYS).takePQ(EXISTS_PNI, SAMPLE_DEVICE_ID);
verify(KEYS).getEcSignedPreKey(EXISTS_PNI, SAMPLE_DEVICE_ID);
verify(KEYS).takeDevicePreKeys(eq(SAMPLE_DEVICE_ID), eq(EXISTS_PNI_SERVICE_ID), any());
verifyNoMoreInteractions(KEYS);
}
@@ -420,9 +356,7 @@ class KeysControllerTest {
assertThat(result.getDevice(SAMPLE_DEVICE_ID).getRegistrationId()).isEqualTo(SAMPLE_PNI_REGISTRATION_ID);
assertEquals(SAMPLE_SIGNED_PNI_KEY, result.getDevice(SAMPLE_DEVICE_ID).getSignedPreKey());
verify(KEYS).takeEC(EXISTS_PNI, SAMPLE_DEVICE_ID);
verify(KEYS).takePQ(EXISTS_PNI, SAMPLE_DEVICE_ID);
verify(KEYS).getEcSignedPreKey(EXISTS_PNI, SAMPLE_DEVICE_ID);
verify(KEYS).takeDevicePreKeys(eq(SAMPLE_DEVICE_ID), eq(EXISTS_PNI_SERVICE_ID), any());
verifyNoMoreInteractions(KEYS);
}
@@ -437,8 +371,16 @@ class KeysControllerTest {
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get();
final String expectedRatelimitKey = String.format("%s.%s__%s.%s.%s",
AuthHelper.VALID_UUID,
AuthHelper.VALID_DEVICE.getId(),
EXISTS_PNI,
"*",
"*");
assertThat(result.getStatus()).isEqualTo(429);
assertThat(result.getHeaderString("Retry-After")).isEqualTo(String.valueOf(retryAfter.toSeconds()));
verify(rateLimiter).validate(expectedRatelimitKey);
}
@Test
@@ -456,64 +398,40 @@ class KeysControllerTest {
assertEquals(SAMPLE_PQ_KEY, result.getDevice(SAMPLE_DEVICE_ID).getPqPreKey());
assertEquals(SAMPLE_SIGNED_KEY, result.getDevice(SAMPLE_DEVICE_ID).getSignedPreKey());
verify(KEYS).takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID);
verify(KEYS).takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID);
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, SAMPLE_DEVICE_ID);
verify(KEYS).takeDevicePreKeys(eq(SAMPLE_DEVICE_ID), eq(EXISTS_ACI), any());
verifyNoMoreInteractions(KEYS);
}
private enum RereadBehavior {
ACCOUNT_MISSING,
DEVICE_MISSING,
REG_ID_CHANGED,
PRESENT
}
@ParameterizedTest
@EnumSource(RereadBehavior.class)
void testGetKeysMissingLastResort(RereadBehavior rereadBehavior) {
when(KEYS.takeEC(EXISTS_PNI, SAMPLE_DEVICE_ID))
.thenReturn(CompletableFuture.completedFuture(Optional.of(SAMPLE_KEY)));
when(KEYS.takeEC(EXISTS_PNI, SAMPLE_DEVICE_ID2))
.thenReturn(CompletableFuture.completedFuture(Optional.of(SAMPLE_KEY2)));
when(KEYS.takePQ(EXISTS_PNI, SAMPLE_DEVICE_ID))
.thenReturn(CompletableFuture.completedFuture(Optional.of(SAMPLE_PQ_KEY)));
when(KEYS.takePQ(EXISTS_PNI, SAMPLE_DEVICE_ID2))
// Missing PQ key
@Test
void testNoKeysForDevice() {
final List<Device> devices = List.of(
createSampleDevice((byte) 1, 2, 3),
createSampleDevice((byte) 4, 5, 6));
// device 1 is missing required prekeys, device 4 is missing an optional EC prekey
when(KEYS.takeDevicePreKeys(eq((byte) 4), eq(EXISTS_PNI_SERVICE_ID), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.of(
new KeysManager.DevicePreKeys(SAMPLE_SIGNED_PNI_KEY, Optional.empty(), SAMPLE_PQ_KEY_PNI))));
when(KEYS.takeDevicePreKeys(eq((byte) 1), eq(EXISTS_PNI_SERVICE_ID), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.empty()));
switch (rereadBehavior) {
case ACCOUNT_MISSING -> when(accounts.getByServiceIdentifierAsync(new PniServiceIdentifier(EXISTS_PNI)))
.thenReturn(CompletableFuture.completedFuture(Optional.empty()));
case DEVICE_MISSING -> when(existsAccount.getDevice(SAMPLE_DEVICE_ID2))
.thenReturn(Optional.empty());
case REG_ID_CHANGED -> when(sampleDevice2.getRegistrationId(IdentityType.PNI))
.thenReturn(SAMPLE_PNI_REGISTRATION_ID2)
.thenReturn(SAMPLE_PNI_REGISTRATION_ID2 + 1);
case PRESENT -> {
}
}
when(existsAccount.getDevice((byte) 1)).thenReturn(Optional.of(devices.get(0)));
when(existsAccount.getDevice((byte) 4)).thenReturn(Optional.of(devices.get(1)));
when(existsAccount.getDevices()).thenReturn(devices);
when(existsAccount.getDevices()).thenReturn(List.of(sampleDevice, sampleDevice2));
Response response = resources.getJerseyTest()
PreKeyResponse results = resources.getJerseyTest()
.target(String.format("/v2/keys/PNI:%s/*", EXISTS_PNI))
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get();
if (rereadBehavior == RereadBehavior.PRESENT) {
// The device was missing a last resort prekey which should be impossible
assertThat(response.getStatus()).isEqualTo(500);
} else {
// In the other cases, the device plausibly disappeared so we can just leave that device out
final PreKeyResponse result = response.readEntity(PreKeyResponse.class);
assertThat(result.getDevicesCount()).isEqualTo(1);
assertThat(result.getIdentityKey()).isEqualTo(existsAccount.getIdentityKey(IdentityType.PNI));
assertThat(result.getDevice(SAMPLE_DEVICE_ID).getPqPreKey()).isEqualTo(SAMPLE_PQ_KEY);
}
}
.get(PreKeyResponse.class);
// Should drop device 1 and keep device 4
assertThat(results.getDevicesCount()).isEqualTo(1);
final PreKeyResponseItem result = results.getDevice((byte) 4);
assertEquals(6, result.getRegistrationId());
assertNull(result.getPreKey());
assertEquals(SAMPLE_SIGNED_PNI_KEY, result.getSignedPreKey());
assertEquals(SAMPLE_PQ_KEY_PNI, result.getPqPreKey());
}
@ParameterizedTest
@MethodSource
@@ -545,9 +463,7 @@ class KeysControllerTest {
assertEquals(SAMPLE_PQ_KEY, result.getDevice(SAMPLE_DEVICE_ID).getPqPreKey());
assertEquals(SAMPLE_SIGNED_KEY, result.getDevice(SAMPLE_DEVICE_ID).getSignedPreKey());
verify(KEYS).takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID);
verify(KEYS).takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID);
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, SAMPLE_DEVICE_ID);
verify(KEYS).takeDevicePreKeys(eq(SAMPLE_DEVICE_ID), eq(EXISTS_ACI), any());
}
verifyNoMoreInteractions(KEYS);
@@ -617,162 +533,54 @@ class KeysControllerTest {
}
@Test
void validMultiRequestTestV2() {
when(KEYS.takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID)).thenReturn(
CompletableFuture.completedFuture(Optional.of(SAMPLE_KEY)));
when(KEYS.takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID2)).thenReturn(
CompletableFuture.completedFuture(Optional.of(SAMPLE_KEY2)));
when(KEYS.takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID3)).thenReturn(
CompletableFuture.completedFuture(Optional.of(SAMPLE_KEY3)));
when(KEYS.takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID4)).thenReturn(
CompletableFuture.completedFuture(Optional.of(SAMPLE_KEY4)));
@ParameterizedTest
@EnumSource
void validMultiRequestTestV2(IdentityType identityType) {
final ServiceIdentifier serviceIdentifier = switch (identityType) {
case ACI -> new AciServiceIdentifier(EXISTS_UUID);
case PNI -> new PniServiceIdentifier(EXISTS_PNI);
};
when(KEYS.takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID)).thenReturn(
CompletableFuture.completedFuture(Optional.of(SAMPLE_PQ_KEY)));
when(KEYS.takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID2)).thenReturn(
CompletableFuture.completedFuture(Optional.of(SAMPLE_PQ_KEY2)));
when(KEYS.takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID3)).thenReturn(
CompletableFuture.completedFuture(Optional.of(SAMPLE_PQ_KEY3)));
when(KEYS.takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID4)).thenReturn(
CompletableFuture.completedFuture(Optional.of(SAMPLE_PQ_KEY4)));
final List<Device> devices = new ArrayList<>();
final List<KeysManager.DevicePreKeys> devicePreKeys = new ArrayList<>();
for (int i = 0; i < 4; i++) {
devices.add(createSampleDevice((byte) i, i + 100, i + 200));
final ECSignedPreKey signedEcPreKey = KeysHelper.signedECPreKey(i + 300, IDENTITY_KEY_PAIR);
final ECPreKey ecPreKey = KeysHelper.ecPreKey(i + 400);
final KEMSignedPreKey kemSignedPreKey = KeysHelper.signedKEMPreKey(i + 500, ECKeyPair.generate());
devicePreKeys.add(new KeysManager.DevicePreKeys(signedEcPreKey, Optional.of(ecPreKey), kemSignedPreKey));
when(existsAccount.getDevice((byte) i)).thenReturn(Optional.of(devices.getLast()));
when(KEYS.takeDevicePreKeys(eq((byte) i), eq(serviceIdentifier), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.of(devicePreKeys.getLast())));
}
when(existsAccount.getDevices()).thenReturn(devices);
PreKeyResponse results = resources.getJerseyTest()
.target(String.format("/v2/keys/%s/*", EXISTS_UUID))
.target(String.format("/v2/keys/%s/*", serviceIdentifier.toServiceIdentifierString()))
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get(PreKeyResponse.class);
assertThat(results.getDevicesCount()).isEqualTo(4);
assertThat(results.getIdentityKey()).isEqualTo(existsAccount.getIdentityKey(IdentityType.ACI));
assertThat(results.getIdentityKey()).isEqualTo(existsAccount.getIdentityKey(identityType));
ECSignedPreKey signedPreKey = results.getDevice(SAMPLE_DEVICE_ID).getSignedPreKey();
ECPreKey preKey = results.getDevice(SAMPLE_DEVICE_ID).getPreKey();
long registrationId = results.getDevice(SAMPLE_DEVICE_ID).getRegistrationId();
byte deviceId = results.getDevice(SAMPLE_DEVICE_ID).getDeviceId();
for (int i = 0; i < 4; i++) {
final PreKeyResponseItem result = results.getDevice((byte) i);
final KeysManager.DevicePreKeys expectedPreKeys = devicePreKeys.get(i);
final Device expectedDevice = devices.get(i);
assertEquals(SAMPLE_KEY, preKey);
assertThat(registrationId).isEqualTo(SAMPLE_REGISTRATION_ID);
assertEquals(SAMPLE_SIGNED_KEY, signedPreKey);
assertThat(deviceId).isEqualTo(SAMPLE_DEVICE_ID);
assertEquals(expectedDevice.getRegistrationId(identityType), result.getRegistrationId());
assertEquals(expectedPreKeys.ecPreKey().orElseThrow(), result.getPreKey());
assertEquals(expectedPreKeys.ecSignedPreKey(), result.getSignedPreKey());
assertEquals(expectedPreKeys.kemSignedPreKey(), result.getPqPreKey());
signedPreKey = results.getDevice(SAMPLE_DEVICE_ID2).getSignedPreKey();
preKey = results.getDevice(SAMPLE_DEVICE_ID2).getPreKey();
registrationId = results.getDevice(SAMPLE_DEVICE_ID2).getRegistrationId();
deviceId = results.getDevice(SAMPLE_DEVICE_ID2).getDeviceId();
assertEquals(SAMPLE_KEY2, preKey);
assertThat(registrationId).isEqualTo(SAMPLE_REGISTRATION_ID2);
assertEquals(SAMPLE_SIGNED_KEY2, signedPreKey);
assertThat(deviceId).isEqualTo(SAMPLE_DEVICE_ID2);
signedPreKey = results.getDevice(SAMPLE_DEVICE_ID4).getSignedPreKey();
preKey = results.getDevice(SAMPLE_DEVICE_ID4).getPreKey();
registrationId = results.getDevice(SAMPLE_DEVICE_ID4).getRegistrationId();
deviceId = results.getDevice(SAMPLE_DEVICE_ID4).getDeviceId();
assertEquals(SAMPLE_KEY4, preKey);
assertThat(registrationId).isEqualTo(SAMPLE_REGISTRATION_ID4);
assertThat(signedPreKey).isNull();
assertThat(deviceId).isEqualTo(SAMPLE_DEVICE_ID4);
verify(KEYS).takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID);
verify(KEYS).takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID2);
verify(KEYS).takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID3);
verify(KEYS).takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID4);
verify(KEYS).takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID);
verify(KEYS).takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID2);
verify(KEYS).takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID3);
verify(KEYS).takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID4);
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, SAMPLE_DEVICE_ID);
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, SAMPLE_DEVICE_ID2);
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, SAMPLE_DEVICE_ID3);
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, SAMPLE_DEVICE_ID4);
verify(KEYS).takeDevicePreKeys(eq((byte) i), eq(serviceIdentifier), any());
}
verifyNoMoreInteractions(KEYS);
}
@Test
void validMultiRequestPqTestV2() {
when(KEYS.takeEC(any(), anyByte())).thenReturn(CompletableFuture.completedFuture(Optional.empty()));
when(KEYS.takePQ(any(), anyByte())).thenReturn(CompletableFuture.completedFuture(Optional.empty()));
when(KEYS.takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID)).thenReturn(
CompletableFuture.completedFuture(Optional.of(SAMPLE_KEY)));
when(KEYS.takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID3)).thenReturn(
CompletableFuture.completedFuture(Optional.of(SAMPLE_KEY3)));
when(KEYS.takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID4)).thenReturn(
CompletableFuture.completedFuture(Optional.of(SAMPLE_KEY4)));
when(KEYS.takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID)).thenReturn(
CompletableFuture.completedFuture(Optional.of(SAMPLE_PQ_KEY)));
when(KEYS.takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID2)).thenReturn(
CompletableFuture.completedFuture(Optional.of(SAMPLE_PQ_KEY2)));
when(KEYS.takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID3)).thenReturn(
CompletableFuture.completedFuture(Optional.of(SAMPLE_PQ_KEY3)));
when(KEYS.takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID4)).thenReturn(
CompletableFuture.completedFuture(Optional.of(SAMPLE_PQ_KEY4)));
PreKeyResponse results = resources.getJerseyTest()
.target(String.format("/v2/keys/%s/*", EXISTS_UUID))
.queryParam("pq", "true")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get(PreKeyResponse.class);
assertThat(results.getDevicesCount()).isEqualTo(4);
assertThat(results.getIdentityKey()).isEqualTo(existsAccount.getIdentityKey(IdentityType.ACI));
ECSignedPreKey signedPreKey = results.getDevice(SAMPLE_DEVICE_ID).getSignedPreKey();
ECPreKey preKey = results.getDevice(SAMPLE_DEVICE_ID).getPreKey();
KEMSignedPreKey pqPreKey = results.getDevice(SAMPLE_DEVICE_ID).getPqPreKey();
int registrationId = results.getDevice(SAMPLE_DEVICE_ID).getRegistrationId();
byte deviceId = results.getDevice(SAMPLE_DEVICE_ID).getDeviceId();
assertEquals(SAMPLE_KEY, preKey);
assertEquals(SAMPLE_PQ_KEY, pqPreKey);
assertThat(registrationId).isEqualTo(SAMPLE_REGISTRATION_ID);
assertEquals(SAMPLE_SIGNED_KEY, signedPreKey);
assertThat(deviceId).isEqualTo(SAMPLE_DEVICE_ID);
signedPreKey = results.getDevice(SAMPLE_DEVICE_ID2).getSignedPreKey();
preKey = results.getDevice(SAMPLE_DEVICE_ID2).getPreKey();
pqPreKey = results.getDevice(SAMPLE_DEVICE_ID2).getPqPreKey();
registrationId = results.getDevice(SAMPLE_DEVICE_ID2).getRegistrationId();
deviceId = results.getDevice(SAMPLE_DEVICE_ID2).getDeviceId();
assertThat(preKey).isNull();
assertEquals(SAMPLE_PQ_KEY2, pqPreKey);
assertThat(registrationId).isEqualTo(SAMPLE_REGISTRATION_ID2);
assertEquals(SAMPLE_SIGNED_KEY2, signedPreKey);
assertThat(deviceId).isEqualTo(SAMPLE_DEVICE_ID2);
signedPreKey = results.getDevice(SAMPLE_DEVICE_ID4).getSignedPreKey();
preKey = results.getDevice(SAMPLE_DEVICE_ID4).getPreKey();
pqPreKey = results.getDevice(SAMPLE_DEVICE_ID4).getPqPreKey();
registrationId = results.getDevice(SAMPLE_DEVICE_ID4).getRegistrationId();
deviceId = results.getDevice(SAMPLE_DEVICE_ID4).getDeviceId();
assertEquals(SAMPLE_KEY4, preKey);
assertThat(pqPreKey).isEqualTo(SAMPLE_PQ_KEY4);
assertThat(registrationId).isEqualTo(SAMPLE_REGISTRATION_ID4);
assertThat(signedPreKey).isNull();
assertThat(deviceId).isEqualTo(SAMPLE_DEVICE_ID4);
verify(KEYS).takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID);
verify(KEYS).takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID);
verify(KEYS).takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID2);
verify(KEYS).takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID2);
verify(KEYS).takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID3);
verify(KEYS).takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID3);
verify(KEYS).takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID4);
verify(KEYS).takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID4);
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, SAMPLE_DEVICE_ID);
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, SAMPLE_DEVICE_ID2);
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, SAMPLE_DEVICE_ID3);
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, SAMPLE_DEVICE_ID4);
verifyNoMoreInteractions(KEYS);
}
@Test
void invalidRequestTestV2() {
Response response = resources.getJerseyTest()
@@ -786,6 +594,7 @@ class KeysControllerTest {
@Test
void anotherInvalidRequestTestV2() {
when(existsAccount.getDevice((byte) 22)).thenReturn(Optional.empty());
Response response = resources.getJerseyTest()
.target(String.format("/v2/keys/%s/22", EXISTS_UUID))
.request()
@@ -442,9 +442,7 @@ class ProfileControllerTest {
@CartesianTest
void testProfileCapabilities(
@CartesianTest.Values(booleans = {true, false}) final boolean isDeleteSyncSupported,
@CartesianTest.Values(booleans = {true, false}) final boolean isAttachmentBackfillSupported) {
when(capabilitiesAccount.hasCapability(DeviceCapability.DELETE_SYNC)).thenReturn(isDeleteSyncSupported);
when(capabilitiesAccount.hasCapability(DeviceCapability.ATTACHMENT_BACKFILL)).thenReturn(isAttachmentBackfillSupported);
final BaseProfileResponse profile = resources.getJerseyTest()
.target("/v1/profile/" + AuthHelper.VALID_UUID)
@@ -452,7 +450,6 @@ class ProfileControllerTest {
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get(BaseProfileResponse.class);
assertEquals(isDeleteSyncSupported, profile.getCapabilities().get("deleteSync"));
assertEquals(isAttachmentBackfillSupported, profile.getCapabilities().get("attachmentBackfill"));
}
@@ -1,70 +0,0 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.controllers;
import static org.assertj.core.api.Assertions.assertThat;
import static org.whispersystems.textsecuregcm.util.MockUtils.randomSecretBytes;
import io.dropwizard.auth.AuthValueFactoryProvider;
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
import io.dropwizard.testing.junit5.ResourceExtension;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
import org.whispersystems.textsecuregcm.configuration.SecureValueRecoveryConfiguration;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.util.MutableClock;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import java.time.Instant;
import java.util.HexFormat;
@ExtendWith(DropwizardExtensionsSupport.class)
public class SecureValueRecoveryBControllerTest {
private static final SecureValueRecoveryConfiguration CFG = new SecureValueRecoveryConfiguration(
"",
randomSecretBytes(32),
randomSecretBytes(32),
null,
null,
null
);
private static final MutableClock CLOCK = new MutableClock();
private static final ExternalServiceCredentialsGenerator CREDENTIAL_GENERATOR =
SecureValueRecoveryBController.credentialsGenerator(CFG, CLOCK);
private static final SecureValueRecoveryBController CONTROLLER =
new SecureValueRecoveryBController(CREDENTIAL_GENERATOR);
private static final ResourceExtension RESOURCES = ResourceExtension.builder()
.addProvider(AuthHelper.getAuthFilter())
.addProvider(new AuthValueFactoryProvider.Binder<>(AuthenticatedDevice.class))
.setMapper(SystemMapper.jsonMapper())
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
.addResource(CONTROLLER)
.build();
@Test
public void testGetCredentials() {
CLOCK.setTimeInstant(Instant.ofEpochSecond(123));
final ExternalServiceCredentials creds = RESOURCES.getJerseyTest()
.target("/v1/svrb/auth")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get(ExternalServiceCredentials.class);
assertThat(HexFormat.of().parseHex(creds.username())).hasSize(16);
System.out.println(creds.password());
final String[] split = creds.password().split(":", 2);
assertThat(Long.parseLong(split[0])).isEqualTo(123);
}
}
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.grpc;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyByte;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
@@ -100,15 +101,11 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
final ECPreKey ecPreKey = new ECPreKey(1, ECKeyPair.generate().getPublicKey());
final ECSignedPreKey ecSignedPreKey = KeysHelper.signedECPreKey(2, identityKeyPair);
final KEMSignedPreKey kemSignedPreKey = KeysHelper.signedKEMPreKey(3, identityKeyPair);
final KeysManager.DevicePreKeys devicePreKeys =
new KeysManager.DevicePreKeys(ecSignedPreKey, Optional.of(ecPreKey), kemSignedPreKey);
when(keysManager.takeEC(uuid, Device.PRIMARY_ID))
.thenReturn(CompletableFuture.completedFuture(Optional.of(ecPreKey)));
when(keysManager.takePQ(uuid, Device.PRIMARY_ID))
.thenReturn(CompletableFuture.completedFuture(Optional.of(kemSignedPreKey)));
when(keysManager.getEcSignedPreKey(uuid, Device.PRIMARY_ID))
.thenReturn(CompletableFuture.completedFuture(Optional.of(ecSignedPreKey)));
when(keysManager.takeDevicePreKeys(eq(Device.PRIMARY_ID), eq(identifier), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.of(devicePreKeys)));
final GetPreKeysResponse response = unauthenticatedServiceStub().getPreKeys(GetPreKeysAnonymousRequest.newBuilder()
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
@@ -151,15 +148,11 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
final ECPreKey ecPreKey = new ECPreKey(1, ECKeyPair.generate().getPublicKey());
final ECSignedPreKey ecSignedPreKey = KeysHelper.signedECPreKey(2, identityKeyPair);
final KEMSignedPreKey kemSignedPreKey = KeysHelper.signedKEMPreKey(3, identityKeyPair);
final KeysManager.DevicePreKeys devicePreKeys =
new KeysManager.DevicePreKeys(ecSignedPreKey, Optional.of(ecPreKey), kemSignedPreKey);
when(keysManager.takeEC(uuid, Device.PRIMARY_ID))
.thenReturn(CompletableFuture.completedFuture(Optional.of(ecPreKey)));
when(keysManager.takePQ(uuid, Device.PRIMARY_ID))
.thenReturn(CompletableFuture.completedFuture(Optional.of(kemSignedPreKey)));
when(keysManager.getEcSignedPreKey(uuid, Device.PRIMARY_ID))
.thenReturn(CompletableFuture.completedFuture(Optional.of(ecSignedPreKey)));
when(keysManager.takeDevicePreKeys(eq(Device.PRIMARY_ID), eq(identifier), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.of(devicePreKeys)));
// Expirations must be on day boundaries or libsignal will refuse to create or verify the token
final Instant expiration = Instant.now().truncatedTo(ChronoUnit.DAYS);
@@ -10,7 +10,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyByte;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
@@ -59,6 +59,7 @@ import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.Account;
@@ -464,26 +465,52 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest<KeysGrpcService, KeysGrpc.K
final UUID identifier = UUID.randomUUID();
final IdentityType identityType = IdentityTypeUtil.fromGrpcIdentityType(grpcIdentityType);
final org.whispersystems.textsecuregcm.identity.ServiceIdentifier serviceIdentifier = switch (identityType) {
case PNI -> new PniServiceIdentifier(identifier);
case ACI -> new AciServiceIdentifier(identifier);
};
when(targetAccount.getUuid()).thenReturn(UUID.randomUUID());
when(targetAccount.getIdentifier(identityType)).thenReturn(identifier);
when(targetAccount.getIdentityKey(identityType)).thenReturn(identityKey);
when(accountsManager.getByServiceIdentifierAsync(argThat(serviceIdentifier -> serviceIdentifier.uuid().equals(identifier))))
when(accountsManager.getByServiceIdentifierAsync(serviceIdentifier))
.thenReturn(CompletableFuture.completedFuture(Optional.of(targetAccount)));
final Map<Byte, ECPreKey> ecOneTimePreKeys = new HashMap<>();
final Map<Byte, KEMSignedPreKey> kemPreKeys = new HashMap<>();
final Map<Byte, ECSignedPreKey> ecSignedPreKeys = new HashMap<>();
final Map<Byte, KeysManager.DevicePreKeys> devicePreKeysMap = new HashMap<>();
final Map<Byte, Device> devices = new HashMap<>();
final Map<Byte, GetPreKeysResponse.PreKeyBundle> expectedPreKeyBundles = new HashMap<>();
final byte deviceId1 = 1;
final byte deviceId2 = 2;
for (final byte deviceId : List.of(deviceId1, deviceId2)) {
ecOneTimePreKeys.put(deviceId, new ECPreKey(1, ECKeyPair.generate().getPublicKey()));
kemPreKeys.put(deviceId, KeysHelper.signedKEMPreKey(2, identityKeyPair));
ecSignedPreKeys.put(deviceId, KeysHelper.signedECPreKey(3, identityKeyPair));
final ECSignedPreKey ecSignedPreKey = KeysHelper.signedECPreKey(3, identityKeyPair);
final Optional<ECPreKey> maybeEcPreKey = Optional
.of(new ECPreKey(1, ECKeyPair.generate().getPublicKey()))
.filter(_ -> deviceId == deviceId1);
final KEMSignedPreKey kemSignedPreKey = KeysHelper.signedKEMPreKey(2, identityKeyPair);
devicePreKeysMap.put(deviceId, new KeysManager.DevicePreKeys(ecSignedPreKey, maybeEcPreKey, kemSignedPreKey));
final GetPreKeysResponse.PreKeyBundle.Builder builder = GetPreKeysResponse.PreKeyBundle.newBuilder()
.setEcSignedPreKey(EcSignedPreKey.newBuilder()
.setKeyId(ecSignedPreKey.keyId())
.setPublicKey(ByteString.copyFrom(ecSignedPreKey.serializedPublicKey()))
.setSignature(ByteString.copyFrom(ecSignedPreKey.signature()))
.build())
.setKemOneTimePreKey(KemSignedPreKey.newBuilder()
.setKeyId(kemSignedPreKey.keyId())
.setPublicKey(ByteString.copyFrom(kemSignedPreKey.serializedPublicKey()))
.setSignature(ByteString.copyFrom(kemSignedPreKey.signature()))
.build());
maybeEcPreKey.ifPresent(ecPreKey -> builder
.setEcOneTimePreKey(EcPreKey.newBuilder()
.setKeyId(ecPreKey.keyId())
.setPublicKey(ByteString.copyFrom(ecPreKey.serializedPublicKey()))
.build()));
expectedPreKeyBundles.put(deviceId, builder.build());
final Device device = mock(Device.class);
when(device.getId()).thenReturn(deviceId);
@@ -494,14 +521,9 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest<KeysGrpcService, KeysGrpc.K
when(targetAccount.getDevices()).thenReturn(new ArrayList<>(devices.values()));
ecOneTimePreKeys.forEach((deviceId, preKey) -> when(keysManager.takeEC(identifier, deviceId))
.thenReturn(CompletableFuture.completedFuture(Optional.of(preKey))));
ecSignedPreKeys.forEach((deviceId, preKey) -> when(keysManager.getEcSignedPreKey(identifier, deviceId))
.thenReturn(CompletableFuture.completedFuture(Optional.of(preKey))));
kemPreKeys.forEach((deviceId, preKey) -> when(keysManager.takePQ(identifier, deviceId))
.thenReturn(CompletableFuture.completedFuture(Optional.of(preKey))));
devicePreKeysMap.forEach((deviceId, preKeys) -> when(keysManager.takeDevicePreKeys(eq(deviceId),
eq(serviceIdentifier), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.of(preKeys))));
{
final GetPreKeysResponse response = authenticatedServiceStub().getPreKeys(GetPreKeysRequest.newBuilder()
@@ -514,30 +536,12 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest<KeysGrpcService, KeysGrpc.K
final GetPreKeysResponse expectedResponse = GetPreKeysResponse.newBuilder()
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
.putPreKeys(1, GetPreKeysResponse.PreKeyBundle.newBuilder()
.setEcSignedPreKey(EcSignedPreKey.newBuilder()
.setKeyId(ecSignedPreKeys.get(deviceId1).keyId())
.setPublicKey(ByteString.copyFrom(ecSignedPreKeys.get(deviceId1).serializedPublicKey()))
.setSignature(ByteString.copyFrom(ecSignedPreKeys.get(deviceId1).signature()))
.build())
.setEcOneTimePreKey(EcPreKey.newBuilder()
.setKeyId(ecOneTimePreKeys.get(deviceId1).keyId())
.setPublicKey(ByteString.copyFrom(ecOneTimePreKeys.get(deviceId1).serializedPublicKey()))
.build())
.setKemOneTimePreKey(KemSignedPreKey.newBuilder()
.setKeyId(kemPreKeys.get(deviceId1).keyId())
.setPublicKey(ByteString.copyFrom(kemPreKeys.get(deviceId1).serializedPublicKey()))
.setSignature(ByteString.copyFrom(kemPreKeys.get(deviceId1).signature()))
.build())
.build())
.putPreKeys(1, expectedPreKeyBundles.get(deviceId1))
.build();
assertEquals(expectedResponse, response);
}
when(keysManager.takeEC(identifier, deviceId2)).thenReturn(CompletableFuture.completedFuture(Optional.empty()));
when(keysManager.takePQ(identifier, deviceId2)).thenReturn(CompletableFuture.completedFuture(Optional.empty()));
{
final GetPreKeysResponse response = authenticatedServiceStub().getPreKeys(GetPreKeysRequest.newBuilder()
.setTargetIdentifier(ServiceIdentifier.newBuilder()
@@ -548,29 +552,8 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest<KeysGrpcService, KeysGrpc.K
final GetPreKeysResponse expectedResponse = GetPreKeysResponse.newBuilder()
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
.putPreKeys(1, GetPreKeysResponse.PreKeyBundle.newBuilder()
.setEcSignedPreKey(EcSignedPreKey.newBuilder()
.setKeyId(ecSignedPreKeys.get(deviceId1).keyId())
.setPublicKey(ByteString.copyFrom(ecSignedPreKeys.get(deviceId1).serializedPublicKey()))
.setSignature(ByteString.copyFrom(ecSignedPreKeys.get(deviceId1).signature()))
.build())
.setEcOneTimePreKey(EcPreKey.newBuilder()
.setKeyId(ecOneTimePreKeys.get(deviceId1).keyId())
.setPublicKey(ByteString.copyFrom(ecOneTimePreKeys.get(deviceId1).serializedPublicKey()))
.build())
.setKemOneTimePreKey(KemSignedPreKey.newBuilder()
.setKeyId(kemPreKeys.get(deviceId1).keyId())
.setPublicKey(ByteString.copyFrom(kemPreKeys.get(deviceId1).serializedPublicKey()))
.setSignature(ByteString.copyFrom(kemPreKeys.get(deviceId1).signature()))
.build())
.build())
.putPreKeys(2, GetPreKeysResponse.PreKeyBundle.newBuilder()
.setEcSignedPreKey(EcSignedPreKey.newBuilder()
.setKeyId(ecSignedPreKeys.get(deviceId2).keyId())
.setPublicKey(ByteString.copyFrom(ecSignedPreKeys.get(deviceId2).serializedPublicKey()))
.setSignature(ByteString.copyFrom(ecSignedPreKeys.get(deviceId2).signature()))
.build())
.build())
.putPreKeys(1, expectedPreKeyBundles.get(deviceId1))
.putPreKeys(2, expectedPreKeyBundles.get(deviceId2))
.build();
assertEquals(expectedResponse, response);
@@ -0,0 +1,165 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.offset;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.common.net.InetAddresses;
import com.google.protobuf.ByteString;
import io.grpc.ManagedChannel;
import io.grpc.Server;
import io.grpc.StatusException;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import io.grpc.stub.BlockingClientCall;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.Timer;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.signal.chat.rpc.EchoRequest;
import org.signal.chat.rpc.EchoResponse;
import org.signal.chat.rpc.EchoServiceGrpc;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
import org.whispersystems.textsecuregcm.util.ua.UserAgent;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
public class MetricServerInterceptorTest {
private static String USER_AGENT = "Signal-Android/4.53.7 (Android 8.1; libsignal)";
private Server server;
private ManagedChannel channel;
private SimpleMeterRegistry simpleMeterRegistry;
private ClientReleaseManager clientReleaseManager;
@BeforeEach
void setUp() throws Exception {
simpleMeterRegistry = new SimpleMeterRegistry();
clientReleaseManager = mock(ClientReleaseManager.class);
final MockRequestAttributesInterceptor mockRequestAttributesInterceptor = new MockRequestAttributesInterceptor();
mockRequestAttributesInterceptor.setRequestAttributes(
new RequestAttributes(InetAddresses.forString("127.0.0.1"), USER_AGENT, null));
server = InProcessServerBuilder.forName("MetricServerInterceptorTest")
.directExecutor()
.addService(new EchoServiceImpl())
.intercept(new MetricServerInterceptor(simpleMeterRegistry, clientReleaseManager))
.intercept(mockRequestAttributesInterceptor)
.intercept(mockRequestAttributesInterceptor)
.build()
.start();
channel = InProcessChannelBuilder.forName("MetricServerInterceptorTest")
.directExecutor()
.build();
}
@AfterEach
void tearDown() throws Exception {
server.shutdownNow();
channel.shutdownNow();
server.awaitTermination(1, TimeUnit.SECONDS);
channel.awaitTermination(1, TimeUnit.SECONDS);
}
@Test
void unary() {
final EchoServiceGrpc.EchoServiceBlockingStub client = EchoServiceGrpc.newBlockingStub(channel);
client.echo(EchoRequest.newBuilder().setPayload(ByteString.copyFromUtf8("hello")).build());
final Tags commonTags = Tags.of(
"platform", "android",
"libsignal", "true",
"grpcService", "org.signal.chat.rpc.EchoService",
"method", "echo");
final Counter requestCount = find(Counter.class, MetricServerInterceptor.REQUEST_MESSAGE_COUNTER_NAME);
assertThat(requestCount.count()).isCloseTo(1.0, offset(0.01));
final Counter responseCount = find(Counter.class, MetricServerInterceptor.RESPONSE_COUNTER_NAME);
assertThat(responseCount.count()).isCloseTo(1.0, offset(0.01));
final Counter rpcCount = find(Counter.class, MetricServerInterceptor.RPC_COUNTER_NAME);
assertThat(rpcCount.count()).isCloseTo(1.0, offset(0.01));
final Timer timer = find(Timer.class, MetricServerInterceptor.DURATION_TIMER_NAME);
assertThat(timer.count()).isEqualTo(1);
for (final Meter meter : List.of(requestCount, responseCount, rpcCount, timer)) {
for (final Tag tag : commonTags) {
assertThat(meter.getId().getTag(tag.getKey())).isEqualTo(tag.getValue());
}
}
assertThat(rpcCount.getId().getTag("statusCode")).isEqualTo("OK");
}
@Test
void streaming() throws StatusException, InterruptedException, TimeoutException {
final EchoServiceGrpc.EchoServiceBlockingV2Stub client = EchoServiceGrpc.newBlockingV2Stub(channel);
final BlockingClientCall<EchoRequest, EchoResponse> echoStream = client.echoStream();
echoStream.write(EchoRequest.newBuilder().setPayload(ByteString.copyFromUtf8("1")).build());
echoStream.write(EchoRequest.newBuilder().setPayload(ByteString.copyFromUtf8("2")).build());
echoStream.read();
echoStream.read();
echoStream.halfClose();
// Make sure we don't check metrics before our close is processed
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
final Counter requestCount = find(Counter.class, MetricServerInterceptor.REQUEST_MESSAGE_COUNTER_NAME);
assertThat(requestCount.count()).isCloseTo(2.0, offset(0.01));
final Counter responseCount = find(Counter.class, MetricServerInterceptor.RESPONSE_COUNTER_NAME);
assertThat(responseCount.count()).isCloseTo(2.0, offset(0.01));
final Counter rpcCount = find(Counter.class, MetricServerInterceptor.RPC_COUNTER_NAME);
assertThat(rpcCount.count()).isCloseTo(1.0, offset(0.01));
final Timer timer = find(Timer.class, MetricServerInterceptor.DURATION_TIMER_NAME);
assertThat(timer.count()).isEqualTo(1);
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void clientRelease(boolean enabled) throws UnrecognizedUserAgentException {
final UserAgent ua = UserAgentUtil.parseUserAgentString(USER_AGENT);
when(clientReleaseManager.isVersionActive(ua.platform(), ua.version())).thenReturn(enabled);
final EchoServiceGrpc.EchoServiceBlockingV2Stub client = EchoServiceGrpc.newBlockingV2Stub(channel);
client.echo(EchoRequest.newBuilder().setPayload(ByteString.copyFromUtf8("hello")).build());
final String actualClientVersion = find(Meter.class, MetricServerInterceptor.REQUEST_MESSAGE_COUNTER_NAME)
.getId()
.getTag("clientVersion");
final String expectedClientVersion = enabled ? ua.version().toString() : null;
assertThat(expectedClientVersion).isEqualTo(actualClientVersion);
}
private <T extends Meter> T find(Class<T> cls, final String name) {
final Meter meter = simpleMeterRegistry.getMeters().stream()
.filter(m -> m.getId().getName().equals(name))
.findFirst()
.orElseThrow();
if (cls.isInstance(meter)) {
return cls.cast(meter);
}
throw new IllegalArgumentException("Meter " + name + " should be an instance of " + cls);
}
}
@@ -100,7 +100,6 @@ import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountBadge;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
@@ -451,7 +450,6 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(account.getBadges()).thenReturn(Collections.emptyList());
when(account.hasCapability(any())).thenReturn(false);
when(account.hasCapability(DeviceCapability.DELETE_SYNC)).thenReturn(true);
when(profileBadgeConverter.convert(any(), any(), anyBoolean())).thenReturn(badges);
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
@@ -462,7 +460,6 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
.setUnidentifiedAccess(ByteString.copyFrom(unidentifiedAccessChecksum))
.setUnrestrictedUnidentifiedAccess(true)
.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_DELETE_SYNC)
.addAllBadges(ProfileGrpcHelper.buildBadges(badges))
.build();
@@ -46,6 +46,7 @@ import java.util.function.Supplier;
import javax.net.ssl.SSLException;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
import org.whispersystems.textsecuregcm.grpc.net.FramingType;
import org.whispersystems.textsecuregcm.grpc.net.NoiseTunnelProtos;
import org.whispersystems.textsecuregcm.grpc.net.noisedirect.NoiseDirectFrame;
import org.whispersystems.textsecuregcm.grpc.net.noisedirect.NoiseDirectFrameCodec;
@@ -64,11 +65,6 @@ public class NoiseTunnelClient implements AutoCloseable {
public static final URI AUTHENTICATED_WEBSOCKET_URI = URI.create("wss://localhost/authenticated");
public static final URI ANONYMOUS_WEBSOCKET_URI = URI.create("wss://localhost/anonymous");
public enum FramingType {
WEBSOCKET,
NOISE_DIRECT
}
public static class Builder {
final SocketAddress remoteServerAddress;
@@ -4,6 +4,7 @@ import io.netty.channel.local.LocalAddress;
import io.netty.channel.nio.NioEventLoopGroup;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
import org.whispersystems.textsecuregcm.grpc.net.FramingType;
import org.whispersystems.textsecuregcm.grpc.net.GrpcClientConnectionManager;
import org.whispersystems.textsecuregcm.grpc.net.client.NoiseTunnelClient;
import org.whispersystems.textsecuregcm.grpc.net.AbstractNoiseTunnelServerIntegrationTest;
@@ -44,6 +45,6 @@ class DirectNoiseTunnelServerIntegrationTest extends AbstractNoiseTunnelServerIn
protected NoiseTunnelClient.Builder clientBuilder(final NioEventLoopGroup eventLoopGroup, final ECPublicKey serverPublicKey) {
return new NoiseTunnelClient
.Builder(noiseDirectTunnelServer.getLocalAddress(), eventLoopGroup, serverPublicKey)
.setFramingType(NoiseTunnelClient.FramingType.NOISE_DIRECT);
.setFramingType(FramingType.NOISE_DIRECT);
}
}
@@ -11,7 +11,6 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import io.lettuce.core.cluster.SlotHash;
@@ -20,9 +19,7 @@ import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
import io.lettuce.core.cluster.pubsub.api.async.RedisClusterPubSubAsyncCommands;
import io.lettuce.core.cluster.pubsub.api.sync.RedisClusterPubSubCommands;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -38,17 +35,15 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.tests.util.MockRedisFuture;
import org.whispersystems.textsecuregcm.tests.util.RedisClusterHelper;
@Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
class WebSocketConnectionEventManagerTest {
class RedisMessageAvailabilityManagerTest {
private WebSocketConnectionEventManager localEventManager;
private WebSocketConnectionEventManager remoteEventManager;
private RedisMessageAvailabilityManager localEventManager;
private RedisMessageAvailabilityManager remoteEventManager;
private static ExecutorService webSocketConnectionEventExecutor;
private static ExecutorService asyncOperationQueueingExecutor;
@@ -56,7 +51,7 @@ class WebSocketConnectionEventManagerTest {
@RegisterExtension
static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
private static class WebSocketConnectionEventAdapter implements WebSocketConnectionEventListener {
private static class MessageAvailabilityAdapter implements MessageAvailabilityListener {
@Override
public void handleNewMessageAvailable() {
@@ -67,7 +62,7 @@ class WebSocketConnectionEventManagerTest {
}
@Override
public void handleConnectionDisplaced(final boolean connectedElsewhere) {
public void handleConflictingMessageConsumer() {
}
}
@@ -79,15 +74,11 @@ class WebSocketConnectionEventManagerTest {
@BeforeEach
void setUp() {
localEventManager = new WebSocketConnectionEventManager(mock(AccountsManager.class),
mock(PushNotificationManager.class),
REDIS_CLUSTER_EXTENSION.getRedisCluster(),
localEventManager = new RedisMessageAvailabilityManager(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
webSocketConnectionEventExecutor,
asyncOperationQueueingExecutor);
remoteEventManager = new WebSocketConnectionEventManager(mock(AccountsManager.class),
mock(PushNotificationManager.class),
REDIS_CLUSTER_EXTENSION.getRedisCluster(),
remoteEventManager = new RedisMessageAvailabilityManager(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
webSocketConnectionEventExecutor,
asyncOperationQueueingExecutor);
@@ -116,15 +107,12 @@ class WebSocketConnectionEventManagerTest {
final AtomicBoolean firstListenerDisplaced = new AtomicBoolean(false);
final AtomicBoolean secondListenerDisplaced = new AtomicBoolean(false);
final AtomicBoolean firstListenerConnectedElsewhere = new AtomicBoolean(false);
localEventManager.handleClientConnected(accountIdentifier, deviceId, new WebSocketConnectionEventAdapter() {
localEventManager.handleClientConnected(accountIdentifier, deviceId, new MessageAvailabilityAdapter() {
@Override
public void handleConnectionDisplaced(final boolean connectedElsewhere) {
public void handleConflictingMessageConsumer() {
synchronized (firstListenerDisplaced) {
firstListenerDisplaced.set(true);
firstListenerConnectedElsewhere.set(connectedElsewhere);
firstListenerDisplaced.notifyAll();
}
}
@@ -133,12 +121,12 @@ class WebSocketConnectionEventManagerTest {
assertFalse(firstListenerDisplaced.get());
assertFalse(secondListenerDisplaced.get());
final WebSocketConnectionEventManager displacingManager =
final RedisMessageAvailabilityManager displacingManager =
displaceRemotely ? remoteEventManager : localEventManager;
displacingManager.handleClientConnected(accountIdentifier, deviceId, new WebSocketConnectionEventAdapter() {
displacingManager.handleClientConnected(accountIdentifier, deviceId, new MessageAvailabilityAdapter() {
@Override
public void handleConnectionDisplaced(final boolean connectedElsewhere) {
public void handleConflictingMessageConsumer() {
secondListenerDisplaced.set(true);
}
}).toCompletableFuture().join();
@@ -151,8 +139,6 @@ class WebSocketConnectionEventManagerTest {
assertTrue(firstListenerDisplaced.get());
assertFalse(secondListenerDisplaced.get());
assertTrue(firstListenerConnectedElsewhere.get());
}
@Test
@@ -163,7 +149,7 @@ class WebSocketConnectionEventManagerTest {
assertFalse(localEventManager.isLocallyPresent(accountIdentifier, deviceId));
assertFalse(remoteEventManager.isLocallyPresent(accountIdentifier, deviceId));
localEventManager.handleClientConnected(accountIdentifier, deviceId, new WebSocketConnectionEventAdapter())
localEventManager.handleClientConnected(accountIdentifier, deviceId, new MessageAvailabilityAdapter())
.toCompletableFuture()
.join();
@@ -178,56 +164,6 @@ class WebSocketConnectionEventManagerTest {
assertFalse(remoteEventManager.isLocallyPresent(accountIdentifier, deviceId));
}
@Test
void handleDisconnectionRequest() throws InterruptedException {
final UUID accountIdentifier = UUID.randomUUID();
final byte firstDeviceId = Device.PRIMARY_ID;
final byte secondDeviceId = firstDeviceId + 1;
final AtomicBoolean firstListenerDisplaced = new AtomicBoolean(false);
final AtomicBoolean secondListenerDisplaced = new AtomicBoolean(false);
final AtomicBoolean firstListenerConnectedElsewhere = new AtomicBoolean(false);
localEventManager.handleClientConnected(accountIdentifier, firstDeviceId, new WebSocketConnectionEventAdapter() {
@Override
public void handleConnectionDisplaced(final boolean connectedElsewhere) {
synchronized (firstListenerDisplaced) {
firstListenerDisplaced.set(true);
firstListenerConnectedElsewhere.set(connectedElsewhere);
firstListenerDisplaced.notifyAll();
}
}
}).toCompletableFuture().join();
localEventManager.handleClientConnected(accountIdentifier, secondDeviceId, new WebSocketConnectionEventAdapter() {
@Override
public void handleConnectionDisplaced(final boolean connectedElsewhere) {
synchronized (secondListenerDisplaced) {
secondListenerDisplaced.set(true);
secondListenerDisplaced.notifyAll();
}
}
}).toCompletableFuture().join();
assertFalse(firstListenerDisplaced.get());
assertFalse(secondListenerDisplaced.get());
localEventManager.handleDisconnectionRequest(accountIdentifier, List.of(firstDeviceId));
synchronized (firstListenerDisplaced) {
while (!firstListenerDisplaced.get()) {
firstListenerDisplaced.wait();
}
}
assertTrue(firstListenerDisplaced.get());
assertFalse(secondListenerDisplaced.get());
assertFalse(firstListenerConnectedElsewhere.get());
}
@Test
void resubscribe() {
@SuppressWarnings("unchecked") final RedisClusterPubSubCommands<byte[], byte[]> pubSubCommands =
@@ -243,9 +179,7 @@ class WebSocketConnectionEventManagerTest {
.binaryPubSubAsyncCommands(pubSubAsyncCommands)
.build();
final WebSocketConnectionEventManager eventManager = new WebSocketConnectionEventManager(
mock(AccountsManager.class),
mock(PushNotificationManager.class),
final RedisMessageAvailabilityManager eventManager = new RedisMessageAvailabilityManager(
clusterClient,
Runnable::run,
Runnable::run);
@@ -254,7 +188,7 @@ class WebSocketConnectionEventManagerTest {
final UUID firstAccountIdentifier = UUID.randomUUID();
final byte firstDeviceId = Device.PRIMARY_ID;
final int firstSlot = SlotHash.getSlot(WebSocketConnectionEventManager.getClientEventChannel(firstAccountIdentifier, firstDeviceId));
final int firstSlot = SlotHash.getSlot(RedisMessageAvailabilityManager.getClientEventChannel(firstAccountIdentifier, firstDeviceId));
final UUID secondAccountIdentifier;
final byte secondDeviceId = firstDeviceId + 1;
@@ -265,15 +199,15 @@ class WebSocketConnectionEventManagerTest {
do {
candidateIdentifier = UUID.randomUUID();
} while (SlotHash.getSlot(WebSocketConnectionEventManager.getClientEventChannel(candidateIdentifier, secondDeviceId)) == firstSlot);
} while (SlotHash.getSlot(RedisMessageAvailabilityManager.getClientEventChannel(candidateIdentifier, secondDeviceId)) == firstSlot);
secondAccountIdentifier = candidateIdentifier;
}
eventManager.handleClientConnected(firstAccountIdentifier, firstDeviceId, new WebSocketConnectionEventAdapter()).toCompletableFuture().join();
eventManager.handleClientConnected(secondAccountIdentifier, secondDeviceId, new WebSocketConnectionEventAdapter()).toCompletableFuture().join();
eventManager.handleClientConnected(firstAccountIdentifier, firstDeviceId, new MessageAvailabilityAdapter()).toCompletableFuture().join();
eventManager.handleClientConnected(secondAccountIdentifier, secondDeviceId, new MessageAvailabilityAdapter()).toCompletableFuture().join();
final int secondSlot = SlotHash.getSlot(WebSocketConnectionEventManager.getClientEventChannel(secondAccountIdentifier, secondDeviceId));
final int secondSlot = SlotHash.getSlot(RedisMessageAvailabilityManager.getClientEventChannel(secondAccountIdentifier, secondDeviceId));
final String firstNodeId = UUID.randomUUID().toString();
@@ -296,8 +230,8 @@ class WebSocketConnectionEventManagerTest {
List.of(firstBeforeNode),
List.of(firstAfterNode, secondAfterNode)));
verify(pubSubCommands).ssubscribe(WebSocketConnectionEventManager.getClientEventChannel(secondAccountIdentifier, secondDeviceId));
verify(pubSubCommands, never()).ssubscribe(WebSocketConnectionEventManager.getClientEventChannel(firstAccountIdentifier, firstDeviceId));
verify(pubSubCommands).ssubscribe(RedisMessageAvailabilityManager.getClientEventChannel(secondAccountIdentifier, secondDeviceId));
verify(pubSubCommands, never()).ssubscribe(RedisMessageAvailabilityManager.getClientEventChannel(firstAccountIdentifier, firstDeviceId));
}
@Test
@@ -311,9 +245,7 @@ class WebSocketConnectionEventManagerTest {
.binaryPubSubAsyncCommands(pubSubAsyncCommands)
.build();
final WebSocketConnectionEventManager eventManager = new WebSocketConnectionEventManager(
mock(AccountsManager.class),
mock(PushNotificationManager.class),
final RedisMessageAvailabilityManager eventManager = new RedisMessageAvailabilityManager(
clusterClient,
Runnable::run,
Runnable::run);
@@ -326,76 +258,20 @@ class WebSocketConnectionEventManagerTest {
final UUID noListenerAccountIdentifier = UUID.randomUUID();
final byte noListenerDeviceId = listenerDeviceId + 1;
eventManager.handleClientConnected(listenerAccountIdentifier, listenerDeviceId, new WebSocketConnectionEventAdapter())
eventManager.handleClientConnected(listenerAccountIdentifier, listenerDeviceId, new MessageAvailabilityAdapter())
.toCompletableFuture()
.join();
eventManager.unsubscribeIfMissingListener(
new WebSocketConnectionEventManager.AccountAndDeviceIdentifier(listenerAccountIdentifier, listenerDeviceId));
new RedisMessageAvailabilityManager.AccountAndDeviceIdentifier(listenerAccountIdentifier, listenerDeviceId));
eventManager.unsubscribeIfMissingListener(
new WebSocketConnectionEventManager.AccountAndDeviceIdentifier(noListenerAccountIdentifier, noListenerDeviceId));
new RedisMessageAvailabilityManager.AccountAndDeviceIdentifier(noListenerAccountIdentifier, noListenerDeviceId));
verify(pubSubAsyncCommands, never())
.sunsubscribe(WebSocketConnectionEventManager.getClientEventChannel(listenerAccountIdentifier, listenerDeviceId));
.sunsubscribe(RedisMessageAvailabilityManager.getClientEventChannel(listenerAccountIdentifier, listenerDeviceId));
verify(pubSubAsyncCommands)
.sunsubscribe(WebSocketConnectionEventManager.getClientEventChannel(noListenerAccountIdentifier, noListenerDeviceId));
}
@Test
void newMessageNotificationWithoutListener() throws NotPushRegisteredException {
final UUID listenerAccountIdentifier = UUID.randomUUID();
final byte listenerDeviceId = Device.PRIMARY_ID;
final UUID noListenerAccountIdentifier = UUID.randomUUID();
final byte noListenerDeviceId = listenerDeviceId + 1;
final Account noListenerAccount = mock(Account.class);
final AccountsManager accountsManager = mock(AccountsManager.class);
when(accountsManager.getByAccountIdentifierAsync(noListenerAccountIdentifier))
.thenReturn(CompletableFuture.completedFuture(Optional.of(noListenerAccount)));
final PushNotificationManager pushNotificationManager = mock(PushNotificationManager.class);
@SuppressWarnings("unchecked") final RedisClusterPubSubAsyncCommands<byte[], byte[]> pubSubAsyncCommands =
mock(RedisClusterPubSubAsyncCommands.class);
when(pubSubAsyncCommands.ssubscribe(any())).thenReturn(MockRedisFuture.completedFuture(null));
final FaultTolerantRedisClusterClient clusterClient = RedisClusterHelper.builder()
.binaryPubSubAsyncCommands(pubSubAsyncCommands)
.build();
final WebSocketConnectionEventManager eventManager = new WebSocketConnectionEventManager(
accountsManager,
pushNotificationManager,
clusterClient,
Runnable::run,
Runnable::run);
eventManager.start();
eventManager.handleClientConnected(listenerAccountIdentifier, listenerDeviceId, new WebSocketConnectionEventAdapter())
.toCompletableFuture()
.join();
final byte[] newMessagePayload = ClientEvent.newBuilder()
.setNewMessageAvailable(NewMessageAvailableEvent.getDefaultInstance())
.build()
.toByteArray();
eventManager.smessage(mock(RedisClusterNode.class),
WebSocketConnectionEventManager.getClientEventChannel(listenerAccountIdentifier, listenerDeviceId),
newMessagePayload);
eventManager.smessage(mock(RedisClusterNode.class),
WebSocketConnectionEventManager.getClientEventChannel(noListenerAccountIdentifier, noListenerDeviceId),
newMessagePayload);
verify(pushNotificationManager).sendNewMessageNotification(noListenerAccount, noListenerDeviceId, true);
verifyNoMoreInteractions(pushNotificationManager);
.sunsubscribe(RedisMessageAvailabilityManager.getClientEventChannel(noListenerAccountIdentifier, noListenerDeviceId));
}
}
@@ -70,7 +70,7 @@ import org.whispersystems.textsecuregcm.util.RedisClusterUtil;
@Timeout(value = 5, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
class FaultTolerantRedisClusterClientTest {
private static final Duration TIMEOUT = Duration.ofMillis(50);
private static final Duration TIMEOUT = Duration.ofMillis(200);
private static final RetryConfiguration RETRY_CONFIGURATION = new RetryConfiguration();
@@ -4,7 +4,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.i18n.phonenumbers.PhoneNumberToTimeZonesMapper;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import java.time.Clock;
import java.time.Instant;
@@ -13,13 +12,9 @@ import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import com.google.i18n.phonenumbers.Phonenumber;
import org.junit.jupiter.api.Test;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.util.TestClock;
class SchedulingUtilTest {
@@ -51,26 +46,23 @@ class SchedulingUtilTest {
{
final Account account = mock(Account.class);
final Device primaryDevice = mock(Device.class);
// The account does not have a phone number that can be connected to a region/time zone
when(account.getNumber()).thenReturn("Not a parseable number");
when(account.getPrimaryDevice()).thenReturn(primaryDevice);
when(primaryDevice.getCreated())
.thenReturn(ZonedDateTime.of(2024, 7, 10, 9, 53, 12, 0, ZoneId.systemDefault()).toInstant().toEpochMilli());
final ZonedDateTime beforeNotificationTime = ZonedDateTime.now(ZoneId.systemDefault()).with(LocalTime.of(9, 0));
final ZonedDateTime beforeNotificationTime = ZonedDateTime.now(ZoneId.systemDefault()).with(LocalTime.of(13, 59));
final LocalTime preferredNotificationTime = LocalTime.of(14, 0);
assertEquals(
beforeNotificationTime.with(LocalTime.of(9, 53, 12)).toInstant(),
SchedulingUtil.getNextRecommendedNotificationTime(account, LocalTime.of(14, 0),
beforeNotificationTime.with(preferredNotificationTime).toInstant(),
SchedulingUtil.getNextRecommendedNotificationTime(account, preferredNotificationTime,
Clock.fixed(beforeNotificationTime.toInstant(), ZoneId.systemDefault())));
final ZonedDateTime afterNotificationTime = ZonedDateTime.now(ZoneId.systemDefault()).with(LocalTime.of(10, 0));
final ZonedDateTime afterNotificationTime = ZonedDateTime.now(ZoneId.systemDefault()).with(LocalTime.of(14, 1));
assertEquals(
afterNotificationTime.with(LocalTime.of(9, 53, 12)).plusDays(1).toInstant(),
SchedulingUtil.getNextRecommendedNotificationTime(account, LocalTime.of(14, 0),
afterNotificationTime.with(preferredNotificationTime).plusDays(1).toInstant(),
SchedulingUtil.getNextRecommendedNotificationTime(account, preferredNotificationTime,
Clock.fixed(afterNotificationTime.toInstant(), ZoneId.systemDefault())));
}
}
Loaded 100 of 129 files, more files were not shown because too many files have changed in this diff. Show more