mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 00:36:47 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fedeef4da5 | ||
|
|
b593d49399 | ||
|
|
4a91fc3c3d | ||
|
|
bb9605d7c3 | ||
|
|
1049326a70 | ||
|
|
457ecf145f | ||
|
|
463dd9d7d8 | ||
|
|
bdcd055aaf | ||
|
|
30ae2037e8 | ||
|
|
ce4fdbfb3c | ||
|
|
2d154eb0cf | ||
|
|
a3e82dfae8 | ||
|
|
97a7469432 | ||
|
|
1a1defb055 | ||
|
|
93c78b6e40 | ||
|
|
b852d6681d | ||
|
|
8e48ac4ede | ||
|
|
859f646c55 | ||
|
|
fb39b2edaf | ||
|
|
d7bf815bd5 | ||
|
|
c93af9e31e | ||
|
|
b81a0e99d4 | ||
|
|
f8fefe2e5e | ||
|
|
f26bc70b59 | ||
|
|
b5fd131aba | ||
|
|
06997e19e0 | ||
|
|
97710540c0 | ||
|
|
c78c109577 | ||
|
|
8d995e456e | ||
|
|
cc3cab9c88 | ||
|
|
0122b410be | ||
|
|
2ddd2b9476 | ||
|
|
a768498250 | ||
|
|
a45aadae16 | ||
|
|
25802432c2 | ||
|
|
98578b18aa | ||
|
|
6d81f69785 | ||
|
|
7dce183170 | ||
|
|
f1962a03ef | ||
|
|
cb26bfd807 | ||
|
|
befd336372 | ||
|
|
8501e61eb1 | ||
|
|
ae489e5a52 | ||
|
|
13afdbda97 |
No files matched your search
@@ -77,7 +77,7 @@ public final class Operations {
|
||||
|
||||
// register account
|
||||
final RegistrationRequest registrationRequest = new RegistrationRequest(
|
||||
null, registrationPassword, accountAttributes, true,
|
||||
null, registrationPassword, accountAttributes, true, false,
|
||||
Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty());
|
||||
|
||||
final AccountIdentityResponse registrationResponse = apiPost("/v1/registration", registrationRequest)
|
||||
@@ -113,6 +113,7 @@ public final class Operations {
|
||||
registrationPassword,
|
||||
accountAttributes,
|
||||
true,
|
||||
true,
|
||||
Optional.of(new IdentityKey(aciIdentityKeyPair.getPublicKey())),
|
||||
Optional.of(new IdentityKey(pniIdentityKeyPair.getPublicKey())),
|
||||
Optional.of(generateSignedECPreKey(1, aciIdentityKeyPair)),
|
||||
@@ -311,6 +312,7 @@ public final class Operations {
|
||||
return FaultTolerantHttpClient.newBuilder()
|
||||
.withName("integration-test")
|
||||
.withExecutor(Executors.newFixedThreadPool(16))
|
||||
.withRetryExecutor(Executors.newSingleThreadScheduledExecutor())
|
||||
.withCircuitBreaker(new CircuitBreakerConfiguration())
|
||||
.withTrustedServerCertificates(CONFIG.rootCert())
|
||||
.build();
|
||||
|
||||
@@ -38,7 +38,6 @@
|
||||
</modules>
|
||||
|
||||
<properties>
|
||||
<aws.sdk.version>1.12.376</aws.sdk.version>
|
||||
<aws.sdk2.version>2.19.8</aws.sdk2.version>
|
||||
<braintree.version>3.19.0</braintree.version>
|
||||
<commons-csv.version>1.9.0</commons-csv.version>
|
||||
@@ -53,7 +52,7 @@
|
||||
<jedis.version>2.9.0</jedis.version>
|
||||
<kotlin.version>1.8.0</kotlin.version>
|
||||
<kotlinx-serialization.version>1.4.1</kotlinx-serialization.version>
|
||||
<lettuce.version>6.2.1.RELEASE</lettuce.version>
|
||||
<lettuce.version>6.2.4.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>
|
||||
@@ -73,6 +72,8 @@
|
||||
<docker.image.sha256>ddf36656dc8920621fddf4928bdcb4b98c0d0e7bc9672f0cea8115c10ad5cbc6</docker.image.sha256>
|
||||
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
|
||||
<deploy.skip.s3.upload>false</deploy.skip.s3.upload>
|
||||
</properties>
|
||||
|
||||
<groupId>org.whispersystems.textsecure</groupId>
|
||||
@@ -109,13 +110,6 @@
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-java-sdk-bom</artifactId>
|
||||
<version>${aws.sdk.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>bom</artifactId>
|
||||
@@ -411,6 +405,7 @@
|
||||
<goal>compile</goal>
|
||||
<goal>compile-custom</goal>
|
||||
<goal>test-compile</goal>
|
||||
<goal>test-compile-custom</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
|
||||
@@ -71,10 +71,6 @@ zkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrs
|
||||
|
||||
genericZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
|
||||
|
||||
remoteConfig.authorizedTokens:
|
||||
- token1 # 1st authorized token
|
||||
- token2 # 2nd authorized token
|
||||
|
||||
paymentsService.userAuthenticationTokenSharedSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= # base64-encoded 32-byte secret shared with MobileCoin services used to generate auth tokens for Signal users
|
||||
paymentsService.fixerApiKey: unset
|
||||
paymentsService.coinMarketCapApiKey: unset
|
||||
|
||||
@@ -51,6 +51,8 @@ adminEventLoggingConfiguration:
|
||||
projectId: some-project-id
|
||||
logName: some-log-name
|
||||
|
||||
grpcPort: 8080
|
||||
|
||||
stripe:
|
||||
apiKey: secret://stripe.apiKey
|
||||
idempotencyKeyGenerator: secret://stripe.idempotencyKeyGenerator
|
||||
@@ -96,6 +98,8 @@ dynamoDbTables:
|
||||
generator: abcdefg12345678= # random base64-encoded binary sequence
|
||||
ecKeys:
|
||||
tableName: Example_Keys
|
||||
ecSignedPreKeys:
|
||||
tableName: Example_EC_Signed_Pre_Keys
|
||||
pqKeys:
|
||||
tableName: Example_PQ_Keys
|
||||
pqLastResortKeys:
|
||||
@@ -301,7 +305,6 @@ appConfig:
|
||||
configuration: example
|
||||
|
||||
remoteConfig:
|
||||
authorizedTokens: secret://remoteConfig.authorizedTokens
|
||||
authorizedUsers:
|
||||
- # 1st authorized user
|
||||
- # 2nd authorized user
|
||||
|
||||
+2
-9
@@ -306,18 +306,10 @@
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>appconfigdata</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-java-sdk-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-java-sdk-sts</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>dynamodb-lock-client</artifactId>
|
||||
<version>1.1.0</version>
|
||||
<version>1.2.0</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>commons-logging</groupId>
|
||||
@@ -570,6 +562,7 @@
|
||||
<bucketName>${deploy.bucketName}</bucketName>
|
||||
<region>${deploy.bucketRegion}</region>
|
||||
<destination>${project.build.finalName}-bin.tar.gz</destination>
|
||||
<doNotUpload>${deploy.skip.s3.upload}</doNotUpload>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
|
||||
+10
@@ -270,6 +270,11 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private TurnSecretConfiguration turn;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private int grpcPort;
|
||||
|
||||
public AdminEventLoggingConfiguration getAdminEventLoggingConfiguration() {
|
||||
return adminEventLoggingConfiguration;
|
||||
}
|
||||
@@ -448,4 +453,9 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
public TurnSecretConfiguration getTurnSecretConfiguration() {
|
||||
return turn;
|
||||
}
|
||||
|
||||
public int getGrpcPort() {
|
||||
return grpcPort;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -7,10 +7,6 @@ package org.whispersystems.textsecuregcm;
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
import static java.util.Objects.requireNonNull;
|
||||
|
||||
import com.amazonaws.ClientConfiguration;
|
||||
import com.amazonaws.auth.AWSCredentialsProviderChain;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
|
||||
import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
|
||||
import com.google.api.client.http.apache.v2.ApacheHttpTransport;
|
||||
import com.google.api.client.json.gson.GsonFactory;
|
||||
@@ -27,8 +23,13 @@ import io.dropwizard.auth.basic.BasicCredentialAuthFilter;
|
||||
import io.dropwizard.auth.basic.BasicCredentials;
|
||||
import io.dropwizard.setup.Bootstrap;
|
||||
import io.dropwizard.setup.Environment;
|
||||
import io.grpc.Server;
|
||||
import io.grpc.ServerBuilder;
|
||||
import io.lettuce.core.metrics.MicrometerCommandLatencyRecorder;
|
||||
import io.lettuce.core.metrics.MicrometerOptions;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.binder.grpc.MetricCollectingServerInterceptor;
|
||||
import io.micrometer.core.instrument.binder.jvm.ExecutorServiceMetrics;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.net.http.HttpClient;
|
||||
@@ -46,7 +47,6 @@ import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import javax.servlet.DispatcherType;
|
||||
import javax.servlet.FilterRegistration;
|
||||
import javax.servlet.ServletRegistration;
|
||||
@@ -110,6 +110,8 @@ import org.whispersystems.textsecuregcm.controllers.VerificationController;
|
||||
import org.whispersystems.textsecuregcm.currency.CoinMarketCapClient;
|
||||
import org.whispersystems.textsecuregcm.currency.CurrencyConversionManager;
|
||||
import org.whispersystems.textsecuregcm.currency.FixerClient;
|
||||
import org.whispersystems.textsecuregcm.grpc.GrpcServerManagedWrapper;
|
||||
import org.whispersystems.textsecuregcm.grpc.UserAgentInterceptor;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteDeprecationFilter;
|
||||
import org.whispersystems.textsecuregcm.filters.RequestStatisticsFilter;
|
||||
@@ -127,18 +129,8 @@ import org.whispersystems.textsecuregcm.mappers.NonNormalizedPhoneNumberExceptio
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.ServerRejectedExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.metrics.ApplicationShutdownMonitor;
|
||||
import org.whispersystems.textsecuregcm.metrics.BufferPoolGauges;
|
||||
import org.whispersystems.textsecuregcm.metrics.CpuUsageGauge;
|
||||
import org.whispersystems.textsecuregcm.metrics.FileDescriptorGauge;
|
||||
import org.whispersystems.textsecuregcm.metrics.FreeMemoryGauge;
|
||||
import org.whispersystems.textsecuregcm.metrics.GarbageCollectionGauges;
|
||||
import org.whispersystems.textsecuregcm.metrics.MaxFileDescriptorGauge;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsApplicationEventListener;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.NetworkReceivedGauge;
|
||||
import org.whispersystems.textsecuregcm.metrics.NetworkSentGauge;
|
||||
import org.whispersystems.textsecuregcm.metrics.OperatingSystemMemoryGauge;
|
||||
import org.whispersystems.textsecuregcm.metrics.ReportedMessageMetricsListener;
|
||||
import org.whispersystems.textsecuregcm.metrics.TrafficSource;
|
||||
import org.whispersystems.textsecuregcm.providers.MultiRecipientMessageProvider;
|
||||
@@ -165,10 +157,6 @@ 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.storage.AccountCleaner;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountDatabaseCrawler;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountDatabaseCrawlerCache;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountDatabaseCrawlerListener;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountLockManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Accounts;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
@@ -177,16 +165,13 @@ import org.whispersystems.textsecuregcm.storage.DeletedAccounts;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.KeysManager;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagePersister;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesCache;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.NonNormalizedAccountCrawlerListener;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.Profiles;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PushChallengeDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.PushFeedbackProcessor;
|
||||
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswords;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
@@ -215,6 +200,7 @@ import org.whispersystems.textsecuregcm.workers.CheckDynamicConfigurationCommand
|
||||
import org.whispersystems.textsecuregcm.workers.CrawlAccountsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.MessagePersisterServiceCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.MigrateSignedECPreKeysCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ScheduledApnPushNotificationSenderServiceCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ServerVersionCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.SetRequestLoggingEnabledTask;
|
||||
@@ -246,12 +232,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
InstanceProfileCredentialsProvider.create(),
|
||||
WebIdentityTokenFileCredentialsProvider.create());
|
||||
|
||||
public static final AWSCredentialsProviderChain AWSSDK_V1_CREDENTIALS_PROVIDER_CHAIN = new AWSCredentialsProviderChain(
|
||||
com.amazonaws.auth.InstanceProfileCredentialsProvider.getInstance(),
|
||||
com.amazonaws.auth.WebIdentityTokenCredentialsProvider.create()
|
||||
);
|
||||
|
||||
|
||||
@Override
|
||||
public void initialize(final Bootstrap<WhisperServerConfiguration> bootstrap) {
|
||||
// `SecretStore` needs to be initialized before Dropwizard reads the main application config file.
|
||||
@@ -275,6 +255,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
bootstrap.addCommand(new CrawlAccountsCommand());
|
||||
bootstrap.addCommand(new ScheduledApnPushNotificationSenderServiceCommand());
|
||||
bootstrap.addCommand(new MessagePersisterServiceCommand());
|
||||
bootstrap.addCommand(new MigrateSignedECPreKeysCommand());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -308,15 +289,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
DynamoDbClient dynamoDbClient = DynamoDbFromConfig.client(config.getDynamoDbClientConfiguration(),
|
||||
AWSSDK_CREDENTIALS_PROVIDER);
|
||||
|
||||
AmazonDynamoDB deletedAccountsLockDynamoDbClient = AmazonDynamoDBClientBuilder.standard()
|
||||
.withRegion(config.getDynamoDbClientConfiguration().getRegion())
|
||||
.withClientConfiguration(new ClientConfiguration().withClientExecutionTimeout(
|
||||
((int) config.getDynamoDbClientConfiguration().getClientExecutionTimeout().toMillis()))
|
||||
.withRequestTimeout(
|
||||
(int) config.getDynamoDbClientConfiguration().getClientRequestTimeout().toMillis()))
|
||||
.withCredentials(AWSSDK_V1_CREDENTIALS_PROVIDER_CHAIN)
|
||||
.build();
|
||||
|
||||
DeletedAccounts deletedAccounts = new DeletedAccounts(dynamoDbClient,
|
||||
config.getDynamoDbTables().getDeletedAccounts().getTableName());
|
||||
|
||||
@@ -349,7 +321,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
dynamoDbAsyncClient,
|
||||
config.getDynamoDbTables().getEcKeys().getTableName(),
|
||||
config.getDynamoDbTables().getKemKeys().getTableName(),
|
||||
config.getDynamoDbTables().getKemLastResortKeys().getTableName());
|
||||
config.getDynamoDbTables().getEcSignedPreKeys().getTableName(),
|
||||
config.getDynamoDbTables().getKemLastResortKeys().getTableName(),
|
||||
dynamicConfigurationManager);
|
||||
MessagesDynamoDb messagesDynamoDb = new MessagesDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
|
||||
config.getDynamoDbTables().getMessages().getTableName(),
|
||||
config.getDynamoDbTables().getMessages().getExpiration(),
|
||||
@@ -375,7 +349,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
final VerificationSessions verificationSessions = new VerificationSessions(dynamoDbAsyncClient,
|
||||
config.getDynamoDbTables().getVerificationSessions().getTableName(), clock);
|
||||
|
||||
ClientResources redisClientResources = ClientResources.builder().build();
|
||||
final ClientResources redisClientResources = ClientResources.builder()
|
||||
.commandLatencyRecorder(new MicrometerCommandLatencyRecorder(Metrics.globalRegistry, MicrometerOptions.builder().build()))
|
||||
.build();
|
||||
|
||||
ConnectionEventLogger.logConnectionEvents(redisClientResources);
|
||||
|
||||
FaultTolerantRedisCluster cacheCluster = new FaultTolerantRedisCluster("main_cache_cluster", config.getCacheClusterConfiguration(), redisClientResources);
|
||||
@@ -398,26 +375,33 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
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();
|
||||
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 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();
|
||||
ScheduledExecutorService secureValueRecoveryServiceRetryExecutor = environment.lifecycle()
|
||||
.scheduledExecutorService(name(getClass(), "secureValueRecoveryServiceRetry-%d")).threads(1).build();
|
||||
ScheduledExecutorService storageServiceRetryExecutor = environment.lifecycle()
|
||||
.scheduledExecutorService(name(getClass(), "storageServiceRetry-%d")).threads(1).build();
|
||||
|
||||
Scheduler messageDeliveryScheduler = Schedulers.fromExecutorService(
|
||||
ExecutorServiceMetrics.monitor(Metrics.globalRegistry,
|
||||
environment.lifecycle().executorService(name(getClass(), "messageDelivery-%d"))
|
||||
.minThreads(20)
|
||||
.maxThreads(20)
|
||||
.workQueue(messageDeliveryQueue)
|
||||
.build(),
|
||||
MetricsUtil.name(getClass(), "messageDeliveryExecutor"), MetricsUtil.PREFIX),
|
||||
"messageDelivery");
|
||||
ExecutorServiceMetrics.monitor(Metrics.globalRegistry,
|
||||
environment.lifecycle().executorService(name(getClass(), "messageDelivery-%d"))
|
||||
.minThreads(20)
|
||||
.maxThreads(20)
|
||||
.workQueue(messageDeliveryQueue)
|
||||
.build(),
|
||||
MetricsUtil.name(getClass(), "messageDeliveryExecutor"), MetricsUtil.PREFIX),
|
||||
"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()
|
||||
@@ -440,6 +424,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.maxThreads(2)
|
||||
.minThreads(2)
|
||||
.build();
|
||||
ScheduledExecutorService subscriptionProcessorRetryExecutor = environment.lifecycle()
|
||||
.scheduledExecutorService(name(getClass(), "subscriptionProcessorRetry-%d")).threads(1).build();
|
||||
|
||||
final AdminEventLogger adminEventLogger = new GoogleCloudAdminEventLogger(
|
||||
LoggingOptions.newBuilder().setProjectId(config.getAdminEventLoggingConfiguration().projectId())
|
||||
@@ -455,9 +441,11 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getStripe().idempotencyKeyGenerator().value(), config.getStripe().boostDescription(), config.getStripe()
|
||||
.supportedCurrencies());
|
||||
BraintreeManager braintreeManager = new BraintreeManager(config.getBraintree().merchantId(),
|
||||
config.getBraintree().publicKey(), config.getBraintree().privateKey().value(), config.getBraintree().environment(),
|
||||
config.getBraintree().publicKey(), config.getBraintree().privateKey().value(),
|
||||
config.getBraintree().environment(),
|
||||
config.getBraintree().supportedCurrencies(), config.getBraintree().merchantAccounts(),
|
||||
config.getBraintree().graphqlUrl(), config.getBraintree().circuitBreaker(), subscriptionProcessorExecutor);
|
||||
config.getBraintree().graphqlUrl(), config.getBraintree().circuitBreaker(), subscriptionProcessorExecutor,
|
||||
subscriptionProcessorRetryExecutor);
|
||||
|
||||
ExternalServiceCredentialsGenerator directoryV2CredentialsGenerator = DirectoryV2Controller.credentialsGenerator(
|
||||
config.getDirectoryV2Configuration().getDirectoryV2ClientConfiguration());
|
||||
@@ -490,11 +478,12 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getRegistrationServiceConfiguration().registrationCaCertificate(),
|
||||
registrationCallbackExecutor);
|
||||
SecureBackupClient secureBackupClient = new SecureBackupClient(backupCredentialsGenerator,
|
||||
secureValueRecoveryServiceExecutor, config.getSecureBackupServiceConfiguration());
|
||||
secureValueRecoveryServiceExecutor, secureValueRecoveryServiceRetryExecutor,
|
||||
config.getSecureBackupServiceConfiguration());
|
||||
SecureValueRecovery2Client secureValueRecovery2Client = new SecureValueRecovery2Client(svr2CredentialsGenerator,
|
||||
secureValueRecoveryServiceExecutor, config.getSvr2Configuration());
|
||||
secureValueRecoveryServiceExecutor, secureValueRecoveryServiceRetryExecutor, config.getSvr2Configuration());
|
||||
SecureStorageClient secureStorageClient = new SecureStorageClient(storageCredentialsGenerator,
|
||||
storageServiceExecutor, config.getSecureStorageServiceConfiguration());
|
||||
storageServiceExecutor, storageServiceRetryExecutor, config.getSecureStorageServiceConfiguration());
|
||||
ClientPresenceManager clientPresenceManager = new ClientPresenceManager(clientPresenceCluster, recurringJobExecutor,
|
||||
keyspaceNotificationDispatchExecutor);
|
||||
StoredVerificationCodeManager pendingAccountsManager = new StoredVerificationCodeManager(pendingAccounts);
|
||||
@@ -507,7 +496,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getReportMessageConfiguration().getCounterTtl());
|
||||
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager,
|
||||
messageDeletionAsyncExecutor);
|
||||
AccountLockManager accountLockManager = new AccountLockManager(deletedAccountsLockDynamoDbClient, config.getDynamoDbTables().getDeletedAccountsLock().getTableName());
|
||||
AccountLockManager accountLockManager = new AccountLockManager(dynamoDbClient,
|
||||
config.getDynamoDbTables().getDeletedAccountsLock().getTableName());
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
accountLockManager, deletedAccounts, keys, messagesManager, profilesManager,
|
||||
pendingAccountsManager, secureStorageClient, secureBackupClient, secureValueRecovery2Client,
|
||||
@@ -517,7 +507,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
APNSender apnSender = new APNSender(apnSenderExecutor, config.getApnConfiguration());
|
||||
FcmSender fcmSender = new FcmSender(fcmSenderExecutor, config.getFcmConfiguration().credentials().value());
|
||||
ApnPushNotificationScheduler apnPushNotificationScheduler = new ApnPushNotificationScheduler(pushSchedulerCluster,
|
||||
apnSender, accountsManager, Optional.empty(), dynamicConfigurationManager);
|
||||
apnSender, accountsManager, 0);
|
||||
PushNotificationManager pushNotificationManager = new PushNotificationManager(accountsManager, apnSender, fcmSender,
|
||||
apnPushNotificationScheduler, pushLatencyManager);
|
||||
RateLimiters rateLimiters = RateLimiters.createAndValidate(config.getLimitsConfiguration(),
|
||||
@@ -574,36 +564,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
RateLimitChallengeManager rateLimitChallengeManager = new RateLimitChallengeManager(pushChallengeManager,
|
||||
captchaChecker, rateLimiters);
|
||||
|
||||
MessagePersister messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager,
|
||||
dynamicConfigurationManager, Duration.ofMinutes(config.getMessageCacheConfiguration().getPersistDelayMinutes()),
|
||||
Optional.empty());
|
||||
ChangeNumberManager changeNumberManager = new ChangeNumberManager(messageSender, accountsManager);
|
||||
|
||||
AccountDatabaseCrawlerCache accountCleanerAccountDatabaseCrawlerCache =
|
||||
new AccountDatabaseCrawlerCache(cacheCluster, AccountDatabaseCrawlerCache.ACCOUNT_CLEANER_PREFIX);
|
||||
AccountDatabaseCrawler accountCleanerAccountDatabaseCrawler = new AccountDatabaseCrawler("Account cleaner crawler",
|
||||
accountsManager,
|
||||
accountCleanerAccountDatabaseCrawlerCache,
|
||||
List.of(new AccountCleaner(accountsManager, accountDeletionExecutor)),
|
||||
config.getAccountDatabaseCrawlerConfiguration().getChunkSize(),
|
||||
dynamicConfigurationManager
|
||||
);
|
||||
|
||||
// TODO listeners must be ordered so that ones that directly update accounts come last, so that read-only ones are not working with stale data
|
||||
final List<AccountDatabaseCrawlerListener> accountDatabaseCrawlerListeners = List.of(
|
||||
new NonNormalizedAccountCrawlerListener(accountsManager, metricsCluster),
|
||||
// PushFeedbackProcessor may update device properties
|
||||
new PushFeedbackProcessor(accountsManager));
|
||||
|
||||
AccountDatabaseCrawlerCache accountDatabaseCrawlerCache = new AccountDatabaseCrawlerCache(cacheCluster,
|
||||
AccountDatabaseCrawlerCache.GENERAL_PURPOSE_PREFIX);
|
||||
AccountDatabaseCrawler accountDatabaseCrawler = new AccountDatabaseCrawler("General-purpose account crawler",
|
||||
accountsManager,
|
||||
accountDatabaseCrawlerCache, accountDatabaseCrawlerListeners,
|
||||
config.getAccountDatabaseCrawlerConfiguration().getChunkSize(),
|
||||
dynamicConfigurationManager
|
||||
);
|
||||
|
||||
HttpClient currencyClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2).connectTimeout(Duration.ofSeconds(10)).build();
|
||||
FixerClient fixerClient = new FixerClient(currencyClient, config.getPaymentsServiceConfiguration().fixerApiKey().value());
|
||||
CoinMarketCapClient coinMarketCapClient = new CoinMarketCapClient(currencyClient, config.getPaymentsServiceConfiguration().coinMarketCapApiKey().value(), config.getPaymentsServiceConfiguration().coinMarketCapCurrencyIds());
|
||||
@@ -613,10 +575,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
environment.lifecycle().manage(apnSender);
|
||||
environment.lifecycle().manage(apnPushNotificationScheduler);
|
||||
environment.lifecycle().manage(provisioningManager);
|
||||
environment.lifecycle().manage(accountDatabaseCrawler);
|
||||
environment.lifecycle().manage(accountCleanerAccountDatabaseCrawler);
|
||||
environment.lifecycle().manage(messagesCache);
|
||||
environment.lifecycle().manage(messagePersister);
|
||||
environment.lifecycle().manage(clientPresenceManager);
|
||||
environment.lifecycle().manage(currencyManager);
|
||||
environment.lifecycle().manage(registrationServiceClient);
|
||||
@@ -648,10 +607,22 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
AuthFilter<BasicCredentials, DisabledPermittedAuthenticatedAccount> disabledPermittedAccountAuthFilter = new BasicCredentialAuthFilter.Builder<DisabledPermittedAuthenticatedAccount>().setAuthenticator(
|
||||
disabledPermittedAccountAuthenticator).buildAuthFilter();
|
||||
|
||||
final ServerBuilder<?> grpcServer = ServerBuilder.forPort(config.getGrpcPort())
|
||||
.intercept(new MetricCollectingServerInterceptor(Metrics.globalRegistry)); /* TODO: specialize metrics with user-agent platform */
|
||||
|
||||
RemoteDeprecationFilter remoteDeprecationFilter = new RemoteDeprecationFilter(dynamicConfigurationManager);
|
||||
environment.servlets()
|
||||
.addFilter("RemoteDeprecationFilter", new RemoteDeprecationFilter(dynamicConfigurationManager))
|
||||
.addFilter("RemoteDeprecationFilter", remoteDeprecationFilter)
|
||||
.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");
|
||||
|
||||
// Note: interceptors run in the reverse order they are added; the remote deprecation filter
|
||||
// depends on the user-agent context so it has to come first here!
|
||||
// http://grpc.github.io/grpc-java/javadoc/io/grpc/ServerBuilder.html#intercept-io.grpc.ServerInterceptor-
|
||||
grpcServer.intercept(remoteDeprecationFilter);
|
||||
grpcServer.intercept(new UserAgentInterceptor());
|
||||
|
||||
environment.lifecycle().manage(new GrpcServerManagedWrapper(grpcServer.build()));
|
||||
|
||||
environment.jersey().register(new RequestStatisticsFilter(TrafficSource.HTTP));
|
||||
environment.jersey().register(MultiRecipientMessageProvider.class);
|
||||
environment.jersey().register(new MetricsApplicationEventListener(TrafficSource.HTTP));
|
||||
@@ -756,7 +727,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new RegistrationController(accountsManager, phoneVerificationTokenManager, registrationLockVerificationManager,
|
||||
keys, rateLimiters),
|
||||
new RemoteConfigController(remoteConfigsManager, adminEventLogger,
|
||||
config.getRemoteConfigConfiguration().authorizedTokens().value(),
|
||||
config.getRemoteConfigConfiguration().authorizedUsers(),
|
||||
config.getRemoteConfigConfiguration().requiredHostedDomain(),
|
||||
config.getRemoteConfigConfiguration().audiences(),
|
||||
@@ -783,7 +753,6 @@ 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));
|
||||
@@ -817,21 +786,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
environment.healthChecks().register("cacheCluster", new RedisClusterHealthCheck(cacheCluster));
|
||||
|
||||
environment.lifecycle().manage(new ApplicationShutdownMonitor(Metrics.globalRegistry));
|
||||
|
||||
environment.metrics().register(name(CpuUsageGauge.class, "cpu"), new CpuUsageGauge(3, TimeUnit.SECONDS));
|
||||
environment.metrics().register(name(FreeMemoryGauge.class, "free_memory"), new FreeMemoryGauge());
|
||||
environment.metrics().register(name(NetworkSentGauge.class, "bytes_sent"), new NetworkSentGauge());
|
||||
environment.metrics().register(name(NetworkReceivedGauge.class, "bytes_received"), new NetworkReceivedGauge());
|
||||
environment.metrics().register(name(FileDescriptorGauge.class, "fd_count"), new FileDescriptorGauge());
|
||||
environment.metrics().register(name(MaxFileDescriptorGauge.class, "max_fd_count"), new MaxFileDescriptorGauge());
|
||||
environment.metrics()
|
||||
.register(name(OperatingSystemMemoryGauge.class, "buffers"), new OperatingSystemMemoryGauge("Buffers"));
|
||||
environment.metrics()
|
||||
.register(name(OperatingSystemMemoryGauge.class, "cached"), new OperatingSystemMemoryGauge("Cached"));
|
||||
|
||||
BufferPoolGauges.registerMetrics();
|
||||
GarbageCollectionGauges.registerMetrics();
|
||||
MetricsUtil.registerSystemResourceMetrics(environment);
|
||||
}
|
||||
|
||||
|
||||
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth.grpc;
|
||||
|
||||
import io.grpc.Context;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Provides utility methods for working with authentication in the context of gRPC calls.
|
||||
*/
|
||||
public class AuthenticationUtil {
|
||||
|
||||
static final Context.Key<UUID> CONTEXT_AUTHENTICATED_ACCOUNT_IDENTIFIER_KEY = Context.key("authenticated-aci");
|
||||
static final Context.Key<Long> CONTEXT_AUTHENTICATED_DEVICE_IDENTIFIER_KEY = Context.key("authenticated-device-id");
|
||||
|
||||
public static Optional<UUID> getAuthenticatedAccountIdentifier() {
|
||||
return Optional.ofNullable(CONTEXT_AUTHENTICATED_ACCOUNT_IDENTIFIER_KEY.get());
|
||||
}
|
||||
|
||||
public static Optional<Long> getAuthenticatedDeviceIdentifier() {
|
||||
return Optional.ofNullable(CONTEXT_AUTHENTICATED_DEVICE_IDENTIFIER_KEY.get());
|
||||
}
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth.grpc;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.auth.basic.BasicCredentials;
|
||||
import io.grpc.Context;
|
||||
import io.grpc.Contexts;
|
||||
import io.grpc.Metadata;
|
||||
import io.grpc.ServerCall;
|
||||
import io.grpc.ServerCallHandler;
|
||||
import io.grpc.ServerInterceptor;
|
||||
import io.grpc.Status;
|
||||
import java.util.Optional;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.BaseAccountAuthenticator;
|
||||
|
||||
/**
|
||||
* A basic credential authentication interceptor enforces the presence of a valid username and password on every call.
|
||||
* Callers supply credentials by providing a username (UUID and optional device ID) and password pair in the
|
||||
* {@code x-signal-basic-auth-credentials} call header.
|
||||
* <p/>
|
||||
* Downstream services can retrieve the identity of the authenticated caller using
|
||||
* {@link AuthenticationUtil#getAuthenticatedAccountIdentifier()} and
|
||||
* {@link AuthenticationUtil#getAuthenticatedDeviceIdentifier()}.
|
||||
* <p/>
|
||||
* Note that this authentication, while fully functional, is intended only for development and testing purposes and is
|
||||
* intended to be replaced with a more robust and efficient strategy before widespread client adoption.
|
||||
*
|
||||
* @see AuthenticationUtil
|
||||
* @see BaseAccountAuthenticator
|
||||
*/
|
||||
public class BasicCredentialAuthenticationInterceptor implements ServerInterceptor {
|
||||
|
||||
private final BaseAccountAuthenticator baseAccountAuthenticator;
|
||||
|
||||
@VisibleForTesting
|
||||
static final Metadata.Key<String> BASIC_CREDENTIALS =
|
||||
Metadata.Key.of("x-signal-basic-auth-credentials", Metadata.ASCII_STRING_MARSHALLER);
|
||||
|
||||
private static final Metadata EMPTY_TRAILERS = new Metadata();
|
||||
|
||||
public BasicCredentialAuthenticationInterceptor(final BaseAccountAuthenticator baseAccountAuthenticator) {
|
||||
this.baseAccountAuthenticator = baseAccountAuthenticator;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call,
|
||||
final Metadata headers,
|
||||
final ServerCallHandler<ReqT, RespT> next) {
|
||||
|
||||
final String credentialString = headers.get(BASIC_CREDENTIALS);
|
||||
|
||||
if (StringUtils.isNotBlank(credentialString)) {
|
||||
try {
|
||||
final BasicCredentials credentials = extractBasicCredentials(credentialString);
|
||||
final Optional<AuthenticatedAccount> maybeAuthenticatedAccount =
|
||||
baseAccountAuthenticator.authenticate(credentials, false);
|
||||
|
||||
if (maybeAuthenticatedAccount.isPresent()) {
|
||||
final AuthenticatedAccount authenticatedAccount = maybeAuthenticatedAccount.get();
|
||||
|
||||
final Context context = Context.current()
|
||||
.withValue(AuthenticationUtil.CONTEXT_AUTHENTICATED_ACCOUNT_IDENTIFIER_KEY, authenticatedAccount.getAccount().getUuid())
|
||||
.withValue(AuthenticationUtil.CONTEXT_AUTHENTICATED_DEVICE_IDENTIFIER_KEY, authenticatedAccount.getAuthenticatedDevice().getId());
|
||||
|
||||
return Contexts.interceptCall(context, call, headers, next);
|
||||
} else {
|
||||
call.close(Status.UNAUTHENTICATED.withDescription("Credentials not accepted"), EMPTY_TRAILERS);
|
||||
}
|
||||
} catch (final IllegalArgumentException e) {
|
||||
call.close(Status.UNAUTHENTICATED.withDescription("Could not parse credentials"), EMPTY_TRAILERS);
|
||||
}
|
||||
} else {
|
||||
call.close(Status.UNAUTHENTICATED.withDescription("No credentials provided"), EMPTY_TRAILERS);
|
||||
}
|
||||
|
||||
return new ServerCall.Listener<>() {};
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static BasicCredentials extractBasicCredentials(final String credentials) {
|
||||
if (credentials.indexOf(':') < 0) {
|
||||
throw new IllegalArgumentException("Credentials do not include a username and password part");
|
||||
}
|
||||
|
||||
final String[] pieces = credentials.split(":", 2);
|
||||
|
||||
return new BasicCredentials(pieces[0], pieces[1]);
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth.grpc;
|
||||
|
||||
/**
|
||||
* Indicates that a caller tried to get information about the authenticated gRPC caller, but no caller has been
|
||||
* authenticated.
|
||||
*/
|
||||
public class NotAuthenticatedException extends Exception {
|
||||
}
|
||||
+9
@@ -51,6 +51,7 @@ public class DynamoDbTables {
|
||||
private final Table deletedAccountsLock;
|
||||
private final IssuedReceiptsTableConfiguration issuedReceipts;
|
||||
private final Table ecKeys;
|
||||
private final Table ecSignedPreKeys;
|
||||
private final Table kemKeys;
|
||||
private final Table kemLastResortKeys;
|
||||
private final TableWithExpiration messages;
|
||||
@@ -72,6 +73,7 @@ public class DynamoDbTables {
|
||||
@JsonProperty("deletedAccountsLock") final Table deletedAccountsLock,
|
||||
@JsonProperty("issuedReceipts") final IssuedReceiptsTableConfiguration issuedReceipts,
|
||||
@JsonProperty("ecKeys") final Table ecKeys,
|
||||
@JsonProperty("ecSignedPreKeys") final Table ecSignedPreKeys,
|
||||
@JsonProperty("pqKeys") final Table kemKeys,
|
||||
@JsonProperty("pqLastResortKeys") final Table kemLastResortKeys,
|
||||
@JsonProperty("messages") final TableWithExpiration messages,
|
||||
@@ -92,6 +94,7 @@ public class DynamoDbTables {
|
||||
this.deletedAccountsLock = deletedAccountsLock;
|
||||
this.issuedReceipts = issuedReceipts;
|
||||
this.ecKeys = ecKeys;
|
||||
this.ecSignedPreKeys = ecSignedPreKeys;
|
||||
this.kemKeys = kemKeys;
|
||||
this.kemLastResortKeys = kemLastResortKeys;
|
||||
this.messages = messages;
|
||||
@@ -138,6 +141,12 @@ public class DynamoDbTables {
|
||||
return ecKeys;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getEcSignedPreKeys() {
|
||||
return ecSignedPreKeys;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getKemKeys() {
|
||||
|
||||
+1
-3
@@ -10,10 +10,8 @@ import java.util.Map;
|
||||
import java.util.Set;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretStringList;
|
||||
|
||||
public record RemoteConfigConfiguration(@NotNull SecretStringList authorizedTokens,
|
||||
@NotNull Set<String> authorizedUsers,
|
||||
public record RemoteConfigConfiguration(@NotNull Set<String> authorizedUsers,
|
||||
@NotNull String requiredHostedDomain,
|
||||
@NotNull @NotEmpty List<String> audiences,
|
||||
@NotNull Map<String, String> globalConfig) {
|
||||
|
||||
+3
-14
@@ -47,24 +47,17 @@ public class DynamicConfiguration {
|
||||
@Valid
|
||||
private DynamicTurnConfiguration turn = new DynamicTurnConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
DynamicScheduledApnNotificationSendingConfiguration scheduledApnNotificationSending = new DynamicScheduledApnNotificationSendingConfiguration(
|
||||
true, false);
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
DynamicMessagePersisterConfiguration messagePersister = new DynamicMessagePersisterConfiguration();
|
||||
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
DynamicRateLimitPolicy rateLimitPolicy = new DynamicRateLimitPolicy(false);
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
DynamicAccountDatabaseCrawlerConfiguration accountDatabaseCrawler = new DynamicAccountDatabaseCrawlerConfiguration(
|
||||
true, false);
|
||||
DynamicECPreKeyMigrationConfiguration ecPreKeyMigration = new DynamicECPreKeyMigrationConfiguration(true, false);
|
||||
|
||||
public Optional<DynamicExperimentEnrollmentConfiguration> getExperimentEnrollmentConfiguration(
|
||||
final String experimentName) {
|
||||
@@ -100,10 +93,6 @@ public class DynamicConfiguration {
|
||||
return turn;
|
||||
}
|
||||
|
||||
public DynamicScheduledApnNotificationSendingConfiguration getScheduledApnNotificationSendingConfiguration() {
|
||||
return scheduledApnNotificationSending;
|
||||
}
|
||||
|
||||
public DynamicMessagePersisterConfiguration getMessagePersisterConfiguration() {
|
||||
return messagePersister;
|
||||
}
|
||||
@@ -112,7 +101,7 @@ public class DynamicConfiguration {
|
||||
return rateLimitPolicy;
|
||||
}
|
||||
|
||||
public DynamicAccountDatabaseCrawlerConfiguration getAccountDatabaseCrawlerConfiguration() {
|
||||
return accountDatabaseCrawler;
|
||||
public DynamicECPreKeyMigrationConfiguration getEcPreKeyMigrationConfiguration() {
|
||||
return ecPreKeyMigration;
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -5,6 +5,5 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
public record DynamicAccountDatabaseCrawlerConfiguration(boolean periodicWorkEnabled, boolean crawlAllEnabled) {
|
||||
|
||||
public record DynamicECPreKeyMigrationConfiguration(boolean deleteEcSignedPreKeys, boolean storeEcSignedPreKeys) {
|
||||
}
|
||||
+3
-10
@@ -10,16 +10,9 @@ import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
public class DynamicMessagePersisterConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
private boolean serverPersistenceEnabled = true;
|
||||
private boolean persistenceEnabled = true;
|
||||
|
||||
@JsonProperty
|
||||
private boolean dedicatedProcessEnabled = false;
|
||||
|
||||
public boolean isServerPersistenceEnabled() {
|
||||
return serverPersistenceEnabled;
|
||||
}
|
||||
|
||||
public boolean isDedicatedProcessEnabled() {
|
||||
return dedicatedProcessEnabled;
|
||||
public boolean isPersistenceEnabled() {
|
||||
return persistenceEnabled;
|
||||
}
|
||||
}
|
||||
-11
@@ -1,11 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
public record DynamicScheduledApnNotificationSendingConfiguration(boolean enabledForServer,
|
||||
boolean enabledForDedicatedProcess) {
|
||||
|
||||
}
|
||||
+2
@@ -341,7 +341,9 @@ public class DeviceController {
|
||||
keys.delete(a.getPhoneNumberIdentifier(), device.getId());
|
||||
|
||||
maybeDeviceActivationRequest.ifPresent(deviceActivationRequest -> {
|
||||
keys.storeEcSignedPreKeys(a.getUuid(), Map.of(device.getId(), deviceActivationRequest.aciSignedPreKey().get()));
|
||||
keys.storePqLastResort(a.getUuid(), Map.of(device.getId(), deviceActivationRequest.aciPqLastResortPreKey().get()));
|
||||
keys.storeEcSignedPreKeys(a.getPhoneNumberIdentifier(), Map.of(device.getId(), deviceActivationRequest.pniSignedPreKey().get()));
|
||||
keys.storePqLastResort(a.getPhoneNumberIdentifier(), Map.of(device.getId(), deviceActivationRequest.pniPqLastResortPreKey().get()));
|
||||
});
|
||||
|
||||
|
||||
+20
-18
@@ -16,6 +16,8 @@ import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import io.swagger.v3.oas.annotations.parameters.RequestBody;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
@@ -36,6 +38,8 @@ import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.Anonymous;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.ChangesDeviceEnabledState;
|
||||
@@ -48,7 +52,7 @@ import org.whispersystems.textsecuregcm.entities.PreKeyCount;
|
||||
import org.whispersystems.textsecuregcm.entities.PreKeyResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.PreKeyResponseItem;
|
||||
import org.whispersystems.textsecuregcm.entities.PreKeyState;
|
||||
import org.whispersystems.textsecuregcm.entities.SignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.experiment.Experiment;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
@@ -61,9 +65,10 @@ import org.whispersystems.textsecuregcm.storage.KeysManager;
|
||||
@Tag(name = "Keys")
|
||||
public class KeysController {
|
||||
|
||||
private final RateLimiters rateLimiters;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final KeysManager keys;
|
||||
private final AccountsManager accounts;
|
||||
private final AccountsManager accounts;
|
||||
private final Experiment compareSignedEcPreKeysExperiment = new Experiment("compareSignedEcPreKeys");
|
||||
|
||||
private static final String IDENTITY_KEY_CHANGE_COUNTER_NAME = name(KeysController.class, "identityKeyChange");
|
||||
private static final String IDENTITY_KEY_CHANGE_FORBIDDEN_COUNTER_NAME = name(KeysController.class, "identityKeyChangeForbidden");
|
||||
@@ -71,6 +76,8 @@ public class KeysController {
|
||||
private static final String IDENTITY_TYPE_TAG_NAME = "identityType";
|
||||
private static final String HAS_IDENTITY_KEY_TAG_NAME = "hasIdentityKey";
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(KeysController.class);
|
||||
|
||||
public KeysController(RateLimiters rateLimiters, KeysManager keys, AccountsManager accounts) {
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.keys = keys;
|
||||
@@ -132,6 +139,12 @@ public class KeysController {
|
||||
throw new ForbiddenException();
|
||||
}
|
||||
Metrics.counter(IDENTITY_KEY_CHANGE_COUNTER_NAME, tags).increment();
|
||||
|
||||
if (hasIdentityKey) {
|
||||
logger.warn("Existing {} identity key changed; account age is {} days",
|
||||
identityType.orElse("aci"),
|
||||
Duration.between(Instant.ofEpochMilli(device.getCreated()), Instant.now()).toDays());
|
||||
}
|
||||
}
|
||||
|
||||
if (updateAccount) {
|
||||
@@ -156,7 +169,7 @@ public class KeysController {
|
||||
|
||||
keys.store(
|
||||
getIdentifier(account, identityType), device.getId(),
|
||||
preKeys.getPreKeys(), preKeys.getPqPreKeys(), preKeys.getPqLastResortPreKey());
|
||||
preKeys.getPreKeys(), preKeys.getPqPreKeys(), preKeys.getSignedPreKey(), preKeys.getPqLastResortPreKey());
|
||||
}
|
||||
|
||||
@Timed
|
||||
@@ -213,6 +226,9 @@ public class KeysController {
|
||||
ECPreKey unsignedECPreKey = keys.takeEC(identifier, device.getId()).orElse(null);
|
||||
KEMSignedPreKey pqPreKey = returnPqKey ? keys.takePQ(identifier, device.getId()).orElse(null) : null;
|
||||
|
||||
compareSignedEcPreKeysExperiment.compareFutureResult(Optional.ofNullable(signedECPreKey),
|
||||
keys.getEcSignedPreKey(identifier, device.getId()));
|
||||
|
||||
if (signedECPreKey != null || unsignedECPreKey != null || pqPreKey != null) {
|
||||
final int registrationId = usePhoneNumberIdentity ?
|
||||
device.getPhoneNumberIdentityRegistrationId().orElse(device.getRegistrationId()) :
|
||||
@@ -250,20 +266,6 @@ public class KeysController {
|
||||
});
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/signed")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public Optional<ECSignedPreKey> getSignedKey(@Auth final AuthenticatedAccount auth,
|
||||
@QueryParam("identity") final Optional<String> identityType) {
|
||||
|
||||
Device device = auth.getAuthenticatedDevice();
|
||||
ECSignedPreKey signedPreKey = usePhoneNumberIdentity(identityType) ?
|
||||
device.getPhoneNumberIdentitySignedPreKey() : device.getSignedPreKey();
|
||||
|
||||
return Optional.ofNullable(signedPreKey);
|
||||
}
|
||||
|
||||
private static boolean usePhoneNumberIdentity(final Optional<String> identityType) {
|
||||
return "pni".equals(identityType.map(String::toLowerCase).orElse("aci"));
|
||||
}
|
||||
|
||||
+5
-14
@@ -100,8 +100,6 @@ import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
|
||||
import org.whispersystems.textsecuregcm.util.DestinationDeviceValidator;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
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.Scheduler;
|
||||
@@ -536,21 +534,14 @@ public class MessageController {
|
||||
|
||||
final OutgoingMessageEntityList messages = new OutgoingMessageEntityList(envelopes
|
||||
.map(OutgoingMessageEntity::fromEnvelope)
|
||||
.peek(
|
||||
outgoingMessageEntity -> MessageMetrics.measureAccountOutgoingMessageUuidMismatches(auth.getAccount(),
|
||||
outgoingMessageEntity))
|
||||
.peek(outgoingMessageEntity -> {
|
||||
MessageMetrics.measureAccountOutgoingMessageUuidMismatches(auth.getAccount(), outgoingMessageEntity);
|
||||
MessageMetrics.measureOutgoingMessageLatency(outgoingMessageEntity.serverTimestamp(), "rest", userAgent);
|
||||
})
|
||||
.collect(Collectors.toList()),
|
||||
messagesAndHasMore.second());
|
||||
|
||||
String platform;
|
||||
|
||||
try {
|
||||
platform = UserAgentUtil.parseUserAgentString(userAgent).getPlatform().name().toLowerCase();
|
||||
} catch (final UnrecognizedUserAgentException ignored) {
|
||||
platform = "unrecognized";
|
||||
}
|
||||
|
||||
Metrics.summary(OUTGOING_MESSAGE_LIST_SIZE_BYTES_DISTRIBUTION_NAME, "platform", platform)
|
||||
Metrics.summary(OUTGOING_MESSAGE_LIST_SIZE_BYTES_DISTRIBUTION_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.record(estimateMessageListSizeBytes(messages));
|
||||
|
||||
return messages;
|
||||
|
||||
+2
@@ -176,7 +176,9 @@ public class RegistrationController {
|
||||
registrationRequest.deviceActivationRequest().gcmToken().ifPresent(gcmRegistrationId ->
|
||||
device.setGcmId(gcmRegistrationId.gcmRegistrationId()));
|
||||
|
||||
keysManager.storeEcSignedPreKeys(a.getUuid(), Map.of(Device.MASTER_ID, registrationRequest.deviceActivationRequest().aciSignedPreKey().get()));
|
||||
keysManager.storePqLastResort(a.getUuid(), Map.of(Device.MASTER_ID, registrationRequest.deviceActivationRequest().aciPqLastResortPreKey().get()));
|
||||
keysManager.storeEcSignedPreKeys(a.getPhoneNumberIdentifier(), Map.of(Device.MASTER_ID, registrationRequest.deviceActivationRequest().pniSignedPreKey().get()));
|
||||
keysManager.storePqLastResort(a.getPhoneNumberIdentifier(), Map.of(Device.MASTER_ID, registrationRequest.deviceActivationRequest().pniPqLastResortPreKey().get()));
|
||||
});
|
||||
}
|
||||
|
||||
+4
-10
@@ -15,6 +15,7 @@ import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Clock;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
@@ -54,7 +55,6 @@ public class RemoteConfigController {
|
||||
|
||||
private final RemoteConfigsManager remoteConfigsManager;
|
||||
private final AdminEventLogger adminEventLogger;
|
||||
private final List<String> configAuthTokens;
|
||||
private final Set<String> configAuthUsers;
|
||||
private final Map<String, String> globalConfig;
|
||||
|
||||
@@ -65,11 +65,10 @@ public class RemoteConfigController {
|
||||
private static final String GLOBAL_CONFIG_PREFIX = "global.";
|
||||
|
||||
public RemoteConfigController(RemoteConfigsManager remoteConfigsManager, AdminEventLogger adminEventLogger,
|
||||
List<String> configAuthTokens, Set<String> configAuthUsers, String requiredHostedDomain, List<String> audience,
|
||||
Set<String> configAuthUsers, String requiredHostedDomain, List<String> audience,
|
||||
final GoogleIdTokenVerifier.Builder googleIdTokenVerifierBuilder, Map<String, String> globalConfig) {
|
||||
this.remoteConfigsManager = remoteConfigsManager;
|
||||
this.adminEventLogger = Objects.requireNonNull(adminEventLogger);
|
||||
this.configAuthTokens = configAuthTokens;
|
||||
this.configAuthUsers = configAuthUsers;
|
||||
this.globalConfig = globalConfig;
|
||||
|
||||
@@ -93,7 +92,7 @@ public class RemoteConfigController {
|
||||
config.getUuids());
|
||||
return new UserRemoteConfig(config.getName(), inBucket,
|
||||
inBucket ? config.getValue() : config.getDefaultValue());
|
||||
}), globalConfigStream).collect(Collectors.toList()));
|
||||
}), globalConfigStream).collect(Collectors.toList()), Clock.systemUTC().instant());
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
@@ -141,8 +140,7 @@ public class RemoteConfigController {
|
||||
|
||||
private Optional<String> getAuthIdentity(String token) {
|
||||
return getAuthorizedGoogleIdentity(token)
|
||||
.map(googleIdToken -> googleIdToken.getPayload().getEmail())
|
||||
.or(() -> Optional.ofNullable(isAuthorized(token) ? token : null));
|
||||
.map(googleIdToken -> googleIdToken.getPayload().getEmail());
|
||||
}
|
||||
|
||||
private Optional<GoogleIdToken> getAuthorizedGoogleIdentity(String token) {
|
||||
@@ -183,8 +181,4 @@ public class RemoteConfigController {
|
||||
return bucket < configPercentage;
|
||||
}
|
||||
|
||||
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
|
||||
private boolean isAuthorized(String configToken) {
|
||||
return configToken != null && configAuthTokens.stream().anyMatch(authorized -> MessageDigest.isEqual(authorized.getBytes(), configToken.getBytes()));
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -10,6 +10,7 @@ import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.fasterxml.jackson.annotation.JsonFormat.Shape;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import java.time.Duration;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
@@ -27,7 +28,7 @@ public class PurchasableBadge extends Badge {
|
||||
@JsonProperty("svgs") final List<BadgeSvg> svgs,
|
||||
@JsonProperty("duration") final Duration duration) {
|
||||
super(id, category, name, description, sprites6, svg, svgs);
|
||||
this.duration = duration;
|
||||
this.duration = duration != null ? duration.truncatedTo(ChronoUnit.SECONDS) : null;
|
||||
}
|
||||
|
||||
public PurchasableBadge(final Badge badge, final Duration duration) {
|
||||
@@ -39,7 +40,7 @@ public class PurchasableBadge extends Badge {
|
||||
badge.getSprites6(),
|
||||
badge.getSvg(),
|
||||
badge.getSvgs());
|
||||
this.duration = duration;
|
||||
this.duration = duration != null ? duration.truncatedTo(ChronoUnit.SECONDS) : null;
|
||||
}
|
||||
|
||||
@JsonFormat(shape = Shape.NUMBER_INT)
|
||||
|
||||
+10
-2
@@ -50,6 +50,13 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT
|
||||
""")
|
||||
boolean skipDeviceTransfer,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
|
||||
If true, indicates that this is a request for "atomic" registration. If any properties
|
||||
needed for atomic account creation are not present, the request will fail. If false,
|
||||
atomic account creation can still occur, but only if all required fields are present.
|
||||
""")
|
||||
boolean requireAtomic,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
|
||||
The ACI-associated identity key for the account, encoded as a base64 string. If
|
||||
provided, an account will be created "atomically," and all other properties needed for
|
||||
@@ -78,6 +85,7 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT
|
||||
@JsonProperty("recoveryPassword") byte[] recoveryPassword,
|
||||
@JsonProperty("accountAttributes") AccountAttributes accountAttributes,
|
||||
@JsonProperty("skipDeviceTransfer") boolean skipDeviceTransfer,
|
||||
@JsonProperty("requireAtomic") boolean requireAtomic,
|
||||
@JsonProperty("aciIdentityKey") Optional<IdentityKey> aciIdentityKey,
|
||||
@JsonProperty("pniIdentityKey") Optional<IdentityKey> pniIdentityKey,
|
||||
@JsonProperty("aciSignedPreKey") Optional<@Valid ECSignedPreKey> aciSignedPreKey,
|
||||
@@ -90,7 +98,7 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT
|
||||
// This may seem a little verbose, but at the time of writing, Jackson struggles with `@JsonUnwrapped` members in
|
||||
// records, and this is a workaround. Please see
|
||||
// https://github.com/FasterXML/jackson-databind/issues/3726#issuecomment-1525396869 for additional context.
|
||||
this(sessionId, recoveryPassword, accountAttributes, skipDeviceTransfer, aciIdentityKey, pniIdentityKey,
|
||||
this(sessionId, recoveryPassword, accountAttributes, skipDeviceTransfer, requireAtomic, aciIdentityKey, pniIdentityKey,
|
||||
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, apnToken, gcmToken));
|
||||
}
|
||||
|
||||
@@ -122,7 +130,7 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT
|
||||
&& deviceActivationRequest().aciPqLastResortPreKey().isEmpty()
|
||||
&& deviceActivationRequest().pniPqLastResortPreKey().isEmpty();
|
||||
|
||||
return supportsAtomicAccountCreation() || hasNoAtomicAccountCreationParameters;
|
||||
return supportsAtomicAccountCreation() || (!requireAtomic() && hasNoAtomicAccountCreationParameters);
|
||||
}
|
||||
|
||||
public boolean supportsAtomicAccountCreation() {
|
||||
|
||||
+13
-1
@@ -5,8 +5,11 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.List;
|
||||
|
||||
public class UserRemoteConfigList {
|
||||
@@ -14,13 +17,22 @@ public class UserRemoteConfigList {
|
||||
@JsonProperty
|
||||
private List<UserRemoteConfig> config;
|
||||
|
||||
@JsonProperty
|
||||
@JsonFormat(shape = JsonFormat.Shape.NUMBER_INT)
|
||||
private Instant serverEpochTime;
|
||||
|
||||
public UserRemoteConfigList() {}
|
||||
|
||||
public UserRemoteConfigList(List<UserRemoteConfig> config) {
|
||||
public UserRemoteConfigList(List<UserRemoteConfig> config, Instant serverEpochTime) {
|
||||
this.config = config;
|
||||
this.serverEpochTime = serverEpochTime != null ? serverEpochTime.truncatedTo(ChronoUnit.SECONDS) : null;
|
||||
}
|
||||
|
||||
public List<UserRemoteConfig> getConfig() {
|
||||
return config;
|
||||
}
|
||||
|
||||
public Instant getServerEpochTime() {
|
||||
return serverEpochTime;
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,6 @@ import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Supplier;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -72,65 +71,62 @@ public class Experiment {
|
||||
}
|
||||
|
||||
public <T> void compareFutureResult(final T expected, final CompletionStage<T> experimentStage) {
|
||||
final long startNanos = System.nanoTime();
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
experimentStage.whenComplete((actual, cause) -> {
|
||||
final long durationNanos = System.nanoTime() - startNanos;
|
||||
|
||||
if (cause != null) {
|
||||
recordError(cause, durationNanos);
|
||||
recordError(cause, sample);
|
||||
} else {
|
||||
recordResult(expected, actual, durationNanos);
|
||||
recordResult(expected, actual, sample);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public <T> void compareSupplierResult(final T expected, final Supplier<T> experimentSupplier) {
|
||||
final long startNanos = System.nanoTime();
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
try {
|
||||
final T result = experimentSupplier.get();
|
||||
|
||||
recordResult(expected, result, System.nanoTime() - startNanos);
|
||||
recordResult(expected, result, sample);
|
||||
} catch (final Exception e) {
|
||||
recordError(e, System.nanoTime() - startNanos);
|
||||
recordError(e, sample);
|
||||
}
|
||||
}
|
||||
|
||||
public <T> void compareSupplierResultAsync(final T expected, final Supplier<T> experimentSupplier,
|
||||
final Executor executor) {
|
||||
final long startNanos = System.nanoTime();
|
||||
public <T> void compareSupplierResultAsync(final T expected, final Supplier<T> experimentSupplier, final Executor executor) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
try {
|
||||
compareFutureResult(expected, CompletableFuture.supplyAsync(experimentSupplier, executor));
|
||||
} catch (final Exception e) {
|
||||
recordError(e, System.nanoTime() - startNanos);
|
||||
recordError(e, sample);
|
||||
}
|
||||
}
|
||||
|
||||
private void recordError(final Throwable cause, final long durationNanos) {
|
||||
private void recordError(final Throwable cause, final Timer.Sample sample) {
|
||||
log.warn("Experiment {} threw an exception.", name, cause);
|
||||
errorTimer.record(durationNanos, TimeUnit.NANOSECONDS);
|
||||
sample.stop(errorTimer);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
<T> void recordResult(final T expected, final T actual, final long durationNanos) {
|
||||
<T> void recordResult(final T expected, final T actual, final Timer.Sample sample) {
|
||||
if (expected instanceof Optional && actual instanceof Optional) {
|
||||
recordResult(((Optional) expected).orElse(null), ((Optional) actual).orElse(null), durationNanos);
|
||||
recordResult(((Optional) expected).orElse(null), ((Optional) actual).orElse(null), sample);
|
||||
} else {
|
||||
final Timer Timer;
|
||||
final Timer timer;
|
||||
|
||||
if (Objects.equals(expected, actual)) {
|
||||
Timer = matchTimer;
|
||||
timer = matchTimer;
|
||||
} else if (expected == null) {
|
||||
Timer = controlNullMismatchTimer;
|
||||
timer = controlNullMismatchTimer;
|
||||
} else if (actual == null) {
|
||||
Timer = experimentNullMismatchTimer;
|
||||
timer = experimentNullMismatchTimer;
|
||||
} else {
|
||||
Timer = bothPresentMismatchTimer;
|
||||
timer = bothPresentMismatchTimer;
|
||||
}
|
||||
|
||||
Timer.record(durationNanos, TimeUnit.NANOSECONDS);
|
||||
sample.stop(timer);
|
||||
}
|
||||
}
|
||||
}
|
||||
+77
-44
@@ -7,8 +7,15 @@ package org.whispersystems.textsecuregcm.filters;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import com.vdurmont.semver4j.Semver;
|
||||
|
||||
import io.grpc.Metadata;
|
||||
import io.grpc.ServerCall;
|
||||
import io.grpc.ServerCallHandler;
|
||||
import io.grpc.ServerInterceptor;
|
||||
import io.grpc.Status;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
@@ -22,6 +29,8 @@ import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicRemoteDeprecationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.grpc.StatusConstants;
|
||||
import org.whispersystems.textsecuregcm.grpc.UserAgentInterceptor;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
|
||||
@@ -34,7 +43,7 @@ import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
|
||||
* If a client platform does not have a configured minimum version, all traffic from that client
|
||||
* platform is allowed.
|
||||
*/
|
||||
public class RemoteDeprecationFilter implements Filter {
|
||||
public class RemoteDeprecationFilter implements Filter, ServerInterceptor {
|
||||
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
|
||||
@@ -52,60 +61,84 @@ public class RemoteDeprecationFilter implements Filter {
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
|
||||
final DynamicRemoteDeprecationConfiguration configuration = dynamicConfigurationManager
|
||||
.getConfiguration().getRemoteDeprecationConfiguration();
|
||||
|
||||
final Map<ClientPlatform, Semver> minimumVersionsByPlatform = configuration.getMinimumVersions();
|
||||
final Map<ClientPlatform, Semver> versionsPendingDeprecationByPlatform = configuration.getVersionsPendingDeprecation();
|
||||
final Map<ClientPlatform, Set<Semver>> blockedVersionsByPlatform = configuration.getBlockedVersions();
|
||||
final Map<ClientPlatform, Set<Semver>> versionsPendingBlockByPlatform = configuration.getVersionsPendingBlock();
|
||||
final boolean allowUnrecognizedUserAgents = configuration.isUnrecognizedUserAgentAllowed();
|
||||
|
||||
boolean shouldBlock = false;
|
||||
final String userAgentString = ((HttpServletRequest) request).getHeader(HttpHeaders.USER_AGENT);
|
||||
|
||||
UserAgent userAgent;
|
||||
try {
|
||||
final String userAgentString = ((HttpServletRequest) request).getHeader(HttpHeaders.USER_AGENT);
|
||||
final UserAgent userAgent = UserAgentUtil.parseUserAgentString(userAgentString);
|
||||
|
||||
if (blockedVersionsByPlatform.containsKey(userAgent.getPlatform())) {
|
||||
if (blockedVersionsByPlatform.get(userAgent.getPlatform()).contains(userAgent.getVersion())) {
|
||||
recordDeprecation(userAgent, BLOCKED_CLIENT_REASON);
|
||||
shouldBlock = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (minimumVersionsByPlatform.containsKey(userAgent.getPlatform())) {
|
||||
if (userAgent.getVersion().isLowerThan(minimumVersionsByPlatform.get(userAgent.getPlatform()))) {
|
||||
recordDeprecation(userAgent, EXPIRED_CLIENT_REASON);
|
||||
shouldBlock = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (versionsPendingBlockByPlatform.containsKey(userAgent.getPlatform())) {
|
||||
if (versionsPendingBlockByPlatform.get(userAgent.getPlatform()).contains(userAgent.getVersion())) {
|
||||
recordPendingDeprecation(userAgent, BLOCKED_CLIENT_REASON);
|
||||
}
|
||||
}
|
||||
|
||||
if (versionsPendingDeprecationByPlatform.containsKey(userAgent.getPlatform())) {
|
||||
if (userAgent.getVersion().isLowerThan(versionsPendingDeprecationByPlatform.get(userAgent.getPlatform()))) {
|
||||
recordPendingDeprecation(userAgent, EXPIRED_CLIENT_REASON);
|
||||
}
|
||||
}
|
||||
userAgent = UserAgentUtil.parseUserAgentString(userAgentString);
|
||||
} catch (final UnrecognizedUserAgentException e) {
|
||||
if (!allowUnrecognizedUserAgents) {
|
||||
recordDeprecation(null, UNRECOGNIZED_UA_REASON);
|
||||
shouldBlock = true;
|
||||
}
|
||||
userAgent = null;
|
||||
}
|
||||
|
||||
if (shouldBlock) {
|
||||
if (shouldBlock(userAgent)) {
|
||||
((HttpServletResponse) response).sendError(499);
|
||||
} else {
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
|
||||
final ServerCall<ReqT, RespT> call,
|
||||
final Metadata headers,
|
||||
final ServerCallHandler<ReqT, RespT> next) {
|
||||
|
||||
if (shouldBlock(UserAgentUtil.userAgentFromGrpcContext())) {
|
||||
call.close(StatusConstants.UPGRADE_NEEDED_STATUS, new Metadata());
|
||||
return new ServerCall.Listener<>() {};
|
||||
} else {
|
||||
return next.startCall(call, headers);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean shouldBlock(final UserAgent userAgent) {
|
||||
final DynamicRemoteDeprecationConfiguration configuration = dynamicConfigurationManager
|
||||
.getConfiguration().getRemoteDeprecationConfiguration();
|
||||
final Map<ClientPlatform, Semver> minimumVersionsByPlatform = configuration.getMinimumVersions();
|
||||
final Map<ClientPlatform, Semver> versionsPendingDeprecationByPlatform = configuration
|
||||
.getVersionsPendingDeprecation();
|
||||
final Map<ClientPlatform, Set<Semver>> blockedVersionsByPlatform = configuration.getBlockedVersions();
|
||||
final Map<ClientPlatform, Set<Semver>> versionsPendingBlockByPlatform = configuration.getVersionsPendingBlock();
|
||||
|
||||
boolean shouldBlock = false;
|
||||
|
||||
if (userAgent == null) {
|
||||
if (configuration.isUnrecognizedUserAgentAllowed()) {
|
||||
return false;
|
||||
}
|
||||
recordDeprecation(null, UNRECOGNIZED_UA_REASON);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (blockedVersionsByPlatform.containsKey(userAgent.getPlatform())) {
|
||||
if (blockedVersionsByPlatform.get(userAgent.getPlatform()).contains(userAgent.getVersion())) {
|
||||
recordDeprecation(userAgent, BLOCKED_CLIENT_REASON);
|
||||
shouldBlock = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (minimumVersionsByPlatform.containsKey(userAgent.getPlatform())) {
|
||||
if (userAgent.getVersion().isLowerThan(minimumVersionsByPlatform.get(userAgent.getPlatform()))) {
|
||||
recordDeprecation(userAgent, EXPIRED_CLIENT_REASON);
|
||||
shouldBlock = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (versionsPendingBlockByPlatform.containsKey(userAgent.getPlatform())) {
|
||||
if (versionsPendingBlockByPlatform.get(userAgent.getPlatform()).contains(userAgent.getVersion())) {
|
||||
recordPendingDeprecation(userAgent, BLOCKED_CLIENT_REASON);
|
||||
}
|
||||
}
|
||||
|
||||
if (versionsPendingDeprecationByPlatform.containsKey(userAgent.getPlatform())) {
|
||||
if (userAgent.getVersion().isLowerThan(versionsPendingDeprecationByPlatform.get(userAgent.getPlatform()))) {
|
||||
recordPendingDeprecation(userAgent, EXPIRED_CLIENT_REASON);
|
||||
}
|
||||
}
|
||||
|
||||
return shouldBlock;
|
||||
}
|
||||
|
||||
private void recordDeprecation(final UserAgent userAgent, final String reason) {
|
||||
Metrics.counter(DEPRECATED_CLIENT_COUNTER_NAME,
|
||||
PLATFORM_TAG, userAgent != null ? userAgent.getPlatform().name().toLowerCase() : "unrecognized",
|
||||
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import io.grpc.Server;
|
||||
|
||||
public class GrpcServerManagedWrapper implements Managed {
|
||||
|
||||
private final Server server;
|
||||
|
||||
public GrpcServerManagedWrapper(final Server server) {
|
||||
this.server = server;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() throws IOException {
|
||||
server.start();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
try {
|
||||
server.shutdown().awaitTermination(5, TimeUnit.MINUTES);
|
||||
} catch (InterruptedException e) {
|
||||
server.shutdownNow();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import io.grpc.Status;
|
||||
|
||||
public abstract class StatusConstants {
|
||||
public static final Status UPGRADE_NEEDED_STATUS = Status.INVALID_ARGUMENT.withDescription("signal-upgrade-required");
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
|
||||
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UserAgent;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
|
||||
|
||||
import io.grpc.Context;
|
||||
import io.grpc.Contexts;
|
||||
import io.grpc.Metadata;
|
||||
import io.grpc.ServerCall;
|
||||
import io.grpc.ServerCallHandler;
|
||||
import io.grpc.ServerInterceptor;
|
||||
import io.grpc.Status;
|
||||
|
||||
public class UserAgentInterceptor implements ServerInterceptor {
|
||||
@VisibleForTesting
|
||||
public static final Metadata.Key<String> USER_AGENT_GRPC_HEADER =
|
||||
Metadata.Key.of("user-agent", Metadata.ASCII_STRING_MARSHALLER);
|
||||
|
||||
@Override
|
||||
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call,
|
||||
final Metadata headers,
|
||||
final ServerCallHandler<ReqT, RespT> next) {
|
||||
|
||||
UserAgent userAgent;
|
||||
try {
|
||||
userAgent = UserAgentUtil.parseUserAgentString(headers.get(USER_AGENT_GRPC_HEADER));
|
||||
} catch (final UnrecognizedUserAgentException e) {
|
||||
userAgent = null;
|
||||
}
|
||||
|
||||
final Context context = Context.current().withValue(UserAgentUtil.USER_AGENT_CONTEXT_KEY, userAgent);
|
||||
return Contexts.interceptCall(context, call, headers, next);
|
||||
}
|
||||
|
||||
}
|
||||
+35
-25
@@ -17,7 +17,6 @@ import java.time.Duration;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.function.Supplier;
|
||||
import org.glassfish.jersey.SslConfigurator;
|
||||
@@ -28,10 +27,10 @@ import org.whispersystems.textsecuregcm.util.CircuitBreakerUtil;
|
||||
|
||||
public class FaultTolerantHttpClient {
|
||||
|
||||
private final HttpClient httpClient;
|
||||
private final HttpClient httpClient;
|
||||
private final ScheduledExecutorService retryExecutor;
|
||||
private final Retry retry;
|
||||
private final CircuitBreaker breaker;
|
||||
private final Retry retry;
|
||||
private final CircuitBreaker breaker;
|
||||
|
||||
public static final String SECURITY_PROTOCOL_TLS_1_2 = "TLSv1.2";
|
||||
public static final String SECURITY_PROTOCOL_TLS_1_3 = "TLSv1.3";
|
||||
@@ -40,15 +39,20 @@ public class FaultTolerantHttpClient {
|
||||
return new Builder();
|
||||
}
|
||||
|
||||
private FaultTolerantHttpClient(String name, HttpClient httpClient, RetryConfiguration retryConfiguration, CircuitBreakerConfiguration circuitBreakerConfiguration) {
|
||||
this.httpClient = httpClient;
|
||||
this.retryExecutor = Executors.newSingleThreadScheduledExecutor();
|
||||
this.breaker = CircuitBreaker.of(name + "-breaker", circuitBreakerConfiguration.toCircuitBreakerConfig());
|
||||
private FaultTolerantHttpClient(String name, HttpClient httpClient, ScheduledExecutorService retryExecutor,
|
||||
RetryConfiguration retryConfiguration, CircuitBreakerConfiguration circuitBreakerConfiguration) {
|
||||
this.httpClient = httpClient;
|
||||
this.retryExecutor = retryExecutor;
|
||||
this.breaker = CircuitBreaker.of(name + "-breaker", circuitBreakerConfiguration.toCircuitBreakerConfig());
|
||||
|
||||
CircuitBreakerUtil.registerMetrics(breaker, FaultTolerantHttpClient.class);
|
||||
|
||||
if (retryConfiguration != null) {
|
||||
RetryConfig retryConfig = retryConfiguration.<HttpResponse>toRetryConfigBuilder().retryOnResult(o -> o.statusCode() >= 500).build();
|
||||
if (this.retryExecutor == null) {
|
||||
throw new IllegalArgumentException("retryExecutor must be specified with retryConfiguration");
|
||||
}
|
||||
RetryConfig retryConfig = retryConfiguration.<HttpResponse>toRetryConfigBuilder()
|
||||
.retryOnResult(o -> o.statusCode() >= 500).build();
|
||||
this.retry = Retry.of(name + "-retry", retryConfig);
|
||||
CircuitBreakerUtil.registerMetrics(retry, FaultTolerantHttpClient.class);
|
||||
} else {
|
||||
@@ -76,19 +80,20 @@ public class FaultTolerantHttpClient {
|
||||
|
||||
public static class Builder {
|
||||
|
||||
private HttpClient.Version version = HttpClient.Version.HTTP_2;
|
||||
private HttpClient.Redirect redirect = HttpClient.Redirect.NEVER;
|
||||
private Duration connectTimeout = Duration.ofSeconds(10);
|
||||
|
||||
private HttpClient.Version version = HttpClient.Version.HTTP_2;
|
||||
private HttpClient.Redirect redirect = HttpClient.Redirect.NEVER;
|
||||
private Duration connectTimeout = Duration.ofSeconds(10);
|
||||
|
||||
private String name;
|
||||
private Executor executor;
|
||||
private KeyStore trustStore;
|
||||
private String securityProtocol = SECURITY_PROTOCOL_TLS_1_2;
|
||||
private RetryConfiguration retryConfiguration;
|
||||
private String name;
|
||||
private Executor executor;
|
||||
private ScheduledExecutorService retryExecutor;
|
||||
private KeyStore trustStore;
|
||||
private String securityProtocol = SECURITY_PROTOCOL_TLS_1_2;
|
||||
private RetryConfiguration retryConfiguration;
|
||||
private CircuitBreakerConfiguration circuitBreakerConfiguration;
|
||||
|
||||
private Builder() {}
|
||||
private Builder() {
|
||||
}
|
||||
|
||||
public Builder withName(String name) {
|
||||
this.name = name;
|
||||
@@ -120,6 +125,11 @@ public class FaultTolerantHttpClient {
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder withRetryExecutor(ScheduledExecutorService retryExecutor) {
|
||||
this.retryExecutor = retryExecutor;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder withCircuitBreaker(CircuitBreakerConfiguration circuitBreakerConfiguration) {
|
||||
this.circuitBreakerConfiguration = circuitBreakerConfiguration;
|
||||
return this;
|
||||
@@ -141,10 +151,10 @@ public class FaultTolerantHttpClient {
|
||||
}
|
||||
|
||||
final HttpClient.Builder builder = HttpClient.newBuilder()
|
||||
.connectTimeout(connectTimeout)
|
||||
.followRedirects(redirect)
|
||||
.version(version)
|
||||
.executor(executor);
|
||||
.connectTimeout(connectTimeout)
|
||||
.followRedirects(redirect)
|
||||
.version(version)
|
||||
.executor(executor);
|
||||
|
||||
final SslConfigurator sslConfigurator = SslConfigurator.newInstance().securityProtocol(securityProtocol);
|
||||
|
||||
@@ -154,9 +164,9 @@ public class FaultTolerantHttpClient {
|
||||
|
||||
builder.sslContext(sslConfigurator.createSSLContext());
|
||||
|
||||
return new FaultTolerantHttpClient(name, builder.build(), retryConfiguration, circuitBreakerConfiguration);
|
||||
return new FaultTolerantHttpClient(name, builder.build(), retryExecutor, retryConfiguration,
|
||||
circuitBreakerConfiguration);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -8,7 +8,11 @@ package org.whispersystems.textsecuregcm.metrics;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
@@ -22,6 +26,8 @@ public final class MessageMetrics {
|
||||
private static final String MISMATCHED_ACCOUNT_ENVELOPE_UUID_COUNTER_NAME = name(MessageMetrics.class,
|
||||
"mismatchedAccountEnvelopeUuid");
|
||||
|
||||
private static final String DELIVERY_LATENCY_TIMER_NAME = name(MessageMetrics.class, "deliveryLatency");
|
||||
|
||||
public static void measureAccountOutgoingMessageUuidMismatches(final Account account,
|
||||
final OutgoingMessageEntity outgoingMessage) {
|
||||
measureAccountDestinationUuidMismatches(account, outgoingMessage.destinationUuid());
|
||||
@@ -48,4 +54,10 @@ public final class MessageMetrics {
|
||||
}
|
||||
}
|
||||
|
||||
public static void measureOutgoingMessageLatency(final long serverTimestamp, final String channel, final String userAgent) {
|
||||
Metrics.timer(DELIVERY_LATENCY_TIMER_NAME, Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of("channel", channel)))
|
||||
.record(Duration.between(Instant.ofEpochMilli(serverTimestamp), Instant.now()));
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.config.MeterFilter;
|
||||
import io.micrometer.core.instrument.distribution.DistributionStatisticConfig;
|
||||
import io.micrometer.datadog.DatadogMeterRegistry;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerVersion;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
@@ -66,5 +67,23 @@ public class MetricsUtil {
|
||||
}
|
||||
|
||||
environment.lifecycle().manage(new MicrometerRegistryManager(Metrics.globalRegistry));
|
||||
environment.lifecycle().manage(new ApplicationShutdownMonitor(Metrics.globalRegistry));
|
||||
}
|
||||
|
||||
public static void registerSystemResourceMetrics(final Environment environment) {
|
||||
environment.metrics().register(name(CpuUsageGauge.class, "cpu"), new CpuUsageGauge(3, TimeUnit.SECONDS));
|
||||
environment.metrics().register(name(FreeMemoryGauge.class, "free_memory"), new FreeMemoryGauge());
|
||||
environment.metrics().register(name(NetworkSentGauge.class, "bytes_sent"), new NetworkSentGauge());
|
||||
environment.metrics().register(name(NetworkReceivedGauge.class, "bytes_received"), new NetworkReceivedGauge());
|
||||
environment.metrics().register(name(FileDescriptorGauge.class, "fd_count"), new FileDescriptorGauge());
|
||||
environment.metrics().register(name(MaxFileDescriptorGauge.class, "max_fd_count"), new MaxFileDescriptorGauge());
|
||||
environment.metrics()
|
||||
.register(name(OperatingSystemMemoryGauge.class, "buffers"), new OperatingSystemMemoryGauge("Buffers"));
|
||||
environment.metrics()
|
||||
.register(name(OperatingSystemMemoryGauge.class, "cached"), new OperatingSystemMemoryGauge("Cached"));
|
||||
|
||||
BufferPoolGauges.registerMetrics();
|
||||
GarbageCollectionGauges.registerMetrics();
|
||||
}
|
||||
|
||||
}
|
||||
+5
-28
@@ -33,13 +33,11 @@ import java.util.function.Consumer;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
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.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.RedisClusterUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
@@ -75,10 +73,6 @@ public class ApnPushNotificationScheduler implements Managed {
|
||||
private final ClusterLuaScript scheduleBackgroundNotificationScript;
|
||||
|
||||
private final Thread[] workerThreads;
|
||||
private final boolean dedicatedProcess;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
|
||||
private static final int DEFAULT_WORKER_THREAD_COUNT = 4;
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration BACKGROUND_NOTIFICATION_PERIOD = Duration.ofMinutes(20);
|
||||
@@ -105,18 +99,6 @@ public class ApnPushNotificationScheduler implements Managed {
|
||||
}
|
||||
|
||||
private long processNextSlot() {
|
||||
if (dedicatedProcess) {
|
||||
if (!dynamicConfigurationManager.getConfiguration().getScheduledApnNotificationSendingConfiguration()
|
||||
.enabledForDedicatedProcess()) {
|
||||
return 0;
|
||||
}
|
||||
} else {
|
||||
if (!dynamicConfigurationManager.getConfiguration().getScheduledApnNotificationSendingConfiguration()
|
||||
.enabledForServer()) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
final int slot = (int) (pushSchedulingCluster.withCluster(connection ->
|
||||
connection.sync().incr(NEXT_SLOT_TO_PROCESS_KEY)) % SlotHash.SLOT_COUNT);
|
||||
|
||||
@@ -181,11 +163,10 @@ public class ApnPushNotificationScheduler implements Managed {
|
||||
}
|
||||
|
||||
public ApnPushNotificationScheduler(FaultTolerantRedisCluster pushSchedulingCluster,
|
||||
APNSender apnSender, AccountsManager accountsManager, final Optional<Integer> dedicatedProcessWorkerThreadCount,
|
||||
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) throws IOException {
|
||||
APNSender apnSender, AccountsManager accountsManager, final int dedicatedProcessWorkerThreadCount)
|
||||
throws IOException {
|
||||
|
||||
this(pushSchedulingCluster, apnSender, accountsManager, Clock.systemUTC(), dedicatedProcessWorkerThreadCount,
|
||||
dynamicConfigurationManager);
|
||||
this(pushSchedulingCluster, apnSender, accountsManager, Clock.systemUTC(), dedicatedProcessWorkerThreadCount);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -193,8 +174,7 @@ public class ApnPushNotificationScheduler implements Managed {
|
||||
APNSender apnSender,
|
||||
AccountsManager accountsManager,
|
||||
Clock clock,
|
||||
Optional<Integer> dedicatedProcessThreadCount,
|
||||
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) throws IOException {
|
||||
int dedicatedProcessThreadCount) throws IOException {
|
||||
|
||||
this.apnSender = apnSender;
|
||||
this.accountsManager = accountsManager;
|
||||
@@ -211,14 +191,11 @@ public class ApnPushNotificationScheduler implements Managed {
|
||||
this.scheduleBackgroundNotificationScript = ClusterLuaScript.fromResource(pushSchedulingCluster,
|
||||
"lua/apn/schedule_background_notification.lua", ScriptOutputType.VALUE);
|
||||
|
||||
this.workerThreads = dedicatedProcessThreadCount.map(Thread[]::new)
|
||||
.orElseGet(() -> new Thread[DEFAULT_WORKER_THREAD_COUNT]);
|
||||
this.workerThreads = new Thread[dedicatedProcessThreadCount];
|
||||
|
||||
for (int i = 0; i < this.workerThreads.length; i++) {
|
||||
this.workerThreads[i] = new Thread(new NotificationWorker(), "ApnFallbackManagerWorker-" + i);
|
||||
}
|
||||
this.dedicatedProcess = dedicatedProcessThreadCount.isPresent();
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -89,7 +89,7 @@ public class MessageSender {
|
||||
pushNotificationManager.sendNewMessageNotification(account, device.getId(), message.getUrgent());
|
||||
|
||||
final boolean useVoip = StringUtils.isNotBlank(device.getVoipApnId());
|
||||
RedisOperation.unchecked(() -> pushLatencyManager.recordPushSent(account.getUuid(), device.getId(), useVoip));
|
||||
RedisOperation.unchecked(() -> pushLatencyManager.recordPushSent(account.getUuid(), device.getId(), useVoip, message.getUrgent()));
|
||||
} catch (final NotPushRegisteredException e) {
|
||||
if (!device.getFetchesMessages()) {
|
||||
throw e;
|
||||
|
||||
+4
-2
@@ -19,16 +19,17 @@ import io.lettuce.core.pubsub.RedisPubSubAdapter;
|
||||
import io.lettuce.core.pubsub.StatefulRedisPubSubConnection;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Consumer;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisOperation;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisUriUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.PubSubProtos;
|
||||
import org.whispersystems.textsecuregcm.util.CircuitBreakerUtil;
|
||||
import org.whispersystems.textsecuregcm.websocket.InvalidWebsocketAddressException;
|
||||
@@ -60,7 +61,8 @@ public class ProvisioningManager extends RedisPubSubAdapter<byte[], byte[]> impl
|
||||
final Duration timeout,
|
||||
final CircuitBreakerConfiguration circuitBreakerConfiguration) {
|
||||
|
||||
this(RedisClient.create(clientResources, redisUri), timeout, circuitBreakerConfiguration);
|
||||
this(RedisClient.create(clientResources, RedisUriUtil.createRedisUriWithTimeout(redisUri, timeout)), timeout,
|
||||
circuitBreakerConfiguration);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
|
||||
+8
-33
@@ -6,8 +6,6 @@
|
||||
package org.whispersystems.textsecuregcm.push;
|
||||
|
||||
import com.codahale.metrics.MetricRegistry;
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.vdurmont.semver4j.Semver;
|
||||
@@ -20,10 +18,10 @@ import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -63,29 +61,7 @@ public class PushLatencyManager {
|
||||
VOIP
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static class PushRecord {
|
||||
private final Instant timestamp;
|
||||
|
||||
@Nullable
|
||||
private final PushType pushType;
|
||||
|
||||
@JsonCreator
|
||||
PushRecord(@JsonProperty("timestamp") final Instant timestamp,
|
||||
@JsonProperty("pushType") @Nullable final PushType pushType) {
|
||||
|
||||
this.timestamp = timestamp;
|
||||
this.pushType = pushType;
|
||||
}
|
||||
|
||||
public Instant getTimestamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public PushType getPushType() {
|
||||
return pushType;
|
||||
}
|
||||
record PushRecord(Instant timestamp, PushType pushType, Optional<Boolean> urgent) {
|
||||
}
|
||||
|
||||
public PushLatencyManager(final FaultTolerantRedisCluster redisCluster,
|
||||
@@ -104,10 +80,10 @@ public class PushLatencyManager {
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
void recordPushSent(final UUID accountUuid, final long deviceId, final boolean isVoip) {
|
||||
void recordPushSent(final UUID accountUuid, final long deviceId, final boolean isVoip, final boolean isUrgent) {
|
||||
try {
|
||||
final String recordJson = SystemMapper.jsonMapper().writeValueAsString(
|
||||
new PushRecord(Instant.now(clock), isVoip ? PushType.VOIP : PushType.STANDARD));
|
||||
new PushRecord(Instant.now(clock), isVoip ? PushType.VOIP : PushType.STANDARD, Optional.of(isUrgent)));
|
||||
|
||||
redisCluster.useCluster(connection ->
|
||||
connection.async().set(getFirstUnacknowledgedPushKey(accountUuid, deviceId),
|
||||
@@ -122,15 +98,14 @@ public class PushLatencyManager {
|
||||
void recordQueueRead(final UUID accountUuid, final long deviceId, final String userAgentString) {
|
||||
takePushRecord(accountUuid, deviceId).thenAccept(pushRecord -> {
|
||||
if (pushRecord != null) {
|
||||
final Duration latency = Duration.between(pushRecord.getTimestamp(), Instant.now());
|
||||
final Duration latency = Duration.between(pushRecord.timestamp(), Instant.now());
|
||||
|
||||
final List<Tag> tags = new ArrayList<>(2);
|
||||
final List<Tag> tags = new ArrayList<>(3);
|
||||
|
||||
tags.add(UserAgentTagUtil.getPlatformTag(userAgentString));
|
||||
tags.add(Tag.of("pushType", pushRecord.pushType().name().toLowerCase()));
|
||||
|
||||
if (pushRecord.getPushType() != null) {
|
||||
tags.add(Tag.of("pushType", pushRecord.getPushType().name().toLowerCase()));
|
||||
}
|
||||
pushRecord.urgent().ifPresent(urgent -> tags.add(Tag.of("urgent", String.valueOf(urgent))));
|
||||
|
||||
try {
|
||||
final UserAgent userAgent = UserAgentUtil.parseUserAgentString(userAgentString);
|
||||
|
||||
+9
-3
@@ -15,6 +15,7 @@ import io.github.resilience4j.retry.RetryConfig;
|
||||
import io.lettuce.core.ClientOptions.DisconnectedBehavior;
|
||||
import io.lettuce.core.RedisCommandTimeoutException;
|
||||
import io.lettuce.core.RedisException;
|
||||
import io.lettuce.core.TimeoutOptions;
|
||||
import io.lettuce.core.cluster.ClusterClientOptions;
|
||||
import io.lettuce.core.cluster.ClusterTopologyRefreshOptions;
|
||||
import io.lettuce.core.cluster.RedisClusterClient;
|
||||
@@ -57,7 +58,9 @@ public class FaultTolerantRedisCluster {
|
||||
public FaultTolerantRedisCluster(final String name, final RedisClusterConfiguration clusterConfiguration,
|
||||
final ClientResources clientResources) {
|
||||
this(name,
|
||||
RedisClusterClient.create(clientResources, clusterConfiguration.getConfigurationUri()),
|
||||
RedisClusterClient.create(clientResources,
|
||||
RedisUriUtil.createRedisUriWithTimeout(clusterConfiguration.getConfigurationUri(),
|
||||
clusterConfiguration.getTimeout())),
|
||||
clusterConfiguration.getTimeout(),
|
||||
clusterConfiguration.getCircuitBreakerConfiguration(),
|
||||
clusterConfiguration.getRetryConfiguration());
|
||||
@@ -69,13 +72,16 @@ public class FaultTolerantRedisCluster {
|
||||
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())
|
||||
// for asynchronous commands
|
||||
.timeoutOptions(TimeoutOptions.builder()
|
||||
.fixedTimeout(commandTimeout)
|
||||
.build())
|
||||
.publishOnScheduler(true)
|
||||
.build());
|
||||
|
||||
@@ -172,6 +178,6 @@ public class FaultTolerantRedisCluster {
|
||||
pubSubConnections.add(pubSubConnection);
|
||||
|
||||
return new FaultTolerantPubSubConnection<>(name, pubSubConnection, circuitBreaker, retry, topologyChangedEventRetry,
|
||||
Schedulers.newSingle(name + "-redisPubSubEvents"));
|
||||
Schedulers.newSingle(name + "-redisPubSubEvents", true));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.redis;
|
||||
|
||||
import io.lettuce.core.RedisURI;
|
||||
import java.time.Duration;
|
||||
|
||||
public class RedisUriUtil {
|
||||
|
||||
public static RedisURI createRedisUriWithTimeout(final String uri, final Duration timeout) {
|
||||
final RedisURI redisUri = RedisURI.create(uri);
|
||||
// for synchronous commands and the initial connection
|
||||
redisUri.setTimeout(timeout);
|
||||
return redisUri;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -5,15 +5,14 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.s3;
|
||||
|
||||
import com.amazonaws.util.Base16Lower;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.HexFormat;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
public class PolicySigner {
|
||||
|
||||
@@ -43,7 +42,7 @@ public class PolicySigner {
|
||||
|
||||
mac.init(new SecretKeySpec(signingKey, "HmacSHA256"));
|
||||
|
||||
return Base16Lower.encodeAsString(mac.doFinal(policy.getBytes("UTF-8")));
|
||||
return HexFormat.of().formatHex(mac.doFinal(policy.getBytes("UTF-8")));
|
||||
} catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
|
||||
+32
-27
@@ -18,6 +18,7 @@ import java.time.Duration;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureBackupServiceConfiguration;
|
||||
@@ -29,37 +30,41 @@ import org.whispersystems.textsecuregcm.util.HttpUtils;
|
||||
*/
|
||||
public class SecureBackupClient {
|
||||
|
||||
private final ExternalServiceCredentialsGenerator secureBackupCredentialsGenerator;
|
||||
private final URI deleteUri;
|
||||
private final FaultTolerantHttpClient httpClient;
|
||||
private final ExternalServiceCredentialsGenerator secureBackupCredentialsGenerator;
|
||||
private final URI deleteUri;
|
||||
private final FaultTolerantHttpClient httpClient;
|
||||
|
||||
@VisibleForTesting
|
||||
static final String DELETE_PATH = "/v1/backup";
|
||||
@VisibleForTesting
|
||||
static final String DELETE_PATH = "/v1/backup";
|
||||
|
||||
public SecureBackupClient(final ExternalServiceCredentialsGenerator secureBackupCredentialsGenerator, final Executor executor, final SecureBackupServiceConfiguration configuration) throws CertificateException {
|
||||
this.secureBackupCredentialsGenerator = secureBackupCredentialsGenerator;
|
||||
this.deleteUri = URI.create(configuration.getUri()).resolve(DELETE_PATH);
|
||||
this.httpClient = FaultTolerantHttpClient.newBuilder()
|
||||
.withCircuitBreaker(configuration.getCircuitBreakerConfiguration())
|
||||
.withRetry(configuration.getRetryConfiguration())
|
||||
.withVersion(HttpClient.Version.HTTP_1_1)
|
||||
.withConnectTimeout(Duration.ofSeconds(10))
|
||||
.withRedirect(HttpClient.Redirect.NEVER)
|
||||
.withExecutor(executor)
|
||||
.withName("secure-backup")
|
||||
.withSecurityProtocol(FaultTolerantHttpClient.SECURITY_PROTOCOL_TLS_1_2)
|
||||
.withTrustedServerCertificates(configuration.getBackupCaCertificates().toArray(new String[0]))
|
||||
.build();
|
||||
}
|
||||
public SecureBackupClient(final ExternalServiceCredentialsGenerator secureBackupCredentialsGenerator,
|
||||
final Executor executor, final
|
||||
ScheduledExecutorService retryExecutor, final SecureBackupServiceConfiguration configuration)
|
||||
throws CertificateException {
|
||||
this.secureBackupCredentialsGenerator = secureBackupCredentialsGenerator;
|
||||
this.deleteUri = URI.create(configuration.getUri()).resolve(DELETE_PATH);
|
||||
this.httpClient = FaultTolerantHttpClient.newBuilder()
|
||||
.withCircuitBreaker(configuration.getCircuitBreakerConfiguration())
|
||||
.withRetry(configuration.getRetryConfiguration())
|
||||
.withRetryExecutor(retryExecutor)
|
||||
.withVersion(HttpClient.Version.HTTP_1_1)
|
||||
.withConnectTimeout(Duration.ofSeconds(10))
|
||||
.withRedirect(HttpClient.Redirect.NEVER)
|
||||
.withExecutor(executor)
|
||||
.withName("secure-backup")
|
||||
.withSecurityProtocol(FaultTolerantHttpClient.SECURITY_PROTOCOL_TLS_1_2)
|
||||
.withTrustedServerCertificates(configuration.getBackupCaCertificates().toArray(new String[0]))
|
||||
.build();
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> deleteBackups(final UUID accountUuid) {
|
||||
final ExternalServiceCredentials credentials = secureBackupCredentialsGenerator.generateForUuid(accountUuid);
|
||||
public CompletableFuture<Void> deleteBackups(final UUID accountUuid) {
|
||||
final ExternalServiceCredentials credentials = secureBackupCredentialsGenerator.generateForUuid(accountUuid);
|
||||
|
||||
final HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(deleteUri)
|
||||
.DELETE()
|
||||
.header(HttpHeaders.AUTHORIZATION, basicAuthHeader(credentials))
|
||||
.build();
|
||||
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())) {
|
||||
|
||||
+32
-27
@@ -18,6 +18,7 @@ import java.time.Duration;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureStorageServiceConfiguration;
|
||||
@@ -29,37 +30,41 @@ import org.whispersystems.textsecuregcm.util.HttpUtils;
|
||||
*/
|
||||
public class SecureStorageClient {
|
||||
|
||||
private final ExternalServiceCredentialsGenerator storageServiceCredentialsGenerator;
|
||||
private final URI deleteUri;
|
||||
private final FaultTolerantHttpClient httpClient;
|
||||
private final ExternalServiceCredentialsGenerator storageServiceCredentialsGenerator;
|
||||
private final URI deleteUri;
|
||||
private final FaultTolerantHttpClient httpClient;
|
||||
|
||||
@VisibleForTesting
|
||||
static final String DELETE_PATH = "/v1/storage";
|
||||
@VisibleForTesting
|
||||
static final String DELETE_PATH = "/v1/storage";
|
||||
|
||||
public SecureStorageClient(final ExternalServiceCredentialsGenerator storageServiceCredentialsGenerator, final Executor executor, final SecureStorageServiceConfiguration configuration) throws CertificateException {
|
||||
this.storageServiceCredentialsGenerator = storageServiceCredentialsGenerator;
|
||||
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-storage")
|
||||
.withSecurityProtocol(FaultTolerantHttpClient.SECURITY_PROTOCOL_TLS_1_3)
|
||||
.withTrustedServerCertificates(configuration.storageCaCertificates().toArray(new String[0]))
|
||||
.build();
|
||||
}
|
||||
public SecureStorageClient(final ExternalServiceCredentialsGenerator storageServiceCredentialsGenerator,
|
||||
final Executor executor, final
|
||||
ScheduledExecutorService retryExecutor, final SecureStorageServiceConfiguration configuration)
|
||||
throws CertificateException {
|
||||
this.storageServiceCredentialsGenerator = storageServiceCredentialsGenerator;
|
||||
this.deleteUri = URI.create(configuration.uri()).resolve(DELETE_PATH);
|
||||
this.httpClient = FaultTolerantHttpClient.newBuilder()
|
||||
.withCircuitBreaker(configuration.circuitBreaker())
|
||||
.withRetry(configuration.retry())
|
||||
.withRetryExecutor(retryExecutor)
|
||||
.withVersion(HttpClient.Version.HTTP_1_1)
|
||||
.withConnectTimeout(Duration.ofSeconds(10))
|
||||
.withRedirect(HttpClient.Redirect.NEVER)
|
||||
.withExecutor(executor)
|
||||
.withName("secure-storage")
|
||||
.withSecurityProtocol(FaultTolerantHttpClient.SECURITY_PROTOCOL_TLS_1_3)
|
||||
.withTrustedServerCertificates(configuration.storageCaCertificates().toArray(new String[0]))
|
||||
.build();
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> deleteStoredData(final UUID accountUuid) {
|
||||
final ExternalServiceCredentials credentials = storageServiceCredentialsGenerator.generateForUuid(accountUuid);
|
||||
public CompletableFuture<Void> deleteStoredData(final UUID accountUuid) {
|
||||
final ExternalServiceCredentials credentials = storageServiceCredentialsGenerator.generateForUuid(accountUuid);
|
||||
|
||||
final HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(deleteUri)
|
||||
.DELETE()
|
||||
.header(HttpHeaders.AUTHORIZATION, basicAuthHeader(credentials))
|
||||
.build();
|
||||
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())) {
|
||||
|
||||
+4
-1
@@ -18,6 +18,7 @@ import java.time.Duration;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureValueRecovery2Configuration;
|
||||
@@ -37,13 +38,15 @@ public class SecureValueRecovery2Client {
|
||||
static final String DELETE_PATH = "/v1/delete";
|
||||
|
||||
public SecureValueRecovery2Client(final ExternalServiceCredentialsGenerator secureValueRecoveryCredentialsGenerator,
|
||||
final Executor executor, final SecureValueRecovery2Configuration configuration)
|
||||
final Executor executor, final ScheduledExecutorService retryExecutor,
|
||||
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())
|
||||
.withRetryExecutor(retryExecutor)
|
||||
.withVersion(HttpClient.Version.HTTP_1_1)
|
||||
.withConnectTimeout(Duration.ofSeconds(10))
|
||||
.withRedirect(HttpClient.Redirect.NEVER)
|
||||
|
||||
+18
-129
@@ -9,21 +9,15 @@ import static com.codahale.metrics.MetricRegistry.name;
|
||||
import com.codahale.metrics.MetricRegistry;
|
||||
import com.codahale.metrics.SharedMetricRegistries;
|
||||
import com.codahale.metrics.Timer;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
public class AccountDatabaseCrawler implements Managed, Runnable {
|
||||
public class AccountDatabaseCrawler {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(AccountDatabaseCrawler.class);
|
||||
private static final MetricRegistry metricRegistry = SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME);
|
||||
@@ -32,7 +26,6 @@ public class AccountDatabaseCrawler implements Managed, Runnable {
|
||||
name(AccountDatabaseCrawler.class, "processChunk"));
|
||||
|
||||
private static final long WORKER_TTL_MS = 120_000L;
|
||||
private static final long CHUNK_INTERVAL_MILLIS = Duration.ofSeconds(2).toMillis();
|
||||
|
||||
private final String name;
|
||||
private final AccountsManager accounts;
|
||||
@@ -41,58 +34,17 @@ public class AccountDatabaseCrawler implements Managed, Runnable {
|
||||
private final AccountDatabaseCrawlerCache cache;
|
||||
private final List<AccountDatabaseCrawlerListener> listeners;
|
||||
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
|
||||
private AtomicBoolean running = new AtomicBoolean(false);
|
||||
private boolean finished;
|
||||
|
||||
public AccountDatabaseCrawler(final String name,
|
||||
AccountsManager accounts,
|
||||
AccountDatabaseCrawlerCache cache,
|
||||
List<AccountDatabaseCrawlerListener> listeners,
|
||||
int chunkSize,
|
||||
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
int chunkSize) {
|
||||
this.name = name;
|
||||
this.accounts = accounts;
|
||||
this.chunkSize = chunkSize;
|
||||
this.workerId = UUID.randomUUID().toString();
|
||||
this.cache = cache;
|
||||
this.listeners = listeners;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void start() {
|
||||
running.set(true);
|
||||
new Thread(this).start();
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void stop() {
|
||||
running.set(false);
|
||||
notifyAll();
|
||||
while (!finished) {
|
||||
Util.wait(this);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
|
||||
while (running.get()) {
|
||||
try {
|
||||
doPeriodicWork();
|
||||
sleepWhileRunning(CHUNK_INTERVAL_MILLIS);
|
||||
} catch (Throwable t) {
|
||||
logger.warn("{}: error in database crawl: {}: {}", name, t.getClass().getSimpleName(), t.getMessage(), t);
|
||||
Util.sleep(10000);
|
||||
}
|
||||
}
|
||||
|
||||
synchronized (this) {
|
||||
finished = true;
|
||||
notifyAll();
|
||||
}
|
||||
}
|
||||
|
||||
public void crawlAllAccounts() {
|
||||
@@ -101,7 +53,7 @@ public class AccountDatabaseCrawler implements Managed, Runnable {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Optional<UUID> fromUuid = cache.getLastUuid();
|
||||
Optional<UUID> fromUuid = getLastUuid();
|
||||
|
||||
if (fromUuid.isEmpty()) {
|
||||
logger.info("{}: Started crawl", name);
|
||||
@@ -110,83 +62,26 @@ public class AccountDatabaseCrawler implements Managed, Runnable {
|
||||
logger.info("{}: Resuming crawl", name);
|
||||
}
|
||||
|
||||
try {
|
||||
AccountCrawlChunk chunkAccounts;
|
||||
do {
|
||||
if (!dynamicConfigurationManager.getConfiguration().getAccountDatabaseCrawlerConfiguration()
|
||||
.crawlAllEnabled()) {
|
||||
logger.warn("Exiting crawl - not enabled by dynamic configuration");
|
||||
return;
|
||||
}
|
||||
try (Timer.Context timer = processChunkTimer.time()) {
|
||||
logger.debug("{}: Processing chunk", name);
|
||||
chunkAccounts = readChunk(fromUuid, chunkSize);
|
||||
AccountCrawlChunk chunkAccounts;
|
||||
do {
|
||||
try (Timer.Context timer = processChunkTimer.time()) {
|
||||
logger.debug("{}: Processing chunk", name);
|
||||
chunkAccounts = readChunk(fromUuid, chunkSize);
|
||||
|
||||
for (AccountDatabaseCrawlerListener listener : listeners) {
|
||||
listener.timeAndProcessCrawlChunk(fromUuid, chunkAccounts.getAccounts());
|
||||
}
|
||||
fromUuid = chunkAccounts.getLastUuid();
|
||||
cacheLastUuid(fromUuid);
|
||||
}
|
||||
|
||||
} while (!chunkAccounts.getAccounts().isEmpty());
|
||||
|
||||
logger.info("{}: Finished crawl", name);
|
||||
listeners.forEach(AccountDatabaseCrawlerListener::onCrawlEnd);
|
||||
|
||||
} catch (AccountDatabaseCrawlerRestartException e) {
|
||||
logger.warn("Crawl stopped", e);
|
||||
}
|
||||
|
||||
} finally {
|
||||
cache.releaseActiveWork(workerId);
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public void doPeriodicWork() {
|
||||
if (!dynamicConfigurationManager.getConfiguration().getAccountDatabaseCrawlerConfiguration()
|
||||
.periodicWorkEnabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (cache.claimActiveWork(workerId, WORKER_TTL_MS)) {
|
||||
try {
|
||||
processChunk();
|
||||
} finally {
|
||||
cache.releaseActiveWork(workerId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void processChunk() {
|
||||
|
||||
try (Timer.Context timer = processChunkTimer.time()) {
|
||||
|
||||
final Optional<UUID> fromUuid = getLastUuid();
|
||||
|
||||
if (fromUuid.isEmpty()) {
|
||||
logger.info("{}: Started crawl", name);
|
||||
listeners.forEach(AccountDatabaseCrawlerListener::onCrawlStart);
|
||||
}
|
||||
|
||||
final AccountCrawlChunk chunkAccounts = readChunk(fromUuid, chunkSize);
|
||||
|
||||
if (chunkAccounts.getAccounts().isEmpty()) {
|
||||
logger.info("{}: Finished crawl", name);
|
||||
listeners.forEach(AccountDatabaseCrawlerListener::onCrawlEnd);
|
||||
cacheLastUuid(Optional.empty());
|
||||
} else {
|
||||
logger.debug("{}: Processing chunk", name);
|
||||
try {
|
||||
for (AccountDatabaseCrawlerListener listener : listeners) {
|
||||
listener.timeAndProcessCrawlChunk(fromUuid, chunkAccounts.getAccounts());
|
||||
}
|
||||
cacheLastUuid(chunkAccounts.getLastUuid());
|
||||
} catch (AccountDatabaseCrawlerRestartException e) {
|
||||
cacheLastUuid(Optional.empty());
|
||||
fromUuid = chunkAccounts.getLastUuid();
|
||||
cacheLastUuid(fromUuid);
|
||||
}
|
||||
}
|
||||
|
||||
} while (!chunkAccounts.getAccounts().isEmpty());
|
||||
|
||||
logger.info("{}: Finished crawl", name);
|
||||
listeners.forEach(AccountDatabaseCrawlerListener::onCrawlEnd);
|
||||
|
||||
} finally {
|
||||
cache.releaseActiveWork(workerId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -213,10 +108,4 @@ public class AccountDatabaseCrawler implements Managed, Runnable {
|
||||
cache.setLastUuid(lastUuid);
|
||||
}
|
||||
|
||||
private synchronized void sleepWhileRunning(long delayMs) {
|
||||
if (running.get()) {
|
||||
Util.wait(this, delayMs);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+3
-3
@@ -16,19 +16,19 @@ import org.whispersystems.textsecuregcm.util.Constants;
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
public abstract class AccountDatabaseCrawlerListener {
|
||||
|
||||
private Timer processChunkTimer;
|
||||
private final Timer processChunkTimer;
|
||||
|
||||
abstract public void onCrawlStart();
|
||||
|
||||
abstract public void onCrawlEnd();
|
||||
|
||||
abstract protected void onCrawlChunk(Optional<UUID> fromUuid, List<Account> chunkAccounts) throws AccountDatabaseCrawlerRestartException;
|
||||
abstract protected void onCrawlChunk(Optional<UUID> fromUuid, List<Account> chunkAccounts);
|
||||
|
||||
public AccountDatabaseCrawlerListener() {
|
||||
processChunkTimer = SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME).timer(name(AccountDatabaseCrawlerListener.class, "processChunk", getClass().getSimpleName()));
|
||||
}
|
||||
|
||||
public void timeAndProcessCrawlChunk(Optional<UUID> fromUuid, List<Account> chunkAccounts) throws AccountDatabaseCrawlerRestartException {
|
||||
public void timeAndProcessCrawlChunk(Optional<UUID> fromUuid, List<Account> chunkAccounts) {
|
||||
try (Timer.Context timer = processChunkTimer.time()) {
|
||||
onCrawlChunk(fromUuid, chunkAccounts);
|
||||
}
|
||||
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
public class AccountDatabaseCrawlerRestartException extends Exception {
|
||||
public AccountDatabaseCrawlerRestartException(String s) {
|
||||
super(s);
|
||||
}
|
||||
|
||||
public AccountDatabaseCrawlerRestartException(Exception e) {
|
||||
super(e);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -1,7 +1,6 @@
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.amazonaws.services.dynamodbv2.AcquireLockOptions;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBLockClient;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBLockClientOptions;
|
||||
import com.amazonaws.services.dynamodbv2.LockItem;
|
||||
@@ -10,12 +9,13 @@ import com.google.common.annotations.VisibleForTesting;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
|
||||
public class AccountLockManager {
|
||||
|
||||
private final AmazonDynamoDBLockClient lockClient;
|
||||
|
||||
public AccountLockManager(final AmazonDynamoDB lockDynamoDb, final String lockTableName) {
|
||||
public AccountLockManager(final DynamoDbClient lockDynamoDb, final String lockTableName) {
|
||||
this(new AmazonDynamoDBLockClient(
|
||||
AmazonDynamoDBLockClientOptions.builder(lockDynamoDb, lockTableName)
|
||||
.withPartitionKeyName(DeletedAccounts.KEY_ACCOUNT_E164)
|
||||
|
||||
@@ -36,6 +36,7 @@ import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import reactor.core.publisher.Flux;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
@@ -677,6 +678,23 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
}));
|
||||
}
|
||||
|
||||
Flux<Account> getAll(final int segments) {
|
||||
if (segments < 1) {
|
||||
throw new IllegalArgumentException("Total number of segments must be positive");
|
||||
}
|
||||
|
||||
return Flux.merge(
|
||||
Flux.range(0, segments)
|
||||
.map(segment -> asyncClient.scanPaginator(ScanRequest.builder()
|
||||
.tableName(accountsTableName)
|
||||
.consistentRead(true)
|
||||
.segment(segment)
|
||||
.totalSegments(segments)
|
||||
.build())
|
||||
.items()
|
||||
.map(Accounts::fromItem)));
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
public AccountCrawlChunk getAllFrom(final UUID from, final int maxCount) {
|
||||
final ScanRequest.Builder scanRequestBuilder = ScanRequest.builder()
|
||||
|
||||
+12
-1
@@ -58,6 +58,7 @@ import org.whispersystems.textsecuregcm.util.Constants;
|
||||
import org.whispersystems.textsecuregcm.util.DestinationDeviceValidator;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
public class AccountsManager {
|
||||
|
||||
@@ -311,7 +312,10 @@ public class AccountsManager {
|
||||
|
||||
numberChangedAccount = updateWithRetries(
|
||||
account,
|
||||
a -> { setPniKeys(account, pniIdentityKey, pniSignedPreKeys, pniRegistrationIds); return true; },
|
||||
a -> {
|
||||
setPniKeys(account, pniIdentityKey, pniSignedPreKeys, pniRegistrationIds);
|
||||
return true;
|
||||
},
|
||||
a -> accounts.changeNumber(a, targetNumber, phoneNumberIdentifier),
|
||||
() -> accounts.getByAccountIdentifier(uuid).orElseThrow(),
|
||||
AccountChangeValidator.NUMBER_CHANGE_VALIDATOR);
|
||||
@@ -321,6 +325,8 @@ public class AccountsManager {
|
||||
keysManager.delete(phoneNumberIdentifier);
|
||||
keysManager.delete(originalPhoneNumberIdentifier);
|
||||
|
||||
keysManager.storeEcSignedPreKeys(phoneNumberIdentifier, pniSignedPreKeys);
|
||||
|
||||
if (pniPqLastResortPreKeys != null) {
|
||||
keysManager.storePqLastResort(
|
||||
phoneNumberIdentifier,
|
||||
@@ -361,6 +367,7 @@ public class AccountsManager {
|
||||
|
||||
final List<Long> pqEnabledDeviceIDs = keysManager.getPqEnabledDevices(pni);
|
||||
keysManager.delete(pni);
|
||||
keysManager.storeEcSignedPreKeys(pni, pniSignedPreKeys);
|
||||
if (pniPqLastResortPreKeys != null) {
|
||||
keysManager.storePqLastResort(pni, pqEnabledDeviceIDs.stream().collect(Collectors.toMap(Function.identity(), pniPqLastResortPreKeys::get)));
|
||||
}
|
||||
@@ -714,6 +721,10 @@ public class AccountsManager {
|
||||
return accounts.getAllFrom(uuid, length);
|
||||
}
|
||||
|
||||
public Flux<Account> streamAllFromDynamo(final int segments) {
|
||||
return accounts.getAll(segments);
|
||||
}
|
||||
|
||||
public void delete(final Account account, final DeletionReason deletionReason) throws InterruptedException {
|
||||
try (final Timer.Context ignored = deleteTimer.time()) {
|
||||
accountLockManager.withLock(List.of(account.getNumber()), () -> {
|
||||
|
||||
@@ -13,34 +13,44 @@ import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.ECPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
|
||||
public class KeysManager {
|
||||
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
|
||||
private final SingleUseECPreKeyStore ecPreKeys;
|
||||
private final SingleUseKEMPreKeyStore pqPreKeys;
|
||||
private final RepeatedUseECSignedPreKeyStore ecSignedPreKeys;
|
||||
private final RepeatedUseKEMSignedPreKeyStore pqLastResortKeys;
|
||||
|
||||
public KeysManager(
|
||||
final DynamoDbAsyncClient dynamoDbAsyncClient,
|
||||
final String ecTableName,
|
||||
final String pqTableName,
|
||||
final String pqLastResortTableName) {
|
||||
final String ecSignedPreKeysTableName,
|
||||
final String pqLastResortTableName,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
this.ecPreKeys = new SingleUseECPreKeyStore(dynamoDbAsyncClient, ecTableName);
|
||||
this.pqPreKeys = new SingleUseKEMPreKeyStore(dynamoDbAsyncClient, pqTableName);
|
||||
this.ecSignedPreKeys = new RepeatedUseECSignedPreKeyStore(dynamoDbAsyncClient, ecSignedPreKeysTableName);
|
||||
this.pqLastResortKeys = new RepeatedUseKEMSignedPreKeyStore(dynamoDbAsyncClient, pqLastResortTableName);
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
}
|
||||
|
||||
public void store(final UUID identifier, final long deviceId, final List<ECPreKey> keys) {
|
||||
store(identifier, deviceId, keys, null, null);
|
||||
store(identifier, deviceId, keys, null, null, null);
|
||||
}
|
||||
|
||||
public void store(
|
||||
final UUID identifier, final long deviceId,
|
||||
@Nullable final List<ECPreKey> ecKeys,
|
||||
@Nullable final List<KEMSignedPreKey> pqKeys,
|
||||
@Nullable final ECSignedPreKey ecSignedPreKey,
|
||||
@Nullable final KEMSignedPreKey pqLastResortKey) {
|
||||
|
||||
final List<CompletableFuture<Void>> storeFutures = new ArrayList<>();
|
||||
@@ -53,6 +63,10 @@ public class KeysManager {
|
||||
storeFutures.add(pqPreKeys.store(identifier, deviceId, pqKeys));
|
||||
}
|
||||
|
||||
if (ecSignedPreKey != null && dynamicConfigurationManager.getConfiguration().getEcPreKeyMigrationConfiguration().storeEcSignedPreKeys()) {
|
||||
storeFutures.add(ecSignedPreKeys.store(identifier, deviceId, ecSignedPreKey));
|
||||
}
|
||||
|
||||
if (pqLastResortKey != null) {
|
||||
storeFutures.add(pqLastResortKeys.store(identifier, deviceId, pqLastResortKey));
|
||||
}
|
||||
@@ -60,6 +74,16 @@ public class KeysManager {
|
||||
CompletableFuture.allOf(storeFutures.toArray(new CompletableFuture[0])).join();
|
||||
}
|
||||
|
||||
public void storeEcSignedPreKeys(final UUID identifier, final Map<Long, ECSignedPreKey> keys) {
|
||||
if (dynamicConfigurationManager.getConfiguration().getEcPreKeyMigrationConfiguration().storeEcSignedPreKeys()) {
|
||||
ecSignedPreKeys.store(identifier, keys).join();
|
||||
}
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> storeEcSignedPreKeyIfAbsent(final UUID identifier, final long deviceId, final ECSignedPreKey signedPreKey) {
|
||||
return ecSignedPreKeys.storeIfAbsent(identifier, deviceId, signedPreKey);
|
||||
}
|
||||
|
||||
public void storePqLastResort(final UUID identifier, final Map<Long, KEMSignedPreKey> keys) {
|
||||
pqLastResortKeys.store(identifier, keys).join();
|
||||
}
|
||||
@@ -80,6 +104,10 @@ public class KeysManager {
|
||||
return pqLastResortKeys.find(identifier, deviceId).join();
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<ECSignedPreKey>> getEcSignedPreKey(final UUID identifier, final long deviceId) {
|
||||
return ecSignedPreKeys.find(identifier, deviceId);
|
||||
}
|
||||
|
||||
public List<Long> getPqEnabledDevices(final UUID identifier) {
|
||||
return pqLastResortKeys.getDeviceIdsWithKeys(identifier).collectList().block();
|
||||
}
|
||||
@@ -96,6 +124,9 @@ public class KeysManager {
|
||||
CompletableFuture.allOf(
|
||||
ecPreKeys.delete(accountUuid),
|
||||
pqPreKeys.delete(accountUuid),
|
||||
dynamicConfigurationManager.getConfiguration().getEcPreKeyMigrationConfiguration().deleteEcSignedPreKeys()
|
||||
? ecSignedPreKeys.delete(accountUuid)
|
||||
: CompletableFuture.completedFuture(null),
|
||||
pqLastResortKeys.delete(accountUuid))
|
||||
.join();
|
||||
}
|
||||
@@ -104,6 +135,9 @@ public class KeysManager {
|
||||
CompletableFuture.allOf(
|
||||
ecPreKeys.delete(accountUuid, deviceId),
|
||||
pqPreKeys.delete(accountUuid, deviceId),
|
||||
dynamicConfigurationManager.getConfiguration().getEcPreKeyMigrationConfiguration().deleteEcSignedPreKeys()
|
||||
? ecSignedPreKeys.delete(accountUuid, deviceId)
|
||||
: CompletableFuture.completedFuture(null),
|
||||
pqLastResortKeys.delete(accountUuid, deviceId))
|
||||
.join();
|
||||
}
|
||||
|
||||
+5
-19
@@ -22,7 +22,6 @@ import java.util.UUID;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicMessagePersisterConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
@@ -52,8 +51,6 @@ public class MessagePersister implements Managed {
|
||||
|
||||
private static final long EXCEPTION_PAUSE_MILLIS = Duration.ofSeconds(3).toMillis();
|
||||
|
||||
private static final int DEFAULT_WORKER_THREAD_COUNT = 4;
|
||||
|
||||
private static final int CONSECUTIVE_EMPTY_CACHE_REMOVAL_LIMIT = 3;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessagePersister.class);
|
||||
@@ -62,19 +59,19 @@ public class MessagePersister implements Managed {
|
||||
final AccountsManager accountsManager,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final Duration persistDelay,
|
||||
final Optional<Integer> dedicatedProcessWorkerThreadCount) {
|
||||
final int dedicatedProcessWorkerThreadCount) {
|
||||
this.messagesCache = messagesCache;
|
||||
this.messagesManager = messagesManager;
|
||||
this.accountsManager = accountsManager;
|
||||
this.persistDelay = persistDelay;
|
||||
this.workerThreads = dedicatedProcessWorkerThreadCount.map(Thread[]::new)
|
||||
.orElseGet(() -> new Thread[DEFAULT_WORKER_THREAD_COUNT]);
|
||||
this.dedicatedProcess = dedicatedProcessWorkerThreadCount.isPresent();
|
||||
this.workerThreads = new Thread[dedicatedProcessWorkerThreadCount];
|
||||
this.dedicatedProcess = true;
|
||||
|
||||
for (int i = 0; i < workerThreads.length; i++) {
|
||||
workerThreads[i] = new Thread(() -> {
|
||||
while (running) {
|
||||
if (enabled(dynamicConfigurationManager)) {
|
||||
if (dynamicConfigurationManager.getConfiguration().getMessagePersisterConfiguration()
|
||||
.isPersistenceEnabled()) {
|
||||
try {
|
||||
final int queuesPersisted = persistNextQueues(Instant.now());
|
||||
queueCountHistogram.update(queuesPersisted);
|
||||
@@ -94,17 +91,6 @@ public class MessagePersister implements Managed {
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
boolean enabled(final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
final DynamicMessagePersisterConfiguration messagePersisterConfiguration = dynamicConfigurationManager.getConfiguration()
|
||||
.getMessagePersisterConfiguration();
|
||||
if (dedicatedProcess) {
|
||||
return messagePersisterConfiguration.isDedicatedProcessEnabled();
|
||||
}
|
||||
|
||||
return messagePersisterConfiguration.isServerPersistenceEnabled();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
Duration getPersistDelay() {
|
||||
return persistDelay;
|
||||
|
||||
+75
-43
@@ -13,20 +13,35 @@ import com.codahale.metrics.SharedMetricRegistries;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
public class PushFeedbackProcessor extends AccountDatabaseCrawlerListener {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(PushFeedbackProcessor.class);
|
||||
|
||||
private final MetricRegistry metricRegistry = SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME);
|
||||
private final Meter expired = metricRegistry.meter(name(getClass(), "unregistered", "expired"));
|
||||
private final Meter recovered = metricRegistry.meter(name(getClass(), "unregistered", "recovered"));
|
||||
private final Meter expired = metricRegistry.meter(name(getClass(), "unregistered", "expired"));
|
||||
private final Meter recovered = metricRegistry.meter(name(getClass(), "unregistered", "recovered"));
|
||||
|
||||
private static final Counter UPDATED_ACCOUNT_COUNTER = Metrics.counter(
|
||||
MetricsUtil.name(PushFeedbackProcessor.class, "updatedAccounts"));
|
||||
|
||||
|
||||
private final AccountsManager accountsManager;
|
||||
private final ExecutorService updateExecutor;
|
||||
|
||||
public PushFeedbackProcessor(AccountsManager accountsManager) {
|
||||
public PushFeedbackProcessor(AccountsManager accountsManager, ExecutorService updateExecutor) {
|
||||
this.accountsManager = accountsManager;
|
||||
this.updateExecutor = updateExecutor;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -38,51 +53,68 @@ public class PushFeedbackProcessor extends AccountDatabaseCrawlerListener {
|
||||
|
||||
@Override
|
||||
protected void onCrawlChunk(Optional<UUID> fromUuid, List<Account> chunkAccounts) {
|
||||
for (Account account : chunkAccounts) {
|
||||
boolean update = false;
|
||||
|
||||
for (Device device : account.getDevices()) {
|
||||
if (deviceNeedsUpdate(device)) {
|
||||
if (deviceExpired(device)) {
|
||||
if (device.isEnabled()) {
|
||||
expired.mark();
|
||||
update = true;
|
||||
}
|
||||
} else {
|
||||
recovered.mark();
|
||||
update = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
final List<CompletableFuture<Void>> updateFutures = chunkAccounts.stream()
|
||||
.filter(account -> {
|
||||
boolean update = false;
|
||||
|
||||
if (update) {
|
||||
// fetch a new version, since the chunk is shared and implicitly read-only
|
||||
accountsManager.getByAccountIdentifier(account.getUuid()).ifPresent(accountToUpdate -> {
|
||||
accountsManager.update(accountToUpdate, a -> {
|
||||
for (Device device : a.getDevices()) {
|
||||
if (deviceNeedsUpdate(device)) {
|
||||
if (deviceExpired(device)) {
|
||||
if (!Util.isEmpty(device.getApnId())) {
|
||||
if (device.getId() == 1) {
|
||||
device.setUserAgent("OWI");
|
||||
} else {
|
||||
device.setUserAgent("OWP");
|
||||
}
|
||||
} else if (!Util.isEmpty(device.getGcmId())) {
|
||||
device.setUserAgent("OWA");
|
||||
}
|
||||
device.setGcmId(null);
|
||||
device.setApnId(null);
|
||||
device.setVoipApnId(null);
|
||||
device.setFetchesMessages(false);
|
||||
} else {
|
||||
device.setUninstalledFeedbackTimestamp(0);
|
||||
for (Device device : account.getDevices()) {
|
||||
if (deviceNeedsUpdate(device)) {
|
||||
if (deviceExpired(device)) {
|
||||
if (device.isEnabled()) {
|
||||
expired.mark();
|
||||
update = true;
|
||||
}
|
||||
} else {
|
||||
recovered.mark();
|
||||
update = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return update;
|
||||
})
|
||||
.map(account -> CompletableFuture.runAsync(() -> {
|
||||
// fetch a new version, since the chunk is shared and implicitly read-only
|
||||
accountsManager.getByAccountIdentifier(account.getUuid()).ifPresent(accountToUpdate -> {
|
||||
accountsManager.update(accountToUpdate, a -> {
|
||||
for (Device device : a.getDevices()) {
|
||||
if (deviceNeedsUpdate(device)) {
|
||||
if (deviceExpired(device)) {
|
||||
if (!Util.isEmpty(device.getApnId())) {
|
||||
if (device.getId() == 1) {
|
||||
device.setUserAgent("OWI");
|
||||
} else {
|
||||
device.setUserAgent("OWP");
|
||||
}
|
||||
} else if (!Util.isEmpty(device.getGcmId())) {
|
||||
device.setUserAgent("OWA");
|
||||
}
|
||||
device.setGcmId(null);
|
||||
device.setApnId(null);
|
||||
device.setVoipApnId(null);
|
||||
device.setFetchesMessages(false);
|
||||
} else {
|
||||
device.setUninstalledFeedbackTimestamp(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}, updateExecutor)
|
||||
.whenComplete((ignored, throwable) -> {
|
||||
if (throwable != null) {
|
||||
log.warn("Failed to update account {}", account.getUuid(), throwable);
|
||||
} else {
|
||||
UPDATED_ACCOUNT_COUNTER.increment();
|
||||
}
|
||||
}))
|
||||
.toList();
|
||||
|
||||
try {
|
||||
CompletableFuture.allOf(updateFutures.toArray(new CompletableFuture[0])).join();
|
||||
} catch (final Exception e) {
|
||||
log.debug("Failed to update one or more accounts in chunk", e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.signal.libsignal.protocol.InvalidKeyException;
|
||||
import org.signal.libsignal.protocol.ecc.ECPublicKey;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
|
||||
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
|
||||
|
||||
public class RepeatedUseECSignedPreKeyStore extends RepeatedUseSignedPreKeyStore<ECSignedPreKey> {
|
||||
|
||||
private final DynamoDbAsyncClient dynamoDbAsyncClient;
|
||||
private final String tableName;
|
||||
|
||||
public RepeatedUseECSignedPreKeyStore(final DynamoDbAsyncClient dynamoDbAsyncClient, final String tableName) {
|
||||
super(dynamoDbAsyncClient, tableName);
|
||||
|
||||
this.dynamoDbAsyncClient = dynamoDbAsyncClient;
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Map<String, AttributeValue> getItemFromPreKey(final UUID accountUuid, final long deviceId, final ECSignedPreKey signedPreKey) {
|
||||
|
||||
return Map.of(
|
||||
KEY_ACCOUNT_UUID, getPartitionKey(accountUuid),
|
||||
KEY_DEVICE_ID, getSortKey(deviceId),
|
||||
ATTR_KEY_ID, AttributeValues.fromLong(signedPreKey.keyId()),
|
||||
ATTR_PUBLIC_KEY, AttributeValues.fromByteArray(signedPreKey.serializedPublicKey()),
|
||||
ATTR_SIGNATURE, AttributeValues.fromByteArray(signedPreKey.signature()));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ECSignedPreKey getPreKeyFromItem(final Map<String, AttributeValue> item) {
|
||||
try {
|
||||
return new ECSignedPreKey(
|
||||
Long.parseLong(item.get(ATTR_KEY_ID).n()),
|
||||
new ECPublicKey(item.get(ATTR_PUBLIC_KEY).b().asByteArray()),
|
||||
item.get(ATTR_SIGNATURE).b().asByteArray());
|
||||
} catch (final InvalidKeyException e) {
|
||||
// This should never happen since we're serializing keys directly from `ECPublicKey` instances on the way in
|
||||
throw new IllegalArgumentException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> storeIfAbsent(final UUID identifier, final long deviceId, final ECSignedPreKey signedPreKey) {
|
||||
return dynamoDbAsyncClient.putItem(PutItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.item(getItemFromPreKey(identifier, deviceId, signedPreKey))
|
||||
.conditionExpression("attribute_not_exists(#public_key)")
|
||||
.expressionAttributeNames(Map.of("#public_key", ATTR_PUBLIC_KEY))
|
||||
.build())
|
||||
.thenApply(ignored -> true)
|
||||
.exceptionally(throwable -> {
|
||||
if (ExceptionUtils.unwrap(throwable) instanceof ConditionalCheckFailedException) {
|
||||
return false;
|
||||
}
|
||||
|
||||
throw ExceptionUtils.wrap(throwable);
|
||||
});
|
||||
}
|
||||
}
|
||||
+11
-18
@@ -45,20 +45,12 @@ public abstract class RepeatedUseSignedPreKeyStore<K extends SignedPreKey<?>> {
|
||||
static final String ATTR_PUBLIC_KEY = "P";
|
||||
static final String ATTR_SIGNATURE = "S";
|
||||
|
||||
private static final Timer STORE_SINGLE_KEY_TIMER =
|
||||
Metrics.timer(MetricsUtil.name(RepeatedUseSignedPreKeyStore.class, "storeSingleKey"));
|
||||
private final Timer storeSingleKeyTimer = Metrics.timer(MetricsUtil.name(getClass(), "storeSingleKey"));
|
||||
private final Timer storeKeyBatchTimer = Metrics.timer(MetricsUtil.name(getClass(), "storeKeyBatch"));
|
||||
private final Timer deleteForDeviceTimer = Metrics.timer(MetricsUtil.name(getClass(), "deleteForDevice"));
|
||||
private final Timer deleteForAccountTimer = Metrics.timer(MetricsUtil.name(getClass(), "deleteForAccount"));
|
||||
|
||||
private static final Timer STORE_KEY_BATCH_TIMER =
|
||||
Metrics.timer(MetricsUtil.name(RepeatedUseSignedPreKeyStore.class, "storeKeyBatch"));
|
||||
|
||||
private static final Timer DELETE_FOR_DEVICE_TIMER =
|
||||
Metrics.timer(MetricsUtil.name(RepeatedUseSignedPreKeyStore.class, "deleteForDevice"));
|
||||
|
||||
private static final Timer DELETE_FOR_ACCOUNT_TIMER =
|
||||
Metrics.timer(MetricsUtil.name(RepeatedUseSignedPreKeyStore.class, "deleteForAccount"));
|
||||
|
||||
private static final String FIND_KEY_TIMER_NAME = MetricsUtil.name(RepeatedUseSignedPreKeyStore.class, "findKey");
|
||||
private static final String KEY_PRESENT_TAG_NAME = "keyPresent";
|
||||
private final String findKeyTimerName = MetricsUtil.name(getClass(), "findKey");
|
||||
|
||||
public RepeatedUseSignedPreKeyStore(final DynamoDbAsyncClient dynamoDbAsyncClient, final String tableName) {
|
||||
this.dynamoDbAsyncClient = dynamoDbAsyncClient;
|
||||
@@ -82,7 +74,7 @@ public abstract class RepeatedUseSignedPreKeyStore<K extends SignedPreKey<?>> {
|
||||
.tableName(tableName)
|
||||
.item(getItemFromPreKey(identifier, deviceId, signedPreKey))
|
||||
.build())
|
||||
.thenRun(() -> sample.stop(STORE_SINGLE_KEY_TIMER));
|
||||
.thenRun(() -> sample.stop(storeSingleKeyTimer));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -113,7 +105,7 @@ public abstract class RepeatedUseSignedPreKeyStore<K extends SignedPreKey<?>> {
|
||||
})
|
||||
.toList())
|
||||
.build())
|
||||
.thenRun(() -> sample.stop(STORE_KEY_BATCH_TIMER));
|
||||
.thenRun(() -> sample.stop(storeKeyBatchTimer));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -136,7 +128,8 @@ public abstract class RepeatedUseSignedPreKeyStore<K extends SignedPreKey<?>> {
|
||||
.thenApply(response -> response.hasItem() ? Optional.of(getPreKeyFromItem(response.item())) : Optional.empty());
|
||||
|
||||
findFuture.whenComplete((maybeSignedPreKey, throwable) ->
|
||||
sample.stop(Metrics.timer(FIND_KEY_TIMER_NAME, KEY_PRESENT_TAG_NAME, String.valueOf(maybeSignedPreKey != null && maybeSignedPreKey.isPresent()))));
|
||||
sample.stop(Metrics.timer(findKeyTimerName,
|
||||
"keyPresent", String.valueOf(maybeSignedPreKey != null && maybeSignedPreKey.isPresent()))));
|
||||
|
||||
return findFuture;
|
||||
}
|
||||
@@ -161,7 +154,7 @@ public abstract class RepeatedUseSignedPreKeyStore<K extends SignedPreKey<?>> {
|
||||
// Idiom: wait for everything to finish, but discard the results
|
||||
.reduce(0, (a, b) -> 0)
|
||||
.toFuture()
|
||||
.thenRun(() -> sample.stop(DELETE_FOR_ACCOUNT_TIMER));
|
||||
.thenRun(() -> sample.stop(deleteForAccountTimer));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -179,7 +172,7 @@ public abstract class RepeatedUseSignedPreKeyStore<K extends SignedPreKey<?>> {
|
||||
.tableName(tableName)
|
||||
.key(getPrimaryKey(identifier, deviceId))
|
||||
.build())
|
||||
.thenRun(() -> sample.stop(DELETE_FOR_DEVICE_TIMER));
|
||||
.thenRun(() -> sample.stop(deleteForDeviceTimer));
|
||||
}
|
||||
|
||||
public Flux<Long> getDeviceIdsWithKeys(final UUID identifier) {
|
||||
|
||||
+4
-1
@@ -32,6 +32,7 @@ import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.ws.rs.ClientErrorException;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
@@ -61,7 +62,8 @@ public class BraintreeManager implements SubscriptionProcessorManager {
|
||||
final Map<String, String> currenciesToMerchantAccounts,
|
||||
final String graphqlUri,
|
||||
final CircuitBreakerConfiguration circuitBreakerConfiguration,
|
||||
final Executor executor) {
|
||||
final Executor executor,
|
||||
final ScheduledExecutorService retryExecutor) {
|
||||
|
||||
this(new BraintreeGateway(braintreeEnvironment, braintreeMerchantId, braintreePublicKey,
|
||||
braintreePrivateKey),
|
||||
@@ -71,6 +73,7 @@ public class BraintreeManager implements SubscriptionProcessorManager {
|
||||
.withName("braintree-graphql")
|
||||
.withCircuitBreaker(circuitBreakerConfiguration)
|
||||
.withExecutor(executor)
|
||||
.withRetryExecutor(retryExecutor)
|
||||
.build(), graphqlUri, braintreePublicKey, braintreePrivateKey),
|
||||
executor);
|
||||
}
|
||||
|
||||
@@ -1,64 +1,63 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* Copyright 2013-2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.util.ua;
|
||||
|
||||
import com.vdurmont.semver4j.Semver;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
public class UserAgent {
|
||||
|
||||
private final ClientPlatform platform;
|
||||
private final Semver version;
|
||||
private final String additionalSpecifiers;
|
||||
private final ClientPlatform platform;
|
||||
private final Semver version;
|
||||
private final String additionalSpecifiers;
|
||||
|
||||
public UserAgent(final ClientPlatform platform, final Semver version) {
|
||||
this(platform, version, null);
|
||||
}
|
||||
public UserAgent(final ClientPlatform platform, final Semver version) {
|
||||
this(platform, version, null);
|
||||
}
|
||||
|
||||
public UserAgent(final ClientPlatform platform, final Semver version, final String additionalSpecifiers) {
|
||||
this.platform = platform;
|
||||
this.version = version;
|
||||
this.additionalSpecifiers = additionalSpecifiers;
|
||||
}
|
||||
public UserAgent(final ClientPlatform platform, final Semver version, final String additionalSpecifiers) {
|
||||
this.platform = platform;
|
||||
this.version = version;
|
||||
this.additionalSpecifiers = additionalSpecifiers;
|
||||
}
|
||||
|
||||
public ClientPlatform getPlatform() {
|
||||
return platform;
|
||||
}
|
||||
public ClientPlatform getPlatform() {
|
||||
return platform;
|
||||
}
|
||||
|
||||
public Semver getVersion() {
|
||||
return version;
|
||||
}
|
||||
public Semver getVersion() {
|
||||
return version;
|
||||
}
|
||||
|
||||
public Optional<String> getAdditionalSpecifiers() {
|
||||
return Optional.ofNullable(additionalSpecifiers);
|
||||
}
|
||||
public Optional<String> getAdditionalSpecifiers() {
|
||||
return Optional.ofNullable(additionalSpecifiers);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
final UserAgent userAgent = (UserAgent)o;
|
||||
return platform == userAgent.platform &&
|
||||
version.equals(userAgent.version) &&
|
||||
Objects.equals(additionalSpecifiers, userAgent.additionalSpecifiers);
|
||||
}
|
||||
@Override
|
||||
public boolean equals(final Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
final UserAgent userAgent = (UserAgent)o;
|
||||
return platform == userAgent.platform &&
|
||||
version.equals(userAgent.version) &&
|
||||
Objects.equals(additionalSpecifiers, userAgent.additionalSpecifiers);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(platform, version, additionalSpecifiers);
|
||||
}
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(platform, version, additionalSpecifiers);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "UserAgent{" +
|
||||
"platform=" + platform +
|
||||
", version=" + version +
|
||||
", additionalSpecifiers='" + additionalSpecifiers + '\'' +
|
||||
'}';
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "UserAgent{" +
|
||||
"platform=" + platform +
|
||||
", version=" + version +
|
||||
", additionalSpecifiers='" + additionalSpecifiers + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@@ -7,40 +7,47 @@ package org.whispersystems.textsecuregcm.util.ua;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.vdurmont.semver4j.Semver;
|
||||
import io.grpc.Context;
|
||||
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);
|
||||
public static final Context.Key<UserAgent> USER_AGENT_CONTEXT_KEY = Context.key("x-signal-user-agent");
|
||||
|
||||
public static UserAgent parseUserAgentString(final String userAgentString) throws UnrecognizedUserAgentException {
|
||||
if (StringUtils.isBlank(userAgentString)) {
|
||||
throw new UnrecognizedUserAgentException("User-Agent string is blank");
|
||||
}
|
||||
private static final Pattern STANDARD_UA_PATTERN = Pattern.compile("^Signal-(Android|Desktop|iOS)/([^ ]+)( (.+))?$", Pattern.CASE_INSENSITIVE);
|
||||
|
||||
try {
|
||||
final UserAgent standardUserAgent = parseStandardUserAgentString(userAgentString);
|
||||
|
||||
if (standardUserAgent != null) {
|
||||
return standardUserAgent;
|
||||
}
|
||||
} catch (final Exception e) {
|
||||
throw new UnrecognizedUserAgentException(e);
|
||||
}
|
||||
|
||||
throw new UnrecognizedUserAgentException();
|
||||
public static UserAgent parseUserAgentString(final String userAgentString) throws UnrecognizedUserAgentException {
|
||||
if (StringUtils.isBlank(userAgentString)) {
|
||||
throw new UnrecognizedUserAgentException("User-Agent string is blank");
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static UserAgent parseStandardUserAgentString(final String userAgentString) {
|
||||
final Matcher matcher = STANDARD_UA_PATTERN.matcher(userAgentString);
|
||||
try {
|
||||
final UserAgent standardUserAgent = parseStandardUserAgentString(userAgentString);
|
||||
|
||||
if (matcher.matches()) {
|
||||
return new UserAgent(ClientPlatform.valueOf(matcher.group(1).toUpperCase()), new Semver(matcher.group(2)), StringUtils.stripToNull(matcher.group(4)));
|
||||
}
|
||||
|
||||
return null;
|
||||
if (standardUserAgent != null) {
|
||||
return standardUserAgent;
|
||||
}
|
||||
} catch (final Exception e) {
|
||||
throw new UnrecognizedUserAgentException(e);
|
||||
}
|
||||
|
||||
throw new UnrecognizedUserAgentException();
|
||||
}
|
||||
|
||||
public static UserAgent userAgentFromGrpcContext() {
|
||||
return USER_AGENT_CONTEXT_KEY.get();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static UserAgent parseStandardUserAgentString(final String userAgentString) {
|
||||
final Matcher matcher = STANDARD_UA_PATTERN.matcher(userAgentString);
|
||||
|
||||
if (matcher.matches()) {
|
||||
return new UserAgent(ClientPlatform.valueOf(matcher.group(1).toUpperCase()), new Semver(matcher.group(2)), StringUtils.stripToNull(matcher.group(4)));
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+2
@@ -207,6 +207,8 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
.whenComplete((ignored, throwable) -> {
|
||||
if (throwable != null) {
|
||||
sendFailuresMeter.mark();
|
||||
} else {
|
||||
MessageMetrics.measureOutgoingMessageLatency(message.getServerTimestamp(), "websocket", client.getUserAgent());
|
||||
}
|
||||
}).thenCompose(response -> {
|
||||
final CompletableFuture<Void> result;
|
||||
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import io.dropwizard.Application;
|
||||
import io.dropwizard.cli.EnvironmentCommand;
|
||||
import io.dropwizard.setup.Environment;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.util.logging.UncaughtExceptionHandler;
|
||||
import reactor.core.publisher.Flux;
|
||||
import java.util.Objects;
|
||||
|
||||
public abstract class AbstractSinglePassCrawlAccountsCommand extends EnvironmentCommand<WhisperServerConfiguration> {
|
||||
|
||||
private CommandDependencies commandDependencies;
|
||||
|
||||
private static final String SEGMENT_COUNT = "segments";
|
||||
|
||||
public AbstractSinglePassCrawlAccountsCommand(final String name, final String description) {
|
||||
super(new Application<>() {
|
||||
@Override
|
||||
public void run(final WhisperServerConfiguration configuration, final Environment environment) {
|
||||
}
|
||||
}, name, description);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(final Subparser subparser) {
|
||||
super.configure(subparser);
|
||||
|
||||
subparser.addArgument("--segments")
|
||||
.type(Integer.class)
|
||||
.dest(SEGMENT_COUNT)
|
||||
.required(false)
|
||||
.setDefault(1)
|
||||
.help("The total number of segments for a DynamoDB scan");
|
||||
}
|
||||
|
||||
protected CommandDependencies getCommandDependencies() {
|
||||
return commandDependencies;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void run(final Environment environment, final Namespace namespace,
|
||||
final WhisperServerConfiguration configuration) throws Exception {
|
||||
|
||||
UncaughtExceptionHandler.register();
|
||||
|
||||
MetricsUtil.configureRegistries(configuration, environment);
|
||||
commandDependencies = CommandDependencies.build(getName(), environment, configuration);
|
||||
|
||||
final int segments = Objects.requireNonNull(namespace.getInt(SEGMENT_COUNT));
|
||||
crawlAccounts(commandDependencies.accountsManager().streamAllFromDynamo(segments));
|
||||
}
|
||||
|
||||
protected abstract void crawlAccounts(final Flux<Account> accounts);
|
||||
}
|
||||
+18
-22
@@ -7,9 +7,6 @@ package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.amazonaws.ClientConfiguration;
|
||||
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;
|
||||
@@ -21,6 +18,7 @@ import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
@@ -110,9 +108,13 @@ public class AssignUsernameCommand extends EnvironmentCommand<WhisperServerConfi
|
||||
ExecutorService messageDeletionExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "messageDeletion-%d")).maxThreads(4).build();
|
||||
ExecutorService secureValueRecoveryExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "secureValueRecoveryService-%d")).maxThreads(8).minThreads(1).build();
|
||||
.executorService(name(getClass(), "secureValueRecoveryService-%d")).maxThreads(1).minThreads(1).build();
|
||||
ExecutorService storageServiceExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "storageService-%d")).maxThreads(8).minThreads(1).build();
|
||||
.executorService(name(getClass(), "storageService-%d")).maxThreads(1).minThreads(1).build();
|
||||
ScheduledExecutorService secureValueRecoveryServiceRetryExecutor = environment.lifecycle()
|
||||
.scheduledExecutorService(name(getClass(), "secureValueRecoveryServiceRetry-%d")).threads(1).build();
|
||||
ScheduledExecutorService storageServiceRetryExecutor = environment.lifecycle()
|
||||
.scheduledExecutorService(name(getClass(), "storageServiceRetry-%d")).threads(1).build();
|
||||
|
||||
ExternalServiceCredentialsGenerator backupCredentialsGenerator = SecureBackupController.credentialsGenerator(
|
||||
configuration.getSecureBackupServiceConfiguration());
|
||||
@@ -135,17 +137,6 @@ public class AssignUsernameCommand extends EnvironmentCommand<WhisperServerConfi
|
||||
DynamoDbClient dynamoDbClient = DynamoDbFromConfig.client(configuration.getDynamoDbClientConfiguration(),
|
||||
WhisperServerService.AWSSDK_CREDENTIALS_PROVIDER);
|
||||
|
||||
AmazonDynamoDB deletedAccountsLockDynamoDbClient = AmazonDynamoDBClientBuilder.standard()
|
||||
.withRegion(configuration.getDynamoDbClientConfiguration().getRegion())
|
||||
.withClientConfiguration(new ClientConfiguration().withClientExecutionTimeout(
|
||||
((int) configuration.getDynamoDbClientConfiguration().getClientExecutionTimeout()
|
||||
.toMillis()))
|
||||
.withRequestTimeout(
|
||||
(int) configuration.getDynamoDbClientConfiguration().getClientRequestTimeout()
|
||||
.toMillis()))
|
||||
.withCredentials(WhisperServerService.AWSSDK_V1_CREDENTIALS_PROVIDER_CHAIN)
|
||||
.build();
|
||||
|
||||
DeletedAccounts deletedAccounts = new DeletedAccounts(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getDeletedAccounts().getTableName());
|
||||
VerificationCodeStore pendingAccounts = new VerificationCodeStore(dynamoDbClient,
|
||||
@@ -175,7 +166,9 @@ public class AssignUsernameCommand extends EnvironmentCommand<WhisperServerConfi
|
||||
dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getEcKeys().getTableName(),
|
||||
configuration.getDynamoDbTables().getKemKeys().getTableName(),
|
||||
configuration.getDynamoDbTables().getKemLastResortKeys().getTableName());
|
||||
configuration.getDynamoDbTables().getEcSignedPreKeys().getTableName(),
|
||||
configuration.getDynamoDbTables().getKemLastResortKeys().getTableName(),
|
||||
dynamicConfigurationManager);
|
||||
MessagesDynamoDb messagesDynamoDb = new MessagesDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getMessages().getTableName(),
|
||||
configuration.getDynamoDbTables().getMessages().getExpiration(),
|
||||
@@ -188,12 +181,14 @@ public class AssignUsernameCommand extends EnvironmentCommand<WhisperServerConfi
|
||||
configuration.getClientPresenceClusterConfiguration(), redisClusterClientResources);
|
||||
FaultTolerantRedisCluster rateLimitersCluster = new FaultTolerantRedisCluster("rate_limiters",
|
||||
configuration.getRateLimitersCluster(), redisClusterClientResources);
|
||||
SecureBackupClient secureBackupClient = new SecureBackupClient(backupCredentialsGenerator, secureValueRecoveryExecutor,
|
||||
configuration.getSecureBackupServiceConfiguration());
|
||||
SecureBackupClient secureBackupClient = new SecureBackupClient(backupCredentialsGenerator,
|
||||
secureValueRecoveryExecutor,
|
||||
secureValueRecoveryServiceRetryExecutor, configuration.getSecureBackupServiceConfiguration());
|
||||
SecureValueRecovery2Client secureValueRecovery2Client = new SecureValueRecovery2Client(
|
||||
secureValueRecoveryCredentialsGenerator, secureValueRecoveryExecutor, configuration.getSvr2Configuration());
|
||||
secureValueRecoveryCredentialsGenerator, secureValueRecoveryExecutor, secureValueRecoveryServiceRetryExecutor,
|
||||
configuration.getSvr2Configuration());
|
||||
SecureStorageClient secureStorageClient = new SecureStorageClient(storageCredentialsGenerator,
|
||||
storageServiceExecutor, configuration.getSecureStorageServiceConfiguration());
|
||||
storageServiceExecutor, storageServiceRetryExecutor, configuration.getSecureStorageServiceConfiguration());
|
||||
ClientPresenceManager clientPresenceManager = new ClientPresenceManager(clientPresenceCluster,
|
||||
Executors.newSingleThreadScheduledExecutor(), keyspaceNotificationDispatchExecutor);
|
||||
MessagesCache messagesCache = new MessagesCache(messageInsertCacheCluster, messageReadDeleteCluster,
|
||||
@@ -206,7 +201,8 @@ public class AssignUsernameCommand extends EnvironmentCommand<WhisperServerConfi
|
||||
configuration.getReportMessageConfiguration().getCounterTtl());
|
||||
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache,
|
||||
reportMessageManager, messageDeletionExecutor);
|
||||
AccountLockManager accountLockManager = new AccountLockManager(deletedAccountsLockDynamoDbClient, configuration.getDynamoDbTables().getDeletedAccountsLock().getTableName());
|
||||
AccountLockManager accountLockManager = new AccountLockManager(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getDeletedAccountsLock().getTableName());
|
||||
StoredVerificationCodeManager pendingAccountsManager = new StoredVerificationCodeManager(pendingAccounts);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
accountLockManager, deletedAccounts, keys, messagesManager, profilesManager,
|
||||
|
||||
+24
-23
@@ -7,9 +7,6 @@ package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.amazonaws.ClientConfiguration;
|
||||
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;
|
||||
@@ -17,7 +14,7 @@ import java.io.IOException;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.time.Clock;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerService;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
@@ -83,6 +80,8 @@ record CommandDependencies(
|
||||
FaultTolerantRedisCluster cacheCluster = new FaultTolerantRedisCluster("main_cache_cluster",
|
||||
configuration.getCacheClusterConfiguration(), redisClusterClientResources);
|
||||
|
||||
ScheduledExecutorService recurringJobExecutor = environment.lifecycle()
|
||||
.scheduledExecutorService(name(name, "recurringJob-%d")).threads(2).build();
|
||||
Scheduler messageDeliveryScheduler = Schedulers.fromExecutorService(
|
||||
environment.lifecycle().executorService("messageDelivery").maxThreads(4)
|
||||
.build());
|
||||
@@ -91,9 +90,14 @@ record CommandDependencies(
|
||||
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(name(name, "secureValueRecoveryService-%d")).maxThreads(8).minThreads(8).build();
|
||||
ExecutorService storageServiceExecutor = environment.lifecycle()
|
||||
.executorService(name(name, "storageService-%d")).maxThreads(8).minThreads(1).build();
|
||||
.executorService(name(name, "storageService-%d")).maxThreads(8).minThreads(8).build();
|
||||
|
||||
ScheduledExecutorService secureValueRecoveryServiceRetryExecutor = environment.lifecycle()
|
||||
.scheduledExecutorService(name(name, "secureValueRecoveryServiceRetry-%d")).threads(1).build();
|
||||
ScheduledExecutorService storageServiceRetryExecutor = environment.lifecycle()
|
||||
.scheduledExecutorService(name(name, "storageServiceRetry-%d")).threads(1).build();
|
||||
|
||||
ExternalServiceCredentialsGenerator backupCredentialsGenerator = SecureBackupController.credentialsGenerator(
|
||||
configuration.getSecureBackupServiceConfiguration());
|
||||
@@ -116,17 +120,6 @@ record CommandDependencies(
|
||||
DynamoDbClient dynamoDbClient = DynamoDbFromConfig.client(
|
||||
configuration.getDynamoDbClientConfiguration(), WhisperServerService.AWSSDK_CREDENTIALS_PROVIDER);
|
||||
|
||||
AmazonDynamoDB deletedAccountsLockDynamoDbClient = AmazonDynamoDBClientBuilder.standard()
|
||||
.withRegion(configuration.getDynamoDbClientConfiguration().getRegion())
|
||||
.withClientConfiguration(new ClientConfiguration().withClientExecutionTimeout(
|
||||
((int) configuration.getDynamoDbClientConfiguration().getClientExecutionTimeout()
|
||||
.toMillis()))
|
||||
.withRequestTimeout(
|
||||
(int) configuration.getDynamoDbClientConfiguration().getClientRequestTimeout()
|
||||
.toMillis()))
|
||||
.withCredentials(WhisperServerService.AWSSDK_V1_CREDENTIALS_PROVIDER_CHAIN)
|
||||
.build();
|
||||
|
||||
DeletedAccounts deletedAccounts = new DeletedAccounts(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getDeletedAccounts().getTableName());
|
||||
VerificationCodeStore pendingAccounts = new VerificationCodeStore(dynamoDbClient,
|
||||
@@ -157,7 +150,9 @@ record CommandDependencies(
|
||||
dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getEcKeys().getTableName(),
|
||||
configuration.getDynamoDbTables().getKemKeys().getTableName(),
|
||||
configuration.getDynamoDbTables().getKemLastResortKeys().getTableName());
|
||||
configuration.getDynamoDbTables().getEcSignedPreKeys().getTableName(),
|
||||
configuration.getDynamoDbTables().getKemLastResortKeys().getTableName(),
|
||||
dynamicConfigurationManager);
|
||||
MessagesDynamoDb messagesDynamoDb = new MessagesDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getMessages().getTableName(),
|
||||
configuration.getDynamoDbTables().getMessages().getExpiration(),
|
||||
@@ -171,15 +166,16 @@ record CommandDependencies(
|
||||
FaultTolerantRedisCluster rateLimitersCluster = new FaultTolerantRedisCluster("rate_limiters",
|
||||
configuration.getRateLimitersCluster(), redisClusterClientResources);
|
||||
SecureBackupClient secureBackupClient = new SecureBackupClient(backupCredentialsGenerator,
|
||||
secureValueRecoveryServiceExecutor,
|
||||
secureValueRecoveryServiceExecutor, secureValueRecoveryServiceRetryExecutor,
|
||||
configuration.getSecureBackupServiceConfiguration());
|
||||
SecureValueRecovery2Client secureValueRecovery2Client = new SecureValueRecovery2Client(
|
||||
secureValueRecoveryCredentialsGenerator, secureValueRecoveryServiceExecutor,
|
||||
secureValueRecoveryServiceRetryExecutor,
|
||||
configuration.getSvr2Configuration());
|
||||
SecureStorageClient secureStorageClient = new SecureStorageClient(storageCredentialsGenerator,
|
||||
storageServiceExecutor, configuration.getSecureStorageServiceConfiguration());
|
||||
storageServiceExecutor, storageServiceRetryExecutor, configuration.getSecureStorageServiceConfiguration());
|
||||
ClientPresenceManager clientPresenceManager = new ClientPresenceManager(clientPresenceCluster,
|
||||
Executors.newSingleThreadScheduledExecutor(), keyspaceNotificationDispatchExecutor);
|
||||
recurringJobExecutor, keyspaceNotificationDispatchExecutor);
|
||||
MessagesCache messagesCache = new MessagesCache(messageInsertCacheCluster, messageReadDeleteCluster,
|
||||
keyspaceNotificationDispatchExecutor, messageDeliveryScheduler, messageDeletionExecutor, Clock.systemUTC());
|
||||
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster);
|
||||
@@ -190,13 +186,18 @@ record CommandDependencies(
|
||||
configuration.getReportMessageConfiguration().getCounterTtl());
|
||||
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache,
|
||||
reportMessageManager, messageDeletionExecutor);
|
||||
AccountLockManager accountLockManager = new AccountLockManager(deletedAccountsLockDynamoDbClient, configuration.getDynamoDbTables().getDeletedAccountsLock().getTableName());
|
||||
AccountLockManager accountLockManager = new AccountLockManager(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getDeletedAccountsLock().getTableName());
|
||||
StoredVerificationCodeManager pendingAccountsManager = new StoredVerificationCodeManager(pendingAccounts);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
accountLockManager, deletedAccounts, keys, messagesManager, profilesManager,
|
||||
pendingAccountsManager, secureStorageClient, secureBackupClient, secureValueRecovery2Client, clientPresenceManager,
|
||||
pendingAccountsManager, secureStorageClient, secureBackupClient, secureValueRecovery2Client,
|
||||
clientPresenceManager,
|
||||
experimentEnrollmentManager, registrationRecoveryPasswordsManager, clock);
|
||||
|
||||
environment.lifecycle().manage(messagesCache);
|
||||
environment.lifecycle().manage(clientPresenceManager);
|
||||
|
||||
return new CommandDependencies(
|
||||
accountsManager,
|
||||
profilesManager,
|
||||
|
||||
+62
-34
@@ -11,6 +11,7 @@ import io.dropwizard.Application;
|
||||
import io.dropwizard.cli.EnvironmentCommand;
|
||||
import io.dropwizard.setup.Environment;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import net.sourceforge.argparse4j.inf.Argument;
|
||||
import net.sourceforge.argparse4j.inf.ArgumentParser;
|
||||
@@ -18,6 +19,7 @@ import net.sourceforge.argparse4j.inf.ArgumentParserException;
|
||||
import net.sourceforge.argparse4j.inf.ArgumentType;
|
||||
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.configuration.dynamic.DynamicConfiguration;
|
||||
@@ -36,13 +38,15 @@ import org.whispersystems.textsecuregcm.util.logging.UncaughtExceptionHandler;
|
||||
public class CrawlAccountsCommand extends EnvironmentCommand<WhisperServerConfiguration> {
|
||||
|
||||
private static final String CRAWL_TYPE = "crawlType";
|
||||
private static final String WORKER_COUNT = "workers";
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(CrawlAccountsCommand.class);
|
||||
|
||||
public enum CrawlType implements ArgumentType<CrawlType> {
|
||||
GENERAL_PURPOSE,
|
||||
ACCOUNT_CLEANER,
|
||||
;
|
||||
|
||||
|
||||
@Override
|
||||
public CrawlType convert(final ArgumentParser parser, final Argument arg, final String value)
|
||||
throws ArgumentParserException {
|
||||
@@ -67,6 +71,12 @@ public class CrawlAccountsCommand extends EnvironmentCommand<WhisperServerConfig
|
||||
.dest(CRAWL_TYPE)
|
||||
.required(true)
|
||||
.help("The type of crawl to perform");
|
||||
|
||||
subparser.addArgument("--workers")
|
||||
.type(Integer.class)
|
||||
.dest(WORKER_COUNT)
|
||||
.required(true)
|
||||
.help("The number of worker threads");
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -84,12 +94,6 @@ public class CrawlAccountsCommand extends EnvironmentCommand<WhisperServerConfig
|
||||
final FaultTolerantRedisCluster metricsCluster = new FaultTolerantRedisCluster("metrics_cluster",
|
||||
configuration.getMetricsClusterConfiguration(), deps.redisClusterClientResources());
|
||||
|
||||
// TODO listeners must be ordered so that ones that directly update accounts come last, so that read-only ones are not working with stale data
|
||||
final List<AccountDatabaseCrawlerListener> accountDatabaseCrawlerListeners = List.of(
|
||||
new NonNormalizedAccountCrawlerListener(accountsManager, metricsCluster),
|
||||
// PushFeedbackProcessor may update device properties
|
||||
new PushFeedbackProcessor(accountsManager));
|
||||
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
|
||||
new DynamicConfigurationManager<>(configuration.getAppConfig().getApplication(),
|
||||
configuration.getAppConfig().getEnvironment(),
|
||||
@@ -97,38 +101,55 @@ public class CrawlAccountsCommand extends EnvironmentCommand<WhisperServerConfig
|
||||
DynamicConfiguration.class);
|
||||
|
||||
dynamicConfigurationManager.start();
|
||||
MetricsUtil.registerSystemResourceMetrics(environment);
|
||||
|
||||
final AccountDatabaseCrawler crawler =
|
||||
final int workers = Objects.requireNonNull(namespace.getInt(WORKER_COUNT));
|
||||
|
||||
switch ((CrawlType) namespace.get(CRAWL_TYPE)) {
|
||||
case GENERAL_PURPOSE -> {
|
||||
final AccountDatabaseCrawlerCache accountDatabaseCrawlerCache = new AccountDatabaseCrawlerCache(
|
||||
cacheCluster,
|
||||
AccountDatabaseCrawlerCache.GENERAL_PURPOSE_PREFIX);
|
||||
final AccountDatabaseCrawler crawler = switch ((CrawlType) namespace.get(CRAWL_TYPE)) {
|
||||
case GENERAL_PURPOSE -> {
|
||||
final ExecutorService pushFeedbackUpdateExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "pushFeedback-%d")).maxThreads(workers).minThreads(workers).build();
|
||||
|
||||
yield new AccountDatabaseCrawler("General-purpose account crawler",
|
||||
accountsManager,
|
||||
accountDatabaseCrawlerCache, accountDatabaseCrawlerListeners,
|
||||
configuration.getAccountDatabaseCrawlerConfiguration().getChunkSize(),
|
||||
dynamicConfigurationManager
|
||||
);
|
||||
}
|
||||
case ACCOUNT_CLEANER -> {
|
||||
final ExecutorService accountDeletionExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "accountCleaner-%d")).maxThreads(16).minThreads(16).build();
|
||||
// TODO listeners must be ordered so that ones that directly update accounts come last, so that read-only ones are not working with stale data
|
||||
final List<AccountDatabaseCrawlerListener> accountDatabaseCrawlerListeners = List.of(
|
||||
new NonNormalizedAccountCrawlerListener(accountsManager, metricsCluster),
|
||||
// PushFeedbackProcessor may update device properties
|
||||
new PushFeedbackProcessor(accountsManager, pushFeedbackUpdateExecutor));
|
||||
|
||||
final AccountDatabaseCrawlerCache accountDatabaseCrawlerCache = new AccountDatabaseCrawlerCache(
|
||||
cacheCluster, AccountDatabaseCrawlerCache.ACCOUNT_CLEANER_PREFIX);
|
||||
final AccountDatabaseCrawlerCache accountDatabaseCrawlerCache = new AccountDatabaseCrawlerCache(
|
||||
cacheCluster,
|
||||
AccountDatabaseCrawlerCache.GENERAL_PURPOSE_PREFIX);
|
||||
|
||||
yield new AccountDatabaseCrawler("Account cleaner crawler",
|
||||
accountsManager,
|
||||
accountDatabaseCrawlerCache,
|
||||
List.of(new AccountCleaner(accountsManager, accountDeletionExecutor)),
|
||||
configuration.getAccountDatabaseCrawlerConfiguration().getChunkSize(),
|
||||
dynamicConfigurationManager
|
||||
);
|
||||
}
|
||||
};
|
||||
yield new AccountDatabaseCrawler("General-purpose account crawler",
|
||||
accountsManager,
|
||||
accountDatabaseCrawlerCache, accountDatabaseCrawlerListeners,
|
||||
configuration.getAccountDatabaseCrawlerConfiguration().getChunkSize()
|
||||
);
|
||||
}
|
||||
case ACCOUNT_CLEANER -> {
|
||||
final ExecutorService accountDeletionExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "accountCleaner-%d")).maxThreads(workers).minThreads(workers).build();
|
||||
|
||||
final AccountDatabaseCrawlerCache accountDatabaseCrawlerCache = new AccountDatabaseCrawlerCache(
|
||||
cacheCluster, AccountDatabaseCrawlerCache.ACCOUNT_CLEANER_PREFIX);
|
||||
|
||||
yield new AccountDatabaseCrawler("Account cleaner crawler",
|
||||
accountsManager,
|
||||
accountDatabaseCrawlerCache,
|
||||
List.of(new AccountCleaner(accountsManager, accountDeletionExecutor)),
|
||||
configuration.getAccountDatabaseCrawlerConfiguration().getChunkSize()
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
environment.lifecycle().getManagedObjects().forEach(managedObject -> {
|
||||
try {
|
||||
managedObject.start();
|
||||
} catch (final Exception e) {
|
||||
logger.error("Failed to start managed object", e);
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
crawler.crawlAllAccounts();
|
||||
@@ -136,5 +157,12 @@ public class CrawlAccountsCommand extends EnvironmentCommand<WhisperServerConfig
|
||||
LoggerFactory.getLogger(CrawlAccountsCommand.class).error("Error crawling accounts", e);
|
||||
}
|
||||
|
||||
environment.lifecycle().getManagedObjects().forEach(managedObject -> {
|
||||
try {
|
||||
managedObject.stop();
|
||||
} catch (final Exception e) {
|
||||
logger.error("Failed to stop managed object", e);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -9,7 +9,6 @@ import io.dropwizard.Application;
|
||||
import io.dropwizard.cli.ServerCommand;
|
||||
import io.dropwizard.setup.Environment;
|
||||
import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
@@ -65,11 +64,13 @@ public class MessagePersisterServiceCommand extends ServerCommand<WhisperServerC
|
||||
deps.accountsManager(),
|
||||
dynamicConfigurationManager,
|
||||
Duration.ofMinutes(configuration.getMessageCacheConfiguration().getPersistDelayMinutes()),
|
||||
Optional.of(namespace.getInt(WORKER_COUNT)));
|
||||
namespace.getInt(WORKER_COUNT));
|
||||
|
||||
environment.lifecycle().manage(deps.messagesCache());
|
||||
environment.lifecycle().manage(messagePersister);
|
||||
|
||||
MetricsUtil.registerSystemResourceMetrics(environment);
|
||||
|
||||
super.run(environment, namespace, configuration);
|
||||
}
|
||||
|
||||
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.KeysManager;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.util.function.Tuple3;
|
||||
import reactor.util.function.Tuples;
|
||||
|
||||
public class MigrateSignedECPreKeysCommand extends AbstractSinglePassCrawlAccountsCommand {
|
||||
|
||||
private static final String STORE_KEY_ATTEMPT_COUNTER_NAME =
|
||||
MetricsUtil.name(MigrateSignedECPreKeysCommand.class, "storeKeyAttempt");
|
||||
|
||||
public MigrateSignedECPreKeysCommand() {
|
||||
super("migrate-signed-ec-pre-keys", "Migrate signed EC pre-keys from Account records to a dedicated table");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void crawlAccounts(final Flux<Account> accounts) {
|
||||
final KeysManager keysManager = getCommandDependencies().keysManager();
|
||||
|
||||
accounts.flatMap(account -> Flux.fromIterable(account.getDevices())
|
||||
.flatMap(device -> {
|
||||
final List<Tuple3<UUID, Long, ECSignedPreKey>> keys = new ArrayList<>(2);
|
||||
|
||||
if (device.getSignedPreKey() != null) {
|
||||
keys.add(Tuples.of(account.getUuid(), device.getId(), device.getSignedPreKey()));
|
||||
}
|
||||
|
||||
if (device.getPhoneNumberIdentitySignedPreKey() != null) {
|
||||
keys.add(Tuples.of(account.getPhoneNumberIdentifier(), device.getId(), device.getPhoneNumberIdentitySignedPreKey()));
|
||||
}
|
||||
|
||||
return Flux.fromIterable(keys);
|
||||
}))
|
||||
.flatMap(keyTuple -> Mono.fromFuture(
|
||||
keysManager.storeEcSignedPreKeyIfAbsent(keyTuple.getT1(), keyTuple.getT2(), keyTuple.getT3())))
|
||||
.doOnNext(keyStored -> Metrics.counter(STORE_KEY_ATTEMPT_COUNTER_NAME, "stored", String.valueOf(keyStored)).increment())
|
||||
.blockLast();
|
||||
}
|
||||
}
|
||||
+3
-13
@@ -10,17 +10,14 @@ import static com.codahale.metrics.MetricRegistry.name;
|
||||
import io.dropwizard.Application;
|
||||
import io.dropwizard.cli.ServerCommand;
|
||||
import io.dropwizard.setup.Environment;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.push.APNSender;
|
||||
import org.whispersystems.textsecuregcm.push.ApnPushNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.logging.UncaughtExceptionHandler;
|
||||
|
||||
public class ScheduledApnPushNotificationSenderServiceCommand extends ServerCommand<WhisperServerConfiguration> {
|
||||
@@ -63,22 +60,15 @@ public class ScheduledApnPushNotificationSenderServiceCommand extends ServerComm
|
||||
final ExecutorService apnSenderExecutor = environment.lifecycle().executorService(name(getClass(), "apnSender-%d"))
|
||||
.maxThreads(1).minThreads(1).build();
|
||||
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = new DynamicConfigurationManager<>(
|
||||
configuration.getAppConfig().getApplication(),
|
||||
configuration.getAppConfig().getEnvironment(),
|
||||
configuration.getAppConfig().getConfigurationName(),
|
||||
DynamicConfiguration.class);
|
||||
|
||||
dynamicConfigurationManager.start();
|
||||
|
||||
final APNSender apnSender = new APNSender(apnSenderExecutor, configuration.getApnConfiguration());
|
||||
final ApnPushNotificationScheduler apnPushNotificationScheduler = new ApnPushNotificationScheduler(
|
||||
pushSchedulerCluster, apnSender, deps.accountsManager(), Optional.of(namespace.getInt(WORKER_COUNT)),
|
||||
dynamicConfigurationManager);
|
||||
pushSchedulerCluster, apnSender, deps.accountsManager(), namespace.getInt(WORKER_COUNT));
|
||||
|
||||
environment.lifecycle().manage(apnSender);
|
||||
environment.lifecycle().manage(apnPushNotificationScheduler);
|
||||
|
||||
MetricsUtil.registerSystemResourceMetrics(environment);
|
||||
|
||||
super.run(environment, namespace, configuration);
|
||||
}
|
||||
|
||||
|
||||
@@ -21,30 +21,13 @@ 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))
|
||||
local tokensRemainingStr, lastUpdateTimeMillisStr = unpack(redis.call("HMGET", bucketId, SIZE_FIELD, TIME_FIELD))
|
||||
if tokensRemainingStr and lastUpdateTimeMillisStr then
|
||||
tokensRemaining = tonumber(tokensRemainingStr)
|
||||
lastUpdateTimeMillis = tonumber(lastUpdateTimeMillisStr)
|
||||
else
|
||||
tokensRemaining = bucketSize
|
||||
lastUpdateTimeMillis = currentTimeMillis
|
||||
end
|
||||
|
||||
local elapsedTime = currentTimeMillis - lastUpdateTimeMillis
|
||||
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth.grpc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import io.dropwizard.auth.basic.BasicCredentials;
|
||||
import io.grpc.CallCredentials;
|
||||
import io.grpc.ManagedChannel;
|
||||
import io.grpc.Metadata;
|
||||
import io.grpc.Server;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import io.grpc.inprocess.InProcessChannelBuilder;
|
||||
import io.grpc.inprocess.InProcessServerBuilder;
|
||||
import java.io.IOException;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.stream.Stream;
|
||||
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.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.signal.chat.rpc.EchoRequest;
|
||||
import org.signal.chat.rpc.EchoServiceGrpc;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.BaseAccountAuthenticator;
|
||||
import org.whispersystems.textsecuregcm.grpc.EchoServiceImpl;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
|
||||
class BasicCredentialAuthenticationInterceptorTest {
|
||||
|
||||
private Server server;
|
||||
private ManagedChannel managedChannel;
|
||||
|
||||
private BaseAccountAuthenticator baseAccountAuthenticator;
|
||||
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
baseAccountAuthenticator = mock(BaseAccountAuthenticator.class);
|
||||
|
||||
final BasicCredentialAuthenticationInterceptor authenticationInterceptor =
|
||||
new BasicCredentialAuthenticationInterceptor(baseAccountAuthenticator);
|
||||
|
||||
final String serverName = InProcessServerBuilder.generateName();
|
||||
|
||||
server = InProcessServerBuilder.forName(serverName)
|
||||
.directExecutor()
|
||||
.intercept(authenticationInterceptor)
|
||||
.addService(new EchoServiceImpl())
|
||||
.build()
|
||||
.start();
|
||||
|
||||
managedChannel = InProcessChannelBuilder.forName(serverName)
|
||||
.directExecutor()
|
||||
.build();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
managedChannel.shutdown();
|
||||
server.shutdown();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void interceptCall(final Metadata headers, final boolean acceptCredentials, final boolean expectAuthentication) {
|
||||
if (acceptCredentials) {
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getUuid()).thenReturn(UUID.randomUUID());
|
||||
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getId()).thenReturn(Device.MASTER_ID);
|
||||
|
||||
when(baseAccountAuthenticator.authenticate(any(), anyBoolean()))
|
||||
.thenReturn(Optional.of(new AuthenticatedAccount(() -> new Pair<>(account, device))));
|
||||
} else {
|
||||
when(baseAccountAuthenticator.authenticate(any(), anyBoolean()))
|
||||
.thenReturn(Optional.empty());
|
||||
}
|
||||
|
||||
final EchoServiceGrpc.EchoServiceBlockingStub stub = EchoServiceGrpc.newBlockingStub(managedChannel)
|
||||
.withCallCredentials(new CallCredentials() {
|
||||
@Override
|
||||
public void applyRequestMetadata(final RequestInfo requestInfo, final Executor appExecutor, final MetadataApplier applier) {
|
||||
applier.apply(headers);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void thisUsesUnstableApi() {
|
||||
}
|
||||
});
|
||||
|
||||
if (expectAuthentication) {
|
||||
assertDoesNotThrow(() -> stub.echo(EchoRequest.newBuilder().build()));
|
||||
} else {
|
||||
final StatusRuntimeException exception =
|
||||
assertThrows(StatusRuntimeException.class, () -> stub.echo(EchoRequest.newBuilder().build()));
|
||||
|
||||
assertEquals(Status.UNAUTHENTICATED.getCode(), exception.getStatus().getCode());
|
||||
}
|
||||
}
|
||||
|
||||
private static Stream<Arguments> interceptCall() {
|
||||
final Metadata malformedCredentialHeaders = new Metadata();
|
||||
malformedCredentialHeaders.put(BasicCredentialAuthenticationInterceptor.BASIC_CREDENTIALS, "Incorrect");
|
||||
|
||||
final Metadata structurallyValidCredentialHeaders = new Metadata();
|
||||
structurallyValidCredentialHeaders.put(BasicCredentialAuthenticationInterceptor.BASIC_CREDENTIALS,
|
||||
UUID.randomUUID() + ":" + RandomStringUtils.randomAlphanumeric(16));
|
||||
|
||||
return Stream.of(
|
||||
Arguments.of(new Metadata(), true, false),
|
||||
Arguments.of(malformedCredentialHeaders, true, false),
|
||||
Arguments.of(structurallyValidCredentialHeaders, false, false),
|
||||
Arguments.of(structurallyValidCredentialHeaders, true, true)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractBasicCredentials() {
|
||||
final String username = UUID.randomUUID().toString();
|
||||
final String password = RandomStringUtils.random(16);
|
||||
|
||||
final BasicCredentials basicCredentials =
|
||||
BasicCredentialAuthenticationInterceptor.extractBasicCredentials(username + ":" + password);
|
||||
|
||||
assertEquals(username, basicCredentials.getUsername());
|
||||
assertEquals(password, basicCredentials.getPassword());
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractBasicCredentialsIllegalArgument() {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> BasicCredentialAuthenticationInterceptor.extractBasicCredentials("This does not include a password"));
|
||||
}
|
||||
}
|
||||
+5
-8
@@ -359,14 +359,13 @@ class DynamicConfigurationTest {
|
||||
final DynamicConfiguration emptyConfig =
|
||||
DynamicConfigurationManager.parseConfiguration(emptyConfigYaml, DynamicConfiguration.class).orElseThrow();
|
||||
|
||||
assertTrue(emptyConfig.getMessagePersisterConfiguration().isServerPersistenceEnabled());
|
||||
assertFalse(emptyConfig.getMessagePersisterConfiguration().isDedicatedProcessEnabled());
|
||||
assertTrue(emptyConfig.getMessagePersisterConfiguration().isPersistenceEnabled());
|
||||
}
|
||||
|
||||
{
|
||||
final String messagePersisterEnabledYaml = REQUIRED_CONFIG.concat("""
|
||||
messagePersister:
|
||||
serverPersistenceEnabled: true
|
||||
persistenceEnabled: true
|
||||
dedicatedProcessEnabled: true
|
||||
""");
|
||||
|
||||
@@ -374,22 +373,20 @@ class DynamicConfigurationTest {
|
||||
DynamicConfigurationManager.parseConfiguration(messagePersisterEnabledYaml, DynamicConfiguration.class)
|
||||
.orElseThrow();
|
||||
|
||||
assertTrue(config.getMessagePersisterConfiguration().isServerPersistenceEnabled());
|
||||
assertTrue(config.getMessagePersisterConfiguration().isDedicatedProcessEnabled());
|
||||
assertTrue(config.getMessagePersisterConfiguration().isPersistenceEnabled());
|
||||
}
|
||||
|
||||
{
|
||||
final String messagePersisterDisabledYaml = REQUIRED_CONFIG.concat("""
|
||||
messagePersister:
|
||||
serverPersistenceEnabled: false
|
||||
persistenceEnabled: false
|
||||
""");
|
||||
|
||||
final DynamicConfiguration config =
|
||||
DynamicConfigurationManager.parseConfiguration(messagePersisterDisabledYaml, DynamicConfiguration.class)
|
||||
.orElseThrow();
|
||||
|
||||
assertFalse(config.getMessagePersisterConfiguration().isServerPersistenceEnabled());
|
||||
assertFalse(config.getMessagePersisterConfiguration().isDedicatedProcessEnabled());
|
||||
assertFalse(config.getMessagePersisterConfiguration().isPersistenceEnabled());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+150
-71
@@ -47,6 +47,7 @@ import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ecc.Curve;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
@@ -117,10 +118,10 @@ class RegistrationControllerTest {
|
||||
|
||||
@Test
|
||||
public void testRegistrationRequest() throws Exception {
|
||||
assertFalse(new RegistrationRequest("", new byte[0], new AccountAttributes(), true, Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()).isValid());
|
||||
assertFalse(new RegistrationRequest("some", new byte[32], new AccountAttributes(), true, Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()).isValid());
|
||||
assertTrue(new RegistrationRequest("", new byte[32], new AccountAttributes(), true, Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()).isValid());
|
||||
assertTrue(new RegistrationRequest("some", new byte[0], new AccountAttributes(), true, Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()).isValid());
|
||||
assertFalse(new RegistrationRequest("", new byte[0], new AccountAttributes(), true, false, Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()).isValid());
|
||||
assertFalse(new RegistrationRequest("some", new byte[32], new AccountAttributes(), true, false, Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()).isValid());
|
||||
assertTrue(new RegistrationRequest("", new byte[32], new AccountAttributes(), true, false, Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()).isValid());
|
||||
assertTrue(new RegistrationRequest("some", new byte[0], new AccountAttributes(), true, false, Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()).isValid());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -447,6 +448,7 @@ class RegistrationControllerTest {
|
||||
new byte[0],
|
||||
fetchesMessagesAccountAttributes,
|
||||
true,
|
||||
false,
|
||||
aciIdentityKey,
|
||||
pniIdentityKey,
|
||||
aciSignedPreKey,
|
||||
@@ -461,6 +463,7 @@ class RegistrationControllerTest {
|
||||
new byte[0],
|
||||
fetchesMessagesAccountAttributes,
|
||||
true,
|
||||
false,
|
||||
aciIdentityKey,
|
||||
pniIdentityKey,
|
||||
aciSignedPreKey,
|
||||
@@ -475,6 +478,7 @@ class RegistrationControllerTest {
|
||||
new byte[0],
|
||||
pushAccountAttributes,
|
||||
true,
|
||||
false,
|
||||
aciIdentityKey,
|
||||
pniIdentityKey,
|
||||
aciSignedPreKey,
|
||||
@@ -533,6 +537,7 @@ class RegistrationControllerTest {
|
||||
new byte[0],
|
||||
accountAttributes,
|
||||
true,
|
||||
false,
|
||||
aciIdentityKey,
|
||||
pniIdentityKey,
|
||||
aciSignedPreKey,
|
||||
@@ -547,6 +552,7 @@ class RegistrationControllerTest {
|
||||
new byte[0],
|
||||
accountAttributes,
|
||||
true,
|
||||
false,
|
||||
aciIdentityKey,
|
||||
pniIdentityKey,
|
||||
Optional.empty(),
|
||||
@@ -561,6 +567,7 @@ class RegistrationControllerTest {
|
||||
new byte[0],
|
||||
accountAttributes,
|
||||
true,
|
||||
false,
|
||||
aciIdentityKey,
|
||||
pniIdentityKey,
|
||||
aciSignedPreKey,
|
||||
@@ -575,6 +582,7 @@ class RegistrationControllerTest {
|
||||
new byte[0],
|
||||
accountAttributes,
|
||||
true,
|
||||
false,
|
||||
aciIdentityKey,
|
||||
pniIdentityKey,
|
||||
aciSignedPreKey,
|
||||
@@ -589,6 +597,7 @@ class RegistrationControllerTest {
|
||||
new byte[0],
|
||||
accountAttributes,
|
||||
true,
|
||||
false,
|
||||
Optional.empty(),
|
||||
pniIdentityKey,
|
||||
aciSignedPreKey,
|
||||
@@ -603,6 +612,7 @@ class RegistrationControllerTest {
|
||||
new byte[0],
|
||||
accountAttributes,
|
||||
true,
|
||||
false,
|
||||
aciIdentityKey,
|
||||
Optional.empty(),
|
||||
aciSignedPreKey,
|
||||
@@ -671,6 +681,8 @@ class RegistrationControllerTest {
|
||||
verify(device).setSignedPreKey(expectedAciSignedPreKey);
|
||||
verify(device).setPhoneNumberIdentitySignedPreKey(expectedPniSignedPreKey);
|
||||
|
||||
verify(keysManager).storeEcSignedPreKeys(accountIdentifier, Map.of(Device.MASTER_ID, expectedAciSignedPreKey));
|
||||
verify(keysManager).storeEcSignedPreKeys(phoneNumberIdentifier, Map.of(Device.MASTER_ID, expectedPniSignedPreKey));
|
||||
verify(keysManager).storePqLastResort(accountIdentifier, Map.of(Device.MASTER_ID, expectedAciPqLastResortPreKey));
|
||||
verify(keysManager).storePqLastResort(phoneNumberIdentifier, Map.of(Device.MASTER_ID, expectedPniPqLastResortPreKey));
|
||||
|
||||
@@ -684,6 +696,43 @@ class RegistrationControllerTest {
|
||||
() -> verify(device, never()).setGcmId(any()));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void nonAtomicAccountCreationWithNoAtomicFields(boolean requireAtomic) throws InterruptedException {
|
||||
when(registrationServiceClient.getSession(any(), any()))
|
||||
.thenReturn(
|
||||
CompletableFuture.completedFuture(
|
||||
Optional.of(new RegistrationServiceSession(new byte[16], NUMBER, true, null, null, null,
|
||||
SESSION_EXPIRATION_SECONDS))));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/registration")
|
||||
.request()
|
||||
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD));
|
||||
|
||||
when(accountsManager.create(any(), any(), any(), any(), any()))
|
||||
.thenReturn(mock(Account.class));
|
||||
|
||||
RegistrationRequest reg = new RegistrationRequest("session-id",
|
||||
new byte[0],
|
||||
new AccountAttributes(true, 1, "test", null, true, new Device.DeviceCapabilities()),
|
||||
true,
|
||||
requireAtomic,
|
||||
Optional.empty(),
|
||||
Optional.empty(),
|
||||
Optional.empty(),
|
||||
Optional.empty(),
|
||||
Optional.empty(),
|
||||
Optional.empty(),
|
||||
Optional.empty(),
|
||||
Optional.empty());
|
||||
|
||||
try (final Response response = request.post(Entity.json(reg))) {
|
||||
int expected = requireAtomic ? 422 : 200;
|
||||
assertEquals(expected, response.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
private static Stream<Arguments> atomicAccountCreationSuccess() {
|
||||
final Optional<IdentityKey> aciIdentityKey;
|
||||
final Optional<IdentityKey> pniIdentityKey;
|
||||
@@ -713,75 +762,105 @@ class RegistrationControllerTest {
|
||||
final String apnsVoipToken = "apns-voip-token";
|
||||
final String gcmToken = "gcm-token";
|
||||
|
||||
return Stream.of(
|
||||
// Fetches messages; no push tokens
|
||||
Arguments.of(new RegistrationRequest("session-id",
|
||||
new byte[0],
|
||||
fetchesMessagesAccountAttributes,
|
||||
true,
|
||||
aciIdentityKey,
|
||||
pniIdentityKey,
|
||||
aciSignedPreKey,
|
||||
pniSignedPreKey,
|
||||
aciPqLastResortPreKey,
|
||||
pniPqLastResortPreKey,
|
||||
Optional.empty(),
|
||||
Optional.empty()),
|
||||
aciIdentityKey.get(),
|
||||
pniIdentityKey.get(),
|
||||
aciSignedPreKey.get(),
|
||||
pniSignedPreKey.get(),
|
||||
aciPqLastResortPreKey.get(),
|
||||
pniPqLastResortPreKey.get(),
|
||||
Optional.empty(),
|
||||
Optional.empty(),
|
||||
Optional.empty()),
|
||||
return Stream.of(false, true)
|
||||
// try with and without strict atomic checking
|
||||
.flatMap(requireAtomic ->
|
||||
Stream.of(
|
||||
// Fetches messages; no push tokens
|
||||
Arguments.of(new RegistrationRequest("session-id",
|
||||
new byte[0],
|
||||
fetchesMessagesAccountAttributes,
|
||||
true,
|
||||
requireAtomic,
|
||||
aciIdentityKey,
|
||||
pniIdentityKey,
|
||||
aciSignedPreKey,
|
||||
pniSignedPreKey,
|
||||
aciPqLastResortPreKey,
|
||||
pniPqLastResortPreKey,
|
||||
Optional.empty(),
|
||||
Optional.empty()),
|
||||
aciIdentityKey.get(),
|
||||
pniIdentityKey.get(),
|
||||
aciSignedPreKey.get(),
|
||||
pniSignedPreKey.get(),
|
||||
aciPqLastResortPreKey.get(),
|
||||
pniPqLastResortPreKey.get(),
|
||||
Optional.empty(),
|
||||
Optional.empty(),
|
||||
Optional.empty()),
|
||||
|
||||
// Has APNs tokens
|
||||
Arguments.of(new RegistrationRequest("session-id",
|
||||
new byte[0],
|
||||
pushAccountAttributes,
|
||||
true,
|
||||
aciIdentityKey,
|
||||
pniIdentityKey,
|
||||
aciSignedPreKey,
|
||||
pniSignedPreKey,
|
||||
aciPqLastResortPreKey,
|
||||
pniPqLastResortPreKey,
|
||||
Optional.of(new ApnRegistrationId(apnsToken, apnsVoipToken)),
|
||||
Optional.empty()),
|
||||
aciIdentityKey.get(),
|
||||
pniIdentityKey.get(),
|
||||
aciSignedPreKey.get(),
|
||||
pniSignedPreKey.get(),
|
||||
aciPqLastResortPreKey.get(),
|
||||
pniPqLastResortPreKey.get(),
|
||||
Optional.of(apnsToken),
|
||||
Optional.of(apnsVoipToken),
|
||||
Optional.empty()),
|
||||
// Has APNs tokens
|
||||
Arguments.of(new RegistrationRequest("session-id",
|
||||
new byte[0],
|
||||
pushAccountAttributes,
|
||||
true,
|
||||
requireAtomic,
|
||||
aciIdentityKey,
|
||||
pniIdentityKey,
|
||||
aciSignedPreKey,
|
||||
pniSignedPreKey,
|
||||
aciPqLastResortPreKey,
|
||||
pniPqLastResortPreKey,
|
||||
Optional.of(new ApnRegistrationId(apnsToken, apnsVoipToken)),
|
||||
Optional.empty()),
|
||||
aciIdentityKey.get(),
|
||||
pniIdentityKey.get(),
|
||||
aciSignedPreKey.get(),
|
||||
pniSignedPreKey.get(),
|
||||
aciPqLastResortPreKey.get(),
|
||||
pniPqLastResortPreKey.get(),
|
||||
Optional.of(apnsToken),
|
||||
Optional.of(apnsVoipToken),
|
||||
Optional.empty()),
|
||||
|
||||
// Fetches messages; no push tokens
|
||||
Arguments.of(new RegistrationRequest("session-id",
|
||||
new byte[0],
|
||||
pushAccountAttributes,
|
||||
true,
|
||||
aciIdentityKey,
|
||||
pniIdentityKey,
|
||||
aciSignedPreKey,
|
||||
pniSignedPreKey,
|
||||
aciPqLastResortPreKey,
|
||||
pniPqLastResortPreKey,
|
||||
Optional.empty(),
|
||||
Optional.of(new GcmRegistrationId(gcmToken))),
|
||||
aciIdentityKey.get(),
|
||||
pniIdentityKey.get(),
|
||||
aciSignedPreKey.get(),
|
||||
pniSignedPreKey.get(),
|
||||
aciPqLastResortPreKey.get(),
|
||||
pniPqLastResortPreKey.get(),
|
||||
Optional.empty(),
|
||||
Optional.empty(),
|
||||
Optional.of(gcmToken)));
|
||||
// requires the request to be atomic
|
||||
Arguments.of(new RegistrationRequest("session-id",
|
||||
new byte[0],
|
||||
pushAccountAttributes,
|
||||
true,
|
||||
requireAtomic,
|
||||
aciIdentityKey,
|
||||
pniIdentityKey,
|
||||
aciSignedPreKey,
|
||||
pniSignedPreKey,
|
||||
aciPqLastResortPreKey,
|
||||
pniPqLastResortPreKey,
|
||||
Optional.of(new ApnRegistrationId(apnsToken, apnsVoipToken)),
|
||||
Optional.empty()),
|
||||
aciIdentityKey.get(),
|
||||
pniIdentityKey.get(),
|
||||
aciSignedPreKey.get(),
|
||||
pniSignedPreKey.get(),
|
||||
aciPqLastResortPreKey.get(),
|
||||
pniPqLastResortPreKey.get(),
|
||||
Optional.of(apnsToken),
|
||||
Optional.of(apnsVoipToken),
|
||||
Optional.empty()),
|
||||
|
||||
// Fetches messages; no push tokens
|
||||
Arguments.of(new RegistrationRequest("session-id",
|
||||
new byte[0],
|
||||
pushAccountAttributes,
|
||||
true,
|
||||
requireAtomic,
|
||||
aciIdentityKey,
|
||||
pniIdentityKey,
|
||||
aciSignedPreKey,
|
||||
pniSignedPreKey,
|
||||
aciPqLastResortPreKey,
|
||||
pniPqLastResortPreKey,
|
||||
Optional.empty(),
|
||||
Optional.of(new GcmRegistrationId(gcmToken))),
|
||||
aciIdentityKey.get(),
|
||||
pniIdentityKey.get(),
|
||||
aciSignedPreKey.get(),
|
||||
pniSignedPreKey.get(),
|
||||
aciPqLastResortPreKey.get(),
|
||||
pniPqLastResortPreKey.get(),
|
||||
Optional.empty(),
|
||||
Optional.empty(),
|
||||
Optional.of(gcmToken))));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+8
-4
@@ -13,6 +13,7 @@ import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.reset;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import io.micrometer.core.instrument.MockClock;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
@@ -104,13 +105,16 @@ class ExperimentTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
public void testRecordResult(final Object expected, final Object actual, final Experiment experiment,
|
||||
final Timer expectedTimer) {
|
||||
public void testRecordResult(final Object expected, final Object actual, final Experiment experiment, final Timer expectedTimer) {
|
||||
reset(expectedTimer);
|
||||
|
||||
final long durationNanos = 123;
|
||||
final MockClock clock = new MockClock();
|
||||
final Timer.Sample sample = Timer.start(clock);
|
||||
|
||||
experiment.recordResult(expected, actual, durationNanos);
|
||||
final long durationNanos = 123;
|
||||
clock.add(durationNanos, TimeUnit.NANOSECONDS);
|
||||
|
||||
experiment.recordResult(expected, actual, sample);
|
||||
verify(expectedTimer).record(durationNanos, TimeUnit.NANOSECONDS);
|
||||
}
|
||||
|
||||
|
||||
+132
-70
@@ -5,6 +5,8 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.filters;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.Mockito.mock;
|
||||
@@ -13,105 +15,165 @@ import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.vdurmont.semver4j.Semver;
|
||||
import java.io.IOException;
|
||||
import java.util.EnumMap;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.signal.chat.rpc.EchoServiceGrpc;
|
||||
import org.signal.chat.rpc.EchoRequest;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicRemoteDeprecationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.grpc.EchoServiceImpl;
|
||||
import org.whispersystems.textsecuregcm.grpc.StatusConstants;
|
||||
import org.whispersystems.textsecuregcm.grpc.UserAgentInterceptor;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
|
||||
import io.grpc.Metadata;
|
||||
import io.grpc.ManagedChannel;
|
||||
import io.grpc.Server;
|
||||
import io.grpc.ServerBuilder;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import io.grpc.inprocess.InProcessServerBuilder;
|
||||
import io.grpc.inprocess.InProcessChannelBuilder;
|
||||
import io.grpc.stub.MetadataUtils;
|
||||
|
||||
class RemoteDeprecationFilterTest {
|
||||
|
||||
@Test
|
||||
void testEmptyMap() throws IOException, ServletException {
|
||||
// We're happy as long as there's no exception
|
||||
final DynamicConfigurationManager dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
final DynamicRemoteDeprecationConfiguration emptyConfiguration = new DynamicRemoteDeprecationConfiguration();
|
||||
@Test
|
||||
void testEmptyMap() throws IOException, ServletException {
|
||||
// We're happy as long as there's no exception
|
||||
final DynamicConfigurationManager dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
final DynamicRemoteDeprecationConfiguration emptyConfiguration = new DynamicRemoteDeprecationConfiguration();
|
||||
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
when(dynamicConfiguration.getRemoteDeprecationConfiguration()).thenReturn(emptyConfiguration);
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
when(dynamicConfiguration.getRemoteDeprecationConfiguration()).thenReturn(emptyConfiguration);
|
||||
|
||||
final RemoteDeprecationFilter filter = new RemoteDeprecationFilter(dynamicConfigurationManager);
|
||||
final RemoteDeprecationFilter filter = new RemoteDeprecationFilter(dynamicConfigurationManager);
|
||||
|
||||
final HttpServletRequest servletRequest = mock(HttpServletRequest.class);
|
||||
final HttpServletResponse servletResponse = mock(HttpServletResponse.class);
|
||||
final FilterChain filterChain = mock(FilterChain.class);
|
||||
final HttpServletRequest servletRequest = mock(HttpServletRequest.class);
|
||||
final HttpServletResponse servletResponse = mock(HttpServletResponse.class);
|
||||
final FilterChain filterChain = mock(FilterChain.class);
|
||||
|
||||
when(servletRequest.getHeader("UserAgent")).thenReturn("Signal-Android/4.68.3");
|
||||
when(servletRequest.getHeader("UserAgent")).thenReturn("Signal-Android/4.68.3");
|
||||
|
||||
filter.doFilter(servletRequest, servletResponse, filterChain);
|
||||
filter.doFilter(servletRequest, servletResponse, filterChain);
|
||||
|
||||
verify(filterChain).doFilter(servletRequest, servletResponse);
|
||||
verify(servletResponse, never()).sendError(anyInt());
|
||||
verify(filterChain).doFilter(servletRequest, servletResponse);
|
||||
verify(servletResponse, never()).sendError(anyInt());
|
||||
}
|
||||
|
||||
private RemoteDeprecationFilter filterConfiguredForTest() {
|
||||
final EnumMap<ClientPlatform, Semver> minimumVersionsByPlatform = new EnumMap<>(ClientPlatform.class);
|
||||
minimumVersionsByPlatform.put(ClientPlatform.ANDROID, new Semver("1.0.0"));
|
||||
minimumVersionsByPlatform.put(ClientPlatform.IOS, new Semver("1.0.0"));
|
||||
minimumVersionsByPlatform.put(ClientPlatform.DESKTOP, new Semver("1.0.0"));
|
||||
|
||||
final EnumMap<ClientPlatform, Semver> versionsPendingDeprecationByPlatform = new EnumMap<>(ClientPlatform.class);
|
||||
minimumVersionsByPlatform.put(ClientPlatform.ANDROID, new Semver("1.1.0"));
|
||||
minimumVersionsByPlatform.put(ClientPlatform.IOS, new Semver("1.1.0"));
|
||||
minimumVersionsByPlatform.put(ClientPlatform.DESKTOP, new Semver("1.1.0"));
|
||||
|
||||
final EnumMap<ClientPlatform, Set<Semver>> blockedVersionsByPlatform = new EnumMap<>(ClientPlatform.class);
|
||||
blockedVersionsByPlatform.put(ClientPlatform.DESKTOP, Set.of(new Semver("8.0.0-beta.2")));
|
||||
|
||||
final EnumMap<ClientPlatform, Set<Semver>> versionsPendingBlockByPlatform = new EnumMap<>(ClientPlatform.class);
|
||||
versionsPendingBlockByPlatform.put(ClientPlatform.DESKTOP, Set.of(new Semver("8.0.0-beta.3")));
|
||||
|
||||
final DynamicRemoteDeprecationConfiguration remoteDeprecationConfiguration = new DynamicRemoteDeprecationConfiguration();
|
||||
remoteDeprecationConfiguration.setMinimumVersions(minimumVersionsByPlatform);
|
||||
remoteDeprecationConfiguration.setVersionsPendingDeprecation(versionsPendingDeprecationByPlatform);
|
||||
remoteDeprecationConfiguration.setBlockedVersions(blockedVersionsByPlatform);
|
||||
remoteDeprecationConfiguration.setVersionsPendingBlock(versionsPendingBlockByPlatform);
|
||||
remoteDeprecationConfiguration.setUnrecognizedUserAgentAllowed(true);
|
||||
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
final DynamicConfigurationManager dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
|
||||
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
when(dynamicConfiguration.getRemoteDeprecationConfiguration()).thenReturn(remoteDeprecationConfiguration);
|
||||
|
||||
return new RemoteDeprecationFilter(dynamicConfigurationManager);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void testFilter(final String userAgent, final boolean expectDeprecation) throws IOException, ServletException {
|
||||
final HttpServletRequest servletRequest = mock(HttpServletRequest.class);
|
||||
final HttpServletResponse servletResponse = mock(HttpServletResponse.class);
|
||||
final FilterChain filterChain = mock(FilterChain.class);
|
||||
|
||||
when(servletRequest.getHeader(HttpHeaders.USER_AGENT)).thenReturn(userAgent);
|
||||
|
||||
final RemoteDeprecationFilter filter = filterConfiguredForTest();
|
||||
filter.doFilter(servletRequest, servletResponse, filterChain);
|
||||
|
||||
if (expectDeprecation) {
|
||||
verify(filterChain, never()).doFilter(any(), any());
|
||||
verify(servletResponse).sendError(499);
|
||||
} else {
|
||||
verify(filterChain).doFilter(servletRequest, servletResponse);
|
||||
verify(servletResponse, never()).sendError(anyInt());
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource(delimiter = '|', value =
|
||||
{"Unrecognized UA | false",
|
||||
"Signal-Android/4.68.3 | false",
|
||||
"Signal-iOS/3.9.0 | false",
|
||||
"Signal-Desktop/1.2.3 | false",
|
||||
"Signal-Android/0.68.3 | true",
|
||||
"Signal-iOS/0.9.0 | true",
|
||||
"Signal-Desktop/0.2.3 | true",
|
||||
"Signal-Desktop/8.0.0-beta.2 | true",
|
||||
"Signal-Desktop/8.0.0-beta.1 | false",
|
||||
"Signal-iOS/8.0.0-beta.2 | false"})
|
||||
void testFilter(final String userAgent, final boolean expectDeprecation) throws IOException, ServletException {
|
||||
final EnumMap<ClientPlatform, Semver> minimumVersionsByPlatform = new EnumMap<>(ClientPlatform.class);
|
||||
minimumVersionsByPlatform.put(ClientPlatform.ANDROID, new Semver("1.0.0"));
|
||||
minimumVersionsByPlatform.put(ClientPlatform.IOS, new Semver("1.0.0"));
|
||||
minimumVersionsByPlatform.put(ClientPlatform.DESKTOP, new Semver("1.0.0"));
|
||||
@ParameterizedTest
|
||||
@MethodSource(value="testFilter")
|
||||
void testGrpcFilter(final String userAgent, final boolean expectDeprecation) throws Exception {
|
||||
final Server testServer = InProcessServerBuilder.forName("RemoteDeprecationFilterTest")
|
||||
.directExecutor()
|
||||
.addService(new EchoServiceImpl())
|
||||
.intercept(filterConfiguredForTest())
|
||||
.intercept(new UserAgentInterceptor())
|
||||
.build()
|
||||
.start();
|
||||
final ManagedChannel channel = InProcessChannelBuilder.forName("RemoteDeprecationFilterTest")
|
||||
.directExecutor()
|
||||
.userAgent(userAgent)
|
||||
.build();
|
||||
|
||||
final EnumMap<ClientPlatform, Semver> versionsPendingDeprecationByPlatform = new EnumMap<>(ClientPlatform.class);
|
||||
minimumVersionsByPlatform.put(ClientPlatform.ANDROID, new Semver("1.1.0"));
|
||||
minimumVersionsByPlatform.put(ClientPlatform.IOS, new Semver("1.1.0"));
|
||||
minimumVersionsByPlatform.put(ClientPlatform.DESKTOP, new Semver("1.1.0"));
|
||||
|
||||
final EnumMap<ClientPlatform, Set<Semver>> blockedVersionsByPlatform = new EnumMap<>(ClientPlatform.class);
|
||||
blockedVersionsByPlatform.put(ClientPlatform.DESKTOP, Set.of(new Semver("8.0.0-beta.2")));
|
||||
|
||||
final EnumMap<ClientPlatform, Set<Semver>> versionsPendingBlockByPlatform = new EnumMap<>(ClientPlatform.class);
|
||||
versionsPendingBlockByPlatform.put(ClientPlatform.DESKTOP, Set.of(new Semver("8.0.0-beta.3")));
|
||||
|
||||
final DynamicRemoteDeprecationConfiguration remoteDeprecationConfiguration = new DynamicRemoteDeprecationConfiguration();
|
||||
remoteDeprecationConfiguration.setMinimumVersions(minimumVersionsByPlatform);
|
||||
remoteDeprecationConfiguration.setVersionsPendingDeprecation(versionsPendingDeprecationByPlatform);
|
||||
remoteDeprecationConfiguration.setBlockedVersions(blockedVersionsByPlatform);
|
||||
remoteDeprecationConfiguration.setVersionsPendingBlock(versionsPendingBlockByPlatform);
|
||||
remoteDeprecationConfiguration.setUnrecognizedUserAgentAllowed(true);
|
||||
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
final DynamicConfigurationManager dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
|
||||
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
when(dynamicConfiguration.getRemoteDeprecationConfiguration()).thenReturn(remoteDeprecationConfiguration);
|
||||
|
||||
final HttpServletRequest servletRequest = mock(HttpServletRequest.class);
|
||||
final HttpServletResponse servletResponse = mock(HttpServletResponse.class);
|
||||
final FilterChain filterChain = mock(FilterChain.class);
|
||||
|
||||
when(servletRequest.getHeader(HttpHeaders.USER_AGENT)).thenReturn(userAgent);
|
||||
|
||||
final RemoteDeprecationFilter filter = new RemoteDeprecationFilter(dynamicConfigurationManager);
|
||||
filter.doFilter(servletRequest, servletResponse, filterChain);
|
||||
try {
|
||||
final EchoServiceGrpc.EchoServiceBlockingStub client = EchoServiceGrpc.newBlockingStub(channel);
|
||||
|
||||
final EchoRequest req = EchoRequest.newBuilder().setPayload(ByteString.copyFromUtf8("cluck cluck, i'm a parrot")).build();
|
||||
if (expectDeprecation) {
|
||||
verify(filterChain, never()).doFilter(any(), any());
|
||||
verify(servletResponse).sendError(499);
|
||||
final StatusRuntimeException e = assertThrows(
|
||||
StatusRuntimeException.class,
|
||||
() -> client.echo(req));
|
||||
assertEquals(StatusConstants.UPGRADE_NEEDED_STATUS.toString(), e.getStatus().toString());
|
||||
} else {
|
||||
verify(filterChain).doFilter(servletRequest, servletResponse);
|
||||
verify(servletResponse, never()).sendError(anyInt());
|
||||
assertEquals("cluck cluck, i'm a parrot", client.echo(req).getPayload().toStringUtf8());
|
||||
}
|
||||
} finally {
|
||||
testServer.shutdownNow();
|
||||
testServer.awaitTermination();
|
||||
}
|
||||
}
|
||||
|
||||
private static Stream<Arguments> testFilter() {
|
||||
return Stream.of(
|
||||
Arguments.of("Unrecognized UA", false),
|
||||
Arguments.of("Signal-Android/4.68.3", false),
|
||||
Arguments.of("Signal-iOS/3.9.0", false),
|
||||
Arguments.of("Signal-Desktop/1.2.3", false),
|
||||
Arguments.of("Signal-Android/0.68.3", true),
|
||||
Arguments.of("Signal-iOS/0.9.0", true),
|
||||
Arguments.of("Signal-Desktop/0.2.3", true),
|
||||
Arguments.of("Signal-Desktop/8.0.0-beta.2", true),
|
||||
Arguments.of("Signal-Desktop/8.0.0-beta.1", false),
|
||||
Arguments.of("Signal-iOS/8.0.0-beta.2", false));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import io.grpc.stub.StreamObserver;
|
||||
import org.signal.chat.rpc.EchoServiceGrpc;
|
||||
import org.signal.chat.rpc.EchoRequest;
|
||||
import org.signal.chat.rpc.EchoResponse;
|
||||
|
||||
public class EchoServiceImpl extends EchoServiceGrpc.EchoServiceImplBase {
|
||||
@Override
|
||||
public void echo(EchoRequest req, StreamObserver<EchoResponse> responseObserver) {
|
||||
responseObserver.onNext(EchoResponse.newBuilder().setPayload(req.getPayload()).build());
|
||||
responseObserver.onCompleted();
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.vdurmont.semver4j.Semver;
|
||||
import io.grpc.ManagedChannel;
|
||||
import io.grpc.Metadata;
|
||||
import io.grpc.Server;
|
||||
import io.grpc.inprocess.InProcessChannelBuilder;
|
||||
import io.grpc.inprocess.InProcessServerBuilder;
|
||||
import io.grpc.stub.MetadataUtils;
|
||||
import io.grpc.stub.StreamObserver;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.signal.chat.rpc.EchoRequest;
|
||||
import org.signal.chat.rpc.EchoResponse;
|
||||
import org.signal.chat.rpc.EchoServiceGrpc;
|
||||
import org.whispersystems.textsecuregcm.grpc.EchoServiceImpl;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UserAgent;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class UserAgentInterceptorTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void testInterceptor(final String header, final ClientPlatform platform, final String version) throws Exception {
|
||||
|
||||
final AtomicReference<UserAgent> observedUserAgent = new AtomicReference<>(null);
|
||||
final EchoServiceImpl serviceImpl = new EchoServiceImpl() {
|
||||
@Override
|
||||
public void echo(EchoRequest req, StreamObserver<EchoResponse> responseObserver) {
|
||||
observedUserAgent.set(UserAgentUtil.userAgentFromGrpcContext());
|
||||
super.echo(req, responseObserver);
|
||||
}
|
||||
};
|
||||
|
||||
final Server testServer = InProcessServerBuilder.forName("RemoteDeprecationFilterTest")
|
||||
.directExecutor()
|
||||
.addService(serviceImpl)
|
||||
.intercept(new UserAgentInterceptor())
|
||||
.build()
|
||||
.start();
|
||||
|
||||
try {
|
||||
final ManagedChannel channel = InProcessChannelBuilder.forName("RemoteDeprecationFilterTest")
|
||||
.directExecutor()
|
||||
.userAgent(header)
|
||||
.build();
|
||||
|
||||
final EchoServiceGrpc.EchoServiceBlockingStub client = EchoServiceGrpc.newBlockingStub(channel);
|
||||
|
||||
final EchoRequest req = EchoRequest.newBuilder().setPayload(ByteString.copyFromUtf8("cluck cluck, i'm a parrot")).build();
|
||||
assertEquals("cluck cluck, i'm a parrot", client.echo(req).getPayload().toStringUtf8());
|
||||
if (platform == null) {
|
||||
assertNull(observedUserAgent.get());
|
||||
} else {
|
||||
assertEquals(platform, observedUserAgent.get().getPlatform());
|
||||
assertEquals(new Semver(version), observedUserAgent.get().getVersion());
|
||||
// can't assert on the additional specifiers because they include internal details of the grpc in-process channel itself
|
||||
}
|
||||
} finally {
|
||||
testServer.shutdownNow();
|
||||
testServer.awaitTermination();
|
||||
}
|
||||
}
|
||||
|
||||
private static Stream<Arguments> testInterceptor() {
|
||||
return Stream.of(
|
||||
Arguments.of(null, null, null),
|
||||
Arguments.of("", null, null),
|
||||
Arguments.of("Unrecognized UA", null, null),
|
||||
Arguments.of("Signal-Android/4.68.3", ClientPlatform.ANDROID, "4.68.3"),
|
||||
Arguments.of("Signal-iOS/3.9.0", ClientPlatform.IOS, "3.9.0"),
|
||||
Arguments.of("Signal-Desktop/1.2.3", ClientPlatform.DESKTOP, "1.2.3"),
|
||||
Arguments.of("Signal-Desktop/8.0.0-beta.2", ClientPlatform.DESKTOP, "8.0.0-beta.2"),
|
||||
Arguments.of("Signal-iOS/8.0.0-beta.2", ClientPlatform.IOS, "8.0.0-beta.2"));
|
||||
}
|
||||
}
|
||||
-44
@@ -69,50 +69,6 @@ public class RateLimitersLuaScriptTest {
|
||||
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, Duration.ofSeconds(1))),
|
||||
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;
|
||||
|
||||
+6
-26
@@ -31,13 +31,11 @@ import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicScheduledApnNotificationSendingConfiguration;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
|
||||
@@ -81,17 +79,8 @@ class ApnPushNotificationSchedulerTest {
|
||||
apnSender = mock(APNSender.class);
|
||||
clock = TestClock.now();
|
||||
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = mock(
|
||||
DynamicConfigurationManager.class);
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
final DynamicScheduledApnNotificationSendingConfiguration scheduledApnNotificationSendingConfiguration = new DynamicScheduledApnNotificationSendingConfiguration(
|
||||
true, true);
|
||||
when(dynamicConfiguration.getScheduledApnNotificationSendingConfiguration()).thenReturn(
|
||||
scheduledApnNotificationSendingConfiguration);
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
|
||||
apnPushNotificationScheduler = new ApnPushNotificationScheduler(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
apnSender, accountsManager, clock, Optional.empty(), dynamicConfigurationManager);
|
||||
apnSender, accountsManager, clock, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -236,30 +225,21 @@ class ApnPushNotificationSchedulerTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"true, false, true, true",
|
||||
"true, true, false, false",
|
||||
"false, true, false, true",
|
||||
"false, false, true, false"
|
||||
"1, true",
|
||||
"0, false",
|
||||
})
|
||||
void testDedicatedProcessDynamicConfiguration(final boolean dedicatedProcess, final boolean enabledForServer,
|
||||
final boolean enabledForDedicatedProcess, final boolean expectActivity) throws Exception {
|
||||
void testDedicatedProcessDynamicConfiguration(final int dedicatedThreadCount, final boolean expectActivity)
|
||||
throws Exception {
|
||||
|
||||
final FaultTolerantRedisCluster redisCluster = mock(FaultTolerantRedisCluster.class);
|
||||
when(redisCluster.withCluster(any())).thenReturn(0L);
|
||||
|
||||
final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = mock(
|
||||
DynamicConfigurationManager.class);
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
final DynamicScheduledApnNotificationSendingConfiguration scheduledApnNotificationSendingConfiguration = new DynamicScheduledApnNotificationSendingConfiguration(
|
||||
enabledForServer, enabledForDedicatedProcess);
|
||||
when(dynamicConfiguration.getScheduledApnNotificationSendingConfiguration()).thenReturn(
|
||||
scheduledApnNotificationSendingConfiguration);
|
||||
|
||||
apnPushNotificationScheduler = new ApnPushNotificationScheduler(redisCluster, apnSender,
|
||||
accountsManager, dedicatedProcess ? Optional.of(4) : Optional.empty(), dynamicConfigurationManager);
|
||||
accountsManager, dedicatedThreadCount);
|
||||
|
||||
apnPushNotificationScheduler.start();
|
||||
apnPushNotificationScheduler.stop();
|
||||
|
||||
+19
-7
@@ -15,15 +15,17 @@ import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Collections;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicPushLatencyConfiguration;
|
||||
import org.whispersystems.textsecuregcm.push.PushLatencyManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushLatencyManager.PushRecord;
|
||||
import org.whispersystems.textsecuregcm.push.PushLatencyManager.PushType;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
@@ -49,8 +51,8 @@ class PushLatencyManagerTest {
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void testTakeRecord(final boolean isVoip) throws ExecutionException, InterruptedException {
|
||||
@MethodSource
|
||||
void testTakeRecord(final boolean isVoip, final boolean isUrgent) throws ExecutionException, InterruptedException {
|
||||
final UUID accountUuid = UUID.randomUUID();
|
||||
final long deviceId = 1;
|
||||
|
||||
@@ -61,14 +63,24 @@ class PushLatencyManagerTest {
|
||||
|
||||
assertNull(pushLatencyManager.takePushRecord(accountUuid, deviceId).get());
|
||||
|
||||
pushLatencyManager.recordPushSent(accountUuid, deviceId, isVoip);
|
||||
pushLatencyManager.recordPushSent(accountUuid, deviceId, isVoip, isUrgent);
|
||||
|
||||
final PushRecord pushRecord = pushLatencyManager.takePushRecord(accountUuid, deviceId).get();
|
||||
|
||||
assertNotNull(pushRecord);
|
||||
assertEquals(pushTimestamp, pushRecord.getTimestamp());
|
||||
assertEquals(isVoip ? PushType.VOIP : PushType.STANDARD, pushRecord.getPushType());
|
||||
assertEquals(pushTimestamp, pushRecord.timestamp());
|
||||
assertEquals(isVoip ? PushType.VOIP : PushType.STANDARD, pushRecord.pushType());
|
||||
assertEquals(Optional.of(isUrgent), pushRecord.urgent());
|
||||
|
||||
assertNull(pushLatencyManager.takePushRecord(accountUuid, deviceId).get());
|
||||
}
|
||||
|
||||
private static Stream<Arguments> testTakeRecord() {
|
||||
return Stream.of(
|
||||
Arguments.of(true, true),
|
||||
Arguments.of(true, false),
|
||||
Arguments.of(false, true),
|
||||
Arguments.of(false, false)
|
||||
);
|
||||
}
|
||||
}
|
||||
+97
-55
@@ -7,6 +7,7 @@ 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.assertTimeoutPreemptively;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
@@ -22,81 +23,122 @@ import io.lettuce.core.cluster.pubsub.StatefulRedisClusterPubSubConnection;
|
||||
import io.lettuce.core.event.EventBus;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
class FaultTolerantRedisClusterTest {
|
||||
|
||||
private RedisAdvancedClusterCommands<String, String> clusterCommands;
|
||||
private FaultTolerantRedisCluster faultTolerantCluster;
|
||||
private RedisAdvancedClusterCommands<String, String> clusterCommands;
|
||||
private FaultTolerantRedisCluster faultTolerantCluster;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
final RedisClusterClient clusterClient = mock(RedisClusterClient.class);
|
||||
final StatefulRedisClusterConnection<String, String> clusterConnection = mock(StatefulRedisClusterConnection.class);
|
||||
final StatefulRedisClusterPubSubConnection<String, String> pubSubConnection = mock(StatefulRedisClusterPubSubConnection.class);
|
||||
final ClientResources clientResources = mock(ClientResources.class);
|
||||
final EventBus eventBus = mock(EventBus.class);
|
||||
@SuppressWarnings("unchecked")
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
final RedisClusterClient clusterClient = mock(RedisClusterClient.class);
|
||||
final StatefulRedisClusterConnection<String, String> clusterConnection = mock(StatefulRedisClusterConnection.class);
|
||||
final StatefulRedisClusterPubSubConnection<String, String> pubSubConnection = mock(
|
||||
StatefulRedisClusterPubSubConnection.class);
|
||||
final ClientResources clientResources = mock(ClientResources.class);
|
||||
final EventBus eventBus = mock(EventBus.class);
|
||||
|
||||
clusterCommands = mock(RedisAdvancedClusterCommands.class);
|
||||
clusterCommands = mock(RedisAdvancedClusterCommands.class);
|
||||
|
||||
when(clusterClient.connect()).thenReturn(clusterConnection);
|
||||
when(clusterClient.connectPubSub()).thenReturn(pubSubConnection);
|
||||
when(clusterClient.getResources()).thenReturn(clientResources);
|
||||
when(clusterConnection.sync()).thenReturn(clusterCommands);
|
||||
when(clientResources.eventBus()).thenReturn(eventBus);
|
||||
when(eventBus.get()).thenReturn(mock(Flux.class));
|
||||
when(clusterClient.connect()).thenReturn(clusterConnection);
|
||||
when(clusterClient.connectPubSub()).thenReturn(pubSubConnection);
|
||||
when(clusterClient.getResources()).thenReturn(clientResources);
|
||||
when(clusterConnection.sync()).thenReturn(clusterCommands);
|
||||
when(clientResources.eventBus()).thenReturn(eventBus);
|
||||
when(eventBus.get()).thenReturn(mock(Flux.class));
|
||||
|
||||
final CircuitBreakerConfiguration breakerConfiguration = new CircuitBreakerConfiguration();
|
||||
breakerConfiguration.setFailureRateThreshold(100);
|
||||
breakerConfiguration.setSlidingWindowSize(1);
|
||||
breakerConfiguration.setSlidingWindowMinimumNumberOfCalls(1);
|
||||
breakerConfiguration.setWaitDurationInOpenStateInSeconds(Integer.MAX_VALUE);
|
||||
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(0);
|
||||
final RetryConfiguration retryConfiguration = new RetryConfiguration();
|
||||
retryConfiguration.setMaxAttempts(3);
|
||||
retryConfiguration.setWaitDuration(0);
|
||||
|
||||
faultTolerantCluster = new FaultTolerantRedisCluster("test", clusterClient, Duration.ofSeconds(2),
|
||||
breakerConfiguration, retryConfiguration);
|
||||
faultTolerantCluster = new FaultTolerantRedisCluster("test", clusterClient, Duration.ofSeconds(2),
|
||||
breakerConfiguration, retryConfiguration);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testBreaker() {
|
||||
when(clusterCommands.get(anyString()))
|
||||
.thenReturn("value")
|
||||
.thenThrow(new RuntimeException("Badness has ensued."));
|
||||
|
||||
assertEquals("value", faultTolerantCluster.withCluster(connection -> connection.sync().get("key")));
|
||||
|
||||
assertThrows(RedisException.class,
|
||||
() -> faultTolerantCluster.withCluster(connection -> connection.sync().get("OH NO")));
|
||||
|
||||
final RedisException redisException = assertThrows(RedisException.class,
|
||||
() -> faultTolerantCluster.withCluster(connection -> connection.sync().get("OH NO")));
|
||||
|
||||
assertTrue(redisException.getCause() instanceof CallNotPermittedException);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRetry() {
|
||||
when(clusterCommands.get(anyString()))
|
||||
.thenThrow(new RedisCommandTimeoutException())
|
||||
.thenThrow(new RedisCommandTimeoutException())
|
||||
.thenReturn("value");
|
||||
|
||||
assertEquals("value", faultTolerantCluster.withCluster(connection -> connection.sync().get("key")));
|
||||
|
||||
when(clusterCommands.get(anyString()))
|
||||
.thenThrow(new RedisCommandTimeoutException())
|
||||
.thenThrow(new RedisCommandTimeoutException())
|
||||
.thenThrow(new RedisCommandTimeoutException())
|
||||
.thenReturn("value");
|
||||
|
||||
assertThrows(RedisCommandTimeoutException.class,
|
||||
() -> faultTolerantCluster.withCluster(connection -> connection.sync().get("key")));
|
||||
|
||||
}
|
||||
|
||||
@Nested
|
||||
class WithRealCluster {
|
||||
|
||||
private static final Duration TIMEOUT = Duration.ofMillis(50);
|
||||
|
||||
private static final RetryConfiguration retryConfiguration = new RetryConfiguration();
|
||||
|
||||
static {
|
||||
retryConfiguration.setMaxAttempts(1);
|
||||
retryConfiguration.setWaitDuration(50);
|
||||
}
|
||||
|
||||
@RegisterExtension
|
||||
static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder()
|
||||
.retryConfiguration(retryConfiguration)
|
||||
.timeout(TIMEOUT)
|
||||
.build();
|
||||
|
||||
@Test
|
||||
void testBreaker() {
|
||||
when(clusterCommands.get(anyString()))
|
||||
.thenReturn("value")
|
||||
.thenThrow(new RuntimeException("Badness has ensued."));
|
||||
void testTimeout() {
|
||||
final FaultTolerantRedisCluster cluster = REDIS_CLUSTER_EXTENSION.getRedisCluster();
|
||||
|
||||
assertEquals("value", faultTolerantCluster.withCluster(connection -> connection.sync().get("key")));
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(1), () -> {
|
||||
final ExecutionException asyncException = assertThrows(ExecutionException.class,
|
||||
() -> cluster.withCluster(connection -> connection.async().blpop(TIMEOUT.toMillis() * 2, "key")).get());
|
||||
assertTrue(asyncException.getCause() instanceof RedisCommandTimeoutException);
|
||||
|
||||
assertThrows(RedisException.class,
|
||||
() -> faultTolerantCluster.withCluster(connection -> connection.sync().get("OH NO")));
|
||||
assertThrows(RedisCommandTimeoutException.class,
|
||||
() -> cluster.withCluster(connection -> connection.sync().blpop(TIMEOUT.toMillis() * 2, "key")));
|
||||
});
|
||||
|
||||
final RedisException redisException = assertThrows(RedisException.class,
|
||||
() -> faultTolerantCluster.withCluster(connection -> connection.sync().get("OH NO")));
|
||||
|
||||
assertTrue(redisException.getCause() instanceof CallNotPermittedException);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRetry() {
|
||||
when(clusterCommands.get(anyString()))
|
||||
.thenThrow(new RedisCommandTimeoutException())
|
||||
.thenThrow(new RedisCommandTimeoutException())
|
||||
.thenReturn("value");
|
||||
|
||||
assertEquals("value", faultTolerantCluster.withCluster(connection -> connection.sync().get("key")));
|
||||
|
||||
when(clusterCommands.get(anyString()))
|
||||
.thenThrow(new RedisCommandTimeoutException())
|
||||
.thenThrow(new RedisCommandTimeoutException())
|
||||
.thenThrow(new RedisCommandTimeoutException())
|
||||
.thenReturn("value");
|
||||
|
||||
assertThrows(RedisCommandTimeoutException.class, () -> faultTolerantCluster.withCluster(connection -> connection.sync().get("key")));
|
||||
}
|
||||
}
|
||||
+26
-4
@@ -32,14 +32,23 @@ import org.whispersystems.textsecuregcm.util.RedisClusterUtil;
|
||||
import redis.embedded.RedisServer;
|
||||
import redis.embedded.exceptions.EmbeddedRedisException;
|
||||
|
||||
public class RedisClusterExtension implements BeforeAllCallback, BeforeEachCallback, AfterAllCallback, AfterEachCallback {
|
||||
public class RedisClusterExtension implements BeforeAllCallback, BeforeEachCallback, AfterAllCallback,
|
||||
AfterEachCallback {
|
||||
|
||||
private static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(2);
|
||||
private static final int NODE_COUNT = 2;
|
||||
|
||||
private static final RedisServer[] CLUSTER_NODES = new RedisServer[NODE_COUNT];
|
||||
|
||||
private final Duration timeout;
|
||||
private final RetryConfiguration retryConfiguration;
|
||||
private FaultTolerantRedisCluster redisCluster;
|
||||
|
||||
public RedisClusterExtension(final Duration timeout, final RetryConfiguration retryConfiguration) {
|
||||
this.timeout = timeout;
|
||||
this.retryConfiguration = retryConfiguration;
|
||||
}
|
||||
|
||||
|
||||
public static RedisClusterExtensionBuilder builder() {
|
||||
return new RedisClusterExtensionBuilder();
|
||||
@@ -78,9 +87,9 @@ public class RedisClusterExtension implements BeforeAllCallback, BeforeEachCallb
|
||||
|
||||
redisCluster = new FaultTolerantRedisCluster("test-cluster",
|
||||
RedisClusterClient.create(urls.stream().map(RedisURI::create).collect(Collectors.toList())),
|
||||
Duration.ofSeconds(2),
|
||||
timeout,
|
||||
new CircuitBreakerConfiguration(),
|
||||
new RetryConfiguration());
|
||||
retryConfiguration);
|
||||
|
||||
redisCluster.useCluster(connection -> {
|
||||
boolean setAll = false;
|
||||
@@ -208,11 +217,24 @@ public class RedisClusterExtension implements BeforeAllCallback, BeforeEachCallb
|
||||
|
||||
public static class RedisClusterExtensionBuilder {
|
||||
|
||||
private Duration timeout = DEFAULT_TIMEOUT;
|
||||
private RetryConfiguration retryConfiguration = new RetryConfiguration();
|
||||
|
||||
private RedisClusterExtensionBuilder() {
|
||||
}
|
||||
|
||||
RedisClusterExtensionBuilder timeout(Duration timeout) {
|
||||
this.timeout = timeout;
|
||||
return this;
|
||||
}
|
||||
|
||||
RedisClusterExtensionBuilder retryConfiguration(RetryConfiguration retryConfiguration) {
|
||||
this.retryConfiguration = retryConfiguration;
|
||||
return this;
|
||||
}
|
||||
|
||||
public RedisClusterExtension build() {
|
||||
return new RedisClusterExtension();
|
||||
return new RedisClusterExtension(timeout, retryConfiguration);
|
||||
}
|
||||
}
|
||||
}
|
||||
+54
-49
@@ -21,6 +21,7 @@ import java.util.UUID;
|
||||
import java.util.concurrent.CompletionException;
|
||||
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;
|
||||
@@ -36,6 +37,7 @@ class SecureBackupClientTest {
|
||||
private UUID accountUuid;
|
||||
private ExternalServiceCredentialsGenerator credentialsGenerator;
|
||||
private ExecutorService httpExecutor;
|
||||
private ScheduledExecutorService retryExecutor;
|
||||
|
||||
private SecureBackupClient secureStorageClient;
|
||||
|
||||
@@ -46,68 +48,71 @@ class SecureBackupClientTest {
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws CertificateException {
|
||||
accountUuid = UUID.randomUUID();
|
||||
accountUuid = UUID.randomUUID();
|
||||
credentialsGenerator = mock(ExternalServiceCredentialsGenerator.class);
|
||||
httpExecutor = Executors.newSingleThreadExecutor();
|
||||
httpExecutor = Executors.newSingleThreadExecutor();
|
||||
retryExecutor = Executors.newSingleThreadScheduledExecutor();
|
||||
|
||||
final SecureBackupServiceConfiguration config = new SecureBackupServiceConfiguration();
|
||||
config.setUri("http://localhost:" + wireMock.getPort());
|
||||
|
||||
// This is a randomly-generated, throwaway certificate that's not actually connected to anything
|
||||
config.setBackupCaCertificates(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-----
|
||||
"""));
|
||||
config.setBackupCaCertificates(
|
||||
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-----
|
||||
"""));
|
||||
|
||||
secureStorageClient = new SecureBackupClient(credentialsGenerator, httpExecutor, config);
|
||||
secureStorageClient = new SecureBackupClient(credentialsGenerator, httpExecutor, retryExecutor, config);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws InterruptedException {
|
||||
httpExecutor.shutdown();
|
||||
httpExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
retryExecutor.shutdown();
|
||||
retryExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+103
-93
@@ -22,6 +22,7 @@ import java.util.UUID;
|
||||
import java.util.concurrent.CompletionException;
|
||||
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;
|
||||
@@ -36,111 +37,120 @@ import org.whispersystems.textsecuregcm.configuration.SecureStorageServiceConfig
|
||||
|
||||
class SecureStorageClientTest {
|
||||
|
||||
private UUID accountUuid;
|
||||
private ExternalServiceCredentialsGenerator credentialsGenerator;
|
||||
private ExecutorService httpExecutor;
|
||||
private UUID accountUuid;
|
||||
private ExternalServiceCredentialsGenerator credentialsGenerator;
|
||||
private ExecutorService httpExecutor;
|
||||
private ScheduledExecutorService retryExecutor;
|
||||
|
||||
private SecureStorageClient secureStorageClient;
|
||||
private SecureStorageClient secureStorageClient;
|
||||
|
||||
@RegisterExtension
|
||||
private final WireMockExtension wireMock = WireMockExtension.newInstance()
|
||||
.options(wireMockConfig().dynamicPort().dynamicHttpsPort())
|
||||
.build();
|
||||
@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();
|
||||
@BeforeEach
|
||||
void setUp() throws CertificateException {
|
||||
accountUuid = UUID.randomUUID();
|
||||
credentialsGenerator = mock(ExternalServiceCredentialsGenerator.class);
|
||||
httpExecutor = Executors.newSingleThreadExecutor();
|
||||
retryExecutor = Executors.newSingleThreadScheduledExecutor();
|
||||
|
||||
final SecureStorageServiceConfiguration config = new SecureStorageServiceConfiguration(
|
||||
randomSecretBytes(32),
|
||||
"http://localhost:" + wireMock.getPort(),
|
||||
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-----
|
||||
"""),
|
||||
new CircuitBreakerConfiguration(),
|
||||
new RetryConfiguration());
|
||||
final SecureStorageServiceConfiguration config = new SecureStorageServiceConfiguration(
|
||||
randomSecretBytes(32),
|
||||
"http://localhost:" + wireMock.getPort(),
|
||||
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-----
|
||||
"""),
|
||||
new CircuitBreakerConfiguration(),
|
||||
new RetryConfiguration());
|
||||
|
||||
secureStorageClient = new SecureStorageClient(credentialsGenerator, httpExecutor, config);
|
||||
}
|
||||
secureStorageClient = new SecureStorageClient(credentialsGenerator, httpExecutor, retryExecutor, config);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws InterruptedException {
|
||||
httpExecutor.shutdown();
|
||||
httpExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
}
|
||||
@AfterEach
|
||||
void tearDown() throws InterruptedException {
|
||||
|
||||
@Test
|
||||
void deleteStoredData() {
|
||||
final String username = RandomStringUtils.randomAlphabetic(16);
|
||||
final String password = RandomStringUtils.randomAlphanumeric(32);
|
||||
httpExecutor.shutdown();
|
||||
httpExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
retryExecutor.shutdown();
|
||||
retryExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
when(credentialsGenerator.generateForUuid(accountUuid)).thenReturn(new ExternalServiceCredentials(username, password));
|
||||
@Test
|
||||
void deleteStoredData() {
|
||||
|
||||
wireMock.stubFor(delete(urlEqualTo(SecureStorageClient.DELETE_PATH))
|
||||
.withBasicAuth(username, password)
|
||||
.willReturn(aResponse().withStatus(202)));
|
||||
final String username = RandomStringUtils.randomAlphabetic(16);
|
||||
final String password = RandomStringUtils.randomAlphanumeric(32);
|
||||
|
||||
// We're happy as long as this doesn't throw an exception
|
||||
secureStorageClient.deleteStoredData(accountUuid).join();
|
||||
}
|
||||
when(credentialsGenerator.generateForUuid(accountUuid)).thenReturn(
|
||||
new ExternalServiceCredentials(username, password));
|
||||
|
||||
@Test
|
||||
void deleteStoredDataFailure() {
|
||||
final String username = RandomStringUtils.randomAlphabetic(16);
|
||||
final String password = RandomStringUtils.randomAlphanumeric(32);
|
||||
wireMock.stubFor(delete(urlEqualTo(SecureStorageClient.DELETE_PATH))
|
||||
.withBasicAuth(username, password)
|
||||
.willReturn(aResponse().withStatus(202)));
|
||||
|
||||
when(credentialsGenerator.generateForUuid(accountUuid)).thenReturn(new ExternalServiceCredentials(username, password));
|
||||
// We're happy as long as this doesn't throw an exception
|
||||
secureStorageClient.deleteStoredData(accountUuid).join();
|
||||
}
|
||||
|
||||
wireMock.stubFor(delete(urlEqualTo(SecureStorageClient.DELETE_PATH))
|
||||
.withBasicAuth(username, password)
|
||||
.willReturn(aResponse().withStatus(400)));
|
||||
@Test
|
||||
void deleteStoredDataFailure() {
|
||||
|
||||
final CompletionException completionException = assertThrows(CompletionException.class, () -> secureStorageClient.deleteStoredData(accountUuid).join());
|
||||
assertTrue(completionException.getCause() instanceof SecureStorageException);
|
||||
}
|
||||
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(SecureStorageClient.DELETE_PATH))
|
||||
.withBasicAuth(username, password)
|
||||
.willReturn(aResponse().withStatus(400)));
|
||||
|
||||
final CompletionException completionException = assertThrows(CompletionException.class,
|
||||
() -> secureStorageClient.deleteStoredData(accountUuid).join());
|
||||
assertTrue(completionException.getCause() instanceof SecureStorageException);
|
||||
}
|
||||
}
|
||||
+7
-1
@@ -23,6 +23,7 @@ import java.util.UUID;
|
||||
import java.util.concurrent.CompletionException;
|
||||
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;
|
||||
@@ -38,6 +39,7 @@ class SecureValueRecovery2ClientTest {
|
||||
private UUID accountUuid;
|
||||
private ExternalServiceCredentialsGenerator credentialsGenerator;
|
||||
private ExecutorService httpExecutor;
|
||||
private ScheduledExecutorService retryExecutor;
|
||||
|
||||
private SecureValueRecovery2Client secureValueRecovery2Client;
|
||||
|
||||
@@ -51,6 +53,7 @@ class SecureValueRecovery2ClientTest {
|
||||
accountUuid = UUID.randomUUID();
|
||||
credentialsGenerator = mock(ExternalServiceCredentialsGenerator.class);
|
||||
httpExecutor = Executors.newSingleThreadExecutor();
|
||||
retryExecutor = Executors.newSingleThreadScheduledExecutor();
|
||||
|
||||
final SecureValueRecovery2Configuration config = new SecureValueRecovery2Configuration(
|
||||
"http://localhost:" + wireMock.getPort(),
|
||||
@@ -104,13 +107,16 @@ class SecureValueRecovery2ClientTest {
|
||||
"""),
|
||||
null, null);
|
||||
|
||||
secureValueRecovery2Client = new SecureValueRecovery2Client(credentialsGenerator, httpExecutor, config);
|
||||
secureValueRecovery2Client = new SecureValueRecovery2Client(credentialsGenerator, httpExecutor, retryExecutor,
|
||||
config);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws InterruptedException {
|
||||
httpExecutor.shutdown();
|
||||
httpExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
retryExecutor.shutdown();
|
||||
retryExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+1
-1
@@ -77,7 +77,7 @@ class AccountCleanerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAccounts() throws AccountDatabaseCrawlerRestartException, InterruptedException {
|
||||
void testAccounts() throws InterruptedException {
|
||||
AccountCleaner accountCleaner = new AccountCleaner(accountsManager, deletionExecutor);
|
||||
accountCleaner.onCrawlStart();
|
||||
accountCleaner.timeAndProcessCrawlChunk(Optional.empty(),
|
||||
|
||||
+1
-49
@@ -7,9 +7,7 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -20,8 +18,6 @@ import java.util.UUID;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicAccountDatabaseCrawlerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
|
||||
class AccountDatabaseCrawlerIntegrationTest {
|
||||
@@ -60,54 +56,10 @@ class AccountDatabaseCrawlerIntegrationTest {
|
||||
.thenReturn(new AccountCrawlChunk(List.of(secondAccount), SECOND_UUID))
|
||||
.thenReturn(new AccountCrawlChunk(Collections.emptyList(), null));
|
||||
|
||||
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = mock(
|
||||
DynamicConfigurationManager.class);
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
DynamicAccountDatabaseCrawlerConfiguration accountDatabaseCrawlerConfiguration = new DynamicAccountDatabaseCrawlerConfiguration(
|
||||
true, true);
|
||||
when(dynamicConfiguration.getAccountDatabaseCrawlerConfiguration()).thenReturn(accountDatabaseCrawlerConfiguration);
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
|
||||
final AccountDatabaseCrawlerCache crawlerCache = new AccountDatabaseCrawlerCache(
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster(), "test");
|
||||
accountDatabaseCrawler = new AccountDatabaseCrawler("test", accountsManager, crawlerCache, List.of(listener),
|
||||
CHUNK_SIZE, dynamicConfigurationManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCrawlUninterrupted() throws AccountDatabaseCrawlerRestartException {
|
||||
accountDatabaseCrawler.doPeriodicWork();
|
||||
accountDatabaseCrawler.doPeriodicWork();
|
||||
accountDatabaseCrawler.doPeriodicWork();
|
||||
|
||||
verify(accountsManager).getAllFromDynamo(CHUNK_SIZE);
|
||||
verify(accountsManager).getAllFromDynamo(FIRST_UUID, CHUNK_SIZE);
|
||||
verify(accountsManager).getAllFromDynamo(SECOND_UUID, CHUNK_SIZE);
|
||||
|
||||
verify(listener).onCrawlStart();
|
||||
verify(listener).timeAndProcessCrawlChunk(Optional.empty(), List.of(firstAccount));
|
||||
verify(listener).timeAndProcessCrawlChunk(Optional.of(FIRST_UUID), List.of(secondAccount));
|
||||
verify(listener).onCrawlEnd();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCrawlWithReset() throws AccountDatabaseCrawlerRestartException {
|
||||
doThrow(new AccountDatabaseCrawlerRestartException("OH NO")).doNothing()
|
||||
.when(listener).timeAndProcessCrawlChunk(Optional.empty(), List.of(firstAccount));
|
||||
|
||||
accountDatabaseCrawler.doPeriodicWork();
|
||||
accountDatabaseCrawler.doPeriodicWork();
|
||||
accountDatabaseCrawler.doPeriodicWork();
|
||||
accountDatabaseCrawler.doPeriodicWork();
|
||||
|
||||
verify(accountsManager, times(2)).getAllFromDynamo(CHUNK_SIZE);
|
||||
verify(accountsManager).getAllFromDynamo(FIRST_UUID, CHUNK_SIZE);
|
||||
verify(accountsManager).getAllFromDynamo(SECOND_UUID, CHUNK_SIZE);
|
||||
|
||||
verify(listener, times(2)).onCrawlStart();
|
||||
verify(listener, times(2)).timeAndProcessCrawlChunk(Optional.empty(), List.of(firstAccount));
|
||||
verify(listener).timeAndProcessCrawlChunk(Optional.of(FIRST_UUID), List.of(secondAccount));
|
||||
verify(listener).onCrawlEnd();
|
||||
CHUNK_SIZE);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+1
-1
@@ -83,7 +83,7 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
deletedAccounts = new DeletedAccounts(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
|
||||
Tables.DELETED_ACCOUNTS.tableName());
|
||||
|
||||
final AccountLockManager accountLockManager = new AccountLockManager(DYNAMO_DB_EXTENSION.getLegacyDynamoClient(),
|
||||
final AccountLockManager accountLockManager = new AccountLockManager(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
|
||||
Tables.DELETED_ACCOUNTS_LOCK.tableName());
|
||||
|
||||
final SecureStorageClient secureStorageClient = mock(SecureStorageClient.class);
|
||||
|
||||
+3
@@ -709,6 +709,7 @@ class AccountsManagerTest {
|
||||
verify(keysManager).delete(originalPni);
|
||||
verify(keysManager, atLeastOnce()).delete(targetPni);
|
||||
verify(keysManager).delete(newPni);
|
||||
verify(keysManager).storeEcSignedPreKeys(eq(newPni), any());
|
||||
verifyNoMoreInteractions(keysManager);
|
||||
}
|
||||
|
||||
@@ -748,6 +749,7 @@ class AccountsManagerTest {
|
||||
verify(keysManager).delete(newPni);
|
||||
verify(keysManager).delete(originalPni);
|
||||
verify(keysManager).getPqEnabledDevices(uuid);
|
||||
verify(keysManager).storeEcSignedPreKeys(newPni, newSignedKeys);
|
||||
verify(keysManager).storePqLastResort(eq(newPni), eq(Map.of(1L, newSignedPqKeys.get(1L))));
|
||||
verifyNoMoreInteractions(keysManager);
|
||||
}
|
||||
@@ -852,6 +854,7 @@ class AccountsManagerTest {
|
||||
verifyNoInteractions(deletedAccounts);
|
||||
|
||||
verify(keysManager).delete(oldPni);
|
||||
verify(keysManager).storeEcSignedPreKeys(oldPni, newSignedKeys);
|
||||
|
||||
// only the pq key for the already-pq-enabled device should be saved
|
||||
verify(keysManager).storePqLastResort(eq(oldPni), eq(Map.of(1L, newSignedPqKeys.get(1L))));
|
||||
|
||||
@@ -11,6 +11,7 @@ import static org.assertj.core.api.Assertions.assertThatNoException;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
@@ -36,6 +37,7 @@ import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.stream.Collectors;
|
||||
import org.apache.commons.lang3.RandomUtils;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -492,6 +494,23 @@ class AccountsTest {
|
||||
assertThat(users).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAll() {
|
||||
final List<Account> expectedAccounts = new ArrayList<>();
|
||||
|
||||
for (int i = 1; i <= 100; i++) {
|
||||
final Account account = generateAccount("+1" + String.format("%03d", i), UUID.randomUUID(), UUID.randomUUID());
|
||||
expectedAccounts.add(account);
|
||||
accounts.create(account);
|
||||
}
|
||||
|
||||
final List<Account> retrievedAccounts = accounts.getAll(2).collectList().block();
|
||||
|
||||
assertNotNull(retrievedAccounts);
|
||||
assertEquals(expectedAccounts.stream().map(Account::getUuid).collect(Collectors.toSet()),
|
||||
retrievedAccounts.stream().map(Account::getUuid).collect(Collectors.toSet()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDelete() {
|
||||
final Device deletedDevice = generateDevice(1);
|
||||
|
||||
+1
-16
@@ -6,16 +6,10 @@
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.almworks.sqlite4java.SQLite;
|
||||
import com.amazonaws.auth.AWSStaticCredentialsProvider;
|
||||
import com.amazonaws.auth.BasicAWSCredentials;
|
||||
import com.amazonaws.client.builder.AwsClientBuilder;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
|
||||
import com.amazonaws.services.dynamodbv2.local.main.ServerRunner;
|
||||
import com.amazonaws.services.dynamodbv2.local.server.DynamoDBProxyServer;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.URI;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import org.junit.jupiter.api.extension.AfterEachCallback;
|
||||
@@ -63,11 +57,10 @@ public class DynamoDbExtension implements BeforeEachCallback, AfterEachCallback
|
||||
|
||||
private DynamoDBProxyServer server;
|
||||
private int port;
|
||||
|
||||
|
||||
private final List<TableSchema> schemas;
|
||||
private DynamoDbClient dynamoDB2;
|
||||
private DynamoDbAsyncClient dynamoAsyncDB2;
|
||||
private AmazonDynamoDB legacyDynamoClient;
|
||||
|
||||
public DynamoDbExtension(TableSchema... schemas) {
|
||||
this.schemas = List.of(schemas);
|
||||
@@ -165,11 +158,6 @@ public class DynamoDbExtension implements BeforeEachCallback, AfterEachCallback
|
||||
.credentialsProvider(StaticCredentialsProvider.create(
|
||||
AwsBasicCredentials.create("accessKey", "secretKey")))
|
||||
.build();
|
||||
legacyDynamoClient = AmazonDynamoDBClientBuilder.standard()
|
||||
.withEndpointConfiguration(
|
||||
new AwsClientBuilder.EndpointConfiguration("http://localhost:" + port, "local-test-region"))
|
||||
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("accessKey", "secretKey")))
|
||||
.build();
|
||||
}
|
||||
|
||||
public DynamoDbClient getDynamoDbClient() {
|
||||
@@ -180,7 +168,4 @@ public class DynamoDbExtension implements BeforeEachCallback, AfterEachCallback
|
||||
return dynamoAsyncDB2;
|
||||
}
|
||||
|
||||
public AmazonDynamoDB getLegacyDynamoClient() {
|
||||
return legacyDynamoClient;
|
||||
}
|
||||
}
|
||||
+15
-1
@@ -115,7 +115,21 @@ public final class DynamoDbExtensionSchema {
|
||||
.build()),
|
||||
List.of(), List.of()),
|
||||
|
||||
REPEATED_USE_SIGNED_PRE_KEYS("repeated_use_signed_pre_keys_test",
|
||||
REPEATED_USE_EC_SIGNED_PRE_KEYS("repeated_use_signed_ec_pre_keys_test",
|
||||
RepeatedUseSignedPreKeyStore.KEY_ACCOUNT_UUID,
|
||||
RepeatedUseSignedPreKeyStore.KEY_DEVICE_ID,
|
||||
List.of(
|
||||
AttributeDefinition.builder()
|
||||
.attributeName(RepeatedUseSignedPreKeyStore.KEY_ACCOUNT_UUID)
|
||||
.attributeType(ScalarAttributeType.B)
|
||||
.build(),
|
||||
AttributeDefinition.builder()
|
||||
.attributeName(RepeatedUseSignedPreKeyStore.KEY_DEVICE_ID)
|
||||
.attributeType(ScalarAttributeType.N)
|
||||
.build()),
|
||||
List.of(), List.of()),
|
||||
|
||||
REPEATED_USE_KEM_SIGNED_PRE_KEYS("repeated_use_signed_kem_pre_keys_test",
|
||||
RepeatedUseSignedPreKeyStore.KEY_ACCOUNT_UUID,
|
||||
RepeatedUseSignedPreKeyStore.KEY_DEVICE_ID,
|
||||
List.of(
|
||||
|
||||
+70
-20
@@ -9,6 +9,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertIterableEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -20,6 +22,8 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.signal.libsignal.protocol.ecc.Curve;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicECPreKeyMigrationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.ECPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
@@ -28,11 +32,12 @@ import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
|
||||
|
||||
class KeysManagerTest {
|
||||
|
||||
private DynamicECPreKeyMigrationConfiguration ecPreKeyMigrationConfiguration;
|
||||
private KeysManager keysManager;
|
||||
|
||||
@RegisterExtension
|
||||
static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(
|
||||
Tables.EC_KEYS, Tables.PQ_KEYS, Tables.REPEATED_USE_SIGNED_PRE_KEYS);
|
||||
Tables.EC_KEYS, Tables.PQ_KEYS, Tables.REPEATED_USE_EC_SIGNED_PRE_KEYS, Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS);
|
||||
|
||||
private static final UUID ACCOUNT_UUID = UUID.randomUUID();
|
||||
private static final long DEVICE_ID = 1L;
|
||||
@@ -41,11 +46,22 @@ class KeysManagerTest {
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
ecPreKeyMigrationConfiguration = mock(DynamicECPreKeyMigrationConfiguration.class);
|
||||
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
when(dynamicConfiguration.getEcPreKeyMigrationConfiguration()).thenReturn(ecPreKeyMigrationConfiguration);
|
||||
when(ecPreKeyMigrationConfiguration.storeEcSignedPreKeys()).thenReturn(true);
|
||||
when(ecPreKeyMigrationConfiguration.deleteEcSignedPreKeys()).thenReturn(true);
|
||||
|
||||
keysManager = new KeysManager(
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
|
||||
Tables.EC_KEYS.tableName(),
|
||||
Tables.PQ_KEYS.tableName(),
|
||||
Tables.REPEATED_USE_SIGNED_PRE_KEYS.tableName());
|
||||
Tables.REPEATED_USE_EC_SIGNED_PRE_KEYS.tableName(),
|
||||
Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS.tableName(),
|
||||
dynamicConfigurationManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -64,25 +80,25 @@ class KeysManagerTest {
|
||||
assertEquals(1, keysManager.getEcCount(ACCOUNT_UUID, DEVICE_ID),
|
||||
"Repeatedly storing same key should have no effect");
|
||||
|
||||
keysManager.store(ACCOUNT_UUID, DEVICE_ID, null, List.of(generateTestKEMSignedPreKey(1)), null);
|
||||
keysManager.store(ACCOUNT_UUID, DEVICE_ID, null, List.of(generateTestKEMSignedPreKey(1)), null, null);
|
||||
assertEquals(1, keysManager.getEcCount(ACCOUNT_UUID, DEVICE_ID),
|
||||
"Uploading new PQ prekeys should have no effect on EC prekeys");
|
||||
assertEquals(1, keysManager.getPqCount(ACCOUNT_UUID, DEVICE_ID));
|
||||
|
||||
keysManager.store(ACCOUNT_UUID, DEVICE_ID, null, null, generateTestKEMSignedPreKey(1001));
|
||||
keysManager.store(ACCOUNT_UUID, DEVICE_ID, null, null, null, generateTestKEMSignedPreKey(1001));
|
||||
assertEquals(1, keysManager.getEcCount(ACCOUNT_UUID, DEVICE_ID),
|
||||
"Uploading new PQ last-resort prekey should have no effect on EC prekeys");
|
||||
assertEquals(1, keysManager.getPqCount(ACCOUNT_UUID, DEVICE_ID),
|
||||
"Uploading new PQ last-resort prekey should have no effect on one-time PQ prekeys");
|
||||
assertEquals(1001, keysManager.getLastResort(ACCOUNT_UUID, DEVICE_ID).get().keyId());
|
||||
|
||||
keysManager.store(ACCOUNT_UUID, DEVICE_ID, List.of(generateTestPreKey(2)), null, null);
|
||||
keysManager.store(ACCOUNT_UUID, DEVICE_ID, List.of(generateTestPreKey(2)), null, null, null);
|
||||
assertEquals(1, keysManager.getEcCount(ACCOUNT_UUID, DEVICE_ID),
|
||||
"Inserting a new key should overwrite all prior keys of the same type for the given account/device");
|
||||
assertEquals(1, keysManager.getPqCount(ACCOUNT_UUID, DEVICE_ID),
|
||||
"Uploading new EC prekeys should have no effect on PQ prekeys");
|
||||
|
||||
keysManager.store(ACCOUNT_UUID, DEVICE_ID, List.of(generateTestPreKey(3)), List.of(generateTestKEMSignedPreKey(2)), null);
|
||||
keysManager.store(ACCOUNT_UUID, DEVICE_ID, List.of(generateTestPreKey(3)), List.of(generateTestKEMSignedPreKey(2)), null, null);
|
||||
assertEquals(1, keysManager.getEcCount(ACCOUNT_UUID, DEVICE_ID),
|
||||
"Inserting a new key should overwrite all prior keys of the same type for the given account/device");
|
||||
assertEquals(1, keysManager.getPqCount(ACCOUNT_UUID, DEVICE_ID),
|
||||
@@ -90,7 +106,7 @@ class KeysManagerTest {
|
||||
|
||||
keysManager.store(ACCOUNT_UUID, DEVICE_ID,
|
||||
List.of(generateTestPreKey(4), generateTestPreKey(5)),
|
||||
List.of(generateTestKEMSignedPreKey(6), generateTestKEMSignedPreKey(7)), generateTestKEMSignedPreKey(1002));
|
||||
List.of(generateTestKEMSignedPreKey(6), generateTestKEMSignedPreKey(7)), null, generateTestKEMSignedPreKey(1002));
|
||||
assertEquals(2, keysManager.getEcCount(ACCOUNT_UUID, DEVICE_ID),
|
||||
"Inserting multiple new keys should overwrite all prior keys for the given account/device");
|
||||
assertEquals(2, keysManager.getPqCount(ACCOUNT_UUID, DEVICE_ID),
|
||||
@@ -119,7 +135,7 @@ class KeysManagerTest {
|
||||
final KEMSignedPreKey preKey2 = generateTestKEMSignedPreKey(2);
|
||||
final KEMSignedPreKey preKeyLast = generateTestKEMSignedPreKey(1001);
|
||||
|
||||
keysManager.store(ACCOUNT_UUID, DEVICE_ID, null, List.of(preKey1, preKey2), preKeyLast);
|
||||
keysManager.store(ACCOUNT_UUID, DEVICE_ID, null, List.of(preKey1, preKey2), null, preKeyLast);
|
||||
|
||||
assertEquals(Optional.of(preKey1), keysManager.takePQ(ACCOUNT_UUID, DEVICE_ID));
|
||||
assertEquals(1, keysManager.getPqCount(ACCOUNT_UUID, DEVICE_ID));
|
||||
@@ -139,7 +155,7 @@ class KeysManagerTest {
|
||||
assertEquals(0, keysManager.getEcCount(ACCOUNT_UUID, DEVICE_ID));
|
||||
assertEquals(0, keysManager.getPqCount(ACCOUNT_UUID, DEVICE_ID));
|
||||
|
||||
keysManager.store(ACCOUNT_UUID, DEVICE_ID, List.of(generateTestPreKey(1)), List.of(generateTestKEMSignedPreKey(1)), null);
|
||||
keysManager.store(ACCOUNT_UUID, DEVICE_ID, List.of(generateTestPreKey(1)), List.of(generateTestKEMSignedPreKey(1)), null, null);
|
||||
assertEquals(1, keysManager.getEcCount(ACCOUNT_UUID, DEVICE_ID));
|
||||
assertEquals(1, keysManager.getPqCount(ACCOUNT_UUID, DEVICE_ID));
|
||||
}
|
||||
@@ -148,53 +164,69 @@ class KeysManagerTest {
|
||||
void testDeleteByAccount() {
|
||||
keysManager.store(ACCOUNT_UUID, DEVICE_ID,
|
||||
List.of(generateTestPreKey(1), generateTestPreKey(2)),
|
||||
List.of(generateTestKEMSignedPreKey(3), generateTestKEMSignedPreKey(4)), generateTestKEMSignedPreKey(5));
|
||||
List.of(generateTestKEMSignedPreKey(3), generateTestKEMSignedPreKey(4)),
|
||||
generateTestECSignedPreKey(5),
|
||||
generateTestKEMSignedPreKey(6));
|
||||
|
||||
keysManager.store(ACCOUNT_UUID, DEVICE_ID + 1,
|
||||
List.of(generateTestPreKey(6)),
|
||||
List.of(generateTestKEMSignedPreKey(7)), generateTestKEMSignedPreKey(8));
|
||||
List.of(generateTestPreKey(7)),
|
||||
List.of(generateTestKEMSignedPreKey(8)),
|
||||
generateTestECSignedPreKey(9),
|
||||
generateTestKEMSignedPreKey(10));
|
||||
|
||||
assertEquals(2, keysManager.getEcCount(ACCOUNT_UUID, DEVICE_ID));
|
||||
assertEquals(2, keysManager.getPqCount(ACCOUNT_UUID, DEVICE_ID));
|
||||
assertTrue(keysManager.getEcSignedPreKey(ACCOUNT_UUID, DEVICE_ID).join().isPresent());
|
||||
assertTrue(keysManager.getLastResort(ACCOUNT_UUID, DEVICE_ID).isPresent());
|
||||
assertEquals(1, keysManager.getEcCount(ACCOUNT_UUID, DEVICE_ID + 1));
|
||||
assertEquals(1, keysManager.getPqCount(ACCOUNT_UUID, DEVICE_ID + 1));
|
||||
assertTrue(keysManager.getEcSignedPreKey(ACCOUNT_UUID, DEVICE_ID + 1).join().isPresent());
|
||||
assertTrue(keysManager.getLastResort(ACCOUNT_UUID, DEVICE_ID + 1).isPresent());
|
||||
|
||||
keysManager.delete(ACCOUNT_UUID);
|
||||
|
||||
assertEquals(0, keysManager.getEcCount(ACCOUNT_UUID, DEVICE_ID));
|
||||
assertEquals(0, keysManager.getPqCount(ACCOUNT_UUID, DEVICE_ID));
|
||||
assertFalse(keysManager.getEcSignedPreKey(ACCOUNT_UUID, DEVICE_ID).join().isPresent());
|
||||
assertFalse(keysManager.getLastResort(ACCOUNT_UUID, DEVICE_ID).isPresent());
|
||||
assertEquals(0, keysManager.getEcCount(ACCOUNT_UUID, DEVICE_ID + 1));
|
||||
assertEquals(0, keysManager.getPqCount(ACCOUNT_UUID, DEVICE_ID + 1));
|
||||
assertFalse(keysManager.getEcSignedPreKey(ACCOUNT_UUID, DEVICE_ID + 1).join().isPresent());
|
||||
assertFalse(keysManager.getLastResort(ACCOUNT_UUID, DEVICE_ID + 1).isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteByAccountAndDevice() {
|
||||
keysManager.store(ACCOUNT_UUID, DEVICE_ID,
|
||||
List.of(generateTestPreKey(1), generateTestPreKey(2)),
|
||||
List.of(generateTestKEMSignedPreKey(3), generateTestKEMSignedPreKey(4)), generateTestKEMSignedPreKey(5));
|
||||
List.of(generateTestPreKey(1),generateTestPreKey(2)),
|
||||
List.of(generateTestKEMSignedPreKey(3), generateTestKEMSignedPreKey(4)),
|
||||
generateTestECSignedPreKey(5),
|
||||
generateTestKEMSignedPreKey(6));
|
||||
|
||||
keysManager.store(ACCOUNT_UUID, DEVICE_ID + 1,
|
||||
List.of(generateTestPreKey(6)),
|
||||
List.of(generateTestKEMSignedPreKey(7)), generateTestKEMSignedPreKey(8));
|
||||
List.of(generateTestPreKey(7)),
|
||||
List.of(generateTestKEMSignedPreKey(8)),
|
||||
generateTestECSignedPreKey(9),
|
||||
generateTestKEMSignedPreKey(10));
|
||||
|
||||
assertEquals(2, keysManager.getEcCount(ACCOUNT_UUID, DEVICE_ID));
|
||||
assertEquals(2, keysManager.getPqCount(ACCOUNT_UUID, DEVICE_ID));
|
||||
assertTrue(keysManager.getEcSignedPreKey(ACCOUNT_UUID, DEVICE_ID).join().isPresent());
|
||||
assertTrue(keysManager.getLastResort(ACCOUNT_UUID, DEVICE_ID).isPresent());
|
||||
assertEquals(1, keysManager.getEcCount(ACCOUNT_UUID, DEVICE_ID + 1));
|
||||
assertEquals(1, keysManager.getPqCount(ACCOUNT_UUID, DEVICE_ID + 1));
|
||||
assertTrue(keysManager.getEcSignedPreKey(ACCOUNT_UUID, DEVICE_ID + 1).join().isPresent());
|
||||
assertTrue(keysManager.getLastResort(ACCOUNT_UUID, DEVICE_ID + 1).isPresent());
|
||||
|
||||
keysManager.delete(ACCOUNT_UUID, DEVICE_ID);
|
||||
|
||||
assertEquals(0, keysManager.getEcCount(ACCOUNT_UUID, DEVICE_ID));
|
||||
assertEquals(0, keysManager.getPqCount(ACCOUNT_UUID, DEVICE_ID));
|
||||
assertFalse(keysManager.getEcSignedPreKey(ACCOUNT_UUID, DEVICE_ID).join().isPresent());
|
||||
assertFalse(keysManager.getLastResort(ACCOUNT_UUID, DEVICE_ID).isPresent());
|
||||
assertEquals(1, keysManager.getEcCount(ACCOUNT_UUID, DEVICE_ID + 1));
|
||||
assertEquals(1, keysManager.getPqCount(ACCOUNT_UUID, DEVICE_ID + 1));
|
||||
assertTrue(keysManager.getEcSignedPreKey(ACCOUNT_UUID, DEVICE_ID + 1).join().isPresent());
|
||||
assertTrue(keysManager.getLastResort(ACCOUNT_UUID, DEVICE_ID + 1).isPresent());
|
||||
}
|
||||
|
||||
@@ -225,15 +257,33 @@ class KeysManagerTest {
|
||||
void testGetPqEnabledDevices() {
|
||||
final ECKeyPair identityKeyPair = Curve.generateKeyPair();
|
||||
|
||||
keysManager.store(ACCOUNT_UUID, DEVICE_ID, null, List.of(KeysHelper.signedKEMPreKey(1, identityKeyPair)), null);
|
||||
keysManager.store(ACCOUNT_UUID, DEVICE_ID + 1, null, null, KeysHelper.signedKEMPreKey(2, identityKeyPair));
|
||||
keysManager.store(ACCOUNT_UUID, DEVICE_ID + 2, null, List.of(KeysHelper.signedKEMPreKey(3, identityKeyPair)), KeysHelper.signedKEMPreKey(4, identityKeyPair));
|
||||
keysManager.store(ACCOUNT_UUID, DEVICE_ID + 3, null, null, null);
|
||||
keysManager.store(ACCOUNT_UUID, DEVICE_ID, null, List.of(KeysHelper.signedKEMPreKey(1, identityKeyPair)), null, null);
|
||||
keysManager.store(ACCOUNT_UUID, DEVICE_ID + 1, null, null, null, KeysHelper.signedKEMPreKey(2, identityKeyPair));
|
||||
keysManager.store(ACCOUNT_UUID, DEVICE_ID + 2, null, List.of(KeysHelper.signedKEMPreKey(3, identityKeyPair)), null, KeysHelper.signedKEMPreKey(4, identityKeyPair));
|
||||
keysManager.store(ACCOUNT_UUID, DEVICE_ID + 3, null, null, null, null);
|
||||
assertIterableEquals(
|
||||
Set.of(DEVICE_ID + 1, DEVICE_ID + 2),
|
||||
Set.copyOf(keysManager.getPqEnabledDevices(ACCOUNT_UUID)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testStoreEcSignedPreKeyDisabled() {
|
||||
when(ecPreKeyMigrationConfiguration.storeEcSignedPreKeys()).thenReturn(false);
|
||||
|
||||
final ECKeyPair identityKeyPair = Curve.generateKeyPair();
|
||||
|
||||
keysManager.store(ACCOUNT_UUID, DEVICE_ID,
|
||||
List.of(generateTestPreKey(1)),
|
||||
List.of(KeysHelper.signedKEMPreKey(2, identityKeyPair)),
|
||||
KeysHelper.signedECPreKey(3, identityKeyPair),
|
||||
KeysHelper.signedKEMPreKey(4, identityKeyPair));
|
||||
|
||||
assertEquals(1, keysManager.getEcCount(ACCOUNT_UUID, DEVICE_ID));
|
||||
assertEquals(1, keysManager.getPqCount(ACCOUNT_UUID, DEVICE_ID));
|
||||
assertTrue(keysManager.getLastResort(ACCOUNT_UUID, DEVICE_ID).isPresent());
|
||||
assertFalse(keysManager.getEcSignedPreKey(ACCOUNT_UUID, DEVICE_ID).join().isPresent());
|
||||
}
|
||||
|
||||
private static ECPreKey generateTestPreKey(final long keyId) {
|
||||
return new ECPreKey(keyId, Curve.generateKeyPair().getPublicKey());
|
||||
}
|
||||
|
||||
+1
-1
@@ -83,7 +83,7 @@ class MessagePersisterIntegrationTest {
|
||||
messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, mock(ReportMessageManager.class),
|
||||
messageDeletionExecutorService);
|
||||
messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager,
|
||||
dynamicConfigurationManager, PERSIST_DELAY, Optional.empty());
|
||||
dynamicConfigurationManager, PERSIST_DELAY, 1);
|
||||
|
||||
account = mock(Account.class);
|
||||
|
||||
|
||||
+1
-29
@@ -37,12 +37,9 @@ 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.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.stubbing.Answer;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicMessagePersisterConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
@@ -91,7 +88,7 @@ class MessagePersisterTest {
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster(), sharedExecutorService, messageDeliveryScheduler,
|
||||
sharedExecutorService, Clock.systemUTC());
|
||||
messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager,
|
||||
dynamicConfigurationManager, PERSIST_DELAY, Optional.empty());
|
||||
dynamicConfigurationManager, PERSIST_DELAY, 1);
|
||||
|
||||
doAnswer(invocation -> {
|
||||
final UUID destinationUuid = invocation.getArgument(0);
|
||||
@@ -229,31 +226,6 @@ class MessagePersisterTest {
|
||||
() -> messagePersister.persistQueue(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID)));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"true, true, false, false",
|
||||
"true, false, true, true",
|
||||
"false, true, false, true",
|
||||
"false, false, true, false",
|
||||
})
|
||||
void testEnabled(final boolean dedicatedProcess, final boolean serverPersistenceEnabled,
|
||||
final boolean dedicatedProcessEnabled, final boolean expectEnabled) {
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = mock(
|
||||
DynamicConfigurationManager.class);
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
|
||||
final DynamicMessagePersisterConfiguration dynamicMessagePersisterConfiguration = mock(
|
||||
DynamicMessagePersisterConfiguration.class);
|
||||
when(dynamicConfiguration.getMessagePersisterConfiguration()).thenReturn(dynamicMessagePersisterConfiguration);
|
||||
when(dynamicMessagePersisterConfiguration.isDedicatedProcessEnabled()).thenReturn(dedicatedProcessEnabled);
|
||||
when(dynamicMessagePersisterConfiguration.isServerPersistenceEnabled()).thenReturn(serverPersistenceEnabled);
|
||||
|
||||
messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager,
|
||||
dynamicConfigurationManager, PERSIST_DELAY, dedicatedProcess ? Optional.of(4) : Optional.empty());
|
||||
assertEquals(expectEnabled, messagePersister.enabled(dynamicConfigurationManager));
|
||||
}
|
||||
|
||||
@SuppressWarnings("SameParameterValue")
|
||||
private static String generateRandomQueueNameForSlot(final int slot) {
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
|
||||
+20
-22
@@ -7,12 +7,11 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.atLeast;
|
||||
import static org.mockito.Mockito.atMost;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
@@ -46,7 +45,6 @@ import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.stream.Collectors;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
@@ -64,10 +62,10 @@ import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
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;
|
||||
import reactor.test.publisher.TestPublisher;
|
||||
|
||||
class MessagesCacheTest {
|
||||
|
||||
@@ -586,14 +584,14 @@ class MessagesCacheTest {
|
||||
// is subscribed. Rather, we should be fetching in pages to satisfy downstream requests, so that memory usage
|
||||
// is limited to few pages of messages
|
||||
|
||||
// we use a combination of Flux.just() and Sinks to control when data is “fetched” from the cache. The initial
|
||||
// Flux.just()s are pages that are readily available, on demand. By design, there are more of these pages than
|
||||
// the initial prefetch. The sinks allow us to create extra demand but defer producing values to satisfy the demand
|
||||
// until later on.
|
||||
// we use a combination of Flux.just() and TestPublishers to control when data is “fetched” and emitted from the
|
||||
// cache. The initial Flux.just()s are pages that are readily available, on demand. By design, there are more of
|
||||
// these pages than the initial prefetch. The publishers allow us to create extra demand but defer producing
|
||||
// values to satisfy the demand until later on.
|
||||
|
||||
final AtomicReference<FluxSink<Object>> page4Sink = new AtomicReference<>();
|
||||
final AtomicReference<FluxSink<Object>> page56Sink = new AtomicReference<>();
|
||||
final AtomicReference<FluxSink<Object>> emptyFinalPageSink = new AtomicReference<>();
|
||||
final TestPublisher<Object> page4Publisher = TestPublisher.create();
|
||||
final TestPublisher<Object> page56Publisher = TestPublisher.create();
|
||||
final TestPublisher<Object> emptyFinalPagePublisher = TestPublisher.create();
|
||||
|
||||
final Deque<List<byte[]>> pages = new ArrayDeque<>();
|
||||
pages.add(generatePage());
|
||||
@@ -608,9 +606,9 @@ class MessagesCacheTest {
|
||||
.thenReturn(Flux.just(pages.pop()))
|
||||
.thenReturn(Flux.just(pages.pop()))
|
||||
.thenReturn(Flux.just(pages.pop()))
|
||||
.thenReturn(Flux.create(sink -> page4Sink.compareAndSet(null, sink)))
|
||||
.thenReturn(Flux.create(sink -> page56Sink.compareAndSet(null, sink)))
|
||||
.thenReturn(Flux.create(sink -> emptyFinalPageSink.compareAndSet(null, sink)))
|
||||
.thenReturn(Flux.from(page4Publisher))
|
||||
.thenReturn(Flux.from(page56Publisher))
|
||||
.thenReturn(Flux.from(emptyFinalPagePublisher))
|
||||
.thenReturn(Flux.empty());
|
||||
|
||||
final Flux<?> allMessages = messagesCache.getAllMessages(UUID.randomUUID(), 1L);
|
||||
@@ -635,9 +633,9 @@ class MessagesCacheTest {
|
||||
.thenRequest(halfPage) // page 0.5 requested
|
||||
.expectNextCount(halfPage) // page 0.5 produced
|
||||
// page 0.5 produced, 1.5 remain, so no additional interactions with the cache cluster
|
||||
.then(() -> verify(reactiveCommands, times(expectedReactiveCommandInvocations.get())).evalsha(any(),
|
||||
.then(() -> verify(reactiveCommands, atMost(expectedReactiveCommandInvocations.get())).evalsha(any(),
|
||||
any(), any(), any()))
|
||||
.then(() -> assertNull(page4Sink.get(), "page 4 should not have been fetched yet"))
|
||||
.then(page4Publisher::assertWasNotRequested)
|
||||
.thenRequest(page) // page 1.5 requested
|
||||
.expectNextCount(page) // page 1.5 produced
|
||||
|
||||
@@ -647,26 +645,26 @@ class MessagesCacheTest {
|
||||
// also NB: times() checks cumulative calls, hence addAndGet
|
||||
.then(() -> verify(reactiveCommands, times(expectedReactiveCommandInvocations.addAndGet(1))).evalsha(any(),
|
||||
any(), any(), any()))
|
||||
.then(() -> assertNotNull(page4Sink.get(), "page 4 should have been fetched"))
|
||||
.then(page4Publisher::assertWasSubscribed)
|
||||
.thenRequest(page + halfPage) // page 3 requested
|
||||
.expectNextCount(page + halfPage) // page 1.5–3 produced
|
||||
|
||||
.thenRequest(halfPage) // page 3.5 requested
|
||||
.then(() -> assertNull(page56Sink.get(), "page 5 should not have been fetched yet"))
|
||||
.then(() -> page4Sink.get().next(pages.pop()).complete())
|
||||
.then(page56Publisher::assertWasNotRequested)
|
||||
.then(() -> page4Publisher.emit(pages.pop()))
|
||||
.expectNextCount(halfPage) // page 3.5 produced
|
||||
.then(() -> verify(reactiveCommands, times(expectedReactiveCommandInvocations.addAndGet(1))).evalsha(any(),
|
||||
any(), any(), any()))
|
||||
.then(() -> assertNotNull(page56Sink.get(), "page 5 should have been fetched"))
|
||||
.then(page56Publisher::assertWasSubscribed)
|
||||
|
||||
.thenRequest(page) // page 4.5 requested
|
||||
.expectNextCount(halfPage) // page 4 produced
|
||||
|
||||
.thenRequest(page * 4) // request more demand than we will ultimately satisfy
|
||||
|
||||
.then(() -> page56Sink.get().next(pages.pop()).next(pages.pop()).complete())
|
||||
.then(() -> page56Publisher.next(pages.pop()).next(pages.pop()).complete())
|
||||
.expectNextCount(page + page) // page 5 and 6 produced
|
||||
.then(() -> emptyFinalPageSink.get().complete())
|
||||
.then(emptyFinalPagePublisher::complete)
|
||||
// confirm that cache calls increased by 2: one for page 5-and-6 (we got a two-fer in next(pop()).next(pop()),
|
||||
// and one for the final, empty page
|
||||
.then(() -> verify(reactiveCommands, times(expectedReactiveCommandInvocations.addAndGet(2))).evalsha(any(),
|
||||
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.signal.libsignal.protocol.ecc.Curve;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class RepeatedUseECSignedPreKeyStoreTest extends RepeatedUseSignedPreKeyStoreTest<ECSignedPreKey> {
|
||||
|
||||
private RepeatedUseECSignedPreKeyStore keyStore;
|
||||
|
||||
private int currentKeyId = 1;
|
||||
|
||||
@RegisterExtension
|
||||
static final DynamoDbExtension DYNAMO_DB_EXTENSION =
|
||||
new DynamoDbExtension(DynamoDbExtensionSchema.Tables.REPEATED_USE_EC_SIGNED_PRE_KEYS);
|
||||
|
||||
private static final ECKeyPair IDENTITY_KEY_PAIR = Curve.generateKeyPair();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
keyStore = new RepeatedUseECSignedPreKeyStore(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
|
||||
DynamoDbExtensionSchema.Tables.REPEATED_USE_EC_SIGNED_PRE_KEYS.tableName());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected RepeatedUseSignedPreKeyStore<ECSignedPreKey> getKeyStore() {
|
||||
return keyStore;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ECSignedPreKey generateSignedPreKey() {
|
||||
return KeysHelper.signedECPreKey(currentKeyId++, IDENTITY_KEY_PAIR);
|
||||
}
|
||||
|
||||
@Test
|
||||
void storeIfAbsent() {
|
||||
final UUID identifier = UUID.randomUUID();
|
||||
final long deviceIdWithExistingKey = 1;
|
||||
final long deviceIdWithoutExistingKey = deviceIdWithExistingKey + 1;
|
||||
|
||||
final ECSignedPreKey originalSignedPreKey = generateSignedPreKey();
|
||||
|
||||
keyStore.store(identifier, deviceIdWithExistingKey, originalSignedPreKey).join();
|
||||
|
||||
assertFalse(keyStore.storeIfAbsent(identifier, deviceIdWithExistingKey, generateSignedPreKey()).join());
|
||||
assertTrue(keyStore.storeIfAbsent(identifier, deviceIdWithoutExistingKey, generateSignedPreKey()).join());
|
||||
|
||||
assertEquals(Optional.of(originalSignedPreKey), keyStore.find(identifier, deviceIdWithExistingKey).join());
|
||||
assertTrue(keyStore.find(identifier, deviceIdWithoutExistingKey).join().isPresent());
|
||||
}
|
||||
}
|
||||
+2
-4
@@ -12,8 +12,6 @@ import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class RepeatedUseKEMSignedPreKeyStoreTest extends RepeatedUseSignedPreKeyStoreTest<KEMSignedPreKey> {
|
||||
|
||||
private RepeatedUseKEMSignedPreKeyStore keyStore;
|
||||
@@ -22,14 +20,14 @@ class RepeatedUseKEMSignedPreKeyStoreTest extends RepeatedUseSignedPreKeyStoreTe
|
||||
|
||||
@RegisterExtension
|
||||
static final DynamoDbExtension DYNAMO_DB_EXTENSION =
|
||||
new DynamoDbExtension(DynamoDbExtensionSchema.Tables.REPEATED_USE_SIGNED_PRE_KEYS);
|
||||
new DynamoDbExtension(DynamoDbExtensionSchema.Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS);
|
||||
|
||||
private static final ECKeyPair IDENTITY_KEY_PAIR = Curve.generateKeyPair();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
keyStore = new RepeatedUseKEMSignedPreKeyStore(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
|
||||
DynamoDbExtensionSchema.Tables.REPEATED_USE_SIGNED_PRE_KEYS.tableName());
|
||||
DynamoDbExtensionSchema.Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS.tableName());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+2
@@ -315,6 +315,8 @@ class DeviceControllerTest {
|
||||
verify(pendingDevicesManager).remove(AuthHelper.VALID_NUMBER);
|
||||
verify(messagesManager).clear(eq(AuthHelper.VALID_UUID), eq(42L));
|
||||
verify(clientPresenceManager).disconnectPresence(AuthHelper.VALID_UUID, Device.MASTER_ID);
|
||||
verify(keysManager).storeEcSignedPreKeys(AuthHelper.VALID_UUID, Map.of(response.getDeviceId(), aciSignedPreKey.get()));
|
||||
verify(keysManager).storeEcSignedPreKeys(AuthHelper.VALID_PNI, Map.of(response.getDeviceId(), pniSignedPreKey.get()));
|
||||
verify(keysManager).storePqLastResort(AuthHelper.VALID_UUID, Map.of(response.getDeviceId(), aciPqLastResortPreKey.get()));
|
||||
verify(keysManager).storePqLastResort(AuthHelper.VALID_PNI, Map.of(response.getDeviceId(), pniPqLastResortPreKey.get()));
|
||||
}
|
||||
|
||||
+21
-34
@@ -33,6 +33,7 @@ import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import javax.ws.rs.client.Entity;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
@@ -53,7 +54,6 @@ import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.entities.ECPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.PreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.PreKeyCount;
|
||||
import org.whispersystems.textsecuregcm.entities.PreKeyResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.PreKeyState;
|
||||
@@ -139,10 +139,6 @@ class KeysControllerTest {
|
||||
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
|
||||
byte[] publicKey) {
|
||||
|
||||
static WeaklyTypedPreKey fromPreKey(final PreKey<?> preKey) {
|
||||
return new WeaklyTypedPreKey(preKey.keyId(), preKey.serializedPublicKey());
|
||||
}
|
||||
}
|
||||
|
||||
private record WeaklyTypedSignedPreKey(long keyId,
|
||||
@@ -226,6 +222,8 @@ class KeysControllerTest {
|
||||
|
||||
when(rateLimiters.getPreKeysLimiter()).thenReturn(rateLimiter);
|
||||
|
||||
when(KEYS.getEcSignedPreKey(any(), anyLong())).thenReturn(CompletableFuture.completedFuture(Optional.empty()));
|
||||
|
||||
when(KEYS.takeEC(EXISTS_UUID, 1)).thenReturn(Optional.of(SAMPLE_KEY));
|
||||
when(KEYS.takePQ(EXISTS_UUID, 1)).thenReturn(Optional.of(SAMPLE_PQ_KEY));
|
||||
when(KEYS.takeEC(EXISTS_PNI, 1)).thenReturn(Optional.of(SAMPLE_KEY_PNI));
|
||||
@@ -268,30 +266,6 @@ class KeysControllerTest {
|
||||
verify(KEYS).getPqCount(AuthHelper.VALID_UUID, 1);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void getSignedPreKeyV2() {
|
||||
ECSignedPreKey result = resources.getJerseyTest()
|
||||
.target("/v2/keys/signed")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get(ECSignedPreKey.class);
|
||||
|
||||
assertEquals(VALID_DEVICE_SIGNED_KEY, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getPhoneNumberIdentifierSignedPreKeyV2() {
|
||||
ECSignedPreKey result = resources.getJerseyTest()
|
||||
.target("/v2/keys/signed")
|
||||
.queryParam("identity", "pni")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get(ECSignedPreKey.class);
|
||||
|
||||
assertEquals(VALID_DEVICE_PNI_SIGNED_KEY, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void putSignedPreKeyV2() {
|
||||
ECSignedPreKey test = KeysHelper.signedECPreKey(9998, IDENTITY_KEY_PAIR);
|
||||
@@ -354,6 +328,7 @@ class KeysControllerTest {
|
||||
assertEquals(existsAccount.getDevice(1).get().getSignedPreKey(), result.getDevice(1).getSignedPreKey());
|
||||
|
||||
verify(KEYS).takeEC(EXISTS_UUID, 1);
|
||||
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, 1);
|
||||
verifyNoMoreInteractions(KEYS);
|
||||
}
|
||||
|
||||
@@ -377,6 +352,7 @@ class KeysControllerTest {
|
||||
|
||||
verify(KEYS).takeEC(EXISTS_UUID, 1);
|
||||
verify(KEYS).takePQ(EXISTS_UUID, 1);
|
||||
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, 1);
|
||||
verifyNoMoreInteractions(KEYS);
|
||||
}
|
||||
|
||||
@@ -398,6 +374,7 @@ class KeysControllerTest {
|
||||
|
||||
verify(KEYS).takeEC(EXISTS_UUID, 1);
|
||||
verify(KEYS).takePQ(EXISTS_UUID, 1);
|
||||
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, 1);
|
||||
verifyNoMoreInteractions(KEYS);
|
||||
}
|
||||
|
||||
@@ -417,6 +394,7 @@ class KeysControllerTest {
|
||||
assertEquals(existsAccount.getDevice(1).get().getPhoneNumberIdentitySignedPreKey(), result.getDevice(1).getSignedPreKey());
|
||||
|
||||
verify(KEYS).takeEC(EXISTS_PNI, 1);
|
||||
verify(KEYS).getEcSignedPreKey(EXISTS_PNI, 1);
|
||||
verifyNoMoreInteractions(KEYS);
|
||||
}
|
||||
|
||||
@@ -438,6 +416,7 @@ class KeysControllerTest {
|
||||
|
||||
verify(KEYS).takeEC(EXISTS_PNI, 1);
|
||||
verify(KEYS).takePQ(EXISTS_PNI, 1);
|
||||
verify(KEYS).getEcSignedPreKey(EXISTS_PNI, 1);
|
||||
verifyNoMoreInteractions(KEYS);
|
||||
}
|
||||
|
||||
@@ -459,6 +438,7 @@ class KeysControllerTest {
|
||||
assertEquals(existsAccount.getDevice(1).get().getPhoneNumberIdentitySignedPreKey(), result.getDevice(1).getSignedPreKey());
|
||||
|
||||
verify(KEYS).takeEC(EXISTS_PNI, 1);
|
||||
verify(KEYS).getEcSignedPreKey(EXISTS_PNI, 1);
|
||||
verifyNoMoreInteractions(KEYS);
|
||||
}
|
||||
|
||||
@@ -494,6 +474,7 @@ class KeysControllerTest {
|
||||
|
||||
verify(KEYS).takeEC(EXISTS_UUID, 1);
|
||||
verify(KEYS).takePQ(EXISTS_UUID, 1);
|
||||
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, 1);
|
||||
verifyNoMoreInteractions(KEYS);
|
||||
}
|
||||
|
||||
@@ -586,6 +567,9 @@ class KeysControllerTest {
|
||||
verify(KEYS).takeEC(EXISTS_UUID, 1);
|
||||
verify(KEYS).takeEC(EXISTS_UUID, 2);
|
||||
verify(KEYS).takeEC(EXISTS_UUID, 4);
|
||||
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, 1);
|
||||
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, 2);
|
||||
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, 4);
|
||||
verifyNoMoreInteractions(KEYS);
|
||||
}
|
||||
|
||||
@@ -651,6 +635,9 @@ class KeysControllerTest {
|
||||
verify(KEYS).takePQ(EXISTS_UUID, 2);
|
||||
verify(KEYS).takeEC(EXISTS_UUID, 4);
|
||||
verify(KEYS).takePQ(EXISTS_UUID, 4);
|
||||
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, 1);
|
||||
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, 2);
|
||||
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, 4);
|
||||
verifyNoMoreInteractions(KEYS);
|
||||
}
|
||||
|
||||
@@ -716,7 +703,7 @@ class KeysControllerTest {
|
||||
assertThat(response.getStatus()).isEqualTo(204);
|
||||
|
||||
ArgumentCaptor<List<ECPreKey>> listCaptor = ArgumentCaptor.forClass(List.class);
|
||||
verify(KEYS).store(eq(AuthHelper.VALID_UUID), eq(1L), listCaptor.capture(), isNull(), isNull());
|
||||
verify(KEYS).store(eq(AuthHelper.VALID_UUID), eq(1L), listCaptor.capture(), isNull(), eq(signedPreKey), isNull());
|
||||
|
||||
assertThat(listCaptor.getValue()).containsExactly(preKey);
|
||||
|
||||
@@ -747,7 +734,7 @@ class KeysControllerTest {
|
||||
|
||||
ArgumentCaptor<List<ECPreKey>> ecCaptor = ArgumentCaptor.forClass(List.class);
|
||||
ArgumentCaptor<List<KEMSignedPreKey>> pqCaptor = ArgumentCaptor.forClass(List.class);
|
||||
verify(KEYS).store(eq(AuthHelper.VALID_UUID), eq(1L), ecCaptor.capture(), pqCaptor.capture(), eq(pqLastResortPreKey));
|
||||
verify(KEYS).store(eq(AuthHelper.VALID_UUID), eq(1L), ecCaptor.capture(), pqCaptor.capture(), eq(signedPreKey), eq(pqLastResortPreKey));
|
||||
|
||||
assertThat(ecCaptor.getValue()).containsExactly(preKey);
|
||||
assertThat(pqCaptor.getValue()).containsExactly(pqPreKey);
|
||||
@@ -849,7 +836,7 @@ class KeysControllerTest {
|
||||
assertThat(response.getStatus()).isEqualTo(204);
|
||||
|
||||
ArgumentCaptor<List<ECPreKey>> listCaptor = ArgumentCaptor.forClass(List.class);
|
||||
verify(KEYS).store(eq(AuthHelper.VALID_PNI), eq(1L), listCaptor.capture(), isNull(), isNull());
|
||||
verify(KEYS).store(eq(AuthHelper.VALID_PNI), eq(1L), listCaptor.capture(), isNull(), eq(signedPreKey), isNull());
|
||||
|
||||
assertThat(listCaptor.getValue()).containsExactly(preKey);
|
||||
|
||||
@@ -881,7 +868,7 @@ class KeysControllerTest {
|
||||
|
||||
ArgumentCaptor<List<ECPreKey>> ecCaptor = ArgumentCaptor.forClass(List.class);
|
||||
ArgumentCaptor<List<KEMSignedPreKey>> pqCaptor = ArgumentCaptor.forClass(List.class);
|
||||
verify(KEYS).store(eq(AuthHelper.VALID_PNI), eq(1L), ecCaptor.capture(), pqCaptor.capture(), eq(pqLastResortPreKey));
|
||||
verify(KEYS).store(eq(AuthHelper.VALID_PNI), eq(1L), ecCaptor.capture(), pqCaptor.capture(), eq(signedPreKey), eq(pqLastResortPreKey));
|
||||
|
||||
assertThat(ecCaptor.getValue()).containsExactly(preKey);
|
||||
assertThat(pqCaptor.getValue()).containsExactly(pqPreKey);
|
||||
@@ -925,7 +912,7 @@ class KeysControllerTest {
|
||||
assertThat(response.getStatus()).isEqualTo(204);
|
||||
|
||||
ArgumentCaptor<List<ECPreKey>> listCaptor = ArgumentCaptor.forClass(List.class);
|
||||
verify(KEYS).store(eq(AuthHelper.DISABLED_UUID), eq(1L), listCaptor.capture(), isNull(), isNull());
|
||||
verify(KEYS).store(eq(AuthHelper.DISABLED_UUID), eq(1L), listCaptor.capture(), isNull(), eq(signedPreKey), isNull());
|
||||
|
||||
List<ECPreKey> capturedList = listCaptor.getValue();
|
||||
assertThat(capturedList.size()).isEqualTo(1);
|
||||
|
||||
+29
-55
@@ -31,7 +31,6 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Stream;
|
||||
import javax.ws.rs.client.Entity;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
@@ -40,9 +39,6 @@ import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.signal.event.NoOpAdminEventLogger;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
@@ -59,7 +55,6 @@ import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
class RemoteConfigControllerTest {
|
||||
|
||||
private static final RemoteConfigsManager remoteConfigsManager = mock(RemoteConfigsManager.class);
|
||||
private static final List<String> remoteConfigsAuth = List.of("foo", "bar");
|
||||
|
||||
private static final Set<String> remoteConfigsUsers = Set.of("user1@example.com", "user2@example.com");
|
||||
|
||||
@@ -79,8 +74,8 @@ class RemoteConfigControllerTest {
|
||||
ImmutableSet.of(AuthenticatedAccount.class, DisabledPermittedAuthenticatedAccount.class)))
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addProvider(new DeviceLimitExceededExceptionMapper())
|
||||
.addResource(new RemoteConfigController(remoteConfigsManager, new NoOpAdminEventLogger(), remoteConfigsAuth,
|
||||
remoteConfigsUsers, requiredHostedDomain, Collections.singletonList("aud.example.com"),
|
||||
.addResource(new RemoteConfigController(remoteConfigsManager, new NoOpAdminEventLogger(), remoteConfigsUsers,
|
||||
requiredHostedDomain, Collections.singletonList("aud.example.com"),
|
||||
googleIdVerificationTokenBuilder, Map.of("maxGroupSize", "42")))
|
||||
.build();
|
||||
|
||||
@@ -228,13 +223,12 @@ class RemoteConfigControllerTest {
|
||||
verifyNoMoreInteractions(remoteConfigsManager);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("authorizedTokens")
|
||||
void testSetConfig(final String configToken) {
|
||||
@Test
|
||||
void testSetConfig() {
|
||||
Response response = resources.getJerseyTest()
|
||||
.target("/v1/config")
|
||||
.request()
|
||||
.header("Config-Token", configToken)
|
||||
.header("Config-Token", "user1.valid")
|
||||
.put(Entity.entity(new RemoteConfig("android.stickers", 88, Set.of(), "FALSE", "TRUE", null),
|
||||
MediaType.APPLICATION_JSON_TYPE));
|
||||
|
||||
@@ -249,13 +243,12 @@ class RemoteConfigControllerTest {
|
||||
assertThat(captor.getValue().getUuids()).isEmpty();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("authorizedTokens")
|
||||
void testSetConfigValued(final String configToken) {
|
||||
@Test
|
||||
void testSetConfigValued() {
|
||||
Response response = resources.getJerseyTest()
|
||||
.target("/v1/config")
|
||||
.request()
|
||||
.header("Config-Token", configToken)
|
||||
.header("Config-Token", "user1.valid")
|
||||
.put(Entity.entity(new RemoteConfig("value.sometimes", 50, Set.of(), "a", "b", null),
|
||||
MediaType.APPLICATION_JSON_TYPE));
|
||||
|
||||
@@ -270,9 +263,9 @@ class RemoteConfigControllerTest {
|
||||
assertThat(captor.getValue().getUuids()).isEmpty();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("authorizedTokens")
|
||||
void testSetConfigWithHashKey(final String configToken) {
|
||||
@Test
|
||||
void testSetConfigWithHashKey() {
|
||||
final String configToken = "user1.valid";
|
||||
Response response1 = resources.getJerseyTest()
|
||||
.target("/v1/config")
|
||||
.request()
|
||||
@@ -308,13 +301,12 @@ class RemoteConfigControllerTest {
|
||||
assertThat(capture2.getHashKey()).isEqualTo("linked.config.0");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("unauthorizedTokens")
|
||||
void testSetConfigUnauthorized(final String configToken) {
|
||||
@Test
|
||||
void testSetConfigUnauthorized() {
|
||||
Response response = resources.getJerseyTest()
|
||||
.target("/v1/config")
|
||||
.request()
|
||||
.header("Config-Token", configToken)
|
||||
.header("Config-Token", "user3.valid")
|
||||
.put(Entity.entity(new RemoteConfig("android.stickers", 88, Set.of(), "FALSE", "TRUE", null),
|
||||
MediaType.APPLICATION_JSON_TYPE));
|
||||
|
||||
@@ -336,13 +328,12 @@ class RemoteConfigControllerTest {
|
||||
verifyNoMoreInteractions(remoteConfigsManager);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("authorizedTokens")
|
||||
void testSetConfigBadName(final String configToken) {
|
||||
@Test
|
||||
void testSetConfigBadName() {
|
||||
Response response = resources.getJerseyTest()
|
||||
.target("/v1/config")
|
||||
.request()
|
||||
.header("Config-Token", configToken)
|
||||
.header("Config-Token", "user1.valid")
|
||||
.put(Entity.entity(new RemoteConfig("android-stickers", 88, Set.of(), "FALSE", "TRUE", null),
|
||||
MediaType.APPLICATION_JSON_TYPE));
|
||||
|
||||
@@ -351,13 +342,12 @@ class RemoteConfigControllerTest {
|
||||
verifyNoMoreInteractions(remoteConfigsManager);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("authorizedTokens")
|
||||
void testSetConfigEmptyName(final String configToken) {
|
||||
@Test
|
||||
void testSetConfigEmptyName() {
|
||||
Response response = resources.getJerseyTest()
|
||||
.target("/v1/config")
|
||||
.request()
|
||||
.header("Config-Token", configToken)
|
||||
.header("Config-Token", "user1.valid")
|
||||
.put(Entity.entity(new RemoteConfig("", 88, Set.of(), "FALSE", "TRUE", null), MediaType.APPLICATION_JSON_TYPE));
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(422);
|
||||
@@ -365,26 +355,24 @@ class RemoteConfigControllerTest {
|
||||
verifyNoMoreInteractions(remoteConfigsManager);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("authorizedTokens")
|
||||
void testSetGlobalConfig(final String configToken) {
|
||||
@Test
|
||||
void testSetGlobalConfig() {
|
||||
Response response = resources.getJerseyTest()
|
||||
.target("/v1/config")
|
||||
.request()
|
||||
.header("Config-Token", configToken)
|
||||
.header("Config-Token", "user1.valid")
|
||||
.put(Entity.entity(new RemoteConfig("global.maxGroupSize", 88, Set.of(), "FALSE", "TRUE", null),
|
||||
MediaType.APPLICATION_JSON_TYPE));
|
||||
assertThat(response.getStatus()).isEqualTo(403);
|
||||
verifyNoMoreInteractions(remoteConfigsManager);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("authorizedTokens")
|
||||
void testDelete(final String configToken) {
|
||||
@Test
|
||||
void testDelete() {
|
||||
Response response = resources.getJerseyTest()
|
||||
.target("/v1/config/android.stickers")
|
||||
.request()
|
||||
.header("Config-Token", configToken)
|
||||
.header("Config-Token", "user1.valid")
|
||||
.delete();
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(204);
|
||||
@@ -406,13 +394,12 @@ class RemoteConfigControllerTest {
|
||||
verifyNoMoreInteractions(remoteConfigsManager);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("authorizedTokens")
|
||||
void testDeleteGlobalConfig(final String configToken) {
|
||||
@Test
|
||||
void testDeleteGlobalConfig() {
|
||||
Response response = resources.getJerseyTest()
|
||||
.target("/v1/config/global.maxGroupSize")
|
||||
.request()
|
||||
.header("Config-Token", configToken)
|
||||
.header("Config-Token", "user1.valid")
|
||||
.delete();
|
||||
assertThat(response.getStatus()).isEqualTo(403);
|
||||
verifyNoMoreInteractions(remoteConfigsManager);
|
||||
@@ -447,17 +434,4 @@ class RemoteConfigControllerTest {
|
||||
}
|
||||
}
|
||||
|
||||
static Stream<Arguments> authorizedTokens() {
|
||||
return Stream.of(
|
||||
Arguments.of("foo"),
|
||||
Arguments.of("user1.valid")
|
||||
);
|
||||
}
|
||||
|
||||
static Stream<Arguments> unauthorizedTokens() {
|
||||
return Stream.of(
|
||||
Arguments.of("baz"),
|
||||
Arguments.of("user3.valid")
|
||||
);
|
||||
}
|
||||
}
|
||||
+41
-17
@@ -20,7 +20,12 @@ import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
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.configuration.CircuitBreakerConfiguration;
|
||||
@@ -34,21 +39,38 @@ class FaultTolerantHttpClientTest {
|
||||
.options(wireMockConfig().dynamicPort().dynamicHttpsPort())
|
||||
.build();
|
||||
|
||||
private ExecutorService httpExecutor;
|
||||
private ScheduledExecutorService retryExecutor;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
httpExecutor = Executors.newSingleThreadExecutor();
|
||||
retryExecutor = Executors.newSingleThreadScheduledExecutor();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws InterruptedException {
|
||||
httpExecutor.shutdown();
|
||||
httpExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
retryExecutor.shutdown();
|
||||
retryExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSimpleGet() {
|
||||
wireMock.stubFor(get(urlEqualTo("/ping"))
|
||||
.willReturn(aResponse()
|
||||
.withHeader("Content-Type", "text/plain")
|
||||
.withBody("Pong!")));
|
||||
|
||||
.willReturn(aResponse()
|
||||
.withHeader("Content-Type", "text/plain")
|
||||
.withBody("Pong!")));
|
||||
|
||||
FaultTolerantHttpClient client = FaultTolerantHttpClient.newBuilder()
|
||||
.withCircuitBreaker(new CircuitBreakerConfiguration())
|
||||
.withRetry(new RetryConfiguration())
|
||||
.withExecutor(Executors.newSingleThreadExecutor())
|
||||
.withName("test")
|
||||
.withVersion(HttpClient.Version.HTTP_2)
|
||||
.build();
|
||||
.withCircuitBreaker(new CircuitBreakerConfiguration())
|
||||
.withRetry(new RetryConfiguration())
|
||||
.withExecutor(httpExecutor)
|
||||
.withRetryExecutor(retryExecutor)
|
||||
.withName("test")
|
||||
.withVersion(HttpClient.Version.HTTP_2)
|
||||
.build();
|
||||
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create("http://localhost:" + wireMock.getPort() + "/ping"))
|
||||
@@ -72,12 +94,13 @@ class FaultTolerantHttpClientTest {
|
||||
.withBody("Pong!")));
|
||||
|
||||
FaultTolerantHttpClient client = FaultTolerantHttpClient.newBuilder()
|
||||
.withCircuitBreaker(new CircuitBreakerConfiguration())
|
||||
.withRetry(new RetryConfiguration())
|
||||
.withExecutor(Executors.newSingleThreadExecutor())
|
||||
.withName("test")
|
||||
.withVersion(HttpClient.Version.HTTP_2)
|
||||
.build();
|
||||
.withCircuitBreaker(new CircuitBreakerConfiguration())
|
||||
.withRetry(new RetryConfiguration())
|
||||
.withExecutor(httpExecutor)
|
||||
.withRetryExecutor(retryExecutor)
|
||||
.withName("test")
|
||||
.withVersion(HttpClient.Version.HTTP_2)
|
||||
.build();
|
||||
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create("http://localhost:" + wireMock.getPort() + "/failure"))
|
||||
@@ -104,7 +127,8 @@ class FaultTolerantHttpClientTest {
|
||||
FaultTolerantHttpClient client = FaultTolerantHttpClient.newBuilder()
|
||||
.withCircuitBreaker(circuitBreakerConfiguration)
|
||||
.withRetry(new RetryConfiguration())
|
||||
.withExecutor(Executors.newSingleThreadExecutor())
|
||||
.withRetryExecutor(retryExecutor)
|
||||
.withExecutor(httpExecutor)
|
||||
.withName("test")
|
||||
.withVersion(HttpClient.Version.HTTP_2)
|
||||
.build();
|
||||
|
||||
+2
-133
@@ -9,11 +9,9 @@ import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -23,16 +21,12 @@ import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicAccountDatabaseCrawlerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountCrawlChunk;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountDatabaseCrawler;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountDatabaseCrawlerCache;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountDatabaseCrawlerListener;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountDatabaseCrawlerRestartException;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
|
||||
class AccountDatabaseCrawlerTest {
|
||||
|
||||
@@ -48,11 +42,8 @@ class AccountDatabaseCrawlerTest {
|
||||
private final AccountDatabaseCrawlerListener listener = mock(AccountDatabaseCrawlerListener.class);
|
||||
private final AccountDatabaseCrawlerCache cache = mock(AccountDatabaseCrawlerCache.class);
|
||||
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = mock(
|
||||
DynamicConfigurationManager.class);
|
||||
|
||||
private final AccountDatabaseCrawler crawler =
|
||||
new AccountDatabaseCrawler("test", accounts, cache, List.of(listener), CHUNK_SIZE, dynamicConfigurationManager);
|
||||
new AccountDatabaseCrawler("test", accounts, cache, List.of(listener), CHUNK_SIZE);
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
@@ -67,132 +58,10 @@ class AccountDatabaseCrawlerTest {
|
||||
new AccountCrawlChunk(Collections.emptyList(), null));
|
||||
|
||||
when(cache.claimActiveWork(any(), anyLong())).thenReturn(true);
|
||||
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
final DynamicAccountDatabaseCrawlerConfiguration accountDatabaseCrawlerConfiguration =
|
||||
new DynamicAccountDatabaseCrawlerConfiguration(true, true);
|
||||
when(dynamicConfiguration.getAccountDatabaseCrawlerConfiguration()).thenReturn(accountDatabaseCrawlerConfiguration);
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCrawlStart() throws AccountDatabaseCrawlerRestartException {
|
||||
when(cache.getLastUuid()).thenReturn(Optional.empty());
|
||||
|
||||
crawler.doPeriodicWork();
|
||||
|
||||
verify(cache, times(1)).claimActiveWork(any(String.class), anyLong());
|
||||
verify(cache, times(1)).getLastUuid();
|
||||
verify(listener, times(1)).onCrawlStart();
|
||||
verify(accounts, times(1)).getAllFromDynamo(eq(CHUNK_SIZE));
|
||||
verify(accounts, times(0)).getAllFromDynamo(any(UUID.class), eq(CHUNK_SIZE));
|
||||
verify(account1, times(0)).getUuid();
|
||||
verify(listener, times(1)).timeAndProcessCrawlChunk(eq(Optional.empty()), eq(List.of(account1, account2)));
|
||||
verify(cache, times(1)).setLastUuid(eq(Optional.of(ACCOUNT2)));
|
||||
verify(cache, times(1)).releaseActiveWork(any(String.class));
|
||||
|
||||
verifyNoMoreInteractions(account1);
|
||||
verifyNoMoreInteractions(account2);
|
||||
verifyNoMoreInteractions(accounts);
|
||||
verifyNoMoreInteractions(listener);
|
||||
verifyNoMoreInteractions(cache);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCrawlChunk() throws AccountDatabaseCrawlerRestartException {
|
||||
when(cache.getLastUuid()).thenReturn(Optional.of(ACCOUNT1));
|
||||
|
||||
crawler.doPeriodicWork();
|
||||
|
||||
verify(cache, times(1)).claimActiveWork(any(String.class), anyLong());
|
||||
verify(cache, times(1)).getLastUuid();
|
||||
verify(accounts, times(0)).getAllFromDynamo(eq(CHUNK_SIZE));
|
||||
verify(accounts, times(1)).getAllFromDynamo(eq(ACCOUNT1), eq(CHUNK_SIZE));
|
||||
verify(listener, times(1)).timeAndProcessCrawlChunk(eq(Optional.of(ACCOUNT1)), eq(List.of(account2)));
|
||||
verify(cache, times(1)).setLastUuid(eq(Optional.of(ACCOUNT2)));
|
||||
verify(cache, times(1)).releaseActiveWork(any(String.class));
|
||||
|
||||
verifyNoInteractions(account1);
|
||||
|
||||
verifyNoMoreInteractions(account2);
|
||||
verifyNoMoreInteractions(accounts);
|
||||
verifyNoMoreInteractions(listener);
|
||||
verifyNoMoreInteractions(cache);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCrawlChunkAccelerated() throws AccountDatabaseCrawlerRestartException {
|
||||
when(cache.getLastUuid()).thenReturn(Optional.of(ACCOUNT1));
|
||||
|
||||
crawler.doPeriodicWork();
|
||||
|
||||
verify(cache, times(1)).claimActiveWork(any(String.class), anyLong());
|
||||
verify(cache, times(1)).getLastUuid();
|
||||
verify(accounts, times(0)).getAllFromDynamo(eq(CHUNK_SIZE));
|
||||
verify(accounts, times(1)).getAllFromDynamo(eq(ACCOUNT1), eq(CHUNK_SIZE));
|
||||
verify(listener, times(1)).timeAndProcessCrawlChunk(eq(Optional.of(ACCOUNT1)), eq(List.of(account2)));
|
||||
verify(cache, times(1)).setLastUuid(eq(Optional.of(ACCOUNT2)));
|
||||
verify(cache, times(1)).releaseActiveWork(any(String.class));
|
||||
|
||||
verifyNoInteractions(account1);
|
||||
|
||||
verifyNoMoreInteractions(account2);
|
||||
verifyNoMoreInteractions(accounts);
|
||||
verifyNoMoreInteractions(listener);
|
||||
verifyNoMoreInteractions(cache);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCrawlChunkRestart() throws AccountDatabaseCrawlerRestartException {
|
||||
when(cache.getLastUuid()).thenReturn(Optional.of(ACCOUNT1));
|
||||
doThrow(AccountDatabaseCrawlerRestartException.class).when(listener)
|
||||
.timeAndProcessCrawlChunk(eq(Optional.of(ACCOUNT1)), eq(List.of(account2)));
|
||||
|
||||
crawler.doPeriodicWork();
|
||||
|
||||
verify(cache, times(1)).claimActiveWork(any(String.class), anyLong());
|
||||
verify(cache, times(1)).getLastUuid();
|
||||
verify(accounts, times(0)).getAllFromDynamo(eq(CHUNK_SIZE));
|
||||
verify(accounts, times(1)).getAllFromDynamo(eq(ACCOUNT1), eq(CHUNK_SIZE));
|
||||
verify(account2, times(0)).getNumber();
|
||||
verify(listener, times(1)).timeAndProcessCrawlChunk(eq(Optional.of(ACCOUNT1)), eq(List.of(account2)));
|
||||
verify(cache, times(1)).setLastUuid(eq(Optional.empty()));
|
||||
verify(cache, times(1)).releaseActiveWork(any(String.class));
|
||||
|
||||
verifyNoInteractions(account1);
|
||||
|
||||
verifyNoMoreInteractions(account2);
|
||||
verifyNoMoreInteractions(accounts);
|
||||
verifyNoMoreInteractions(listener);
|
||||
verifyNoMoreInteractions(cache);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCrawlEnd() {
|
||||
when(cache.getLastUuid()).thenReturn(Optional.of(ACCOUNT2));
|
||||
|
||||
crawler.doPeriodicWork();
|
||||
|
||||
verify(cache, times(1)).claimActiveWork(any(String.class), anyLong());
|
||||
verify(cache, times(1)).getLastUuid();
|
||||
verify(accounts, times(0)).getAllFromDynamo(eq(CHUNK_SIZE));
|
||||
verify(accounts, times(1)).getAllFromDynamo(eq(ACCOUNT2), eq(CHUNK_SIZE));
|
||||
verify(account1, times(0)).getNumber();
|
||||
verify(account2, times(0)).getNumber();
|
||||
verify(listener, times(1)).onCrawlEnd();
|
||||
verify(cache, times(1)).setLastUuid(eq(Optional.empty()));
|
||||
verify(cache, times(1)).releaseActiveWork(any(String.class));
|
||||
|
||||
verifyNoInteractions(account1);
|
||||
verifyNoInteractions(account2);
|
||||
|
||||
verifyNoMoreInteractions(accounts);
|
||||
verifyNoMoreInteractions(listener);
|
||||
verifyNoMoreInteractions(cache);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCrawlAllAccounts() throws Exception {
|
||||
void testCrawlAllAccounts() {
|
||||
when(cache.getLastUuid())
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
|
||||
+6
-7
@@ -22,11 +22,11 @@ import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountDatabaseCrawlerRestartException;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.PushFeedbackProcessor;
|
||||
@@ -35,7 +35,7 @@ import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
class PushFeedbackProcessorTest {
|
||||
|
||||
private AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
private final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
|
||||
private Account uninstalledAccount = mock(Account.class);
|
||||
private Account mixedAccount = mock(Account.class);
|
||||
@@ -98,18 +98,17 @@ class PushFeedbackProcessorTest {
|
||||
Set.of(uninstalledAccount, mixedAccount, freshAccount, cleanAccount, stillActiveAccount));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void testEmpty() throws AccountDatabaseCrawlerRestartException {
|
||||
PushFeedbackProcessor processor = new PushFeedbackProcessor(accountsManager);
|
||||
void testEmpty() {
|
||||
PushFeedbackProcessor processor = new PushFeedbackProcessor(accountsManager, Executors.newSingleThreadExecutor());
|
||||
processor.timeAndProcessCrawlChunk(Optional.of(UUID.randomUUID()), Collections.emptyList());
|
||||
|
||||
verifyNoInteractions(accountsManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdate() throws AccountDatabaseCrawlerRestartException {
|
||||
PushFeedbackProcessor processor = new PushFeedbackProcessor(accountsManager);
|
||||
void testUpdate() {
|
||||
PushFeedbackProcessor processor = new PushFeedbackProcessor(accountsManager, Executors.newSingleThreadExecutor());
|
||||
processor.timeAndProcessCrawlChunk(Optional.of(UUID.randomUUID()),
|
||||
List.of(uninstalledAccount, mixedAccount, stillActiveAccount, freshAccount, cleanAccount));
|
||||
|
||||
|
||||
+5
-2
@@ -53,7 +53,10 @@ class UserAgentUtilTest {
|
||||
Arguments.of("Signal-iOS/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)")),
|
||||
Arguments.of("Signal-iOS/3.9.0 iOS/14.2", new UserAgent(ClientPlatform.IOS, new Semver("3.9.0"), "iOS/14.2")),
|
||||
Arguments.of("Signal-iOS/3.9.0", new UserAgent(ClientPlatform.IOS, new Semver("3.9.0")))
|
||||
);
|
||||
Arguments.of("Signal-iOS/3.9.0", new UserAgent(ClientPlatform.IOS, new Semver("3.9.0"))),
|
||||
Arguments.of("Signal-Android/7.11.23-nightly-1982-06-28-07-07-07 tonic/0.31",
|
||||
new UserAgent(ClientPlatform.ANDROID, new Semver("7.11.23-nightly-1982-06-28-07-07-07"), "tonic/0.31")),
|
||||
Arguments.of("Signal-Android/7.11.23-nightly-1982-06-28-07-07-07 Android/42 tonic/0.31",
|
||||
new UserAgent(ClientPlatform.ANDROID, new Semver("7.11.23-nightly-1982-06-28-07-07-07"), "Android/42 tonic/0.31")));
|
||||
}
|
||||
}
|
||||
Loaded 100 of 103 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user