mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 00:36:47 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f5726f63bd | ||
|
|
391b070cff | ||
|
|
781cd0ca3f | ||
|
|
84355963f9 | ||
|
|
3ccfeb490b | ||
|
|
0cc84131de | ||
|
|
4fa08fb189 | ||
|
|
2a551d1d41 | ||
|
|
391aa9c518 | ||
|
|
39d9fd0317 | ||
|
|
18b1fcd724 | ||
|
|
f5c62a3d85 | ||
|
|
6075d5137b | ||
|
|
890293e429 | ||
|
|
05b43a878b | ||
|
|
fe9c3982a1 | ||
|
|
82baa892f7 | ||
|
|
ee53260d72 | ||
|
|
a8eb27940d | ||
|
|
fd8918eaff | ||
|
|
a3a7d7108b | ||
|
|
cd27fe0409 | ||
|
|
35606a9afd | ||
|
|
2052e62c01 | ||
|
|
8ccab5c1e0 | ||
|
|
292f69256e | ||
|
|
fbdcb942e8 | ||
|
|
c14ef7e6cf | ||
|
|
a04fe133b6 | ||
|
|
483e444174 | ||
|
|
ebf8aa7b15 | ||
|
|
7c52be2ac1 | ||
|
|
203a49975c | ||
|
|
7d45838a1e | ||
|
|
2683f1c6e7 | ||
|
|
d13413aff2 | ||
|
|
4c85e7ba66 | ||
|
|
46fef4082c | ||
|
|
c06313dd2e | ||
|
|
59bc2c5535 |
No files matched your search
@@ -14,14 +14,6 @@
|
||||
<enabled>false</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>dynamodb-local-oregon</id>
|
||||
<name>DynamoDB Local Release Repository</name>
|
||||
<url>https://s3-us-west-2.amazonaws.com/dynamodb-local/release</url>
|
||||
<snapshots>
|
||||
<enabled>false</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<pluginRepositories>
|
||||
@@ -64,6 +56,7 @@
|
||||
<lettuce.version>6.2.1.RELEASE</lettuce.version>
|
||||
<libphonenumber.version>8.12.54</libphonenumber.version>
|
||||
<logstash.logback.version>7.2</logstash.logback.version>
|
||||
<luajava.version>3.4.0</luajava.version>
|
||||
<micrometer.version>1.10.3</micrometer.version>
|
||||
<mockito.version>4.11.0</mockito.version>
|
||||
<netty.version>4.1.82.Final</netty.version>
|
||||
|
||||
@@ -146,8 +146,34 @@ directoryV2:
|
||||
userIdTokenSharedSecret: bbcdefghijklmnopqrstuvwxyz0123456789ABCDEFG= # base64-encoded secret shared with CDS to generate auth identity tokens for Signal users
|
||||
|
||||
svr2:
|
||||
enabled: false
|
||||
uri: svr2.example.com
|
||||
userAuthenticationTokenSharedSecret: abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG= # base64-encoded secret shared with SVR2 to generate auth tokens for Signal users
|
||||
userIdTokenSharedSecret: bbcdefghijklmnopqrstuvwxyz0123456789ABCDEFG= # base64-encoded secret shared with SVR2 to generate auth identity tokens for Signal users
|
||||
svrCaCertificates:
|
||||
- |
|
||||
-----BEGIN CERTIFICATE-----
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
AAAAAAAAAAAAAAAAAAAA
|
||||
-----END CERTIFICATE-----
|
||||
|
||||
|
||||
messageCache: # Redis server configuration for message store cache
|
||||
persistDelayMinutes: 1
|
||||
|
||||
+21
-1
@@ -172,6 +172,26 @@
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>party.iroiro.luajava</groupId>
|
||||
<artifactId>luajava</artifactId>
|
||||
<version>${luajava.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>party.iroiro.luajava</groupId>
|
||||
<artifactId>lua51</artifactId>
|
||||
<version>${luajava.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>party.iroiro.luajava</groupId>
|
||||
<artifactId>lua51-platform</artifactId>
|
||||
<version>${luajava.version}</version>
|
||||
<classifier>natives-desktop</classifier>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.eclipse.jetty.websocket</groupId>
|
||||
<artifactId>websocket-api</artifactId>
|
||||
@@ -429,7 +449,7 @@
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>DynamoDBLocal</artifactId>
|
||||
<version>1.21.0</version>
|
||||
<version>1.21.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
|
||||
+1
-1
@@ -33,7 +33,6 @@ import org.whispersystems.textsecuregcm.configuration.MaxDeviceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.MessageCacheConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.PaymentsServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiterConfig;
|
||||
import org.whispersystems.textsecuregcm.configuration.RecaptchaConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.RedisClusterConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.RedisConfiguration;
|
||||
@@ -49,6 +48,7 @@ import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.TestDeviceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.UnidentifiedDeliveryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.ZkConfig;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiterConfig;
|
||||
import org.whispersystems.websocket.configuration.WebSocketConfiguration;
|
||||
|
||||
/** @noinspection MismatchedQueryAndUpdateOfCollection, WeakerAccess */
|
||||
|
||||
@@ -28,6 +28,7 @@ import io.lettuce.core.resource.ClientResources;
|
||||
import io.micrometer.core.instrument.Meter.Id;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.binder.jvm.ExecutorServiceMetrics;
|
||||
import io.micrometer.core.instrument.config.MeterFilter;
|
||||
import io.micrometer.core.instrument.distribution.DistributionStatisticConfig;
|
||||
import io.micrometer.datadog.DatadogMeterRegistry;
|
||||
@@ -137,6 +138,7 @@ import org.whispersystems.textsecuregcm.metrics.GarbageCollectionGauges;
|
||||
import org.whispersystems.textsecuregcm.metrics.MaxFileDescriptorGauge;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsApplicationEventListener;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsRequestEventListener;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.MicrometerRegistryManager;
|
||||
import org.whispersystems.textsecuregcm.metrics.NetworkReceivedGauge;
|
||||
import org.whispersystems.textsecuregcm.metrics.NetworkSentGauge;
|
||||
@@ -163,9 +165,11 @@ import org.whispersystems.textsecuregcm.s3.PolicySigner;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.securebackup.SecureBackupClient;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
|
||||
import org.whispersystems.textsecuregcm.spam.FilterSpam;
|
||||
import org.whispersystems.textsecuregcm.spam.RateLimitChallengeListener;
|
||||
import org.whispersystems.textsecuregcm.spam.ReportSpamTokenProvider;
|
||||
import org.whispersystems.textsecuregcm.spam.ScoreThresholdProvider;
|
||||
import org.whispersystems.textsecuregcm.spam.SpamFilter;
|
||||
import org.whispersystems.textsecuregcm.sqs.DirectoryQueue;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountCleaner;
|
||||
@@ -229,9 +233,12 @@ import org.whispersystems.textsecuregcm.workers.ServerVersionCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.SetCrawlerAccelerationTask;
|
||||
import org.whispersystems.textsecuregcm.workers.SetRequestLoggingEnabledTask;
|
||||
import org.whispersystems.textsecuregcm.workers.SetUserDiscoverabilityCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.UnlinkDeviceCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ZkParamsCommand;
|
||||
import org.whispersystems.websocket.WebSocketResourceProviderFactory;
|
||||
import org.whispersystems.websocket.setup.WebSocketEnvironment;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
@@ -253,6 +260,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
bootstrap.addCommand(new SetUserDiscoverabilityCommand());
|
||||
bootstrap.addCommand(new ReserveUsernameCommand());
|
||||
bootstrap.addCommand(new AssignUsernameCommand());
|
||||
bootstrap.addCommand(new UnlinkDeviceCommand());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -396,23 +404,39 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
FaultTolerantRedisCluster rateLimitersCluster = new FaultTolerantRedisCluster("rate_limiters", config.getRateLimitersCluster(), redisClientResources);
|
||||
|
||||
final BlockingQueue<Runnable> keyspaceNotificationDispatchQueue = new ArrayBlockingQueue<>(100_000);
|
||||
Metrics.gaugeCollectionSize(name(getClass(), "keyspaceNotificationDispatchQueueSize"), Collections.emptyList(), keyspaceNotificationDispatchQueue);
|
||||
Metrics.gaugeCollectionSize(name(getClass(), "keyspaceNotificationDispatchQueueSize"), Collections.emptyList(),
|
||||
keyspaceNotificationDispatchQueue);
|
||||
final BlockingQueue<Runnable> receiptSenderQueue = new LinkedBlockingQueue<>();
|
||||
Metrics.gaugeCollectionSize(name(getClass(), "receiptSenderQueue"), Collections.emptyList(), receiptSenderQueue);
|
||||
|
||||
final BlockingQueue<Runnable> fcmSenderQueue = new LinkedBlockingQueue<>();
|
||||
Metrics.gaugeCollectionSize(name(getClass(), "fcmSenderQueue"), Collections.emptyList(), fcmSenderQueue);
|
||||
final BlockingQueue<Runnable> messageDeliveryQueue = new LinkedBlockingQueue<>();
|
||||
Metrics.gaugeCollectionSize(MetricsUtil.name(getClass(), "messageDeliveryQueue"), Collections.emptyList(),
|
||||
messageDeliveryQueue);
|
||||
|
||||
ScheduledExecutorService recurringJobExecutor = environment.lifecycle()
|
||||
.scheduledExecutorService(name(getClass(), "recurringJob-%d")).threads(6).build();
|
||||
ScheduledExecutorService websocketScheduledExecutor = environment.lifecycle().scheduledExecutorService(name(getClass(), "websocket-%d")).threads(8).build();
|
||||
ExecutorService keyspaceNotificationDispatchExecutor = environment.lifecycle().executorService(name(getClass(), "keyspaceNotification-%d")).maxThreads(16).workQueue(keyspaceNotificationDispatchQueue).build();
|
||||
ExecutorService apnSenderExecutor = environment.lifecycle().executorService(name(getClass(), "apnSender-%d")).maxThreads(1).minThreads(1).build();
|
||||
ExecutorService fcmSenderExecutor = environment.lifecycle().executorService(name(getClass(), "fcmSender-%d")).maxThreads(32).minThreads(32).workQueue(fcmSenderQueue).build();
|
||||
ExecutorService backupServiceExecutor = environment.lifecycle().executorService(name(getClass(), "backupService-%d")).maxThreads(1).minThreads(1).build();
|
||||
ExecutorService storageServiceExecutor = environment.lifecycle().executorService(name(getClass(), "storageService-%d")).maxThreads(1).minThreads(1).build();
|
||||
ExecutorService fcmSenderExecutor = environment.lifecycle().executorService(name(getClass(), "fcmSender-%d"))
|
||||
.maxThreads(32).minThreads(32).workQueue(fcmSenderQueue).build();
|
||||
ExecutorService secureValueRecoveryServiceExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "secureValueRecoveryService-%d")).maxThreads(1).minThreads(1).build();
|
||||
ExecutorService storageServiceExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "storageService-%d")).maxThreads(1).minThreads(1).build();
|
||||
ExecutorService accountDeletionExecutor = environment.lifecycle().executorService(name(getClass(), "accountCleaner-%d")).maxThreads(16).minThreads(16).build();
|
||||
|
||||
// using 80 threads to match Schedulers.boundedElastic() behavior
|
||||
Scheduler messageDeliveryScheduler = Schedulers.fromExecutorService(
|
||||
ExecutorServiceMetrics.monitor(Metrics.globalRegistry,
|
||||
environment.lifecycle().executorService(name(getClass(), "messageDelivery-%d"))
|
||||
.minThreads(80)
|
||||
.maxThreads(80)
|
||||
.workQueue(messageDeliveryQueue)
|
||||
.build(),
|
||||
MetricsUtil.name(getClass(), "messageDeliveryExecutor")),
|
||||
"messageDelivery");
|
||||
// TODO: generally speaking this is a DynamoDB I/O executor for the accounts table; we should eventually have a general executor for speaking to the accounts table, but most of the server is still synchronous so this isn't widely useful yet
|
||||
ExecutorService batchIdentityCheckExecutor = environment.lifecycle().executorService(name(getClass(), "batchIdentityCheck-%d")).minThreads(32).maxThreads(32).build();
|
||||
ExecutorService multiRecipientMessageExecutor = environment.lifecycle()
|
||||
@@ -469,20 +493,30 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
dynamicConfigurationManager.start();
|
||||
|
||||
ExperimentEnrollmentManager experimentEnrollmentManager = new ExperimentEnrollmentManager(dynamicConfigurationManager);
|
||||
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager = new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords);
|
||||
ExperimentEnrollmentManager experimentEnrollmentManager = new ExperimentEnrollmentManager(
|
||||
dynamicConfigurationManager);
|
||||
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager = new RegistrationRecoveryPasswordsManager(
|
||||
registrationRecoveryPasswords);
|
||||
UsernameHashZkProofVerifier usernameHashZkProofVerifier = new UsernameHashZkProofVerifier();
|
||||
|
||||
RegistrationServiceClient registrationServiceClient = new RegistrationServiceClient(config.getRegistrationServiceConfiguration().getHost(), config.getRegistrationServiceConfiguration().getPort(), config.getRegistrationServiceConfiguration().getApiKey(), config.getRegistrationServiceConfiguration().getRegistrationCaCertificate(), registrationCallbackExecutor);
|
||||
SecureBackupClient secureBackupClient = new SecureBackupClient(backupCredentialsGenerator, backupServiceExecutor, config.getSecureBackupServiceConfiguration());
|
||||
SecureStorageClient secureStorageClient = new SecureStorageClient(storageCredentialsGenerator, storageServiceExecutor, config.getSecureStorageServiceConfiguration());
|
||||
ClientPresenceManager clientPresenceManager = new ClientPresenceManager(clientPresenceCluster, recurringJobExecutor, keyspaceNotificationDispatchExecutor);
|
||||
DirectoryQueue directoryQueue = new DirectoryQueue(config.getDirectoryConfiguration().getSqsConfiguration());
|
||||
StoredVerificationCodeManager pendingAccountsManager = new StoredVerificationCodeManager(pendingAccounts);
|
||||
StoredVerificationCodeManager pendingDevicesManager = new StoredVerificationCodeManager(pendingDevices);
|
||||
RegistrationServiceClient registrationServiceClient = new RegistrationServiceClient(
|
||||
config.getRegistrationServiceConfiguration().getHost(), config.getRegistrationServiceConfiguration().getPort(),
|
||||
config.getRegistrationServiceConfiguration().getApiKey(),
|
||||
config.getRegistrationServiceConfiguration().getRegistrationCaCertificate(), registrationCallbackExecutor);
|
||||
SecureBackupClient secureBackupClient = new SecureBackupClient(backupCredentialsGenerator,
|
||||
secureValueRecoveryServiceExecutor, config.getSecureBackupServiceConfiguration());
|
||||
SecureValueRecovery2Client secureValueRecovery2Client = new SecureValueRecovery2Client(svr2CredentialsGenerator,
|
||||
secureValueRecoveryServiceExecutor, config.getSvr2Configuration());
|
||||
SecureStorageClient secureStorageClient = new SecureStorageClient(storageCredentialsGenerator,
|
||||
storageServiceExecutor, config.getSecureStorageServiceConfiguration());
|
||||
ClientPresenceManager clientPresenceManager = new ClientPresenceManager(clientPresenceCluster, recurringJobExecutor,
|
||||
keyspaceNotificationDispatchExecutor);
|
||||
DirectoryQueue directoryQueue = new DirectoryQueue(config.getDirectoryConfiguration().getSqsConfiguration());
|
||||
StoredVerificationCodeManager pendingAccountsManager = new StoredVerificationCodeManager(pendingAccounts);
|
||||
StoredVerificationCodeManager pendingDevicesManager = new StoredVerificationCodeManager(pendingDevices);
|
||||
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster);
|
||||
MessagesCache messagesCache = new MessagesCache(messagesCluster, messagesCluster, Clock.systemUTC(),
|
||||
keyspaceNotificationDispatchExecutor, messageDeletionAsyncExecutor);
|
||||
MessagesCache messagesCache = new MessagesCache(messagesCluster, messagesCluster,
|
||||
keyspaceNotificationDispatchExecutor, messageDeliveryScheduler, messageDeletionAsyncExecutor, clock);
|
||||
PushLatencyManager pushLatencyManager = new PushLatencyManager(metricsCluster, dynamicConfigurationManager);
|
||||
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster,
|
||||
config.getReportMessageConfiguration().getCounterTtl());
|
||||
@@ -492,7 +526,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
deletedAccountsLockDynamoDbClient, config.getDynamoDbTables().getDeletedAccountsLock().getTableName());
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
deletedAccountsManager, directoryQueue, keys, messagesManager, profilesManager,
|
||||
pendingAccountsManager, secureStorageClient, secureBackupClient, clientPresenceManager,
|
||||
pendingAccountsManager, secureStorageClient, secureBackupClient, secureValueRecovery2Client, clientPresenceManager,
|
||||
experimentEnrollmentManager, registrationRecoveryPasswordsManager, clock);
|
||||
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs);
|
||||
DispatchManager dispatchManager = new DispatchManager(pubSubClientFactory, Optional.empty());
|
||||
@@ -671,7 +705,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
webSocketEnvironment.setAuthenticator(new WebSocketAccountAuthenticator(accountAuthenticator));
|
||||
webSocketEnvironment.setConnectListener(
|
||||
new AuthenticatedConnectListener(receiptSender, messagesManager, pushNotificationManager,
|
||||
clientPresenceManager, websocketScheduledExecutor));
|
||||
clientPresenceManager, websocketScheduledExecutor, messageDeliveryScheduler));
|
||||
webSocketEnvironment.jersey()
|
||||
.register(new WebsocketRefreshApplicationEventListener(accountsManager, clientPresenceManager));
|
||||
webSocketEnvironment.jersey().register(new RequestStatisticsFilter(TrafficSource.WEBSOCKET));
|
||||
@@ -747,8 +781,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new DirectoryV2Controller(directoryV2CredentialsGenerator),
|
||||
new DonationController(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(),
|
||||
ReceiptCredentialPresentation::new),
|
||||
new MessageController(rateLimiters, messageSender, receiptSender, accountsManager, deletedAccountsManager, messagesManager, pushNotificationManager, reportMessageManager, multiRecipientMessageExecutor,
|
||||
reportSpamTokenProvider),
|
||||
new MessageController(rateLimiters, messageSender, receiptSender, accountsManager, deletedAccountsManager,
|
||||
messagesManager, pushNotificationManager, reportMessageManager, multiRecipientMessageExecutor,
|
||||
messageDeliveryScheduler, reportSpamTokenProvider),
|
||||
new PaymentsController(currencyManager, paymentsCredentialsGenerator),
|
||||
new ProfileController(clock, rateLimiters, accountsManager, profilesManager, dynamicConfigurationManager,
|
||||
profileBadgeConverter, config.getBadges(), cdnS3Client, profileCdnPolicyGenerator, profileCdnPolicySigner,
|
||||
@@ -761,13 +796,13 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getRemoteConfigConfiguration().getGlobalConfig()),
|
||||
new SecureBackupController(backupCredentialsGenerator, accountsManager),
|
||||
new SecureStorageController(storageCredentialsGenerator),
|
||||
new SecureValueRecovery2Controller(svr2CredentialsGenerator),
|
||||
new SecureValueRecovery2Controller(svr2CredentialsGenerator, config.getSvr2Configuration()),
|
||||
new StickerController(rateLimiters, config.getCdnConfiguration().getAccessKey(),
|
||||
config.getCdnConfiguration().getAccessSecret(), config.getCdnConfiguration().getRegion(),
|
||||
config.getCdnConfiguration().getBucket()),
|
||||
new VerificationController(registrationServiceClient, new VerificationSessionManager(verificationSessions),
|
||||
pushNotificationManager, registrationCaptchaManager, registrationRecoveryPasswordsManager, rateLimiters,
|
||||
clock)
|
||||
accountsManager, clock)
|
||||
);
|
||||
if (config.getSubscription() != null && config.getOneTimeDonations() != null) {
|
||||
commonControllers.add(new SubscriptionController(clock, config.getSubscription(), config.getOneTimeDonations(),
|
||||
@@ -780,6 +815,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
webSocketEnvironment.jersey().register(controller);
|
||||
}
|
||||
|
||||
|
||||
WebSocketEnvironment<AuthenticatedAccount> provisioningEnvironment = new WebSocketEnvironment<>(environment,
|
||||
webSocketEnvironment.getRequestLog(), 60000);
|
||||
provisioningEnvironment.jersey().register(new WebsocketRefreshApplicationEventListener(accountsManager, clientPresenceManager));
|
||||
@@ -789,6 +825,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
registerCorsFilter(environment);
|
||||
registerExceptionMappers(environment, webSocketEnvironment, provisioningEnvironment);
|
||||
registerProviders(environment, webSocketEnvironment, provisioningEnvironment);
|
||||
|
||||
environment.jersey().property(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE);
|
||||
webSocketEnvironment.jersey().property(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE);
|
||||
@@ -830,6 +867,15 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
GarbageCollectionGauges.registerMetrics();
|
||||
}
|
||||
|
||||
|
||||
private void registerProviders(Environment environment,
|
||||
WebSocketEnvironment<AuthenticatedAccount> webSocketEnvironment,
|
||||
WebSocketEnvironment<AuthenticatedAccount> provisioningEnvironment) {
|
||||
environment.jersey().register(ScoreThresholdProvider.ScoreThresholdFeature.class);
|
||||
webSocketEnvironment.jersey().register(ScoreThresholdProvider.ScoreThresholdFeature.class);
|
||||
provisioningEnvironment.jersey().register(ScoreThresholdProvider.ScoreThresholdFeature.class);
|
||||
}
|
||||
|
||||
private void registerExceptionMappers(Environment environment,
|
||||
WebSocketEnvironment<AuthenticatedAccount> webSocketEnvironment,
|
||||
WebSocketEnvironment<AuthenticatedAccount> provisioningEnvironment) {
|
||||
|
||||
+16
-7
@@ -18,8 +18,6 @@ import org.apache.commons.lang3.Validate;
|
||||
|
||||
public class ExternalServiceCredentialsGenerator {
|
||||
|
||||
private static final int TRUNCATE_LENGTH = 10;
|
||||
|
||||
private static final String DELIMITER = ":";
|
||||
|
||||
private final byte[] key;
|
||||
@@ -32,6 +30,7 @@ public class ExternalServiceCredentialsGenerator {
|
||||
|
||||
private final Clock clock;
|
||||
|
||||
private final int truncateLength;
|
||||
|
||||
public static ExternalServiceCredentialsGenerator.Builder builder(final byte[] key) {
|
||||
return new Builder(key);
|
||||
@@ -42,12 +41,14 @@ public class ExternalServiceCredentialsGenerator {
|
||||
final byte[] userDerivationKey,
|
||||
final boolean prependUsername,
|
||||
final boolean truncateSignature,
|
||||
final Clock clock) {
|
||||
final Clock clock,
|
||||
final int truncateLength) {
|
||||
this.key = requireNonNull(key);
|
||||
this.userDerivationKey = requireNonNull(userDerivationKey);
|
||||
this.prependUsername = prependUsername;
|
||||
this.truncateSignature = truncateSignature;
|
||||
this.clock = requireNonNull(clock);
|
||||
this.truncateLength = truncateLength;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -66,7 +67,7 @@ public class ExternalServiceCredentialsGenerator {
|
||||
*/
|
||||
public ExternalServiceCredentials generateFor(final String identity) {
|
||||
final String username = shouldDeriveUsername()
|
||||
? hmac256TruncatedToHexString(userDerivationKey, identity, TRUNCATE_LENGTH)
|
||||
? hmac256TruncatedToHexString(userDerivationKey, identity, truncateLength)
|
||||
: identity;
|
||||
|
||||
final long currentTimeSeconds = currentTimeSeconds();
|
||||
@@ -74,7 +75,7 @@ public class ExternalServiceCredentialsGenerator {
|
||||
final String dataToSign = username + DELIMITER + currentTimeSeconds;
|
||||
|
||||
final String signature = truncateSignature
|
||||
? hmac256TruncatedToHexString(key, dataToSign, TRUNCATE_LENGTH)
|
||||
? hmac256TruncatedToHexString(key, dataToSign, truncateLength)
|
||||
: hmac256ToHexString(key, dataToSign);
|
||||
|
||||
final String token = (prependUsername ? dataToSign : currentTimeSeconds) + DELIMITER + signature;
|
||||
@@ -131,7 +132,7 @@ public class ExternalServiceCredentialsGenerator {
|
||||
|
||||
final String signedData = credentials.username() + DELIMITER + timestampSeconds;
|
||||
final String expectedSignature = truncateSignature
|
||||
? hmac256TruncatedToHexString(key, signedData, TRUNCATE_LENGTH)
|
||||
? hmac256TruncatedToHexString(key, signedData, truncateLength)
|
||||
: hmac256ToHexString(key, signedData);
|
||||
|
||||
// if the signature is valid it's safe to parse the `timestampSeconds` string into Long
|
||||
@@ -171,6 +172,8 @@ public class ExternalServiceCredentialsGenerator {
|
||||
|
||||
private boolean truncateSignature = true;
|
||||
|
||||
private int truncateLength = 10;
|
||||
|
||||
private Clock clock = Clock.systemUTC();
|
||||
|
||||
|
||||
@@ -189,6 +192,12 @@ public class ExternalServiceCredentialsGenerator {
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder withTruncateLength(int truncateLength) {
|
||||
Validate.inclusiveBetween(10, 32, truncateLength);
|
||||
this.truncateLength = truncateLength;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder prependUsername(final boolean prependUsername) {
|
||||
this.prependUsername = prependUsername;
|
||||
return this;
|
||||
@@ -201,7 +210,7 @@ public class ExternalServiceCredentialsGenerator {
|
||||
|
||||
public ExternalServiceCredentialsGenerator build() {
|
||||
return new ExternalServiceCredentialsGenerator(
|
||||
key, userDerivationKey, prependUsername, truncateSignature, clock);
|
||||
key, userDerivationKey, prependUsername, truncateSignature, clock, truncateLength);
|
||||
}
|
||||
}
|
||||
}
|
||||
+64
-16
@@ -11,23 +11,39 @@ import com.google.common.annotations.VisibleForTesting;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.Response;
|
||||
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 org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
|
||||
public class RegistrationLockVerificationManager {
|
||||
public enum Flow {
|
||||
REGISTRATION,
|
||||
CHANGE_NUMBER
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public static final int FAILURE_HTTP_STATUS = 423;
|
||||
|
||||
private static final String LOCKED_ACCOUNT_COUNTER_NAME =
|
||||
name(RegistrationLockVerificationManager.class, "lockedAccount");
|
||||
private static final String LOCK_REASON_TAG_NAME = "lockReason";
|
||||
private static final String EXPIRED_REGISTRATION_LOCK_COUNTER_NAME =
|
||||
name(RegistrationLockVerificationManager.class, "expiredRegistrationLock");
|
||||
private static final String REQUIRED_REGISTRATION_LOCK_COUNTER_NAME =
|
||||
name(RegistrationLockVerificationManager.class, "requiredRegistrationLock");
|
||||
private static final String ALREADY_LOCKED_TAG_NAME = "alreadyLocked";
|
||||
private static final String REGISTRATION_LOCK_VERIFICATION_FLOW_TAG_NAME = "flow";
|
||||
private static final String REGISTRATION_LOCK_MATCHES_TAG_NAME = "registrationLockMatches";
|
||||
private static final String PHONE_VERIFICATION_TYPE_TAG_NAME = "phoneVerificationType";
|
||||
|
||||
|
||||
private final AccountsManager accounts;
|
||||
@@ -52,15 +68,29 @@ public class RegistrationLockVerificationManager {
|
||||
* @throws RateLimitExceededException
|
||||
* @throws WebApplicationException
|
||||
*/
|
||||
public void verifyRegistrationLock(final Account account, @Nullable final String clientRegistrationLock)
|
||||
throws RateLimitExceededException, WebApplicationException {
|
||||
public void verifyRegistrationLock(final Account account, @Nullable final String clientRegistrationLock,
|
||||
final String userAgent,
|
||||
final Flow flow,
|
||||
final PhoneVerificationRequest.VerificationType phoneVerificationType
|
||||
) throws RateLimitExceededException, WebApplicationException {
|
||||
|
||||
final Tags expiredTags = Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(REGISTRATION_LOCK_VERIFICATION_FLOW_TAG_NAME, flow.name()),
|
||||
Tag.of(PHONE_VERIFICATION_TYPE_TAG_NAME, phoneVerificationType.name())
|
||||
);
|
||||
|
||||
final StoredRegistrationLock existingRegistrationLock = account.getRegistrationLock();
|
||||
final ExternalServiceCredentials existingBackupCredentials =
|
||||
backupServiceCredentialGenerator.generateForUuid(account.getUuid());
|
||||
|
||||
if (!existingRegistrationLock.requiresClientRegistrationLock()) {
|
||||
return;
|
||||
switch (existingRegistrationLock.getStatus()) {
|
||||
case EXPIRED:
|
||||
Metrics.counter(EXPIRED_REGISTRATION_LOCK_COUNTER_NAME, expiredTags).increment();
|
||||
return;
|
||||
case ABSENT:
|
||||
return;
|
||||
case REQUIRED:
|
||||
break;
|
||||
default:
|
||||
throw new RuntimeException("Unexpected status: " + existingRegistrationLock.getStatus());
|
||||
}
|
||||
|
||||
if (!Util.isEmpty(clientRegistrationLock)) {
|
||||
@@ -68,18 +98,34 @@ public class RegistrationLockVerificationManager {
|
||||
}
|
||||
|
||||
final String phoneNumber = account.getNumber();
|
||||
final boolean registrationLockMatches = existingRegistrationLock.verify(clientRegistrationLock);
|
||||
final boolean alreadyLocked = account.hasLockedCredentials();
|
||||
|
||||
if (!existingRegistrationLock.verify(clientRegistrationLock)) {
|
||||
final Tags additionalTags = expiredTags.and(
|
||||
REGISTRATION_LOCK_MATCHES_TAG_NAME, Boolean.toString(registrationLockMatches),
|
||||
ALREADY_LOCKED_TAG_NAME, Boolean.toString(alreadyLocked)
|
||||
);
|
||||
|
||||
Metrics.counter(REQUIRED_REGISTRATION_LOCK_COUNTER_NAME, additionalTags).increment();
|
||||
|
||||
final DistributionSummary registrationLockIdleDays = DistributionSummary
|
||||
.builder(name(RegistrationLockVerificationManager.class, "registrationLockIdleDays"))
|
||||
.tags(additionalTags)
|
||||
.publishPercentiles(0.75, 0.95, 0.99, 0.999)
|
||||
.distributionStatisticExpiry(Duration.ofHours(2))
|
||||
.register(Metrics.globalRegistry);
|
||||
|
||||
final Instant accountLastSeen = Instant.ofEpochMilli(account.getLastSeen());
|
||||
final Duration timeSinceLastSeen = Duration.between(accountLastSeen, Instant.now());
|
||||
|
||||
registrationLockIdleDays.record(timeSinceLastSeen.toDays());
|
||||
|
||||
if (!registrationLockMatches) {
|
||||
// At this point, the client verified ownership of the phone number but doesn’t have the reglock PIN.
|
||||
// Freezing the existing account credentials will definitively start the reglock timeout.
|
||||
// Until the timeout, the current reglock can still be supplied,
|
||||
// along with phone number verification, to restore access.
|
||||
/*
|
||||
boolean alreadyLocked = existingAccount.hasLockedCredentials();
|
||||
Metrics.counter(LOCKED_ACCOUNT_COUNTER_NAME,
|
||||
LOCK_REASON_TAG_NAME, "verifiedNumberFailedReglock",
|
||||
ALREADY_LOCKED_TAG_NAME, Boolean.toString(alreadyLocked))
|
||||
.increment();
|
||||
|
||||
final Account updatedAccount;
|
||||
if (!alreadyLocked) {
|
||||
@@ -91,9 +137,11 @@ public class RegistrationLockVerificationManager {
|
||||
List<Long> deviceIds = updatedAccount.getDevices().stream().map(Device::getId).toList();
|
||||
clientPresenceManager.disconnectAllPresences(updatedAccount.getUuid(), deviceIds);
|
||||
*/
|
||||
final ExternalServiceCredentials existingBackupCredentials =
|
||||
backupServiceCredentialGenerator.generateForUuid(account.getUuid());
|
||||
|
||||
throw new WebApplicationException(Response.status(FAILURE_HTTP_STATUS)
|
||||
.entity(new RegistrationLockFailure(existingRegistrationLock.getTimeRemaining(),
|
||||
.entity(new RegistrationLockFailure(existingRegistrationLock.getTimeRemaining().toMillis(),
|
||||
existingRegistrationLock.needsFailureCredentials() ? existingBackupCredentials : null))
|
||||
.build());
|
||||
}
|
||||
|
||||
+29
-10
@@ -6,25 +6,35 @@
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
public class StoredRegistrationLock {
|
||||
public enum Status {
|
||||
REQUIRED,
|
||||
EXPIRED,
|
||||
ABSENT
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration REGISTRATION_LOCK_EXPIRATION_DAYS = Duration.ofDays(7);
|
||||
|
||||
private final Optional<String> registrationLock;
|
||||
|
||||
private final Optional<String> registrationLockSalt;
|
||||
|
||||
private final long lastSeen;
|
||||
private final Instant lastSeen;
|
||||
|
||||
/**
|
||||
* @return milliseconds since the last time the account was seen.
|
||||
*/
|
||||
private long timeSinceLastSeen() {
|
||||
return System.currentTimeMillis() - lastSeen;
|
||||
return System.currentTimeMillis() - lastSeen.toEpochMilli();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -34,23 +44,32 @@ public class StoredRegistrationLock {
|
||||
return registrationLock.isPresent() && registrationLockSalt.isPresent();
|
||||
}
|
||||
|
||||
public StoredRegistrationLock(Optional<String> registrationLock, Optional<String> registrationLockSalt, long lastSeen) {
|
||||
public boolean isPresent() {
|
||||
return hasLockAndSalt();
|
||||
}
|
||||
|
||||
public StoredRegistrationLock(Optional<String> registrationLock, Optional<String> registrationLockSalt, Instant lastSeen) {
|
||||
this.registrationLock = registrationLock;
|
||||
this.registrationLockSalt = registrationLockSalt;
|
||||
this.lastSeen = lastSeen;
|
||||
}
|
||||
|
||||
public boolean requiresClientRegistrationLock() {
|
||||
boolean hasTimeRemaining = getTimeRemaining() >= 0;
|
||||
return hasLockAndSalt() && hasTimeRemaining;
|
||||
public Status getStatus() {
|
||||
if (!isPresent()) {
|
||||
return Status.ABSENT;
|
||||
}
|
||||
if (getTimeRemaining().toMillis() > 0) {
|
||||
return Status.REQUIRED;
|
||||
}
|
||||
return Status.EXPIRED;
|
||||
}
|
||||
|
||||
public boolean needsFailureCredentials() {
|
||||
return hasLockAndSalt();
|
||||
}
|
||||
|
||||
public long getTimeRemaining() {
|
||||
return TimeUnit.DAYS.toMillis(7) - timeSinceLastSeen();
|
||||
public Duration getTimeRemaining() {
|
||||
return REGISTRATION_LOCK_EXPIRATION_DAYS.minus(timeSinceLastSeen(), ChronoUnit.MILLIS);
|
||||
}
|
||||
|
||||
public boolean verify(@Nullable String clientRegistrationLock) {
|
||||
@@ -64,6 +83,6 @@ public class StoredRegistrationLock {
|
||||
|
||||
@VisibleForTesting
|
||||
public StoredRegistrationLock forTime(long timestamp) {
|
||||
return new StoredRegistrationLock(registrationLock, registrationLockSalt, timestamp);
|
||||
return new StoredRegistrationLock(registrationLock, registrationLockSalt, Instant.ofEpochMilli(timestamp));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.captcha;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import java.util.Arrays;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public enum Action {
|
||||
CHALLENGE("challenge"),
|
||||
REGISTRATION("registration");
|
||||
|
||||
private final String actionName;
|
||||
|
||||
Action(String actionName) {
|
||||
this.actionName = actionName;
|
||||
}
|
||||
|
||||
public String getActionName() {
|
||||
return actionName;
|
||||
}
|
||||
|
||||
private static final Map<String, Action> ENUM_MAP = Arrays
|
||||
.stream(Action.values())
|
||||
.collect(Collectors.toMap(
|
||||
a -> a.actionName,
|
||||
Function.identity()));
|
||||
@JsonCreator
|
||||
public static Action fromString(String key) {
|
||||
return ENUM_MAP.get(key.toLowerCase(Locale.ROOT).strip());
|
||||
}
|
||||
|
||||
static Optional<Action> parse(final String action) {
|
||||
return Optional.ofNullable(fromString(action));
|
||||
}
|
||||
}
|
||||
+98
-10
@@ -5,23 +5,111 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.captcha;
|
||||
|
||||
/**
|
||||
* A captcha assessment
|
||||
*
|
||||
* @param valid whether the captcha was passed
|
||||
* @param score string representation of the risk level
|
||||
*/
|
||||
public record AssessmentResult(boolean valid, String score) {
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
public static AssessmentResult invalid() {
|
||||
return new AssessmentResult(false, "");
|
||||
public class AssessmentResult {
|
||||
|
||||
private final boolean solved;
|
||||
private final float actualScore;
|
||||
private final float defaultScoreThreshold;
|
||||
private final String scoreString;
|
||||
|
||||
/**
|
||||
* A captcha assessment
|
||||
*
|
||||
* @param solved if false, the captcha was not successfully completed
|
||||
* @param actualScore float representation of the risk level from [0, 1.0], with 1.0 being the least risky
|
||||
* @param defaultScoreThreshold the score threshold which the score will be evaluated against by default
|
||||
* @param scoreString a quantized string representation of the risk level, suitable for use in metrics
|
||||
*/
|
||||
private AssessmentResult(boolean solved, float actualScore, float defaultScoreThreshold, final String scoreString) {
|
||||
this.solved = solved;
|
||||
this.actualScore = actualScore;
|
||||
this.defaultScoreThreshold = defaultScoreThreshold;
|
||||
this.scoreString = scoreString;
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct an {@link AssessmentResult} from a captcha evaluation score
|
||||
*
|
||||
* @param actualScore the score
|
||||
* @param defaultScoreThreshold the threshold to compare the score against by default
|
||||
*/
|
||||
public static AssessmentResult fromScore(float actualScore, float defaultScoreThreshold) {
|
||||
if (actualScore < 0 || actualScore > 1.0 || defaultScoreThreshold < 0 || defaultScoreThreshold > 1.0) {
|
||||
throw new IllegalArgumentException("invalid captcha score");
|
||||
}
|
||||
return new AssessmentResult(true, actualScore, defaultScoreThreshold, AssessmentResult.scoreString(actualScore));
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a captcha assessment that will always be invalid
|
||||
*/
|
||||
public static AssessmentResult invalid() {
|
||||
return new AssessmentResult(false, 0.0f, 0.0f, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a captcha assessment that will always be valid
|
||||
*/
|
||||
public static AssessmentResult alwaysValid() {
|
||||
return new AssessmentResult(true, 1.0f, 0.0f, "1.0");
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the captcha assessment should be accepted using the default score threshold
|
||||
*
|
||||
* @return true if this assessment should be accepted under the default score threshold
|
||||
*/
|
||||
public boolean isValid() {
|
||||
return isValid(Optional.empty());
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the captcha assessment should be accepted
|
||||
*
|
||||
* @param scoreThreshold the minimum score the assessment requires to pass, uses default if empty
|
||||
* @return true if the assessment scored higher than the provided scoreThreshold
|
||||
*/
|
||||
public boolean isValid(Optional<Float> scoreThreshold) {
|
||||
if (!solved) {
|
||||
return false;
|
||||
}
|
||||
return this.actualScore >= scoreThreshold.orElse(this.defaultScoreThreshold);
|
||||
}
|
||||
|
||||
public String getScoreString() {
|
||||
return scoreString;
|
||||
}
|
||||
|
||||
public float getScore() {
|
||||
return this.actualScore;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Map a captcha score in [0.0, 1.0] to a low cardinality discrete space in [0, 100] suitable for use in metrics
|
||||
*/
|
||||
static String scoreString(final float score) {
|
||||
private static String scoreString(final float score) {
|
||||
final int x = Math.round(score * 10); // [0, 10]
|
||||
return Integer.toString(x * 10); // [0, 100] in increments of 10
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
AssessmentResult that = (AssessmentResult) o;
|
||||
return solved == that.solved && Float.compare(that.actualScore, actualScore) == 0
|
||||
&& Float.compare(that.defaultScoreThreshold, defaultScoreThreshold) == 0 && Objects.equals(scoreString,
|
||||
that.scoreString);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(solved, actualScore, defaultScoreThreshold, scoreString);
|
||||
}
|
||||
}
|
||||
+45
-22
@@ -5,19 +5,26 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.captcha;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.ws.rs.BadRequestException;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class CaptchaChecker {
|
||||
private static final Logger logger = LoggerFactory.getLogger(CaptchaChecker.class);
|
||||
private static final String INVALID_SITEKEY_COUNTER_NAME = name(CaptchaChecker.class, "invalidSiteKey");
|
||||
private static final String ASSESSMENTS_COUNTER_NAME = name(RecaptchaClient.class, "assessments");
|
||||
private static final String INVALID_ACTION_COUNTER_NAME = name(CaptchaChecker.class, "invalidActions");
|
||||
|
||||
@VisibleForTesting
|
||||
static final String SEPARATOR = ".";
|
||||
@@ -29,46 +36,62 @@ public class CaptchaChecker {
|
||||
.collect(Collectors.toMap(CaptchaClient::scheme, Function.identity()));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Check if a solved captcha should be accepted
|
||||
* <p>
|
||||
*
|
||||
* @param input expected to contain a prefix indicating the captcha scheme, sitekey, token, and action. The expected
|
||||
* format is {@code version-prefix.sitekey.[action.]token}
|
||||
* @param ip IP of the solver
|
||||
* @param expectedAction the {@link Action} for which this captcha solution is intended
|
||||
* @param input expected to contain a prefix indicating the captcha scheme, sitekey, token, and action. The
|
||||
* expected format is {@code version-prefix.sitekey.action.token}
|
||||
* @param ip IP of the solver
|
||||
* @return An {@link AssessmentResult} indicating whether the solution should be accepted, and a score that can be
|
||||
* used for metrics
|
||||
* @throws IOException if there is an error validating the captcha with the underlying service
|
||||
* @throws BadRequestException if input is not in the expected format
|
||||
*/
|
||||
public AssessmentResult verify(final String input, final String ip) throws IOException {
|
||||
/*
|
||||
* For action to be optional, there is a strong assumption that the token will never contain a {@value SEPARATOR}.
|
||||
* Observation suggests {@code token} is base-64 encoded. In practice, an action should always be present, but we
|
||||
* don’t need to be strict.
|
||||
*/
|
||||
public AssessmentResult verify(
|
||||
final Action expectedAction,
|
||||
final String input,
|
||||
final String ip) throws IOException {
|
||||
final String[] parts = input.split("\\" + SEPARATOR, 4);
|
||||
|
||||
// we allow missing actions, if we're missing 1 part, assume it's the action
|
||||
if (parts.length < 3) {
|
||||
if (parts.length < 4) {
|
||||
throw new BadRequestException("too few parts");
|
||||
}
|
||||
|
||||
int idx = 0;
|
||||
final String prefix = parts[idx++];
|
||||
final String siteKey = parts[idx++];
|
||||
final String action = parts.length == 3 ? null : parts[idx++];
|
||||
final String token = parts[idx];
|
||||
final String prefix = parts[0];
|
||||
final String siteKey = parts[1].toLowerCase(Locale.ROOT).strip();
|
||||
final String action = parts[2];
|
||||
final String token = parts[3];
|
||||
|
||||
final CaptchaClient client = this.captchaClientMap.get(prefix);
|
||||
if (client == null) {
|
||||
throw new BadRequestException("invalid captcha scheme");
|
||||
}
|
||||
final AssessmentResult result = client.verify(siteKey, action, token, ip);
|
||||
|
||||
final Action parsedAction = Action.parse(action)
|
||||
.orElseThrow(() -> {
|
||||
Metrics.counter(INVALID_ACTION_COUNTER_NAME, "action", action).increment();
|
||||
throw new BadRequestException("invalid captcha action");
|
||||
});
|
||||
|
||||
if (!parsedAction.equals(expectedAction)) {
|
||||
Metrics.counter(INVALID_ACTION_COUNTER_NAME, "action", action).increment();
|
||||
throw new BadRequestException("invalid captcha action");
|
||||
}
|
||||
|
||||
final Set<String> allowedSiteKeys = client.validSiteKeys(parsedAction);
|
||||
if (!allowedSiteKeys.contains(siteKey)) {
|
||||
logger.debug("invalid site-key {}, action={}, token={}", siteKey, action, token);
|
||||
Metrics.counter(INVALID_SITEKEY_COUNTER_NAME, "action", action).increment();
|
||||
throw new BadRequestException("invalid captcha site-key");
|
||||
}
|
||||
|
||||
final AssessmentResult result = client.verify(siteKey, parsedAction, token, ip);
|
||||
Metrics.counter(ASSESSMENTS_COUNTER_NAME,
|
||||
"action", String.valueOf(action),
|
||||
"valid", String.valueOf(result.valid()),
|
||||
"score", result.score(),
|
||||
"action", action,
|
||||
"score", result.getScoreString(),
|
||||
"provider", prefix)
|
||||
.increment();
|
||||
return result;
|
||||
|
||||
@@ -5,29 +5,37 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.captcha;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.io.IOException;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
public interface CaptchaClient {
|
||||
|
||||
|
||||
/**
|
||||
* @return the identifying captcha scheme that this CaptchaClient handles
|
||||
*/
|
||||
String scheme();
|
||||
|
||||
/**
|
||||
* @param action the action to retrieve site keys for
|
||||
* @return siteKeys this client is willing to accept
|
||||
*/
|
||||
Set<String> validSiteKeys(final Action action);
|
||||
|
||||
/**
|
||||
* Verify a provided captcha solution
|
||||
*
|
||||
* @param siteKey identifying string for the captcha service
|
||||
* @param action an optional action indicating the purpose of the captcha
|
||||
* @param action an action indicating the purpose of the captcha
|
||||
* @param token the captcha solution that will be verified
|
||||
* @param ip the ip of the captcha solve
|
||||
* @param ip the ip of the captcha solver
|
||||
* @return An {@link AssessmentResult} indicating whether the solution should be accepted
|
||||
* @throws IOException if the underlying captcha provider returns an error
|
||||
*/
|
||||
AssessmentResult verify(
|
||||
final String siteKey,
|
||||
final @Nullable String action,
|
||||
final Action action,
|
||||
final String token,
|
||||
final String ip) throws IOException;
|
||||
}
|
||||
+28
-14
@@ -9,13 +9,16 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.net.URI;
|
||||
import java.net.URLEncoder;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import javax.annotation.Nullable;
|
||||
import java.util.Collections;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import javax.ws.rs.core.Response;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -49,21 +52,31 @@ public class HCaptchaClient implements CaptchaClient {
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssessmentResult verify(final String siteKey, final @Nullable String action, final String token,
|
||||
public Set<String> validSiteKeys(final Action action) {
|
||||
final DynamicCaptchaConfiguration config = dynamicConfigurationManager.getConfiguration().getCaptchaConfiguration();
|
||||
if (!config.isAllowHCaptcha()) {
|
||||
logger.warn("Received request to verify an hCaptcha, but hCaptcha is not enabled");
|
||||
return Collections.emptySet();
|
||||
}
|
||||
return Optional
|
||||
.ofNullable(config.getHCaptchaSiteKeys().get(action))
|
||||
.orElse(Collections.emptySet());
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssessmentResult verify(
|
||||
final String siteKey,
|
||||
final Action action,
|
||||
final String token,
|
||||
final String ip)
|
||||
throws IOException {
|
||||
|
||||
final DynamicCaptchaConfiguration config = dynamicConfigurationManager.getConfiguration().getCaptchaConfiguration();
|
||||
if (!config.isAllowHCaptcha()) {
|
||||
logger.warn("Received request to verify an hCaptcha, but hCaptcha is not enabled");
|
||||
return AssessmentResult.invalid();
|
||||
}
|
||||
|
||||
final String body = String.format("response=%s&secret=%s&remoteip=%s",
|
||||
URLEncoder.encode(token, StandardCharsets.UTF_8),
|
||||
URLEncoder.encode(this.apiKey, StandardCharsets.UTF_8),
|
||||
ip);
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
final HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create("https://hcaptcha.com/siteverify"))
|
||||
.header("Content-Type", "application/x-www-form-urlencoded")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(body))
|
||||
@@ -89,26 +102,27 @@ public class HCaptchaClient implements CaptchaClient {
|
||||
if (!hCaptchaResponse.success) {
|
||||
for (String errorCode : hCaptchaResponse.errorCodes) {
|
||||
Metrics.counter(INVALID_REASON_COUNTER_NAME,
|
||||
"action", String.valueOf(action),
|
||||
"action", action.getActionName(),
|
||||
"reason", errorCode).increment();
|
||||
}
|
||||
return AssessmentResult.invalid();
|
||||
}
|
||||
|
||||
// hcaptcha uses the inverse scheme of recaptcha (for hcaptcha, a low score is less risky)
|
||||
float score = 1.0f - hCaptchaResponse.score;
|
||||
final float score = 1.0f - hCaptchaResponse.score;
|
||||
if (score < 0.0f || score > 1.0f) {
|
||||
logger.error("Invalid score {} from hcaptcha response {}", hCaptchaResponse.score, hCaptchaResponse);
|
||||
return AssessmentResult.invalid();
|
||||
}
|
||||
final String scoreString = AssessmentResult.scoreString(score);
|
||||
final BigDecimal threshold = config.getScoreFloorByAction().getOrDefault(action, config.getScoreFloor());
|
||||
final AssessmentResult assessmentResult = AssessmentResult.fromScore(score, threshold.floatValue());
|
||||
|
||||
for (String reason : hCaptchaResponse.scoreReasons) {
|
||||
Metrics.counter(ASSESSMENT_REASON_COUNTER_NAME,
|
||||
"action", String.valueOf(action),
|
||||
"action", action.getActionName(),
|
||||
"reason", reason,
|
||||
"score", scoreString).increment();
|
||||
"score", assessmentResult.getScoreString()).increment();
|
||||
}
|
||||
return new AssessmentResult(score >= config.getScoreFloor().floatValue(), scoreString);
|
||||
return assessmentResult;
|
||||
}
|
||||
}
|
||||
+34
-13
@@ -18,10 +18,13 @@ import com.google.recaptchaenterprise.v1.RiskAnalysis;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Collections;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicCaptchaConfiguration;
|
||||
@@ -34,8 +37,10 @@ public class RecaptchaClient implements CaptchaClient {
|
||||
|
||||
private static final String V2_PREFIX = "signal-recaptcha-v2";
|
||||
private static final String INVALID_REASON_COUNTER_NAME = name(RecaptchaClient.class, "invalidReason");
|
||||
private static final String INVALID_SITEKEY_COUNTER_NAME = name(RecaptchaClient.class, "invalidSiteKey");
|
||||
private static final String ASSESSMENT_REASON_COUNTER_NAME = name(RecaptchaClient.class, "assessmentReason");
|
||||
|
||||
|
||||
private final String projectPath;
|
||||
private final RecaptchaEnterpriseServiceClient client;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
@@ -63,12 +68,28 @@ public class RecaptchaClient implements CaptchaClient {
|
||||
}
|
||||
|
||||
@Override
|
||||
public org.whispersystems.textsecuregcm.captcha.AssessmentResult verify(final String sitekey,
|
||||
final @Nullable String expectedAction,
|
||||
final String token, final String ip) throws IOException {
|
||||
public Set<String> validSiteKeys(final Action action) {
|
||||
final DynamicCaptchaConfiguration config = dynamicConfigurationManager.getConfiguration().getCaptchaConfiguration();
|
||||
if (!config.isAllowRecaptcha()) {
|
||||
log.warn("Received request to verify a recaptcha, but recaptcha is not enabled");
|
||||
return Collections.emptySet();
|
||||
}
|
||||
return Optional
|
||||
.ofNullable(config.getRecaptchaSiteKeys().get(action))
|
||||
.orElse(Collections.emptySet());
|
||||
}
|
||||
|
||||
@Override
|
||||
public org.whispersystems.textsecuregcm.captcha.AssessmentResult verify(
|
||||
final String sitekey,
|
||||
final Action action,
|
||||
final String token,
|
||||
final String ip) throws IOException {
|
||||
final DynamicCaptchaConfiguration config = dynamicConfigurationManager.getConfiguration().getCaptchaConfiguration();
|
||||
final Set<String> allowedSiteKeys = config.getRecaptchaSiteKeys().get(action);
|
||||
if (allowedSiteKeys != null && !allowedSiteKeys.contains(sitekey)) {
|
||||
log.info("invalid recaptcha sitekey {}, action={}, token={}", action, token);
|
||||
Metrics.counter(INVALID_SITEKEY_COUNTER_NAME, "action", action.getActionName()).increment();
|
||||
return AssessmentResult.invalid();
|
||||
}
|
||||
|
||||
@@ -77,8 +98,8 @@ public class RecaptchaClient implements CaptchaClient {
|
||||
.setToken(token)
|
||||
.setUserIpAddress(ip);
|
||||
|
||||
if (expectedAction != null) {
|
||||
eventBuilder.setExpectedAction(expectedAction);
|
||||
if (action != null) {
|
||||
eventBuilder.setExpectedAction(action.getActionName());
|
||||
}
|
||||
|
||||
final Event event = eventBuilder.build();
|
||||
@@ -91,20 +112,20 @@ public class RecaptchaClient implements CaptchaClient {
|
||||
|
||||
if (assessment.getTokenProperties().getValid()) {
|
||||
final float score = assessment.getRiskAnalysis().getScore();
|
||||
log.debug("assessment for {} was valid, score: {}", expectedAction, score);
|
||||
log.debug("assessment for {} was valid, score: {}", action.getActionName(), score);
|
||||
final BigDecimal threshold = config.getScoreFloorByAction().getOrDefault(action, config.getScoreFloor());
|
||||
final AssessmentResult assessmentResult = AssessmentResult.fromScore(score, threshold.floatValue());
|
||||
for (RiskAnalysis.ClassificationReason reason : assessment.getRiskAnalysis().getReasonsList()) {
|
||||
Metrics.counter(ASSESSMENT_REASON_COUNTER_NAME,
|
||||
"action", String.valueOf(expectedAction),
|
||||
"score", AssessmentResult.scoreString(score),
|
||||
"action", action.getActionName(),
|
||||
"score", assessmentResult.getScoreString(),
|
||||
"reason", reason.name())
|
||||
.increment();
|
||||
}
|
||||
return new AssessmentResult(
|
||||
score >= config.getScoreFloor().floatValue(),
|
||||
AssessmentResult.scoreString(score));
|
||||
return assessmentResult;
|
||||
} else {
|
||||
Metrics.counter(INVALID_REASON_COUNTER_NAME,
|
||||
"action", String.valueOf(expectedAction),
|
||||
"action", action.getActionName(),
|
||||
"reason", assessment.getTokenProperties().getInvalidReason().name())
|
||||
.increment();
|
||||
return AssessmentResult.invalid();
|
||||
|
||||
+1
-1
@@ -54,7 +54,7 @@ public class RegistrationCaptchaManager {
|
||||
public Optional<AssessmentResult> assessCaptcha(final Optional<String> captcha, final String sourceHost)
|
||||
throws IOException {
|
||||
return captcha.isPresent()
|
||||
? Optional.of(captchaChecker.verify(captcha.get(), sourceHost))
|
||||
? Optional.of(captchaChecker.verify(Action.REGISTRATION, captcha.get(), sourceHost))
|
||||
: Optional.empty();
|
||||
}
|
||||
|
||||
|
||||
+22
-2
@@ -1,12 +1,32 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import java.util.List;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
|
||||
public record SecureValueRecovery2Configuration(
|
||||
boolean enabled,
|
||||
@NotBlank String uri,
|
||||
@ExactlySize({32}) byte[] userAuthenticationTokenSharedSecret,
|
||||
@ExactlySize({32}) byte[] userIdTokenSharedSecret) {
|
||||
@ExactlySize({32}) byte[] userIdTokenSharedSecret,
|
||||
@NotEmpty List<@NotBlank String> svrCaCertificates,
|
||||
@NotNull @Valid CircuitBreakerConfiguration circuitBreaker,
|
||||
@NotNull @Valid RetryConfiguration retry) {
|
||||
|
||||
public SecureValueRecovery2Configuration {
|
||||
if (circuitBreaker == null) {
|
||||
circuitBreaker = new CircuitBreakerConfiguration();
|
||||
}
|
||||
|
||||
if (retry == null) {
|
||||
retry = new RetryConfiguration();
|
||||
}
|
||||
}
|
||||
}
|
||||
+39
@@ -7,8 +7,11 @@ package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import org.whispersystems.textsecuregcm.captcha.Action;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import javax.validation.constraints.DecimalMax;
|
||||
import javax.validation.constraints.DecimalMin;
|
||||
@@ -28,6 +31,18 @@ public class DynamicCaptchaConfiguration {
|
||||
@JsonProperty
|
||||
private boolean allowRecaptcha = true;
|
||||
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
private Map<Action, Set<String>> hCaptchaSiteKeys = Collections.emptyMap();
|
||||
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
private Map<Action, Set<String>> recaptchaSiteKeys = Collections.emptyMap();
|
||||
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
private Map<Action, BigDecimal> scoreFloorByAction = Collections.emptyMap();
|
||||
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
private Set<String> signupCountryCodes = Collections.emptySet();
|
||||
@@ -66,6 +81,10 @@ public class DynamicCaptchaConfiguration {
|
||||
return allowRecaptcha;
|
||||
}
|
||||
|
||||
public Map<Action, BigDecimal> getScoreFloorByAction() {
|
||||
return scoreFloorByAction;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public void setAllowHCaptcha(final boolean allowHCaptcha) {
|
||||
this.allowHCaptcha = allowHCaptcha;
|
||||
@@ -75,4 +94,24 @@ public class DynamicCaptchaConfiguration {
|
||||
public void setScoreFloor(final BigDecimal scoreFloor) {
|
||||
this.scoreFloor = scoreFloor;
|
||||
}
|
||||
|
||||
public Map<Action, Set<String>> getHCaptchaSiteKeys() {
|
||||
return hCaptchaSiteKeys;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public void setHCaptchaSiteKeys(final Map<Action, Set<String>> hCaptchaSiteKeys) {
|
||||
this.hCaptchaSiteKeys = hCaptchaSiteKeys;
|
||||
}
|
||||
|
||||
public Map<Action, Set<String>> getRecaptchaSiteKeys() {
|
||||
return recaptchaSiteKeys;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public void setRecaptchaSiteKeys(final Map<Action, Set<String>> recaptchaSiteKeys) {
|
||||
this.recaptchaSiteKeys = recaptchaSiteKeys;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+27
-18
@@ -78,6 +78,7 @@ import org.whispersystems.textsecuregcm.entities.ConfirmUsernameHashRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.DeviceName;
|
||||
import org.whispersystems.textsecuregcm.entities.GcmRegistrationId;
|
||||
import org.whispersystems.textsecuregcm.entities.MismatchedDevices;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationLock;
|
||||
import org.whispersystems.textsecuregcm.entities.ReserveUsernameHashRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.ReserveUsernameHashResponse;
|
||||
@@ -92,7 +93,9 @@ import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.registration.ClientType;
|
||||
import org.whispersystems.textsecuregcm.registration.MessageTransport;
|
||||
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
|
||||
import org.whispersystems.textsecuregcm.spam.Extract;
|
||||
import org.whispersystems.textsecuregcm.spam.FilterSpam;
|
||||
import org.whispersystems.textsecuregcm.spam.ScoreThreshold;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
|
||||
@@ -237,7 +240,7 @@ public class AccountController {
|
||||
storedVerificationCode = existingStoredVerificationCode;
|
||||
}
|
||||
} else {
|
||||
final byte[] sessionId = createRegistrationSession(phoneNumber);
|
||||
final byte[] sessionId = createRegistrationSession(phoneNumber, accounts.getByE164(number).isPresent());
|
||||
storedVerificationCode = new StoredVerificationCode(null, clock.millis(), generatePushChallenge(), sessionId);
|
||||
new StoredVerificationCode(null, clock.millis(), generatePushChallenge(), sessionId);
|
||||
}
|
||||
@@ -254,14 +257,15 @@ public class AccountController {
|
||||
@Path("/{transport}/code/{number}")
|
||||
@FilterSpam
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public Response createAccount(@PathParam("transport") String transport,
|
||||
@PathParam("number") String number,
|
||||
@HeaderParam(HttpHeaders.X_FORWARDED_FOR) String forwardedFor,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent,
|
||||
@HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) Optional<String> acceptLanguage,
|
||||
@QueryParam("client") Optional<String> client,
|
||||
@QueryParam("captcha") Optional<String> captcha,
|
||||
@QueryParam("challenge") Optional<String> pushChallenge)
|
||||
public Response createAccount(@PathParam("transport") String transport,
|
||||
@PathParam("number") String number,
|
||||
@HeaderParam(HttpHeaders.X_FORWARDED_FOR) String forwardedFor,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent,
|
||||
@HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) Optional<String> acceptLanguage,
|
||||
@QueryParam("client") Optional<String> client,
|
||||
@QueryParam("captcha") Optional<String> captcha,
|
||||
@QueryParam("challenge") Optional<String> pushChallenge,
|
||||
@Extract ScoreThreshold captchaScoreThreshold)
|
||||
throws RateLimitExceededException, ImpossiblePhoneNumberException, NonNormalizedPhoneNumberException, IOException {
|
||||
|
||||
Util.requireNormalizedNumber(number);
|
||||
@@ -277,12 +281,12 @@ public class AccountController {
|
||||
|
||||
assessmentResult.ifPresent(result ->
|
||||
Metrics.counter(CAPTCHA_ATTEMPT_COUNTER_NAME, Tags.of(
|
||||
Tag.of("success", String.valueOf(result.valid())),
|
||||
Tag.of("success", String.valueOf(result.isValid(captchaScoreThreshold.getScoreThreshold()))),
|
||||
UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(COUNTRY_CODE_TAG_NAME, countryCode),
|
||||
Tag.of(REGION_TAG_NAME, region),
|
||||
Tag.of(REGION_CODE_TAG_NAME, region),
|
||||
Tag.of(SCORE_TAG_NAME, result.score())))
|
||||
Tag.of(SCORE_TAG_NAME, result.getScoreString())))
|
||||
.increment());
|
||||
|
||||
final boolean pushChallengeMatch = pushChallengeMatches(number, pushChallenge, maybeStoredVerificationCode);
|
||||
@@ -292,7 +296,7 @@ public class AccountController {
|
||||
}
|
||||
|
||||
final boolean requiresCaptcha = assessmentResult
|
||||
.map(result -> !result.valid())
|
||||
.map(result -> !result.isValid(captchaScoreThreshold.getScoreThreshold()))
|
||||
.orElseGet(
|
||||
() -> registrationCaptchaManager.requiresCaptcha(number, forwardedFor, sourceHost, pushChallengeMatch));
|
||||
|
||||
@@ -344,8 +348,9 @@ public class AccountController {
|
||||
|
||||
// During the transition to explicit session creation, some previously-stored records may not have a session ID;
|
||||
// after the transition, we can assume that any existing record has an associated session ID.
|
||||
final byte[] sessionId = maybeStoredVerificationCode.isPresent() && maybeStoredVerificationCode.get().sessionId() != null ?
|
||||
maybeStoredVerificationCode.get().sessionId() : createRegistrationSession(phoneNumber);
|
||||
final byte[] sessionId = maybeStoredVerificationCode.isPresent() && maybeStoredVerificationCode.get().sessionId() != null
|
||||
? maybeStoredVerificationCode.get().sessionId()
|
||||
: createRegistrationSession(phoneNumber, accounts.getByE164(number).isPresent());
|
||||
|
||||
sendVerificationCode(sessionId, messageTransport, clientType, acceptLanguage);
|
||||
|
||||
@@ -409,7 +414,9 @@ public class AccountController {
|
||||
|
||||
if (existingAccount.isPresent()) {
|
||||
registrationLockVerificationManager.verifyRegistrationLock(existingAccount.get(),
|
||||
accountAttributes.getRegistrationLock());
|
||||
accountAttributes.getRegistrationLock(),
|
||||
userAgent, RegistrationLockVerificationManager.Flow.REGISTRATION,
|
||||
PhoneVerificationRequest.VerificationType.SESSION);
|
||||
}
|
||||
|
||||
if (availableForTransfer.orElse(false) && existingAccount.map(Account::isTransferSupported).orElse(false)) {
|
||||
@@ -471,7 +478,8 @@ public class AccountController {
|
||||
final Optional<Account> existingAccount = accounts.getByE164(number);
|
||||
|
||||
if (existingAccount.isPresent()) {
|
||||
registrationLockVerificationManager.verifyRegistrationLock(existingAccount.get(), request.registrationLock());
|
||||
registrationLockVerificationManager.verifyRegistrationLock(existingAccount.get(), request.registrationLock(),
|
||||
userAgent, RegistrationLockVerificationManager.Flow.CHANGE_NUMBER, PhoneVerificationRequest.VerificationType.SESSION);
|
||||
}
|
||||
|
||||
rateLimiters.getVerifyLimiter().clear(number);
|
||||
@@ -855,10 +863,11 @@ public class AccountController {
|
||||
return HexFormat.of().formatHex(challenge);
|
||||
}
|
||||
|
||||
private byte[] createRegistrationSession(final Phonenumber.PhoneNumber phoneNumber) throws RateLimitExceededException {
|
||||
private byte[] createRegistrationSession(final Phonenumber.PhoneNumber phoneNumber,
|
||||
final boolean accountExistsWithPhoneNumber) throws RateLimitExceededException {
|
||||
|
||||
try {
|
||||
return registrationServiceClient.createRegistrationSession(phoneNumber, REGISTRATION_RPC_TIMEOUT).join();
|
||||
return registrationServiceClient.createRegistrationSession(phoneNumber, accountExistsWithPhoneNumber, REGISTRATION_RPC_TIMEOUT).join();
|
||||
} catch (final CompletionException e) {
|
||||
rethrowRateLimitException(e);
|
||||
|
||||
|
||||
+35
-1
@@ -13,12 +13,17 @@ import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.ws.rs.BadRequestException;
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.ForbiddenException;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.HeaderParam;
|
||||
import javax.ws.rs.PUT;
|
||||
import javax.ws.rs.Path;
|
||||
@@ -29,6 +34,7 @@ import javax.ws.rs.core.Response;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountDataReportResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ChangeNumberRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.MismatchedDevices;
|
||||
@@ -91,7 +97,8 @@ public class AccountControllerV2 {
|
||||
final Optional<Account> existingAccount = accountsManager.getByE164(number);
|
||||
|
||||
if (existingAccount.isPresent()) {
|
||||
registrationLockVerificationManager.verifyRegistrationLock(existingAccount.get(), request.registrationLock());
|
||||
registrationLockVerificationManager.verifyRegistrationLock(existingAccount.get(), request.registrationLock(),
|
||||
userAgent, RegistrationLockVerificationManager.Flow.CHANGE_NUMBER, verificationType);
|
||||
}
|
||||
|
||||
Metrics.counter(CHANGE_NUMBER_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
@@ -143,4 +150,31 @@ public class AccountControllerV2 {
|
||||
accountsManager.update(auth.getAccount(), a -> a.setDiscoverableByPhoneNumber(
|
||||
phoneNumberDiscoverability.discoverableByPhoneNumber()));
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/data_report")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(summary = "Produces a report of non-ephemeral account data stored by the service")
|
||||
@ApiResponse(responseCode = "200",
|
||||
description = "Response with data report. A plain text representation is a field in the response.",
|
||||
useReturnTypeSchema = true)
|
||||
public AccountDataReportResponse getAccountDataReport(@Auth final AuthenticatedAccount auth) {
|
||||
|
||||
final Account account = auth.getAccount();
|
||||
|
||||
return new AccountDataReportResponse(UUID.randomUUID(), Instant.now(),
|
||||
new AccountDataReportResponse.AccountAndDevicesDataReport(
|
||||
new AccountDataReportResponse.AccountDataReport(
|
||||
account.getNumber(),
|
||||
account.getBadges().stream().map(AccountDataReportResponse.BadgeDataReport::new).toList(),
|
||||
account.isUnrestrictedUnidentifiedAccess(),
|
||||
account.isDiscoverableByPhoneNumber()),
|
||||
account.getDevices().stream().map(device ->
|
||||
new AccountDataReportResponse.DeviceDataReport(
|
||||
device.getId(),
|
||||
Instant.ofEpochMilli(device.getLastSeen()),
|
||||
Instant.ofEpochMilli(device.getCreated()),
|
||||
device.getUserAgent())).toList()));
|
||||
}
|
||||
}
|
||||
+12
-10
@@ -20,8 +20,9 @@ import io.swagger.v3.oas.annotations.parameters.RequestBody;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import java.io.IOException;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Optional;
|
||||
import javax.validation.Valid;
|
||||
import javax.ws.rs.BadRequestException;
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.HeaderParam;
|
||||
import javax.ws.rs.POST;
|
||||
@@ -85,19 +86,20 @@ public class ChallengeController {
|
||||
tags = tags.and(CHALLENGE_TYPE_TAG, "push");
|
||||
|
||||
rateLimitChallengeManager.answerPushChallenge(auth.getAccount(), pushChallengeRequest.getChallenge());
|
||||
} else if (answerRequest instanceof AnswerRecaptchaChallengeRequest) {
|
||||
} else if (answerRequest instanceof AnswerRecaptchaChallengeRequest recaptchaChallengeRequest) {
|
||||
tags = tags.and(CHALLENGE_TYPE_TAG, "recaptcha");
|
||||
|
||||
try {
|
||||
final AnswerRecaptchaChallengeRequest recaptchaChallengeRequest = (AnswerRecaptchaChallengeRequest) answerRequest;
|
||||
final String mostRecentProxy = HeaderUtils.getMostRecentProxy(forwardedFor).orElseThrow();
|
||||
final String mostRecentProxy = HeaderUtils.getMostRecentProxy(forwardedFor).orElseThrow(() -> new BadRequestException());
|
||||
boolean success = rateLimitChallengeManager.answerRecaptchaChallenge(
|
||||
auth.getAccount(),
|
||||
recaptchaChallengeRequest.getCaptcha(),
|
||||
mostRecentProxy,
|
||||
userAgent);
|
||||
|
||||
rateLimitChallengeManager.answerRecaptchaChallenge(auth.getAccount(), recaptchaChallengeRequest.getCaptcha(),
|
||||
mostRecentProxy, userAgent);
|
||||
|
||||
} catch (final NoSuchElementException e) {
|
||||
return Response.status(400).build();
|
||||
if (!success) {
|
||||
return Response.status(428).build();
|
||||
}
|
||||
|
||||
} else {
|
||||
tags = tags.and(CHALLENGE_TYPE_TAG, "unrecognized");
|
||||
}
|
||||
|
||||
+1
-1
@@ -224,7 +224,7 @@ public class DeviceController {
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/capabilities")
|
||||
public void setCapabiltities(@Auth AuthenticatedAccount auth, @NotNull @Valid DeviceCapabilities capabilities) {
|
||||
public void setCapabilities(@Auth AuthenticatedAccount auth, @NotNull @Valid DeviceCapabilities capabilities) {
|
||||
assert (auth.getAuthenticatedDevice() != null);
|
||||
final long deviceId = auth.getAuthenticatedDevice().getId();
|
||||
accounts.updateDevice(auth.getAccount(), deviceId, d -> d.setCapabilities(capabilities));
|
||||
|
||||
@@ -79,10 +79,6 @@ public class KeysController {
|
||||
|
||||
int count = keys.getCount(getIdentifier(auth.getAccount(), identityType), auth.getAuthenticatedDevice().getId());
|
||||
|
||||
if (count > 0) {
|
||||
count = count - 1;
|
||||
}
|
||||
|
||||
return new PreKeyCount(count);
|
||||
}
|
||||
|
||||
|
||||
+5
-2
@@ -104,7 +104,7 @@ import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
|
||||
import org.whispersystems.textsecuregcm.websocket.WebSocketConnection;
|
||||
import org.whispersystems.websocket.Stories;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
@Path("/v1/messages")
|
||||
@@ -122,6 +122,7 @@ public class MessageController {
|
||||
private final PushNotificationManager pushNotificationManager;
|
||||
private final ReportMessageManager reportMessageManager;
|
||||
private final ExecutorService multiRecipientMessageExecutor;
|
||||
private final Scheduler messageDeliveryScheduler;
|
||||
private final ReportSpamTokenProvider reportSpamTokenProvider;
|
||||
|
||||
private static final String REJECT_OVERSIZE_MESSAGE_COUNTER = name(MessageController.class, "rejectOversizeMessage");
|
||||
@@ -154,6 +155,7 @@ public class MessageController {
|
||||
PushNotificationManager pushNotificationManager,
|
||||
ReportMessageManager reportMessageManager,
|
||||
@Nonnull ExecutorService multiRecipientMessageExecutor,
|
||||
Scheduler messageDeliveryScheduler,
|
||||
@Nonnull ReportSpamTokenProvider reportSpamTokenProvider) {
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.messageSender = messageSender;
|
||||
@@ -164,6 +166,7 @@ public class MessageController {
|
||||
this.pushNotificationManager = pushNotificationManager;
|
||||
this.reportMessageManager = reportMessageManager;
|
||||
this.multiRecipientMessageExecutor = Objects.requireNonNull(multiRecipientMessageExecutor);
|
||||
this.messageDeliveryScheduler = messageDeliveryScheduler;
|
||||
this.reportSpamTokenProvider = reportSpamTokenProvider;
|
||||
}
|
||||
|
||||
@@ -553,7 +556,7 @@ public class MessageController {
|
||||
return messages;
|
||||
})
|
||||
.timeout(Duration.ofSeconds(5))
|
||||
.subscribeOn(Schedulers.boundedElastic())
|
||||
.subscribeOn(messageDeliveryScheduler)
|
||||
.toFuture();
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -102,7 +102,8 @@ public class RegistrationController {
|
||||
|
||||
if (existingAccount.isPresent()) {
|
||||
registrationLockVerificationManager.verifyRegistrationLock(existingAccount.get(),
|
||||
registrationRequest.accountAttributes().getRegistrationLock());
|
||||
registrationRequest.accountAttributes().getRegistrationLock(),
|
||||
userAgent, RegistrationLockVerificationManager.Flow.REGISTRATION, verificationType);
|
||||
}
|
||||
|
||||
if (!registrationRequest.skipDeviceTransfer() && existingAccount.map(Account::isTransferSupported).orElse(false)) {
|
||||
|
||||
+10
-1
@@ -11,6 +11,7 @@ import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.NotFoundException;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
@@ -27,13 +28,18 @@ public class SecureValueRecovery2Controller {
|
||||
return ExternalServiceCredentialsGenerator
|
||||
.builder(cfg.userAuthenticationTokenSharedSecret())
|
||||
.withUserDerivationKey(cfg.userIdTokenSharedSecret())
|
||||
.prependUsername(false)
|
||||
.withTruncateLength(16)
|
||||
.build();
|
||||
}
|
||||
|
||||
private final ExternalServiceCredentialsGenerator backupServiceCredentialGenerator;
|
||||
private final boolean enabled;
|
||||
|
||||
public SecureValueRecovery2Controller(final ExternalServiceCredentialsGenerator backupServiceCredentialGenerator) {
|
||||
public SecureValueRecovery2Controller(final ExternalServiceCredentialsGenerator backupServiceCredentialGenerator,
|
||||
final SecureValueRecovery2Configuration cfg) {
|
||||
this.backupServiceCredentialGenerator = backupServiceCredentialGenerator;
|
||||
this.enabled = cfg.enabled();
|
||||
}
|
||||
|
||||
@Timed
|
||||
@@ -50,6 +56,9 @@ public class SecureValueRecovery2Controller {
|
||||
@ApiResponse(responseCode = "200", description = "`JSON` with generated credentials.", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
public ExternalServiceCredentials getAuth(@Auth final AuthenticatedAccount auth) {
|
||||
if (!enabled) {
|
||||
throw new NotFoundException();
|
||||
}
|
||||
return backupServiceCredentialGenerator.generateFor(auth.getAccount().getUuid().toString());
|
||||
}
|
||||
}
|
||||
+20
-9
@@ -75,7 +75,10 @@ import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
|
||||
import org.whispersystems.textsecuregcm.registration.RegistrationServiceException;
|
||||
import org.whispersystems.textsecuregcm.registration.RegistrationServiceSenderException;
|
||||
import org.whispersystems.textsecuregcm.registration.VerificationSession;
|
||||
import org.whispersystems.textsecuregcm.spam.Extract;
|
||||
import org.whispersystems.textsecuregcm.spam.FilterSpam;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.spam.ScoreThreshold;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
@@ -88,7 +91,6 @@ import org.whispersystems.textsecuregcm.util.Util;
|
||||
public class VerificationController {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(VerificationController.class);
|
||||
|
||||
private static final Duration REGISTRATION_RPC_TIMEOUT = Duration.ofSeconds(15);
|
||||
private static final Duration DYNAMODB_TIMEOUT = Duration.ofSeconds(5);
|
||||
|
||||
@@ -112,6 +114,7 @@ public class VerificationController {
|
||||
private final RegistrationCaptchaManager registrationCaptchaManager;
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final AccountsManager accountsManager;
|
||||
|
||||
private final Clock clock;
|
||||
|
||||
@@ -119,7 +122,9 @@ public class VerificationController {
|
||||
final VerificationSessionManager verificationSessionManager,
|
||||
final PushNotificationManager pushNotificationManager,
|
||||
final RegistrationCaptchaManager registrationCaptchaManager,
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager, final RateLimiters rateLimiters,
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
|
||||
final RateLimiters rateLimiters,
|
||||
final AccountsManager accountsManager,
|
||||
final Clock clock) {
|
||||
this.registrationServiceClient = registrationServiceClient;
|
||||
this.verificationSessionManager = verificationSessionManager;
|
||||
@@ -127,6 +132,7 @@ public class VerificationController {
|
||||
this.registrationCaptchaManager = registrationCaptchaManager;
|
||||
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.accountsManager = accountsManager;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@@ -151,6 +157,7 @@ public class VerificationController {
|
||||
final RegistrationServiceSession registrationServiceSession;
|
||||
try {
|
||||
registrationServiceSession = registrationServiceClient.createRegistrationSessionSession(phoneNumber,
|
||||
accountsManager.getByE164(request.getNumber()).isPresent(),
|
||||
REGISTRATION_RPC_TIMEOUT).join();
|
||||
} catch (final CancellationException e) {
|
||||
|
||||
@@ -189,7 +196,8 @@ public class VerificationController {
|
||||
public VerificationSessionResponse updateSession(@PathParam("sessionId") final String encodedSessionId,
|
||||
@HeaderParam(com.google.common.net.HttpHeaders.X_FORWARDED_FOR) String forwardedFor,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@NotNull @Valid final UpdateVerificationSessionRequest updateVerificationSessionRequest) {
|
||||
@NotNull @Valid final UpdateVerificationSessionRequest updateVerificationSessionRequest,
|
||||
@NotNull @Extract final ScoreThreshold captchaScoreThreshold) {
|
||||
|
||||
final String sourceHost = HeaderUtils.getMostRecentProxy(forwardedFor).orElseThrow();
|
||||
|
||||
@@ -207,7 +215,7 @@ public class VerificationController {
|
||||
verificationSession);
|
||||
|
||||
verificationSession = handleCaptcha(sourceHost, updateVerificationSessionRequest, registrationServiceSession,
|
||||
verificationSession, userAgent);
|
||||
verificationSession, userAgent, captchaScoreThreshold.getScoreThreshold());
|
||||
} catch (final RateLimitExceededException e) {
|
||||
|
||||
final Response response = buildResponseForRateLimitExceeded(verificationSession, registrationServiceSession,
|
||||
@@ -345,11 +353,13 @@ public class VerificationController {
|
||||
* @throws ForbiddenException if assessment is not valid.
|
||||
* @throws RateLimitExceededException if too many captchas have been submitted
|
||||
*/
|
||||
private VerificationSession handleCaptcha(final String sourceHost,
|
||||
private VerificationSession handleCaptcha(
|
||||
final String sourceHost,
|
||||
final UpdateVerificationSessionRequest updateVerificationSessionRequest,
|
||||
final RegistrationServiceSession registrationServiceSession,
|
||||
VerificationSession verificationSession,
|
||||
final String userAgent) throws RateLimitExceededException {
|
||||
final String userAgent,
|
||||
final Optional<Float> captchaScoreThreshold) throws RateLimitExceededException {
|
||||
|
||||
if (updateVerificationSessionRequest.captcha() == null) {
|
||||
return verificationSession;
|
||||
@@ -360,23 +370,24 @@ public class VerificationController {
|
||||
|
||||
final AssessmentResult assessmentResult;
|
||||
try {
|
||||
|
||||
assessmentResult = registrationCaptchaManager.assessCaptcha(
|
||||
Optional.of(updateVerificationSessionRequest.captcha()), sourceHost)
|
||||
.orElseThrow(() -> new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR));
|
||||
|
||||
Metrics.counter(CAPTCHA_ATTEMPT_COUNTER_NAME, Tags.of(
|
||||
Tag.of(SUCCESS_TAG_NAME, String.valueOf(assessmentResult.valid())),
|
||||
Tag.of(SUCCESS_TAG_NAME, String.valueOf(assessmentResult.isValid(captchaScoreThreshold))),
|
||||
UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(COUNTRY_CODE_TAG_NAME, Util.getCountryCode(registrationServiceSession.number())),
|
||||
Tag.of(REGION_CODE_TAG_NAME, Util.getRegion(registrationServiceSession.number())),
|
||||
Tag.of(SCORE_TAG_NAME, assessmentResult.score())))
|
||||
Tag.of(SCORE_TAG_NAME, assessmentResult.getScoreString())))
|
||||
.increment();
|
||||
|
||||
} catch (IOException e) {
|
||||
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE);
|
||||
}
|
||||
|
||||
if (assessmentResult.valid()) {
|
||||
if (assessmentResult.isValid(captchaScoreThreshold)) {
|
||||
final List<VerificationSession.Information> submittedInformation = new ArrayList<>(
|
||||
verificationSession.submittedInformation());
|
||||
submittedInformation.add(VerificationSession.Information.CAPTCHA);
|
||||
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import com.fasterxml.jackson.datatype.jsr310.ser.InstantSerializer;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
|
||||
public record AccountDataReportResponse(UUID reportId,
|
||||
@JsonSerialize(using = InstantSerializer.class)
|
||||
@JsonFormat(pattern = DATE_FORMAT, timezone = UTC)
|
||||
Instant reportTimestamp,
|
||||
AccountAndDevicesDataReport data) {
|
||||
|
||||
private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
|
||||
private static final String UTC = "Etc/UTC";
|
||||
|
||||
@JsonProperty
|
||||
@Schema(description = "A plaintext representation of the data report")
|
||||
String text() {
|
||||
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
|
||||
// header
|
||||
builder.append(String.format("""
|
||||
Report ID: %s
|
||||
Report timestamp: %s
|
||||
|
||||
""",
|
||||
reportId,
|
||||
reportTimestamp.truncatedTo(ChronoUnit.SECONDS)));
|
||||
|
||||
// account
|
||||
builder.append(String.format("""
|
||||
# Account
|
||||
Phone number: %s
|
||||
Allow sealed sender from anyone: %s
|
||||
Find account by phone number: %s
|
||||
""",
|
||||
data.account.phoneNumber(),
|
||||
data.account.allowSealedSenderFromAnyone(),
|
||||
data.account.findAccountByPhoneNumber()));
|
||||
|
||||
// badges
|
||||
builder.append("Badges:");
|
||||
|
||||
if (data.account.badges().isEmpty()) {
|
||||
builder.append(" None\n");
|
||||
} else {
|
||||
builder.append("\n");
|
||||
data.account.badges().forEach(badgeDataReport -> builder.append(String.format("""
|
||||
- ID: %s
|
||||
Expiration: %s
|
||||
Visible: %s
|
||||
""",
|
||||
badgeDataReport.id(),
|
||||
badgeDataReport.expiration().truncatedTo(ChronoUnit.SECONDS),
|
||||
badgeDataReport.visible())));
|
||||
}
|
||||
|
||||
// devices
|
||||
builder.append("\n# Devices\n");
|
||||
|
||||
data.devices().forEach(deviceDataReport ->
|
||||
builder.append(String.format("""
|
||||
- ID: %s
|
||||
Created: %s
|
||||
Last seen: %s
|
||||
User-agent: %s
|
||||
""",
|
||||
deviceDataReport.id(),
|
||||
deviceDataReport.created().truncatedTo(ChronoUnit.SECONDS),
|
||||
deviceDataReport.lastSeen().truncatedTo(ChronoUnit.SECONDS),
|
||||
deviceDataReport.userAgent())));
|
||||
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
|
||||
public record AccountAndDevicesDataReport(AccountDataReport account,
|
||||
List<DeviceDataReport> devices) {
|
||||
|
||||
}
|
||||
|
||||
public record AccountDataReport(String phoneNumber, List<BadgeDataReport> badges, boolean allowSealedSenderFromAnyone,
|
||||
boolean findAccountByPhoneNumber) {
|
||||
|
||||
}
|
||||
|
||||
public record DeviceDataReport(long id,
|
||||
@JsonFormat(pattern = DATE_FORMAT, timezone = UTC)
|
||||
Instant lastSeen,
|
||||
@JsonFormat(pattern = DATE_FORMAT, timezone = UTC)
|
||||
Instant created,
|
||||
@Nullable String userAgent) {
|
||||
|
||||
|
||||
}
|
||||
|
||||
public record BadgeDataReport(String id,
|
||||
@JsonFormat(pattern = DATE_FORMAT, timezone = UTC)
|
||||
Instant expiration,
|
||||
boolean visible) {
|
||||
|
||||
public BadgeDataReport(AccountBadge badge) {
|
||||
this(badge.getId(), badge.getExpiration(), badge.isVisible());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+5
@@ -5,12 +5,17 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayBase64UrlAdapter;
|
||||
import java.util.UUID;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
public record AccountIdentityResponse(UUID uuid,
|
||||
String number,
|
||||
UUID pni,
|
||||
@JsonSerialize(using = ByteArrayBase64UrlAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64UrlAdapter.Deserializing.class)
|
||||
@Nullable byte[] usernameHash,
|
||||
boolean storageCapable) {
|
||||
}
|
||||
+23
-5
@@ -7,7 +7,11 @@ package org.whispersystems.textsecuregcm.limits;
|
||||
|
||||
import static java.util.Objects.requireNonNull;
|
||||
|
||||
import io.lettuce.core.ScriptOutputType;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.time.Clock;
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
@@ -17,6 +21,7 @@ import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
|
||||
@@ -33,12 +38,14 @@ public abstract class BaseRateLimiters<T extends RateLimiterDescriptor> {
|
||||
final T[] values,
|
||||
final Map<String, RateLimiterConfig> configs,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final FaultTolerantRedisCluster cacheCluster) {
|
||||
final ClusterLuaScript validateScript,
|
||||
final FaultTolerantRedisCluster cacheCluster,
|
||||
final Clock clock) {
|
||||
this.configs = configs;
|
||||
this.rateLimiterByDescriptor = Arrays.stream(values)
|
||||
.map(descriptor -> Pair.of(
|
||||
descriptor,
|
||||
createForDescriptor(descriptor, configs, dynamicConfigurationManager, cacheCluster)))
|
||||
createForDescriptor(descriptor, configs, dynamicConfigurationManager, validateScript, cacheCluster, clock)))
|
||||
.collect(Collectors.toUnmodifiableMap(Pair::getKey, Pair::getValue));
|
||||
}
|
||||
|
||||
@@ -62,11 +69,22 @@ public abstract class BaseRateLimiters<T extends RateLimiterDescriptor> {
|
||||
}
|
||||
}
|
||||
|
||||
protected static ClusterLuaScript defaultScript(final FaultTolerantRedisCluster cacheCluster) {
|
||||
try {
|
||||
return ClusterLuaScript.fromResource(
|
||||
cacheCluster, "lua/validate_rate_limit.lua", ScriptOutputType.INTEGER);
|
||||
} catch (final IOException e) {
|
||||
throw new UncheckedIOException("Failed to load rate limit validation script", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static RateLimiter createForDescriptor(
|
||||
final RateLimiterDescriptor descriptor,
|
||||
final Map<String, RateLimiterConfig> configs,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final FaultTolerantRedisCluster cacheCluster) {
|
||||
final ClusterLuaScript validateScript,
|
||||
final FaultTolerantRedisCluster cacheCluster,
|
||||
final Clock clock) {
|
||||
if (descriptor.isDynamic()) {
|
||||
final Supplier<RateLimiterConfig> configResolver = () -> {
|
||||
final RateLimiterConfig config = dynamicConfigurationManager.getConfiguration().getLimits().get(descriptor.id());
|
||||
@@ -74,9 +92,9 @@ public abstract class BaseRateLimiters<T extends RateLimiterDescriptor> {
|
||||
? config
|
||||
: configs.getOrDefault(descriptor.id(), descriptor.defaultConfig());
|
||||
};
|
||||
return new DynamicRateLimiter(descriptor.id(), configResolver, cacheCluster);
|
||||
return new DynamicRateLimiter(descriptor.id(), configResolver, validateScript, cacheCluster, clock);
|
||||
}
|
||||
final RateLimiterConfig cfg = configs.getOrDefault(descriptor.id(), descriptor.defaultConfig());
|
||||
return new StaticRateLimiter(descriptor.id(), cfg, cacheCluster);
|
||||
return new StaticRateLimiter(descriptor.id(), cfg, validateScript, cacheCluster, clock);
|
||||
}
|
||||
}
|
||||
+28
-2
@@ -7,10 +7,13 @@ package org.whispersystems.textsecuregcm.limits;
|
||||
|
||||
import static java.util.Objects.requireNonNull;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Supplier;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
|
||||
public class DynamicRateLimiter implements RateLimiter {
|
||||
@@ -19,18 +22,26 @@ public class DynamicRateLimiter implements RateLimiter {
|
||||
|
||||
private final Supplier<RateLimiterConfig> configResolver;
|
||||
|
||||
private final ClusterLuaScript validateScript;
|
||||
|
||||
private final FaultTolerantRedisCluster cluster;
|
||||
|
||||
private final Clock clock;
|
||||
|
||||
private final AtomicReference<Pair<RateLimiterConfig, RateLimiter>> currentHolder = new AtomicReference<>();
|
||||
|
||||
|
||||
public DynamicRateLimiter(
|
||||
final String name,
|
||||
final Supplier<RateLimiterConfig> configResolver,
|
||||
final FaultTolerantRedisCluster cluster) {
|
||||
final ClusterLuaScript validateScript,
|
||||
final FaultTolerantRedisCluster cluster,
|
||||
final Clock clock) {
|
||||
this.name = requireNonNull(name);
|
||||
this.configResolver = requireNonNull(configResolver);
|
||||
this.validateScript = requireNonNull(validateScript);
|
||||
this.cluster = requireNonNull(cluster);
|
||||
this.clock = requireNonNull(clock);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -38,16 +49,31 @@ public class DynamicRateLimiter implements RateLimiter {
|
||||
current().getRight().validate(key, amount);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletionStage<Void> validateAsync(final String key, final int amount) {
|
||||
return current().getRight().validateAsync(key, amount);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasAvailablePermits(final String key, final int permits) {
|
||||
return current().getRight().hasAvailablePermits(key, permits);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletionStage<Boolean> hasAvailablePermitsAsync(final String key, final int amount) {
|
||||
return current().getRight().hasAvailablePermitsAsync(key, amount);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear(final String key) {
|
||||
current().getRight().clear(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletionStage<Void> clearAsync(final String key) {
|
||||
return current().getRight().clearAsync(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public RateLimiterConfig config() {
|
||||
return current().getLeft();
|
||||
@@ -57,7 +83,7 @@ public class DynamicRateLimiter implements RateLimiter {
|
||||
final RateLimiterConfig cfg = configResolver.get();
|
||||
return currentHolder.updateAndGet(p -> p != null && p.getLeft().equals(cfg)
|
||||
? p
|
||||
: Pair.of(cfg, new StaticRateLimiter(name, cfg, cluster))
|
||||
: Pair.of(cfg, new StaticRateLimiter(name, cfg, validateScript, cluster, clock))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.limits;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
|
||||
public class LeakyBucket {
|
||||
|
||||
private final int bucketSize;
|
||||
private final double leakRatePerMillis;
|
||||
|
||||
private int spaceRemaining;
|
||||
private long lastUpdateTimeMillis;
|
||||
|
||||
public LeakyBucket(int bucketSize, double leakRatePerMillis) {
|
||||
this(bucketSize, leakRatePerMillis, bucketSize, System.currentTimeMillis());
|
||||
}
|
||||
|
||||
private LeakyBucket(int bucketSize, double leakRatePerMillis, int spaceRemaining, long lastUpdateTimeMillis) {
|
||||
this.bucketSize = bucketSize;
|
||||
this.leakRatePerMillis = leakRatePerMillis;
|
||||
this.spaceRemaining = spaceRemaining;
|
||||
this.lastUpdateTimeMillis = lastUpdateTimeMillis;
|
||||
}
|
||||
|
||||
public boolean add(int amount) {
|
||||
this.spaceRemaining = getUpdatedSpaceRemaining();
|
||||
this.lastUpdateTimeMillis = System.currentTimeMillis();
|
||||
|
||||
if (this.spaceRemaining >= amount) {
|
||||
this.spaceRemaining -= amount;
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private int getUpdatedSpaceRemaining() {
|
||||
long elapsedTime = System.currentTimeMillis() - this.lastUpdateTimeMillis;
|
||||
|
||||
return Math.min(this.bucketSize,
|
||||
(int)Math.floor(this.spaceRemaining + (elapsedTime * this.leakRatePerMillis)));
|
||||
}
|
||||
|
||||
public Duration getTimeUntilSpaceAvailable(int amount) {
|
||||
int currentSpaceRemaining = getUpdatedSpaceRemaining();
|
||||
if (currentSpaceRemaining >= amount) {
|
||||
return Duration.ZERO;
|
||||
} else if (amount > this.bucketSize) {
|
||||
// This shouldn't happen today but if so we should bubble this to the clients somehow
|
||||
throw new IllegalArgumentException("Requested permits exceed maximum bucket size");
|
||||
} else {
|
||||
return Duration.ofMillis((long)Math.ceil((double)(amount - currentSpaceRemaining) / this.leakRatePerMillis));
|
||||
}
|
||||
}
|
||||
|
||||
public String serialize(ObjectMapper mapper) throws JsonProcessingException {
|
||||
return mapper.writeValueAsString(new LeakyBucketEntity(bucketSize, leakRatePerMillis, spaceRemaining, lastUpdateTimeMillis));
|
||||
}
|
||||
|
||||
public static LeakyBucket fromSerialized(ObjectMapper mapper, String serialized) throws IOException {
|
||||
LeakyBucketEntity entity = mapper.readValue(serialized, LeakyBucketEntity.class);
|
||||
|
||||
return new LeakyBucket(entity.bucketSize, entity.leakRatePerMillis,
|
||||
entity.spaceRemaining, entity.lastUpdateTimeMillis);
|
||||
}
|
||||
|
||||
private static class LeakyBucketEntity {
|
||||
@JsonProperty
|
||||
private int bucketSize;
|
||||
|
||||
@JsonProperty
|
||||
private double leakRatePerMillis;
|
||||
|
||||
@JsonProperty
|
||||
private int spaceRemaining;
|
||||
|
||||
@JsonProperty
|
||||
private long lastUpdateTimeMillis;
|
||||
|
||||
public LeakyBucketEntity() {}
|
||||
|
||||
private LeakyBucketEntity(int bucketSize, double leakRatePerMillis,
|
||||
int spaceRemaining, long lastUpdateTimeMillis)
|
||||
{
|
||||
this.bucketSize = bucketSize;
|
||||
this.leakRatePerMillis = leakRatePerMillis;
|
||||
this.spaceRemaining = spaceRemaining;
|
||||
this.lastUpdateTimeMillis = lastUpdateTimeMillis;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.limits;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.lettuce.core.SetArgs;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Duration;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
|
||||
public class LockingRateLimiter extends StaticRateLimiter {
|
||||
|
||||
private static final RateLimitExceededException REUSABLE_RATE_LIMIT_EXCEEDED_EXCEPTION
|
||||
= new RateLimitExceededException(Duration.ZERO, true);
|
||||
|
||||
private final Counter counter;
|
||||
|
||||
|
||||
public LockingRateLimiter(
|
||||
final String name,
|
||||
final RateLimiterConfig config,
|
||||
final FaultTolerantRedisCluster cacheCluster) {
|
||||
super(name, config, cacheCluster);
|
||||
this.counter = Metrics.counter(name(getClass(), "locked"), "name", name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validate(final String key, final int amount) throws RateLimitExceededException {
|
||||
if (!acquireLock(key)) {
|
||||
counter.increment();
|
||||
throw REUSABLE_RATE_LIMIT_EXCEEDED_EXCEPTION;
|
||||
}
|
||||
|
||||
try {
|
||||
super.validate(key, amount);
|
||||
} finally {
|
||||
releaseLock(key);
|
||||
}
|
||||
}
|
||||
|
||||
private void releaseLock(final String key) {
|
||||
cacheCluster.useCluster(connection -> connection.sync().del(getLockName(key)));
|
||||
}
|
||||
|
||||
private boolean acquireLock(final String key) {
|
||||
return cacheCluster.withCluster(connection -> connection.sync().set(getLockName(key), "L", SetArgs.Builder.nx().ex(10))) != null;
|
||||
}
|
||||
|
||||
private String getLockName(final String key) {
|
||||
return "leaky_lock::" + name + "::" + key;
|
||||
}
|
||||
}
|
||||
+4
-2
@@ -14,6 +14,7 @@ import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import org.whispersystems.textsecuregcm.captcha.Action;
|
||||
import org.whispersystems.textsecuregcm.captcha.CaptchaChecker;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
@@ -62,12 +63,12 @@ public class RateLimitChallengeManager {
|
||||
}
|
||||
}
|
||||
|
||||
public void answerRecaptchaChallenge(final Account account, final String captcha, final String mostRecentProxyIp, final String userAgent)
|
||||
public boolean answerRecaptchaChallenge(final Account account, final String captcha, final String mostRecentProxyIp, final String userAgent)
|
||||
throws RateLimitExceededException, IOException {
|
||||
|
||||
rateLimiters.getRecaptchaChallengeAttemptLimiter().validate(account.getUuid());
|
||||
|
||||
final boolean challengeSuccess = captchaChecker.verify(captcha, mostRecentProxyIp).valid();
|
||||
final boolean challengeSuccess = captchaChecker.verify(Action.CHALLENGE, captcha, mostRecentProxyIp).isValid();
|
||||
|
||||
final Tags tags = Tags.of(
|
||||
Tag.of(SOURCE_COUNTRY_TAG_NAME, Util.getCountryCode(account.getNumber())),
|
||||
@@ -81,6 +82,7 @@ public class RateLimitChallengeManager {
|
||||
rateLimiters.getRecaptchaChallengeSuccessLimiter().validate(account.getUuid());
|
||||
resetRateLimits(account);
|
||||
}
|
||||
return challengeSuccess;
|
||||
}
|
||||
|
||||
private void resetRateLimits(final Account account) throws RateLimitExceededException {
|
||||
|
||||
@@ -6,16 +6,23 @@
|
||||
package org.whispersystems.textsecuregcm.limits;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
|
||||
public interface RateLimiter {
|
||||
|
||||
void validate(String key, int amount) throws RateLimitExceededException;
|
||||
|
||||
CompletionStage<Void> validateAsync(String key, int amount);
|
||||
|
||||
boolean hasAvailablePermits(String key, int permits);
|
||||
|
||||
CompletionStage<Boolean> hasAvailablePermitsAsync(String key, int amount);
|
||||
|
||||
void clear(String key);
|
||||
|
||||
CompletionStage<Void> clearAsync(String key);
|
||||
|
||||
RateLimiterConfig config();
|
||||
|
||||
default void validate(final String key) throws RateLimitExceededException {
|
||||
@@ -30,14 +37,34 @@ public interface RateLimiter {
|
||||
validate(srcAccountUuid.toString() + "__" + dstAccountUuid.toString());
|
||||
}
|
||||
|
||||
default CompletionStage<Void> validateAsync(final String key) {
|
||||
return validateAsync(key, 1);
|
||||
}
|
||||
|
||||
default CompletionStage<Void> validateAsync(final UUID accountUuid) {
|
||||
return validateAsync(accountUuid.toString());
|
||||
}
|
||||
|
||||
default CompletionStage<Void> validateAsync(final UUID srcAccountUuid, final UUID dstAccountUuid) {
|
||||
return validateAsync(srcAccountUuid.toString() + "__" + dstAccountUuid.toString());
|
||||
}
|
||||
|
||||
default boolean hasAvailablePermits(final UUID accountUuid, final int permits) {
|
||||
return hasAvailablePermits(accountUuid.toString(), permits);
|
||||
}
|
||||
|
||||
default CompletionStage<Boolean> hasAvailablePermitsAsync(final UUID accountUuid, final int permits) {
|
||||
return hasAvailablePermitsAsync(accountUuid.toString(), permits);
|
||||
}
|
||||
|
||||
default void clear(final UUID accountUuid) {
|
||||
clear(accountUuid.toString());
|
||||
}
|
||||
|
||||
default CompletionStage<Void> clearAsync(final UUID accountUuid) {
|
||||
return clearAsync(accountUuid.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* If the wrapped {@code validate()} call throws a {@link RateLimitExceededException}, it will adapt it to ensure that
|
||||
* {@link RateLimitExceededException#isLegacy()} returns {@code true}
|
||||
|
||||
@@ -6,8 +6,10 @@ package org.whispersystems.textsecuregcm.limits;
|
||||
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.time.Clock;
|
||||
import java.util.Map;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
|
||||
@@ -26,7 +28,7 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
|
||||
|
||||
SMS_VOICE_PREFIX("smsVoicePrefix", false, new RateLimiterConfig(1000, 1000)),
|
||||
|
||||
VERIFY("verify", false, new RateLimiterConfig(2, 2)),
|
||||
VERIFY("verify", false, new RateLimiterConfig(6, 2)),
|
||||
|
||||
PIN("pin", false, new RateLimiterConfig(10, 1 / (24.0 * 60.0))),
|
||||
|
||||
@@ -103,7 +105,8 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
|
||||
final Map<String, RateLimiterConfig> configs,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final FaultTolerantRedisCluster cacheCluster) {
|
||||
final RateLimiters rateLimiters = new RateLimiters(configs, dynamicConfigurationManager, cacheCluster);
|
||||
final RateLimiters rateLimiters = new RateLimiters(
|
||||
configs, dynamicConfigurationManager, defaultScript(cacheCluster), cacheCluster, Clock.systemUTC());
|
||||
rateLimiters.validateValuesAndConfigs();
|
||||
return rateLimiters;
|
||||
}
|
||||
@@ -112,8 +115,10 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
|
||||
RateLimiters(
|
||||
final Map<String, RateLimiterConfig> configs,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final FaultTolerantRedisCluster cacheCluster) {
|
||||
super(For.values(), configs, dynamicConfigurationManager, cacheCluster);
|
||||
final ClusterLuaScript validateScript,
|
||||
final FaultTolerantRedisCluster cacheCluster,
|
||||
final Clock clock) {
|
||||
super(For.values(), configs, dynamicConfigurationManager, validateScript, cacheCluster, clock);
|
||||
}
|
||||
|
||||
public RateLimiter getAllocateDeviceLimiter() {
|
||||
|
||||
+79
-43
@@ -5,60 +5,97 @@
|
||||
package org.whispersystems.textsecuregcm.limits;
|
||||
|
||||
import static java.util.Objects.requireNonNull;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
import static java.util.concurrent.CompletableFuture.completedFuture;
|
||||
import static java.util.concurrent.CompletableFuture.failedFuture;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.io.IOException;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
public class StaticRateLimiter implements RateLimiter {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(StaticRateLimiter.class);
|
||||
|
||||
protected final String name;
|
||||
|
||||
private final RateLimiterConfig config;
|
||||
|
||||
protected final FaultTolerantRedisCluster cacheCluster;
|
||||
|
||||
private final Counter counter;
|
||||
|
||||
private final ClusterLuaScript validateScript;
|
||||
|
||||
private final FaultTolerantRedisCluster cacheCluster;
|
||||
|
||||
private final Clock clock;
|
||||
|
||||
|
||||
public StaticRateLimiter(
|
||||
final String name,
|
||||
final RateLimiterConfig config,
|
||||
final FaultTolerantRedisCluster cacheCluster) {
|
||||
final ClusterLuaScript validateScript,
|
||||
final FaultTolerantRedisCluster cacheCluster,
|
||||
final Clock clock) {
|
||||
this.name = requireNonNull(name);
|
||||
this.config = requireNonNull(config);
|
||||
this.validateScript = requireNonNull(validateScript);
|
||||
this.cacheCluster = requireNonNull(cacheCluster);
|
||||
this.counter = Metrics.counter(name(getClass(), "exceeded"), "name", name);
|
||||
this.clock = requireNonNull(clock);
|
||||
this.counter = Metrics.counter(MetricsUtil.name(getClass(), "exceeded"), "name", name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validate(final String key, final int amount) throws RateLimitExceededException {
|
||||
final LeakyBucket bucket = getBucket(key);
|
||||
if (bucket.add(amount)) {
|
||||
setBucket(key, bucket);
|
||||
} else {
|
||||
final long deficitPermitsAmount = executeValidateScript(key, amount, true);
|
||||
if (deficitPermitsAmount > 0) {
|
||||
counter.increment();
|
||||
throw new RateLimitExceededException(bucket.getTimeUntilSpaceAvailable(amount), true);
|
||||
final Duration retryAfter = Duration.ofMillis(
|
||||
(long) Math.ceil((double) deficitPermitsAmount / config.leakRatePerMillis()));
|
||||
throw new RateLimitExceededException(retryAfter, true);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasAvailablePermits(final String key, final int permits) {
|
||||
return getBucket(key).getTimeUntilSpaceAvailable(permits).equals(Duration.ZERO);
|
||||
public CompletionStage<Void> validateAsync(final String key, final int amount) {
|
||||
return executeValidateScriptAsync(key, amount, true)
|
||||
.thenCompose(deficitPermitsAmount -> {
|
||||
if (deficitPermitsAmount == 0) {
|
||||
return completedFuture(null);
|
||||
}
|
||||
counter.increment();
|
||||
final Duration retryAfter = Duration.ofMillis(
|
||||
(long) Math.ceil((double) deficitPermitsAmount / config.leakRatePerMillis()));
|
||||
return failedFuture(new RateLimitExceededException(retryAfter, true));
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasAvailablePermits(final String key, final int amount) {
|
||||
final long deficitPermitsAmount = executeValidateScript(key, amount, false);
|
||||
return deficitPermitsAmount == 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletionStage<Boolean> hasAvailablePermitsAsync(final String key, final int amount) {
|
||||
return executeValidateScriptAsync(key, amount, false)
|
||||
.thenApply(deficitPermitsAmount -> deficitPermitsAmount == 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear(final String key) {
|
||||
cacheCluster.useCluster(connection -> connection.sync().del(getBucketName(key)));
|
||||
cacheCluster.useCluster(connection -> connection.sync().del(bucketName(name, key)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletionStage<Void> clearAsync(final String key) {
|
||||
return cacheCluster.withCluster(connection -> connection.async().del(bucketName(name, key)))
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -66,33 +103,32 @@ public class StaticRateLimiter implements RateLimiter {
|
||||
return config;
|
||||
}
|
||||
|
||||
private void setBucket(final String key, final LeakyBucket bucket) {
|
||||
try {
|
||||
final String serialized = bucket.serialize(SystemMapper.jsonMapper());
|
||||
cacheCluster.useCluster(connection -> connection.sync().setex(
|
||||
getBucketName(key),
|
||||
(int) Math.ceil((config.bucketSize() / config.leakRatePerMillis()) / 1000),
|
||||
serialized));
|
||||
} catch (final JsonProcessingException e) {
|
||||
throw new IllegalArgumentException(e);
|
||||
}
|
||||
private long executeValidateScript(final String key, final int amount, final boolean applyChanges) {
|
||||
final List<String> keys = List.of(bucketName(name, key));
|
||||
final List<String> arguments = List.of(
|
||||
String.valueOf(config.bucketSize()),
|
||||
String.valueOf(config.leakRatePerMillis()),
|
||||
String.valueOf(clock.millis()),
|
||||
String.valueOf(amount),
|
||||
String.valueOf(applyChanges)
|
||||
);
|
||||
return (Long) validateScript.execute(keys, arguments);
|
||||
}
|
||||
|
||||
private LeakyBucket getBucket(final String key) {
|
||||
try {
|
||||
final String serialized = cacheCluster.withCluster(connection -> connection.sync().get(getBucketName(key)));
|
||||
|
||||
if (serialized != null) {
|
||||
return LeakyBucket.fromSerialized(SystemMapper.jsonMapper(), serialized);
|
||||
}
|
||||
} catch (final IOException e) {
|
||||
logger.warn("Deserialization error", e);
|
||||
}
|
||||
|
||||
return new LeakyBucket(config.bucketSize(), config.leakRatePerMillis());
|
||||
private CompletionStage<Long> executeValidateScriptAsync(final String key, final int amount, final boolean applyChanges) {
|
||||
final List<String> keys = List.of(bucketName(name, key));
|
||||
final List<String> arguments = List.of(
|
||||
String.valueOf(config.bucketSize()),
|
||||
String.valueOf(config.leakRatePerMillis()),
|
||||
String.valueOf(clock.millis()),
|
||||
String.valueOf(amount),
|
||||
String.valueOf(applyChanges)
|
||||
);
|
||||
return validateScript.executeAsync(keys, arguments).thenApply(o -> (Long) o);
|
||||
}
|
||||
|
||||
private String getBucketName(final String key) {
|
||||
@VisibleForTesting
|
||||
protected static String bucketName(final String name, final String key) {
|
||||
return "leaky_bucket::" + name + "::" + key;
|
||||
}
|
||||
}
|
||||
+7
-7
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
@@ -18,7 +18,6 @@ import io.lettuce.core.RedisFuture;
|
||||
import io.lettuce.core.ScriptOutputType;
|
||||
import io.lettuce.core.cluster.SlotHash;
|
||||
import io.lettuce.core.cluster.api.sync.RedisAdvancedClusterCommands;
|
||||
import io.lettuce.core.cluster.event.ClusterTopologyChangedEvent;
|
||||
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
|
||||
import io.lettuce.core.cluster.pubsub.RedisClusterPubSubAdapter;
|
||||
import java.io.IOException;
|
||||
@@ -86,8 +85,10 @@ public class ClientPresenceManager extends RedisClusterPubSubAdapter<String, Str
|
||||
final ExecutorService keyspaceNotificationExecutorService) throws IOException {
|
||||
this.presenceCluster = presenceCluster;
|
||||
this.pubSubConnection = this.presenceCluster.createPubSubConnection();
|
||||
this.clearPresenceScript = ClusterLuaScript.fromResource(presenceCluster, "lua/clear_presence.lua", ScriptOutputType.INTEGER);
|
||||
this.renewPresenceScript = ClusterLuaScript.fromResource(presenceCluster, "lua/renew_presence.lua", ScriptOutputType.VALUE);
|
||||
this.clearPresenceScript = ClusterLuaScript.fromResource(presenceCluster, "lua/clear_presence.lua",
|
||||
ScriptOutputType.INTEGER);
|
||||
this.renewPresenceScript = ClusterLuaScript.fromResource(presenceCluster, "lua/renew_presence.lua",
|
||||
ScriptOutputType.VALUE);
|
||||
this.scheduledExecutorService = scheduledExecutorService;
|
||||
this.keyspaceNotificationExecutorService = keyspaceNotificationExecutorService;
|
||||
|
||||
@@ -112,9 +113,6 @@ public class ClientPresenceManager extends RedisClusterPubSubAdapter<String, Str
|
||||
public void start() {
|
||||
pubSubConnection.usePubSubConnection(connection -> {
|
||||
connection.addListener(this);
|
||||
connection.getResources().eventBus().get()
|
||||
.filter(event -> event instanceof ClusterTopologyChangedEvent)
|
||||
.subscribe(event -> resubscribeAll());
|
||||
|
||||
final String presenceChannel = getManagerPresenceChannel(managerId);
|
||||
final int slot = SlotHash.getSlot(presenceChannel);
|
||||
@@ -124,6 +122,8 @@ public class ClientPresenceManager extends RedisClusterPubSubAdapter<String, Str
|
||||
.subscribe(presenceChannel);
|
||||
});
|
||||
|
||||
pubSubConnection.subscribeToClusterTopologyChangedEvents(this::resubscribeAll);
|
||||
|
||||
presenceCluster.useCluster(connection -> connection.sync().sadd(MANAGER_SET_KEY, managerId));
|
||||
|
||||
pruneMissingPeersFuture = scheduledExecutorService.scheduleWithFixedDelay(() -> {
|
||||
|
||||
@@ -7,6 +7,8 @@ package org.whispersystems.textsecuregcm.push;
|
||||
|
||||
import com.codahale.metrics.InstrumentedExecutorService;
|
||||
import com.codahale.metrics.SharedMetricRegistries;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.binder.jvm.ExecutorServiceMetrics;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import org.slf4j.Logger;
|
||||
@@ -29,9 +31,13 @@ public class ReceiptSender {
|
||||
final ExecutorService executor) {
|
||||
this.accountManager = accountManager;
|
||||
this.messageSender = messageSender;
|
||||
this.executor = new InstrumentedExecutorService(executor,
|
||||
SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME),
|
||||
MetricsUtil.name(ReceiptSender.class, "executor"));
|
||||
this.executor = ExecutorServiceMetrics.monitor(
|
||||
Metrics.globalRegistry,
|
||||
new InstrumentedExecutorService(executor,
|
||||
SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME),
|
||||
MetricsUtil.name(ReceiptSender.class, "executor")),
|
||||
MetricsUtil.name(ReceiptSender.class, "executor"))
|
||||
;
|
||||
}
|
||||
|
||||
public void sendReceipt(UUID sourceUuid, long sourceDeviceId, UUID destinationUuid, long messageId) {
|
||||
|
||||
+40
-6
@@ -10,28 +10,41 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
|
||||
import io.github.resilience4j.retry.Retry;
|
||||
import io.lettuce.core.RedisException;
|
||||
import io.lettuce.core.cluster.event.ClusterTopologyChangedEvent;
|
||||
import io.lettuce.core.cluster.pubsub.StatefulRedisClusterPubSubConnection;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.util.CircuitBreakerUtil;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
|
||||
public class FaultTolerantPubSubConnection<K, V> {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(FaultTolerantPubSubConnection.class);
|
||||
|
||||
|
||||
private final String name;
|
||||
private final StatefulRedisClusterPubSubConnection<K, V> pubSubConnection;
|
||||
|
||||
private final CircuitBreaker circuitBreaker;
|
||||
private final Retry retry;
|
||||
private final Retry resubscribeRetry;
|
||||
private final Scheduler topologyChangedEventScheduler;
|
||||
|
||||
private final Timer executeTimer;
|
||||
|
||||
public FaultTolerantPubSubConnection(final String name,
|
||||
final StatefulRedisClusterPubSubConnection<K, V> pubSubConnection, final CircuitBreaker circuitBreaker,
|
||||
final Retry retry) {
|
||||
final Retry retry, final Retry resubscribeRetry, final Scheduler topologyChangedEventScheduler) {
|
||||
this.name = name;
|
||||
this.pubSubConnection = pubSubConnection;
|
||||
this.circuitBreaker = circuitBreaker;
|
||||
this.retry = retry;
|
||||
this.resubscribeRetry = resubscribeRetry;
|
||||
this.topologyChangedEventScheduler = topologyChangedEventScheduler;
|
||||
|
||||
this.pubSubConnection.setNodeMessagePropagation(true);
|
||||
|
||||
@@ -58,11 +71,32 @@ public class FaultTolerantPubSubConnection<K, V> {
|
||||
return circuitBreaker.executeCheckedSupplier(
|
||||
() -> retry.executeCallable(() -> executeTimer.record(() -> function.apply(pubSubConnection))));
|
||||
} catch (final Throwable t) {
|
||||
if (t instanceof RedisException) {
|
||||
throw (RedisException) t;
|
||||
} else {
|
||||
throw new RedisException(t);
|
||||
}
|
||||
if (t instanceof RedisException) {
|
||||
throw (RedisException) t;
|
||||
} else {
|
||||
throw new RedisException(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void subscribeToClusterTopologyChangedEvents(final Runnable eventHandler) {
|
||||
|
||||
usePubSubConnection(connection -> connection.getResources().eventBus().get()
|
||||
.filter(event -> event instanceof ClusterTopologyChangedEvent)
|
||||
.subscribeOn(topologyChangedEventScheduler)
|
||||
.subscribe(event -> {
|
||||
logger.info("Got topology change event for {}, resubscribing all keyspace notifications", name);
|
||||
|
||||
resubscribeRetry.executeRunnable(() -> {
|
||||
try {
|
||||
eventHandler.run();
|
||||
} catch (final RuntimeException e) {
|
||||
logger.warn("Resubscribe for {} failed", name, e);
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
}
|
||||
+48
-34
@@ -7,9 +7,11 @@ package org.whispersystems.textsecuregcm.redis;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
|
||||
import io.github.resilience4j.core.IntervalFunction;
|
||||
import io.github.resilience4j.reactor.circuitbreaker.operator.CircuitBreakerOperator;
|
||||
import io.github.resilience4j.reactor.retry.RetryOperator;
|
||||
import io.github.resilience4j.retry.Retry;
|
||||
import io.github.resilience4j.retry.RetryConfig;
|
||||
import io.lettuce.core.ClientOptions.DisconnectedBehavior;
|
||||
import io.lettuce.core.RedisCommandTimeoutException;
|
||||
import io.lettuce.core.RedisException;
|
||||
@@ -31,6 +33,7 @@ import org.whispersystems.textsecuregcm.configuration.RedisClusterConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.util.CircuitBreakerUtil;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
|
||||
/**
|
||||
* A fault-tolerant access manager for a Redis cluster. A fault-tolerant Redis cluster provides managed,
|
||||
@@ -38,51 +41,61 @@ import reactor.core.publisher.Flux;
|
||||
*/
|
||||
public class FaultTolerantRedisCluster {
|
||||
|
||||
private final String name;
|
||||
private final String name;
|
||||
|
||||
private final RedisClusterClient clusterClient;
|
||||
private final RedisClusterClient clusterClient;
|
||||
|
||||
private final StatefulRedisClusterConnection<String, String> stringConnection;
|
||||
private final StatefulRedisClusterConnection<byte[], byte[]> binaryConnection;
|
||||
private final StatefulRedisClusterConnection<String, String> stringConnection;
|
||||
private final StatefulRedisClusterConnection<byte[], byte[]> binaryConnection;
|
||||
|
||||
private final List<StatefulRedisClusterPubSubConnection<?, ?>> pubSubConnections = new ArrayList<>();
|
||||
private final List<StatefulRedisClusterPubSubConnection<?, ?>> pubSubConnections = new ArrayList<>();
|
||||
|
||||
private final CircuitBreaker circuitBreaker;
|
||||
private final Retry retry;
|
||||
private final CircuitBreaker circuitBreaker;
|
||||
private final Retry retry;
|
||||
private final Retry topologyChangedEventRetry;
|
||||
|
||||
public FaultTolerantRedisCluster(final String name, final RedisClusterConfiguration clusterConfiguration, final ClientResources clientResources) {
|
||||
this(name,
|
||||
RedisClusterClient.create(clientResources, clusterConfiguration.getConfigurationUri()),
|
||||
clusterConfiguration.getTimeout(),
|
||||
clusterConfiguration.getCircuitBreakerConfiguration(),
|
||||
clusterConfiguration.getRetryConfiguration());
|
||||
}
|
||||
public FaultTolerantRedisCluster(final String name, final RedisClusterConfiguration clusterConfiguration,
|
||||
final ClientResources clientResources) {
|
||||
this(name,
|
||||
RedisClusterClient.create(clientResources, clusterConfiguration.getConfigurationUri()),
|
||||
clusterConfiguration.getTimeout(),
|
||||
clusterConfiguration.getCircuitBreakerConfiguration(),
|
||||
clusterConfiguration.getRetryConfiguration());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
FaultTolerantRedisCluster(final String name, final RedisClusterClient clusterClient, final Duration commandTimeout, final CircuitBreakerConfiguration circuitBreakerConfiguration, final RetryConfiguration retryConfiguration) {
|
||||
this.name = name;
|
||||
@VisibleForTesting
|
||||
FaultTolerantRedisCluster(final String name, final RedisClusterClient clusterClient, final Duration commandTimeout,
|
||||
final CircuitBreakerConfiguration circuitBreakerConfiguration, final RetryConfiguration retryConfiguration) {
|
||||
this.name = name;
|
||||
|
||||
this.clusterClient = clusterClient;
|
||||
this.clusterClient.setDefaultTimeout(commandTimeout);
|
||||
this.clusterClient.setOptions(ClusterClientOptions.builder()
|
||||
.disconnectedBehavior(DisconnectedBehavior.REJECT_COMMANDS)
|
||||
.validateClusterNodeMembership(false)
|
||||
.topologyRefreshOptions(ClusterTopologyRefreshOptions.builder()
|
||||
.enableAllAdaptiveRefreshTriggers()
|
||||
.build())
|
||||
.publishOnScheduler(true)
|
||||
.build());
|
||||
this.clusterClient = clusterClient;
|
||||
this.clusterClient.setDefaultTimeout(commandTimeout);
|
||||
this.clusterClient.setOptions(ClusterClientOptions.builder()
|
||||
.disconnectedBehavior(DisconnectedBehavior.REJECT_COMMANDS)
|
||||
.validateClusterNodeMembership(false)
|
||||
.topologyRefreshOptions(ClusterTopologyRefreshOptions.builder()
|
||||
.enableAllAdaptiveRefreshTriggers()
|
||||
.build())
|
||||
.publishOnScheduler(true)
|
||||
.build());
|
||||
|
||||
this.stringConnection = clusterClient.connect();
|
||||
this.binaryConnection = clusterClient.connect(ByteArrayCodec.INSTANCE);
|
||||
this.stringConnection = clusterClient.connect();
|
||||
this.binaryConnection = clusterClient.connect(ByteArrayCodec.INSTANCE);
|
||||
|
||||
this.circuitBreaker = CircuitBreaker.of(name + "-breaker", circuitBreakerConfiguration.toCircuitBreakerConfig());
|
||||
this.retry = Retry.of(name + "-retry", retryConfiguration.toRetryConfigBuilder()
|
||||
.retryOnException(exception -> exception instanceof RedisCommandTimeoutException).build());
|
||||
this.circuitBreaker = CircuitBreaker.of(name + "-breaker", circuitBreakerConfiguration.toCircuitBreakerConfig());
|
||||
this.retry = Retry.of(name + "-retry", retryConfiguration.toRetryConfigBuilder()
|
||||
.retryOnException(exception -> exception instanceof RedisCommandTimeoutException).build());
|
||||
final RetryConfig topologyChangedEventRetryConfig = RetryConfig.custom()
|
||||
.maxAttempts(Integer.MAX_VALUE)
|
||||
.intervalFunction(
|
||||
IntervalFunction.ofExponentialRandomBackoff(Duration.ofSeconds(1), 1.5, Duration.ofSeconds(30)))
|
||||
.build();
|
||||
|
||||
this.topologyChangedEventRetry = Retry.of(name + "-topologyChangedRetry", topologyChangedEventRetryConfig);
|
||||
|
||||
CircuitBreakerUtil.registerMetrics(circuitBreaker, FaultTolerantRedisCluster.class);
|
||||
CircuitBreakerUtil.registerMetrics(retry, FaultTolerantRedisCluster.class);
|
||||
}
|
||||
}
|
||||
|
||||
void shutdown() {
|
||||
stringConnection.close();
|
||||
@@ -158,6 +171,7 @@ public class FaultTolerantRedisCluster {
|
||||
final StatefulRedisClusterPubSubConnection<String, String> pubSubConnection = clusterClient.connectPubSub();
|
||||
pubSubConnections.add(pubSubConnection);
|
||||
|
||||
return new FaultTolerantPubSubConnection<>(name, pubSubConnection, circuitBreaker, retry);
|
||||
return new FaultTolerantPubSubConnection<>(name, pubSubConnection, circuitBreaker, retry, topologyChangedEventRetry,
|
||||
Schedulers.newSingle(name + "-redisPubSubEvents"));
|
||||
}
|
||||
}
|
||||
+29
-5
@@ -81,13 +81,14 @@ public class RegistrationServiceClient implements Managed {
|
||||
// The …Session suffix methods distinguish the new methods, which return Sessions, from the old.
|
||||
// Once the deprecated methods are removed, the names can be streamlined.
|
||||
public CompletableFuture<RegistrationServiceSession> createRegistrationSessionSession(
|
||||
final Phonenumber.PhoneNumber phoneNumber, final Duration timeout) {
|
||||
final Phonenumber.PhoneNumber phoneNumber, final boolean accountExistsWithPhoneNumber, final Duration timeout) {
|
||||
final long e164 = Long.parseLong(
|
||||
PhoneNumberUtil.getInstance().format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164).substring(1));
|
||||
|
||||
return toCompletableFuture(stub.withDeadline(toDeadline(timeout))
|
||||
.createSession(CreateRegistrationSessionRequest.newBuilder()
|
||||
.setE164(e164)
|
||||
.setAccountExistsWithE164(accountExistsWithPhoneNumber)
|
||||
.build()))
|
||||
.thenApply(response -> switch (response.getResponseCase()) {
|
||||
case SESSION_METADATA -> buildSessionResponseFromMetadata(response.getSessionMetadata());
|
||||
@@ -111,8 +112,8 @@ public class RegistrationServiceClient implements Managed {
|
||||
|
||||
@Deprecated
|
||||
public CompletableFuture<byte[]> createRegistrationSession(final Phonenumber.PhoneNumber phoneNumber,
|
||||
final Duration timeout) {
|
||||
return createRegistrationSessionSession(phoneNumber, timeout)
|
||||
final boolean accountExistsWithPhoneNumber, final Duration timeout) {
|
||||
return createRegistrationSessionSession(phoneNumber, accountExistsWithPhoneNumber, timeout)
|
||||
.thenApply(RegistrationServiceSession::id);
|
||||
}
|
||||
|
||||
@@ -181,8 +182,31 @@ public class RegistrationServiceClient implements Managed {
|
||||
final String verificationCode,
|
||||
final Duration timeout) {
|
||||
|
||||
return checkVerificationCodeSession(sessionId, verificationCode, timeout)
|
||||
.thenApply(RegistrationServiceSession::verified);
|
||||
return toCompletableFuture(stub.withDeadline(toDeadline(timeout))
|
||||
.legacyCheckVerificationCode(CheckVerificationCodeRequest.newBuilder()
|
||||
.setSessionId(ByteString.copyFrom(sessionId))
|
||||
.setVerificationCode(verificationCode)
|
||||
.build()))
|
||||
.thenApply(response -> {
|
||||
if (response.hasError()) {
|
||||
switch (response.getError().getErrorType()) {
|
||||
case CHECK_VERIFICATION_CODE_ERROR_TYPE_RATE_LIMITED ->
|
||||
throw new CompletionException(new RateLimitExceededException(response.getError().getMayRetry()
|
||||
? Duration.ofSeconds(response.getError().getRetryAfterSeconds())
|
||||
: null, true));
|
||||
|
||||
case CHECK_VERIFICATION_CODE_ERROR_TYPE_NO_CODE_SENT,
|
||||
CHECK_VERIFICATION_CODE_ERROR_TYPE_ATTEMPT_EXPIRED,
|
||||
CHECK_VERIFICATION_CODE_ERROR_TYPE_SESSION_NOT_FOUND ->
|
||||
throw new CompletionException(new RegistrationServiceException(null));
|
||||
|
||||
default -> throw new CompletionException(
|
||||
new RuntimeException("Failed to check verification code: " + response.getError().getErrorType()));
|
||||
}
|
||||
} else {
|
||||
return response.getVerified();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public CompletableFuture<RegistrationServiceSession> checkVerificationCodeSession(final byte[] sessionId,
|
||||
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.securevaluerecovery;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.util.HeaderUtils.basicAuthHeader;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.time.Duration;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureValueRecovery2Configuration;
|
||||
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.
|
||||
*/
|
||||
public class SecureValueRecovery2Client {
|
||||
|
||||
private final ExternalServiceCredentialsGenerator secureValueRecoveryCredentialsGenerator;
|
||||
private final URI deleteUri;
|
||||
private final FaultTolerantHttpClient httpClient;
|
||||
private final boolean enabled;
|
||||
|
||||
@VisibleForTesting
|
||||
static final String DELETE_PATH = "/v1/delete";
|
||||
|
||||
public SecureValueRecovery2Client(final ExternalServiceCredentialsGenerator secureValueRecoveryCredentialsGenerator,
|
||||
final Executor executor, final SecureValueRecovery2Configuration configuration)
|
||||
throws CertificateException {
|
||||
this.secureValueRecoveryCredentialsGenerator = secureValueRecoveryCredentialsGenerator;
|
||||
this.deleteUri = URI.create(configuration.uri()).resolve(DELETE_PATH);
|
||||
this.httpClient = FaultTolerantHttpClient.newBuilder()
|
||||
.withCircuitBreaker(configuration.circuitBreaker())
|
||||
.withRetry(configuration.retry())
|
||||
.withVersion(HttpClient.Version.HTTP_1_1)
|
||||
.withConnectTimeout(Duration.ofSeconds(10))
|
||||
.withRedirect(HttpClient.Redirect.NEVER)
|
||||
.withExecutor(executor)
|
||||
.withName("secure-value-recovery")
|
||||
.withSecurityProtocol(FaultTolerantHttpClient.SECURITY_PROTOCOL_TLS_1_2)
|
||||
.withTrustedServerCertificates(configuration.svrCaCertificates().toArray(new String[0]))
|
||||
.build();
|
||||
this.enabled = configuration.enabled();
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> deleteBackups(final UUID accountUuid) {
|
||||
|
||||
if (!enabled) {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
|
||||
final ExternalServiceCredentials credentials = secureValueRecoveryCredentialsGenerator.generateForUuid(accountUuid);
|
||||
|
||||
final HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(deleteUri)
|
||||
.DELETE()
|
||||
.header(HttpHeaders.AUTHORIZATION, basicAuthHeader(credentials))
|
||||
.build();
|
||||
|
||||
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString()).thenApply(response -> {
|
||||
if (HttpUtils.isSuccessfulResponse(response.statusCode())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
throw new SecureValueRecoveryException("Failed to delete backup: " + response.statusCode());
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.securevaluerecovery;
|
||||
|
||||
public class SecureValueRecoveryException extends RuntimeException {
|
||||
|
||||
public SecureValueRecoveryException(final String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.spam;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* Indicates that a parameter should be parsed from a {@link org.glassfish.jersey.server.ContainerRequest}
|
||||
*/
|
||||
@Target({ElementType.PARAMETER, ElementType.FIELD})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface Extract {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.spam;
|
||||
|
||||
import org.glassfish.jersey.server.ContainerRequest;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* A ScoreThreshold may be provided by an upstream request filter. If request contains a property for
|
||||
* SCORE_THRESHOLD_PROPERTY_NAME it can be forwarded to a downstream filter to indicate it can use
|
||||
* a more or less strict score threshold when evaluating whether a request should be allowed to continue.
|
||||
*/
|
||||
public class ScoreThreshold {
|
||||
private static final Logger logger = LoggerFactory.getLogger(ScoreThreshold.class);
|
||||
|
||||
public static final String PROPERTY_NAME = "scoreThreshold";
|
||||
|
||||
/**
|
||||
* A score threshold in the range [0, 1.0]
|
||||
*/
|
||||
private final Optional<Float> scoreThreshold;
|
||||
|
||||
/**
|
||||
* Extract an optional score threshold parameter provided by an upstream request filter
|
||||
*/
|
||||
public ScoreThreshold(final ContainerRequest containerRequest) {
|
||||
this.scoreThreshold = Optional
|
||||
.ofNullable(containerRequest.getProperty(PROPERTY_NAME))
|
||||
.flatMap(obj -> {
|
||||
if (obj instanceof Float f) {
|
||||
return Optional.of(f);
|
||||
}
|
||||
logger.warn("invalid format for filter provided score threshold {}", obj);
|
||||
return Optional.empty();
|
||||
});
|
||||
}
|
||||
|
||||
public Optional<Float> getScoreThreshold() {
|
||||
return this.scoreThreshold;
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package org.whispersystems.textsecuregcm.spam;
|
||||
|
||||
import java.util.function.Function;
|
||||
import javax.inject.Singleton;
|
||||
import javax.ws.rs.core.Feature;
|
||||
import javax.ws.rs.core.FeatureContext;
|
||||
import org.glassfish.jersey.internal.inject.AbstractBinder;
|
||||
import org.glassfish.jersey.server.ContainerRequest;
|
||||
import org.glassfish.jersey.server.model.Parameter;
|
||||
import org.glassfish.jersey.server.spi.internal.ValueParamProvider;
|
||||
|
||||
/**
|
||||
* Parses a {@link ScoreThreshold} out of a {@link ContainerRequest} to provide to jersey resources.
|
||||
*
|
||||
* A request filter may enrich a ContainerRequest with a scoreThreshold by providing a float property with the name
|
||||
* {@link ScoreThreshold#PROPERTY_NAME}. This indicates the desired scoreThreshold to use when evaluating whether a
|
||||
* request should proceed.
|
||||
*
|
||||
* A resource can consume a ScoreThreshold with by annotating a ScoreThreshold parameter with {@link Extract}
|
||||
*/
|
||||
public class ScoreThresholdProvider implements ValueParamProvider {
|
||||
|
||||
/**
|
||||
* Configures the ScoreThresholdProvider
|
||||
*/
|
||||
public static class ScoreThresholdFeature implements Feature {
|
||||
@Override
|
||||
public boolean configure(FeatureContext context) {
|
||||
context.register(new AbstractBinder() {
|
||||
@Override
|
||||
protected void configure() {
|
||||
bind(ScoreThresholdProvider.class)
|
||||
.to(ValueParamProvider.class)
|
||||
.in(Singleton.class);
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Function<ContainerRequest, ?> getValueProvider(final Parameter parameter) {
|
||||
if (parameter.getRawType().equals(ScoreThreshold.class)
|
||||
&& parameter.isAnnotationPresent(Extract.class)) {
|
||||
return ScoreThreshold::new;
|
||||
}
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public PriorityType getPriority() {
|
||||
return Priority.HIGH;
|
||||
}
|
||||
}
|
||||
@@ -414,7 +414,7 @@ public class Account {
|
||||
public StoredRegistrationLock getRegistrationLock() {
|
||||
requireNotStale();
|
||||
|
||||
return new StoredRegistrationLock(Optional.ofNullable(registrationLock), Optional.ofNullable(registrationLockSalt), getLastSeen());
|
||||
return new StoredRegistrationLock(Optional.ofNullable(registrationLock), Optional.ofNullable(registrationLockSalt), Instant.ofEpochMilli(getLastSeen()));
|
||||
}
|
||||
|
||||
public Optional<byte[]> getUnidentifiedAccessKey() {
|
||||
|
||||
+10
-2
@@ -47,6 +47,7 @@ import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisOperation;
|
||||
import org.whispersystems.textsecuregcm.securebackup.SecureBackupClient;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
|
||||
import org.whispersystems.textsecuregcm.sqs.DirectoryQueue;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
import org.whispersystems.textsecuregcm.util.DestinationDeviceValidator;
|
||||
@@ -91,6 +92,7 @@ public class AccountsManager {
|
||||
private final StoredVerificationCodeManager pendingAccounts;
|
||||
private final SecureStorageClient secureStorageClient;
|
||||
private final SecureBackupClient secureBackupClient;
|
||||
private final SecureValueRecovery2Client secureValueRecovery2Client;
|
||||
private final ClientPresenceManager clientPresenceManager;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
@@ -134,6 +136,7 @@ public class AccountsManager {
|
||||
final StoredVerificationCodeManager pendingAccounts,
|
||||
final SecureStorageClient secureStorageClient,
|
||||
final SecureBackupClient secureBackupClient,
|
||||
final SecureValueRecovery2Client secureValueRecovery2Client,
|
||||
final ClientPresenceManager clientPresenceManager,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager,
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
|
||||
@@ -148,7 +151,8 @@ public class AccountsManager {
|
||||
this.profilesManager = profilesManager;
|
||||
this.pendingAccounts = pendingAccounts;
|
||||
this.secureStorageClient = secureStorageClient;
|
||||
this.secureBackupClient = secureBackupClient;
|
||||
this.secureBackupClient = secureBackupClient;
|
||||
this.secureValueRecovery2Client = secureValueRecovery2Client;
|
||||
this.clientPresenceManager = clientPresenceManager;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
this.registrationRecoveryPasswordsManager = requireNonNull(registrationRecoveryPasswordsManager);
|
||||
@@ -655,8 +659,11 @@ public class AccountsManager {
|
||||
}
|
||||
|
||||
private void delete(final Account account) {
|
||||
final CompletableFuture<Void> deleteStorageServiceDataFuture = secureStorageClient.deleteStoredData(account.getUuid());
|
||||
final CompletableFuture<Void> deleteStorageServiceDataFuture = secureStorageClient.deleteStoredData(
|
||||
account.getUuid());
|
||||
final CompletableFuture<Void> deleteBackupServiceDataFuture = secureBackupClient.deleteBackups(account.getUuid());
|
||||
final CompletableFuture<Void> deleteSecureValueRecoveryServiceDataFuture = secureValueRecovery2Client.deleteBackups(
|
||||
account.getUuid());
|
||||
|
||||
profilesManager.deleteAll(account.getUuid());
|
||||
keys.delete(account.getUuid());
|
||||
@@ -667,6 +674,7 @@ public class AccountsManager {
|
||||
|
||||
deleteStorageServiceDataFuture.join();
|
||||
deleteBackupServiceDataFuture.join();
|
||||
deleteSecureValueRecoveryServiceDataFuture.join();
|
||||
|
||||
accounts.delete(account.getUuid());
|
||||
redisDelete(account);
|
||||
|
||||
@@ -14,7 +14,6 @@ import io.lettuce.core.ScoredValue;
|
||||
import io.lettuce.core.ScriptOutputType;
|
||||
import io.lettuce.core.ZAddArgs;
|
||||
import io.lettuce.core.cluster.SlotHash;
|
||||
import io.lettuce.core.cluster.event.ClusterTopologyChangedEvent;
|
||||
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
|
||||
import io.lettuce.core.cluster.pubsub.RedisClusterPubSubAdapter;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
@@ -63,6 +62,7 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
private final Clock clock;
|
||||
|
||||
private final ExecutorService notificationExecutorService;
|
||||
private final Scheduler messageDeliveryScheduler;
|
||||
private final ExecutorService messageDeletionExecutorService;
|
||||
// messageDeletionExecutorService wrapped into a reactor Scheduler
|
||||
private final Scheduler messageDeletionScheduler;
|
||||
@@ -103,14 +103,15 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessagesCache.class);
|
||||
|
||||
public MessagesCache(final FaultTolerantRedisCluster insertCluster, final FaultTolerantRedisCluster readDeleteCluster,
|
||||
final Clock clock, final ExecutorService notificationExecutorService,
|
||||
final ExecutorService messageDeletionExecutorService) throws IOException {
|
||||
final ExecutorService notificationExecutorService, final Scheduler messageDeliveryScheduler,
|
||||
final ExecutorService messageDeletionExecutorService, final Clock clock) throws IOException {
|
||||
|
||||
this.readDeleteCluster = readDeleteCluster;
|
||||
this.pubSubConnection = readDeleteCluster.createPubSubConnection();
|
||||
this.clock = clock;
|
||||
|
||||
this.notificationExecutorService = notificationExecutorService;
|
||||
this.messageDeliveryScheduler = messageDeliveryScheduler;
|
||||
this.messageDeletionExecutorService = messageDeletionExecutorService;
|
||||
this.messageDeletionScheduler = Schedulers.fromExecutorService(messageDeletionExecutorService, "messageDeletion");
|
||||
|
||||
@@ -126,12 +127,8 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
pubSubConnection.usePubSubConnection(connection -> {
|
||||
connection.addListener(this);
|
||||
connection.getResources().eventBus().get()
|
||||
.filter(event -> event instanceof ClusterTopologyChangedEvent)
|
||||
.subscribe(event -> resubscribeAll());
|
||||
});
|
||||
pubSubConnection.usePubSubConnection(connection -> connection.addListener(this));
|
||||
pubSubConnection.subscribeToClusterTopologyChangedEvents(this::resubscribeAll);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -140,7 +137,6 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
}
|
||||
|
||||
private void resubscribeAll() {
|
||||
logger.info("Got topology change event, resubscribing all keyspace notifications");
|
||||
|
||||
final Set<String> queueNames;
|
||||
|
||||
@@ -263,7 +259,7 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
})
|
||||
.limitRate(1)
|
||||
// we want to ensure we don’t accidentally block the Lettuce/netty i/o executors
|
||||
.publishOn(Schedulers.boundedElastic())
|
||||
.publishOn(messageDeliveryScheduler)
|
||||
.map(Pair::first)
|
||||
.flatMapIterable(queueItems -> {
|
||||
final List<MessageProtos.Envelope> envelopes = new ArrayList<>(queueItems.size() / 2);
|
||||
|
||||
@@ -7,25 +7,14 @@ package org.whispersystems.textsecuregcm.util.ua;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.vdurmont.semver4j.Semver;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import java.util.EnumMap;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
public class UserAgentUtil {
|
||||
|
||||
private static final Pattern STANDARD_UA_PATTERN = Pattern.compile("^Signal-(Android|Desktop|iOS)/([^ ]+)( (.+))?$", Pattern.CASE_INSENSITIVE);
|
||||
|
||||
private static final Map<ClientPlatform, Pattern> LEGACY_PATTERNS_BY_PLATFORM = new EnumMap<>(ClientPlatform.class);
|
||||
|
||||
static {
|
||||
LEGACY_PATTERNS_BY_PLATFORM.put(ClientPlatform.ANDROID, Pattern.compile("^Signal-Android ([^ ]+)( (.+))?$", Pattern.CASE_INSENSITIVE));
|
||||
LEGACY_PATTERNS_BY_PLATFORM.put(ClientPlatform.DESKTOP, Pattern.compile("^Signal Desktop (.+)$", Pattern.CASE_INSENSITIVE));
|
||||
LEGACY_PATTERNS_BY_PLATFORM.put(ClientPlatform.IOS, Pattern.compile("^Signal/([^ ]+)( (.+))?$", Pattern.CASE_INSENSITIVE));
|
||||
}
|
||||
|
||||
public static UserAgent parseUserAgentString(final String userAgentString) throws UnrecognizedUserAgentException {
|
||||
if (StringUtils.isBlank(userAgentString)) {
|
||||
throw new UnrecognizedUserAgentException("User-Agent string is blank");
|
||||
@@ -37,12 +26,6 @@ public class UserAgentUtil {
|
||||
if (standardUserAgent != null) {
|
||||
return standardUserAgent;
|
||||
}
|
||||
|
||||
final UserAgent legacyUserAgent = parseLegacyUserAgentString(userAgentString);
|
||||
|
||||
if (legacyUserAgent != null) {
|
||||
return legacyUserAgent;
|
||||
}
|
||||
} catch (final Exception e) {
|
||||
throw new UnrecognizedUserAgentException(e);
|
||||
}
|
||||
@@ -60,27 +43,4 @@ public class UserAgentUtil {
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static UserAgent parseLegacyUserAgentString(final String userAgentString) {
|
||||
for (final Map.Entry<ClientPlatform, Pattern> entry : LEGACY_PATTERNS_BY_PLATFORM.entrySet()) {
|
||||
final ClientPlatform platform = entry.getKey();
|
||||
final Pattern pattern = entry.getValue();
|
||||
final Matcher matcher = pattern.matcher(userAgentString);
|
||||
|
||||
if (matcher.matches()) {
|
||||
final UserAgent userAgent;
|
||||
|
||||
if (matcher.groupCount() > 1) {
|
||||
userAgent = new UserAgent(platform, new Semver(matcher.group(1)), StringUtils.stripToNull(matcher.group(matcher.groupCount())));
|
||||
} else {
|
||||
userAgent = new UserAgent(platform, new Semver(matcher.group(1)));
|
||||
}
|
||||
|
||||
return userAgent;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+9
-4
@@ -11,6 +11,8 @@ import com.codahale.metrics.Counter;
|
||||
import com.codahale.metrics.MetricRegistry;
|
||||
import com.codahale.metrics.SharedMetricRegistries;
|
||||
import com.codahale.metrics.Timer;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.util.EnumMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
@@ -18,8 +20,6 @@ import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
@@ -38,6 +38,7 @@ import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
|
||||
import org.whispersystems.websocket.session.WebSocketSessionContext;
|
||||
import org.whispersystems.websocket.setup.WebSocketConnectListener;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
|
||||
public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
|
||||
@@ -61,6 +62,7 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
private final PushNotificationManager pushNotificationManager;
|
||||
private final ClientPresenceManager clientPresenceManager;
|
||||
private final ScheduledExecutorService scheduledExecutorService;
|
||||
private final Scheduler messageDeliveryScheduler;
|
||||
|
||||
private final Map<ClientPlatform, AtomicInteger> openWebsocketsByClientPlatform;
|
||||
private final AtomicInteger openWebsocketsFromUnknownPlatforms;
|
||||
@@ -69,12 +71,14 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
MessagesManager messagesManager,
|
||||
PushNotificationManager pushNotificationManager,
|
||||
ClientPresenceManager clientPresenceManager,
|
||||
ScheduledExecutorService scheduledExecutorService) {
|
||||
ScheduledExecutorService scheduledExecutorService,
|
||||
Scheduler messageDeliveryScheduler) {
|
||||
this.receiptSender = receiptSender;
|
||||
this.messagesManager = messagesManager;
|
||||
this.pushNotificationManager = pushNotificationManager;
|
||||
this.clientPresenceManager = clientPresenceManager;
|
||||
this.scheduledExecutorService = scheduledExecutorService;
|
||||
this.messageDeliveryScheduler = messageDeliveryScheduler;
|
||||
|
||||
openWebsocketsByClientPlatform = new EnumMap<>(ClientPlatform.class);
|
||||
|
||||
@@ -100,7 +104,8 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
final WebSocketConnection connection = new WebSocketConnection(receiptSender,
|
||||
messagesManager, auth, device,
|
||||
context.getClient(),
|
||||
scheduledExecutorService);
|
||||
scheduledExecutorService,
|
||||
messageDeliveryScheduler);
|
||||
|
||||
final AtomicInteger openWebsocketAtomicInteger = getOpenWebsocketCounter(context.getClient().getUserAgent());
|
||||
|
||||
|
||||
+10
-2
@@ -12,6 +12,7 @@ import java.util.Optional;
|
||||
import org.eclipse.jetty.websocket.api.UpgradeRequest;
|
||||
import org.whispersystems.textsecuregcm.auth.AccountAuthenticator;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.websocket.auth.AuthenticationException;
|
||||
import org.whispersystems.websocket.auth.WebSocketAuthenticator;
|
||||
|
||||
|
||||
@@ -24,7 +25,8 @@ public class WebSocketAccountAuthenticator implements WebSocketAuthenticator<Aut
|
||||
}
|
||||
|
||||
@Override
|
||||
public AuthenticationResult<AuthenticatedAccount> authenticate(UpgradeRequest request) {
|
||||
public AuthenticationResult<AuthenticatedAccount> authenticate(UpgradeRequest request)
|
||||
throws AuthenticationException {
|
||||
Map<String, List<String>> parameters = request.getParameterMap();
|
||||
List<String> usernames = parameters.get("login");
|
||||
List<String> passwords = parameters.get("password");
|
||||
@@ -37,7 +39,13 @@ public class WebSocketAccountAuthenticator implements WebSocketAuthenticator<Aut
|
||||
BasicCredentials credentials = new BasicCredentials(usernames.get(0).replace(" ", "+"),
|
||||
passwords.get(0).replace(" ", "+"));
|
||||
|
||||
return new AuthenticationResult<>(accountAuthenticator.authenticate(credentials), true);
|
||||
try {
|
||||
return new AuthenticationResult<>(accountAuthenticator.authenticate(credentials), true);
|
||||
} catch (final Exception e) {
|
||||
// this will be handled and logged upstream
|
||||
// the most likely exception is a transient error connecting to account storage
|
||||
throw new AuthenticationException(e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+36
-47
@@ -56,7 +56,6 @@ import reactor.core.observability.micrometer.Micrometer;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
|
||||
public class WebSocketConnection implements MessageAvailabilityListener, DisplacedPresenceListener {
|
||||
|
||||
@@ -127,7 +126,7 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
private final AtomicReference<Disposable> messageSubscription = new AtomicReference<>();
|
||||
|
||||
private final Random random = new Random();
|
||||
private final Scheduler reactiveScheduler;
|
||||
private final Scheduler messageDeliveryScheduler;
|
||||
|
||||
private enum StoredMessageState {
|
||||
EMPTY,
|
||||
@@ -136,29 +135,12 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
}
|
||||
|
||||
public WebSocketConnection(ReceiptSender receiptSender,
|
||||
MessagesManager messagesManager,
|
||||
AuthenticatedAccount auth,
|
||||
Device device,
|
||||
WebSocketClient client,
|
||||
ScheduledExecutorService scheduledExecutorService) {
|
||||
|
||||
this(receiptSender,
|
||||
messagesManager,
|
||||
auth,
|
||||
device,
|
||||
client,
|
||||
scheduledExecutorService,
|
||||
Schedulers.boundedElastic());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
WebSocketConnection(ReceiptSender receiptSender,
|
||||
MessagesManager messagesManager,
|
||||
AuthenticatedAccount auth,
|
||||
Device device,
|
||||
WebSocketClient client,
|
||||
ScheduledExecutorService scheduledExecutorService,
|
||||
Scheduler reactiveScheduler) {
|
||||
Scheduler messageDeliveryScheduler) {
|
||||
|
||||
this(receiptSender,
|
||||
messagesManager,
|
||||
@@ -167,7 +149,7 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
client,
|
||||
DEFAULT_SEND_FUTURES_TIMEOUT_MILLIS,
|
||||
scheduledExecutorService,
|
||||
reactiveScheduler);
|
||||
messageDeliveryScheduler);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -178,7 +160,7 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
WebSocketClient client,
|
||||
int sendFuturesTimeoutMillis,
|
||||
ScheduledExecutorService scheduledExecutorService,
|
||||
Scheduler reactiveScheduler) {
|
||||
Scheduler messageDeliveryScheduler) {
|
||||
|
||||
this.receiptSender = receiptSender;
|
||||
this.messagesManager = messagesManager;
|
||||
@@ -187,7 +169,7 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
this.client = client;
|
||||
this.sendFuturesTimeoutMillis = sendFuturesTimeoutMillis;
|
||||
this.scheduledExecutorService = scheduledExecutorService;
|
||||
this.reactiveScheduler = reactiveScheduler;
|
||||
this.messageDeliveryScheduler = messageDeliveryScheduler;
|
||||
}
|
||||
|
||||
public void start() {
|
||||
@@ -210,7 +192,7 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
client.close(1000, "OK");
|
||||
}
|
||||
|
||||
private CompletableFuture<?> sendMessage(final Envelope message, StoredMessageInfo storedMessageInfo) {
|
||||
private CompletableFuture<Void> sendMessage(final Envelope message, StoredMessageInfo storedMessageInfo) {
|
||||
// clear ephemeral field from the envelope
|
||||
final Optional<byte[]> body = Optional.ofNullable(message.toBuilder().clearEphemeral().build().toByteArray());
|
||||
|
||||
@@ -227,11 +209,12 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
sendFailuresMeter.mark();
|
||||
}
|
||||
}).thenCompose(response -> {
|
||||
final CompletableFuture<?> result;
|
||||
final CompletableFuture<Void> result;
|
||||
if (isSuccessResponse(response)) {
|
||||
|
||||
result = messagesManager.delete(auth.getAccount().getUuid(), device.getId(),
|
||||
storedMessageInfo.guid(), storedMessageInfo.serverTimestamp());
|
||||
storedMessageInfo.guid(), storedMessageInfo.serverTimestamp())
|
||||
.thenApply(ignored -> null);
|
||||
|
||||
if (message.getType() != Envelope.Type.SERVER_DELIVERY_RECEIPT) {
|
||||
recordMessageDeliveryDuration(message.getTimestamp(), device);
|
||||
@@ -364,31 +347,37 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
.limitRate(MESSAGE_PUBLISHER_LIMIT_RATE)
|
||||
.flatMapSequential(envelope ->
|
||||
Mono.fromFuture(sendMessage(envelope)
|
||||
.orTimeout(sendFuturesTimeoutMillis, TimeUnit.MILLISECONDS))
|
||||
.doOnError(e -> {
|
||||
final String errorType;
|
||||
if (e instanceof TimeoutException) {
|
||||
errorType = "timeout";
|
||||
} else if (e instanceof java.nio.channels.ClosedChannelException) {
|
||||
errorType = "closedChannel";
|
||||
} else {
|
||||
logger.warn("Send message failed", e);
|
||||
errorType = "other";
|
||||
}
|
||||
final Tags tags = Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(client.getUserAgent()),
|
||||
Tag.of(ERROR_TYPE_TAG, errorType));
|
||||
Metrics.counter(SEND_MESSAGE_ERROR_COUNTER, tags).increment();
|
||||
}))
|
||||
.doOnError(queueCleared::completeExceptionally)
|
||||
.doOnComplete(() -> queueCleared.complete(null))
|
||||
.subscribeOn(reactiveScheduler)
|
||||
.subscribe();
|
||||
.orTimeout(sendFuturesTimeoutMillis, TimeUnit.MILLISECONDS)))
|
||||
.subscribeOn(messageDeliveryScheduler)
|
||||
.subscribe(
|
||||
// no additional consumer of values - it is Flux<Void> by now
|
||||
null,
|
||||
// the first error will terminate the stream, but we may get multiple errors from in-flight messages
|
||||
e -> {
|
||||
queueCleared.completeExceptionally(e);
|
||||
|
||||
final String errorType;
|
||||
if (e instanceof TimeoutException) {
|
||||
errorType = "timeout";
|
||||
} else if (e instanceof java.nio.channels.ClosedChannelException) {
|
||||
errorType = "closedChannel";
|
||||
} else {
|
||||
logger.warn("Send message failed", e);
|
||||
errorType = "other";
|
||||
}
|
||||
final Tags tags = Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(client.getUserAgent()),
|
||||
Tag.of(ERROR_TYPE_TAG, errorType));
|
||||
Metrics.counter(SEND_MESSAGE_ERROR_COUNTER, tags).increment();
|
||||
},
|
||||
// completion
|
||||
() -> queueCleared.complete(null)
|
||||
);
|
||||
|
||||
messageSubscription.set(subscription);
|
||||
}
|
||||
|
||||
private CompletableFuture<?> sendMessage(Envelope envelope) {
|
||||
private CompletableFuture<Void> sendMessage(Envelope envelope) {
|
||||
final UUID messageGuid = UUID.fromString(envelope.getServerGuid());
|
||||
|
||||
if (envelope.getStory() && !client.shouldDeliverStories()) {
|
||||
|
||||
+17
-6
@@ -29,11 +29,13 @@ import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureBackupController;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery2Controller;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.securebackup.SecureBackupClient;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
|
||||
import org.whispersystems.textsecuregcm.sqs.DirectoryQueue;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Accounts;
|
||||
@@ -58,6 +60,8 @@ import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableExceptio
|
||||
import org.whispersystems.textsecuregcm.storage.UsernameReservationNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationCodeStore;
|
||||
import org.whispersystems.textsecuregcm.util.DynamoDbFromConfig;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
|
||||
@@ -100,12 +104,15 @@ public class AssignUsernameCommand extends EnvironmentCommand<WhisperServerConfi
|
||||
FaultTolerantRedisCluster cacheCluster = new FaultTolerantRedisCluster("main_cache_cluster",
|
||||
configuration.getCacheClusterConfiguration(), redisClusterClientResources);
|
||||
|
||||
Scheduler messageDeliveryScheduler = Schedulers.fromExecutorService(
|
||||
environment.lifecycle().executorService("messageDelivery-%d").maxThreads(4)
|
||||
.build());
|
||||
ExecutorService keyspaceNotificationDispatchExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "keyspaceNotification-%d")).maxThreads(4).build();
|
||||
ExecutorService messageDeletionExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "messageDeletion-%d")).maxThreads(4).build();
|
||||
ExecutorService backupServiceExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "backupService-%d")).maxThreads(8).minThreads(1).build();
|
||||
ExecutorService secureValueRecoveryExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "secureValueRecoveryService-%d")).maxThreads(8).minThreads(1).build();
|
||||
ExecutorService storageServiceExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "storageService-%d")).maxThreads(8).minThreads(1).build();
|
||||
|
||||
@@ -113,7 +120,9 @@ public class AssignUsernameCommand extends EnvironmentCommand<WhisperServerConfi
|
||||
configuration.getSecureBackupServiceConfiguration());
|
||||
ExternalServiceCredentialsGenerator storageCredentialsGenerator = SecureStorageController.credentialsGenerator(
|
||||
configuration.getSecureStorageServiceConfiguration());
|
||||
|
||||
ExternalServiceCredentialsGenerator secureValueRecoveryCredentialsGenerator = SecureValueRecovery2Controller.credentialsGenerator(
|
||||
configuration.getSvr2Configuration());
|
||||
|
||||
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = new DynamicConfigurationManager<>(
|
||||
configuration.getAppConfig().getApplication(), configuration.getAppConfig().getEnvironment(),
|
||||
configuration.getAppConfig().getConfigurationName(), DynamicConfiguration.class);
|
||||
@@ -183,14 +192,16 @@ public class AssignUsernameCommand extends EnvironmentCommand<WhisperServerConfi
|
||||
configuration.getClientPresenceClusterConfiguration(), redisClusterClientResources);
|
||||
FaultTolerantRedisCluster rateLimitersCluster = new FaultTolerantRedisCluster("rate_limiters",
|
||||
configuration.getRateLimitersCluster(), redisClusterClientResources);
|
||||
SecureBackupClient secureBackupClient = new SecureBackupClient(backupCredentialsGenerator, backupServiceExecutor,
|
||||
SecureBackupClient secureBackupClient = new SecureBackupClient(backupCredentialsGenerator, secureValueRecoveryExecutor,
|
||||
configuration.getSecureBackupServiceConfiguration());
|
||||
SecureValueRecovery2Client secureValueRecovery2Client = new SecureValueRecovery2Client(
|
||||
secureValueRecoveryCredentialsGenerator, secureValueRecoveryExecutor, configuration.getSvr2Configuration());
|
||||
SecureStorageClient secureStorageClient = new SecureStorageClient(storageCredentialsGenerator,
|
||||
storageServiceExecutor, configuration.getSecureStorageServiceConfiguration());
|
||||
ClientPresenceManager clientPresenceManager = new ClientPresenceManager(clientPresenceCluster,
|
||||
Executors.newSingleThreadScheduledExecutor(), keyspaceNotificationDispatchExecutor);
|
||||
MessagesCache messagesCache = new MessagesCache(messageInsertCacheCluster, messageReadDeleteCluster,
|
||||
Clock.systemUTC(), keyspaceNotificationDispatchExecutor, messageDeletionExecutor);
|
||||
keyspaceNotificationDispatchExecutor, messageDeliveryScheduler, messageDeletionExecutor, Clock.systemUTC());
|
||||
DirectoryQueue directoryQueue = new DirectoryQueue(
|
||||
configuration.getDirectoryConfiguration().getSqsConfiguration());
|
||||
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster);
|
||||
@@ -207,7 +218,7 @@ public class AssignUsernameCommand extends EnvironmentCommand<WhisperServerConfi
|
||||
StoredVerificationCodeManager pendingAccountsManager = new StoredVerificationCodeManager(pendingAccounts);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
deletedAccountsManager, directoryQueue, keys, messagesManager, profilesManager,
|
||||
pendingAccountsManager, secureStorageClient, secureBackupClient, clientPresenceManager,
|
||||
pendingAccountsManager, secureStorageClient, secureBackupClient, secureValueRecovery2Client, clientPresenceManager,
|
||||
experimentEnrollmentManager, registrationRecoveryPasswordsManager, Clock.systemUTC());
|
||||
|
||||
final String usernameHash = namespace.getString("usernameHash");
|
||||
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.amazonaws.ClientConfiguration;
|
||||
import com.amazonaws.auth.InstanceProfileCredentialsProvider;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import io.dropwizard.setup.Environment;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
import java.io.IOException;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.time.Clock;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureBackupController;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery2Controller;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.securebackup.SecureBackupClient;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
|
||||
import org.whispersystems.textsecuregcm.sqs.DirectoryQueue;
|
||||
import org.whispersystems.textsecuregcm.storage.Accounts;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DeletedAccounts;
|
||||
import org.whispersystems.textsecuregcm.storage.DeletedAccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Keys;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesCache;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.Profiles;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswords;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
|
||||
import org.whispersystems.textsecuregcm.storage.StoredVerificationCodeManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationCodeStore;
|
||||
import org.whispersystems.textsecuregcm.util.DynamoDbFromConfig;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
|
||||
/**
|
||||
* Construct utilities commonly used by worker commands
|
||||
*/
|
||||
record CommandDependencies(
|
||||
AccountsManager accountsManager,
|
||||
ProfilesManager profilesManager,
|
||||
ReportMessageManager reportMessageManager,
|
||||
MessagesManager messagesManager,
|
||||
DeletedAccountsManager deletedAccountsManager,
|
||||
StoredVerificationCodeManager pendingAccountsManager,
|
||||
ClientPresenceManager clientPresenceManager,
|
||||
Keys keys) {
|
||||
|
||||
static CommandDependencies build(
|
||||
final String name,
|
||||
final Environment environment,
|
||||
final WhisperServerConfiguration configuration) throws IOException, CertificateException {
|
||||
Clock clock = Clock.systemUTC();
|
||||
|
||||
environment.getObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
|
||||
ClientResources redisClusterClientResources = ClientResources.builder().build();
|
||||
|
||||
FaultTolerantRedisCluster cacheCluster = new FaultTolerantRedisCluster("main_cache_cluster",
|
||||
configuration.getCacheClusterConfiguration(), redisClusterClientResources);
|
||||
|
||||
Scheduler messageDeliveryScheduler = Schedulers.fromExecutorService(
|
||||
environment.lifecycle().executorService("messageDelivery").maxThreads(4)
|
||||
.build());
|
||||
ExecutorService keyspaceNotificationDispatchExecutor = environment.lifecycle()
|
||||
.executorService(name(name, "keyspaceNotification-%d")).maxThreads(4).build();
|
||||
ExecutorService messageDeletionExecutor = environment.lifecycle()
|
||||
.executorService(name(name, "messageDeletion-%d")).maxThreads(4).build();
|
||||
ExecutorService secureValueRecoveryServiceExecutor = environment.lifecycle()
|
||||
.executorService(name(name, "secureValueRecoveryService-%d")).maxThreads(8).minThreads(1).build();
|
||||
ExecutorService storageServiceExecutor = environment.lifecycle()
|
||||
.executorService(name(name, "storageService-%d")).maxThreads(8).minThreads(1).build();
|
||||
|
||||
ExternalServiceCredentialsGenerator backupCredentialsGenerator = SecureBackupController.credentialsGenerator(
|
||||
configuration.getSecureBackupServiceConfiguration());
|
||||
ExternalServiceCredentialsGenerator storageCredentialsGenerator = SecureStorageController.credentialsGenerator(
|
||||
configuration.getSecureStorageServiceConfiguration());
|
||||
ExternalServiceCredentialsGenerator secureValueRecoveryCredentialsGenerator = SecureValueRecovery2Controller.credentialsGenerator(
|
||||
configuration.getSvr2Configuration());
|
||||
|
||||
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = new DynamicConfigurationManager<>(
|
||||
configuration.getAppConfig().getApplication(), configuration.getAppConfig().getEnvironment(),
|
||||
configuration.getAppConfig().getConfigurationName(), DynamicConfiguration.class);
|
||||
dynamicConfigurationManager.start();
|
||||
|
||||
ExperimentEnrollmentManager experimentEnrollmentManager = new ExperimentEnrollmentManager(
|
||||
dynamicConfigurationManager);
|
||||
|
||||
DynamoDbAsyncClient dynamoDbAsyncClient = DynamoDbFromConfig.asyncClient(
|
||||
configuration.getDynamoDbClientConfiguration(),
|
||||
software.amazon.awssdk.auth.credentials.InstanceProfileCredentialsProvider.create());
|
||||
|
||||
DynamoDbClient dynamoDbClient = DynamoDbFromConfig.client(
|
||||
configuration.getDynamoDbClientConfiguration(),
|
||||
software.amazon.awssdk.auth.credentials.InstanceProfileCredentialsProvider.create());
|
||||
|
||||
AmazonDynamoDB deletedAccountsLockDynamoDbClient = AmazonDynamoDBClientBuilder.standard()
|
||||
.withRegion(configuration.getDynamoDbClientConfiguration().getRegion())
|
||||
.withClientConfiguration(new ClientConfiguration().withClientExecutionTimeout(
|
||||
((int) configuration.getDynamoDbClientConfiguration().getClientExecutionTimeout()
|
||||
.toMillis()))
|
||||
.withRequestTimeout(
|
||||
(int) configuration.getDynamoDbClientConfiguration().getClientRequestTimeout()
|
||||
.toMillis()))
|
||||
.withCredentials(InstanceProfileCredentialsProvider.getInstance())
|
||||
.build();
|
||||
|
||||
DeletedAccounts deletedAccounts = new DeletedAccounts(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getDeletedAccounts().getTableName(),
|
||||
configuration.getDynamoDbTables().getDeletedAccounts().getNeedsReconciliationIndexName());
|
||||
VerificationCodeStore pendingAccounts = new VerificationCodeStore(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getPendingAccounts().getTableName());
|
||||
RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
|
||||
configuration.getDynamoDbTables().getRegistrationRecovery().getTableName(),
|
||||
configuration.getDynamoDbTables().getRegistrationRecovery().getExpiration(),
|
||||
dynamoDbClient,
|
||||
dynamoDbAsyncClient
|
||||
);
|
||||
|
||||
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager = new RegistrationRecoveryPasswordsManager(
|
||||
registrationRecoveryPasswords);
|
||||
|
||||
Accounts accounts = new Accounts(
|
||||
dynamoDbClient,
|
||||
dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getAccounts().getTableName(),
|
||||
configuration.getDynamoDbTables().getAccounts().getPhoneNumberTableName(),
|
||||
configuration.getDynamoDbTables().getAccounts().getPhoneNumberIdentifierTableName(),
|
||||
configuration.getDynamoDbTables().getAccounts().getUsernamesTableName(),
|
||||
configuration.getDynamoDbTables().getAccounts().getScanPageSize());
|
||||
PhoneNumberIdentifiers phoneNumberIdentifiers = new PhoneNumberIdentifiers(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getPhoneNumberIdentifiers().getTableName());
|
||||
Profiles profiles = new Profiles(dynamoDbClient, dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getProfiles().getTableName());
|
||||
Keys keys = new Keys(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getKeys().getTableName());
|
||||
MessagesDynamoDb messagesDynamoDb = new MessagesDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getMessages().getTableName(),
|
||||
configuration.getDynamoDbTables().getMessages().getExpiration(),
|
||||
messageDeletionExecutor);
|
||||
FaultTolerantRedisCluster messageInsertCacheCluster = new FaultTolerantRedisCluster("message_insert_cluster",
|
||||
configuration.getMessageCacheConfiguration().getRedisClusterConfiguration(), redisClusterClientResources);
|
||||
FaultTolerantRedisCluster messageReadDeleteCluster = new FaultTolerantRedisCluster("message_read_delete_cluster",
|
||||
configuration.getMessageCacheConfiguration().getRedisClusterConfiguration(), redisClusterClientResources);
|
||||
FaultTolerantRedisCluster clientPresenceCluster = new FaultTolerantRedisCluster("client_presence_cluster",
|
||||
configuration.getClientPresenceClusterConfiguration(), redisClusterClientResources);
|
||||
FaultTolerantRedisCluster rateLimitersCluster = new FaultTolerantRedisCluster("rate_limiters",
|
||||
configuration.getRateLimitersCluster(), redisClusterClientResources);
|
||||
SecureBackupClient secureBackupClient = new SecureBackupClient(backupCredentialsGenerator,
|
||||
secureValueRecoveryServiceExecutor,
|
||||
configuration.getSecureBackupServiceConfiguration());
|
||||
SecureValueRecovery2Client secureValueRecovery2Client = new SecureValueRecovery2Client(
|
||||
secureValueRecoveryCredentialsGenerator, secureValueRecoveryServiceExecutor,
|
||||
configuration.getSvr2Configuration());
|
||||
SecureStorageClient secureStorageClient = new SecureStorageClient(storageCredentialsGenerator,
|
||||
storageServiceExecutor, configuration.getSecureStorageServiceConfiguration());
|
||||
ClientPresenceManager clientPresenceManager = new ClientPresenceManager(clientPresenceCluster,
|
||||
Executors.newSingleThreadScheduledExecutor(), keyspaceNotificationDispatchExecutor);
|
||||
MessagesCache messagesCache = new MessagesCache(messageInsertCacheCluster, messageReadDeleteCluster,
|
||||
keyspaceNotificationDispatchExecutor, messageDeliveryScheduler, messageDeletionExecutor, Clock.systemUTC());
|
||||
DirectoryQueue directoryQueue = new DirectoryQueue(
|
||||
configuration.getDirectoryConfiguration().getSqsConfiguration());
|
||||
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster);
|
||||
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getReportMessage().getTableName(),
|
||||
configuration.getReportMessageConfiguration().getReportTtl());
|
||||
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster,
|
||||
configuration.getReportMessageConfiguration().getCounterTtl());
|
||||
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache,
|
||||
reportMessageManager, messageDeletionExecutor);
|
||||
DeletedAccountsManager deletedAccountsManager = new DeletedAccountsManager(deletedAccounts,
|
||||
deletedAccountsLockDynamoDbClient,
|
||||
configuration.getDynamoDbTables().getDeletedAccountsLock().getTableName());
|
||||
StoredVerificationCodeManager pendingAccountsManager = new StoredVerificationCodeManager(pendingAccounts);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
deletedAccountsManager, directoryQueue, keys, messagesManager, profilesManager,
|
||||
pendingAccountsManager, secureStorageClient, secureBackupClient, secureValueRecovery2Client, clientPresenceManager,
|
||||
experimentEnrollmentManager, registrationRecoveryPasswordsManager, clock);
|
||||
|
||||
return new CommandDependencies(
|
||||
accountsManager,
|
||||
profilesManager,
|
||||
reportMessageManager,
|
||||
messagesManager,
|
||||
deletedAccountsManager,
|
||||
pendingAccountsManager,
|
||||
clientPresenceManager,
|
||||
keys
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
+3
-158
@@ -5,60 +5,19 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.amazonaws.ClientConfiguration;
|
||||
import com.amazonaws.auth.InstanceProfileCredentialsProvider;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import io.dropwizard.Application;
|
||||
import io.dropwizard.cli.EnvironmentCommand;
|
||||
import io.dropwizard.setup.Environment;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
import java.time.Clock;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureBackupController;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.securebackup.SecureBackupClient;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.sqs.DirectoryQueue;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Accounts;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager.DeletionReason;
|
||||
import org.whispersystems.textsecuregcm.storage.DeletedAccounts;
|
||||
import org.whispersystems.textsecuregcm.storage.DeletedAccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Keys;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesCache;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.Profiles;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ProhibitedUsernames;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswords;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
|
||||
import org.whispersystems.textsecuregcm.storage.StoredVerificationCodeManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationCodeStore;
|
||||
import org.whispersystems.textsecuregcm.util.DynamoDbFromConfig;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
|
||||
public class DeleteUserCommand extends EnvironmentCommand<WhisperServerConfiguration> {
|
||||
|
||||
@@ -84,130 +43,16 @@ public class DeleteUserCommand extends EnvironmentCommand<WhisperServerConfigura
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void run(Environment environment, Namespace namespace,
|
||||
WhisperServerConfiguration configuration)
|
||||
protected void run(Environment environment, Namespace namespace, WhisperServerConfiguration configuration)
|
||||
throws Exception
|
||||
{
|
||||
try {
|
||||
Clock clock = Clock.systemUTC();
|
||||
String[] users = namespace.getString("user").split(",");
|
||||
|
||||
environment.getObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
|
||||
ClientResources redisClusterClientResources = ClientResources.builder().build();
|
||||
final CommandDependencies deps = CommandDependencies.build("rmuser", environment, configuration);
|
||||
|
||||
FaultTolerantRedisCluster cacheCluster = new FaultTolerantRedisCluster("main_cache_cluster",
|
||||
configuration.getCacheClusterConfiguration(), redisClusterClientResources);
|
||||
|
||||
ExecutorService keyspaceNotificationDispatchExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "keyspaceNotification-%d")).maxThreads(4).build();
|
||||
ExecutorService messageDeletionExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "messageDeletion-%d")).maxThreads(4).build();
|
||||
ExecutorService backupServiceExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "backupService-%d")).maxThreads(8).minThreads(1).build();
|
||||
ExecutorService storageServiceExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "storageService-%d")).maxThreads(8).minThreads(1).build();
|
||||
|
||||
ExternalServiceCredentialsGenerator backupCredentialsGenerator = SecureBackupController.credentialsGenerator(
|
||||
configuration.getSecureBackupServiceConfiguration());
|
||||
ExternalServiceCredentialsGenerator storageCredentialsGenerator = SecureStorageController.credentialsGenerator(
|
||||
configuration.getSecureStorageServiceConfiguration());
|
||||
|
||||
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = new DynamicConfigurationManager<>(
|
||||
configuration.getAppConfig().getApplication(), configuration.getAppConfig().getEnvironment(),
|
||||
configuration.getAppConfig().getConfigurationName(), DynamicConfiguration.class);
|
||||
dynamicConfigurationManager.start();
|
||||
|
||||
ExperimentEnrollmentManager experimentEnrollmentManager = new ExperimentEnrollmentManager(
|
||||
dynamicConfigurationManager);
|
||||
|
||||
DynamoDbAsyncClient dynamoDbAsyncClient = DynamoDbFromConfig.asyncClient(
|
||||
configuration.getDynamoDbClientConfiguration(),
|
||||
software.amazon.awssdk.auth.credentials.InstanceProfileCredentialsProvider.create());
|
||||
|
||||
DynamoDbClient dynamoDbClient = DynamoDbFromConfig.client(
|
||||
configuration.getDynamoDbClientConfiguration(),
|
||||
software.amazon.awssdk.auth.credentials.InstanceProfileCredentialsProvider.create());
|
||||
|
||||
AmazonDynamoDB deletedAccountsLockDynamoDbClient = AmazonDynamoDBClientBuilder.standard()
|
||||
.withRegion(configuration.getDynamoDbClientConfiguration().getRegion())
|
||||
.withClientConfiguration(new ClientConfiguration().withClientExecutionTimeout(
|
||||
((int) configuration.getDynamoDbClientConfiguration().getClientExecutionTimeout()
|
||||
.toMillis()))
|
||||
.withRequestTimeout(
|
||||
(int) configuration.getDynamoDbClientConfiguration().getClientRequestTimeout()
|
||||
.toMillis()))
|
||||
.withCredentials(InstanceProfileCredentialsProvider.getInstance())
|
||||
.build();
|
||||
|
||||
DeletedAccounts deletedAccounts = new DeletedAccounts(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getDeletedAccounts().getTableName(),
|
||||
configuration.getDynamoDbTables().getDeletedAccounts().getNeedsReconciliationIndexName());
|
||||
VerificationCodeStore pendingAccounts = new VerificationCodeStore(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getPendingAccounts().getTableName());
|
||||
RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
|
||||
configuration.getDynamoDbTables().getRegistrationRecovery().getTableName(),
|
||||
configuration.getDynamoDbTables().getRegistrationRecovery().getExpiration(),
|
||||
dynamoDbClient,
|
||||
dynamoDbAsyncClient
|
||||
);
|
||||
|
||||
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager = new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords);
|
||||
|
||||
Accounts accounts = new Accounts(
|
||||
dynamoDbClient,
|
||||
dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getAccounts().getTableName(),
|
||||
configuration.getDynamoDbTables().getAccounts().getPhoneNumberTableName(),
|
||||
configuration.getDynamoDbTables().getAccounts().getPhoneNumberIdentifierTableName(),
|
||||
configuration.getDynamoDbTables().getAccounts().getUsernamesTableName(),
|
||||
configuration.getDynamoDbTables().getAccounts().getScanPageSize());
|
||||
PhoneNumberIdentifiers phoneNumberIdentifiers = new PhoneNumberIdentifiers(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getPhoneNumberIdentifiers().getTableName());
|
||||
Profiles profiles = new Profiles(dynamoDbClient, dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getProfiles().getTableName());
|
||||
ProhibitedUsernames prohibitedUsernames = new ProhibitedUsernames(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getReservedUsernames().getTableName());
|
||||
Keys keys = new Keys(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getKeys().getTableName());
|
||||
MessagesDynamoDb messagesDynamoDb = new MessagesDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getMessages().getTableName(),
|
||||
configuration.getDynamoDbTables().getMessages().getExpiration(),
|
||||
messageDeletionExecutor);
|
||||
FaultTolerantRedisCluster messageInsertCacheCluster = new FaultTolerantRedisCluster("message_insert_cluster",
|
||||
configuration.getMessageCacheConfiguration().getRedisClusterConfiguration(), redisClusterClientResources);
|
||||
FaultTolerantRedisCluster messageReadDeleteCluster = new FaultTolerantRedisCluster("message_read_delete_cluster",
|
||||
configuration.getMessageCacheConfiguration().getRedisClusterConfiguration(), redisClusterClientResources);
|
||||
FaultTolerantRedisCluster clientPresenceCluster = new FaultTolerantRedisCluster("client_presence_cluster",
|
||||
configuration.getClientPresenceClusterConfiguration(), redisClusterClientResources);
|
||||
FaultTolerantRedisCluster rateLimitersCluster = new FaultTolerantRedisCluster("rate_limiters",
|
||||
configuration.getRateLimitersCluster(), redisClusterClientResources);
|
||||
SecureBackupClient secureBackupClient = new SecureBackupClient(backupCredentialsGenerator, backupServiceExecutor,
|
||||
configuration.getSecureBackupServiceConfiguration());
|
||||
SecureStorageClient secureStorageClient = new SecureStorageClient(storageCredentialsGenerator,
|
||||
storageServiceExecutor, configuration.getSecureStorageServiceConfiguration());
|
||||
ClientPresenceManager clientPresenceManager = new ClientPresenceManager(clientPresenceCluster,
|
||||
Executors.newSingleThreadScheduledExecutor(), keyspaceNotificationDispatchExecutor);
|
||||
MessagesCache messagesCache = new MessagesCache(messageInsertCacheCluster, messageReadDeleteCluster,
|
||||
Clock.systemUTC(), keyspaceNotificationDispatchExecutor, messageDeletionExecutor);
|
||||
DirectoryQueue directoryQueue = new DirectoryQueue(
|
||||
configuration.getDirectoryConfiguration().getSqsConfiguration());
|
||||
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster);
|
||||
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getReportMessage().getTableName(),
|
||||
configuration.getReportMessageConfiguration().getReportTtl());
|
||||
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster,
|
||||
configuration.getReportMessageConfiguration().getCounterTtl());
|
||||
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache,
|
||||
reportMessageManager, messageDeletionExecutor);
|
||||
DeletedAccountsManager deletedAccountsManager = new DeletedAccountsManager(deletedAccounts,
|
||||
deletedAccountsLockDynamoDbClient,
|
||||
configuration.getDynamoDbTables().getDeletedAccountsLock().getTableName());
|
||||
StoredVerificationCodeManager pendingAccountsManager = new StoredVerificationCodeManager(pendingAccounts);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
deletedAccountsManager, directoryQueue, keys, messagesManager, profilesManager,
|
||||
pendingAccountsManager, secureStorageClient, secureBackupClient, clientPresenceManager,
|
||||
experimentEnrollmentManager, registrationRecoveryPasswordsManager, clock);
|
||||
AccountsManager accountsManager = deps.accountsManager();
|
||||
|
||||
for (String user : users) {
|
||||
Optional<Account> account = accountsManager.getByE164(user);
|
||||
|
||||
+2
-157
@@ -5,58 +5,17 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.amazonaws.ClientConfiguration;
|
||||
import com.amazonaws.auth.InstanceProfileCredentialsProvider;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import io.dropwizard.Application;
|
||||
import io.dropwizard.cli.EnvironmentCommand;
|
||||
import io.dropwizard.setup.Environment;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
import java.time.Clock;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureBackupController;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.securebackup.SecureBackupClient;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.sqs.DirectoryQueue;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Accounts;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DeletedAccounts;
|
||||
import org.whispersystems.textsecuregcm.storage.DeletedAccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Keys;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesCache;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.Profiles;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ProhibitedUsernames;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswords;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
|
||||
import org.whispersystems.textsecuregcm.storage.StoredVerificationCodeManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationCodeStore;
|
||||
import org.whispersystems.textsecuregcm.util.DynamoDbFromConfig;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
|
||||
public class SetUserDiscoverabilityCommand extends EnvironmentCommand<WhisperServerConfiguration> {
|
||||
|
||||
@@ -92,124 +51,10 @@ public class SetUserDiscoverabilityCommand extends EnvironmentCommand<WhisperSer
|
||||
final WhisperServerConfiguration configuration) throws Exception {
|
||||
|
||||
try {
|
||||
Clock clock = Clock.systemUTC();
|
||||
environment.getObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
|
||||
ClientResources redisClusterClientResources = ClientResources.builder().build();
|
||||
|
||||
FaultTolerantRedisCluster cacheCluster = new FaultTolerantRedisCluster("main_cache_cluster",
|
||||
configuration.getCacheClusterConfiguration(), redisClusterClientResources);
|
||||
FaultTolerantRedisCluster rateLimitersCluster = new FaultTolerantRedisCluster("rate_limiters",
|
||||
configuration.getRateLimitersCluster(), redisClusterClientResources);
|
||||
|
||||
ExecutorService keyspaceNotificationDispatchExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "keyspaceNotification-%d")).maxThreads(4).build();
|
||||
ExecutorService messageDeletionExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "messageDeletion-%d")).maxThreads(4).build();
|
||||
ExecutorService backupServiceExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "backupService-%d")).maxThreads(8).minThreads(1).build();
|
||||
ExecutorService storageServiceExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "storageService-%d")).maxThreads(8).minThreads(1).build();
|
||||
|
||||
ExternalServiceCredentialsGenerator backupCredentialsGenerator = SecureBackupController.credentialsGenerator(
|
||||
configuration.getSecureBackupServiceConfiguration());
|
||||
ExternalServiceCredentialsGenerator storageCredentialsGenerator = SecureStorageController.credentialsGenerator(
|
||||
configuration.getSecureStorageServiceConfiguration());
|
||||
|
||||
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = new DynamicConfigurationManager<>(
|
||||
configuration.getAppConfig().getApplication(), configuration.getAppConfig().getEnvironment(),
|
||||
configuration.getAppConfig().getConfigurationName(), DynamicConfiguration.class);
|
||||
dynamicConfigurationManager.start();
|
||||
|
||||
ExperimentEnrollmentManager experimentEnrollmentManager = new ExperimentEnrollmentManager(
|
||||
dynamicConfigurationManager);
|
||||
|
||||
DynamoDbAsyncClient dynamoDbAsyncClient = DynamoDbFromConfig.asyncClient(
|
||||
configuration.getDynamoDbClientConfiguration(),
|
||||
software.amazon.awssdk.auth.credentials.InstanceProfileCredentialsProvider.create());
|
||||
|
||||
DynamoDbClient dynamoDbClient = DynamoDbFromConfig.client(
|
||||
configuration.getDynamoDbClientConfiguration(),
|
||||
software.amazon.awssdk.auth.credentials.InstanceProfileCredentialsProvider.create());
|
||||
|
||||
AmazonDynamoDB deletedAccountsLockDynamoDbClient = AmazonDynamoDBClientBuilder.standard()
|
||||
.withRegion(configuration.getDynamoDbClientConfiguration().getRegion())
|
||||
.withClientConfiguration(new ClientConfiguration().withClientExecutionTimeout(
|
||||
((int) configuration.getDynamoDbClientConfiguration().getClientExecutionTimeout()
|
||||
.toMillis()))
|
||||
.withRequestTimeout(
|
||||
(int) configuration.getDynamoDbClientConfiguration().getClientRequestTimeout()
|
||||
.toMillis()))
|
||||
.withCredentials(InstanceProfileCredentialsProvider.getInstance())
|
||||
.build();
|
||||
|
||||
DeletedAccounts deletedAccounts = new DeletedAccounts(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getDeletedAccounts().getTableName(),
|
||||
configuration.getDynamoDbTables().getDeletedAccounts().getNeedsReconciliationIndexName());
|
||||
VerificationCodeStore pendingAccounts = new VerificationCodeStore(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getPendingAccounts().getTableName());
|
||||
RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
|
||||
configuration.getDynamoDbTables().getRegistrationRecovery().getTableName(),
|
||||
configuration.getDynamoDbTables().getRegistrationRecovery().getExpiration(),
|
||||
dynamoDbClient,
|
||||
dynamoDbAsyncClient
|
||||
);
|
||||
|
||||
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager = new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords);
|
||||
|
||||
Accounts accounts = new Accounts(
|
||||
dynamoDbClient,
|
||||
dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getAccounts().getTableName(),
|
||||
configuration.getDynamoDbTables().getAccounts().getPhoneNumberTableName(),
|
||||
configuration.getDynamoDbTables().getAccounts().getPhoneNumberIdentifierTableName(),
|
||||
configuration.getDynamoDbTables().getAccounts().getUsernamesTableName(),
|
||||
configuration.getDynamoDbTables().getAccounts().getScanPageSize());
|
||||
PhoneNumberIdentifiers phoneNumberIdentifiers = new PhoneNumberIdentifiers(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getPhoneNumberIdentifiers().getTableName());
|
||||
Profiles profiles = new Profiles(dynamoDbClient, dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getProfiles().getTableName());
|
||||
ProhibitedUsernames prohibitedUsernames = new ProhibitedUsernames(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getReservedUsernames().getTableName());
|
||||
Keys keys = new Keys(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getKeys().getTableName());
|
||||
MessagesDynamoDb messagesDynamoDb = new MessagesDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getMessages().getTableName(),
|
||||
configuration.getDynamoDbTables().getMessages().getExpiration(),
|
||||
messageDeletionExecutor);
|
||||
FaultTolerantRedisCluster messageInsertCacheCluster = new FaultTolerantRedisCluster("message_insert_cluster",
|
||||
configuration.getMessageCacheConfiguration().getRedisClusterConfiguration(), redisClusterClientResources);
|
||||
FaultTolerantRedisCluster messageReadDeleteCluster = new FaultTolerantRedisCluster("message_read_delete_cluster",
|
||||
configuration.getMessageCacheConfiguration().getRedisClusterConfiguration(), redisClusterClientResources);
|
||||
FaultTolerantRedisCluster clientPresenceCluster = new FaultTolerantRedisCluster("client_presence",
|
||||
configuration.getClientPresenceClusterConfiguration(), redisClusterClientResources);
|
||||
SecureBackupClient secureBackupClient = new SecureBackupClient(backupCredentialsGenerator, backupServiceExecutor,
|
||||
configuration.getSecureBackupServiceConfiguration());
|
||||
SecureStorageClient secureStorageClient = new SecureStorageClient(storageCredentialsGenerator,
|
||||
storageServiceExecutor, configuration.getSecureStorageServiceConfiguration());
|
||||
ClientPresenceManager clientPresenceManager = new ClientPresenceManager(clientPresenceCluster,
|
||||
Executors.newSingleThreadScheduledExecutor(), keyspaceNotificationDispatchExecutor);
|
||||
MessagesCache messagesCache = new MessagesCache(messageInsertCacheCluster, messageReadDeleteCluster,
|
||||
Clock.systemUTC(), keyspaceNotificationDispatchExecutor, messageDeletionExecutor);
|
||||
DirectoryQueue directoryQueue = new DirectoryQueue(
|
||||
configuration.getDirectoryConfiguration().getSqsConfiguration());
|
||||
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster);
|
||||
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getReportMessage().getTableName(),
|
||||
configuration.getReportMessageConfiguration().getReportTtl());
|
||||
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster,
|
||||
configuration.getReportMessageConfiguration().getCounterTtl());
|
||||
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache,
|
||||
reportMessageManager, messageDeletionExecutor);
|
||||
DeletedAccountsManager deletedAccountsManager = new DeletedAccountsManager(deletedAccounts,
|
||||
deletedAccountsLockDynamoDbClient,
|
||||
configuration.getDynamoDbTables().getDeletedAccountsLock().getTableName());
|
||||
StoredVerificationCodeManager pendingAccountsManager = new StoredVerificationCodeManager(pendingAccounts);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
deletedAccountsManager, directoryQueue, keys, messagesManager, profilesManager,
|
||||
pendingAccountsManager, secureStorageClient, secureBackupClient, clientPresenceManager,
|
||||
experimentEnrollmentManager, registrationRecoveryPasswordsManager, clock);
|
||||
|
||||
final CommandDependencies deps = CommandDependencies.build("set-discoverability", environment, configuration);
|
||||
final AccountsManager accountsManager = deps.accountsManager();
|
||||
Optional<Account> maybeAccount;
|
||||
|
||||
try {
|
||||
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import io.dropwizard.Application;
|
||||
import io.dropwizard.cli.EnvironmentCommand;
|
||||
import io.dropwizard.setup.Environment;
|
||||
import java.util.UUID;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
|
||||
public class UnlinkDeviceCommand extends EnvironmentCommand<WhisperServerConfiguration> {
|
||||
|
||||
public UnlinkDeviceCommand() {
|
||||
super(new Application<>() {
|
||||
@Override
|
||||
public void run(WhisperServerConfiguration configuration, Environment environment) {
|
||||
|
||||
}
|
||||
}, "unlink-device", "Unlink a device and clear messages");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(final Subparser subparser) {
|
||||
super.configure(subparser);
|
||||
|
||||
subparser.addArgument("-d", "--deviceId")
|
||||
.dest("deviceId")
|
||||
.type(Long.class)
|
||||
.required(true);
|
||||
|
||||
subparser.addArgument("-u", "--uuid")
|
||||
.help("the UUID of the account to modify")
|
||||
.dest("uuid")
|
||||
.type(String.class)
|
||||
.required(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void run(final Environment environment, final Namespace namespace,
|
||||
final WhisperServerConfiguration configuration) throws Exception {
|
||||
environment.getObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
|
||||
final UUID aci = UUID.fromString(namespace.getString("uuid").trim());
|
||||
final long deviceId = namespace.getLong("deviceId");
|
||||
|
||||
final CommandDependencies deps = CommandDependencies.build("unlink-device", environment, configuration);
|
||||
|
||||
Account account = deps.accountsManager().getByAccountIdentifier(aci)
|
||||
.orElseThrow(() -> new IllegalArgumentException("account id " + aci +" does not exist"));
|
||||
|
||||
if (deviceId == Device.MASTER_ID) {
|
||||
throw new IllegalArgumentException("cannot delete primary device");
|
||||
}
|
||||
|
||||
/** see {@link org.whispersystems.textsecuregcm.controllers.DeviceController#removeDevice} */
|
||||
System.out.format("Removing device %s::%d\n", aci, deviceId);
|
||||
account = deps.accountsManager().update(account, a -> a.removeDevice(deviceId));
|
||||
|
||||
System.out.format("Removing keys for device %s::%d\n", aci, deviceId);
|
||||
deps.keys().delete(account.getUuid(), deviceId);
|
||||
|
||||
System.out.format("Clearing additional messages for %s::%d\n", aci, deviceId);
|
||||
deps.messagesManager().clear(account.getUuid(), deviceId);
|
||||
|
||||
System.out.format("Clearing presence state for %s::%d\n", aci, deviceId);
|
||||
deps.clientPresenceManager().disconnectPresence(aci, deviceId);
|
||||
|
||||
System.out.format("Device %s::%d successfully removed\n", aci, deviceId);
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,8 @@ service RegistrationService {
|
||||
* session.
|
||||
*/
|
||||
rpc check_verification_code (CheckVerificationCodeRequest) returns (CheckVerificationCodeResponse) {}
|
||||
|
||||
rpc legacy_check_verification_code (CheckVerificationCodeRequest) returns (LegacyCheckVerificationCodeResponse) {}
|
||||
}
|
||||
|
||||
message CreateRegistrationSessionRequest {
|
||||
@@ -33,6 +35,12 @@ message CreateRegistrationSessionRequest {
|
||||
* The phone number for which to create a new registration session.
|
||||
*/
|
||||
uint64 e164 = 1;
|
||||
|
||||
/**
|
||||
* Indicates whether an account already exists with the given e164 (i.e. this
|
||||
* session represents a "re-registration" attempt).
|
||||
*/
|
||||
bool account_exists_with_e164 = 2;
|
||||
}
|
||||
|
||||
message CreateRegistrationSessionResponse {
|
||||
@@ -343,6 +351,20 @@ message CheckVerificationCodeResponse {
|
||||
CheckVerificationCodeError error = 3;
|
||||
}
|
||||
|
||||
message LegacyCheckVerificationCodeResponse {
|
||||
/**
|
||||
* Indicates whether the verification code given in the request that produced
|
||||
* this response was correct.
|
||||
*/
|
||||
bool verified = 1;
|
||||
|
||||
/**
|
||||
* If a code could not be checked, explains the underlying error. Will be
|
||||
* absent if no error occurred.
|
||||
*/
|
||||
CheckVerificationCodeError error = 2;
|
||||
}
|
||||
|
||||
message CheckVerificationCodeError {
|
||||
/**
|
||||
* The type of error that prevented a verification code from being checked.
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
-- The script encapsulates the logic of a token bucket rate limiter.
|
||||
-- Two types of operations are supported: 'check-only' and 'use-if-available' (controlled by the 'useTokens' arg).
|
||||
-- Both operations take in rate limiter configuration parameters and the requested amount of tokens.
|
||||
-- Both operations return 0, if the rate limiter has enough tokens to cover the requested amount,
|
||||
-- and the deficit amount otherwise.
|
||||
-- However, 'check-only' operation doesn't modify the bucket, while 'use-if-available' (if successful)
|
||||
-- reduces the amount of available tokens by the requested amount.
|
||||
|
||||
local bucketId = KEYS[1]
|
||||
|
||||
local bucketSize = tonumber(ARGV[1])
|
||||
local refillRatePerMillis = tonumber(ARGV[2])
|
||||
local currentTimeMillis = tonumber(ARGV[3])
|
||||
local requestedAmount = tonumber(ARGV[4])
|
||||
local useTokens = ARGV[5] and string.lower(ARGV[5]) == "true"
|
||||
|
||||
local SIZE_FIELD = "s"
|
||||
local TIME_FIELD = "t"
|
||||
|
||||
local changesMade = false
|
||||
local tokensRemaining
|
||||
local lastUpdateTimeMillis
|
||||
|
||||
-- while we're migrating from json to redis list key types, there are three possible options for the
|
||||
-- type of the `bucketId` key: "string" (legacy, json value), "list" (new format), "none" (key not set).
|
||||
--
|
||||
-- On a separate note -- the reason we're not using a different key is because Redis Lua requires to list all keys
|
||||
-- as a script input and we don't want to expose this migration to the script users.
|
||||
--
|
||||
-- Finally, it's okay to read the "ok" key of the return here because "TYPE" command always succeeds.
|
||||
local keyType = redis.call("TYPE", bucketId)["ok"]
|
||||
if keyType == "none" then
|
||||
-- if the key is not set, building the object from the configuration
|
||||
tokensRemaining = bucketSize
|
||||
lastUpdateTimeMillis = currentTimeMillis
|
||||
elseif keyType == "string" then
|
||||
-- if the key is "string", we parse the value from json
|
||||
local fromJson = cjson.decode(redis.call("GET", bucketId))
|
||||
tokensRemaining = fromJson.spaceRemaining
|
||||
lastUpdateTimeMillis = fromJson.lastUpdateTimeMillis
|
||||
redis.call("DEL", bucketId)
|
||||
changesMade = true
|
||||
elseif keyType == "hash" then
|
||||
-- finally, reading values from the new storage format
|
||||
local tokensRemainingStr, lastUpdateTimeMillisStr = unpack(redis.call("HMGET", bucketId, SIZE_FIELD, TIME_FIELD))
|
||||
tokensRemaining = tonumber(tokensRemainingStr)
|
||||
lastUpdateTimeMillis = tonumber(lastUpdateTimeMillisStr)
|
||||
end
|
||||
|
||||
local elapsedTime = currentTimeMillis - lastUpdateTimeMillis
|
||||
local availableAmount = math.min(
|
||||
bucketSize,
|
||||
math.floor(tokensRemaining + (elapsedTime * refillRatePerMillis))
|
||||
)
|
||||
|
||||
if availableAmount >= requestedAmount then
|
||||
if useTokens then
|
||||
tokensRemaining = availableAmount - requestedAmount
|
||||
lastUpdateTimeMillis = currentTimeMillis
|
||||
changesMade = true
|
||||
end
|
||||
if changesMade then
|
||||
local tokensUsed = bucketSize - tokensRemaining
|
||||
-- Storing a 'full' bucket (i.e. tokensUsed == 0) is equivalent of not storing any state at all
|
||||
-- (in which case a bucket will be just initialized from the input configs as a 'full' one).
|
||||
-- For this reason, we either set an expiration time on the record (calculated to let the bucket fully replenish)
|
||||
-- or we just delete the key if the bucket is full.
|
||||
if tokensUsed > 0 then
|
||||
local ttlMillis = math.ceil(tokensUsed / refillRatePerMillis)
|
||||
redis.call("HSET", bucketId, SIZE_FIELD, tokensRemaining, TIME_FIELD, lastUpdateTimeMillis)
|
||||
redis.call("PEXPIRE", bucketId, ttlMillis)
|
||||
else
|
||||
redis.call("DEL", bucketId)
|
||||
end
|
||||
end
|
||||
return 0
|
||||
else
|
||||
return requestedAmount - availableAmount
|
||||
end
|
||||
+17
-10
@@ -26,6 +26,7 @@ import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
@@ -65,7 +66,7 @@ class RegistrationLockVerificationManagerTest {
|
||||
@EnumSource
|
||||
void testErrors(RegistrationLockError error) throws Exception {
|
||||
|
||||
when(existingRegistrationLock.requiresClientRegistrationLock()).thenReturn(true);
|
||||
when(existingRegistrationLock.getStatus()).thenReturn(StoredRegistrationLock.Status.REQUIRED);
|
||||
|
||||
final String submittedRegistrationLock = "reglock";
|
||||
|
||||
@@ -89,29 +90,35 @@ class RegistrationLockVerificationManagerTest {
|
||||
};
|
||||
|
||||
final Exception e = assertThrows(exceptionType.first(), () ->
|
||||
registrationLockVerificationManager.verifyRegistrationLock(account, submittedRegistrationLock));
|
||||
registrationLockVerificationManager.verifyRegistrationLock(account, submittedRegistrationLock,
|
||||
"Signal-Android/4.68.3", RegistrationLockVerificationManager.Flow.REGISTRATION,
|
||||
PhoneVerificationRequest.VerificationType.SESSION));
|
||||
|
||||
exceptionType.second().accept(e);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void testSuccess(final boolean requiresClientRegistrationLock, @Nullable final String submittedRegistrationLock) {
|
||||
void testSuccess(final StoredRegistrationLock.Status status, @Nullable final String submittedRegistrationLock) {
|
||||
|
||||
when(existingRegistrationLock.requiresClientRegistrationLock())
|
||||
.thenReturn(requiresClientRegistrationLock);
|
||||
when(existingRegistrationLock.getStatus())
|
||||
.thenReturn(status);
|
||||
when(existingRegistrationLock.verify(submittedRegistrationLock)).thenReturn(true);
|
||||
|
||||
assertDoesNotThrow(
|
||||
() -> registrationLockVerificationManager.verifyRegistrationLock(account, submittedRegistrationLock));
|
||||
() -> registrationLockVerificationManager.verifyRegistrationLock(account, submittedRegistrationLock,
|
||||
"Signal-Android/4.68.3", RegistrationLockVerificationManager.Flow.REGISTRATION,
|
||||
PhoneVerificationRequest.VerificationType.SESSION));
|
||||
}
|
||||
|
||||
static Stream<Arguments> testSuccess() {
|
||||
return Stream.of(
|
||||
Arguments.of(false, null),
|
||||
Arguments.of(true, null),
|
||||
Arguments.of(false, "reglock"),
|
||||
Arguments.of(true, "reglock")
|
||||
Arguments.of(StoredRegistrationLock.Status.ABSENT, null),
|
||||
Arguments.of(StoredRegistrationLock.Status.EXPIRED, null),
|
||||
Arguments.of(StoredRegistrationLock.Status.REQUIRED, null),
|
||||
Arguments.of(StoredRegistrationLock.Status.ABSENT, "reglock"),
|
||||
Arguments.of(StoredRegistrationLock.Status.EXPIRED, "reglock"),
|
||||
Arguments.of(StoredRegistrationLock.Status.REQUIRED, "reglock")
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import javax.swing.text.html.Option;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.whispersystems.textsecuregcm.auth.StoredRegistrationLock.REGISTRATION_LOCK_EXPIRATION_DAYS;
|
||||
|
||||
public class StoredRegistrationLockTest {
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void getStatus(final Optional<String> registrationLock, final Optional<String> salt, final long lastSeen,
|
||||
final StoredRegistrationLock.Status expectedStatus) {
|
||||
final StoredRegistrationLock storedLock = new StoredRegistrationLock(registrationLock, salt, Instant.ofEpochMilli(lastSeen));
|
||||
|
||||
assertEquals(expectedStatus, storedLock.getStatus());
|
||||
}
|
||||
|
||||
private static Stream<Arguments> getStatus() {
|
||||
return Stream.of(
|
||||
Arguments.of(Optional.of("registrationLock"), Optional.of("salt"), System.currentTimeMillis() - Duration.ofDays(1).toMillis(), StoredRegistrationLock.Status.REQUIRED),
|
||||
Arguments.of(Optional.empty(), Optional.empty(), 0L, StoredRegistrationLock.Status.ABSENT),
|
||||
Arguments.of(Optional.of("registrationLock"), Optional.of("salt"), System.currentTimeMillis() - REGISTRATION_LOCK_EXPIRATION_DAYS.toMillis(), StoredRegistrationLock.Status.EXPIRED)
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
+42
-25
@@ -16,9 +16,9 @@ import static org.mockito.Mockito.when;
|
||||
import static org.whispersystems.textsecuregcm.captcha.CaptchaChecker.SEPARATOR;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.ws.rs.BadRequestException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
@@ -27,7 +27,8 @@ import org.junit.jupiter.params.provider.MethodSource;
|
||||
|
||||
public class CaptchaCheckerTest {
|
||||
|
||||
private static final String SITE_KEY = "site-key";
|
||||
private static final String CHALLENGE_SITE_KEY = "challenge-site-key";
|
||||
private static final String REG_SITE_KEY = "registration-site-key";
|
||||
private static final String TOKEN = "some-token";
|
||||
private static final String PREFIX = "prefix";
|
||||
private static final String PREFIX_A = "prefix-a";
|
||||
@@ -36,26 +37,33 @@ public class CaptchaCheckerTest {
|
||||
static Stream<Arguments> parseInputToken() {
|
||||
return Stream.of(
|
||||
Arguments.of(
|
||||
String.join(SEPARATOR, PREFIX, SITE_KEY, TOKEN),
|
||||
String.join(SEPARATOR, PREFIX, CHALLENGE_SITE_KEY, "challenge", TOKEN),
|
||||
TOKEN,
|
||||
SITE_KEY,
|
||||
null),
|
||||
CHALLENGE_SITE_KEY,
|
||||
Action.CHALLENGE),
|
||||
Arguments.of(
|
||||
String.join(SEPARATOR, PREFIX, SITE_KEY, "an-action", TOKEN),
|
||||
String.join(SEPARATOR, PREFIX, REG_SITE_KEY, "registration", TOKEN),
|
||||
TOKEN,
|
||||
SITE_KEY,
|
||||
"an-action"),
|
||||
REG_SITE_KEY,
|
||||
Action.REGISTRATION),
|
||||
Arguments.of(
|
||||
String.join(SEPARATOR, PREFIX, SITE_KEY, "an-action", TOKEN, "something-else"),
|
||||
String.join(SEPARATOR, PREFIX, CHALLENGE_SITE_KEY, "challenge", TOKEN, "something-else"),
|
||||
TOKEN + SEPARATOR + "something-else",
|
||||
SITE_KEY,
|
||||
"an-action")
|
||||
CHALLENGE_SITE_KEY,
|
||||
Action.CHALLENGE),
|
||||
Arguments.of(
|
||||
String.join(SEPARATOR, PREFIX, CHALLENGE_SITE_KEY, "ChAlLeNgE", TOKEN),
|
||||
TOKEN,
|
||||
CHALLENGE_SITE_KEY,
|
||||
Action.CHALLENGE)
|
||||
);
|
||||
}
|
||||
|
||||
private static CaptchaClient mockClient(final String prefix) throws IOException {
|
||||
final CaptchaClient captchaClient = mock(CaptchaClient.class);
|
||||
when(captchaClient.scheme()).thenReturn(prefix);
|
||||
when(captchaClient.validSiteKeys(eq(Action.CHALLENGE))).thenReturn(Collections.singleton(CHALLENGE_SITE_KEY));
|
||||
when(captchaClient.validSiteKeys(eq(Action.REGISTRATION))).thenReturn(Collections.singleton(REG_SITE_KEY));
|
||||
when(captchaClient.verify(any(), any(), any(), any())).thenReturn(AssessmentResult.invalid());
|
||||
return captchaClient;
|
||||
}
|
||||
@@ -63,17 +71,20 @@ public class CaptchaCheckerTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void parseInputToken(final String input, final String expectedToken, final String siteKey,
|
||||
@Nullable final String expectedAction) throws IOException {
|
||||
void parseInputToken(
|
||||
final String input,
|
||||
final String expectedToken,
|
||||
final String siteKey,
|
||||
final Action expectedAction) throws IOException {
|
||||
final CaptchaClient captchaClient = mockClient(PREFIX);
|
||||
new CaptchaChecker(List.of(captchaClient)).verify(input, null);
|
||||
new CaptchaChecker(List.of(captchaClient)).verify(expectedAction, input, null);
|
||||
verify(captchaClient, times(1)).verify(eq(siteKey), eq(expectedAction), eq(expectedToken), any());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void scoreString(float score, String expected) {
|
||||
assertThat(AssessmentResult.scoreString(score)).isEqualTo(expected);
|
||||
assertThat(AssessmentResult.fromScore(score, 0.0f).getScoreString()).isEqualTo(expected);
|
||||
}
|
||||
|
||||
|
||||
@@ -89,31 +100,37 @@ public class CaptchaCheckerTest {
|
||||
|
||||
@Test
|
||||
public void choose() throws IOException {
|
||||
String ainput = String.join(SEPARATOR, PREFIX_A, SITE_KEY, TOKEN);
|
||||
String binput = String.join(SEPARATOR, PREFIX_B, SITE_KEY, TOKEN);
|
||||
String ainput = String.join(SEPARATOR, PREFIX_A, CHALLENGE_SITE_KEY, "challenge", TOKEN);
|
||||
String binput = String.join(SEPARATOR, PREFIX_B, CHALLENGE_SITE_KEY, "challenge", TOKEN);
|
||||
final CaptchaClient a = mockClient(PREFIX_A);
|
||||
final CaptchaClient b = mockClient(PREFIX_B);
|
||||
|
||||
new CaptchaChecker(List.of(a, b)).verify(ainput, null);
|
||||
new CaptchaChecker(List.of(a, b)).verify(Action.CHALLENGE, ainput, null);
|
||||
verify(a, times(1)).verify(any(), any(), any(), any());
|
||||
|
||||
new CaptchaChecker(List.of(a, b)).verify(binput, null);
|
||||
new CaptchaChecker(List.of(a, b)).verify(Action.CHALLENGE, binput, null);
|
||||
verify(b, times(1)).verify(any(), any(), any(), any());
|
||||
}
|
||||
|
||||
static Stream<Arguments> badToken() {
|
||||
static Stream<Arguments> badArgs() {
|
||||
return Stream.of(
|
||||
Arguments.of(String.join(SEPARATOR, "invalid", SITE_KEY, "action", TOKEN)),
|
||||
Arguments.of(String.join(SEPARATOR, PREFIX, TOKEN)),
|
||||
Arguments.of(String.join(SEPARATOR, SITE_KEY, PREFIX, "action", TOKEN))
|
||||
Arguments.of(String.join(SEPARATOR, "invalid", CHALLENGE_SITE_KEY, "challenge", TOKEN)), // bad prefix
|
||||
Arguments.of(String.join(SEPARATOR, PREFIX, "challenge", TOKEN)), // no site key
|
||||
Arguments.of(String.join(SEPARATOR, CHALLENGE_SITE_KEY, PREFIX, "challenge", TOKEN)), // incorrect order
|
||||
Arguments.of(String.join(SEPARATOR, PREFIX, CHALLENGE_SITE_KEY, "unknown_action", TOKEN)), // bad action
|
||||
Arguments.of(String.join(SEPARATOR, PREFIX, CHALLENGE_SITE_KEY, "registration", TOKEN)), // action mismatch
|
||||
Arguments.of(String.join(SEPARATOR, PREFIX, "bad-site-key", "challenge", TOKEN)), // invalid site key
|
||||
Arguments.of(String.join(SEPARATOR, PREFIX, CHALLENGE_SITE_KEY, "registration", TOKEN)), // site key for wrong type
|
||||
Arguments.of(String.join(SEPARATOR, PREFIX, REG_SITE_KEY, "challenge", TOKEN)) // site key for wrong type
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
public void badToken(final String input) throws IOException {
|
||||
public void badArgs(final String input) throws IOException {
|
||||
final CaptchaClient cc = mockClient(PREFIX);
|
||||
assertThrows(BadRequestException.class, () -> new CaptchaChecker(List.of(cc)).verify(input, null));
|
||||
assertThrows(BadRequestException.class,
|
||||
() -> new CaptchaChecker(List.of(cc)).verify(Action.CHALLENGE, input, null));
|
||||
|
||||
}
|
||||
}
|
||||
+28
-11
@@ -2,6 +2,7 @@ package org.whispersystems.textsecuregcm.captcha;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -10,6 +11,10 @@ import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
@@ -49,12 +54,11 @@ public class HCaptchaClientTest {
|
||||
success, 1 - score)); // hCaptcha scores are inverted compared to recaptcha scores. (low score is good)
|
||||
|
||||
final AssessmentResult result = new HCaptchaClient("fake", client, mockConfig(true, 0.5))
|
||||
.verify(SITE_KEY, "whatever", TOKEN, null);
|
||||
.verify(SITE_KEY, Action.CHALLENGE, TOKEN, null);
|
||||
if (!success) {
|
||||
assertThat(result).isEqualTo(AssessmentResult.invalid());
|
||||
} else {
|
||||
assertThat(result)
|
||||
.isEqualTo(new AssessmentResult(expectedResult, AssessmentResult.scoreString(score)));
|
||||
assertThat(result.isValid()).isEqualTo(expectedResult);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,31 +66,40 @@ public class HCaptchaClientTest {
|
||||
public void errorResponse() throws IOException, InterruptedException {
|
||||
final HttpClient httpClient = mockResponder(503, "");
|
||||
final HCaptchaClient client = new HCaptchaClient("fake", httpClient, mockConfig(true, 0.5));
|
||||
assertThrows(IOException.class, () -> client.verify(SITE_KEY, "whatever", TOKEN, null));
|
||||
assertThrows(IOException.class, () -> client.verify(SITE_KEY, Action.CHALLENGE, TOKEN, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invalidScore() throws IOException, InterruptedException {
|
||||
final HttpClient httpClient = mockResponder(200, """
|
||||
{"success" : true, "score": 1.1}
|
||||
""");
|
||||
{"success" : true, "score": 1.1}
|
||||
""");
|
||||
final HCaptchaClient client = new HCaptchaClient("fake", httpClient, mockConfig(true, 0.5));
|
||||
assertThat(client.verify(SITE_KEY, "whatever", TOKEN, null)).isEqualTo(AssessmentResult.invalid());
|
||||
assertThat(client.verify(SITE_KEY, Action.CHALLENGE, TOKEN, null)).isEqualTo(AssessmentResult.invalid());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void badBody() throws IOException, InterruptedException {
|
||||
final HttpClient httpClient = mockResponder(200, """
|
||||
{"success" : true,
|
||||
""");
|
||||
{"success" : true,
|
||||
""");
|
||||
final HCaptchaClient client = new HCaptchaClient("fake", httpClient, mockConfig(true, 0.5));
|
||||
assertThrows(IOException.class, () -> client.verify(SITE_KEY, "whatever", TOKEN, null));
|
||||
assertThrows(IOException.class, () -> client.verify(SITE_KEY, Action.CHALLENGE, TOKEN, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void disabled() throws IOException {
|
||||
final HCaptchaClient hc = new HCaptchaClient("fake", null, mockConfig(false, 0.5));
|
||||
assertThat(hc.verify(SITE_KEY, null, TOKEN, null)).isEqualTo(AssessmentResult.invalid());
|
||||
assertTrue(Arrays.stream(Action.values()).map(hc::validSiteKeys).allMatch(Set::isEmpty));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void badSiteKey() throws IOException {
|
||||
final HCaptchaClient hc = new HCaptchaClient("fake", null, mockConfig(true, 0.5));
|
||||
for (Action action : Action.values()) {
|
||||
assertThat(hc.validSiteKeys(action)).contains(SITE_KEY);
|
||||
assertThat(hc.validSiteKeys(action)).doesNotContain("invalid");
|
||||
}
|
||||
}
|
||||
|
||||
private static HttpClient mockResponder(final int statusCode, final String jsonBody)
|
||||
@@ -105,6 +118,10 @@ public class HCaptchaClientTest {
|
||||
final DynamicCaptchaConfiguration config = new DynamicCaptchaConfiguration();
|
||||
config.setAllowHCaptcha(enabled);
|
||||
config.setScoreFloor(BigDecimal.valueOf(scoreFloor));
|
||||
config.setHCaptchaSiteKeys(Map.of(
|
||||
Action.REGISTRATION, Collections.singleton(SITE_KEY),
|
||||
Action.CHALLENGE, Collections.singleton(SITE_KEY)
|
||||
));
|
||||
|
||||
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> m = mock(
|
||||
DynamicConfigurationManager.class);
|
||||
|
||||
+22
@@ -20,6 +20,7 @@ import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.captcha.Action;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiterConfig;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
@@ -262,6 +263,18 @@ class DynamicConfigurationTest {
|
||||
signupCountryCodes:
|
||||
- 1
|
||||
scoreFloor: 0.9
|
||||
scoreFloorByAction:
|
||||
challenge: 0.1
|
||||
registration: 0.2
|
||||
hCaptchaSiteKeys:
|
||||
challenge:
|
||||
- ab317f2a-2b76-4098-84c9-ecdf8ea44f53
|
||||
registration:
|
||||
- e4ddb6ff-05e7-497b-9a29-b76e7331789c
|
||||
- 52fdbc88-f246-4705-a7dd-05ad85b93420
|
||||
recaptchaSiteKeys:
|
||||
challenge:
|
||||
- 299068b6-ac78-4288-a90b-2e2ce5a6ddfe
|
||||
""";
|
||||
|
||||
final DynamicCaptchaConfiguration config =
|
||||
@@ -270,6 +283,15 @@ class DynamicConfigurationTest {
|
||||
|
||||
assertEquals(Set.of("1"), config.getSignupCountryCodes());
|
||||
assertEquals(0.9f, config.getScoreFloor().floatValue());
|
||||
assertEquals(0.1f, config.getScoreFloorByAction().get(Action.CHALLENGE).floatValue());
|
||||
assertEquals(0.2f, config.getScoreFloorByAction().get(Action.REGISTRATION).floatValue());
|
||||
|
||||
assertThat(config.getHCaptchaSiteKeys().get(Action.CHALLENGE)).contains("ab317f2a-2b76-4098-84c9-ecdf8ea44f53");
|
||||
assertThat(config.getHCaptchaSiteKeys().get(Action.REGISTRATION)).contains("e4ddb6ff-05e7-497b-9a29-b76e7331789c");
|
||||
assertThat(config.getHCaptchaSiteKeys().get(Action.REGISTRATION)).contains("52fdbc88-f246-4705-a7dd-05ad85b93420");
|
||||
|
||||
assertThat(config.getRecaptchaSiteKeys().get(Action.CHALLENGE)).contains("299068b6-ac78-4288-a90b-2e2ce5a6ddfe");
|
||||
assertThat(config.getRecaptchaSiteKeys().get(Action.REGISTRATION)).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+45
-38
@@ -9,6 +9,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
@@ -35,6 +36,7 @@ import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
@@ -72,6 +74,7 @@ import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.auth.StoredRegistrationLock;
|
||||
import org.whispersystems.textsecuregcm.auth.StoredVerificationCode;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
|
||||
import org.whispersystems.textsecuregcm.captcha.Action;
|
||||
import org.whispersystems.textsecuregcm.captcha.AssessmentResult;
|
||||
import org.whispersystems.textsecuregcm.captcha.CaptchaChecker;
|
||||
import org.whispersystems.textsecuregcm.captcha.RegistrationCaptchaManager;
|
||||
@@ -106,6 +109,8 @@ import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.registration.ClientType;
|
||||
import org.whispersystems.textsecuregcm.registration.MessageTransport;
|
||||
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
|
||||
import org.whispersystems.textsecuregcm.spam.Extract;
|
||||
import org.whispersystems.textsecuregcm.spam.ScoreThresholdProvider;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
|
||||
@@ -212,6 +217,7 @@ class AccountControllerTest {
|
||||
.addProvider(new ImpossiblePhoneNumberExceptionMapper())
|
||||
.addProvider(new NonNormalizedPhoneNumberExceptionMapper())
|
||||
.addProvider(new RateLimitByIpFilter(rateLimiters))
|
||||
.addProvider(ScoreThresholdProvider.ScoreThresholdFeature.class)
|
||||
.setMapper(SystemMapper.jsonMapper())
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addResource(new AccountController(pendingAccountsManager,
|
||||
@@ -255,22 +261,22 @@ class AccountControllerTest {
|
||||
|
||||
when(senderPinAccount.getLastSeen()).thenReturn(System.currentTimeMillis());
|
||||
when(senderPinAccount.getRegistrationLock()).thenReturn(
|
||||
new StoredRegistrationLock(Optional.empty(), Optional.empty(), System.currentTimeMillis()));
|
||||
new StoredRegistrationLock(Optional.empty(), Optional.empty(), Instant.ofEpochMilli(System.currentTimeMillis())));
|
||||
|
||||
when(senderHasStorage.getUuid()).thenReturn(UUID.randomUUID());
|
||||
when(senderHasStorage.isStorageSupported()).thenReturn(true);
|
||||
when(senderHasStorage.getRegistrationLock()).thenReturn(
|
||||
new StoredRegistrationLock(Optional.empty(), Optional.empty(), System.currentTimeMillis()));
|
||||
new StoredRegistrationLock(Optional.empty(), Optional.empty(), Instant.ofEpochMilli(System.currentTimeMillis())));
|
||||
|
||||
when(senderRegLockAccount.getRegistrationLock()).thenReturn(
|
||||
new StoredRegistrationLock(Optional.of(registrationLockCredentials.hash()),
|
||||
Optional.of(registrationLockCredentials.salt()), System.currentTimeMillis()));
|
||||
Optional.of(registrationLockCredentials.salt()), Instant.ofEpochMilli(System.currentTimeMillis())));
|
||||
when(senderRegLockAccount.getLastSeen()).thenReturn(System.currentTimeMillis());
|
||||
when(senderRegLockAccount.getUuid()).thenReturn(SENDER_REG_LOCK_UUID);
|
||||
when(senderRegLockAccount.getNumber()).thenReturn(SENDER_REG_LOCK);
|
||||
|
||||
when(senderTransfer.getRegistrationLock()).thenReturn(
|
||||
new StoredRegistrationLock(Optional.empty(), Optional.empty(), System.currentTimeMillis()));
|
||||
new StoredRegistrationLock(Optional.empty(), Optional.empty(), Instant.ofEpochMilli(System.currentTimeMillis())));
|
||||
when(senderTransfer.getUuid()).thenReturn(SENDER_TRANSFER_UUID);
|
||||
when(senderTransfer.getNumber()).thenReturn(SENDER_TRANSFER);
|
||||
|
||||
@@ -343,10 +349,10 @@ class AccountControllerTest {
|
||||
|
||||
when(dynamicConfiguration.getCaptchaConfiguration()).thenReturn(signupCaptchaConfig);
|
||||
}
|
||||
when(captchaChecker.verify(eq(INVALID_CAPTCHA_TOKEN), anyString()))
|
||||
when(captchaChecker.verify(eq(Action.REGISTRATION), eq(INVALID_CAPTCHA_TOKEN), anyString()))
|
||||
.thenReturn(AssessmentResult.invalid());
|
||||
when(captchaChecker.verify(eq(VALID_CAPTCHA_TOKEN), anyString()))
|
||||
.thenReturn(new AssessmentResult(true, ""));
|
||||
when(captchaChecker.verify(eq(Action.REGISTRATION), eq(VALID_CAPTCHA_TOKEN), anyString()))
|
||||
.thenReturn(AssessmentResult.alwaysValid());
|
||||
|
||||
doThrow(new RateLimitExceededException(Duration.ZERO, true)).when(pinLimiter).validate(eq(SENDER_OVER_PIN));
|
||||
|
||||
@@ -386,7 +392,7 @@ class AccountControllerTest {
|
||||
|
||||
@Test
|
||||
void testGetFcmPreauth() throws NumberParseException {
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyBoolean(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(new byte[16]));
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER)).thenReturn(Optional.empty());
|
||||
@@ -401,7 +407,7 @@ class AccountControllerTest {
|
||||
final ArgumentCaptor<String> challengeTokenCaptor = ArgumentCaptor.forClass(String.class);
|
||||
|
||||
verify(registrationServiceClient).createRegistrationSession(
|
||||
eq(PhoneNumberUtil.getInstance().parse(SENDER, null)), any());
|
||||
eq(PhoneNumberUtil.getInstance().parse(SENDER, null)), anyBoolean(), any());
|
||||
|
||||
verify(pushNotificationManager).sendRegistrationChallengeNotification(
|
||||
eq("mytoken"), eq(PushNotification.TokenType.FCM), challengeTokenCaptor.capture());
|
||||
@@ -411,7 +417,7 @@ class AccountControllerTest {
|
||||
|
||||
@Test
|
||||
void testGetFcmPreauthIvoryCoast() throws NumberParseException {
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyBoolean(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(new byte[16]));
|
||||
|
||||
Response response = resources.getJerseyTest()
|
||||
@@ -424,7 +430,7 @@ class AccountControllerTest {
|
||||
final ArgumentCaptor<String> challengeTokenCaptor = ArgumentCaptor.forClass(String.class);
|
||||
|
||||
verify(registrationServiceClient).createRegistrationSession(
|
||||
eq(PhoneNumberUtil.getInstance().parse("+2250707312345", null)), any());
|
||||
eq(PhoneNumberUtil.getInstance().parse("+2250707312345", null)), anyBoolean(), any());
|
||||
|
||||
verify(pushNotificationManager).sendRegistrationChallengeNotification(
|
||||
eq("mytoken"), eq(PushNotification.TokenType.FCM), challengeTokenCaptor.capture());
|
||||
@@ -434,7 +440,7 @@ class AccountControllerTest {
|
||||
|
||||
@Test
|
||||
void testGetApnPreauth() throws NumberParseException {
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyBoolean(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(new byte[16]));
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER)).thenReturn(Optional.empty());
|
||||
@@ -449,7 +455,7 @@ class AccountControllerTest {
|
||||
final ArgumentCaptor<String> challengeTokenCaptor = ArgumentCaptor.forClass(String.class);
|
||||
|
||||
verify(registrationServiceClient).createRegistrationSession(
|
||||
eq(PhoneNumberUtil.getInstance().parse(SENDER, null)), any());
|
||||
eq(PhoneNumberUtil.getInstance().parse(SENDER, null)), anyBoolean(), any());
|
||||
|
||||
verify(pushNotificationManager).sendRegistrationChallengeNotification(
|
||||
eq("mytoken"), eq(PushNotification.TokenType.APN_VOIP), challengeTokenCaptor.capture());
|
||||
@@ -459,7 +465,7 @@ class AccountControllerTest {
|
||||
|
||||
@Test
|
||||
void testGetApnPreauthExplicitVoip() throws NumberParseException {
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyBoolean(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(new byte[16]));
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER)).thenReturn(Optional.empty());
|
||||
@@ -475,7 +481,7 @@ class AccountControllerTest {
|
||||
final ArgumentCaptor<String> challengeTokenCaptor = ArgumentCaptor.forClass(String.class);
|
||||
|
||||
verify(registrationServiceClient).createRegistrationSession(
|
||||
eq(PhoneNumberUtil.getInstance().parse(SENDER, null)), any());
|
||||
eq(PhoneNumberUtil.getInstance().parse(SENDER, null)), anyBoolean(), any());
|
||||
|
||||
verify(pushNotificationManager).sendRegistrationChallengeNotification(
|
||||
eq("mytoken"), eq(PushNotification.TokenType.APN_VOIP), challengeTokenCaptor.capture());
|
||||
@@ -485,7 +491,7 @@ class AccountControllerTest {
|
||||
|
||||
@Test
|
||||
void testGetApnPreauthExplicitNoVoip() throws NumberParseException {
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyBoolean(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(new byte[16]));
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER)).thenReturn(Optional.empty());
|
||||
@@ -501,7 +507,7 @@ class AccountControllerTest {
|
||||
final ArgumentCaptor<String> challengeTokenCaptor = ArgumentCaptor.forClass(String.class);
|
||||
|
||||
verify(registrationServiceClient).createRegistrationSession(
|
||||
eq(PhoneNumberUtil.getInstance().parse(SENDER, null)), any());
|
||||
eq(PhoneNumberUtil.getInstance().parse(SENDER, null)), anyBoolean(), any());
|
||||
|
||||
verify(pushNotificationManager).sendRegistrationChallengeNotification(
|
||||
eq("mytoken"), eq(PushNotification.TokenType.APN), challengeTokenCaptor.capture());
|
||||
@@ -546,7 +552,7 @@ class AccountControllerTest {
|
||||
void testGetPreauthExistingSession() throws NumberParseException {
|
||||
final String existingPushCode = "existing-push-code";
|
||||
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyBoolean(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(new byte[16]));
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER)).thenReturn(
|
||||
@@ -561,7 +567,7 @@ class AccountControllerTest {
|
||||
|
||||
final ArgumentCaptor<String> challengeTokenCaptor = ArgumentCaptor.forClass(String.class);
|
||||
|
||||
verify(registrationServiceClient, never()).createRegistrationSession(any(), any());
|
||||
verify(registrationServiceClient, never()).createRegistrationSession(any(), anyBoolean(), any());
|
||||
|
||||
verify(pushNotificationManager).sendRegistrationChallengeNotification(
|
||||
eq("mytoken"), eq(PushNotification.TokenType.APN_VOIP), challengeTokenCaptor.capture());
|
||||
@@ -571,7 +577,7 @@ class AccountControllerTest {
|
||||
|
||||
@Test
|
||||
void testGetPreauthExistingSessionWithoutPushCode() throws NumberParseException {
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyBoolean(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(new byte[16]));
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER)).thenReturn(
|
||||
@@ -586,7 +592,7 @@ class AccountControllerTest {
|
||||
|
||||
final ArgumentCaptor<String> challengeTokenCaptor = ArgumentCaptor.forClass(String.class);
|
||||
|
||||
verify(registrationServiceClient, never()).createRegistrationSession(any(), any());
|
||||
verify(registrationServiceClient, never()).createRegistrationSession(any(), anyBoolean(), any());
|
||||
|
||||
verify(pushNotificationManager).sendRegistrationChallengeNotification(
|
||||
eq("mytoken"), eq(PushNotification.TokenType.APN_VOIP), challengeTokenCaptor.capture());
|
||||
@@ -624,7 +630,7 @@ class AccountControllerTest {
|
||||
void testSendCode() {
|
||||
final byte[] sessionId = "session-id".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyBoolean(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
when(registrationServiceClient.sendRegistrationCode(any(), any(), any(), any(), any()))
|
||||
@@ -648,7 +654,7 @@ class AccountControllerTest {
|
||||
|
||||
@Test
|
||||
void testSendCodeRateLimited() {
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyBoolean(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(new RateLimitExceededException(Duration.ofMinutes(10), true)));
|
||||
|
||||
Response response =
|
||||
@@ -687,6 +693,7 @@ class AccountControllerTest {
|
||||
final Response response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/sms/code/%s", number))
|
||||
.register(Extract.class)
|
||||
.queryParam("challenge", "1234-push")
|
||||
.request()
|
||||
.header(HttpHeaders.X_FORWARDED_FOR, NICE_HOST)
|
||||
@@ -709,7 +716,7 @@ class AccountControllerTest {
|
||||
when(registrationServiceClient.sendRegistrationCode(any(), any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyBoolean(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
Response response =
|
||||
@@ -732,7 +739,7 @@ class AccountControllerTest {
|
||||
when(registrationServiceClient.sendRegistrationCode(any(), any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyBoolean(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
Response response =
|
||||
@@ -785,7 +792,7 @@ class AccountControllerTest {
|
||||
when(registrationServiceClient.sendRegistrationCode(any(), any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyBoolean(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
Response response =
|
||||
@@ -809,7 +816,7 @@ class AccountControllerTest {
|
||||
when(registrationServiceClient.sendRegistrationCode(any(), any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyBoolean(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
Response response =
|
||||
@@ -834,7 +841,7 @@ class AccountControllerTest {
|
||||
when(registrationServiceClient.sendRegistrationCode(any(), any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyBoolean(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
Response response =
|
||||
@@ -847,7 +854,7 @@ class AccountControllerTest {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
|
||||
verify(captchaChecker).verify(eq(VALID_CAPTCHA_TOKEN), eq(NICE_HOST));
|
||||
verify(captchaChecker).verify(eq(Action.REGISTRATION), eq(VALID_CAPTCHA_TOKEN), eq(NICE_HOST));
|
||||
verify(registrationServiceClient).sendRegistrationCode(sessionId, MessageTransport.SMS, ClientType.UNKNOWN, null, AccountController.REGISTRATION_RPC_TIMEOUT);
|
||||
}
|
||||
|
||||
@@ -864,7 +871,7 @@ class AccountControllerTest {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(402);
|
||||
|
||||
verify(captchaChecker).verify(eq(INVALID_CAPTCHA_TOKEN), eq(NICE_HOST));
|
||||
verify(captchaChecker).verify(eq(Action.REGISTRATION), eq(INVALID_CAPTCHA_TOKEN), eq(NICE_HOST));
|
||||
verifyNoInteractions(registrationServiceClient);
|
||||
}
|
||||
|
||||
@@ -944,7 +951,7 @@ class AccountControllerTest {
|
||||
when(registrationServiceClient.sendRegistrationCode(any(), any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyBoolean(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
Response response =
|
||||
@@ -975,7 +982,7 @@ class AccountControllerTest {
|
||||
when(registrationServiceClient.sendRegistrationCode(any(), any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyBoolean(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
Response response =
|
||||
@@ -998,7 +1005,7 @@ class AccountControllerTest {
|
||||
when(registrationServiceClient.sendRegistrationCode(any(), any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyBoolean(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
Response response =
|
||||
@@ -1448,7 +1455,7 @@ class AccountControllerTest {
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
|
||||
final StoredRegistrationLock existingRegistrationLock = mock(StoredRegistrationLock.class);
|
||||
when(existingRegistrationLock.requiresClientRegistrationLock()).thenReturn(false);
|
||||
when(existingRegistrationLock.getStatus()).thenReturn(StoredRegistrationLock.Status.ABSENT);
|
||||
|
||||
final Account existingAccount = mock(Account.class);
|
||||
when(existingAccount.getNumber()).thenReturn(number);
|
||||
@@ -1482,7 +1489,7 @@ class AccountControllerTest {
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
|
||||
final StoredRegistrationLock existingRegistrationLock = mock(StoredRegistrationLock.class);
|
||||
when(existingRegistrationLock.requiresClientRegistrationLock()).thenReturn(true);
|
||||
when(existingRegistrationLock.getStatus()).thenReturn(StoredRegistrationLock.Status.REQUIRED);
|
||||
|
||||
final UUID existingUuid = UUID.randomUUID();
|
||||
final Account existingAccount = mock(Account.class);
|
||||
@@ -1521,7 +1528,7 @@ class AccountControllerTest {
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
|
||||
final StoredRegistrationLock existingRegistrationLock = mock(StoredRegistrationLock.class);
|
||||
when(existingRegistrationLock.requiresClientRegistrationLock()).thenReturn(true);
|
||||
when(existingRegistrationLock.getStatus()).thenReturn(StoredRegistrationLock.Status.REQUIRED);
|
||||
when(existingRegistrationLock.verify(anyString())).thenReturn(false);
|
||||
|
||||
UUID existingUuid = UUID.randomUUID();
|
||||
@@ -1561,7 +1568,7 @@ class AccountControllerTest {
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
|
||||
final StoredRegistrationLock existingRegistrationLock = mock(StoredRegistrationLock.class);
|
||||
when(existingRegistrationLock.requiresClientRegistrationLock()).thenReturn(true);
|
||||
when(existingRegistrationLock.getStatus()).thenReturn(StoredRegistrationLock.Status.REQUIRED);
|
||||
when(existingRegistrationLock.verify(reglock)).thenReturn(true);
|
||||
|
||||
final Account existingAccount = mock(Account.class);
|
||||
@@ -2092,7 +2099,7 @@ class AccountControllerTest {
|
||||
when(registrationServiceClient.sendRegistrationCode(any(), any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyBoolean(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
Response response =
|
||||
|
||||
+209
-6
@@ -8,6 +8,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.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
@@ -20,17 +21,25 @@ import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
import io.dropwizard.auth.PolymorphicAuthValueFactoryProvider;
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import io.dropwizard.testing.junit5.ResourceExtension;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
@@ -57,10 +66,13 @@ import org.whispersystems.textsecuregcm.auth.DisabledPermittedAuthenticatedAccou
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockError;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountDataReportResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ChangeNumberRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneNumberDiscoverabilityRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationServiceSession;
|
||||
import org.whispersystems.textsecuregcm.entities.SignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.mappers.ImpossiblePhoneNumberExceptionMapper;
|
||||
@@ -68,6 +80,7 @@ import org.whispersystems.textsecuregcm.mappers.NonNormalizedPhoneNumberExceptio
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
@@ -75,6 +88,7 @@ import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsMan
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
@ExtendWith(DropwizardExtensionsSupport.class)
|
||||
class AccountControllerV2Test {
|
||||
@@ -295,7 +309,7 @@ class AccountControllerV2Test {
|
||||
case RATE_LIMITED -> new RateLimitExceededException(null, true);
|
||||
};
|
||||
doThrow(e)
|
||||
.when(registrationLockVerificationManager).verifyRegistrationLock(any(), any());
|
||||
.when(registrationLockVerificationManager).verifyRegistrationLock(any(), any(), any(), any(), any());
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v2/accounts/number")
|
||||
@@ -441,14 +455,203 @@ class AccountControllerV2Test {
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.put(Entity.json(
|
||||
"""
|
||||
{
|
||||
"discoverableByPhoneNumber": null
|
||||
}
|
||||
"""));
|
||||
"""
|
||||
{
|
||||
"discoverableByPhoneNumber": null
|
||||
}
|
||||
"""));
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(422);
|
||||
verify(AuthHelper.VALID_ACCOUNT, never()).setDiscoverableByPhoneNumber(anyBoolean());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void testGetAccountDataReport(final Account account, final String expectedTextAfterHeader) throws Exception {
|
||||
when(AuthHelper.ACCOUNTS_MANAGER.getByAccountIdentifier(account.getUuid())).thenReturn(Optional.of(account));
|
||||
|
||||
final Response response = resources.getJerseyTest()
|
||||
.target("/v2/accounts/data_report")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(account.getUuid(), "password"))
|
||||
.get();
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
|
||||
final String stringResponse = response.readEntity(String.class);
|
||||
|
||||
final AccountDataReportResponse structuredResponse = SystemMapper.jsonMapper()
|
||||
.readValue(stringResponse, AccountDataReportResponse.class);
|
||||
|
||||
assertEquals(account.getNumber(), structuredResponse.data().account().phoneNumber());
|
||||
assertEquals(account.isDiscoverableByPhoneNumber(),
|
||||
structuredResponse.data().account().findAccountByPhoneNumber());
|
||||
assertEquals(account.isUnrestrictedUnidentifiedAccess(),
|
||||
structuredResponse.data().account().allowSealedSenderFromAnyone());
|
||||
|
||||
final Set<Long> deviceIds = account.getDevices().stream().map(Device::getId).collect(Collectors.toSet());
|
||||
|
||||
// all devices should be present
|
||||
structuredResponse.data().devices().forEach(deviceDataReport -> {
|
||||
assertTrue(deviceIds.remove(deviceDataReport.id()));
|
||||
assertEquals(account.getDevice(deviceDataReport.id()).orElseThrow().getUserAgent(),
|
||||
deviceDataReport.userAgent());
|
||||
});
|
||||
assertTrue(deviceIds.isEmpty());
|
||||
|
||||
final String actualText = (String) SystemMapper.jsonMapper().readValue(stringResponse, Map.class).get("text");
|
||||
final int headerEnd = actualText.indexOf("# Account");
|
||||
assertEquals(expectedTextAfterHeader, actualText.substring(headerEnd));
|
||||
|
||||
final String actualHeader = actualText.substring(0, headerEnd);
|
||||
assertTrue(actualHeader.matches(
|
||||
"Report ID: [a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}\nReport timestamp: \\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z\n\n"));
|
||||
}
|
||||
|
||||
static Stream<Arguments> testGetAccountDataReport() {
|
||||
final String exampleNumber1 = toE164(PhoneNumberUtil.getInstance().getExampleNumber("ES"));
|
||||
final String account2PhoneNumber = toE164(PhoneNumberUtil.getInstance().getExampleNumber("AU"));
|
||||
final String account3PhoneNumber = toE164(PhoneNumberUtil.getInstance().getExampleNumber("IN"));
|
||||
|
||||
final Instant account1Device1Created = Instant.ofEpochSecond(1669323142); // 2022-11-24T20:52:22Z
|
||||
final Instant account1Device2Created = Instant.ofEpochSecond(1679155122); // 2023-03-18T15:58:42Z
|
||||
final Instant account1Device1LastSeen = Instant.ofEpochMilli(Util.todayInMillis());
|
||||
final Instant account1Device2LastSeen = Instant.ofEpochSecond(1678838400); // 2023-03-15T00:00:00Z
|
||||
|
||||
final Instant account2Device1Created = Instant.ofEpochSecond(1659123001); // 2022-07-29T19:30:01Z
|
||||
final Instant account2Device1LastSeen = Instant.ofEpochMilli(Util.todayInMillis());
|
||||
final Instant badgeAExpiration = Instant.now().plus(Duration.ofDays(21)).truncatedTo(ChronoUnit.SECONDS);
|
||||
|
||||
final Instant account3Device1Created = Instant.ofEpochSecond(1639923487); // 2021-12-19T14:18:07Z
|
||||
final Instant account3Device1LastSeen = Instant.ofEpochMilli(Util.todayInMillis());
|
||||
final Instant badgeBExpiration = Instant.now().plus(Duration.ofDays(21)).truncatedTo(ChronoUnit.SECONDS);
|
||||
final Instant badgeCExpiration = Instant.now().plus(Duration.ofDays(24)).truncatedTo(ChronoUnit.SECONDS);
|
||||
|
||||
return Stream.of(
|
||||
Arguments.of(
|
||||
buildTestAccountForDataReport(UUID.randomUUID(), exampleNumber1,
|
||||
true, true,
|
||||
Collections.emptyList(),
|
||||
List.of(new DeviceData(1, account1Device1LastSeen, account1Device1Created, null),
|
||||
new DeviceData(2, account1Device2LastSeen, account1Device2Created, "OWP"))),
|
||||
String.format("""
|
||||
# Account
|
||||
Phone number: %s
|
||||
Allow sealed sender from anyone: true
|
||||
Find account by phone number: true
|
||||
Badges: None
|
||||
|
||||
# Devices
|
||||
- ID: 1
|
||||
Created: 2022-11-24T20:52:22Z
|
||||
Last seen: %s
|
||||
User-agent: null
|
||||
- ID: 2
|
||||
Created: 2023-03-18T15:58:42Z
|
||||
Last seen: 2023-03-15T00:00:00Z
|
||||
User-agent: OWP
|
||||
""",
|
||||
exampleNumber1,
|
||||
account1Device1LastSeen)
|
||||
),
|
||||
Arguments.of(
|
||||
buildTestAccountForDataReport(UUID.randomUUID(), account2PhoneNumber,
|
||||
false, true,
|
||||
List.of(new AccountBadge("badge_a", badgeAExpiration, true)),
|
||||
List.of(new DeviceData(1, account2Device1LastSeen, account2Device1Created, "OWI"))),
|
||||
String.format("""
|
||||
# Account
|
||||
Phone number: %s
|
||||
Allow sealed sender from anyone: false
|
||||
Find account by phone number: true
|
||||
Badges:
|
||||
- ID: badge_a
|
||||
Expiration: %s
|
||||
Visible: true
|
||||
|
||||
# Devices
|
||||
- ID: 1
|
||||
Created: 2022-07-29T19:30:01Z
|
||||
Last seen: %s
|
||||
User-agent: OWI
|
||||
""", account2PhoneNumber,
|
||||
badgeAExpiration,
|
||||
account2Device1LastSeen)
|
||||
),
|
||||
Arguments.of(
|
||||
buildTestAccountForDataReport(UUID.randomUUID(), account3PhoneNumber,
|
||||
true, false,
|
||||
List.of(
|
||||
new AccountBadge("badge_b", badgeBExpiration, true),
|
||||
new AccountBadge("badge_c", badgeCExpiration, false)),
|
||||
List.of(new DeviceData(1, account3Device1LastSeen, account3Device1Created, "OWA"))),
|
||||
String.format("""
|
||||
# Account
|
||||
Phone number: %s
|
||||
Allow sealed sender from anyone: true
|
||||
Find account by phone number: false
|
||||
Badges:
|
||||
- ID: badge_b
|
||||
Expiration: %s
|
||||
Visible: true
|
||||
- ID: badge_c
|
||||
Expiration: %s
|
||||
Visible: false
|
||||
|
||||
# Devices
|
||||
- ID: 1
|
||||
Created: 2021-12-19T14:18:07Z
|
||||
Last seen: %s
|
||||
User-agent: OWA
|
||||
""", account3PhoneNumber,
|
||||
badgeBExpiration,
|
||||
badgeCExpiration,
|
||||
account3Device1LastSeen)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an {@link Account} with data sufficient for
|
||||
* {@link AccountControllerV2#getAccountDataReport(AuthenticatedAccount)}.
|
||||
* <p>
|
||||
* Note: All devices will have a {@link SaltedTokenHash} for "password"
|
||||
*/
|
||||
static Account buildTestAccountForDataReport(final UUID aci, final String number,
|
||||
final boolean unrestrictedUnidentifiedAccess, final boolean discoverableByPhoneNumber,
|
||||
List<AccountBadge> badges, List<DeviceData> devices) {
|
||||
final Account account = new Account();
|
||||
account.setUuid(aci);
|
||||
account.setNumber(number, UUID.randomUUID());
|
||||
account.setUnrestrictedUnidentifiedAccess(unrestrictedUnidentifiedAccess);
|
||||
account.setDiscoverableByPhoneNumber(discoverableByPhoneNumber);
|
||||
account.setBadges(Clock.systemUTC(), new ArrayList<>(badges));
|
||||
|
||||
assert !devices.isEmpty();
|
||||
|
||||
final SaltedTokenHash passwordTokenHash = SaltedTokenHash.generateFor("password");
|
||||
|
||||
devices.forEach(deviceData -> {
|
||||
final Device device = new Device();
|
||||
device.setId(deviceData.id);
|
||||
device.setAuthTokenHash(passwordTokenHash);
|
||||
device.setFetchesMessages(true);
|
||||
device.setSignedPreKey(new SignedPreKey(1, "publicKey", "signature"));
|
||||
device.setLastSeen(deviceData.lastSeen().toEpochMilli());
|
||||
device.setCreated(deviceData.created().toEpochMilli());
|
||||
device.setUserAgent(deviceData.userAgent());
|
||||
account.addDevice(device);
|
||||
});
|
||||
|
||||
return account;
|
||||
}
|
||||
|
||||
private record DeviceData(long id, Instant lastSeen, Instant created, @Nullable String userAgent) {
|
||||
|
||||
}
|
||||
|
||||
private static String toE164(Phonenumber.PhoneNumber phoneNumber) {
|
||||
return PhoneNumberUtil.getInstance().format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
}
|
||||
}
|
||||
}
|
||||
+27
@@ -14,6 +14,7 @@ import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.reset;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.dropwizard.auth.PolymorphicAuthValueFactoryProvider;
|
||||
@@ -108,6 +109,9 @@ class ChallengeControllerTest {
|
||||
}
|
||||
""";
|
||||
|
||||
when(rateLimitChallengeManager.answerRecaptchaChallenge(any(), any(), any(), any()))
|
||||
.thenReturn(true);
|
||||
|
||||
final Response response = EXTENSION.target("/v1/challenge")
|
||||
.request()
|
||||
.header(HttpHeaders.X_FORWARDED_FOR, "10.0.0.1")
|
||||
@@ -115,9 +119,32 @@ class ChallengeControllerTest {
|
||||
.put(Entity.json(recaptchaChallengeJson));
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
|
||||
verify(rateLimitChallengeManager).answerRecaptchaChallenge(eq(AuthHelper.VALID_ACCOUNT), eq("The value of the solved captcha token"), eq("10.0.0.1"), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testHandleInvalidCaptcha() throws RateLimitExceededException, IOException {
|
||||
final String recaptchaChallengeJson = """
|
||||
{
|
||||
"type": "recaptcha",
|
||||
"token": "A server-generated token",
|
||||
"captcha": "The value of the solved captcha token"
|
||||
}
|
||||
""";
|
||||
|
||||
when(rateLimitChallengeManager.answerRecaptchaChallenge(eq(AuthHelper.VALID_ACCOUNT), eq("The value of the solved captcha token"), eq("10.0.0.1"), anyString()))
|
||||
.thenReturn(false);
|
||||
|
||||
final Response response = EXTENSION.target("/v1/challenge")
|
||||
.request()
|
||||
.header(HttpHeaders.X_FORWARDED_FOR, "10.0.0.1")
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.put(Entity.json(recaptchaChallengeJson));
|
||||
|
||||
assertEquals(428, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testHandleRecaptchaRateLimited() throws RateLimitExceededException, IOException {
|
||||
final String recaptchaChallengeJson = """
|
||||
|
||||
+10
-1
@@ -60,6 +60,7 @@ import javax.ws.rs.core.Response;
|
||||
import org.glassfish.jersey.server.ServerProperties;
|
||||
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
import org.hamcrest.Matcher;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -104,6 +105,8 @@ import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.websocket.Stories;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
|
||||
@ExtendWith(DropwizardExtensionsSupport.class)
|
||||
class MessageControllerTest {
|
||||
@@ -142,6 +145,7 @@ class MessageControllerTest {
|
||||
private static final PushNotificationManager pushNotificationManager = mock(PushNotificationManager.class);
|
||||
private static final ReportMessageManager reportMessageManager = mock(ReportMessageManager.class);
|
||||
private static final ExecutorService multiRecipientMessageExecutor = mock(ExecutorService.class);
|
||||
private static final Scheduler messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
|
||||
|
||||
private static final ResourceExtension resources = ResourceExtension.builder()
|
||||
.addProperty(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE)
|
||||
@@ -154,7 +158,7 @@ class MessageControllerTest {
|
||||
.addResource(
|
||||
new MessageController(rateLimiters, messageSender, receiptSender, accountsManager, deletedAccountsManager,
|
||||
messagesManager, pushNotificationManager, reportMessageManager, multiRecipientMessageExecutor,
|
||||
ReportSpamTokenProvider.noop()))
|
||||
messageDeliveryScheduler, ReportSpamTokenProvider.noop()))
|
||||
.build();
|
||||
|
||||
@BeforeEach
|
||||
@@ -213,6 +217,11 @@ class MessageControllerTest {
|
||||
);
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void teardownAll() {
|
||||
messageDeliveryScheduler.dispose();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSendFromDisabledAccount() throws Exception {
|
||||
Response response =
|
||||
|
||||
+1
-1
@@ -265,7 +265,7 @@ class RegistrationControllerTest {
|
||||
case RATE_LIMITED -> new RateLimitExceededException(null, true);
|
||||
};
|
||||
doThrow(e)
|
||||
.when(registrationLockVerificationManager).verifyRegistrationLock(any(), any());
|
||||
.when(registrationLockVerificationManager).verifyRegistrationLock(any(), any(), any(), any(), any());
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/registration")
|
||||
|
||||
+49
-6
@@ -11,7 +11,9 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
@@ -19,6 +21,8 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import com.google.i18n.phonenumbers.NumberParseException;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import io.dropwizard.testing.junit5.ResourceExtension;
|
||||
import java.io.IOException;
|
||||
@@ -46,6 +50,7 @@ import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.whispersystems.textsecuregcm.captcha.AssessmentResult;
|
||||
import org.whispersystems.textsecuregcm.captcha.RegistrationCaptchaManager;
|
||||
@@ -62,6 +67,9 @@ import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
|
||||
import org.whispersystems.textsecuregcm.registration.RegistrationServiceException;
|
||||
import org.whispersystems.textsecuregcm.registration.RegistrationServiceSenderException;
|
||||
import org.whispersystems.textsecuregcm.registration.VerificationSession;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.spam.ScoreThresholdProvider;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
@@ -81,6 +89,7 @@ class VerificationControllerTest {
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager = mock(
|
||||
RegistrationRecoveryPasswordsManager.class);
|
||||
private final RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
private final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
private final Clock clock = Clock.systemUTC();
|
||||
|
||||
private final RateLimiter captchaLimiter = mock(RateLimiter.class);
|
||||
@@ -92,11 +101,12 @@ class VerificationControllerTest {
|
||||
.addProvider(new ImpossiblePhoneNumberExceptionMapper())
|
||||
.addProvider(new NonNormalizedPhoneNumberExceptionMapper())
|
||||
.addProvider(new RegistrationServiceSenderExceptionMapper())
|
||||
.addProvider(ScoreThresholdProvider.ScoreThresholdFeature.class)
|
||||
.setMapper(SystemMapper.jsonMapper())
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addResource(
|
||||
new VerificationController(registrationServiceClient, verificationSessionManager, pushNotificationManager,
|
||||
registrationCaptchaManager, registrationRecoveryPasswordsManager, rateLimiters, clock))
|
||||
registrationCaptchaManager, registrationRecoveryPasswordsManager, rateLimiters, accountsManager, clock))
|
||||
.build();
|
||||
|
||||
@BeforeEach
|
||||
@@ -105,6 +115,8 @@ class VerificationControllerTest {
|
||||
.thenReturn(captchaLimiter);
|
||||
when(rateLimiters.getVerificationPushChallengeLimiter())
|
||||
.thenReturn(pushChallengeLimiter);
|
||||
|
||||
when(accountsManager.getByE164(any())).thenReturn(Optional.empty());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -153,7 +165,7 @@ class VerificationControllerTest {
|
||||
|
||||
@Test
|
||||
void createSessionRateLimited() {
|
||||
when(registrationServiceClient.createRegistrationSessionSession(any(), any()))
|
||||
when(registrationServiceClient.createRegistrationSessionSession(any(), anyBoolean(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(new RateLimitExceededException(null, true)));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
@@ -167,7 +179,7 @@ class VerificationControllerTest {
|
||||
|
||||
@Test
|
||||
void createSessionRegistrationServiceError() {
|
||||
when(registrationServiceClient.createRegistrationSessionSession(any(), any()))
|
||||
when(registrationServiceClient.createRegistrationSessionSession(any(), anyBoolean(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(new RuntimeException("expected service error")));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
@@ -183,7 +195,7 @@ class VerificationControllerTest {
|
||||
@MethodSource
|
||||
void createSessionSuccess(final String pushToken, final String pushTokenType,
|
||||
final List<VerificationSession.Information> expectedRequestedInformation) {
|
||||
when(registrationServiceClient.createRegistrationSessionSession(any(), any()))
|
||||
when(registrationServiceClient.createRegistrationSessionSession(any(), anyBoolean(), any()))
|
||||
.thenReturn(
|
||||
CompletableFuture.completedFuture(
|
||||
new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null,
|
||||
@@ -214,6 +226,37 @@ class VerificationControllerTest {
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void createSessionReregistration(final boolean isReregistration) throws NumberParseException {
|
||||
when(registrationServiceClient.createRegistrationSessionSession(any(), anyBoolean(), any()))
|
||||
.thenReturn(
|
||||
CompletableFuture.completedFuture(
|
||||
new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null,
|
||||
SESSION_EXPIRATION_SECONDS)));
|
||||
|
||||
when(verificationSessionManager.insert(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
when(accountsManager.getByE164(NUMBER))
|
||||
.thenReturn(isReregistration ? Optional.of(mock(Account.class)) : Optional.empty());
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/verification/session")
|
||||
.request()
|
||||
.header(HttpHeaders.X_FORWARDED_FOR, "127.0.0.1");
|
||||
|
||||
try (final Response response = request.post(Entity.json(createSessionJson(NUMBER, null, null)))) {
|
||||
assertEquals(HttpStatus.SC_OK, response.getStatus());
|
||||
|
||||
verify(registrationServiceClient).createRegistrationSessionSession(
|
||||
eq(PhoneNumberUtil.getInstance().parse(NUMBER, null)),
|
||||
eq(isReregistration),
|
||||
any()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void patchSessionMalformedId() {
|
||||
final String invalidSessionId = "()()()";
|
||||
@@ -580,7 +623,7 @@ class VerificationControllerTest {
|
||||
registrationServiceSession.expiration()))));
|
||||
|
||||
when(registrationCaptchaManager.assessCaptcha(any(), any()))
|
||||
.thenReturn(Optional.of(new AssessmentResult(true, "1")));
|
||||
.thenReturn(Optional.of(AssessmentResult.alwaysValid()));
|
||||
|
||||
when(verificationSessionManager.update(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
@@ -628,7 +671,7 @@ class VerificationControllerTest {
|
||||
registrationServiceSession.expiration()))));
|
||||
|
||||
when(registrationCaptchaManager.assessCaptcha(any(), any()))
|
||||
.thenReturn(Optional.of(new AssessmentResult(true, "1")));
|
||||
.thenReturn(Optional.of(AssessmentResult.alwaysValid()));
|
||||
|
||||
when(verificationSessionManager.update(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
@@ -1,85 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.limits;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
|
||||
class LeakyBucketTest {
|
||||
|
||||
@Test
|
||||
void testFull() {
|
||||
LeakyBucket leakyBucket = new LeakyBucket(2, 1.0 / 2.0);
|
||||
|
||||
assertTrue(leakyBucket.add(1));
|
||||
assertTrue(leakyBucket.add(1));
|
||||
assertFalse(leakyBucket.add(1));
|
||||
|
||||
leakyBucket = new LeakyBucket(2, 1.0 / 2.0);
|
||||
|
||||
assertTrue(leakyBucket.add(2));
|
||||
assertFalse(leakyBucket.add(1));
|
||||
assertFalse(leakyBucket.add(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testLapseRate() throws IOException {
|
||||
ObjectMapper mapper = SystemMapper.jsonMapper();
|
||||
String serialized = "{\"bucketSize\":2,\"leakRatePerMillis\":8.333333333333334E-6,\"spaceRemaining\":0,\"lastUpdateTimeMillis\":" + (System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(2)) + "}";
|
||||
|
||||
LeakyBucket leakyBucket = LeakyBucket.fromSerialized(mapper, serialized);
|
||||
assertTrue(leakyBucket.add(1));
|
||||
|
||||
String serializedAgain = leakyBucket.serialize(mapper);
|
||||
LeakyBucket leakyBucketAgain = LeakyBucket.fromSerialized(mapper, serializedAgain);
|
||||
|
||||
assertFalse(leakyBucketAgain.add(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testLapseShort() throws Exception {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
String serialized = "{\"bucketSize\":2,\"leakRatePerMillis\":8.333333333333334E-6,\"spaceRemaining\":0,\"lastUpdateTimeMillis\":" + (System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(1)) + "}";
|
||||
|
||||
LeakyBucket leakyBucket = LeakyBucket.fromSerialized(mapper, serialized);
|
||||
assertFalse(leakyBucket.add(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetTimeUntilSpaceAvailable() throws Exception {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
{
|
||||
String serialized = "{\"bucketSize\":2,\"leakRatePerMillis\":8.333333333333334E-6,\"spaceRemaining\":2,\"lastUpdateTimeMillis\":" + (System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(1)) + "}";
|
||||
|
||||
LeakyBucket leakyBucket = LeakyBucket.fromSerialized(mapper, serialized);
|
||||
|
||||
assertEquals(Duration.ZERO, leakyBucket.getTimeUntilSpaceAvailable(1));
|
||||
assertThrows(IllegalArgumentException.class, () -> leakyBucket.getTimeUntilSpaceAvailable(5000));
|
||||
}
|
||||
|
||||
{
|
||||
String serialized = "{\"bucketSize\":2,\"leakRatePerMillis\":8.333333333333334E-6,\"spaceRemaining\":0,\"lastUpdateTimeMillis\":" + (System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(1)) + "}";
|
||||
|
||||
LeakyBucket leakyBucket = LeakyBucket.fromSerialized(mapper, serialized);
|
||||
|
||||
Duration timeUntilSpaceAvailable = leakyBucket.getTimeUntilSpaceAvailable(1);
|
||||
|
||||
// TODO Refactor LeakyBucket to be more test-friendly and accept a Clock
|
||||
assertTrue(timeUntilSpaceAvailable.compareTo(Duration.ofMillis(119_000)) > 0);
|
||||
assertTrue(timeUntilSpaceAvailable.compareTo(Duration.ofMinutes(2)) <= 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -17,6 +17,7 @@ import java.util.UUID;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.whispersystems.textsecuregcm.captcha.Action;
|
||||
import org.whispersystems.textsecuregcm.captcha.AssessmentResult;
|
||||
import org.whispersystems.textsecuregcm.captcha.CaptchaChecker;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
@@ -75,9 +76,9 @@ class RateLimitChallengeManagerTest {
|
||||
when(account.getNumber()).thenReturn("+18005551234");
|
||||
when(account.getUuid()).thenReturn(UUID.randomUUID());
|
||||
|
||||
when(captchaChecker.verify(any(), any()))
|
||||
when(captchaChecker.verify(eq(Action.CHALLENGE), any(), any()))
|
||||
.thenReturn(successfulChallenge
|
||||
? new AssessmentResult(true, "")
|
||||
? AssessmentResult.alwaysValid()
|
||||
: AssessmentResult.invalid());
|
||||
|
||||
when(rateLimiters.getRecaptchaChallengeAttemptLimiter()).thenReturn(mock(RateLimiter.class));
|
||||
|
||||
+203
@@ -0,0 +1,203 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.limits;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import io.lettuce.core.ScriptOutputType;
|
||||
import java.time.Clock;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.MockUtils;
|
||||
import org.whispersystems.textsecuregcm.util.MutableClock;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.redis.RedisLuaScriptSandbox;
|
||||
import org.whispersystems.textsecuregcm.util.redis.SimpleCacheCommandsHandler;
|
||||
|
||||
public class RateLimitersLuaScriptTest {
|
||||
|
||||
@RegisterExtension
|
||||
private static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
|
||||
|
||||
private final DynamicConfiguration configuration = mock(DynamicConfiguration.class);
|
||||
|
||||
private final MutableClock clock = MockUtils.mutableClock(0);
|
||||
|
||||
private final RedisLuaScriptSandbox sandbox = RedisLuaScriptSandbox.fromResource(
|
||||
"lua/validate_rate_limit.lua",
|
||||
ScriptOutputType.INTEGER);
|
||||
|
||||
private final SimpleCacheCommandsHandler redisCommandsHandler = new SimpleCacheCommandsHandler(clock);
|
||||
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfig =
|
||||
MockUtils.buildMock(DynamicConfigurationManager.class, cfg -> when(cfg.getConfiguration()).thenReturn(configuration));
|
||||
|
||||
@Test
|
||||
public void testWithEmbeddedRedis() throws Exception {
|
||||
final RateLimiters.For descriptor = RateLimiters.For.REGISTRATION;
|
||||
final FaultTolerantRedisCluster redisCluster = REDIS_CLUSTER_EXTENSION.getRedisCluster();
|
||||
final RateLimiters limiters = new RateLimiters(
|
||||
Map.of(descriptor.id(), new RateLimiterConfig(60, 60)),
|
||||
dynamicConfig,
|
||||
RateLimiters.defaultScript(redisCluster),
|
||||
redisCluster,
|
||||
Clock.systemUTC());
|
||||
|
||||
final RateLimiter rateLimiter = limiters.forDescriptor(descriptor);
|
||||
rateLimiter.validate("test", 25);
|
||||
rateLimiter.validate("test", 25);
|
||||
assertThrows(RateLimitExceededException.class, () -> rateLimiter.validate("test", 25));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFormatMigration() throws Exception {
|
||||
final RateLimiters.For descriptor = RateLimiters.For.REGISTRATION;
|
||||
final FaultTolerantRedisCluster redisCluster = REDIS_CLUSTER_EXTENSION.getRedisCluster();
|
||||
final RateLimiters limiters = new RateLimiters(
|
||||
Map.of(descriptor.id(), new RateLimiterConfig(60, 60)),
|
||||
dynamicConfig,
|
||||
RateLimiters.defaultScript(redisCluster),
|
||||
redisCluster,
|
||||
Clock.systemUTC());
|
||||
|
||||
final RateLimiter rateLimiter = limiters.forDescriptor(descriptor);
|
||||
|
||||
// embedding an existing value in the old format
|
||||
redisCluster.useCluster(c -> c.sync().set(
|
||||
StaticRateLimiter.bucketName(descriptor.id(), "test"),
|
||||
serializeToOldBucketValueFormat(60, 60, 30, System.currentTimeMillis() + 10000)
|
||||
));
|
||||
assertThrows(RateLimitExceededException.class, () -> rateLimiter.validate("test", 40));
|
||||
|
||||
// embedding an existing value in the old format
|
||||
redisCluster.useCluster(c -> c.sync().set(
|
||||
StaticRateLimiter.bucketName(descriptor.id(), "test1"),
|
||||
serializeToOldBucketValueFormat(60, 60, 30, System.currentTimeMillis() + 10000)
|
||||
));
|
||||
rateLimiter.validate("test1", 20);
|
||||
assertThrows(RateLimitExceededException.class, () -> rateLimiter.validate("test1", 20));
|
||||
|
||||
// embedding an existing value in the new format
|
||||
redisCluster.useCluster(c -> c.sync().hset(
|
||||
StaticRateLimiter.bucketName(descriptor.id(), "test2"),
|
||||
Map.of("s", "30", "t", String.valueOf(System.currentTimeMillis() + 10000))
|
||||
));
|
||||
assertThrows(RateLimitExceededException.class, () -> rateLimiter.validate("test2", 40));
|
||||
|
||||
// embedding an existing value in the new format
|
||||
redisCluster.useCluster(c -> c.sync().hset(
|
||||
StaticRateLimiter.bucketName(descriptor.id(), "test3"),
|
||||
Map.of("s", "30", "t", String.valueOf(System.currentTimeMillis() + 10000))
|
||||
));
|
||||
rateLimiter.validate("test3", 20);
|
||||
assertThrows(RateLimitExceededException.class, () -> rateLimiter.validate("test3", 20));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTtl() throws Exception {
|
||||
final RateLimiters.For descriptor = RateLimiters.For.REGISTRATION;
|
||||
final FaultTolerantRedisCluster redisCluster = REDIS_CLUSTER_EXTENSION.getRedisCluster();
|
||||
final RateLimiters limiters = new RateLimiters(
|
||||
Map.of(descriptor.id(), new RateLimiterConfig(1000, 60)),
|
||||
dynamicConfig,
|
||||
RateLimiters.defaultScript(redisCluster),
|
||||
redisCluster,
|
||||
Clock.systemUTC());
|
||||
|
||||
final RateLimiter rateLimiter = limiters.forDescriptor(descriptor);
|
||||
rateLimiter.validate("test", 200);
|
||||
// after using 200 tokens, we expect 200 seconds to refill, so the TTL should be under 200000
|
||||
final long ttl = redisCluster.withCluster(c -> c.sync().ttl("test"));
|
||||
assertTrue(ttl <= 200000);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLuaUpdatesTokenBucket() throws Exception {
|
||||
final String key = "key1";
|
||||
clock.setTimeMillis(0);
|
||||
long result = (long) sandbox.execute(
|
||||
List.of(key),
|
||||
scriptArgs(1000, 1, 200, true),
|
||||
redisCommandsHandler
|
||||
);
|
||||
assertEquals(0L, result);
|
||||
assertEquals(800L, decodeBucket(key).orElseThrow().tokensRemaining);
|
||||
|
||||
// 50 tokens replenished, acquiring 100 more, should end up with 750 available
|
||||
clock.setTimeMillis(50);
|
||||
result = (long) sandbox.execute(
|
||||
List.of(key),
|
||||
scriptArgs(1000, 1, 100, true),
|
||||
redisCommandsHandler
|
||||
);
|
||||
assertEquals(0L, result);
|
||||
assertEquals(750L, decodeBucket(key).orElseThrow().tokensRemaining);
|
||||
|
||||
// now checking without an update, should not affect the count
|
||||
result = (long) sandbox.execute(
|
||||
List.of(key),
|
||||
scriptArgs(1000, 1, 100, false),
|
||||
redisCommandsHandler
|
||||
);
|
||||
assertEquals(0L, result);
|
||||
assertEquals(750L, decodeBucket(key).orElseThrow().tokensRemaining);
|
||||
}
|
||||
|
||||
private String serializeToOldBucketValueFormat(
|
||||
final long bucketSize,
|
||||
final long leakRatePerMillis,
|
||||
final long spaceRemaining,
|
||||
final long lastUpdateTimeMillis) {
|
||||
try {
|
||||
return SystemMapper.jsonMapper().writeValueAsString(Map.of(
|
||||
"bucketSize", bucketSize,
|
||||
"leakRatePerMillis", leakRatePerMillis,
|
||||
"spaceRemaining", spaceRemaining,
|
||||
"lastUpdateTimeMillis", lastUpdateTimeMillis
|
||||
));
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<TokenBucket> decodeBucket(final String key) {
|
||||
final Object[] fields = redisCommandsHandler.hmget(key, List.of("s", "t"));
|
||||
return fields[0] == null
|
||||
? Optional.empty()
|
||||
: Optional.of(new TokenBucket(
|
||||
Double.valueOf(fields[0].toString()).longValue(), Double.valueOf(fields[1].toString()).longValue()));
|
||||
}
|
||||
|
||||
private List<String> scriptArgs(
|
||||
final long bucketSize,
|
||||
final long ratePerMillis,
|
||||
final long requestedAmount,
|
||||
final boolean useTokens) {
|
||||
return List.of(
|
||||
String.valueOf(bucketSize),
|
||||
String.valueOf(ratePerMillis),
|
||||
String.valueOf(clock.millis()),
|
||||
String.valueOf(requestedAmount),
|
||||
String.valueOf(useTokens)
|
||||
);
|
||||
}
|
||||
|
||||
private record TokenBucket(long tokensRemaining, long lastUpdateTimeMillis) {
|
||||
}
|
||||
}
|
||||
+17
-7
@@ -18,9 +18,11 @@ import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.MockUtils;
|
||||
import org.whispersystems.textsecuregcm.util.MutableClock;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public class RateLimitersTest {
|
||||
@@ -30,8 +32,12 @@ public class RateLimitersTest {
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfig =
|
||||
MockUtils.buildMock(DynamicConfigurationManager.class, cfg -> when(cfg.getConfiguration()).thenReturn(configuration));
|
||||
|
||||
private final ClusterLuaScript validateScript = mock(ClusterLuaScript.class);
|
||||
|
||||
private final FaultTolerantRedisCluster redisCluster = mock(FaultTolerantRedisCluster.class);
|
||||
|
||||
private final MutableClock clock = MockUtils.mutableClock(0);
|
||||
|
||||
private static final String BAD_YAML = """
|
||||
limits:
|
||||
smsVoicePrefix:
|
||||
@@ -59,12 +65,12 @@ public class RateLimitersTest {
|
||||
public void testValidateConfigs() throws Exception {
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
final GenericHolder cfg = DynamicConfigurationManager.parseConfiguration(BAD_YAML, GenericHolder.class).orElseThrow();
|
||||
final RateLimiters rateLimiters = new RateLimiters(cfg.limits(), dynamicConfig, redisCluster);
|
||||
final RateLimiters rateLimiters = new RateLimiters(cfg.limits(), dynamicConfig, validateScript, redisCluster, clock);
|
||||
rateLimiters.validateValuesAndConfigs();
|
||||
});
|
||||
|
||||
final GenericHolder cfg = DynamicConfigurationManager.parseConfiguration(GOOD_YAML, GenericHolder.class).orElseThrow();
|
||||
final RateLimiters rateLimiters = new RateLimiters(cfg.limits(), dynamicConfig, redisCluster);
|
||||
final RateLimiters rateLimiters = new RateLimiters(cfg.limits(), dynamicConfig, validateScript, redisCluster, clock);
|
||||
rateLimiters.validateValuesAndConfigs();
|
||||
}
|
||||
|
||||
@@ -79,18 +85,22 @@ public class RateLimitersTest {
|
||||
new TestDescriptor[] { td1, td2, td3, tdDup },
|
||||
Collections.emptyMap(),
|
||||
dynamicConfig,
|
||||
redisCluster) {});
|
||||
validateScript,
|
||||
redisCluster,
|
||||
clock) {});
|
||||
|
||||
new BaseRateLimiters<>(
|
||||
new TestDescriptor[] { td1, td2, td3 },
|
||||
Collections.emptyMap(),
|
||||
dynamicConfig,
|
||||
redisCluster) {};
|
||||
validateScript,
|
||||
redisCluster,
|
||||
clock) {};
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUnchangingConfiguration() {
|
||||
final RateLimiters rateLimiters = new RateLimiters(Collections.emptyMap(), dynamicConfig, redisCluster);
|
||||
final RateLimiters rateLimiters = new RateLimiters(Collections.emptyMap(), dynamicConfig, validateScript, redisCluster, clock);
|
||||
final RateLimiter limiter = rateLimiters.getRateLimitResetLimiter();
|
||||
final RateLimiterConfig expected = RateLimiters.For.RATE_LIMIT_RESET.defaultConfig();
|
||||
assertEquals(expected, limiter.config());
|
||||
@@ -109,7 +119,7 @@ public class RateLimitersTest {
|
||||
|
||||
when(configuration.getLimits()).thenReturn(limitsConfigMap);
|
||||
|
||||
final RateLimiters rateLimiters = new RateLimiters(Collections.emptyMap(), dynamicConfig, redisCluster);
|
||||
final RateLimiters rateLimiters = new RateLimiters(Collections.emptyMap(), dynamicConfig, validateScript, redisCluster, clock);
|
||||
final RateLimiter limiter = rateLimiters.getRateLimitResetLimiter();
|
||||
|
||||
limitsConfigMap.put(RateLimiters.For.RATE_LIMIT_RESET.id(), initialRateLimiterConfig);
|
||||
@@ -137,7 +147,7 @@ public class RateLimitersTest {
|
||||
|
||||
when(configuration.getLimits()).thenReturn(mapForDynamic);
|
||||
|
||||
final RateLimiters rateLimiters = new RateLimiters(mapForStatic, dynamicConfig, redisCluster);
|
||||
final RateLimiters rateLimiters = new RateLimiters(mapForStatic, dynamicConfig, validateScript, redisCluster, clock);
|
||||
final RateLimiter limiter = rateLimiters.forDescriptor(descriptor);
|
||||
|
||||
// test only default is present
|
||||
|
||||
+3
-3
@@ -86,7 +86,7 @@ class MetricsRequestEventListenerTest {
|
||||
when(uriInfo.getMatchedTemplates()).thenReturn(Collections.singletonList(new UriTemplate(path)));
|
||||
|
||||
final ContainerRequest request = mock(ContainerRequest.class);
|
||||
when(request.getRequestHeader(HttpHeaders.USER_AGENT)).thenReturn(Collections.singletonList("Signal-Android 4.53.7 (Android 8.1)"));
|
||||
when(request.getRequestHeader(HttpHeaders.USER_AGENT)).thenReturn(Collections.singletonList("Signal-Android/4.53.7 (Android 8.1)"));
|
||||
|
||||
final ContainerResponse response = mock(ContainerResponse.class);
|
||||
when(response.getStatus()).thenReturn(statusCode);
|
||||
@@ -143,8 +143,8 @@ class MetricsRequestEventListenerTest {
|
||||
|
||||
when(session.getUpgradeRequest()).thenReturn(request);
|
||||
when(session.getRemote()).thenReturn(remoteEndpoint);
|
||||
when(request.getHeader(HttpHeaders.USER_AGENT)).thenReturn("Signal-Android 4.53.7 (Android 8.1)");
|
||||
when(request.getHeaders()).thenReturn(Map.of(HttpHeaders.USER_AGENT, List.of("Signal-Android 4.53.7 (Android 8.1)")));
|
||||
when(request.getHeader(HttpHeaders.USER_AGENT)).thenReturn("Signal-Android/4.53.7 (Android 8.1)");
|
||||
when(request.getHeaders()).thenReturn(Map.of(HttpHeaders.USER_AGENT, List.of("Signal-Android/4.53.7 (Android 8.1)")));
|
||||
|
||||
final ArgumentCaptor<Iterable<Tag>> tagCaptor = ArgumentCaptor.forClass(Iterable.class);
|
||||
when(meterRegistry.counter(eq(MetricsRequestEventListener.REQUEST_COUNTER_NAME), any(Iterable.class))).thenReturn(counter);
|
||||
|
||||
+27
-27
@@ -35,31 +35,31 @@ class UserAgentTagUtilTest {
|
||||
return Stream.of(
|
||||
Arguments.of("This is obviously not a reasonable User-Agent string.", UserAgentTagUtil.UNRECOGNIZED_TAGS),
|
||||
Arguments.of(null, UserAgentTagUtil.UNRECOGNIZED_TAGS),
|
||||
Arguments.of("Signal-Android 4.53.7 (Android 8.1)", platformVersionTags("android", "4.53.7")),
|
||||
Arguments.of("Signal Desktop 1.2.3", platformVersionTags("desktop", "1.2.3")),
|
||||
Arguments.of("Signal/3.9.0 (iPhone; iOS 12.2; Scale/3.00)", platformVersionTags("ios", "3.9.0")),
|
||||
Arguments.of("Signal-Android 1.2.3 (Android 8.1)", UserAgentTagUtil.UNRECOGNIZED_TAGS),
|
||||
Arguments.of("Signal Desktop 3.9.0", platformVersionTags("desktop", "3.9.0")),
|
||||
Arguments.of("Signal/4.53.7 (iPhone; iOS 12.2; Scale/3.00)", platformVersionTags("ios", "4.53.7")),
|
||||
Arguments.of("Signal-Android 4.68.3 (Android 9)", platformVersionTags("android", "4.68.3")),
|
||||
Arguments.of("Signal-Android 1.2.3 (Android 4.3)", UserAgentTagUtil.UNRECOGNIZED_TAGS),
|
||||
Arguments.of("Signal-Android 4.68.3.0-bobsbootlegclient", UserAgentTagUtil.UNRECOGNIZED_TAGS),
|
||||
Arguments.of("Signal Desktop 1.22.45-foo-0", UserAgentTagUtil.UNRECOGNIZED_TAGS),
|
||||
Arguments.of("Signal Desktop 1.34.5-beta.1-fakeclientemporium", UserAgentTagUtil.UNRECOGNIZED_TAGS),
|
||||
Arguments.of("Signal Desktop 1.32.0-beta.3", UserAgentTagUtil.UNRECOGNIZED_TAGS)
|
||||
Arguments.of("Signal-Android/4.53.7 (Android 8.1)", platformVersionTags("android", "4.53.7")),
|
||||
Arguments.of("Signal-Desktop/1.2.3", platformVersionTags("desktop", "1.2.3")),
|
||||
Arguments.of("Signal-iOS/3.9.0 (iPhone; iOS 12.2; Scale/3.00)", platformVersionTags("ios", "3.9.0")),
|
||||
Arguments.of("Signal-Android/1.2.3 (Android 8.1)", UserAgentTagUtil.UNRECOGNIZED_TAGS),
|
||||
Arguments.of("Signal-Desktop/3.9.0", platformVersionTags("desktop", "3.9.0")),
|
||||
Arguments.of("Signal-iOS/4.53.7 (iPhone; iOS 12.2; Scale/3.00)", platformVersionTags("ios", "4.53.7")),
|
||||
Arguments.of("Signal-Android/4.68.3 (Android 9)", platformVersionTags("android", "4.68.3")),
|
||||
Arguments.of("Signal-Android/1.2.3 (Android 4.3)", UserAgentTagUtil.UNRECOGNIZED_TAGS),
|
||||
Arguments.of("Signal-Android/4.68.3.0-bobsbootlegclient", UserAgentTagUtil.UNRECOGNIZED_TAGS),
|
||||
Arguments.of("Signal-Desktop/1.22.45-foo-0", UserAgentTagUtil.UNRECOGNIZED_TAGS),
|
||||
Arguments.of("Signal-Desktop/1.34.5-beta.1-fakeclientemporium", UserAgentTagUtil.UNRECOGNIZED_TAGS),
|
||||
Arguments.of("Signal-Desktop/1.32.0-beta.3", UserAgentTagUtil.UNRECOGNIZED_TAGS)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetUserAgentTagsFlooded() {
|
||||
for (int i = 0; i < UserAgentTagUtil.MAX_VERSIONS; i++) {
|
||||
UserAgentTagUtil.getUserAgentTags(String.format("Signal-Android 4.0.%d (Android 8.1)", i));
|
||||
UserAgentTagUtil.getUserAgentTags(String.format("Signal-Android/4.0.%d (Android 8.1)", i));
|
||||
}
|
||||
|
||||
assertEquals(UserAgentTagUtil.OVERFLOW_TAGS,
|
||||
UserAgentTagUtil.getUserAgentTags("Signal-Android 4.1.0 (Android 8.1)"));
|
||||
UserAgentTagUtil.getUserAgentTags("Signal-Android/4.1.0 (Android 8.1)"));
|
||||
|
||||
final List<Tag> tags = UserAgentTagUtil.getUserAgentTags("Signal-Android 4.0.0 (Android 8.1)");
|
||||
final List<Tag> tags = UserAgentTagUtil.getUserAgentTags("Signal-Android/4.0.0 (Android 8.1)");
|
||||
|
||||
assertEquals(2, tags.size());
|
||||
assertTrue(tags.contains(Tag.of(UserAgentTagUtil.PLATFORM_TAG, "android")));
|
||||
@@ -77,19 +77,19 @@ class UserAgentTagUtilTest {
|
||||
Arguments.of("This is obviously not a reasonable User-Agent string.",
|
||||
Tag.of(UserAgentTagUtil.PLATFORM_TAG, "unrecognized")),
|
||||
Arguments.of(null, Tag.of(UserAgentTagUtil.PLATFORM_TAG, "unrecognized")),
|
||||
Arguments.of("Signal-Android 4.53.7 (Android 8.1)", Tag.of(UserAgentTagUtil.PLATFORM_TAG, "android")),
|
||||
Arguments.of("Signal Desktop 1.2.3", Tag.of(UserAgentTagUtil.PLATFORM_TAG, "desktop")),
|
||||
Arguments.of("Signal/3.9.0 (iPhone; iOS 12.2; Scale/3.00)", Tag.of(UserAgentTagUtil.PLATFORM_TAG, "ios")),
|
||||
Arguments.of("Signal-Android 1.2.3 (Android 8.1)", Tag.of(UserAgentTagUtil.PLATFORM_TAG, "android")),
|
||||
Arguments.of("Signal Desktop 3.9.0", Tag.of(UserAgentTagUtil.PLATFORM_TAG, "desktop")),
|
||||
Arguments.of("Signal/4.53.7 (iPhone; iOS 12.2; Scale/3.00)", Tag.of(UserAgentTagUtil.PLATFORM_TAG, "ios")),
|
||||
Arguments.of("Signal-Android 4.68.3 (Android 9)", Tag.of(UserAgentTagUtil.PLATFORM_TAG, "android")),
|
||||
Arguments.of("Signal-Android 1.2.3 (Android 4.3)", Tag.of(UserAgentTagUtil.PLATFORM_TAG, "android")),
|
||||
Arguments.of("Signal-Android 4.68.3.0-bobsbootlegclient", Tag.of(UserAgentTagUtil.PLATFORM_TAG, "android")),
|
||||
Arguments.of("Signal Desktop 1.22.45-foo-0", Tag.of(UserAgentTagUtil.PLATFORM_TAG, "desktop")),
|
||||
Arguments.of("Signal Desktop 1.34.5-beta.1-fakeclientemporium",
|
||||
Arguments.of("Signal-Android/4.53.7 (Android 8.1)", Tag.of(UserAgentTagUtil.PLATFORM_TAG, "android")),
|
||||
Arguments.of("Signal-Desktop/1.2.3", Tag.of(UserAgentTagUtil.PLATFORM_TAG, "desktop")),
|
||||
Arguments.of("Signal-iOS/3.9.0 (iPhone; iOS 12.2; Scale/3.00)", Tag.of(UserAgentTagUtil.PLATFORM_TAG, "ios")),
|
||||
Arguments.of("Signal-Android/1.2.3 (Android 8.1)", Tag.of(UserAgentTagUtil.PLATFORM_TAG, "android")),
|
||||
Arguments.of("Signal-Desktop/3.9.0", Tag.of(UserAgentTagUtil.PLATFORM_TAG, "desktop")),
|
||||
Arguments.of("Signal-iOS/4.53.7 (iPhone; iOS 12.2; Scale/3.00)", Tag.of(UserAgentTagUtil.PLATFORM_TAG, "ios")),
|
||||
Arguments.of("Signal-Android/4.68.3 (Android 9)", Tag.of(UserAgentTagUtil.PLATFORM_TAG, "android")),
|
||||
Arguments.of("Signal-Android/1.2.3 (Android 4.3)", Tag.of(UserAgentTagUtil.PLATFORM_TAG, "android")),
|
||||
Arguments.of("Signal-Android/4.68.3.0-bobsbootlegclient", Tag.of(UserAgentTagUtil.PLATFORM_TAG, "android")),
|
||||
Arguments.of("Signal-Desktop/1.22.45-foo-0", Tag.of(UserAgentTagUtil.PLATFORM_TAG, "desktop")),
|
||||
Arguments.of("Signal-Desktop/1.34.5-beta.1-fakeclientemporium",
|
||||
Tag.of(UserAgentTagUtil.PLATFORM_TAG, "desktop")),
|
||||
Arguments.of("Signal Desktop 1.32.0-beta.3", Tag.of(UserAgentTagUtil.PLATFORM_TAG, "desktop"))
|
||||
Arguments.of("Signal-Desktop/1.32.0-beta.3", Tag.of(UserAgentTagUtil.PLATFORM_TAG, "desktop"))
|
||||
);
|
||||
}
|
||||
}
|
||||
+11
-1
@@ -42,6 +42,8 @@ class ClientPresenceManagerTest {
|
||||
private static final DisplacedPresenceListener NO_OP = connectedElsewhere -> {
|
||||
};
|
||||
|
||||
private boolean expectExceptionOnClientPresenceManagerStop = false;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
|
||||
@@ -61,7 +63,13 @@ class ClientPresenceManagerTest {
|
||||
presenceRenewalExecutorService.shutdown();
|
||||
presenceRenewalExecutorService.awaitTermination(1, TimeUnit.MINUTES);
|
||||
|
||||
clientPresenceManager.stop();
|
||||
try {
|
||||
clientPresenceManager.stop();
|
||||
} catch (final Exception e) {
|
||||
if (!expectExceptionOnClientPresenceManagerStop) {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -294,6 +302,8 @@ class ClientPresenceManagerTest {
|
||||
}
|
||||
|
||||
assertTrue(clientPresenceManager.isPresent(displacedAccountUuid, displacedAccountDeviceId));
|
||||
|
||||
expectExceptionOnClientPresenceManagerStop = true;
|
||||
}
|
||||
|
||||
@Nested
|
||||
|
||||
+179
-47
@@ -8,86 +8,218 @@ package org.whispersystems.textsecuregcm.redis;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.atLeastOnce;
|
||||
import static org.mockito.Mockito.clearInvocations;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.reset;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import io.github.resilience4j.circuitbreaker.CallNotPermittedException;
|
||||
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
|
||||
import io.github.resilience4j.core.IntervalFunction;
|
||||
import io.github.resilience4j.retry.Retry;
|
||||
import io.github.resilience4j.retry.RetryConfig;
|
||||
import io.lettuce.core.RedisCommandTimeoutException;
|
||||
import io.lettuce.core.RedisException;
|
||||
import io.lettuce.core.cluster.event.ClusterTopologyChangedEvent;
|
||||
import io.lettuce.core.cluster.pubsub.StatefulRedisClusterPubSubConnection;
|
||||
import io.lettuce.core.cluster.pubsub.api.sync.RedisClusterPubSubCommands;
|
||||
import io.lettuce.core.event.Event;
|
||||
import io.lettuce.core.event.EventBus;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
import java.util.Collections;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
import reactor.test.publisher.TestPublisher;
|
||||
|
||||
class FaultTolerantPubSubConnectionTest {
|
||||
|
||||
private RedisClusterPubSubCommands<String, String> pubSubCommands;
|
||||
private FaultTolerantPubSubConnection<String, String> faultTolerantPubSubConnection;
|
||||
private StatefulRedisClusterPubSubConnection<String, String> pubSubConnection;
|
||||
private RedisClusterPubSubCommands<String, String> pubSubCommands;
|
||||
private FaultTolerantPubSubConnection<String, String> faultTolerantPubSubConnection;
|
||||
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
pubSubConnection = mock(StatefulRedisClusterPubSubConnection.class);
|
||||
|
||||
pubSubCommands = mock(RedisClusterPubSubCommands.class);
|
||||
|
||||
when(pubSubConnection.sync()).thenReturn(pubSubCommands);
|
||||
|
||||
final CircuitBreakerConfiguration breakerConfiguration = new CircuitBreakerConfiguration();
|
||||
breakerConfiguration.setFailureRateThreshold(100);
|
||||
breakerConfiguration.setSlidingWindowSize(1);
|
||||
breakerConfiguration.setSlidingWindowMinimumNumberOfCalls(1);
|
||||
breakerConfiguration.setWaitDurationInOpenStateInSeconds(Integer.MAX_VALUE);
|
||||
|
||||
final RetryConfiguration retryConfiguration = new RetryConfiguration();
|
||||
retryConfiguration.setMaxAttempts(3);
|
||||
retryConfiguration.setWaitDuration(10);
|
||||
|
||||
final CircuitBreaker circuitBreaker = CircuitBreaker.of("test", breakerConfiguration.toCircuitBreakerConfig());
|
||||
final Retry retry = Retry.of("test", retryConfiguration.toRetryConfig());
|
||||
|
||||
final RetryConfig resubscribeRetryConfiguration = RetryConfig.custom()
|
||||
.maxAttempts(Integer.MAX_VALUE)
|
||||
.intervalFunction(IntervalFunction.ofExponentialBackoff(5))
|
||||
.build();
|
||||
final Retry resubscribeRetry = Retry.of("test-resubscribe", resubscribeRetryConfiguration);
|
||||
|
||||
faultTolerantPubSubConnection = new FaultTolerantPubSubConnection<>("test", pubSubConnection, circuitBreaker,
|
||||
retry, resubscribeRetry, Schedulers.newSingle("test"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testBreaker() {
|
||||
when(pubSubCommands.get(anyString()))
|
||||
.thenReturn("value")
|
||||
.thenThrow(new RuntimeException("Badness has ensued."));
|
||||
|
||||
assertEquals("value",
|
||||
faultTolerantPubSubConnection.withPubSubConnection(connection -> connection.sync().get("key")));
|
||||
|
||||
assertThrows(RedisException.class,
|
||||
() -> faultTolerantPubSubConnection.withPubSubConnection(connection -> connection.sync().get("OH NO")));
|
||||
|
||||
final RedisException redisException = assertThrows(RedisException.class,
|
||||
() -> faultTolerantPubSubConnection.withPubSubConnection(connection -> connection.sync().get("OH NO")));
|
||||
|
||||
assertTrue(redisException.getCause() instanceof CallNotPermittedException);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRetry() {
|
||||
when(pubSubCommands.get(anyString()))
|
||||
.thenThrow(new RedisCommandTimeoutException())
|
||||
.thenThrow(new RedisCommandTimeoutException())
|
||||
.thenReturn("value");
|
||||
|
||||
assertEquals("value",
|
||||
faultTolerantPubSubConnection.withPubSubConnection(connection -> connection.sync().get("key")));
|
||||
|
||||
when(pubSubCommands.get(anyString()))
|
||||
.thenThrow(new RedisCommandTimeoutException())
|
||||
.thenThrow(new RedisCommandTimeoutException())
|
||||
.thenThrow(new RedisCommandTimeoutException())
|
||||
.thenReturn("value");
|
||||
|
||||
assertThrows(RedisCommandTimeoutException.class,
|
||||
() -> faultTolerantPubSubConnection.withPubSubConnection(connection -> connection.sync().get("key")));
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ClusterTopologyChangedEventTest {
|
||||
|
||||
private TestPublisher<Event> eventPublisher;
|
||||
|
||||
private Runnable resubscribe;
|
||||
|
||||
private AtomicInteger resubscribeCounter;
|
||||
private CountDownLatch resubscribeFailure;
|
||||
private CountDownLatch resubscribeSuccess;
|
||||
|
||||
@BeforeEach
|
||||
@SuppressWarnings("unchecked")
|
||||
void setup() {
|
||||
// ignore inherited stubbing
|
||||
reset(pubSubConnection);
|
||||
|
||||
eventPublisher = TestPublisher.createCold();
|
||||
|
||||
final ClientResources clientResources = mock(ClientResources.class);
|
||||
when(pubSubConnection.getResources())
|
||||
.thenReturn(clientResources);
|
||||
final EventBus eventBus = mock(EventBus.class);
|
||||
when(clientResources.eventBus())
|
||||
.thenReturn(eventBus);
|
||||
|
||||
final Flux<Event> eventFlux = Flux.from(eventPublisher);
|
||||
when(eventBus.get()).thenReturn(eventFlux);
|
||||
|
||||
resubscribeCounter = new AtomicInteger();
|
||||
|
||||
resubscribe = () -> {
|
||||
try {
|
||||
resubscribeCounter.incrementAndGet();
|
||||
pubSubConnection.sync().nodes((ignored) -> true);
|
||||
resubscribeSuccess.countDown();
|
||||
} catch (final RuntimeException e) {
|
||||
resubscribeFailure.countDown();
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
|
||||
resubscribeSuccess = new CountDownLatch(1);
|
||||
resubscribeFailure = new CountDownLatch(1);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
final StatefulRedisClusterPubSubConnection<String, String> pubSubConnection = mock(
|
||||
StatefulRedisClusterPubSubConnection.class);
|
||||
@Test
|
||||
void testSubscribeToClusterTopologyChangedEvents() throws Exception {
|
||||
|
||||
pubSubCommands = mock(RedisClusterPubSubCommands.class);
|
||||
when(pubSubConnection.sync())
|
||||
.thenThrow(new RedisException("Cluster unavailable"));
|
||||
|
||||
when(pubSubConnection.sync()).thenReturn(pubSubCommands);
|
||||
eventPublisher.next(new ClusterTopologyChangedEvent(Collections.emptyList(), Collections.emptyList()));
|
||||
|
||||
final CircuitBreakerConfiguration breakerConfiguration = new CircuitBreakerConfiguration();
|
||||
breakerConfiguration.setFailureRateThreshold(100);
|
||||
breakerConfiguration.setSlidingWindowSize(1);
|
||||
breakerConfiguration.setSlidingWindowMinimumNumberOfCalls(1);
|
||||
breakerConfiguration.setWaitDurationInOpenStateInSeconds(Integer.MAX_VALUE);
|
||||
faultTolerantPubSubConnection.subscribeToClusterTopologyChangedEvents(resubscribe);
|
||||
|
||||
final RetryConfiguration retryConfiguration = new RetryConfiguration();
|
||||
retryConfiguration.setMaxAttempts(3);
|
||||
retryConfiguration.setWaitDuration(0);
|
||||
assertTrue(resubscribeFailure.await(1, TimeUnit.SECONDS));
|
||||
|
||||
final CircuitBreaker circuitBreaker = CircuitBreaker.of("test", breakerConfiguration.toCircuitBreakerConfig());
|
||||
final Retry retry = Retry.of("test", retryConfiguration.toRetryConfig());
|
||||
// simulate cluster recovery - no more exceptions, run the retry
|
||||
reset(pubSubConnection);
|
||||
clearInvocations(pubSubCommands);
|
||||
when(pubSubConnection.sync())
|
||||
.thenReturn(pubSubCommands);
|
||||
|
||||
faultTolerantPubSubConnection = new FaultTolerantPubSubConnection<>("test", pubSubConnection, circuitBreaker,
|
||||
retry);
|
||||
assertTrue(resubscribeSuccess.await(1, TimeUnit.SECONDS));
|
||||
|
||||
assertTrue(resubscribeCounter.get() >= 2, String.format("resubscribe called %d times", resubscribeCounter.get()));
|
||||
verify(pubSubCommands).nodes(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testBreaker() {
|
||||
when(pubSubCommands.get(anyString()))
|
||||
.thenReturn("value")
|
||||
.thenThrow(new RuntimeException("Badness has ensued."));
|
||||
@SuppressWarnings("unchecked")
|
||||
void testMultipleEventsWithPendingRetries() throws Exception {
|
||||
// more complicated scenario: multiple events while retries are pending
|
||||
|
||||
assertEquals("value", faultTolerantPubSubConnection.withPubSubConnection(connection -> connection.sync().get("key")));
|
||||
// cluster is down
|
||||
when(pubSubConnection.sync())
|
||||
.thenThrow(new RedisException("Cluster unavailable"));
|
||||
|
||||
assertThrows(RedisException.class,
|
||||
() -> faultTolerantPubSubConnection.withPubSubConnection(connection -> connection.sync().get("OH NO")));
|
||||
// publish multiple topology changed events
|
||||
eventPublisher.next(new ClusterTopologyChangedEvent(Collections.emptyList(), Collections.emptyList()));
|
||||
eventPublisher.next(new ClusterTopologyChangedEvent(Collections.emptyList(), Collections.emptyList()));
|
||||
eventPublisher.next(new ClusterTopologyChangedEvent(Collections.emptyList(), Collections.emptyList()));
|
||||
eventPublisher.next(new ClusterTopologyChangedEvent(Collections.emptyList(), Collections.emptyList()));
|
||||
|
||||
final RedisException redisException = assertThrows(RedisException.class,
|
||||
() -> faultTolerantPubSubConnection.withPubSubConnection(connection -> connection.sync().get("OH NO")));
|
||||
faultTolerantPubSubConnection.subscribeToClusterTopologyChangedEvents(resubscribe);
|
||||
|
||||
assertTrue(redisException.getCause() instanceof CallNotPermittedException);
|
||||
assertTrue(resubscribeFailure.await(1, TimeUnit.SECONDS));
|
||||
|
||||
// simulate cluster recovery - no more exceptions, run the retry
|
||||
reset(pubSubConnection);
|
||||
clearInvocations(pubSubCommands);
|
||||
when(pubSubConnection.sync())
|
||||
.thenReturn(pubSubCommands);
|
||||
|
||||
assertTrue(resubscribeSuccess.await(1, TimeUnit.SECONDS));
|
||||
|
||||
verify(pubSubCommands, atLeastOnce()).nodes(any());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRetry() {
|
||||
when(pubSubCommands.get(anyString()))
|
||||
.thenThrow(new RedisCommandTimeoutException())
|
||||
.thenThrow(new RedisCommandTimeoutException())
|
||||
.thenReturn("value");
|
||||
|
||||
assertEquals("value", faultTolerantPubSubConnection.withPubSubConnection(connection -> connection.sync().get("key")));
|
||||
|
||||
when(pubSubCommands.get(anyString()))
|
||||
.thenThrow(new RedisCommandTimeoutException())
|
||||
.thenThrow(new RedisCommandTimeoutException())
|
||||
.thenThrow(new RedisCommandTimeoutException())
|
||||
.thenReturn("value");
|
||||
|
||||
assertThrows(RedisCommandTimeoutException.class, () -> faultTolerantPubSubConnection.withPubSubConnection(connection -> connection.sync().get("key")));
|
||||
}
|
||||
}
|
||||
+43
-41
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2013-2022 Signal Messenger, LLC
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
@@ -30,17 +30,24 @@ import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguratio
|
||||
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.util.RedisClusterUtil;
|
||||
import redis.embedded.RedisServer;
|
||||
import redis.embedded.exceptions.EmbeddedRedisException;
|
||||
|
||||
public class RedisClusterExtension implements BeforeAllCallback, BeforeEachCallback, AfterAllCallback, AfterEachCallback {
|
||||
|
||||
private static final int NODE_COUNT = 2;
|
||||
|
||||
private static final RedisServer[] CLUSTER_NODES = new RedisServer[NODE_COUNT];
|
||||
|
||||
private FaultTolerantRedisCluster redisCluster;
|
||||
|
||||
|
||||
public static RedisClusterExtensionBuilder builder() {
|
||||
return new RedisClusterExtensionBuilder();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void afterAll(final ExtensionContext context) throws Exception {
|
||||
for (final RedisServer node : clusterNodes) {
|
||||
for (final RedisServer node : CLUSTER_NODES) {
|
||||
node.stop();
|
||||
}
|
||||
}
|
||||
@@ -54,21 +61,20 @@ public class RedisClusterExtension implements BeforeAllCallback, BeforeEachCallb
|
||||
public void beforeAll(final ExtensionContext context) throws Exception {
|
||||
assumeFalse(System.getProperty("os.name").equalsIgnoreCase("windows"));
|
||||
|
||||
clusterNodes = new RedisServer[NODE_COUNT];
|
||||
|
||||
for (int i = 0; i < NODE_COUNT; i++) {
|
||||
clusterNodes[i] = buildClusterNode(getNextRedisClusterPort());
|
||||
clusterNodes[i].start();
|
||||
// We're occasionally seeing redis server startup failing due to the bind address being already in use.
|
||||
// To mitigate that, we're going to just retry a couple of times before failing the test.
|
||||
CLUSTER_NODES[i] = startWithRetries(3);
|
||||
}
|
||||
|
||||
assembleCluster(clusterNodes);
|
||||
assembleCluster(CLUSTER_NODES);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beforeEach(final ExtensionContext context) throws Exception {
|
||||
final List<String> urls = Arrays.stream(clusterNodes)
|
||||
final List<String> urls = Arrays.stream(CLUSTER_NODES)
|
||||
.map(node -> String.format("redis://127.0.0.1:%d", node.ports().get(0)))
|
||||
.collect(Collectors.toList());
|
||||
.toList();
|
||||
|
||||
redisCluster = new FaultTolerantRedisCluster("test-cluster",
|
||||
RedisClusterClient.create(urls.stream().map(RedisURI::create).collect(Collectors.toList())),
|
||||
@@ -105,12 +111,6 @@ public class RedisClusterExtension implements BeforeAllCallback, BeforeEachCallb
|
||||
redisCluster.useCluster(connection -> connection.sync().flushall());
|
||||
}
|
||||
|
||||
private static final int NODE_COUNT = 2;
|
||||
|
||||
private static RedisServer[] clusterNodes;
|
||||
|
||||
private FaultTolerantRedisCluster redisCluster;
|
||||
|
||||
public FaultTolerantRedisCluster getRedisCluster() {
|
||||
return redisCluster;
|
||||
}
|
||||
@@ -131,17 +131,13 @@ public class RedisClusterExtension implements BeforeAllCallback, BeforeEachCallb
|
||||
}
|
||||
|
||||
private static void assembleCluster(final RedisServer... nodes) throws InterruptedException {
|
||||
final RedisClient meetClient = RedisClient.create(RedisURI.create("127.0.0.1", nodes[0].ports().get(0)));
|
||||
|
||||
try {
|
||||
try (final RedisClient meetClient = RedisClient.create(RedisURI.create("127.0.0.1", nodes[0].ports().get(0)))) {
|
||||
final StatefulRedisConnection<String, String> connection = meetClient.connect();
|
||||
final RedisCommands<String, String> commands = connection.sync();
|
||||
|
||||
for (int i = 1; i < nodes.length; i++) {
|
||||
commands.clusterMeet("127.0.0.1", nodes[i].ports().get(0));
|
||||
}
|
||||
} finally {
|
||||
meetClient.shutdown();
|
||||
}
|
||||
|
||||
final int slotsPerNode = SlotHash.SLOT_COUNT / nodes.length;
|
||||
@@ -150,9 +146,8 @@ public class RedisClusterExtension implements BeforeAllCallback, BeforeEachCallb
|
||||
final int startInclusive = i * slotsPerNode;
|
||||
final int endExclusive = i == nodes.length - 1 ? SlotHash.SLOT_COUNT : (i + 1) * slotsPerNode;
|
||||
|
||||
final RedisClient assignSlotClient = RedisClient.create(RedisURI.create("127.0.0.1", nodes[i].ports().get(0)));
|
||||
|
||||
try (final StatefulRedisConnection<String, String> assignSlotConnection = assignSlotClient.connect()) {
|
||||
try (final RedisClient assignSlotClient = RedisClient.create(RedisURI.create("127.0.0.1", nodes[i].ports().get(0)));
|
||||
final StatefulRedisConnection<String, String> assignSlotConnection = assignSlotClient.connect()) {
|
||||
final int[] slots = new int[endExclusive - startInclusive];
|
||||
|
||||
for (int s = startInclusive; s < endExclusive; s++) {
|
||||
@@ -160,14 +155,11 @@ public class RedisClusterExtension implements BeforeAllCallback, BeforeEachCallb
|
||||
}
|
||||
|
||||
assignSlotConnection.sync().clusterAddSlots(slots);
|
||||
} finally {
|
||||
assignSlotClient.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
final RedisClient waitClient = RedisClient.create(RedisURI.create("127.0.0.1", nodes[0].ports().get(0)));
|
||||
|
||||
try (final StatefulRedisConnection<String, String> connection = waitClient.connect()) {
|
||||
try (final RedisClient waitClient = RedisClient.create(RedisURI.create("127.0.0.1", nodes[0].ports().get(0)));
|
||||
final StatefulRedisConnection<String, String> connection = waitClient.connect()) {
|
||||
// CLUSTER INFO gives us a big blob of key-value pairs, but the one we're interested in is `cluster_state`.
|
||||
// According to https://redis.io/commands/cluster-info, `cluster_state:ok` means that the node is ready to
|
||||
// receive queries, all slots are assigned, and a majority of master nodes are reachable.
|
||||
@@ -183,30 +175,40 @@ public class RedisClusterExtension implements BeforeAllCallback, BeforeEachCallb
|
||||
String.format("Timeout: Redis not ready after waiting %d milliseconds", tries * sleepMillis));
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
waitClient.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
public static int getNextRedisClusterPort() throws IOException {
|
||||
final int MAX_ITERATIONS = 11_000;
|
||||
int port;
|
||||
for (int i = 0; i < MAX_ITERATIONS; i++) {
|
||||
try (ServerSocket socket = new ServerSocket(0)) {
|
||||
final int maxIterations = 11_000;
|
||||
for (int i = 0; i < maxIterations; i++) {
|
||||
try (final ServerSocket socket = new ServerSocket(0)) {
|
||||
socket.setReuseAddress(false);
|
||||
port = socket.getLocalPort();
|
||||
}
|
||||
if (port < 55535) {
|
||||
return port;
|
||||
final int port = socket.getLocalPort();
|
||||
if (port < 55535) {
|
||||
return port;
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new IOException("Couldn't find an open port below 55,535 in " + MAX_ITERATIONS + " tries");
|
||||
throw new IOException("Couldn't find an unused open port below 55,535 in " + maxIterations + " tries");
|
||||
}
|
||||
|
||||
private static RedisServer startWithRetries(final int attemptsLeft) throws Exception {
|
||||
try {
|
||||
final RedisServer redisServer = buildClusterNode(getNextRedisClusterPort());
|
||||
redisServer.start();
|
||||
return redisServer;
|
||||
} catch (final IOException | EmbeddedRedisException e) {
|
||||
if (attemptsLeft == 0) {
|
||||
throw e;
|
||||
}
|
||||
Thread.sleep(500);
|
||||
return startWithRetries(attemptsLeft - 1);
|
||||
}
|
||||
}
|
||||
|
||||
public static class RedisClusterExtensionBuilder {
|
||||
|
||||
private RedisClusterExtensionBuilder() {
|
||||
|
||||
}
|
||||
|
||||
public RedisClusterExtension build() {
|
||||
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.securevaluerecovery;
|
||||
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.delete;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
|
||||
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.github.tomakehurst.wiremock.junit5.WireMockExtension;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureValueRecovery2Configuration;
|
||||
|
||||
class SecureValueRecovery2ClientTest {
|
||||
|
||||
private UUID accountUuid;
|
||||
private ExternalServiceCredentialsGenerator credentialsGenerator;
|
||||
private ExecutorService httpExecutor;
|
||||
|
||||
private SecureValueRecovery2Client secureValueRecovery2Client;
|
||||
|
||||
@RegisterExtension
|
||||
private final WireMockExtension wireMock = WireMockExtension.newInstance()
|
||||
.options(wireMockConfig().dynamicPort().dynamicHttpsPort())
|
||||
.build();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws CertificateException {
|
||||
accountUuid = UUID.randomUUID();
|
||||
credentialsGenerator = mock(ExternalServiceCredentialsGenerator.class);
|
||||
httpExecutor = Executors.newSingleThreadExecutor();
|
||||
|
||||
final SecureValueRecovery2Configuration config = new SecureValueRecovery2Configuration(true,
|
||||
"http://localhost:" + wireMock.getPort(),
|
||||
new byte[0], new byte[0],
|
||||
// This is a randomly-generated, throwaway certificate that's not actually connected to anything
|
||||
List.of("""
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIICZDCCAc2gAwIBAgIBADANBgkqhkiG9w0BAQ0FADBPMQswCQYDVQQGEwJ1czEL
|
||||
MAkGA1UECAwCVVMxHjAcBgNVBAoMFVNpZ25hbCBNZXNzZW5nZXIsIExMQzETMBEG
|
||||
A1UEAwwKc2lnbmFsLm9yZzAeFw0yMDEyMjMyMjQ3NTlaFw0zMDEyMjEyMjQ3NTla
|
||||
ME8xCzAJBgNVBAYTAnVzMQswCQYDVQQIDAJVUzEeMBwGA1UECgwVU2lnbmFsIE1l
|
||||
c3NlbmdlciwgTExDMRMwEQYDVQQDDApzaWduYWwub3JnMIGfMA0GCSqGSIb3DQEB
|
||||
AQUAA4GNADCBiQKBgQCfSLcZNHYqbxSsgWp4JvbPRHjQTrlsrKrgD2q7f/OY6O3Y
|
||||
/X0QNcNSOJpliN8rmzwslfsrXHO3q1diGRw4xHogUJZ/7NQrHiP/zhN0VTDh49pD
|
||||
ZpjXVyUbayLS/6qM5arKxBspzEFBb5v8cF6bPr76SO/rpGXiI0j6yJKX6fRiKwID
|
||||
AQABo1AwTjAdBgNVHQ4EFgQU6Jrs/Fmj0z4dA3wvdq/WqA4P49IwHwYDVR0jBBgw
|
||||
FoAU6Jrs/Fmj0z4dA3wvdq/WqA4P49IwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0B
|
||||
AQ0FAAOBgQB+5d5+NtzLILfrc9QmJdIO1YeDP64JmFwTER0kEUouRsb9UwknVWZa
|
||||
y7MTM4NoBV1k0zb5LAk89SIDPr/maW5AsLtEomzjnEiomjoMBUdNe3YCgQReoLnr
|
||||
R/QaUNbrCjTGYfBsjGbIzmkWPUyTec2ZdRyJ8JiVl386+6CZkxnndQ==
|
||||
-----END CERTIFICATE-----
|
||||
""", """
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIEpDCCAowCCQC43PUTWSADVjANBgkqhkiG9w0BAQsFADAUMRIwEAYDVQQDDAls
|
||||
b2NhbGhvc3QwHhcNMjIxMDE3MjA0NTM0WhcNMjMxMDE3MjA0NTM0WjAUMRIwEAYD
|
||||
VQQDDAlsb2NhbGhvc3QwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDV
|
||||
x1cdEd2ffQTlTXWRiCHGcrlYf4RJnctt9sw/BuHWTLXBu5LhyJSGn5LRszO/NCXK
|
||||
Z/cmGR7pLj366RtiwL+Qo3nhvDCK7T9xZeNIusM6XMcMK9D/DGCYPqtjQz8NXd9V
|
||||
ajBBe6nwTDTa+oqX8Mt89foWNkg5Il/lY62u9Dr18LRZ2W9zzYi3Q9/K0CbIX6pM
|
||||
yVlPIO5rITOR2IsbeyqsO9jufgX5lP4ZKLLBAP1b7usjC4YdvWacjQg/rK5aay1x
|
||||
jC2HCDgo/4N30QVXzSA9nFfSe6AE/xkStK4819JqOkY5JsJCbef1P3hOOdSLEjbp
|
||||
xq3MjOs6G6dOgteaAGs10vx7dHxDWETTIiD7BIZ9zRYgOF5bkCaIUO+JfySE1MHD
|
||||
KBAFLoRuvmRev5Ln5R0MCHpUMSmMNgJqz+RWZV3g/gpYbuWiHgJOwL1393eK50Bg
|
||||
W7SXQ8EjJj2yXZSH+1gPzN0DRoJZiaBoTPnCL2qUgvwFpW1PJsM5FDyUJFUoK5kK
|
||||
HLBBSKAPt6ZlSrUe2nBgJv7EF1GK+fTU08LXgW33OpLceGPa0zTShkukQUMtUtZ8
|
||||
GqhO12ohMzEupIu5Xurthq4VVUrzHUdj1ZZRMhAbfLU36sd03MMyL/xBqTN6dzCa
|
||||
GDGIPGpYjAllZ5xMRt2kZdv+Kr6oo3u2nLUIsqI7KQIDAQABMA0GCSqGSIb3DQEB
|
||||
CwUAA4ICAQCB5s43YF35ssf5YONW5iAaifGpi1o0866xfeOybtohFGvQ7V2W34i9
|
||||
TYBCt8+0hgatMcvZ08f0vqig1i7nrvYcE1hnhL7JNkU8qm0s9ytHZt6j62nB0kd/
|
||||
uqE2hOEQalTf/2TGPV0CCgiqLyd8lEUQvQeA38wktwUeZpVnErlzHeMR2CvV3K8R
|
||||
u4vV6SnBcf+TAt56RKYZkPyvZj5llQPo14Glyoo8qZES7Ky1SHmM0GL+baPRBjRW
|
||||
3KgSt98Wyu4yr9qu21JpnbAnLhBfzfSKjSeCRgFElUE1GIaFGRZ7ypA74dUKeLnb
|
||||
/VUWrszmUhGaEjV9dpI6x6B/kSpQMtIQqBaKRY2ALUeEujS/rURi4iMDwSU+GkSH
|
||||
cyEvZKS97OA/dWeXfLXdo4beDBRG93bI4rQnDg5+VdlBOkQSLueb8x6/VThMoC5d
|
||||
vZiotFQHseljQAdTkNa6tBu6c4XDYPCKB3CfkMYOlCfTS7Acn5G6dxTPKBtLGBnL
|
||||
nQfYyzuwYkN09+2PVzt6auBHr3To7uoclkxX+hxyvPIwIZ0N6b4tQR1FCAkvg29Q
|
||||
WIOjZOKGW690ESKCKOnFjUHVO0HpuWnT81URTuY62FXsYdVc2wE4v0E04mEbqQ0P
|
||||
lY6ZKNA81Lm3YADYtObmK1IUrOPo9BeIaPy0UM08SmN880Vunqa91Q==
|
||||
-----END CERTIFICATE-----
|
||||
"""),
|
||||
null, null);
|
||||
|
||||
secureValueRecovery2Client = new SecureValueRecovery2Client(credentialsGenerator, httpExecutor, config);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws InterruptedException {
|
||||
httpExecutor.shutdown();
|
||||
httpExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteStoredData() {
|
||||
final String username = RandomStringUtils.randomAlphabetic(16);
|
||||
final String password = RandomStringUtils.randomAlphanumeric(32);
|
||||
|
||||
when(credentialsGenerator.generateForUuid(accountUuid)).thenReturn(
|
||||
new ExternalServiceCredentials(username, password));
|
||||
|
||||
wireMock.stubFor(delete(urlEqualTo(SecureValueRecovery2Client.DELETE_PATH))
|
||||
.withBasicAuth(username, password)
|
||||
.willReturn(aResponse().withStatus(202)));
|
||||
|
||||
assertDoesNotThrow(() -> secureValueRecovery2Client.deleteBackups(accountUuid).join());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteStoredDataFailure() {
|
||||
final String username = RandomStringUtils.randomAlphabetic(16);
|
||||
final String password = RandomStringUtils.randomAlphanumeric(32);
|
||||
|
||||
when(credentialsGenerator.generateForUuid(accountUuid)).thenReturn(
|
||||
new ExternalServiceCredentials(username, password));
|
||||
|
||||
wireMock.stubFor(delete(urlEqualTo(SecureValueRecovery2Client.DELETE_PATH))
|
||||
.withBasicAuth(username, password)
|
||||
.willReturn(aResponse().withStatus(400)));
|
||||
|
||||
final CompletionException completionException = assertThrows(CompletionException.class,
|
||||
() -> secureValueRecovery2Client.deleteBackups(accountUuid).join());
|
||||
assertTrue(completionException.getCause() instanceof SecureValueRecoveryException);
|
||||
}
|
||||
}
|
||||
+5
@@ -32,6 +32,7 @@ import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.securebackup.SecureBackupClient;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
|
||||
import org.whispersystems.textsecuregcm.sqs.DirectoryQueue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
|
||||
import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest;
|
||||
@@ -178,6 +179,9 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
final SecureBackupClient secureBackupClient = mock(SecureBackupClient.class);
|
||||
when(secureBackupClient.deleteBackups(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final SecureValueRecovery2Client svr2Client = mock(SecureValueRecovery2Client.class);
|
||||
when(svr2Client.deleteBackups(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
clientPresenceManager = mock(ClientPresenceManager.class);
|
||||
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers =
|
||||
@@ -195,6 +199,7 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
mock(StoredVerificationCodeManager.class),
|
||||
secureStorageClient,
|
||||
secureBackupClient,
|
||||
svr2Client,
|
||||
clientPresenceManager,
|
||||
mock(ExperimentEnrollmentManager.class),
|
||||
mock(RegistrationRecoveryPasswordsManager.class),
|
||||
|
||||
+2
@@ -46,6 +46,7 @@ import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.securebackup.SecureBackupClient;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
|
||||
import org.whispersystems.textsecuregcm.sqs.DirectoryQueue;
|
||||
import org.whispersystems.textsecuregcm.tests.util.DevicesHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.JsonHelpers;
|
||||
@@ -162,6 +163,7 @@ class AccountsManagerConcurrentModificationIntegrationTest {
|
||||
mock(StoredVerificationCodeManager.class),
|
||||
mock(SecureStorageClient.class),
|
||||
mock(SecureBackupClient.class),
|
||||
mock(SecureValueRecovery2Client.class),
|
||||
mock(ClientPresenceManager.class),
|
||||
mock(ExperimentEnrollmentManager.class),
|
||||
mock(RegistrationRecoveryPasswordsManager.class),
|
||||
|
||||
+5
@@ -55,6 +55,7 @@ import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.securebackup.SecureBackupClient;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
|
||||
import org.whispersystems.textsecuregcm.sqs.DirectoryQueue;
|
||||
import org.whispersystems.textsecuregcm.storage.Device.DeviceCapabilities;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
|
||||
@@ -121,6 +122,9 @@ class AccountsManagerTest {
|
||||
final SecureBackupClient backupClient = mock(SecureBackupClient.class);
|
||||
when(backupClient.deleteBackups(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final SecureValueRecovery2Client svr2Client = mock(SecureValueRecovery2Client.class);
|
||||
when(svr2Client.deleteBackups(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers = mock(PhoneNumberIdentifiers.class);
|
||||
phoneNumberIdentifiersByE164 = new HashMap<>();
|
||||
|
||||
@@ -152,6 +156,7 @@ class AccountsManagerTest {
|
||||
mock(StoredVerificationCodeManager.class),
|
||||
storageClient,
|
||||
backupClient,
|
||||
svr2Client,
|
||||
mock(ClientPresenceManager.class),
|
||||
enrollmentManager,
|
||||
mock(RegistrationRecoveryPasswordsManager.class),
|
||||
|
||||
+2
@@ -43,6 +43,7 @@ import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.securebackup.SecureBackupClient;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
|
||||
import org.whispersystems.textsecuregcm.sqs.DirectoryQueue;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
|
||||
@@ -183,6 +184,7 @@ class AccountsManagerUsernameIntegrationTest {
|
||||
mock(StoredVerificationCodeManager.class),
|
||||
mock(SecureStorageClient.class),
|
||||
mock(SecureBackupClient.class),
|
||||
mock(SecureValueRecovery2Client.class),
|
||||
mock(ClientPresenceManager.class),
|
||||
experimentEnrollmentManager,
|
||||
mock(RegistrationRecoveryPasswordsManager.class),
|
||||
|
||||
+11
-2
@@ -24,6 +24,7 @@ import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
@@ -35,6 +36,8 @@ import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfigurati
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.tests.util.MessagesDynamoDbExtension;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ScanRequest;
|
||||
|
||||
@@ -47,7 +50,9 @@ class MessagePersisterIntegrationTest {
|
||||
static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
|
||||
|
||||
private ExecutorService notificationExecutorService;
|
||||
private Scheduler messageDeliveryScheduler;
|
||||
private ExecutorService messageDeletionExecutorService;
|
||||
private ScheduledExecutorService resubscribeRetryExecutorService;
|
||||
private MessagesCache messagesCache;
|
||||
private MessagesManager messagesManager;
|
||||
private MessagePersister messagePersister;
|
||||
@@ -67,6 +72,7 @@ class MessagePersisterIntegrationTest {
|
||||
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(new DynamicConfiguration());
|
||||
|
||||
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
|
||||
messageDeletionExecutorService = Executors.newSingleThreadExecutor();
|
||||
final MessagesDynamoDb messagesDynamoDb = new MessagesDynamoDb(dynamoDbExtension.getDynamoDbClient(),
|
||||
dynamoDbExtension.getDynamoDbAsyncClient(), MessagesDynamoDbExtension.TABLE_NAME, Duration.ofDays(14),
|
||||
@@ -74,9 +80,10 @@ class MessagePersisterIntegrationTest {
|
||||
final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
|
||||
notificationExecutorService = Executors.newSingleThreadExecutor();
|
||||
resubscribeRetryExecutorService = Executors.newSingleThreadScheduledExecutor();
|
||||
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster(), Clock.systemUTC(), notificationExecutorService,
|
||||
messageDeletionExecutorService);
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster(), notificationExecutorService,
|
||||
messageDeliveryScheduler, messageDeletionExecutorService, Clock.systemUTC());
|
||||
messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, mock(ReportMessageManager.class),
|
||||
messageDeletionExecutorService);
|
||||
messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager,
|
||||
@@ -102,6 +109,8 @@ class MessagePersisterIntegrationTest {
|
||||
|
||||
messageDeletionExecutorService.shutdown();
|
||||
messageDeletionExecutorService.awaitTermination(15, TimeUnit.SECONDS);
|
||||
|
||||
messageDeliveryScheduler.dispose();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+13
-1
@@ -30,6 +30,7 @@ import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
@@ -41,6 +42,8 @@ import org.mockito.stubbing.Answer;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
|
||||
class MessagePersisterTest {
|
||||
|
||||
@@ -48,6 +51,8 @@ class MessagePersisterTest {
|
||||
static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
|
||||
|
||||
private ExecutorService sharedExecutorService;
|
||||
private ScheduledExecutorService resubscribeRetryExecutorService;
|
||||
private Scheduler messageDeliveryScheduler;
|
||||
private MessagesCache messagesCache;
|
||||
private MessagesDynamoDb messagesDynamoDb;
|
||||
private MessagePersister messagePersister;
|
||||
@@ -76,8 +81,11 @@ class MessagePersisterTest {
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(new DynamicConfiguration());
|
||||
|
||||
sharedExecutorService = Executors.newSingleThreadExecutor();
|
||||
resubscribeRetryExecutorService = Executors.newSingleThreadScheduledExecutor();
|
||||
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
|
||||
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster(), Clock.systemUTC(), sharedExecutorService, sharedExecutorService);
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster(), sharedExecutorService, messageDeliveryScheduler,
|
||||
sharedExecutorService, Clock.systemUTC());
|
||||
messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager,
|
||||
dynamicConfigurationManager, PERSIST_DELAY);
|
||||
|
||||
@@ -100,6 +108,10 @@ class MessagePersisterTest {
|
||||
void tearDown() throws Exception {
|
||||
sharedExecutorService.shutdown();
|
||||
sharedExecutorService.awaitTermination(1, TimeUnit.SECONDS);
|
||||
|
||||
messageDeliveryScheduler.dispose();
|
||||
resubscribeRetryExecutorService.shutdown();
|
||||
resubscribeRetryExecutorService.awaitTermination(1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+20
-9
@@ -42,6 +42,7 @@ import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
@@ -64,6 +65,8 @@ import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.tests.util.RedisClusterHelper;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.FluxSink;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
import reactor.test.StepVerifier;
|
||||
|
||||
class MessagesCacheTest {
|
||||
@@ -78,9 +81,12 @@ class MessagesCacheTest {
|
||||
static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
|
||||
|
||||
private ExecutorService sharedExecutorService;
|
||||
private ScheduledExecutorService resubscribeRetryExecutorService;
|
||||
private Scheduler messageDeliveryScheduler;
|
||||
private MessagesCache messagesCache;
|
||||
|
||||
private static final UUID DESTINATION_UUID = UUID.randomUUID();
|
||||
|
||||
private static final int DESTINATION_DEVICE_ID = 7;
|
||||
|
||||
@BeforeEach
|
||||
@@ -92,9 +98,10 @@ class MessagesCacheTest {
|
||||
});
|
||||
|
||||
sharedExecutorService = Executors.newSingleThreadExecutor();
|
||||
resubscribeRetryExecutorService = Executors.newSingleThreadScheduledExecutor();
|
||||
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
|
||||
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster(), Clock.systemUTC(), sharedExecutorService,
|
||||
sharedExecutorService);
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster(), sharedExecutorService, messageDeliveryScheduler, sharedExecutorService, Clock.systemUTC());
|
||||
|
||||
messagesCache.start();
|
||||
}
|
||||
@@ -105,6 +112,10 @@ class MessagesCacheTest {
|
||||
|
||||
sharedExecutorService.shutdown();
|
||||
sharedExecutorService.awaitTermination(1, TimeUnit.SECONDS);
|
||||
|
||||
messageDeliveryScheduler.dispose();
|
||||
resubscribeRetryExecutorService.shutdown();
|
||||
resubscribeRetryExecutorService.awaitTermination(1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -263,10 +274,7 @@ class MessagesCacheTest {
|
||||
}
|
||||
|
||||
final MessagesCache messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
cacheClock,
|
||||
sharedExecutorService,
|
||||
sharedExecutorService);
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster(), sharedExecutorService, messageDeliveryScheduler, sharedExecutorService, cacheClock);
|
||||
|
||||
final List<MessageProtos.Envelope> actualMessages = Flux.from(
|
||||
messagesCache.get(DESTINATION_UUID, DESTINATION_DEVICE_ID))
|
||||
@@ -547,25 +555,28 @@ class MessagesCacheTest {
|
||||
private MessagesCache messagesCache;
|
||||
private RedisAdvancedClusterReactiveCommands<byte[], byte[]> reactiveCommands;
|
||||
private RedisAdvancedClusterAsyncCommands<byte[], byte[]> asyncCommands;
|
||||
private Scheduler messageDeliveryScheduler;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@BeforeEach
|
||||
void setup() throws Exception {
|
||||
reactiveCommands = mock(RedisAdvancedClusterReactiveCommands.class);
|
||||
asyncCommands = mock(RedisAdvancedClusterAsyncCommands.class);
|
||||
|
||||
final FaultTolerantRedisCluster mockCluster = RedisClusterHelper.builder()
|
||||
.binaryReactiveCommands(reactiveCommands)
|
||||
.binaryAsyncCommands(asyncCommands)
|
||||
.build();
|
||||
|
||||
messagesCache = new MessagesCache(mockCluster, mockCluster, Clock.systemUTC(), mock(ExecutorService.class),
|
||||
Executors.newSingleThreadExecutor());
|
||||
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
|
||||
|
||||
messagesCache = new MessagesCache(mockCluster, mockCluster, mock(ExecutorService.class),
|
||||
messageDeliveryScheduler, Executors.newSingleThreadExecutor(), Clock.systemUTC());
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void teardown() {
|
||||
StepVerifier.resetDefaultTimeout();
|
||||
messageDeliveryScheduler.dispose();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+11
@@ -112,4 +112,15 @@ class ExternalServiceCredentialsGeneratorTest {
|
||||
assertEquals(generator.validateAndGetTimestamp(credentials, elapsedSeconds + 1).orElseThrow(), TIME_SECONDS);
|
||||
assertTrue(generator.validateAndGetTimestamp(credentials, elapsedSeconds - 1).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTruncateLength() throws Exception {
|
||||
final ExternalServiceCredentialsGenerator generator = ExternalServiceCredentialsGenerator.builder(new byte[32])
|
||||
.withUserDerivationKey(new byte[32])
|
||||
.withTruncateLength(14)
|
||||
.build();
|
||||
final ExternalServiceCredentials creds = generator.generateFor(E164);
|
||||
assertEquals(14*2 /* 2 chars per byte, because hex */, creds.username().length());
|
||||
assertEquals("805b84df7eff1e8fe1baf0c6e838", creds.username());
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -199,7 +199,7 @@ class KeysControllerTest {
|
||||
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get(PreKeyCount.class);
|
||||
|
||||
assertThat(result.getCount()).isEqualTo(4);
|
||||
assertThat(result.getCount()).isEqualTo(5);
|
||||
|
||||
verify(KEYS).getCount(AuthHelper.VALID_UUID, 1);
|
||||
}
|
||||
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.util.redis;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.whispersystems.textsecuregcm.util.redis.RedisLuaScriptSandbox.tail;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* This class is to be extended with implementations of Redis commands as needed.
|
||||
*/
|
||||
public class BaseRedisCommandsHandler implements RedisCommandsHandler {
|
||||
|
||||
@Override
|
||||
public Object redisCommand(final String command, final List<Object> args) {
|
||||
return switch (command.toUpperCase(Locale.ROOT)) {
|
||||
case "SET" -> {
|
||||
assertTrue(args.size() > 2);
|
||||
yield set(args.get(0).toString(), args.get(1).toString(), tail(args, 2));
|
||||
}
|
||||
case "GET" -> {
|
||||
assertEquals(1, args.size());
|
||||
yield get(args.get(0).toString());
|
||||
}
|
||||
case "DEL" -> {
|
||||
assertTrue(args.size() >= 1);
|
||||
yield del(args.stream().map(Object::toString).toList());
|
||||
}
|
||||
case "HSET" -> {
|
||||
assertTrue(args.size() > 1);
|
||||
assertTrue(args.size() % 2 == 1);
|
||||
yield hset(args.get(0).toString(), tail(args, 1));
|
||||
}
|
||||
case "HGET" -> {
|
||||
assertEquals(2, args.size());
|
||||
yield hget(args.get(0).toString(), args.get(1).toString());
|
||||
}
|
||||
case "HMGET" -> {
|
||||
assertTrue(args.size() > 1);
|
||||
yield hmget(args.get(0).toString(), tail(args, 1));
|
||||
}
|
||||
case "PEXPIRE" -> {
|
||||
assertEquals(2, args.size());
|
||||
yield pexpire(args.get(0).toString(), Double.valueOf(args.get(1).toString()).longValue(), tail(args, 2));
|
||||
}
|
||||
case "TYPE" -> {
|
||||
assertEquals(1, args.size());
|
||||
yield type(args.get(0).toString());
|
||||
}
|
||||
case "RPUSH" -> {
|
||||
assertTrue(args.size() > 1);
|
||||
yield push(false, args.get(0).toString(), tail(args, 1));
|
||||
}
|
||||
case "LPUSH" -> {
|
||||
assertTrue(args.size() > 1);
|
||||
yield push(true, args.get(0).toString(), tail(args, 1));
|
||||
}
|
||||
case "RPOP" -> {
|
||||
assertEquals(2, args.size());
|
||||
yield pop(false, args.get(0).toString(), Double.valueOf(args.get(1).toString()).intValue());
|
||||
}
|
||||
case "LPOP" -> {
|
||||
assertEquals(2, args.size());
|
||||
yield pop(true, args.get(0).toString(), Double.valueOf(args.get(1).toString()).intValue());
|
||||
}
|
||||
|
||||
default -> other(command, args);
|
||||
};
|
||||
}
|
||||
|
||||
public Object[] pop(final boolean left, final String key, final int count) {
|
||||
return new Object[count];
|
||||
}
|
||||
|
||||
public Object push(final boolean left, final String key, final List<Object> values) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
public Object type(final String key) {
|
||||
return Map.of("ok", "none");
|
||||
}
|
||||
|
||||
public Object pexpire(final String key, final long ttlMillis, final List<Object> args) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
public Object hset(final String key, final List<Object> fieldsAndValues) {
|
||||
return "OK";
|
||||
}
|
||||
|
||||
public Object hget(final String key, final String field) {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Object[] hmget(final String key, final List<Object> fields) {
|
||||
return new Object[fields.size()];
|
||||
}
|
||||
|
||||
public Object set(final String key, final String value, final List<Object> tail) {
|
||||
return "OK";
|
||||
}
|
||||
|
||||
public String get(final String key) {
|
||||
return null;
|
||||
}
|
||||
|
||||
public int del(final List<String> keys) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
public Object other(final String command, final List<Object> args) {
|
||||
return "OK";
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.util.redis;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface RedisCommandsHandler {
|
||||
|
||||
Object redisCommand(String command, List<Object> args);
|
||||
}
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.util.redis;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.google.common.io.Resources;
|
||||
import io.lettuce.core.ScriptOutputType;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import party.iroiro.luajava.Lua;
|
||||
import party.iroiro.luajava.lua51.Lua51;
|
||||
import party.iroiro.luajava.value.ImmutableLuaValue;
|
||||
|
||||
public class RedisLuaScriptSandbox {
|
||||
|
||||
private static final String PREFIX = """
|
||||
function redis_call(...)
|
||||
-- variable name needs to match the one used in the `L.setGlobal()` call
|
||||
-- method name needs to match method name of the Java class
|
||||
local result = proxy:redisCall(arg)
|
||||
if type(result) == "userdata" then
|
||||
return java.luaify(result)
|
||||
else
|
||||
return result
|
||||
end
|
||||
end
|
||||
|
||||
function json_encode(obj)
|
||||
return mapper:encode(obj)
|
||||
end
|
||||
|
||||
function json_decode(json)
|
||||
return java.luaify(mapper:decode(json))
|
||||
end
|
||||
|
||||
local redis = { call = redis_call }
|
||||
local cjson = { encode = json_encode, decode = json_decode }
|
||||
|
||||
""";
|
||||
|
||||
private final String luaScript;
|
||||
|
||||
private final ScriptOutputType scriptOutputType;
|
||||
|
||||
|
||||
public static RedisLuaScriptSandbox fromResource(
|
||||
final String resource,
|
||||
final ScriptOutputType scriptOutputType) {
|
||||
try {
|
||||
final String src = Resources.toString(Resources.getResource(resource), StandardCharsets.UTF_8);
|
||||
return new RedisLuaScriptSandbox(src, scriptOutputType);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public RedisLuaScriptSandbox(final String luaScript, final ScriptOutputType scriptOutputType) {
|
||||
this.luaScript = luaScript;
|
||||
this.scriptOutputType = scriptOutputType;
|
||||
}
|
||||
|
||||
public Object execute(
|
||||
final List<String> keys,
|
||||
final List<String> args,
|
||||
final RedisCommandsHandler redisCallsHandler) {
|
||||
|
||||
try (final Lua lua = new Lua51()) {
|
||||
lua.openLibraries();
|
||||
final RedisLuaProxy proxy = new RedisLuaProxy(redisCallsHandler);
|
||||
lua.push(MapperLuaProxy.INSTANCE, Lua.Conversion.FULL);
|
||||
lua.setGlobal("mapper");
|
||||
lua.push(proxy, Lua.Conversion.FULL);
|
||||
lua.setGlobal("proxy");
|
||||
lua.push(keys, Lua.Conversion.FULL);
|
||||
lua.setGlobal("KEYS");
|
||||
lua.push(args, Lua.Conversion.FULL);
|
||||
lua.setGlobal("ARGV");
|
||||
final Lua.LuaError executionResult = lua.run(PREFIX + luaScript);
|
||||
assertEquals("OK", executionResult.name(), "Runtime error during Lua script execution");
|
||||
return adaptOutputResult(lua.get());
|
||||
}
|
||||
}
|
||||
|
||||
protected Object adaptOutputResult(final Object luaObject) {
|
||||
if (luaObject instanceof ImmutableLuaValue<?> luaValue) {
|
||||
final Object javaValue = luaValue.toJavaObject();
|
||||
// validate expected script output type
|
||||
switch (scriptOutputType) {
|
||||
case INTEGER -> assertTrue(javaValue instanceof Double); // lua number is always Double
|
||||
case STATUS -> assertTrue(javaValue instanceof String);
|
||||
case BOOLEAN -> assertTrue(javaValue instanceof Boolean);
|
||||
};
|
||||
if (javaValue instanceof Double d) {
|
||||
return d.longValue();
|
||||
}
|
||||
if (javaValue instanceof String s) {
|
||||
return s;
|
||||
}
|
||||
if (javaValue instanceof Boolean b) {
|
||||
return b;
|
||||
}
|
||||
if (javaValue == null) {
|
||||
return null;
|
||||
}
|
||||
throw new IllegalStateException("unexpected script result java type: " + javaValue.getClass().getName());
|
||||
}
|
||||
throw new IllegalStateException("unexpected script result lua type: " + luaObject.getClass().getName());
|
||||
}
|
||||
|
||||
public static <T> List<T> tail(final List<T> list, final int fromIdx) {
|
||||
return fromIdx < list.size() ? list.subList(fromIdx, list.size()) : Collections.emptyList();
|
||||
}
|
||||
|
||||
public static final class MapperLuaProxy {
|
||||
|
||||
public static final MapperLuaProxy INSTANCE = new MapperLuaProxy();
|
||||
|
||||
public String encode(final Map<Object, Object> obj) {
|
||||
try {
|
||||
return SystemMapper.jsonMapper().writeValueAsString(obj);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public Map<Object, Object> decode(final Object json) {
|
||||
try {
|
||||
//noinspection unchecked
|
||||
return SystemMapper.jsonMapper().readValue(json.toString(), Map.class);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Instances of this class are passed to the Lua scripting engine
|
||||
* and serve as a stubs for the calls to `redis.call()`.
|
||||
*
|
||||
* @see #PREFIX
|
||||
*/
|
||||
public static final class RedisLuaProxy {
|
||||
|
||||
private final RedisCommandsHandler handler;
|
||||
|
||||
public RedisLuaProxy(final RedisCommandsHandler handler) {
|
||||
this.handler = handler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Method name needs to match the one from the {@link #PREFIX} code.
|
||||
* The method is getting called from the Lua scripting engine.
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public Object redisCall(final List<Object> args) {
|
||||
assertFalse(args.isEmpty(), "`redis.call()` in Lua script invoked without arguments");
|
||||
assertTrue(args.get(0) instanceof String, "first argument to `redis.call()` must be of type `String`");
|
||||
return handler.redisCommand((String) args.get(0), tail(args, 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.util.redis;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
public class SimpleCacheCommandsHandler extends BaseRedisCommandsHandler {
|
||||
|
||||
public record Entry(Object value, long expirationEpochMillis) {
|
||||
}
|
||||
|
||||
private final Map<String, Entry> cache = new ConcurrentHashMap<>();
|
||||
|
||||
private final Clock clock;
|
||||
|
||||
|
||||
public SimpleCacheCommandsHandler(final Clock clock) {
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object set(final String key, final String value, final List<Object> tail) {
|
||||
cache.put(key, new Entry(value, resolveExpirationEpochMillis(tail)));
|
||||
return "OK";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String get(final String key) {
|
||||
return getIfNotExpired(key, String.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int del(final List<String> key) {
|
||||
return key.stream()
|
||||
.mapToInt(k -> cache.remove(k) != null ? 1 : 0)
|
||||
.sum();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public Object hset(final String key, final List<Object> fieldsAndValues) {
|
||||
Map<Object, Object> map = getIfNotExpired(key, Map.class);
|
||||
if (map == null) {
|
||||
map = new ConcurrentHashMap<>();
|
||||
cache.put(key, new Entry(map, Long.MAX_VALUE));
|
||||
}
|
||||
final Iterator<Object> iter = fieldsAndValues.iterator();
|
||||
while (iter.hasNext()) {
|
||||
final Object k = iter.next();
|
||||
final Object v = iter.next();
|
||||
map.put(k, v);
|
||||
}
|
||||
return "OK";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object hget(final String key, final String field) {
|
||||
final Map<?, ?> map = getIfNotExpired(key, Map.class);
|
||||
return map == null ? null : map.get(field);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object[] hmget(final String key, final List<Object> fields) {
|
||||
final Object[] res = new Object[fields.size()];
|
||||
for (int i = 0; i < fields.size(); i++) {
|
||||
res[i] = hget(key, fields.get(i).toString());
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public Object push(final boolean left, final String key, final List<Object> values) {
|
||||
LinkedList<Object> list = getIfNotExpired(key, LinkedList.class);
|
||||
if (list == null) {
|
||||
list = new LinkedList<>();
|
||||
cache.put(key, new Entry(list, Long.MAX_VALUE));
|
||||
}
|
||||
for (Object v: values) {
|
||||
if (left) {
|
||||
list.addFirst(v.toString());
|
||||
} else {
|
||||
list.addLast(v.toString());
|
||||
}
|
||||
}
|
||||
return list.size();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public Object[] pop(final boolean left, final String key, final int count) {
|
||||
final Object[] result = new String[count];
|
||||
final LinkedList<Object> list = getIfNotExpired(key, LinkedList.class);
|
||||
if (list == null) {
|
||||
return result;
|
||||
}
|
||||
for (int i = 0; i < Math.min(count, list.size()); i++) {
|
||||
result[i] = left ? list.removeFirst() : list.removeLast();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object pexpire(final String key, final long ttlMillis, final List<Object> args) {
|
||||
final Entry e = cache.get(key);
|
||||
if (e == null) {
|
||||
return 0;
|
||||
}
|
||||
final Entry updated = new Entry(e.value(), clock.millis() + ttlMillis);
|
||||
cache.put(key, updated);
|
||||
return 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object type(final String key) {
|
||||
final Object o = getIfNotExpired(key, Object.class);
|
||||
final String type;
|
||||
if (o == null) {
|
||||
type = "none";
|
||||
} else if (o.getClass() == String.class) {
|
||||
type = "string";
|
||||
} else if (Map.class.isAssignableFrom(o.getClass())) {
|
||||
type = "hash";
|
||||
} else if (List.class.isAssignableFrom(o.getClass())) {
|
||||
type = "list";
|
||||
} else {
|
||||
throw new IllegalArgumentException("Unsupported value type: " + o.getClass());
|
||||
}
|
||||
return Map.of("ok", type);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
protected <T> T getIfNotExpired(final String key, final Class<T> expectedType) {
|
||||
final Entry entry = cache.get(key);
|
||||
if (entry == null) {
|
||||
return null;
|
||||
}
|
||||
if (entry.expirationEpochMillis() < clock.millis()) {
|
||||
del(List.of(key));
|
||||
return null;
|
||||
}
|
||||
return expectedType.cast(entry.value());
|
||||
}
|
||||
|
||||
protected long resolveExpirationEpochMillis(final List<Object> args) {
|
||||
for (int i = 0; i < args.size() - 1; i++) {
|
||||
final long currentTimeMillis = clock.millis();
|
||||
final String param = args.get(i).toString();
|
||||
final String value = args.get(i + 1).toString();
|
||||
switch (param) {
|
||||
case "EX" -> {
|
||||
return currentTimeMillis + Double.valueOf(value).longValue() * 1000;
|
||||
}
|
||||
case "PX" -> {
|
||||
return currentTimeMillis + Double.valueOf(value).longValue();
|
||||
}
|
||||
case "EXAT" -> {
|
||||
return Double.valueOf(value).longValue() * 1000;
|
||||
}
|
||||
case "PXAT" -> {
|
||||
return Double.valueOf(value).longValue();
|
||||
}
|
||||
}
|
||||
}
|
||||
return Long.MAX_VALUE;
|
||||
}
|
||||
}
|
||||
@@ -16,23 +16,6 @@ import org.junit.jupiter.params.provider.MethodSource;
|
||||
|
||||
class UserAgentUtilTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void testParseUserAgentString(final String userAgentString, final UserAgent expectedUserAgent)
|
||||
throws UnrecognizedUserAgentException {
|
||||
assertEquals(expectedUserAgent, UserAgentUtil.parseUserAgentString(userAgentString));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private static Stream<Arguments> testParseUserAgentString() {
|
||||
return Stream.of(
|
||||
Arguments.of("Signal-Android/4.68.3 Android/25",
|
||||
new UserAgent(ClientPlatform.ANDROID, new Semver("4.68.3"), "Android/25")),
|
||||
Arguments.of("Signal-Android 4.53.7 (Android 8.1)",
|
||||
new UserAgent(ClientPlatform.ANDROID, new Semver("4.53.7"), "(Android 8.1)"))
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void testParseBogusUserAgentString(final String userAgentString) {
|
||||
@@ -73,24 +56,4 @@ class UserAgentUtilTest {
|
||||
Arguments.of("Signal-iOS/3.9.0", new UserAgent(ClientPlatform.IOS, new Semver("3.9.0")))
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void testParseLegacyUserAgentString(final String userAgentString, final UserAgent expectedUserAgent) {
|
||||
assertEquals(expectedUserAgent, UserAgentUtil.parseLegacyUserAgentString(userAgentString));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private static Stream<Arguments> testParseLegacyUserAgentString() {
|
||||
return Stream.of(
|
||||
Arguments.of("This is obviously not a reasonable User-Agent string.", null),
|
||||
Arguments.of("Signal-Android 4.53.7 (Android 8.1)",
|
||||
new UserAgent(ClientPlatform.ANDROID, new Semver("4.53.7"), "(Android 8.1)")),
|
||||
Arguments.of("Signal Desktop 1.2.3", new UserAgent(ClientPlatform.DESKTOP, new Semver("1.2.3"))),
|
||||
Arguments.of("Signal Desktop 1.32.0-beta.3",
|
||||
new UserAgent(ClientPlatform.DESKTOP, new Semver("1.32.0-beta.3"))),
|
||||
Arguments.of("Signal/3.9.0 (iPhone; iOS 12.2; Scale/3.00)",
|
||||
new UserAgent(ClientPlatform.IOS, new Semver("3.9.0"), "(iPhone; iOS 12.2; Scale/3.00)"))
|
||||
);
|
||||
}
|
||||
}
|
||||
+14
-9
@@ -59,6 +59,7 @@ import org.whispersystems.textsecuregcm.tests.util.MessagesDynamoDbExtension;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.websocket.WebSocketClient;
|
||||
import org.whispersystems.websocket.messages.WebSocketResponseMessage;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
|
||||
class WebSocketConnectionIntegrationTest {
|
||||
@@ -70,13 +71,14 @@ class WebSocketConnectionIntegrationTest {
|
||||
static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
|
||||
|
||||
private ExecutorService sharedExecutorService;
|
||||
private ScheduledExecutorService scheduledExecutorService;
|
||||
private MessagesDynamoDb messagesDynamoDb;
|
||||
private MessagesCache messagesCache;
|
||||
private ReportMessageManager reportMessageManager;
|
||||
private Account account;
|
||||
private Device device;
|
||||
private WebSocketClient webSocketClient;
|
||||
private ScheduledExecutorService retrySchedulingExecutor;
|
||||
private Scheduler messageDeliveryScheduler;
|
||||
|
||||
private long serialTimestamp = System.currentTimeMillis();
|
||||
|
||||
@@ -84,8 +86,10 @@ class WebSocketConnectionIntegrationTest {
|
||||
void setUp() throws Exception {
|
||||
|
||||
sharedExecutorService = Executors.newSingleThreadExecutor();
|
||||
scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
|
||||
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
|
||||
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster(), Clock.systemUTC(), sharedExecutorService, sharedExecutorService);
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster(), sharedExecutorService, messageDeliveryScheduler, sharedExecutorService, Clock.systemUTC());
|
||||
messagesDynamoDb = new MessagesDynamoDb(dynamoDbExtension.getDynamoDbClient(),
|
||||
dynamoDbExtension.getDynamoDbAsyncClient(), MessagesDynamoDbExtension.TABLE_NAME, Duration.ofDays(7),
|
||||
sharedExecutorService);
|
||||
@@ -93,7 +97,6 @@ class WebSocketConnectionIntegrationTest {
|
||||
account = mock(Account.class);
|
||||
device = mock(Device.class);
|
||||
webSocketClient = mock(WebSocketClient.class);
|
||||
retrySchedulingExecutor = Executors.newSingleThreadScheduledExecutor();
|
||||
|
||||
when(account.getNumber()).thenReturn("+18005551234");
|
||||
when(account.getUuid()).thenReturn(UUID.randomUUID());
|
||||
@@ -105,8 +108,8 @@ class WebSocketConnectionIntegrationTest {
|
||||
sharedExecutorService.shutdown();
|
||||
sharedExecutorService.awaitTermination(2, TimeUnit.SECONDS);
|
||||
|
||||
retrySchedulingExecutor.shutdown();
|
||||
retrySchedulingExecutor.awaitTermination(2, TimeUnit.SECONDS);
|
||||
scheduledExecutorService.shutdown();
|
||||
scheduledExecutorService.awaitTermination(2, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -122,7 +125,8 @@ class WebSocketConnectionIntegrationTest {
|
||||
new AuthenticatedAccount(() -> new Pair<>(account, device)),
|
||||
device,
|
||||
webSocketClient,
|
||||
retrySchedulingExecutor);
|
||||
scheduledExecutorService,
|
||||
messageDeliveryScheduler);
|
||||
|
||||
final List<MessageProtos.Envelope> expectedMessages = new ArrayList<>(persistedMessageCount + cachedMessageCount);
|
||||
|
||||
@@ -205,7 +209,8 @@ class WebSocketConnectionIntegrationTest {
|
||||
new AuthenticatedAccount(() -> new Pair<>(account, device)),
|
||||
device,
|
||||
webSocketClient,
|
||||
retrySchedulingExecutor);
|
||||
scheduledExecutorService,
|
||||
messageDeliveryScheduler);
|
||||
|
||||
final int persistedMessageCount = 207;
|
||||
final int cachedMessageCount = 173;
|
||||
@@ -270,8 +275,8 @@ class WebSocketConnectionIntegrationTest {
|
||||
device,
|
||||
webSocketClient,
|
||||
100, // use a very short timeout, so that this test completes quickly
|
||||
retrySchedulingExecutor,
|
||||
Schedulers.boundedElastic());
|
||||
scheduledExecutorService,
|
||||
messageDeliveryScheduler);
|
||||
|
||||
final int persistedMessageCount = 207;
|
||||
final int cachedMessageCount = 173;
|
||||
|
||||
+31
-39
@@ -68,6 +68,7 @@ import org.whispersystems.websocket.messages.WebSocketResponseMessage;
|
||||
import org.whispersystems.websocket.session.WebSocketSessionContext;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.FluxSink;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
import reactor.test.StepVerifier;
|
||||
|
||||
@@ -87,8 +88,10 @@ class WebSocketConnectionTest {
|
||||
private Device device;
|
||||
private AuthenticatedAccount auth;
|
||||
private UpgradeRequest upgradeRequest;
|
||||
private MessagesManager messagesManager;
|
||||
private ReceiptSender receiptSender;
|
||||
private ScheduledExecutorService retrySchedulingExecutor;
|
||||
private Scheduler messageDeliveryScheduler;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
@@ -98,22 +101,24 @@ class WebSocketConnectionTest {
|
||||
device = mock(Device.class);
|
||||
auth = new AuthenticatedAccount(() -> new Pair<>(account, device));
|
||||
upgradeRequest = mock(UpgradeRequest.class);
|
||||
messagesManager = mock(MessagesManager.class);
|
||||
receiptSender = mock(ReceiptSender.class);
|
||||
retrySchedulingExecutor = mock(ScheduledExecutorService.class);
|
||||
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void teardown() {
|
||||
StepVerifier.resetDefaultTimeout();
|
||||
messageDeliveryScheduler.dispose();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCredentials() {
|
||||
MessagesManager storedMessages = mock(MessagesManager.class);
|
||||
void testCredentials() throws Exception {
|
||||
WebSocketAccountAuthenticator webSocketAuthenticator = new WebSocketAccountAuthenticator(accountAuthenticator);
|
||||
AuthenticatedConnectListener connectListener = new AuthenticatedConnectListener(receiptSender, storedMessages,
|
||||
AuthenticatedConnectListener connectListener = new AuthenticatedConnectListener(receiptSender, messagesManager,
|
||||
mock(PushNotificationManager.class), mock(ClientPresenceManager.class),
|
||||
retrySchedulingExecutor);
|
||||
retrySchedulingExecutor, messageDeliveryScheduler);
|
||||
WebSocketSessionContext sessionContext = mock(WebSocketSessionContext.class);
|
||||
|
||||
when(accountAuthenticator.authenticate(eq(new BasicCredentials(VALID_USER, VALID_PASSWORD))))
|
||||
@@ -145,7 +150,6 @@ class WebSocketConnectionTest {
|
||||
|
||||
@Test
|
||||
void testOpen() {
|
||||
MessagesManager storedMessages = mock(MessagesManager.class);
|
||||
|
||||
UUID accountUuid = UUID.randomUUID();
|
||||
UUID senderOneUuid = UUID.randomUUID();
|
||||
@@ -171,9 +175,12 @@ class WebSocketConnectionTest {
|
||||
when(accountsManager.getByE164("sender1")).thenReturn(Optional.of(sender1));
|
||||
when(accountsManager.getByE164("sender2")).thenReturn(Optional.empty());
|
||||
|
||||
when(messagesManager.delete(any(), anyLong(), any(), any())).thenReturn(
|
||||
CompletableFuture.completedFuture(Optional.empty()));
|
||||
|
||||
String userAgent = HttpHeaders.USER_AGENT;
|
||||
|
||||
when(storedMessages.getMessagesForDeviceReactive(account.getUuid(), device.getId(), false))
|
||||
when(messagesManager.getMessagesForDeviceReactive(account.getUuid(), device.getId(), false))
|
||||
.thenReturn(Flux.fromIterable(outgoingMessages));
|
||||
|
||||
final List<CompletableFuture<WebSocketResponseMessage>> futures = new LinkedList<>();
|
||||
@@ -187,7 +194,7 @@ class WebSocketConnectionTest {
|
||||
return future;
|
||||
});
|
||||
|
||||
WebSocketConnection connection = new WebSocketConnection(receiptSender, storedMessages,
|
||||
WebSocketConnection connection = new WebSocketConnection(receiptSender, messagesManager,
|
||||
auth, device, client, retrySchedulingExecutor, Schedulers.immediate());
|
||||
|
||||
connection.start();
|
||||
@@ -203,7 +210,7 @@ class WebSocketConnectionTest {
|
||||
futures.get(0).completeExceptionally(new IOException());
|
||||
futures.get(2).completeExceptionally(new IOException());
|
||||
|
||||
verify(storedMessages, times(1)).delete(eq(accountUuid), eq(deviceId),
|
||||
verify(messagesManager, times(1)).delete(eq(accountUuid), eq(deviceId),
|
||||
eq(UUID.fromString(outgoingMessages.get(1).getServerGuid())), eq(outgoingMessages.get(1).getServerTimestamp()));
|
||||
verify(receiptSender, times(1)).sendReceipt(eq(accountUuid), eq(deviceId), eq(senderOneUuid),
|
||||
eq(2222L));
|
||||
@@ -214,7 +221,6 @@ class WebSocketConnectionTest {
|
||||
|
||||
@Test
|
||||
public void testOnlineSend() {
|
||||
final MessagesManager messagesManager = mock(MessagesManager.class);
|
||||
final WebSocketClient client = mock(WebSocketClient.class);
|
||||
final WebSocketConnection connection = new WebSocketConnection(receiptSender, messagesManager, auth, device, client,
|
||||
retrySchedulingExecutor, Schedulers.immediate());
|
||||
@@ -277,8 +283,6 @@ class WebSocketConnectionTest {
|
||||
|
||||
@Test
|
||||
void testPendingSend() {
|
||||
MessagesManager storedMessages = mock(MessagesManager.class);
|
||||
|
||||
final UUID accountUuid = UUID.randomUUID();
|
||||
final UUID senderTwoUuid = UUID.randomUUID();
|
||||
|
||||
@@ -319,9 +323,12 @@ class WebSocketConnectionTest {
|
||||
when(accountsManager.getByE164("sender1")).thenReturn(Optional.of(sender1));
|
||||
when(accountsManager.getByE164("sender2")).thenReturn(Optional.empty());
|
||||
|
||||
when(messagesManager.delete(any(), anyLong(), any(), any())).thenReturn(
|
||||
CompletableFuture.completedFuture(Optional.empty()));
|
||||
|
||||
String userAgent = HttpHeaders.USER_AGENT;
|
||||
|
||||
when(storedMessages.getMessagesForDeviceReactive(account.getUuid(), device.getId(), false))
|
||||
when(messagesManager.getMessagesForDeviceReactive(account.getUuid(), device.getId(), false))
|
||||
.thenReturn(Flux.fromIterable(pendingMessages));
|
||||
|
||||
final List<CompletableFuture<WebSocketResponseMessage>> futures = new LinkedList<>();
|
||||
@@ -335,7 +342,7 @@ class WebSocketConnectionTest {
|
||||
return future;
|
||||
});
|
||||
|
||||
WebSocketConnection connection = new WebSocketConnection(receiptSender, storedMessages,
|
||||
WebSocketConnection connection = new WebSocketConnection(receiptSender, messagesManager,
|
||||
auth, device, client, retrySchedulingExecutor, Schedulers.immediate());
|
||||
|
||||
connection.start();
|
||||
@@ -358,7 +365,6 @@ class WebSocketConnectionTest {
|
||||
|
||||
@Test
|
||||
void testProcessStoredMessageConcurrency() {
|
||||
final MessagesManager messagesManager = mock(MessagesManager.class);
|
||||
final WebSocketClient client = mock(WebSocketClient.class);
|
||||
final WebSocketConnection connection = new WebSocketConnection(receiptSender, messagesManager, auth, device, client,
|
||||
retrySchedulingExecutor, Schedulers.immediate());
|
||||
@@ -424,7 +430,6 @@ class WebSocketConnectionTest {
|
||||
|
||||
@Test
|
||||
void testProcessStoredMessagesMultiplePages() {
|
||||
final MessagesManager messagesManager = mock(MessagesManager.class);
|
||||
final WebSocketClient client = mock(WebSocketClient.class);
|
||||
final WebSocketConnection connection = new WebSocketConnection(receiptSender, messagesManager, auth, device, client,
|
||||
retrySchedulingExecutor, Schedulers.immediate());
|
||||
@@ -477,7 +482,6 @@ class WebSocketConnectionTest {
|
||||
|
||||
@Test
|
||||
void testProcessStoredMessagesContainsSenderUuid() {
|
||||
final MessagesManager messagesManager = mock(MessagesManager.class);
|
||||
final WebSocketClient client = mock(WebSocketClient.class);
|
||||
final WebSocketConnection connection = new WebSocketConnection(receiptSender, messagesManager, auth, device, client,
|
||||
retrySchedulingExecutor, Schedulers.immediate());
|
||||
@@ -540,7 +544,6 @@ class WebSocketConnectionTest {
|
||||
|
||||
@Test
|
||||
void testProcessStoredMessagesSingleEmptyCall() {
|
||||
final MessagesManager messagesManager = mock(MessagesManager.class);
|
||||
final WebSocketClient client = mock(WebSocketClient.class);
|
||||
final WebSocketConnection connection = new WebSocketConnection(receiptSender, messagesManager, auth, device, client,
|
||||
retrySchedulingExecutor, Schedulers.immediate());
|
||||
@@ -570,7 +573,6 @@ class WebSocketConnectionTest {
|
||||
|
||||
@Test
|
||||
public void testRequeryOnStateMismatch() {
|
||||
final MessagesManager messagesManager = mock(MessagesManager.class);
|
||||
final WebSocketClient client = mock(WebSocketClient.class);
|
||||
final WebSocketConnection connection = new WebSocketConnection(receiptSender, messagesManager, auth, device, client,
|
||||
retrySchedulingExecutor, Schedulers.immediate());
|
||||
@@ -627,7 +629,6 @@ class WebSocketConnectionTest {
|
||||
|
||||
@Test
|
||||
void testProcessCachedMessagesOnly() {
|
||||
final MessagesManager messagesManager = mock(MessagesManager.class);
|
||||
final WebSocketClient client = mock(WebSocketClient.class);
|
||||
final WebSocketConnection connection = new WebSocketConnection(receiptSender, messagesManager, auth, device, client,
|
||||
retrySchedulingExecutor, Schedulers.immediate());
|
||||
@@ -660,7 +661,6 @@ class WebSocketConnectionTest {
|
||||
|
||||
@Test
|
||||
void testProcessDatabaseMessagesAfterPersist() {
|
||||
final MessagesManager messagesManager = mock(MessagesManager.class);
|
||||
final WebSocketClient client = mock(WebSocketClient.class);
|
||||
final WebSocketConnection connection = new WebSocketConnection(receiptSender, messagesManager, auth, device, client,
|
||||
retrySchedulingExecutor, Schedulers.immediate());
|
||||
@@ -690,8 +690,6 @@ class WebSocketConnectionTest {
|
||||
|
||||
@Test
|
||||
void testRetrieveMessageException() {
|
||||
MessagesManager storedMessages = mock(MessagesManager.class);
|
||||
|
||||
UUID accountUuid = UUID.randomUUID();
|
||||
|
||||
when(device.getId()).thenReturn(2L);
|
||||
@@ -699,7 +697,7 @@ class WebSocketConnectionTest {
|
||||
when(account.getNumber()).thenReturn("+14152222222");
|
||||
when(account.getUuid()).thenReturn(accountUuid);
|
||||
|
||||
when(storedMessages.getMessagesForDeviceReactive(account.getUuid(), device.getId(), false))
|
||||
when(messagesManager.getMessagesForDeviceReactive(account.getUuid(), device.getId(), false))
|
||||
.thenReturn(Flux.error(new RedisException("OH NO")));
|
||||
|
||||
when(retrySchedulingExecutor.schedule(any(Runnable.class), anyLong(), any())).thenAnswer(
|
||||
@@ -711,7 +709,7 @@ class WebSocketConnectionTest {
|
||||
final WebSocketClient client = mock(WebSocketClient.class);
|
||||
when(client.isOpen()).thenReturn(true);
|
||||
|
||||
WebSocketConnection connection = new WebSocketConnection(receiptSender, storedMessages, auth, device, client,
|
||||
WebSocketConnection connection = new WebSocketConnection(receiptSender, messagesManager, auth, device, client,
|
||||
retrySchedulingExecutor, Schedulers.immediate());
|
||||
connection.start();
|
||||
|
||||
@@ -722,8 +720,6 @@ class WebSocketConnectionTest {
|
||||
|
||||
@Test
|
||||
void testRetrieveMessageExceptionClientDisconnected() {
|
||||
MessagesManager storedMessages = mock(MessagesManager.class);
|
||||
|
||||
UUID accountUuid = UUID.randomUUID();
|
||||
|
||||
when(device.getId()).thenReturn(2L);
|
||||
@@ -731,13 +727,13 @@ class WebSocketConnectionTest {
|
||||
when(account.getNumber()).thenReturn("+14152222222");
|
||||
when(account.getUuid()).thenReturn(accountUuid);
|
||||
|
||||
when(storedMessages.getMessagesForDeviceReactive(account.getUuid(), device.getId(), false))
|
||||
when(messagesManager.getMessagesForDeviceReactive(account.getUuid(), device.getId(), false))
|
||||
.thenReturn(Flux.error(new RedisException("OH NO")));
|
||||
|
||||
final WebSocketClient client = mock(WebSocketClient.class);
|
||||
when(client.isOpen()).thenReturn(false);
|
||||
|
||||
WebSocketConnection connection = new WebSocketConnection(receiptSender, storedMessages, auth, device, client,
|
||||
WebSocketConnection connection = new WebSocketConnection(receiptSender, messagesManager, auth, device, client,
|
||||
retrySchedulingExecutor, Schedulers.immediate());
|
||||
connection.start();
|
||||
|
||||
@@ -748,8 +744,6 @@ class WebSocketConnectionTest {
|
||||
@Test
|
||||
@Disabled("This test is flaky")
|
||||
void testReactivePublisherLimitRate() {
|
||||
MessagesManager storedMessages = mock(MessagesManager.class);
|
||||
|
||||
final UUID accountUuid = UUID.randomUUID();
|
||||
|
||||
final long deviceId = 2L;
|
||||
@@ -771,7 +765,7 @@ class WebSocketConnectionTest {
|
||||
});
|
||||
});
|
||||
|
||||
when(storedMessages.getMessagesForDeviceReactive(eq(accountUuid), eq(deviceId), anyBoolean()))
|
||||
when(messagesManager.getMessagesForDeviceReactive(eq(accountUuid), eq(deviceId), anyBoolean()))
|
||||
.thenReturn(flux);
|
||||
|
||||
final WebSocketClient client = mock(WebSocketClient.class);
|
||||
@@ -779,11 +773,11 @@ class WebSocketConnectionTest {
|
||||
final WebSocketResponseMessage successResponse = mock(WebSocketResponseMessage.class);
|
||||
when(successResponse.getStatus()).thenReturn(200);
|
||||
when(client.sendRequest(any(), any(), any(), any())).thenReturn(CompletableFuture.completedFuture(successResponse));
|
||||
when(storedMessages.delete(any(), anyLong(), any(), any())).thenReturn(
|
||||
when(messagesManager.delete(any(), anyLong(), any(), any())).thenReturn(
|
||||
CompletableFuture.completedFuture(Optional.empty()));
|
||||
|
||||
WebSocketConnection connection = new WebSocketConnection(receiptSender, storedMessages, auth, device, client,
|
||||
retrySchedulingExecutor);
|
||||
WebSocketConnection connection = new WebSocketConnection(receiptSender, messagesManager, auth, device, client,
|
||||
retrySchedulingExecutor, messageDeliveryScheduler);
|
||||
|
||||
connection.start();
|
||||
|
||||
@@ -808,8 +802,6 @@ class WebSocketConnectionTest {
|
||||
|
||||
@Test
|
||||
void testReactivePublisherDisposedWhenConnectionStopped() {
|
||||
MessagesManager storedMessages = mock(MessagesManager.class);
|
||||
|
||||
final UUID accountUuid = UUID.randomUUID();
|
||||
|
||||
final long deviceId = 2L;
|
||||
@@ -830,7 +822,7 @@ class WebSocketConnectionTest {
|
||||
|
||||
s.onCancel(() -> canceled.set(true));
|
||||
});
|
||||
when(storedMessages.getMessagesForDeviceReactive(eq(accountUuid), eq(deviceId), anyBoolean()))
|
||||
when(messagesManager.getMessagesForDeviceReactive(eq(accountUuid), eq(deviceId), anyBoolean()))
|
||||
.thenReturn(flux);
|
||||
|
||||
final WebSocketClient client = mock(WebSocketClient.class);
|
||||
@@ -838,10 +830,10 @@ class WebSocketConnectionTest {
|
||||
final WebSocketResponseMessage successResponse = mock(WebSocketResponseMessage.class);
|
||||
when(successResponse.getStatus()).thenReturn(200);
|
||||
when(client.sendRequest(any(), any(), any(), any())).thenReturn(CompletableFuture.completedFuture(successResponse));
|
||||
when(storedMessages.delete(any(), anyLong(), any(), any())).thenReturn(
|
||||
when(messagesManager.delete(any(), anyLong(), any(), any())).thenReturn(
|
||||
CompletableFuture.completedFuture(Optional.empty()));
|
||||
|
||||
WebSocketConnection connection = new WebSocketConnection(receiptSender, storedMessages, auth, device, client,
|
||||
WebSocketConnection connection = new WebSocketConnection(receiptSender, messagesManager, auth, device, client,
|
||||
retrySchedulingExecutor, Schedulers.immediate());
|
||||
|
||||
connection.start();
|
||||
|
||||
+1
-1
Submodule spam-filter updated: f1436a4cc9...9a525f0708.
Reference in new issue
Block a user