mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-11-30 23:36:47 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
530b2a310f | ||
|
|
d5b0d99a54 | ||
|
|
43be72d076 | ||
|
|
9558944e22 | ||
|
|
0f6c866c8d | ||
|
|
bac78e9291 | ||
|
|
c22ea78672 | ||
|
|
a85afe827d | ||
|
|
abaed821ec | ||
|
|
6fa9dcd954 | ||
|
|
819d59cd79 | ||
|
|
2f88f0eedb | ||
|
|
74ff491671 | ||
|
|
eac48a6617 | ||
|
|
19617c14f8 | ||
|
|
fc7291c3e8 | ||
|
|
88db808298 | ||
|
|
5193abdab3 | ||
|
|
a315c9be92 | ||
|
|
fc1541591a | ||
|
|
ae97c4db9f | ||
|
|
26bc5973b5 | ||
|
|
e52b8c8423 | ||
|
|
7395489bac | ||
|
|
b384ed7f5c | ||
|
|
e3afcae7d3 | ||
|
|
9faeed7b20 | ||
|
|
49adcca80e | ||
|
|
49c43a6816 | ||
|
|
84f85ae098 | ||
|
|
3d581941ab | ||
|
|
d2d39baede | ||
|
|
111f5ba024 | ||
|
|
ce3fb7fa99 | ||
|
|
fc421d3f21 | ||
|
|
71bea759c6 | ||
|
|
bf1dd791a5 | ||
|
|
4c99577c08 | ||
|
|
5d5c63e6d4 | ||
|
|
42ff3f8432 | ||
|
|
be6ef76486 | ||
|
|
bc297e6d34 | ||
|
|
3a526dcbd7 | ||
|
|
7883352b74 | ||
|
|
982d122d18 | ||
|
|
d8d94407c6 | ||
|
|
28cfc54170 | ||
|
|
2ee7279743 | ||
|
|
eb1b073385 | ||
|
|
c634185b6f | ||
|
|
827a3af419 | ||
|
|
2c33d22a30 | ||
|
|
b41ed9d810 | ||
|
|
58d3a12eff | ||
|
|
88c4b2be97 | ||
|
|
6cbd57f19f | ||
|
|
5522376584 | ||
|
|
5089c37d28 | ||
|
|
1ccf24e68c | ||
|
|
411f7298f2 | ||
|
|
5b0214c6f2 | ||
|
|
735573e61b | ||
|
|
c545cff1b3 |
No files matched your search
@@ -35,6 +35,7 @@
|
||||
<commons-csv.version>1.8</commons-csv.version>
|
||||
<commons-io.version>2.9.0</commons-io.version>
|
||||
<dropwizard.version>2.0.22</dropwizard.version>
|
||||
<dropwizard-metrics-datadog.version>1.1.13</dropwizard-metrics-datadog.version>
|
||||
<guava.version>30.1.1-jre</guava.version>
|
||||
<jaxb.version>2.3.1</jaxb.version>
|
||||
<jedis.version>2.9.0</jedis.version>
|
||||
@@ -42,7 +43,7 @@
|
||||
<libphonenumber.version>8.12.23</libphonenumber.version>
|
||||
<logstash.logback.version>6.6</logstash.logback.version>
|
||||
<micrometer.version>1.5.3</micrometer.version>
|
||||
<mockito.version>2.25.1</mockito.version>
|
||||
<mockito.version>3.11.1</mockito.version>
|
||||
<netty.version>4.1.65.Final</netty.version>
|
||||
<netty.tcnative-boringssl-static.version>2.0.39.Final</netty.tcnative-boringssl-static.version>
|
||||
<opentest4j.version>1.2.0</opentest4j.version>
|
||||
@@ -171,6 +172,11 @@
|
||||
<artifactId>commons-csv</artifactId>
|
||||
<version>${commons-csv.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.coursera</groupId>
|
||||
<artifactId>dropwizard-metrics-datadog</artifactId>
|
||||
<version>${dropwizard-metrics-datadog.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jaxb</groupId>
|
||||
<artifactId>jaxb-runtime</artifactId>
|
||||
@@ -230,7 +236,7 @@
|
||||
<dependency>
|
||||
<groupId>com.github.tomakehurst</groupId>
|
||||
<artifactId>wiremock-jre8</artifactId>
|
||||
<version>2.27.2</version>
|
||||
<version>2.28.1</version>
|
||||
<scope>test</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
package org.whispersystems.dispatch;
|
||||
|
||||
public interface DispatchChannel {
|
||||
public void onDispatchMessage(String channel, byte[] message);
|
||||
public void onDispatchSubscribed(String channel);
|
||||
public void onDispatchUnsubscribed(String channel);
|
||||
void onDispatchMessage(String channel, byte[] message);
|
||||
void onDispatchSubscribed(String channel);
|
||||
void onDispatchUnsubscribed(String channel);
|
||||
}
|
||||
@@ -59,9 +59,7 @@ public class DispatchManager extends Thread {
|
||||
logger.warn("Subscription error", e);
|
||||
}
|
||||
|
||||
if (previous.isPresent()) {
|
||||
dispatchUnsubscription(name, previous.get());
|
||||
}
|
||||
previous.ifPresent(channel -> dispatchUnsubscription(name, channel));
|
||||
}
|
||||
|
||||
public synchronized void unsubscribe(String name, DispatchChannel channel) {
|
||||
@@ -132,46 +130,28 @@ public class DispatchManager extends Thread {
|
||||
}
|
||||
|
||||
private void resubscribeAll() {
|
||||
new Thread() {
|
||||
@Override
|
||||
public void run() {
|
||||
synchronized (DispatchManager.this) {
|
||||
try {
|
||||
for (String name : subscriptions.keySet()) {
|
||||
pubSubConnection.subscribe(name);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
logger.warn("***** RESUBSCRIPTION ERROR *****", e);
|
||||
new Thread(() -> {
|
||||
synchronized (DispatchManager.this) {
|
||||
try {
|
||||
for (String name : subscriptions.keySet()) {
|
||||
pubSubConnection.subscribe(name);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
logger.warn("***** RESUBSCRIPTION ERROR *****", e);
|
||||
}
|
||||
}
|
||||
}.start();
|
||||
}).start();
|
||||
}
|
||||
|
||||
private void dispatchMessage(final String name, final DispatchChannel channel, final byte[] message) {
|
||||
executor.execute(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
channel.onDispatchMessage(name, message);
|
||||
}
|
||||
});
|
||||
executor.execute(() -> channel.onDispatchMessage(name, message));
|
||||
}
|
||||
|
||||
private void dispatchSubscription(final String name, final DispatchChannel channel) {
|
||||
executor.execute(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
channel.onDispatchSubscribed(name);
|
||||
}
|
||||
});
|
||||
executor.execute(() -> channel.onDispatchSubscribed(name));
|
||||
}
|
||||
|
||||
private void dispatchUnsubscription(final String name, final DispatchChannel channel) {
|
||||
executor.execute(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
channel.onDispatchUnsubscribed(name);
|
||||
}
|
||||
});
|
||||
executor.execute(() -> channel.onDispatchUnsubscribed(name));
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -8,6 +8,6 @@ import org.whispersystems.dispatch.redis.PubSubConnection;
|
||||
|
||||
public interface RedisPubSubConnectionFactory {
|
||||
|
||||
public PubSubConnection connect();
|
||||
PubSubConnection connect();
|
||||
|
||||
}
|
||||
+129
-29
@@ -21,9 +21,6 @@ twilio: # Twilio gateway configuration
|
||||
push:
|
||||
queueSize: # Size of push pending queue
|
||||
|
||||
redphone:
|
||||
authKey: # Deprecated
|
||||
|
||||
turn: # TURN server configuration
|
||||
secret: # TURN server secret
|
||||
uris:
|
||||
@@ -36,6 +33,23 @@ cacheCluster: # Redis server configuration for cache cluster
|
||||
urls:
|
||||
- redis://redis.example.com:6379/
|
||||
|
||||
clientPresenceCluster: # Redis server configuration for client presence cluster
|
||||
urls:
|
||||
- redis://redis.example.com:6379/
|
||||
|
||||
pubsub: # Redis server configuration for pubsub cluster
|
||||
url: redis://redis.example.com:6379/
|
||||
replicaUrls:
|
||||
- redis://redis.example.com:6379/
|
||||
|
||||
pushSchedulerCluster: # Redis server configuration for push scheduler cluster
|
||||
urls:
|
||||
- redis://redis.example.com:6379/
|
||||
|
||||
rateLimitersCluster: # Redis server configuration for rate limiters cluster
|
||||
urls:
|
||||
- redis://redis.example.com:6379/
|
||||
|
||||
directory:
|
||||
client: # Configuration for interfacing with Contact Discovery Service cluster
|
||||
userAuthenticationTokenSharedSecret: # hex-encoded secret shared with CDS used to generate auth tokens for Signal users
|
||||
@@ -43,13 +57,13 @@ directory:
|
||||
sqs:
|
||||
accessKey: # AWS SQS accessKey
|
||||
accessSecret: # AWS SQS accessSecret
|
||||
queueUrl: # AWS SQS queue url
|
||||
server:
|
||||
replicationUrl: # CDS replication endpoint base url
|
||||
replicationPassword: # CDS replication endpoint password
|
||||
replicationCaCertificate: # CDS replication endpoint TLS certificate trust root
|
||||
reconciliationChunkSize: # CDS reconciliation chunk size
|
||||
reconciliationChunkIntervalMs: # CDS reconciliation chunk interval, in milliseconds
|
||||
queueUrls: # AWS SQS queue urls
|
||||
- https://sqs.example.com/directory.fifo
|
||||
server: # One or more CDS servers
|
||||
- replicationName: # CDS replication name
|
||||
replicationUrl: # CDS replication endpoint base url
|
||||
replicationPassword: # CDS replication endpoint password
|
||||
replicationCaCertificate: # CDS replication endpoint TLS certificate trust root
|
||||
|
||||
messageCache: # Redis server configuration for message store cache
|
||||
persistDelayMinutes:
|
||||
@@ -58,16 +72,44 @@ messageCache: # Redis server configuration for message store cache
|
||||
urls:
|
||||
- redis://redis.example.com:6379/
|
||||
|
||||
messageStore: # Postgresql database configuration for message store
|
||||
driverClass: org.postgresql.Driver
|
||||
user:
|
||||
password:
|
||||
url:
|
||||
|
||||
metricsCluster:
|
||||
urls:
|
||||
- redis://redis.example.com:6379/
|
||||
|
||||
messageDynamoDb: # DynamoDB table configuration
|
||||
region:
|
||||
tableName:
|
||||
|
||||
keysDynamoDb: # DynamoDB table configuration
|
||||
region:
|
||||
tableName:
|
||||
|
||||
accountsDynamoDb: # DynamoDB table configuration
|
||||
region:
|
||||
tableName:
|
||||
phoneNumberTableName:
|
||||
|
||||
deletedAccountsDynamoDb: # DynamoDb table configuration
|
||||
region:
|
||||
tableName:
|
||||
needsReconciliationIndexName:
|
||||
|
||||
migrationDeletedAccountsDynamoDb: # DynamoDB table configuration
|
||||
region:
|
||||
tableName:
|
||||
|
||||
migrationRetryAccountsDynamoDb: # DynamoDB table configuration
|
||||
region:
|
||||
tableName:
|
||||
|
||||
pushChallengeDynamoDb: # DynamoDB table configuration
|
||||
region:
|
||||
tableName:
|
||||
|
||||
reportMessageDynamoDb: # DynamoDB table configuration
|
||||
region:
|
||||
tableName:
|
||||
|
||||
awsAttachments: # AWS S3 configuration
|
||||
accessKey:
|
||||
accessSecret:
|
||||
@@ -81,18 +123,22 @@ gcpAttachments: # GCP Storage configuration
|
||||
pathPrefix:
|
||||
rsaSigningKey:
|
||||
|
||||
profiles: # AWS S3 configuration
|
||||
accessKey:
|
||||
accessSecret:
|
||||
bucket:
|
||||
region:
|
||||
|
||||
database: # Postgresql database configuration
|
||||
abuseDatabase: # Postgresql database configuration
|
||||
driverClass: org.postgresql.Driver
|
||||
user:
|
||||
password:
|
||||
url:
|
||||
|
||||
accountsDatabase: # Postgresql database configuration
|
||||
driverClass: org.postgresql.Driver
|
||||
user:
|
||||
password:
|
||||
url:
|
||||
|
||||
accountDatabaseCrawler:
|
||||
chunkSize: # accounts per run
|
||||
chunkIntervalMs: # time per run
|
||||
|
||||
apn: # Apple Push Notifications configuration
|
||||
sandbox: true
|
||||
bundleId:
|
||||
@@ -104,11 +150,52 @@ gcm: # GCM Configuration
|
||||
senderId:
|
||||
apiKey:
|
||||
|
||||
micrometer: # Micrometer metrics config
|
||||
- name: "example"
|
||||
- uri: "https://metrics.example.com/"
|
||||
- apiKey:
|
||||
- accountId:
|
||||
cdn:
|
||||
accessKey: # AWS Access Key ID
|
||||
accessSecret: # AWS Access Secret
|
||||
bucket: # S3 Bucket name
|
||||
region: # AWS region
|
||||
|
||||
wavefront: # Wavefront micrometer metrics config
|
||||
uri: # Wavefront proxy endpoint
|
||||
batchSize: # Number of measurements to send per request
|
||||
|
||||
datadog:
|
||||
apiKey:
|
||||
environment:
|
||||
|
||||
unidentifiedDelivery:
|
||||
certificate:
|
||||
privateKey:
|
||||
expiresDays:
|
||||
|
||||
voiceVerification:
|
||||
url: https://cdn-ca.signal.org/verification/
|
||||
locales:
|
||||
- en
|
||||
|
||||
recaptcha:
|
||||
secret:
|
||||
|
||||
storageService:
|
||||
uri:
|
||||
userAuthenticationTokenSharedSecret:
|
||||
storageCaCertificate:
|
||||
|
||||
backupService:
|
||||
uri:
|
||||
userAuthenticationTokenSharedSecret:
|
||||
backupCaCertificate:
|
||||
|
||||
zkConfig:
|
||||
serverPublic:
|
||||
serverSecret:
|
||||
enabled:
|
||||
|
||||
appConfig:
|
||||
application:
|
||||
environment:
|
||||
configuration:
|
||||
|
||||
remoteConfig:
|
||||
authorizedTokens:
|
||||
@@ -118,9 +205,22 @@ remoteConfig:
|
||||
- # Nth authorized token
|
||||
globalConfig: # keys and values that are given to clients on GET /v1/config
|
||||
|
||||
paymentService:
|
||||
|
||||
paymentsService:
|
||||
userAuthenticationTokenSharedSecret: # hex-encoded 32-byte secret shared with MobileCoin services used to generate auth tokens for Signal users
|
||||
|
||||
torExitNodeList:
|
||||
s3Region:
|
||||
s3Bucket:
|
||||
objectKey:
|
||||
maxSize:
|
||||
|
||||
asnTable:
|
||||
s3Region:
|
||||
s3Bucket:
|
||||
objectKey:
|
||||
maxSize:
|
||||
|
||||
donation:
|
||||
uri: # value
|
||||
apiKey: # value
|
||||
|
||||
+13
-10
@@ -226,7 +226,10 @@
|
||||
<groupId>io.micrometer</groupId>
|
||||
<artifactId>micrometer-registry-datadog</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.coursera</groupId>
|
||||
<artifactId>dropwizard-metrics-datadog</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-core</artifactId>
|
||||
@@ -256,6 +259,14 @@
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>s3</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>sqs</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>dynamodb</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-java-sdk-core</artifactId>
|
||||
@@ -264,18 +275,10 @@
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-java-sdk-s3</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-java-sdk-sqs</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-java-sdk-appconfig</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-java-sdk-dynamodb</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>redis.clients</groupId>
|
||||
@@ -407,7 +410,7 @@
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>DynamoDBLocal</artifactId>
|
||||
<version>1.13.6</version>
|
||||
<version>1.16.0</version>
|
||||
<scope>test</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
|
||||
+28
@@ -22,6 +22,7 @@ import org.whispersystems.textsecuregcm.configuration.AwsAttachmentsConfiguratio
|
||||
import org.whispersystems.textsecuregcm.configuration.CdnConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.DatabaseConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.DatadogConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.DeletedAccountsDynamoDbConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.DirectoryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.DonationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.DynamoDbConfiguration;
|
||||
@@ -157,6 +158,11 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private DynamoDbConfiguration migrationRetryAccountsDynamoDb;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private DeletedAccountsDynamoDbConfiguration deletedAccountsDynamoDb;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
@@ -167,6 +173,16 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private DynamoDbConfiguration reportMessageDynamoDb;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private DynamoDbConfiguration pendingAccountsDynamoDb;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private DynamoDbConfiguration pendingDevicesDynamoDb;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
@@ -371,6 +387,10 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return migrationRetryAccountsDynamoDb;
|
||||
}
|
||||
|
||||
public DeletedAccountsDynamoDbConfiguration getDeletedAccountsDynamoDbConfiguration() {
|
||||
return deletedAccountsDynamoDb;
|
||||
}
|
||||
|
||||
public DatabaseConfiguration getAbuseDatabaseConfiguration() {
|
||||
return abuseDatabase;
|
||||
}
|
||||
@@ -465,6 +485,14 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return reportMessageDynamoDb;
|
||||
}
|
||||
|
||||
public DynamoDbConfiguration getPendingAccountsDynamoDbConfiguration() {
|
||||
return pendingAccountsDynamoDb;
|
||||
}
|
||||
|
||||
public DynamoDbConfiguration getPendingDevicesDynamoDbConfiguration() {
|
||||
return pendingDevicesDynamoDb;
|
||||
}
|
||||
|
||||
public MonitoredS3ObjectConfiguration getTorExitNodeListConfiguration() {
|
||||
return torExitNodeList;
|
||||
}
|
||||
|
||||
@@ -6,19 +6,6 @@ package org.whispersystems.textsecuregcm;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.amazonaws.ClientConfiguration;
|
||||
import com.amazonaws.auth.AWSCredentials;
|
||||
import com.amazonaws.auth.AWSCredentialsProvider;
|
||||
import com.amazonaws.auth.AWSStaticCredentialsProvider;
|
||||
import com.amazonaws.auth.BasicAWSCredentials;
|
||||
import com.amazonaws.auth.InstanceProfileCredentialsProvider;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBAsync;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBAsyncClientBuilder;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
|
||||
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
|
||||
import com.amazonaws.services.s3.AmazonS3;
|
||||
import com.amazonaws.services.s3.AmazonS3Client;
|
||||
import com.codahale.metrics.SharedMetricRegistries;
|
||||
import com.codahale.metrics.jdbi3.strategies.DefaultNameStrategy;
|
||||
import com.fasterxml.jackson.annotation.JsonAutoDetect;
|
||||
@@ -39,12 +26,11 @@ import io.dropwizard.setup.Bootstrap;
|
||||
import io.dropwizard.setup.Environment;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
import io.micrometer.core.instrument.Clock;
|
||||
import io.micrometer.core.instrument.Meter;
|
||||
import io.micrometer.core.instrument.Meter.Id;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.config.MeterFilter;
|
||||
import io.micrometer.core.instrument.distribution.DistributionStatisticConfig;
|
||||
import io.micrometer.datadog.DatadogConfig;
|
||||
import io.micrometer.datadog.DatadogMeterRegistry;
|
||||
import io.micrometer.wavefront.WavefrontConfig;
|
||||
import io.micrometer.wavefront.WavefrontMeterRegistry;
|
||||
@@ -70,6 +56,8 @@ import org.jdbi.v3.core.Jdbi;
|
||||
import org.signal.zkgroup.ServerSecretParams;
|
||||
import org.signal.zkgroup.auth.ServerZkAuthOperations;
|
||||
import org.signal.zkgroup.profiles.ServerZkProfileOperations;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.dispatch.DispatchManager;
|
||||
import org.whispersystems.textsecuregcm.auth.AccountAuthenticator;
|
||||
import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
|
||||
@@ -127,7 +115,6 @@ import org.whispersystems.textsecuregcm.metrics.MetricsApplicationEventListener;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsRequestEventListener;
|
||||
import org.whispersystems.textsecuregcm.metrics.NetworkReceivedGauge;
|
||||
import org.whispersystems.textsecuregcm.metrics.NetworkSentGauge;
|
||||
import org.whispersystems.textsecuregcm.metrics.NstatCounters;
|
||||
import org.whispersystems.textsecuregcm.metrics.OperatingSystemMemoryGauge;
|
||||
import org.whispersystems.textsecuregcm.metrics.PushLatencyManager;
|
||||
import org.whispersystems.textsecuregcm.metrics.TrafficSource;
|
||||
@@ -164,6 +151,9 @@ import org.whispersystems.textsecuregcm.storage.AccountsDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsDynamoDbMigrator;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ActiveUserCounter;
|
||||
import org.whispersystems.textsecuregcm.storage.DeletedAccounts;
|
||||
import org.whispersystems.textsecuregcm.storage.DeletedAccountsDirectoryReconciler;
|
||||
import org.whispersystems.textsecuregcm.storage.DeletedAccountsTableCrawler;
|
||||
import org.whispersystems.textsecuregcm.storage.DirectoryReconciler;
|
||||
import org.whispersystems.textsecuregcm.storage.DirectoryReconciliationClient;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
@@ -175,6 +165,7 @@ import org.whispersystems.textsecuregcm.storage.MessagesDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.MigrationDeletedAccounts;
|
||||
import org.whispersystems.textsecuregcm.storage.MigrationRetryAccounts;
|
||||
import org.whispersystems.textsecuregcm.storage.MigrationRetryAccountsTableCrawler;
|
||||
import org.whispersystems.textsecuregcm.storage.PendingAccounts;
|
||||
import org.whispersystems.textsecuregcm.storage.PendingAccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PendingDevices;
|
||||
@@ -192,17 +183,19 @@ import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ReservedUsernames;
|
||||
import org.whispersystems.textsecuregcm.storage.Usernames;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernamesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationCodeStoreDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.util.AsnManager;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
import org.whispersystems.textsecuregcm.util.DynamoDbFromConfig;
|
||||
import org.whispersystems.textsecuregcm.util.HostnameUtil;
|
||||
import org.whispersystems.textsecuregcm.util.TorExitNodeManager;
|
||||
import org.whispersystems.textsecuregcm.websocket.AuthenticatedConnectListener;
|
||||
import org.whispersystems.textsecuregcm.websocket.DeadLetterHandler;
|
||||
import org.whispersystems.textsecuregcm.websocket.ProvisioningConnectListener;
|
||||
import org.whispersystems.textsecuregcm.websocket.WebSocketAccountAuthenticator;
|
||||
import org.whispersystems.textsecuregcm.workers.CertificateCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CheckDynamicConfigurationCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.GetRedisCommandStatsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.GetRedisSlowlogCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ServerVersionCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.SetCrawlerAccelerationTask;
|
||||
import org.whispersystems.textsecuregcm.workers.SetRequestLoggingEnabledTask;
|
||||
@@ -210,18 +203,25 @@ import org.whispersystems.textsecuregcm.workers.VacuumCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ZkParamsCommand;
|
||||
import org.whispersystems.websocket.WebSocketResourceProviderFactory;
|
||||
import org.whispersystems.websocket.setup.WebSocketEnvironment;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.s3.S3Client;
|
||||
|
||||
public class WhisperServerService extends Application<WhisperServerConfiguration> {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(WhisperServerService.class);
|
||||
|
||||
@Override
|
||||
public void initialize(Bootstrap<WhisperServerConfiguration> bootstrap) {
|
||||
bootstrap.addCommand(new VacuumCommand());
|
||||
bootstrap.addCommand(new DeleteUserCommand());
|
||||
bootstrap.addCommand(new CertificateCommand());
|
||||
bootstrap.addCommand(new ZkParamsCommand());
|
||||
bootstrap.addCommand(new GetRedisSlowlogCommand());
|
||||
bootstrap.addCommand(new GetRedisCommandStatsCommand());
|
||||
bootstrap.addCommand(new ServerVersionCommand());
|
||||
bootstrap.addCommand(new CheckDynamicConfigurationCommand());
|
||||
|
||||
bootstrap.addBundle(new NameableMigrationsBundle<WhisperServerConfiguration>("accountdb", "accountsdb.xml") {
|
||||
@Override
|
||||
@@ -279,28 +279,24 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
});
|
||||
|
||||
{
|
||||
final DatadogMeterRegistry datadogMeterRegistry = new DatadogMeterRegistry(new DatadogConfig() {
|
||||
@Override
|
||||
public String get(final String key) {
|
||||
return null;
|
||||
}
|
||||
final DatadogMeterRegistry datadogMeterRegistry = new DatadogMeterRegistry(config.getDatadogConfiguration(), Clock.SYSTEM);
|
||||
|
||||
@Override
|
||||
public String apiKey() {
|
||||
return config.getDatadogConfiguration().getApiKey();
|
||||
}
|
||||
}, Clock.SYSTEM);
|
||||
|
||||
datadogMeterRegistry.config().meterFilter(new MeterFilter() {
|
||||
@Override
|
||||
public DistributionStatisticConfig configure(final Id id, final DistributionStatisticConfig config) {
|
||||
return defaultDistributionStatisticConfig.merge(config);
|
||||
}
|
||||
})
|
||||
datadogMeterRegistry.config().commonTags(
|
||||
Tags.of(
|
||||
"service", "chat",
|
||||
"host", HostnameUtil.getLocalHostname(),
|
||||
"version", WhisperServerVersion.getServerVersion(),
|
||||
"env", config.getDatadogConfiguration().getEnvironment()))
|
||||
.meterFilter(MeterFilter.denyNameStartsWith(MetricsRequestEventListener.REQUEST_COUNTER_NAME))
|
||||
.meterFilter(MeterFilter.denyNameStartsWith(MetricsRequestEventListener.ANDROID_REQUEST_COUNTER_NAME))
|
||||
.meterFilter(MeterFilter.denyNameStartsWith(MetricsRequestEventListener.DESKTOP_REQUEST_COUNTER_NAME))
|
||||
.meterFilter(MeterFilter.denyNameStartsWith(MetricsRequestEventListener.IOS_REQUEST_COUNTER_NAME));
|
||||
.meterFilter(MeterFilter.denyNameStartsWith(MetricsRequestEventListener.IOS_REQUEST_COUNTER_NAME))
|
||||
.meterFilter(new MeterFilter() {
|
||||
@Override
|
||||
public DistributionStatisticConfig configure(final Id id, final DistributionStatisticConfig config) {
|
||||
return defaultDistributionStatisticConfig.merge(config);
|
||||
}
|
||||
});
|
||||
|
||||
Metrics.addRegistry(datadogMeterRegistry);
|
||||
}
|
||||
@@ -316,80 +312,50 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
FaultTolerantDatabase accountDatabase = new FaultTolerantDatabase("accounts_database", accountJdbi, config.getAccountsDatabaseConfiguration().getCircuitBreakerConfiguration());
|
||||
FaultTolerantDatabase abuseDatabase = new FaultTolerantDatabase("abuse_database", abuseJdbi, config.getAbuseDatabaseConfiguration().getCircuitBreakerConfiguration());
|
||||
|
||||
AmazonDynamoDBClientBuilder messageDynamoDbClientBuilder = AmazonDynamoDBClientBuilder
|
||||
.standard()
|
||||
.withRegion(config.getMessageDynamoDbConfiguration().getRegion())
|
||||
.withClientConfiguration(new ClientConfiguration().withClientExecutionTimeout(((int) config.getMessageDynamoDbConfiguration().getClientExecutionTimeout().toMillis()))
|
||||
.withRequestTimeout((int) config.getMessageDynamoDbConfiguration().getClientRequestTimeout().toMillis()))
|
||||
.withCredentials(InstanceProfileCredentialsProvider.getInstance());
|
||||
DynamoDbClient messageDynamoDb = DynamoDbFromConfig.client(config.getMessageDynamoDbConfiguration(),
|
||||
software.amazon.awssdk.auth.credentials.InstanceProfileCredentialsProvider.create());
|
||||
|
||||
AmazonDynamoDBClientBuilder keysDynamoDbClientBuilder = AmazonDynamoDBClientBuilder
|
||||
.standard()
|
||||
.withRegion(config.getKeysDynamoDbConfiguration().getRegion())
|
||||
.withClientConfiguration(new ClientConfiguration().withClientExecutionTimeout(((int) config.getKeysDynamoDbConfiguration().getClientExecutionTimeout().toMillis()))
|
||||
.withRequestTimeout((int) config.getKeysDynamoDbConfiguration().getClientRequestTimeout().toMillis()))
|
||||
.withCredentials(InstanceProfileCredentialsProvider.getInstance());
|
||||
DynamoDbClient preKeyDynamoDb = DynamoDbFromConfig.client(config.getKeysDynamoDbConfiguration(),
|
||||
software.amazon.awssdk.auth.credentials.InstanceProfileCredentialsProvider.create());
|
||||
|
||||
AmazonDynamoDBClientBuilder accountsDynamoDbClientBuilder = AmazonDynamoDBClientBuilder
|
||||
.standard()
|
||||
.withRegion(config.getAccountsDynamoDbConfiguration().getRegion())
|
||||
.withClientConfiguration(new ClientConfiguration().withClientExecutionTimeout(((int) config.getAccountsDynamoDbConfiguration().getClientExecutionTimeout().toMillis()))
|
||||
.withRequestTimeout((int) config.getAccountsDynamoDbConfiguration().getClientRequestTimeout().toMillis()))
|
||||
.withCredentials(InstanceProfileCredentialsProvider.getInstance());
|
||||
DynamoDbClient accountsDynamoDbClient = DynamoDbFromConfig.client(config.getAccountsDynamoDbConfiguration(),
|
||||
software.amazon.awssdk.auth.credentials.InstanceProfileCredentialsProvider.create());
|
||||
|
||||
// The thread pool core & max sizes are set via dynamic configuration within AccountsDynamoDb
|
||||
ThreadPoolExecutor accountsDynamoDbMigrationThreadPool = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS,
|
||||
new LinkedBlockingDeque<>());
|
||||
|
||||
AmazonDynamoDBAsyncClientBuilder accountsDynamoDbAsyncClientBuilder = AmazonDynamoDBAsyncClientBuilder
|
||||
.standard()
|
||||
.withRegion(accountsDynamoDbClientBuilder.getRegion())
|
||||
.withClientConfiguration(accountsDynamoDbClientBuilder.getClientConfiguration())
|
||||
.withCredentials(accountsDynamoDbClientBuilder.getCredentials())
|
||||
.withExecutorFactory(() -> accountsDynamoDbMigrationThreadPool);
|
||||
DynamoDbAsyncClient accountsDynamoDbAsyncClient = DynamoDbFromConfig.asyncClient(config.getAccountsDynamoDbConfiguration(),
|
||||
software.amazon.awssdk.auth.credentials.InstanceProfileCredentialsProvider.create(),
|
||||
accountsDynamoDbMigrationThreadPool);
|
||||
|
||||
AmazonDynamoDBClientBuilder migrationDeletedAccountsDynamoDbClientBuilder = AmazonDynamoDBClientBuilder
|
||||
.standard()
|
||||
.withRegion(config.getMigrationDeletedAccountsDynamoDbConfiguration().getRegion())
|
||||
.withClientConfiguration(new ClientConfiguration().withClientExecutionTimeout(((int) config.getMigrationDeletedAccountsDynamoDbConfiguration().getClientExecutionTimeout().toMillis()))
|
||||
.withRequestTimeout((int) config.getMigrationDeletedAccountsDynamoDbConfiguration().getClientRequestTimeout().toMillis()))
|
||||
.withCredentials(InstanceProfileCredentialsProvider.getInstance());
|
||||
DynamoDbClient deletedAccountsDynamoDbClient = DynamoDbFromConfig.client(config.getDeletedAccountsDynamoDbConfiguration(),
|
||||
software.amazon.awssdk.auth.credentials.InstanceProfileCredentialsProvider.create());
|
||||
|
||||
AmazonDynamoDBClientBuilder migrationRetryAccountsDynamoDbClientBuilder = AmazonDynamoDBClientBuilder
|
||||
.standard()
|
||||
.withRegion(config.getMigrationRetryAccountsDynamoDbConfiguration().getRegion())
|
||||
.withClientConfiguration(new ClientConfiguration().withClientExecutionTimeout(((int) config.getMigrationRetryAccountsDynamoDbConfiguration().getClientExecutionTimeout().toMillis()))
|
||||
.withRequestTimeout((int) config.getMigrationRetryAccountsDynamoDbConfiguration().getClientRequestTimeout().toMillis()))
|
||||
.withCredentials(InstanceProfileCredentialsProvider.getInstance());
|
||||
DynamoDbClient recentlyDeletedAccountsDynamoDb = DynamoDbFromConfig.client(config.getMigrationDeletedAccountsDynamoDbConfiguration(),
|
||||
software.amazon.awssdk.auth.credentials.InstanceProfileCredentialsProvider.create());
|
||||
|
||||
AmazonDynamoDBClientBuilder pushChallengeDynamoDbClientBuilder = AmazonDynamoDBClientBuilder
|
||||
.standard()
|
||||
.withRegion(config.getPushChallengeDynamoDbConfiguration().getRegion())
|
||||
.withClientConfiguration(new ClientConfiguration().withClientExecutionTimeout(((int) config.getPushChallengeDynamoDbConfiguration().getClientExecutionTimeout().toMillis()))
|
||||
.withRequestTimeout((int) config.getPushChallengeDynamoDbConfiguration().getClientRequestTimeout().toMillis()))
|
||||
.withCredentials(InstanceProfileCredentialsProvider.getInstance());
|
||||
DynamoDbClient pushChallengeDynamoDbClient = DynamoDbFromConfig.client(config.getPushChallengeDynamoDbConfiguration(),
|
||||
software.amazon.awssdk.auth.credentials.InstanceProfileCredentialsProvider.create());
|
||||
|
||||
AmazonDynamoDBClientBuilder reportMessageDynamoDbClientBuilder = AmazonDynamoDBClientBuilder
|
||||
.standard()
|
||||
.withRegion(config.getReportMessageDynamoDbConfiguration().getRegion())
|
||||
.withClientConfiguration(new ClientConfiguration().withClientExecutionTimeout(((int) config.getReportMessageDynamoDbConfiguration().getClientExecutionTimeout().toMillis()))
|
||||
.withRequestTimeout((int) config.getReportMessageDynamoDbConfiguration().getClientRequestTimeout().toMillis()))
|
||||
.withCredentials(InstanceProfileCredentialsProvider.getInstance());
|
||||
DynamoDbClient reportMessageDynamoDbClient = DynamoDbFromConfig.client(config.getReportMessageDynamoDbConfiguration(),
|
||||
software.amazon.awssdk.auth.credentials.InstanceProfileCredentialsProvider.create());
|
||||
|
||||
DynamoDB messageDynamoDb = new DynamoDB(messageDynamoDbClientBuilder.build());
|
||||
DynamoDB preKeyDynamoDb = new DynamoDB(keysDynamoDbClientBuilder.build());
|
||||
DynamoDbClient migrationRetryAccountsDynamoDb = DynamoDbFromConfig.client(config.getMigrationRetryAccountsDynamoDbConfiguration(),
|
||||
software.amazon.awssdk.auth.credentials.InstanceProfileCredentialsProvider.create());
|
||||
|
||||
AmazonDynamoDB accountsDynamoDbClient = accountsDynamoDbClientBuilder.build();
|
||||
AmazonDynamoDBAsync accountsDynamodbAsyncClient = accountsDynamoDbAsyncClientBuilder.build();
|
||||
DynamoDbClient pendingAccountsDynamoDbClient = DynamoDbFromConfig.client(config.getPendingAccountsDynamoDbConfiguration(),
|
||||
software.amazon.awssdk.auth.credentials.InstanceProfileCredentialsProvider.create());
|
||||
|
||||
DynamoDB recentlyDeletedAccountsDynamoDb = new DynamoDB(migrationDeletedAccountsDynamoDbClientBuilder.build());
|
||||
DynamoDB migrationRetryAccountsDynamoDb = new DynamoDB(migrationRetryAccountsDynamoDbClientBuilder.build());
|
||||
DynamoDbClient pendingDevicesDynamoDbClient = DynamoDbFromConfig.client(config.getPendingDevicesDynamoDbConfiguration(),
|
||||
software.amazon.awssdk.auth.credentials.InstanceProfileCredentialsProvider.create());
|
||||
|
||||
DeletedAccounts deletedAccounts = new DeletedAccounts(deletedAccountsDynamoDbClient, config.getDeletedAccountsDynamoDbConfiguration().getTableName(), config.getDeletedAccountsDynamoDbConfiguration().getNeedsReconciliationIndexName());
|
||||
MigrationDeletedAccounts migrationDeletedAccounts = new MigrationDeletedAccounts(recentlyDeletedAccountsDynamoDb, config.getMigrationDeletedAccountsDynamoDbConfiguration().getTableName());
|
||||
MigrationRetryAccounts migrationRetryAccounts = new MigrationRetryAccounts(migrationRetryAccountsDynamoDb, config.getMigrationRetryAccountsDynamoDbConfiguration().getTableName());
|
||||
|
||||
Accounts accounts = new Accounts(accountDatabase);
|
||||
AccountsDynamoDb accountsDynamoDb = new AccountsDynamoDb(accountsDynamoDbClient, accountsDynamodbAsyncClient, accountsDynamoDbMigrationThreadPool, new DynamoDB(accountsDynamoDbClient), config.getAccountsDynamoDbConfiguration().getTableName(), config.getAccountsDynamoDbConfiguration().getPhoneNumberTableName(), migrationDeletedAccounts, migrationRetryAccounts);
|
||||
AccountsDynamoDb accountsDynamoDb = new AccountsDynamoDb(accountsDynamoDbClient, accountsDynamoDbAsyncClient, accountsDynamoDbMigrationThreadPool, config.getAccountsDynamoDbConfiguration().getTableName(), config.getAccountsDynamoDbConfiguration().getPhoneNumberTableName(), migrationDeletedAccounts, migrationRetryAccounts);
|
||||
PendingAccounts pendingAccounts = new PendingAccounts(accountDatabase);
|
||||
PendingDevices pendingDevices = new PendingDevices (accountDatabase);
|
||||
Usernames usernames = new Usernames(accountDatabase);
|
||||
@@ -399,8 +365,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
MessagesDynamoDb messagesDynamoDb = new MessagesDynamoDb(messageDynamoDb, config.getMessageDynamoDbConfiguration().getTableName(), config.getMessageDynamoDbConfiguration().getTimeToLive());
|
||||
AbusiveHostRules abusiveHostRules = new AbusiveHostRules(abuseDatabase);
|
||||
RemoteConfigs remoteConfigs = new RemoteConfigs(accountDatabase);
|
||||
PushChallengeDynamoDb pushChallengeDynamoDb = new PushChallengeDynamoDb(new DynamoDB(pushChallengeDynamoDbClientBuilder.build()), config.getPushChallengeDynamoDbConfiguration().getTableName());
|
||||
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(new DynamoDB(reportMessageDynamoDbClientBuilder.build()), config.getReportMessageDynamoDbConfiguration().getTableName());
|
||||
PushChallengeDynamoDb pushChallengeDynamoDb = new PushChallengeDynamoDb(pushChallengeDynamoDbClient, config.getPushChallengeDynamoDbConfiguration().getTableName());
|
||||
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(reportMessageDynamoDbClient, config.getReportMessageDynamoDbConfiguration().getTableName());
|
||||
VerificationCodeStoreDynamoDb pendingAccountsDynamoDb = new VerificationCodeStoreDynamoDb(pendingAccountsDynamoDbClient, config.getPendingAccountsDynamoDbConfiguration().getTableName());
|
||||
VerificationCodeStoreDynamoDb pendingDevicesDynamoDb = new VerificationCodeStoreDynamoDb(pendingDevicesDynamoDbClient, config.getPendingDevicesDynamoDbConfiguration().getTableName());
|
||||
|
||||
RedisClientFactory pubSubClientFactory = new RedisClientFactory("pubsub_cache", config.getPubsubCacheConfiguration().getUrl(), config.getPubsubCacheConfiguration().getReplicaUrls(), config.getPubsubCacheConfiguration().getCircuitBreakerConfiguration());
|
||||
ReplicatedJedisPool pubsubClient = pubSubClientFactory.getRedisClientPool();
|
||||
@@ -427,7 +395,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
BlockingQueue<Runnable> keyspaceNotificationDispatchQueue = new ArrayBlockingQueue<>(10_000);
|
||||
Metrics.gaugeCollectionSize(name(getClass(), "keyspaceNotificationDispatchQueueSize"), Collections.emptyList(), keyspaceNotificationDispatchQueue);
|
||||
|
||||
ScheduledExecutorService recurringJobExecutor = environment.lifecycle().scheduledExecutorService(name(getClass(), "recurringJob-%d")).threads(2).build();
|
||||
ScheduledExecutorService recurringJobExecutor = environment.lifecycle().scheduledExecutorService(name(getClass(), "recurringJob-%d")).threads(3).build();
|
||||
ScheduledExecutorService declinedMessageReceiptExecutor = environment.lifecycle().scheduledExecutorService(name(getClass(), "declined-receipt-%d")).threads(2).build();
|
||||
ScheduledExecutorService retrySchedulingExecutor = environment.lifecycle().scheduledExecutorService(name(getClass(), "retry-%d")).threads(2).build();
|
||||
ExecutorService keyspaceNotificationDispatchExecutor = environment.lifecycle().executorService(name(getClass(), "keyspaceNotification-%d")).maxThreads(16).workQueue(keyspaceNotificationDispatchQueue).build();
|
||||
@@ -457,15 +425,15 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
SecureStorageClient secureStorageClient = new SecureStorageClient(storageCredentialsGenerator, storageServiceExecutor, config.getSecureStorageServiceConfiguration());
|
||||
ClientPresenceManager clientPresenceManager = new ClientPresenceManager(clientPresenceCluster, recurringJobExecutor, keyspaceNotificationDispatchExecutor);
|
||||
DirectoryQueue directoryQueue = new DirectoryQueue(config.getDirectoryConfiguration().getSqsConfiguration());
|
||||
PendingAccountsManager pendingAccountsManager = new PendingAccountsManager(pendingAccounts, cacheCluster);
|
||||
PendingDevicesManager pendingDevicesManager = new PendingDevicesManager(pendingDevices, cacheCluster);
|
||||
PendingAccountsManager pendingAccountsManager = new PendingAccountsManager(pendingAccounts, pendingAccountsDynamoDb, dynamicConfigurationManager);
|
||||
PendingDevicesManager pendingDevicesManager = new PendingDevicesManager(pendingDevices, pendingDevicesDynamoDb, dynamicConfigurationManager);
|
||||
UsernamesManager usernamesManager = new UsernamesManager(usernames, reservedUsernames, cacheCluster);
|
||||
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster);
|
||||
MessagesCache messagesCache = new MessagesCache(messagesCluster, messagesCluster, keyspaceNotificationDispatchExecutor);
|
||||
PushLatencyManager pushLatencyManager = new PushLatencyManager(metricsCluster);
|
||||
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, Metrics.globalRegistry);
|
||||
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, pushLatencyManager, reportMessageManager);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, accountsDynamoDb, cacheCluster, directoryQueue, keysDynamoDb, messagesManager, usernamesManager, profilesManager, secureStorageClient, secureBackupClient, experimentEnrollmentManager, dynamicConfigurationManager);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, accountsDynamoDb, cacheCluster, deletedAccounts, directoryQueue, keysDynamoDb, messagesManager, usernamesManager, profilesManager, secureStorageClient, secureBackupClient, experimentEnrollmentManager, dynamicConfigurationManager);
|
||||
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs);
|
||||
DeadLetterHandler deadLetterHandler = new DeadLetterHandler(accountsManager, messagesManager);
|
||||
DispatchManager dispatchManager = new DispatchManager(pubSubClientFactory, Optional.of(deadLetterHandler));
|
||||
@@ -497,6 +465,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
MessagePersister messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager, dynamicConfigurationManager, Duration.ofMinutes(config.getMessageCacheConfiguration().getPersistDelayMinutes()));
|
||||
|
||||
final List<DeletedAccountsDirectoryReconciler> deletedAccountsDirectoryReconcilers = new ArrayList<>();
|
||||
final List<AccountDatabaseCrawlerListener> accountDatabaseCrawlerListeners = new ArrayList<>();
|
||||
accountDatabaseCrawlerListeners.add(new PushFeedbackProcessor(accountsManager, directoryQueue));
|
||||
accountDatabaseCrawlerListeners.add(new ActiveUserCounter(config.getMetricsFactory(), cacheCluster));
|
||||
@@ -504,6 +473,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
final DirectoryReconciliationClient directoryReconciliationClient = new DirectoryReconciliationClient(directoryServerConfiguration);
|
||||
final DirectoryReconciler directoryReconciler = new DirectoryReconciler(directoryServerConfiguration.getReplicationName(), directoryReconciliationClient);
|
||||
accountDatabaseCrawlerListeners.add(directoryReconciler);
|
||||
|
||||
final DeletedAccountsDirectoryReconciler deletedAccountsDirectoryReconciler = new DeletedAccountsDirectoryReconciler(directoryServerConfiguration.getReplicationName(), directoryReconciliationClient);
|
||||
deletedAccountsDirectoryReconcilers.add(deletedAccountsDirectoryReconciler);
|
||||
}
|
||||
accountDatabaseCrawlerListeners.add(new AccountCleaner(accountsManager));
|
||||
accountDatabaseCrawlerListeners.add(new RegistrationLockVersionCounter(metricsCluster, config.getMetricsFactory()));
|
||||
@@ -517,11 +489,16 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
AccountDatabaseCrawlerCache accountDatabaseCrawlerCache = new AccountDatabaseCrawlerCache(cacheCluster);
|
||||
AccountDatabaseCrawler accountDatabaseCrawler = new AccountDatabaseCrawler(accountsManager, accountDatabaseCrawlerCache, accountDatabaseCrawlerListeners, config.getAccountDatabaseCrawlerConfiguration().getChunkSize(), config.getAccountDatabaseCrawlerConfiguration().getChunkIntervalMs());
|
||||
|
||||
DeletedAccountsTableCrawler deletedAccountsTableCrawler = new DeletedAccountsTableCrawler(deletedAccounts, deletedAccountsDirectoryReconcilers, cacheCluster, recurringJobExecutor);
|
||||
MigrationRetryAccountsTableCrawler migrationRetryAccountsTableCrawler = new MigrationRetryAccountsTableCrawler(migrationRetryAccounts, accountsManager, accountsDynamoDb, cacheCluster, recurringJobExecutor);
|
||||
|
||||
apnSender.setApnFallbackManager(apnFallbackManager);
|
||||
environment.lifecycle().manage(apnFallbackManager);
|
||||
environment.lifecycle().manage(pubSubManager);
|
||||
environment.lifecycle().manage(messageSender);
|
||||
environment.lifecycle().manage(accountDatabaseCrawler);
|
||||
environment.lifecycle().manage(deletedAccountsTableCrawler);
|
||||
environment.lifecycle().manage(migrationRetryAccountsTableCrawler);
|
||||
environment.lifecycle().manage(remoteConfigsManager);
|
||||
environment.lifecycle().manage(messagesCache);
|
||||
environment.lifecycle().manage(messagePersister);
|
||||
@@ -530,9 +507,14 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
environment.lifecycle().manage(torExitNodeManager);
|
||||
environment.lifecycle().manage(asnManager);
|
||||
|
||||
AWSCredentials credentials = new BasicAWSCredentials(config.getCdnConfiguration().getAccessKey(), config.getCdnConfiguration().getAccessSecret());
|
||||
AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);
|
||||
AmazonS3 cdnS3Client = AmazonS3Client.builder().withCredentials(credentialsProvider).withRegion(config.getCdnConfiguration().getRegion()).build();
|
||||
StaticCredentialsProvider cdnCredentialsProvider = StaticCredentialsProvider
|
||||
.create(AwsBasicCredentials.create(
|
||||
config.getCdnConfiguration().getAccessKey(),
|
||||
config.getCdnConfiguration().getAccessSecret()));
|
||||
S3Client cdnS3Client = S3Client.builder()
|
||||
.credentialsProvider(cdnCredentialsProvider)
|
||||
.region(Region.of(config.getCdnConfiguration().getRegion()))
|
||||
.build();
|
||||
PostPolicyGenerator profileCdnPolicyGenerator = new PostPolicyGenerator(config.getCdnConfiguration().getRegion(), config.getCdnConfiguration().getBucket(), config.getCdnConfiguration().getAccessKey());
|
||||
PolicySigner profileCdnPolicySigner = new PolicySigner(config.getCdnConfiguration().getAccessSecret(), config.getCdnConfiguration().getRegion());
|
||||
|
||||
@@ -643,8 +625,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
BufferPoolGauges.registerMetrics();
|
||||
GarbageCollectionGauges.registerMetrics();
|
||||
|
||||
new NstatCounters().registerMetrics(recurringJobExecutor, wavefrontConfig.step());
|
||||
}
|
||||
|
||||
private void registerExceptionMappers(Environment environment, WebSocketEnvironment<Account> webSocketEnvironment, WebSocketEnvironment<Account> provisioningEnvironment) {
|
||||
|
||||
+43
-38
@@ -5,45 +5,34 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import com.codahale.metrics.Meter;
|
||||
import com.codahale.metrics.MetricRegistry;
|
||||
import com.codahale.metrics.SharedMetricRegistries;
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.auth.basic.BasicCredentials;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Optional;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
public class BaseAccountAuthenticator {
|
||||
|
||||
private final MetricRegistry metricRegistry = SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME);
|
||||
private final Meter authenticationFailedMeter = metricRegistry.meter(name(getClass(), "authentication", "failed" ));
|
||||
private final Meter authenticationSucceededMeter = metricRegistry.meter(name(getClass(), "authentication", "succeeded" ));
|
||||
private final Meter noSuchAccountMeter = metricRegistry.meter(name(getClass(), "authentication", "noSuchAccount" ));
|
||||
private final Meter noSuchDeviceMeter = metricRegistry.meter(name(getClass(), "authentication", "noSuchDevice" ));
|
||||
private final Meter accountDisabledMeter = metricRegistry.meter(name(getClass(), "authentication", "accountDisabled"));
|
||||
private final Meter deviceDisabledMeter = metricRegistry.meter(name(getClass(), "authentication", "deviceDisabled" ));
|
||||
private final Meter invalidAuthHeaderMeter = metricRegistry.meter(name(getClass(), "authentication", "invalidHeader" ));
|
||||
|
||||
private final String daysSinceLastSeenDistributionName = name(getClass(), "authentication", "daysSinceLastSeen");
|
||||
private static final String AUTHENTICATION_COUNTER_NAME = name(BaseAccountAuthenticator.class, "authentication");
|
||||
private static final String AUTHENTICATION_SUCCEEDED_TAG_NAME = "succeeded";
|
||||
private static final String AUTHENTICATION_FAILURE_REASON_TAG_NAME = "reason";
|
||||
private static final String AUTHENTICATION_ENABLED_REQUIRED_TAG_NAME = "enabledRequired";
|
||||
private static final String AUTHENTICATION_CREDENTIAL_TYPE_TAG_NAME = "credentialType";
|
||||
|
||||
private static final String DAYS_SINCE_LAST_SEEN_DISTRIBUTION_NAME = name(BaseAccountAuthenticator.class, "daysSinceLastSeen");
|
||||
private static final String IS_PRIMARY_DEVICE_TAG = "isPrimary";
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(BaseAccountAuthenticator.class);
|
||||
|
||||
private final AccountsManager accountsManager;
|
||||
private final Clock clock;
|
||||
|
||||
@@ -58,46 +47,65 @@ public class BaseAccountAuthenticator {
|
||||
}
|
||||
|
||||
public Optional<Account> authenticate(BasicCredentials basicCredentials, boolean enabledRequired) {
|
||||
boolean succeeded = false;
|
||||
String failureReason = null;
|
||||
String credentialType = null;
|
||||
|
||||
try {
|
||||
AuthorizationHeader authorizationHeader = AuthorizationHeader.fromUserAndPassword(basicCredentials.getUsername(), basicCredentials.getPassword());
|
||||
Optional<Account> account = accountsManager.get(authorizationHeader.getIdentifier());
|
||||
|
||||
if (!account.isPresent()) {
|
||||
noSuchAccountMeter.mark();
|
||||
credentialType = authorizationHeader.getIdentifier().hasNumber() ? "e164" : "uuid";
|
||||
|
||||
if (account.isEmpty()) {
|
||||
failureReason = "noSuchAccount";
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
Optional<Device> device = account.get().getDevice(authorizationHeader.getDeviceId());
|
||||
|
||||
if (!device.isPresent()) {
|
||||
noSuchDeviceMeter.mark();
|
||||
if (device.isEmpty()) {
|
||||
failureReason = "noSuchDevice";
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
if (enabledRequired) {
|
||||
if (!device.get().isEnabled()) {
|
||||
deviceDisabledMeter.mark();
|
||||
failureReason = "deviceDisabled";
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
if (!account.get().isEnabled()) {
|
||||
accountDisabledMeter.mark();
|
||||
failureReason = "accountDisabled";
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
if (device.get().getAuthenticationCredentials().verify(basicCredentials.getPassword())) {
|
||||
authenticationSucceededMeter.mark();
|
||||
succeeded = true;
|
||||
account.get().setAuthenticatedDevice(device.get());
|
||||
updateLastSeen(account.get(), device.get());
|
||||
return account;
|
||||
}
|
||||
|
||||
authenticationFailedMeter.mark();
|
||||
return Optional.empty();
|
||||
} catch (IllegalArgumentException | InvalidAuthorizationHeaderException iae) {
|
||||
invalidAuthHeaderMeter.mark();
|
||||
failureReason = "invalidHeader";
|
||||
return Optional.empty();
|
||||
} finally {
|
||||
Tags tags = Tags.of(
|
||||
AUTHENTICATION_SUCCEEDED_TAG_NAME, String.valueOf(succeeded),
|
||||
AUTHENTICATION_ENABLED_REQUIRED_TAG_NAME, String.valueOf(enabledRequired));
|
||||
|
||||
if (StringUtils.isNotBlank(failureReason)) {
|
||||
tags = tags.and(AUTHENTICATION_FAILURE_REASON_TAG_NAME, failureReason);
|
||||
}
|
||||
|
||||
if (StringUtils.isNotBlank(credentialType)) {
|
||||
tags = tags.and(AUTHENTICATION_CREDENTIAL_TYPE_TAG_NAME, credentialType);
|
||||
}
|
||||
|
||||
Metrics.counter(AUTHENTICATION_COUNTER_NAME, tags).increment();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,10 +115,7 @@ public class BaseAccountAuthenticator {
|
||||
final long todayInMillisWithOffset = Util.todayInMillisGivenOffsetFromNow(clock, Duration.ofSeconds(lastSeenOffsetSeconds).negated());
|
||||
|
||||
if (device.getLastSeen() < todayInMillisWithOffset) {
|
||||
DistributionSummary.builder(daysSinceLastSeenDistributionName)
|
||||
.tags(IS_PRIMARY_DEVICE_TAG, String.valueOf(device.isMaster()))
|
||||
.publishPercentileHistogram()
|
||||
.register(Metrics.globalRegistry)
|
||||
Metrics.summary(DAYS_SINCE_LAST_SEEN_DISTRIBUTION_NAME, IS_PRIMARY_DEVICE_TAG, String.valueOf(device.isMaster()))
|
||||
.record(Duration.ofMillis(todayInMillisWithOffset - device.getLastSeen()).toDays());
|
||||
|
||||
device.setLastSeen(Util.todayInMillis(clock));
|
||||
|
||||
+1
-1
@@ -33,7 +33,7 @@ public class CertificateGenerator {
|
||||
this.serverCertificate = ServerCertificate.parseFrom(serverCertificate);
|
||||
}
|
||||
|
||||
public byte[] createFor(Account account, Device device, boolean includeE164) throws IOException, InvalidKeyException {
|
||||
public byte[] createFor(Account account, Device device, boolean includeE164) throws InvalidKeyException {
|
||||
SenderCertificate.Certificate.Builder builder = SenderCertificate.Certificate.newBuilder()
|
||||
.setSenderDevice(Math.toIntExact(device.getId()))
|
||||
.setExpires(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(expiresDays))
|
||||
|
||||
+23
-12
@@ -5,36 +5,42 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class StoredVerificationCode {
|
||||
|
||||
@JsonProperty
|
||||
private String code;
|
||||
private final String code;
|
||||
|
||||
@JsonProperty
|
||||
private long timestamp;
|
||||
private final long timestamp;
|
||||
|
||||
@JsonProperty
|
||||
private String pushCode;
|
||||
private final String pushCode;
|
||||
|
||||
@JsonProperty
|
||||
private String twilioVerificationSid;
|
||||
@Nullable
|
||||
private final String twilioVerificationSid;
|
||||
|
||||
public StoredVerificationCode() {
|
||||
}
|
||||
public static final Duration EXPIRATION = Duration.ofMinutes(10);
|
||||
|
||||
public StoredVerificationCode(String code, long timestamp, String pushCode) {
|
||||
this(code, timestamp, pushCode, null);
|
||||
}
|
||||
@JsonCreator
|
||||
public StoredVerificationCode(
|
||||
@JsonProperty("code") final String code,
|
||||
@JsonProperty("timestamp") final long timestamp,
|
||||
@JsonProperty("pushCode") final String pushCode,
|
||||
@JsonProperty("twilioVerificationSid") @Nullable final String twilioVerificationSid) {
|
||||
|
||||
public StoredVerificationCode(String code, long timestamp, String pushCode, String twilioVerificationSid) {
|
||||
this.code = code;
|
||||
this.timestamp = timestamp;
|
||||
this.pushCode = pushCode;
|
||||
@@ -58,7 +64,12 @@ public class StoredVerificationCode {
|
||||
}
|
||||
|
||||
public boolean isValid(String theirCodeString) {
|
||||
if (timestamp + TimeUnit.MINUTES.toMillis(10) < System.currentTimeMillis()) {
|
||||
return isValid(theirCodeString, Instant.now());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
boolean isValid(String theirCodeString, Instant currentTime) {
|
||||
if (Instant.ofEpochMilli(timestamp).plus(EXPIRATION).isBefore(currentTime)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
+43
-2
@@ -6,15 +6,56 @@
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.micrometer.datadog.DatadogConfig;
|
||||
import javax.validation.constraints.Min;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import java.time.Duration;
|
||||
|
||||
public class DatadogConfiguration {
|
||||
public class DatadogConfiguration implements DatadogConfig {
|
||||
|
||||
@JsonProperty
|
||||
@NotBlank
|
||||
private String apiKey;
|
||||
|
||||
public String getApiKey() {
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
private Duration step = Duration.ofSeconds(10);
|
||||
|
||||
@JsonProperty
|
||||
@NotBlank
|
||||
private String environment;
|
||||
|
||||
@JsonProperty
|
||||
@Min(1)
|
||||
private int batchSize = 5_000;
|
||||
|
||||
@Override
|
||||
public String apiKey() {
|
||||
return apiKey;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Duration step() {
|
||||
return step;
|
||||
}
|
||||
|
||||
public String getEnvironment() {
|
||||
return environment;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int batchSize() {
|
||||
return batchSize;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String hostTag() {
|
||||
return "host";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String get(final String key) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
public class DeletedAccountsDynamoDbConfiguration extends DynamoDbConfiguration {
|
||||
|
||||
@NotNull
|
||||
private String needsReconciliationIndexName;
|
||||
|
||||
public String getNeedsReconciliationIndexName() {
|
||||
return needsReconciliationIndexName;
|
||||
}
|
||||
}
|
||||
+16
@@ -51,6 +51,14 @@ public class DynamicConfiguration {
|
||||
@Valid
|
||||
private DynamicRateLimitChallengeConfiguration rateLimitChallenge = new DynamicRateLimitChallengeConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
private DynamicVerificationCodeStoreMigrationConfiguration pendingAccountsMigration = new DynamicVerificationCodeStoreMigrationConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
private DynamicVerificationCodeStoreMigrationConfiguration pendingDevicesMigration = new DynamicVerificationCodeStoreMigrationConfiguration();
|
||||
|
||||
public Optional<DynamicExperimentEnrollmentConfiguration> getExperimentEnrollmentConfiguration(
|
||||
final String experimentName) {
|
||||
return Optional.ofNullable(experiments.get(experimentName));
|
||||
@@ -101,4 +109,12 @@ public class DynamicConfiguration {
|
||||
public DynamicRateLimitChallengeConfiguration getRateLimitChallengeConfiguration() {
|
||||
return rateLimitChallenge;
|
||||
}
|
||||
|
||||
public DynamicVerificationCodeStoreMigrationConfiguration getPendingAccountsMigrationConfiguration() {
|
||||
return pendingAccountsMigration;
|
||||
}
|
||||
|
||||
public DynamicVerificationCodeStoreMigrationConfiguration getPendingDevicesMigrationConfiguration() {
|
||||
return pendingDevicesMigration;
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
public class DynamicVerificationCodeStoreMigrationConfiguration {
|
||||
|
||||
public enum WriteDestination {
|
||||
POSTGRES,
|
||||
DYNAMODB
|
||||
}
|
||||
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
private WriteDestination writeDestination = WriteDestination.POSTGRES;
|
||||
|
||||
@JsonProperty
|
||||
private boolean readPostgres = true;
|
||||
|
||||
@JsonProperty
|
||||
private boolean readDynamoDb = false;
|
||||
|
||||
public WriteDestination getWriteDestination() {
|
||||
return writeDestination;
|
||||
}
|
||||
|
||||
public void setWriteDestination(final WriteDestination writeDestination) {
|
||||
this.writeDestination = writeDestination;
|
||||
}
|
||||
|
||||
public boolean isReadPostgres() {
|
||||
return readPostgres;
|
||||
}
|
||||
|
||||
public void setReadPostgres(final boolean readPostgres) {
|
||||
this.readPostgres = readPostgres;
|
||||
}
|
||||
|
||||
public boolean isReadDynamoDb() {
|
||||
return readDynamoDb;
|
||||
}
|
||||
|
||||
public void setReadDynamoDb(final boolean readDynamoDb) {
|
||||
this.readDynamoDb = readDynamoDb;
|
||||
}
|
||||
}
|
||||
+10
-3
@@ -184,7 +184,8 @@ public class AccountController {
|
||||
String pushChallenge = generatePushChallenge();
|
||||
StoredVerificationCode storedVerificationCode = new StoredVerificationCode(null,
|
||||
System.currentTimeMillis(),
|
||||
pushChallenge);
|
||||
pushChallenge,
|
||||
null);
|
||||
|
||||
pendingAccounts.store(number, storedVerificationCode);
|
||||
|
||||
@@ -526,7 +527,10 @@ public class AccountController {
|
||||
@PUT
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/pin/")
|
||||
public void setPin(@Auth Account account, @Valid DeprecatedPin accountLock) {
|
||||
public void setPin(@Auth Account account, @Valid DeprecatedPin accountLock, @HeaderParam("User-Agent") String userAgent) {
|
||||
// TODO Remove once PIN-based reglocks have been deprecated
|
||||
logger.info("PIN set by User-Agent: {}", userAgent);
|
||||
|
||||
account.setPin(accountLock.getPin());
|
||||
account.setRegistrationLock(null, null);
|
||||
|
||||
@@ -536,7 +540,10 @@ public class AccountController {
|
||||
@Timed
|
||||
@DELETE
|
||||
@Path("/pin/")
|
||||
public void removePin(@Auth Account account) {
|
||||
public void removePin(@Auth Account account, @HeaderParam("User-Agent") String userAgent) {
|
||||
// TODO Remove once PIN-based reglocks have been deprecated
|
||||
logger.info("PIN removed by User-Agent: {}", userAgent);
|
||||
|
||||
account.setPin(null);
|
||||
accounts.update(account);
|
||||
}
|
||||
|
||||
+24
-19
@@ -5,17 +5,16 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import org.signal.zkgroup.auth.ServerZkAuthOperations;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
|
||||
import org.whispersystems.textsecuregcm.entities.DeliveryCertificate;
|
||||
import org.whispersystems.textsecuregcm.entities.GroupCredentials;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.io.IOException;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.PathParam;
|
||||
@@ -24,22 +23,24 @@ import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.signal.zkgroup.auth.ServerZkAuthOperations;
|
||||
import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
|
||||
import org.whispersystems.textsecuregcm.entities.DeliveryCertificate;
|
||||
import org.whispersystems.textsecuregcm.entities.GroupCredentials;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
@Path("/v1/certificate")
|
||||
public class CertificateController {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(CertificateController.class);
|
||||
|
||||
private final CertificateGenerator certificateGenerator;
|
||||
private final ServerZkAuthOperations serverZkAuthOperations;
|
||||
private final boolean isZkEnabled;
|
||||
|
||||
private static final String GENERATE_DELIVERY_CERTIFICATE_COUNTER_NAME = name(CertificateGenerator.class, "generateCertificate");
|
||||
private static final String INCLUDE_E164_TAG_NAME = "includeE164";
|
||||
|
||||
public CertificateController(CertificateGenerator certificateGenerator, ServerZkAuthOperations serverZkAuthOperations, boolean isZkEnabled) {
|
||||
this.certificateGenerator = certificateGenerator;
|
||||
this.serverZkAuthOperations = serverZkAuthOperations;
|
||||
@@ -51,8 +52,8 @@ public class CertificateController {
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/delivery")
|
||||
public DeliveryCertificate getDeliveryCertificate(@Auth Account account,
|
||||
@QueryParam("includeE164") Optional<Boolean> includeE164)
|
||||
throws IOException, InvalidKeyException
|
||||
@QueryParam("includeE164") Optional<Boolean> maybeIncludeE164)
|
||||
throws InvalidKeyException
|
||||
{
|
||||
if (account.getAuthenticatedDevice().isEmpty()) {
|
||||
throw new AssertionError();
|
||||
@@ -61,7 +62,11 @@ public class CertificateController {
|
||||
throw new WebApplicationException(Response.Status.BAD_REQUEST);
|
||||
}
|
||||
|
||||
return new DeliveryCertificate(certificateGenerator.createFor(account, account.getAuthenticatedDevice().get(), includeE164.orElse(true)));
|
||||
final boolean includeE164 = maybeIncludeE164.orElse(true);
|
||||
|
||||
Metrics.counter(GENERATE_DELIVERY_CERTIFICATE_COUNTER_NAME, INCLUDE_E164_TAG_NAME, String.valueOf(includeE164)).increment();
|
||||
|
||||
return new DeliveryCertificate(certificateGenerator.createFor(account, account.getAuthenticatedDevice().get(), includeE164));
|
||||
}
|
||||
|
||||
@Timed
|
||||
|
||||
+6
-7
@@ -99,9 +99,11 @@ public class DeviceController {
|
||||
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
messages.clear(account.getUuid(), deviceId);
|
||||
account.removeDevice(deviceId);
|
||||
accounts.update(account);
|
||||
directoryQueue.refreshRegisteredUser(account);
|
||||
// ensure any messages that came in after the first clear() are also removed
|
||||
messages.clear(account.getUuid(), deviceId);
|
||||
}
|
||||
|
||||
@@ -131,6 +133,7 @@ public class DeviceController {
|
||||
VerificationCode verificationCode = generateVerificationCode();
|
||||
StoredVerificationCode storedVerificationCode = new StoredVerificationCode(verificationCode.getVerificationCode(),
|
||||
System.currentTimeMillis(),
|
||||
null,
|
||||
null);
|
||||
|
||||
pendingDevices.store(account.getNumber(), storedVerificationCode);
|
||||
@@ -234,13 +237,9 @@ public class DeviceController {
|
||||
private boolean isCapabilityDowngrade(Account account, DeviceCapabilities capabilities, String userAgent) {
|
||||
boolean isDowngrade = false;
|
||||
|
||||
if (account.isSenderKeySupported() && !capabilities.isSenderKey()) {
|
||||
isDowngrade = true;
|
||||
}
|
||||
|
||||
if (account.isGv1MigrationSupported() && !capabilities.isGv1Migration()) {
|
||||
isDowngrade = true;
|
||||
}
|
||||
isDowngrade |= account.isAnnouncementGroupSupported() && !capabilities.isAnnouncementGroup();
|
||||
isDowngrade |= account.isSenderKeySupported() && !capabilities.isSenderKey();
|
||||
isDowngrade |= account.isGv1MigrationSupported() && !capabilities.isGv1Migration();
|
||||
|
||||
if (account.isGroupsV2Supported()) {
|
||||
try {
|
||||
|
||||
+8
-1
@@ -56,6 +56,7 @@ import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.core.Response.Status;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -63,6 +64,7 @@ import org.whispersystems.textsecuregcm.auth.AmbiguousIdentifier;
|
||||
import org.whispersystems.textsecuregcm.auth.Anonymous;
|
||||
import org.whispersystems.textsecuregcm.auth.CombinedUnidentifiedSenderAccessKeys;
|
||||
import org.whispersystems.textsecuregcm.auth.OptionalAccess;
|
||||
import org.whispersystems.textsecuregcm.auth.StoredRegistrationLock;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicMessageRateConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountMismatchedDevices;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountStaleDevices;
|
||||
@@ -232,7 +234,7 @@ public class MessageController {
|
||||
contentLength += message.getBody().length();
|
||||
}
|
||||
|
||||
Metrics.summary(CONTENT_SIZE_DISTRIBUTION_NAME, UserAgentTagUtil.getUserAgentTags(userAgent)).record(contentLength);
|
||||
Metrics.summary(CONTENT_SIZE_DISTRIBUTION_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent))).record(contentLength);
|
||||
|
||||
if (contentLength > MAX_MESSAGE_SIZE) {
|
||||
rejectOver256kibMessageMeter.mark();
|
||||
@@ -495,6 +497,11 @@ public class MessageController {
|
||||
public OutgoingMessageEntityList getPendingMessages(@Auth Account account, @HeaderParam("User-Agent") String userAgent) {
|
||||
assert account.getAuthenticatedDevice().isPresent();
|
||||
|
||||
// TODO Remove once PIN-based reglocks have been deprecated
|
||||
if (account.getRegistrationLock().requiresClientRegistrationLock() && account.getRegistrationLock().hasDeprecatedPin()) {
|
||||
logger.info("User-Agent with deprecated PIN-based registration lock: {}", userAgent);
|
||||
}
|
||||
|
||||
if (!Util.isEmpty(account.getAuthenticatedDevice().get().getApnId())) {
|
||||
RedisOperation.unchecked(() -> apnFallbackManager.cancel(account, account.getAuthenticatedDevice().get()));
|
||||
}
|
||||
|
||||
+12
-5
@@ -5,7 +5,6 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.amazonaws.services.s3.AmazonS3;
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import java.security.SecureRandom;
|
||||
@@ -60,6 +59,8 @@ import org.whispersystems.textsecuregcm.storage.VersionedProfile;
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import software.amazon.awssdk.services.s3.S3Client;
|
||||
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
|
||||
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
@Path("/v1/profile")
|
||||
@@ -78,7 +79,7 @@ public class ProfileController {
|
||||
private final ServerZkProfileOperations zkProfileOperations;
|
||||
private final boolean isZkEnabled;
|
||||
|
||||
private final AmazonS3 s3client;
|
||||
private final S3Client s3client;
|
||||
private final String bucket;
|
||||
|
||||
public ProfileController(RateLimiters rateLimiters,
|
||||
@@ -86,7 +87,7 @@ public class ProfileController {
|
||||
ProfilesManager profilesManager,
|
||||
UsernamesManager usernamesManager,
|
||||
DynamicConfigurationManager dynamicConfigurationManager,
|
||||
AmazonS3 s3client,
|
||||
S3Client s3client,
|
||||
PostPolicyGenerator policyGenerator,
|
||||
PolicySigner policySigner,
|
||||
String bucket,
|
||||
@@ -147,7 +148,10 @@ public class ProfileController {
|
||||
currentAvatar = Optional.of(account.getAvatar());
|
||||
}
|
||||
|
||||
currentAvatar.ifPresent(s -> s3client.deleteObject(bucket, s));
|
||||
currentAvatar.ifPresent(s -> s3client.deleteObject(DeleteObjectRequest.builder()
|
||||
.bucket(bucket)
|
||||
.key(s)
|
||||
.build()));
|
||||
|
||||
response = Optional.of(generateAvatarUploadForm(avatar));
|
||||
}
|
||||
@@ -372,7 +376,10 @@ public class ProfileController {
|
||||
ProfileAvatarUploadAttributes profileAvatarUploadAttributes = generateAvatarUploadForm(objectName);
|
||||
|
||||
if (previousAvatar != null && previousAvatar.startsWith("profiles/")) {
|
||||
s3client.deleteObject(bucket, previousAvatar);
|
||||
s3client.deleteObject(DeleteObjectRequest.builder()
|
||||
.bucket(bucket)
|
||||
.key(previousAvatar)
|
||||
.build());
|
||||
}
|
||||
|
||||
account.setAvatar(objectName);
|
||||
|
||||
+11
-2
@@ -14,7 +14,8 @@ public class UserCapabilities {
|
||||
return new UserCapabilities(
|
||||
account.isGroupsV2Supported(),
|
||||
account.isGv1MigrationSupported(),
|
||||
account.isSenderKeySupported());
|
||||
account.isSenderKeySupported(),
|
||||
account.isAnnouncementGroupSupported());
|
||||
}
|
||||
|
||||
@JsonProperty
|
||||
@@ -26,12 +27,16 @@ public class UserCapabilities {
|
||||
@JsonProperty
|
||||
private boolean senderKey;
|
||||
|
||||
@JsonProperty
|
||||
private boolean announcementGroup;
|
||||
|
||||
public UserCapabilities() {}
|
||||
|
||||
public UserCapabilities(boolean gv2, boolean gv1Migration, final boolean senderKey) {
|
||||
public UserCapabilities(boolean gv2, boolean gv1Migration, final boolean senderKey, final boolean announcementGroup) {
|
||||
this.gv2 = gv2;
|
||||
this.gv1Migration = gv1Migration;
|
||||
this.senderKey = senderKey;
|
||||
this.announcementGroup = announcementGroup;
|
||||
}
|
||||
|
||||
public boolean isGv2() {
|
||||
@@ -45,4 +50,8 @@ public class UserCapabilities {
|
||||
public boolean isSenderKey() {
|
||||
return senderKey;
|
||||
}
|
||||
|
||||
public boolean isAnnouncementGroup() {
|
||||
return announcementGroup;
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -18,7 +18,7 @@ public class PreKeyRateLimiter {
|
||||
|
||||
private static final String RATE_LIMIT_RESET_COUNTER_NAME = name(PreKeyRateLimiter.class, "reset");
|
||||
private static final String RATE_LIMITED_PREKEYS_COUNTER_NAME = name(PreKeyRateLimiter.class, "rateLimited");
|
||||
private static final String RATE_LIMITED_PREKEYS_TOTAL_ACCOUNTS_COUNTER_NAME = name(PreKeyRateLimiter.class, "rateLimited");
|
||||
private static final String RATE_LIMITED_PREKEYS_TOTAL_ACCOUNTS_COUNTER_NAME = name(PreKeyRateLimiter.class, "rateLimitedTotal");
|
||||
private static final String RATE_LIMITED_PREKEYS_ACCOUNTS_ENFORCED_COUNTER_NAME = name(PreKeyRateLimiter.class, "rateLimitedAccountsEnforced");
|
||||
private static final String RATE_LIMITED_PREKEYS_ACCOUNTS_UNENFORCED_COUNTER_NAME = name(PreKeyRateLimiter.class, "rateLimitedAccountsUnenforced");
|
||||
|
||||
|
||||
+7
-2
@@ -18,8 +18,13 @@ public class RateLimitResetMetricsManager {
|
||||
}
|
||||
|
||||
void initializeFunctionCounters(String counterKey, String hllKey) {
|
||||
FunctionCounter.builder(counterKey, null, (ignored) ->
|
||||
metricsCluster.<Long>withCluster(conn -> conn.sync().pfcount(hllKey))).register(meterRegistry);
|
||||
FunctionCounter
|
||||
.builder(counterKey, this, manager -> manager.getCount(hllKey))
|
||||
.register(meterRegistry);
|
||||
}
|
||||
|
||||
Long getCount(final String hllKey) {
|
||||
return metricsCluster.<Long>withCluster(conn -> conn.sync().pfcount(hllKey));
|
||||
}
|
||||
|
||||
void recordMetrics(Account account, boolean enforced, String counterKey, String hllEnforcedKey, String hllTotalKey,
|
||||
|
||||
+2
-1
@@ -21,6 +21,7 @@ import com.fasterxml.jackson.core.JsonFactory;
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.util.HostnameUtil;
|
||||
|
||||
import javax.ws.rs.core.UriBuilder;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
@@ -83,7 +84,7 @@ public class JsonMetricsReporter extends ScheduledReporter {
|
||||
{
|
||||
super(registry, "json-reporter", filter, rateUnit, durationUnit, Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("json-reporter")), true, disabledMetricAttributes);
|
||||
this.httpClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2).build();
|
||||
this.uri = UriBuilder.fromUri(uri).queryParam("h", InetAddress.getLocalHost().getHostName()).build();
|
||||
this.uri = UriBuilder.fromUri(uri).queryParam("h", HostnameUtil.getLocalHostname()).build();
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+2
-5
@@ -27,6 +27,7 @@ import javax.validation.constraints.NotEmpty;
|
||||
import net.logstash.logback.appender.LogstashTcpSocketAppender;
|
||||
import net.logstash.logback.encoder.LogstashEncoder;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerVersion;
|
||||
import org.whispersystems.textsecuregcm.util.HostnameUtil;
|
||||
|
||||
@JsonTypeName("logstashtcpsocket")
|
||||
public class LogstashTcpSocketAppenderFactory extends AbstractAppenderFactory<ILoggingEvent> {
|
||||
@@ -77,11 +78,7 @@ public class LogstashTcpSocketAppenderFactory extends AbstractAppenderFactory<IL
|
||||
|
||||
final LogstashEncoder encoder = new LogstashEncoder();
|
||||
final ObjectNode customFieldsNode = new ObjectNode(JsonNodeFactory.instance);
|
||||
try {
|
||||
customFieldsNode.set("host", TextNode.valueOf(InetAddress.getLocalHost().getHostName()));
|
||||
} catch (UnknownHostException e) {
|
||||
customFieldsNode.set("host", TextNode.valueOf("unknown"));
|
||||
}
|
||||
customFieldsNode.set("host", TextNode.valueOf(HostnameUtil.getLocalHostname()));
|
||||
customFieldsNode.set("service", TextNode.valueOf("chat"));
|
||||
customFieldsNode.set("ddsource", TextNode.valueOf("logstash"));
|
||||
customFieldsNode.set("ddtags", TextNode.valueOf("env:" + environment + ",version:" + WhisperServerVersion.getServerVersion()));
|
||||
|
||||
+2
-1
@@ -10,6 +10,7 @@ import com.google.common.annotations.VisibleForTesting;
|
||||
import io.lettuce.core.SetArgs;
|
||||
import io.lettuce.core.cluster.api.async.RedisAdvancedClusterAsyncCommands;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
|
||||
import java.time.Duration;
|
||||
@@ -49,7 +50,7 @@ public class PushLatencyManager {
|
||||
public void recordQueueRead(final UUID accountUuid, final long deviceId, final String userAgent) {
|
||||
getLatencyAndClearTimestamp(accountUuid, deviceId, System.currentTimeMillis()).thenAccept(latency -> {
|
||||
if (latency != null) {
|
||||
Metrics.timer(TIMER_NAME, UserAgentTagUtil.getUserAgentTags(userAgent)).record(latency, TimeUnit.MILLISECONDS);
|
||||
Metrics.timer(TIMER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent))).record(latency, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
/*
|
||||
* This is derived from Coursera's dropwizard datadog reporter.
|
||||
* https://github.com/coursera/metrics-datadog
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.metrics;
|
||||
|
||||
import com.codahale.metrics.MetricRegistry;
|
||||
import com.codahale.metrics.ScheduledReporter;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeName;
|
||||
import io.dropwizard.metrics.BaseReporterFactory;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import org.coursera.metrics.datadog.DatadogReporter;
|
||||
import org.coursera.metrics.datadog.DatadogReporter.Expansion;
|
||||
import org.coursera.metrics.datadog.DefaultMetricNameFormatterFactory;
|
||||
import org.coursera.metrics.datadog.DynamicTagsCallbackFactory;
|
||||
import org.coursera.metrics.datadog.MetricNameFormatterFactory;
|
||||
import org.coursera.metrics.datadog.transport.AbstractTransportFactory;
|
||||
import org.whispersystems.textsecuregcm.util.HostnameUtil;
|
||||
|
||||
@JsonTypeName("signal-datadog")
|
||||
public class SignalDatadogReporterFactory extends BaseReporterFactory {
|
||||
|
||||
@JsonProperty
|
||||
private List<String> tags = null;
|
||||
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private DynamicTagsCallbackFactory dynamicTagsCallback = null;
|
||||
|
||||
@JsonProperty
|
||||
private String prefix = null;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private MetricNameFormatterFactory metricNameFormatter = new DefaultMetricNameFormatterFactory();
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private AbstractTransportFactory transport = null;
|
||||
|
||||
private static final EnumSet<Expansion> EXPANSIONS = EnumSet.of(
|
||||
Expansion.COUNT,
|
||||
Expansion.MIN,
|
||||
Expansion.MAX,
|
||||
Expansion.MEAN,
|
||||
Expansion.MEDIAN,
|
||||
Expansion.P75,
|
||||
Expansion.P95,
|
||||
Expansion.P99,
|
||||
Expansion.P999
|
||||
);
|
||||
|
||||
public ScheduledReporter build(MetricRegistry registry) {
|
||||
return DatadogReporter.forRegistry(registry)
|
||||
.withTransport(transport.build())
|
||||
.withHost(HostnameUtil.getLocalHostname())
|
||||
.withTags(tags)
|
||||
.withPrefix(prefix)
|
||||
.withExpansions(EXPANSIONS)
|
||||
.withMetricNameFormatter(metricNameFormatter.build())
|
||||
.withDynamicTagCallback(dynamicTagsCallback != null ? dynamicTagsCallback.build() : null)
|
||||
.filter(getFilter())
|
||||
.convertDurationsTo(getDurationUnit())
|
||||
.convertRatesTo(getRateUnit())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -6,16 +6,6 @@ package org.whispersystems.textsecuregcm.sqs;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.amazonaws.AmazonClientException;
|
||||
import com.amazonaws.AmazonServiceException;
|
||||
import com.amazonaws.auth.AWSCredentials;
|
||||
import com.amazonaws.auth.AWSStaticCredentialsProvider;
|
||||
import com.amazonaws.auth.BasicAWSCredentials;
|
||||
import com.amazonaws.services.sqs.AmazonSQS;
|
||||
import com.amazonaws.services.sqs.AmazonSQSClientBuilder;
|
||||
import com.amazonaws.services.sqs.model.MessageAttributeValue;
|
||||
import com.amazonaws.services.sqs.model.SendMessageBatchRequest;
|
||||
import com.amazonaws.services.sqs.model.SendMessageBatchRequestEntry;
|
||||
import com.codahale.metrics.Meter;
|
||||
import com.codahale.metrics.MetricRegistry;
|
||||
import com.codahale.metrics.SharedMetricRegistries;
|
||||
@@ -32,6 +22,15 @@ import org.whispersystems.textsecuregcm.configuration.SqsConfiguration;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.core.exception.SdkClientException;
|
||||
import software.amazon.awssdk.core.exception.SdkServiceException;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.sqs.SqsClient;
|
||||
import software.amazon.awssdk.services.sqs.model.MessageAttributeValue;
|
||||
import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequest;
|
||||
import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequestEntry;
|
||||
|
||||
public class DirectoryQueue {
|
||||
|
||||
@@ -43,20 +42,23 @@ public class DirectoryQueue {
|
||||
private final Timer sendMessageBatchTimer = metricRegistry.timer(name(DirectoryQueue.class, "sendMessageBatch"));
|
||||
|
||||
private final List<String> queueUrls;
|
||||
private final AmazonSQS sqs;
|
||||
private final SqsClient sqs;
|
||||
|
||||
public DirectoryQueue(SqsConfiguration sqsConfig) {
|
||||
final AWSCredentials credentials = new BasicAWSCredentials(sqsConfig.getAccessKey(), sqsConfig.getAccessSecret());
|
||||
final AWSStaticCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);
|
||||
StaticCredentialsProvider credentialsProvider = StaticCredentialsProvider.create(AwsBasicCredentials.create(
|
||||
sqsConfig.getAccessKey(), sqsConfig.getAccessSecret()));
|
||||
|
||||
this.queueUrls = sqsConfig.getQueueUrls();
|
||||
this.sqs = AmazonSQSClientBuilder.standard().withRegion(sqsConfig.getRegion()).withCredentials(credentialsProvider).build();
|
||||
this.sqs = SqsClient.builder()
|
||||
.region(Region.of(sqsConfig.getRegion()))
|
||||
.credentialsProvider(credentialsProvider)
|
||||
.build();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
DirectoryQueue(final List<String> queueUrls, final AmazonSQS sqs) {
|
||||
DirectoryQueue(final List<String> queueUrls, final SqsClient sqs) {
|
||||
this.queueUrls = queueUrls;
|
||||
this.sqs = sqs;
|
||||
this.sqs = sqs;
|
||||
}
|
||||
|
||||
public void refreshRegisteredUser(final Account account) {
|
||||
@@ -82,28 +84,30 @@ public class DirectoryQueue {
|
||||
final Account account = pair.first();
|
||||
final String action = pair.second();
|
||||
|
||||
return new SendMessageBatchRequestEntry()
|
||||
.withMessageBody("-")
|
||||
.withId(UUID.randomUUID().toString())
|
||||
.withMessageDeduplicationId(UUID.randomUUID().toString())
|
||||
.withMessageGroupId(account.getNumber())
|
||||
.withMessageAttributes(Map.of(
|
||||
"id", new MessageAttributeValue().withDataType("String").withStringValue(account.getNumber()),
|
||||
"uuid", new MessageAttributeValue().withDataType("String").withStringValue(account.getUuid().toString()),
|
||||
"action", new MessageAttributeValue().withDataType("String").withStringValue(action)
|
||||
));
|
||||
return SendMessageBatchRequestEntry.builder()
|
||||
.messageBody("-")
|
||||
.id(UUID.randomUUID().toString())
|
||||
.messageDeduplicationId(UUID.randomUUID().toString())
|
||||
.messageGroupId(account.getNumber())
|
||||
.messageAttributes(Map.of(
|
||||
"id", MessageAttributeValue.builder().dataType("String").stringValue(account.getNumber()).build(),
|
||||
"uuid", MessageAttributeValue.builder().dataType("String").stringValue(account.getUuid().toString()).build(),
|
||||
"action", MessageAttributeValue.builder().dataType("String").stringValue(action).build()
|
||||
))
|
||||
.build();
|
||||
}).collect(Collectors.toList());
|
||||
|
||||
final SendMessageBatchRequest sendMessageBatchRequest = new SendMessageBatchRequest()
|
||||
.withQueueUrl(queueUrl)
|
||||
.withEntries(entries);
|
||||
final SendMessageBatchRequest sendMessageBatchRequest = SendMessageBatchRequest.builder()
|
||||
.queueUrl(queueUrl)
|
||||
.entries(entries)
|
||||
.build();
|
||||
|
||||
try (final Timer.Context ignored = sendMessageBatchTimer.time()) {
|
||||
sqs.sendMessageBatch(sendMessageBatchRequest);
|
||||
} catch (AmazonServiceException ex) {
|
||||
} catch (SdkServiceException ex) {
|
||||
serviceErrorMeter.mark();
|
||||
logger.warn("sqs service error: ", ex);
|
||||
} catch (AmazonClientException ex) {
|
||||
} catch (SdkClientException ex) {
|
||||
clientErrorMeter.mark();
|
||||
logger.warn("sqs client error: ", ex);
|
||||
} catch (Throwable t) {
|
||||
@@ -112,5 +116,4 @@ public class DirectoryQueue {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+72
-74
@@ -5,93 +5,91 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.amazonaws.services.dynamodbv2.document.BatchWriteItemOutcome;
|
||||
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.document.Item;
|
||||
import com.amazonaws.services.dynamodbv2.document.Page;
|
||||
import com.amazonaws.services.dynamodbv2.document.QueryOutcome;
|
||||
import com.amazonaws.services.dynamodbv2.document.Table;
|
||||
import com.amazonaws.services.dynamodbv2.document.TableWriteItems;
|
||||
import com.amazonaws.services.dynamodbv2.document.spec.QuerySpec;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
import static io.micrometer.core.instrument.Metrics.counter;
|
||||
import static io.micrometer.core.instrument.Metrics.timer;
|
||||
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.stream.Collectors;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.BatchWriteItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.BatchWriteItemResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ScanRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.WriteRequest;
|
||||
|
||||
public class AbstractDynamoDbStore {
|
||||
|
||||
private final DynamoDB dynamoDb;
|
||||
private final DynamoDbClient dynamoDbClient;
|
||||
|
||||
private final Timer batchWriteItemsFirstPass = timer(name(getClass(), "batchWriteItems"), "firstAttempt", "true");
|
||||
private final Timer batchWriteItemsRetryPass = timer(name(getClass(), "batchWriteItems"), "firstAttempt", "false");
|
||||
private final Counter batchWriteItemsUnprocessed = counter(name(getClass(), "batchWriteItemsUnprocessed"));
|
||||
private final Timer batchWriteItemsFirstPass = timer(name(getClass(), "batchWriteItems"), "firstAttempt", "true");
|
||||
private final Timer batchWriteItemsRetryPass = timer(name(getClass(), "batchWriteItems"), "firstAttempt", "false");
|
||||
private final Counter batchWriteItemsUnprocessed = counter(name(getClass(), "batchWriteItemsUnprocessed"));
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
private final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
|
||||
private static final int MAX_ATTEMPTS_TO_SAVE_BATCH_WRITE = 25; // This was arbitrarily chosen and may be entirely too high.
|
||||
public static final int DYNAMO_DB_MAX_BATCH_SIZE = 25; // This limit comes from Amazon Dynamo DB itself. It will reject batch writes larger than this.
|
||||
public static final int RESULT_SET_CHUNK_SIZE = 100;
|
||||
private static final int MAX_ATTEMPTS_TO_SAVE_BATCH_WRITE = 25; // This was arbitrarily chosen and may be entirely too high.
|
||||
public static final int DYNAMO_DB_MAX_BATCH_SIZE = 25; // This limit comes from Amazon Dynamo DB itself. It will reject batch writes larger than this.
|
||||
public static final int RESULT_SET_CHUNK_SIZE = 100;
|
||||
|
||||
public AbstractDynamoDbStore(final DynamoDB dynamoDb) {
|
||||
this.dynamoDb = dynamoDb;
|
||||
public AbstractDynamoDbStore(final DynamoDbClient dynamoDbClient) {
|
||||
this.dynamoDbClient = dynamoDbClient;
|
||||
}
|
||||
|
||||
protected DynamoDbClient db() {
|
||||
return dynamoDbClient;
|
||||
}
|
||||
|
||||
protected void executeTableWriteItemsUntilComplete(final Map<String, List<WriteRequest>> items) {
|
||||
AtomicReference<BatchWriteItemResponse> outcome = new AtomicReference<>();
|
||||
batchWriteItemsFirstPass.record(
|
||||
() -> outcome.set(dynamoDbClient.batchWriteItem(BatchWriteItemRequest.builder().requestItems(items).build())));
|
||||
int attemptCount = 0;
|
||||
while (!outcome.get().unprocessedItems().isEmpty() && attemptCount < MAX_ATTEMPTS_TO_SAVE_BATCH_WRITE) {
|
||||
batchWriteItemsRetryPass.record(() -> outcome.set(dynamoDbClient.batchWriteItem(BatchWriteItemRequest.builder()
|
||||
.requestItems(outcome.get().unprocessedItems())
|
||||
.build())));
|
||||
++attemptCount;
|
||||
}
|
||||
|
||||
protected DynamoDB getDynamoDb() {
|
||||
return dynamoDb;
|
||||
if (!outcome.get().unprocessedItems().isEmpty()) {
|
||||
int totalItems = outcome.get().unprocessedItems().values().stream().mapToInt(List::size).sum();
|
||||
logger.error(
|
||||
"Attempt count ({}) reached max ({}}) before applying all batch writes to dynamo. {} unprocessed items remain.",
|
||||
attemptCount, MAX_ATTEMPTS_TO_SAVE_BATCH_WRITE, totalItems);
|
||||
batchWriteItemsUnprocessed.increment(totalItems);
|
||||
}
|
||||
}
|
||||
|
||||
protected void executeTableWriteItemsUntilComplete(final TableWriteItems items) {
|
||||
AtomicReference<BatchWriteItemOutcome> outcome = new AtomicReference<>();
|
||||
batchWriteItemsFirstPass.record(() -> outcome.set(dynamoDb.batchWriteItem(items)));
|
||||
int attemptCount = 0;
|
||||
while (!outcome.get().getUnprocessedItems().isEmpty() && attemptCount < MAX_ATTEMPTS_TO_SAVE_BATCH_WRITE) {
|
||||
batchWriteItemsRetryPass.record(() -> outcome.set(dynamoDb.batchWriteItemUnprocessed(outcome.get().getUnprocessedItems())));
|
||||
++attemptCount;
|
||||
}
|
||||
if (!outcome.get().getUnprocessedItems().isEmpty()) {
|
||||
logger.error("Attempt count ({}) reached max ({}}) before applying all batch writes to dynamo. {} unprocessed items remain.", attemptCount, MAX_ATTEMPTS_TO_SAVE_BATCH_WRITE, outcome.get().getUnprocessedItems().size());
|
||||
batchWriteItemsUnprocessed.increment(outcome.get().getUnprocessedItems().size());
|
||||
}
|
||||
protected List<Map<String, AttributeValue>> scan(ScanRequest scanRequest, int max) {
|
||||
|
||||
return db().scanPaginator(scanRequest)
|
||||
.items()
|
||||
.stream()
|
||||
.limit(max)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
static <T> void writeInBatches(final Iterable<T> items, final Consumer<List<T>> action) {
|
||||
final List<T> batch = new ArrayList<>(DYNAMO_DB_MAX_BATCH_SIZE);
|
||||
|
||||
for (T item : items) {
|
||||
batch.add(item);
|
||||
|
||||
if (batch.size() == DYNAMO_DB_MAX_BATCH_SIZE) {
|
||||
action.accept(batch);
|
||||
batch.clear();
|
||||
}
|
||||
}
|
||||
|
||||
protected long countItemsMatchingQuery(final Table table, final QuerySpec querySpec) {
|
||||
// This is very confusing, but does appear to be the intended behavior. See:
|
||||
//
|
||||
// - https://github.com/aws/aws-sdk-java/issues/693
|
||||
// - https://github.com/aws/aws-sdk-java/issues/915
|
||||
// - https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html#Query.Count
|
||||
|
||||
long matchingItems = 0;
|
||||
|
||||
for (final Page<Item, QueryOutcome> page : table.query(querySpec).pages()) {
|
||||
matchingItems += page.getLowLevelResult().getQueryResult().getCount();
|
||||
}
|
||||
|
||||
return matchingItems;
|
||||
}
|
||||
|
||||
static <T> void writeInBatches(final Iterable<T> items, final Consumer<List<T>> action) {
|
||||
final List<T> batch = new ArrayList<>(DYNAMO_DB_MAX_BATCH_SIZE);
|
||||
|
||||
for (T item : items) {
|
||||
batch.add(item);
|
||||
|
||||
if (batch.size() == DYNAMO_DB_MAX_BATCH_SIZE) {
|
||||
action.accept(batch);
|
||||
batch.clear();
|
||||
}
|
||||
}
|
||||
if (!batch.isEmpty()) {
|
||||
action.accept(batch);
|
||||
}
|
||||
if (!batch.isEmpty()) {
|
||||
action.accept(batch);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -151,6 +151,12 @@ public class Account implements Principal {
|
||||
.allMatch(device -> device.getCapabilities() != null && device.getCapabilities().isSenderKey());
|
||||
}
|
||||
|
||||
public boolean isAnnouncementGroupSupported() {
|
||||
return devices.stream()
|
||||
.filter(Device::isEnabled)
|
||||
.allMatch(device -> device.getCapabilities() != null && device.getCapabilities().isAnnouncementGroup());
|
||||
}
|
||||
|
||||
public boolean isEnabled() {
|
||||
return getMasterDevice().map(Device::isEnabled).orElse(false);
|
||||
}
|
||||
|
||||
+145
-141
@@ -2,25 +2,6 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.amazonaws.handlers.AsyncHandler;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBAsync;
|
||||
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.document.Item;
|
||||
import com.amazonaws.services.dynamodbv2.document.PrimaryKey;
|
||||
import com.amazonaws.services.dynamodbv2.document.Table;
|
||||
import com.amazonaws.services.dynamodbv2.document.spec.GetItemSpec;
|
||||
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
|
||||
import com.amazonaws.services.dynamodbv2.model.CancellationReason;
|
||||
import com.amazonaws.services.dynamodbv2.model.Delete;
|
||||
import com.amazonaws.services.dynamodbv2.model.GetItemResult;
|
||||
import com.amazonaws.services.dynamodbv2.model.Put;
|
||||
import com.amazonaws.services.dynamodbv2.model.ReturnValuesOnConditionCheckFailure;
|
||||
import com.amazonaws.services.dynamodbv2.model.TransactWriteItem;
|
||||
import com.amazonaws.services.dynamodbv2.model.TransactWriteItemsRequest;
|
||||
import com.amazonaws.services.dynamodbv2.model.TransactWriteItemsResult;
|
||||
import com.amazonaws.services.dynamodbv2.model.TransactionCanceledException;
|
||||
import com.amazonaws.services.dynamodbv2.model.UpdateItemRequest;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
@@ -33,12 +14,27 @@ import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.stream.Collectors;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.CancellationReason;
|
||||
import software.amazon.awssdk.services.dynamodb.model.Delete;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.Put;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ReturnValuesOnConditionCheckFailure;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledException;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
|
||||
|
||||
public class AccountsDynamoDb extends AbstractDynamoDbStore implements AccountStore {
|
||||
|
||||
@@ -51,9 +47,8 @@ public class AccountsDynamoDb extends AbstractDynamoDbStore implements AccountSt
|
||||
|
||||
static final String ATTR_MIGRATION_VERSION = "V";
|
||||
|
||||
private final AmazonDynamoDB client;
|
||||
private final Table accountsTable;
|
||||
private final AmazonDynamoDBAsync asyncClient;
|
||||
private final DynamoDbClient client;
|
||||
private final DynamoDbAsyncClient asyncClient;
|
||||
|
||||
private final ThreadPoolExecutor migrationThreadPool;
|
||||
|
||||
@@ -61,6 +56,7 @@ public class AccountsDynamoDb extends AbstractDynamoDbStore implements AccountSt
|
||||
private final MigrationRetryAccounts migrationRetryAccounts;
|
||||
|
||||
private final String phoneNumbersTableName;
|
||||
private final String accountsTableName;
|
||||
|
||||
private static final Timer CREATE_TIMER = Metrics.timer(name(AccountsDynamoDb.class, "create"));
|
||||
private static final Timer UPDATE_TIMER = Metrics.timer(name(AccountsDynamoDb.class, "update"));
|
||||
@@ -70,18 +66,17 @@ public class AccountsDynamoDb extends AbstractDynamoDbStore implements AccountSt
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(AccountsDynamoDb.class);
|
||||
|
||||
public AccountsDynamoDb(AmazonDynamoDB client, AmazonDynamoDBAsync asyncClient,
|
||||
ThreadPoolExecutor migrationThreadPool, DynamoDB dynamoDb, String accountsTableName, String phoneNumbersTableName,
|
||||
public AccountsDynamoDb(DynamoDbClient client, DynamoDbAsyncClient asyncClient,
|
||||
ThreadPoolExecutor migrationThreadPool, String accountsTableName, String phoneNumbersTableName,
|
||||
MigrationDeletedAccounts migrationDeletedAccounts,
|
||||
MigrationRetryAccounts accountsMigrationErrors) {
|
||||
|
||||
super(dynamoDb);
|
||||
super(client);
|
||||
|
||||
this.client = client;
|
||||
this.accountsTable = dynamoDb.getTable(accountsTableName);
|
||||
this.phoneNumbersTableName = phoneNumbersTableName;
|
||||
|
||||
this.asyncClient = asyncClient;
|
||||
this.phoneNumbersTableName = phoneNumbersTableName;
|
||||
this.accountsTableName = accountsTableName;
|
||||
this.migrationThreadPool = migrationThreadPool;
|
||||
|
||||
this.migrationDeletedAccounts = migrationDeletedAccounts;
|
||||
@@ -90,32 +85,34 @@ public class AccountsDynamoDb extends AbstractDynamoDbStore implements AccountSt
|
||||
|
||||
@Override
|
||||
public boolean create(Account account) {
|
||||
|
||||
return CREATE_TIMER.record(() -> {
|
||||
|
||||
try {
|
||||
TransactWriteItem phoneNumberConstraintPut = buildPutWriteItemForPhoneNumberConstraint(account, account.getUuid());
|
||||
TransactWriteItem accountPut = buildPutWriteItemForAccount(account, account.getUuid(), Put.builder()
|
||||
.conditionExpression("attribute_not_exists(#number) OR #number = :number")
|
||||
.expressionAttributeNames(Map.of("#number", ATTR_ACCOUNT_E164))
|
||||
.expressionAttributeValues(Map.of(":number", AttributeValues.fromString(account.getNumber()))));
|
||||
|
||||
TransactWriteItem accountPut = buildPutWriteItemForAccount(account, account.getUuid());
|
||||
|
||||
final TransactWriteItemsRequest request = new TransactWriteItemsRequest()
|
||||
.withTransactItems(phoneNumberConstraintPut, accountPut);
|
||||
final TransactWriteItemsRequest request = TransactWriteItemsRequest.builder()
|
||||
.transactItems(phoneNumberConstraintPut, accountPut)
|
||||
.build();
|
||||
|
||||
try {
|
||||
client.transactWriteItems(request);
|
||||
} catch (TransactionCanceledException e) {
|
||||
|
||||
final CancellationReason accountCancellationReason = e.getCancellationReasons().get(1);
|
||||
final CancellationReason accountCancellationReason = e.cancellationReasons().get(1);
|
||||
|
||||
if ("ConditionalCheckFailed".equals(accountCancellationReason.getCode())) {
|
||||
if ("ConditionalCheckFailed".equals(accountCancellationReason.code())) {
|
||||
throw new IllegalArgumentException("uuid present with different phone number");
|
||||
}
|
||||
|
||||
final CancellationReason phoneNumberConstraintCancellationReason = e.getCancellationReasons().get(0);
|
||||
final CancellationReason phoneNumberConstraintCancellationReason = e.cancellationReasons().get(0);
|
||||
|
||||
if ("ConditionalCheckFailed".equals(phoneNumberConstraintCancellationReason.getCode())) {
|
||||
if ("ConditionalCheckFailed".equals(phoneNumberConstraintCancellationReason.code())) {
|
||||
|
||||
ByteBuffer actualAccountUuid = phoneNumberConstraintCancellationReason.getItem().get(KEY_ACCOUNT_UUID).getB();
|
||||
ByteBuffer actualAccountUuid = phoneNumberConstraintCancellationReason.item().get(KEY_ACCOUNT_UUID).b().asByteBuffer();
|
||||
account.setUuid(UUIDUtil.fromByteBuffer(actualAccountUuid));
|
||||
|
||||
update(account);
|
||||
@@ -134,39 +131,37 @@ public class AccountsDynamoDb extends AbstractDynamoDbStore implements AccountSt
|
||||
});
|
||||
}
|
||||
|
||||
private TransactWriteItem buildPutWriteItemForAccount(Account account, UUID uuid) throws JsonProcessingException {
|
||||
return new TransactWriteItem()
|
||||
.withPut(
|
||||
new Put()
|
||||
.withTableName(accountsTable.getTableName())
|
||||
.withItem(Map.of(
|
||||
KEY_ACCOUNT_UUID, new AttributeValue().withB(UUIDUtil.toByteBuffer(uuid)),
|
||||
ATTR_ACCOUNT_E164, new AttributeValue(account.getNumber()),
|
||||
ATTR_ACCOUNT_DATA, new AttributeValue()
|
||||
.withB(ByteBuffer.wrap(SystemMapper.getMapper().writeValueAsBytes(account))),
|
||||
ATTR_MIGRATION_VERSION, new AttributeValue().withN(
|
||||
String.valueOf(account.getDynamoDbMigrationVersion()))))
|
||||
.withConditionExpression("attribute_not_exists(#number) OR #number = :number")
|
||||
.withExpressionAttributeNames(Map.of("#number", ATTR_ACCOUNT_E164))
|
||||
.withExpressionAttributeValues(Map.of(":number", new AttributeValue(account.getNumber()))));
|
||||
private TransactWriteItem buildPutWriteItemForAccount(Account account, UUID uuid, Put.Builder putBuilder) throws JsonProcessingException {
|
||||
return TransactWriteItem.builder()
|
||||
.put(putBuilder
|
||||
.tableName(accountsTableName)
|
||||
.item(Map.of(
|
||||
KEY_ACCOUNT_UUID, AttributeValues.fromUUID(uuid),
|
||||
ATTR_ACCOUNT_E164, AttributeValues.fromString(account.getNumber()),
|
||||
ATTR_ACCOUNT_DATA, AttributeValues.fromByteArray(SystemMapper.getMapper().writeValueAsBytes(account)),
|
||||
ATTR_MIGRATION_VERSION, AttributeValues.fromInt(account.getDynamoDbMigrationVersion())))
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
private TransactWriteItem buildPutWriteItemForPhoneNumberConstraint(Account account, UUID uuid) {
|
||||
return new TransactWriteItem()
|
||||
.withPut(
|
||||
new Put()
|
||||
.withTableName(phoneNumbersTableName)
|
||||
.withItem(Map.of(
|
||||
ATTR_ACCOUNT_E164, new AttributeValue(account.getNumber()),
|
||||
KEY_ACCOUNT_UUID, new AttributeValue().withB(UUIDUtil.toByteBuffer(uuid))))
|
||||
.withConditionExpression(
|
||||
return TransactWriteItem.builder()
|
||||
.put(
|
||||
Put.builder()
|
||||
.tableName(phoneNumbersTableName)
|
||||
.item(Map.of(
|
||||
ATTR_ACCOUNT_E164, AttributeValues.fromString(account.getNumber()),
|
||||
KEY_ACCOUNT_UUID, AttributeValues.fromUUID(uuid)))
|
||||
.conditionExpression(
|
||||
"attribute_not_exists(#number) OR (attribute_exists(#number) AND #uuid = :uuid)")
|
||||
.withExpressionAttributeNames(
|
||||
.expressionAttributeNames(
|
||||
Map.of("#uuid", KEY_ACCOUNT_UUID,
|
||||
"#number", ATTR_ACCOUNT_E164))
|
||||
.withExpressionAttributeValues(
|
||||
Map.of(":uuid", new AttributeValue().withB(UUIDUtil.toByteBuffer(uuid))))
|
||||
.withReturnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD));
|
||||
.expressionAttributeValues(
|
||||
Map.of(":uuid", AttributeValues.fromUUID(uuid)))
|
||||
.returnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD)
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -174,16 +169,18 @@ public class AccountsDynamoDb extends AbstractDynamoDbStore implements AccountSt
|
||||
UPDATE_TIMER.record(() -> {
|
||||
UpdateItemRequest updateItemRequest;
|
||||
try {
|
||||
updateItemRequest = new UpdateItemRequest()
|
||||
.withTableName(accountsTable.getTableName())
|
||||
.withKey(Map.of(KEY_ACCOUNT_UUID, new AttributeValue().withB(UUIDUtil.toByteBuffer(account.getUuid()))))
|
||||
.withUpdateExpression("SET #data = :data, #version = :version")
|
||||
.withConditionExpression("attribute_exists(#number)")
|
||||
.withExpressionAttributeNames(Map.of("#number", ATTR_ACCOUNT_E164,
|
||||
updateItemRequest = UpdateItemRequest.builder()
|
||||
.tableName(accountsTableName)
|
||||
.key(Map.of(KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getUuid())))
|
||||
.updateExpression("SET #data = :data, #version = :version")
|
||||
.conditionExpression("attribute_exists(#number)")
|
||||
.expressionAttributeNames(Map.of("#number", ATTR_ACCOUNT_E164,
|
||||
"#data", ATTR_ACCOUNT_DATA,
|
||||
"#version", ATTR_MIGRATION_VERSION))
|
||||
.withExpressionAttributeValues(Map.of(":data", new AttributeValue().withB(ByteBuffer.wrap(SystemMapper.getMapper().writeValueAsBytes(account))),
|
||||
":version", new AttributeValue().withN(String.valueOf(account.getDynamoDbMigrationVersion()))));
|
||||
.expressionAttributeValues(Map.of(
|
||||
":data", AttributeValues.fromByteArray(SystemMapper.getMapper().writeValueAsBytes(account)),
|
||||
":version", AttributeValues.fromInt(account.getDynamoDbMigrationVersion())))
|
||||
.build();
|
||||
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalArgumentException(e);
|
||||
@@ -193,37 +190,42 @@ public class AccountsDynamoDb extends AbstractDynamoDbStore implements AccountSt
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Optional<Account> get(String number) {
|
||||
|
||||
return GET_BY_NUMBER_TIMER.record(() -> {
|
||||
|
||||
final GetItemResult phoneNumberAndUuid = client.getItem(phoneNumbersTableName,
|
||||
Map.of(ATTR_ACCOUNT_E164, new AttributeValue(number)), true);
|
||||
final GetItemResponse response = client.getItem(GetItemRequest.builder()
|
||||
.tableName(phoneNumbersTableName)
|
||||
.key(Map.of(ATTR_ACCOUNT_E164, AttributeValues.fromString(number)))
|
||||
.build());
|
||||
|
||||
return Optional.ofNullable(phoneNumberAndUuid.getItem())
|
||||
.map(item -> item.get(KEY_ACCOUNT_UUID).getB())
|
||||
.map(uuid -> accountsTable.getItem(new GetItemSpec()
|
||||
.withPrimaryKey(KEY_ACCOUNT_UUID, uuid.array())
|
||||
.withConsistentRead(true)))
|
||||
return Optional.ofNullable(response.item())
|
||||
.map(item -> item.get(KEY_ACCOUNT_UUID))
|
||||
.map(uuid -> accountByUuid(uuid))
|
||||
.map(AccountsDynamoDb::fromItem);
|
||||
});
|
||||
}
|
||||
|
||||
private Map<String, AttributeValue> accountByUuid(AttributeValue uuid) {
|
||||
GetItemResponse r = client.getItem(GetItemRequest.builder()
|
||||
.tableName(accountsTableName)
|
||||
.key(Map.of(KEY_ACCOUNT_UUID, uuid))
|
||||
.consistentRead(true)
|
||||
.build());
|
||||
return r.item().isEmpty() ? null : r.item();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Account> get(UUID uuid) {
|
||||
Optional<Item> maybeItem = GET_BY_UUID_TIMER.record(() ->
|
||||
Optional.ofNullable(accountsTable.getItem(new GetItemSpec().
|
||||
withPrimaryKey(new PrimaryKey(KEY_ACCOUNT_UUID, UUIDUtil.toByteBuffer(uuid)))
|
||||
.withConsistentRead(true))));
|
||||
|
||||
return maybeItem.map(AccountsDynamoDb::fromItem);
|
||||
return GET_BY_UUID_TIMER.record(() ->
|
||||
Optional.ofNullable(accountByUuid(AttributeValues.fromUUID(uuid)))
|
||||
.map(AccountsDynamoDb::fromItem));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(UUID uuid) {
|
||||
DELETE_TIMER.record(() -> {
|
||||
|
||||
delete(uuid, true);
|
||||
});
|
||||
}
|
||||
@@ -238,18 +240,22 @@ public class AccountsDynamoDb extends AbstractDynamoDbStore implements AccountSt
|
||||
|
||||
maybeAccount.ifPresent(account -> {
|
||||
|
||||
TransactWriteItem phoneNumberDelete = new TransactWriteItem()
|
||||
.withDelete(new Delete()
|
||||
.withTableName(phoneNumbersTableName)
|
||||
.withKey(Map.of(ATTR_ACCOUNT_E164, new AttributeValue(account.getNumber()))));
|
||||
TransactWriteItem phoneNumberDelete = TransactWriteItem.builder()
|
||||
.delete(Delete.builder()
|
||||
.tableName(phoneNumbersTableName)
|
||||
.key(Map.of(ATTR_ACCOUNT_E164, AttributeValues.fromString(account.getNumber())))
|
||||
.build())
|
||||
.build();
|
||||
|
||||
TransactWriteItem accountDelete = new TransactWriteItem().withDelete(
|
||||
new Delete()
|
||||
.withTableName(accountsTable.getTableName())
|
||||
.withKey(Map.of(KEY_ACCOUNT_UUID, new AttributeValue().withB(UUIDUtil.toByteBuffer(uuid)))));
|
||||
TransactWriteItem accountDelete = TransactWriteItem.builder()
|
||||
.delete(Delete.builder()
|
||||
.tableName(accountsTableName)
|
||||
.key(Map.of(KEY_ACCOUNT_UUID, AttributeValues.fromUUID(uuid)))
|
||||
.build())
|
||||
.build();
|
||||
|
||||
TransactWriteItemsRequest request = new TransactWriteItemsRequest()
|
||||
.withTransactItems(phoneNumberDelete, accountDelete);
|
||||
TransactWriteItemsRequest request = TransactWriteItemsRequest.builder()
|
||||
.transactItems(phoneNumberDelete, accountDelete).build();
|
||||
|
||||
client.transactWriteItems(request);
|
||||
});
|
||||
@@ -299,64 +305,62 @@ public class AccountsDynamoDb extends AbstractDynamoDbStore implements AccountSt
|
||||
try {
|
||||
TransactWriteItem phoneNumberConstraintPut = buildPutWriteItemForPhoneNumberConstraint(account, account.getUuid());
|
||||
|
||||
TransactWriteItem accountPut = buildPutWriteItemForAccount(account, account.getUuid());
|
||||
accountPut.getPut()
|
||||
.setConditionExpression("attribute_not_exists(#uuid) OR (attribute_exists(#uuid) AND #version < :version)");
|
||||
accountPut.getPut()
|
||||
.setExpressionAttributeNames(Map.of("#uuid", KEY_ACCOUNT_UUID,
|
||||
"#version", ATTR_MIGRATION_VERSION));
|
||||
accountPut.getPut()
|
||||
.setExpressionAttributeValues(
|
||||
Map.of(":version", new AttributeValue().withN(String.valueOf(account.getDynamoDbMigrationVersion()))));
|
||||
TransactWriteItem accountPut = buildPutWriteItemForAccount(account, account.getUuid(), Put.builder()
|
||||
.conditionExpression("attribute_not_exists(#uuid) OR (attribute_exists(#uuid) AND #version < :version)")
|
||||
.expressionAttributeNames(Map.of(
|
||||
"#uuid", KEY_ACCOUNT_UUID,
|
||||
"#version", ATTR_MIGRATION_VERSION))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":version", AttributeValues.fromInt(account.getDynamoDbMigrationVersion()))));
|
||||
|
||||
final TransactWriteItemsRequest request = new TransactWriteItemsRequest()
|
||||
.withTransactItems(phoneNumberConstraintPut, accountPut);
|
||||
final TransactWriteItemsRequest request = TransactWriteItemsRequest.builder()
|
||||
.transactItems(phoneNumberConstraintPut, accountPut).build();
|
||||
|
||||
final CompletableFuture<Boolean> resultFuture = new CompletableFuture<>();
|
||||
|
||||
asyncClient.transactWriteItemsAsync(request,
|
||||
new AsyncHandler<>() {
|
||||
@Override
|
||||
public void onError(Exception exception) {
|
||||
if (exception instanceof TransactionCanceledException) {
|
||||
// account is already migrated
|
||||
resultFuture.complete(false);
|
||||
} else {
|
||||
try {
|
||||
migrationRetryAccounts.put(account.getUuid());
|
||||
} catch (final Exception e) {
|
||||
logger.error("Could not store account {}", account.getUuid());
|
||||
}
|
||||
resultFuture.completeExceptionally(exception);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSuccess(TransactWriteItemsRequest request, TransactWriteItemsResult transactWriteItemsResult) {
|
||||
resultFuture.complete(true);
|
||||
}
|
||||
});
|
||||
|
||||
asyncClient.transactWriteItems(request).whenCompleteAsync((result, exception) -> {
|
||||
if (result != null) {
|
||||
resultFuture.complete(true);
|
||||
return;
|
||||
}
|
||||
if (exception instanceof CompletionException) {
|
||||
// whenCompleteAsync can wrap exceptions in a CompletionException; unwrap it to get to the root cause.
|
||||
exception = exception.getCause();
|
||||
}
|
||||
if (exception instanceof TransactionCanceledException) {
|
||||
// account is already migrated
|
||||
resultFuture.complete(false);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
migrationRetryAccounts.put(account.getUuid());
|
||||
} catch (final Exception e) {
|
||||
logger.error("Could not store account {}", account.getUuid());
|
||||
}
|
||||
resultFuture.completeExceptionally(exception);
|
||||
});
|
||||
return resultFuture;
|
||||
|
||||
} catch (Exception e) {
|
||||
return CompletableFuture.failedFuture(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static String extractCancellationReasonCodes(final TransactionCanceledException exception) {
|
||||
return exception.getCancellationReasons().stream()
|
||||
.map(CancellationReason::getCode)
|
||||
return exception.cancellationReasons().stream()
|
||||
.map(CancellationReason::code)
|
||||
.collect(Collectors.joining(", "));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static Account fromItem(Item item) {
|
||||
static Account fromItem(Map<String, AttributeValue> item) {
|
||||
if (!item.containsKey(ATTR_ACCOUNT_DATA) ||
|
||||
!item.containsKey(ATTR_ACCOUNT_E164) ||
|
||||
!item.containsKey(KEY_ACCOUNT_UUID)) {
|
||||
throw new RuntimeException("item missing values");
|
||||
}
|
||||
try {
|
||||
Account account = SystemMapper.getMapper().readValue(item.getBinary(ATTR_ACCOUNT_DATA), Account.class);
|
||||
|
||||
account.setNumber(item.getString(ATTR_ACCOUNT_E164));
|
||||
account.setUuid(UUIDUtil.fromByteBuffer(item.getByteBuffer(KEY_ACCOUNT_UUID)));
|
||||
Account account = SystemMapper.getMapper().readValue(item.get(ATTR_ACCOUNT_DATA).b().asByteArray(), Account.class);
|
||||
account.setNumber(item.get(ATTR_ACCOUNT_E164).s());
|
||||
account.setUuid(UUIDUtil.fromByteBuffer(item.get(KEY_ACCOUNT_UUID).b().asByteBuffer()));
|
||||
|
||||
return account;
|
||||
|
||||
|
||||
+10
-3
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException;
|
||||
import com.codahale.metrics.MetricRegistry;
|
||||
import com.codahale.metrics.SharedMetricRegistries;
|
||||
import com.codahale.metrics.Timer;
|
||||
@@ -42,6 +41,7 @@ import org.whispersystems.textsecuregcm.sqs.DirectoryQueue;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
|
||||
|
||||
public class AccountsManager {
|
||||
|
||||
@@ -71,6 +71,7 @@ public class AccountsManager {
|
||||
private final Accounts accounts;
|
||||
private final AccountsDynamoDb accountsDynamoDb;
|
||||
private final FaultTolerantRedisCluster cacheCluster;
|
||||
private final DeletedAccounts deletedAccounts;
|
||||
private final DirectoryQueue directoryQueue;
|
||||
private final KeysDynamoDb keysDynamoDb;
|
||||
private final MessagesManager messagesManager;
|
||||
@@ -97,14 +98,18 @@ public class AccountsManager {
|
||||
}
|
||||
}
|
||||
|
||||
public AccountsManager(Accounts accounts, AccountsDynamoDb accountsDynamoDb, FaultTolerantRedisCluster cacheCluster, final DirectoryQueue directoryQueue,
|
||||
public AccountsManager(Accounts accounts, AccountsDynamoDb accountsDynamoDb, FaultTolerantRedisCluster cacheCluster,
|
||||
final DeletedAccounts deletedAccounts,
|
||||
final DirectoryQueue directoryQueue,
|
||||
final KeysDynamoDb keysDynamoDb, final MessagesManager messagesManager, final UsernamesManager usernamesManager,
|
||||
final ProfilesManager profilesManager, final SecureStorageClient secureStorageClient,
|
||||
final SecureBackupClient secureBackupClient,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager, final DynamicConfigurationManager dynamicConfigurationManager) {
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager,
|
||||
final DynamicConfigurationManager dynamicConfigurationManager) {
|
||||
this.accounts = accounts;
|
||||
this.accountsDynamoDb = accountsDynamoDb;
|
||||
this.cacheCluster = cacheCluster;
|
||||
this.deletedAccounts = deletedAccounts;
|
||||
this.directoryQueue = directoryQueue;
|
||||
this.keysDynamoDb = keysDynamoDb;
|
||||
this.messagesManager = messagesManager;
|
||||
@@ -263,6 +268,8 @@ public class AccountsManager {
|
||||
}
|
||||
}
|
||||
|
||||
deletedAccounts.put(account.getUuid(), account.getNumber());
|
||||
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Failed to delete account", e);
|
||||
|
||||
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
public class ChunkProcessingFailedException extends Exception {
|
||||
|
||||
public ChunkProcessingFailedException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public ChunkProcessingFailedException(Exception cause) {
|
||||
super(cause);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ScanRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
|
||||
|
||||
public class DeletedAccounts extends AbstractDynamoDbStore {
|
||||
|
||||
// e164, primary key
|
||||
static final String KEY_ACCOUNT_E164 = "P";
|
||||
static final String ATTR_ACCOUNT_UUID = "U";
|
||||
static final String ATTR_EXPIRES = "E";
|
||||
static final String ATTR_NEEDS_CDS_RECONCILIATION = "R";
|
||||
|
||||
static final Duration TIME_TO_LIVE = Duration.ofDays(30);
|
||||
|
||||
private final String tableName;
|
||||
private final String needsReconciliationIndexName;
|
||||
|
||||
public DeletedAccounts(final DynamoDbClient dynamoDb, final String tableName, final String needsReconciliationIndexName) {
|
||||
|
||||
super(dynamoDb);
|
||||
this.tableName = tableName;
|
||||
this.needsReconciliationIndexName = needsReconciliationIndexName;
|
||||
}
|
||||
|
||||
public void put(UUID uuid, String e164) {
|
||||
db().putItem(PutItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.item(Map.of(
|
||||
KEY_ACCOUNT_E164, AttributeValues.fromString(e164),
|
||||
ATTR_ACCOUNT_UUID, AttributeValues.fromUUID(uuid),
|
||||
ATTR_EXPIRES, AttributeValues.fromLong(Instant.now().plus(TIME_TO_LIVE).getEpochSecond()),
|
||||
ATTR_NEEDS_CDS_RECONCILIATION, AttributeValues.fromInt(1)))
|
||||
.build());
|
||||
}
|
||||
|
||||
public List<Pair<UUID, String>> listAccountsToReconcile(final int max) {
|
||||
|
||||
final ScanRequest scanRequest = ScanRequest.builder()
|
||||
.tableName(tableName)
|
||||
.indexName(needsReconciliationIndexName)
|
||||
.limit(max)
|
||||
.build();
|
||||
|
||||
return scan(scanRequest, max)
|
||||
.stream()
|
||||
.map(item -> new Pair<>(
|
||||
AttributeValues.getUUID(item, ATTR_ACCOUNT_UUID, null),
|
||||
AttributeValues.getString(item, KEY_ACCOUNT_E164, null)))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public void markReconciled(final List<String> phoneNumbersReconciled) {
|
||||
|
||||
phoneNumbersReconciled.forEach(number -> db().updateItem(
|
||||
UpdateItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(
|
||||
KEY_ACCOUNT_E164, AttributeValues.fromString(number)
|
||||
))
|
||||
.updateExpression("REMOVE #needs_reconciliation")
|
||||
.expressionAttributeNames(Map.of(
|
||||
"#needs_reconciliation", ATTR_NEEDS_CDS_RECONCILIATION
|
||||
))
|
||||
.build()
|
||||
));
|
||||
}
|
||||
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.util.List;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.DirectoryReconciliationRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.DirectoryReconciliationRequest.User;
|
||||
import org.whispersystems.textsecuregcm.entities.DirectoryReconciliationResponse;
|
||||
|
||||
public class DeletedAccountsDirectoryReconciler {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(DeletedAccountsDirectoryReconciler.class);
|
||||
|
||||
private final DirectoryReconciliationClient directoryReconciliationClient;
|
||||
|
||||
private final Timer deleteTimer;
|
||||
private final Counter errorCounter;
|
||||
|
||||
public DeletedAccountsDirectoryReconciler(
|
||||
final String replicationName,
|
||||
final DirectoryReconciliationClient directoryReconciliationClient) {
|
||||
this.directoryReconciliationClient = directoryReconciliationClient;
|
||||
|
||||
deleteTimer = Timer.builder(name(DeletedAccountsDirectoryReconciler.class, "delete"))
|
||||
.tag("replicationName", replicationName)
|
||||
.register(Metrics.globalRegistry);
|
||||
|
||||
errorCounter = Counter.builder(name(DeletedAccountsDirectoryReconciler.class, "error"))
|
||||
.tag("replicationName", replicationName)
|
||||
.register(Metrics.globalRegistry);
|
||||
|
||||
}
|
||||
|
||||
public void onCrawlChunk(final List<User> deletedUsers) throws ChunkProcessingFailedException {
|
||||
|
||||
try {
|
||||
deleteTimer.recordCallable(() -> {
|
||||
try {
|
||||
final DirectoryReconciliationResponse response = directoryReconciliationClient.delete(new DirectoryReconciliationRequest(null, null, deletedUsers));
|
||||
|
||||
if (response.getStatus() != DirectoryReconciliationResponse.Status.OK) {
|
||||
errorCounter.increment();
|
||||
|
||||
throw new ChunkProcessingFailedException("Response status: " + response.getStatus());
|
||||
}
|
||||
} catch (final Exception e) {
|
||||
|
||||
errorCounter.increment();
|
||||
|
||||
throw new ChunkProcessingFailedException(e);
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
} catch (final ChunkProcessingFailedException e) {
|
||||
throw e;
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Unexpected exception", e);
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.stream.Collectors;
|
||||
import org.whispersystems.textsecuregcm.entities.DirectoryReconciliationRequest.User;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
|
||||
public class DeletedAccountsTableCrawler extends ManagedPeriodicWork {
|
||||
|
||||
private static final Duration WORKER_TTL = Duration.ofMinutes(2);
|
||||
private static final Duration RUN_INTERVAL = Duration.ofMinutes(15);
|
||||
private static final String ACTIVE_WORKER_KEY = "deleted_accounts_crawler_cache_active_worker";
|
||||
|
||||
private static final int MAX_BATCH_SIZE = 5_000;
|
||||
private static final String BATCH_SIZE_DISTRIBUTION_NAME = name(DeletedAccountsTableCrawler.class, "batchSize");
|
||||
|
||||
private final DeletedAccounts deletedAccounts;
|
||||
private final List<DeletedAccountsDirectoryReconciler> reconcilers;
|
||||
|
||||
public DeletedAccountsTableCrawler(
|
||||
final DeletedAccounts deletedAccounts,
|
||||
final List<DeletedAccountsDirectoryReconciler> reconcilers,
|
||||
final FaultTolerantRedisCluster cluster,
|
||||
final ScheduledExecutorService executorService) throws IOException {
|
||||
|
||||
super(new ManagedPeriodicWorkLock(ACTIVE_WORKER_KEY, cluster), WORKER_TTL, RUN_INTERVAL, executorService);
|
||||
|
||||
this.deletedAccounts = deletedAccounts;
|
||||
this.reconcilers = reconcilers;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doPeriodicWork() throws Exception {
|
||||
|
||||
final List<Pair<UUID, String>> deletedAccounts = this.deletedAccounts.listAccountsToReconcile(MAX_BATCH_SIZE);
|
||||
|
||||
final List<User> deletedUsers = deletedAccounts.stream()
|
||||
.map(pair -> new User(pair.first(), pair.second()))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
for (DeletedAccountsDirectoryReconciler reconciler : reconcilers) {
|
||||
reconciler.onCrawlChunk(deletedUsers);
|
||||
}
|
||||
|
||||
final List<String> reconciledPhoneNumbers = deletedAccounts.stream()
|
||||
.map(Pair::second)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
this.deletedAccounts.markReconciled(reconciledPhoneNumbers);
|
||||
|
||||
Metrics.summary(BATCH_SIZE_DISTRIBUTION_NAME)
|
||||
.record(reconciledPhoneNumbers.size());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -276,10 +276,13 @@ public class Device {
|
||||
@JsonProperty
|
||||
private boolean senderKey;
|
||||
|
||||
@JsonProperty
|
||||
private boolean announcementGroup;
|
||||
|
||||
public DeviceCapabilities() {}
|
||||
|
||||
public DeviceCapabilities(boolean gv2, final boolean gv2_2, final boolean gv2_3, boolean storage, boolean transfer,
|
||||
boolean gv1Migration, final boolean senderKey) {
|
||||
boolean gv1Migration, final boolean senderKey, final boolean announcementGroup) {
|
||||
this.gv2 = gv2;
|
||||
this.gv2_2 = gv2_2;
|
||||
this.gv2_3 = gv2_3;
|
||||
@@ -287,6 +290,7 @@ public class Device {
|
||||
this.transfer = transfer;
|
||||
this.gv1Migration = gv1Migration;
|
||||
this.senderKey = senderKey;
|
||||
this.announcementGroup = announcementGroup;
|
||||
}
|
||||
|
||||
public boolean isGv2() {
|
||||
@@ -316,5 +320,9 @@ public class Device {
|
||||
public boolean isSenderKey() {
|
||||
return senderKey;
|
||||
}
|
||||
|
||||
public boolean isAnnouncementGroup() {
|
||||
return announcementGroup;
|
||||
}
|
||||
}
|
||||
}
|
||||
+16
-10
@@ -4,7 +4,16 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.codahale.metrics.SharedMetricRegistries;
|
||||
import java.security.KeyStore;
|
||||
import java.security.cert.CertificateException;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.ws.rs.client.Client;
|
||||
import javax.ws.rs.client.ClientBuilder;
|
||||
import javax.ws.rs.client.Entity;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import org.glassfish.jersey.SslConfigurator;
|
||||
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
|
||||
import org.whispersystems.textsecuregcm.configuration.DirectoryServerConfiguration;
|
||||
@@ -14,16 +23,6 @@ import org.whispersystems.textsecuregcm.util.CertificateExpirationGauge;
|
||||
import org.whispersystems.textsecuregcm.util.CertificateUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.ws.rs.client.Client;
|
||||
import javax.ws.rs.client.ClientBuilder;
|
||||
import javax.ws.rs.client.Entity;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import java.security.KeyStore;
|
||||
import java.security.cert.CertificateException;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
public class DirectoryReconciliationClient {
|
||||
|
||||
private final String replicationUrl;
|
||||
@@ -47,6 +46,13 @@ public class DirectoryReconciliationClient {
|
||||
.put(Entity.json(request), DirectoryReconciliationResponse.class);
|
||||
}
|
||||
|
||||
public DirectoryReconciliationResponse delete(DirectoryReconciliationRequest request) {
|
||||
return client.target(replicationUrl)
|
||||
.path("/v3/directory/deletes")
|
||||
.request(MediaType.APPLICATION_JSON_TYPE)
|
||||
.put(Entity.json(request), DirectoryReconciliationResponse.class);
|
||||
}
|
||||
|
||||
private static Client initializeClient(DirectoryServerConfiguration directoryServerConfiguration)
|
||||
throws CertificateException
|
||||
{
|
||||
|
||||
+29
-3
@@ -18,8 +18,12 @@ import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
import javax.validation.ConstraintViolation;
|
||||
import javax.validation.Validation;
|
||||
import javax.validation.Validator;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
@@ -32,16 +36,19 @@ public class DynamicConfigurationManager {
|
||||
private final AmazonAppConfig appConfigClient;
|
||||
|
||||
private final AtomicReference<DynamicConfiguration> configuration = new AtomicReference<>();
|
||||
private final Logger logger = LoggerFactory.getLogger(DynamicConfigurationManager.class);
|
||||
|
||||
private GetConfigurationResult lastConfigResult;
|
||||
|
||||
private boolean initialized = false;
|
||||
|
||||
public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(new YAMLFactory())
|
||||
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(new YAMLFactory())
|
||||
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
|
||||
.registerModule(new JavaTimeModule());
|
||||
|
||||
private static final Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(DynamicConfigurationManager.class);
|
||||
|
||||
public DynamicConfigurationManager(String application, String environment, String configurationName) {
|
||||
this(AmazonAppConfigClient.builder()
|
||||
.withClientConfiguration(new ClientConfiguration().withClientExecutionTimeout(10000).withRequestTimeout(10000))
|
||||
@@ -104,7 +111,9 @@ public class DynamicConfigurationManager {
|
||||
|
||||
if (!StringUtils.equals(lastConfigResult.getConfigurationVersion(), previousVersion)) {
|
||||
logger.info("Received new config version: {}", lastConfigResult.getConfigurationVersion());
|
||||
maybeDynamicConfiguration = Optional.of(OBJECT_MAPPER.readValue(StandardCharsets.UTF_8.decode(lastConfigResult.getContent().asReadOnlyBuffer()).toString(), DynamicConfiguration.class));
|
||||
|
||||
maybeDynamicConfiguration =
|
||||
parseConfiguration(StandardCharsets.UTF_8.decode(lastConfigResult.getContent().asReadOnlyBuffer()).toString());
|
||||
} else {
|
||||
// No change since last version
|
||||
maybeDynamicConfiguration = Optional.empty();
|
||||
@@ -113,6 +122,23 @@ public class DynamicConfigurationManager {
|
||||
return maybeDynamicConfiguration;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public static Optional<DynamicConfiguration> parseConfiguration(final String configurationYaml) throws JsonProcessingException {
|
||||
final DynamicConfiguration configuration = OBJECT_MAPPER.readValue(configurationYaml, DynamicConfiguration.class);
|
||||
final Set<ConstraintViolation<DynamicConfiguration>> violations = VALIDATOR.validate(configuration);
|
||||
|
||||
final Optional<DynamicConfiguration> maybeDynamicConfiguration;
|
||||
|
||||
if (violations.isEmpty()) {
|
||||
maybeDynamicConfiguration = Optional.of(configuration);
|
||||
} else {
|
||||
logger.warn("Failed to validate configuration: {}", violations);
|
||||
maybeDynamicConfiguration = Optional.empty();
|
||||
}
|
||||
|
||||
return maybeDynamicConfiguration;
|
||||
}
|
||||
|
||||
private DynamicConfiguration retrieveInitialDynamicConfiguration() {
|
||||
for (;;) {
|
||||
try {
|
||||
|
||||
+186
-151
@@ -7,195 +7,230 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.amazonaws.services.dynamodbv2.document.DeleteItemOutcome;
|
||||
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.document.Item;
|
||||
import com.amazonaws.services.dynamodbv2.document.PrimaryKey;
|
||||
import com.amazonaws.services.dynamodbv2.document.Table;
|
||||
import com.amazonaws.services.dynamodbv2.document.TableWriteItems;
|
||||
import com.amazonaws.services.dynamodbv2.document.spec.DeleteItemSpec;
|
||||
import com.amazonaws.services.dynamodbv2.document.spec.QuerySpec;
|
||||
import com.amazonaws.services.dynamodbv2.model.ReturnValue;
|
||||
import com.amazonaws.services.dynamodbv2.model.Select;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.whispersystems.textsecuregcm.entities.PreKey;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteItemResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.PutRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.Select;
|
||||
import software.amazon.awssdk.services.dynamodb.model.WriteRequest;
|
||||
|
||||
public class KeysDynamoDb extends AbstractDynamoDbStore {
|
||||
|
||||
private final Table table;
|
||||
private final String tableName;
|
||||
|
||||
static final String KEY_ACCOUNT_UUID = "U";
|
||||
static final String KEY_DEVICE_ID_KEY_ID = "DK";
|
||||
static final String KEY_PUBLIC_KEY = "P";
|
||||
static final String KEY_ACCOUNT_UUID = "U";
|
||||
static final String KEY_DEVICE_ID_KEY_ID = "DK";
|
||||
static final String KEY_PUBLIC_KEY = "P";
|
||||
|
||||
private static final Timer STORE_KEYS_TIMER = Metrics.timer(name(KeysDynamoDb.class, "storeKeys"));
|
||||
private static final Timer TAKE_KEY_FOR_DEVICE_TIMER = Metrics.timer(name(KeysDynamoDb.class, "takeKeyForDevice"));
|
||||
private static final Timer TAKE_KEYS_FOR_ACCOUNT_TIMER = Metrics.timer(name(KeysDynamoDb.class, "takeKeyForAccount"));
|
||||
private static final Timer GET_KEY_COUNT_TIMER = Metrics.timer(name(KeysDynamoDb.class, "getKeyCount"));
|
||||
private static final Timer DELETE_KEYS_FOR_DEVICE_TIMER = Metrics.timer(name(KeysDynamoDb.class, "deleteKeysForDevice"));
|
||||
private static final Timer DELETE_KEYS_FOR_ACCOUNT_TIMER = Metrics.timer(name(KeysDynamoDb.class, "deleteKeysForAccount"));
|
||||
private static final DistributionSummary CONTESTED_KEY_DISTRIBUTION = Metrics.summary(name(KeysDynamoDb.class, "contestedKeys"));
|
||||
private static final DistributionSummary KEY_COUNT_DISTRIBUTION = Metrics.summary(name(KeysDynamoDb.class, "keyCount"));
|
||||
private static final Timer STORE_KEYS_TIMER = Metrics.timer(name(KeysDynamoDb.class, "storeKeys"));
|
||||
private static final Timer TAKE_KEY_FOR_DEVICE_TIMER = Metrics.timer(name(KeysDynamoDb.class, "takeKeyForDevice"));
|
||||
private static final Timer TAKE_KEYS_FOR_ACCOUNT_TIMER = Metrics.timer(name(KeysDynamoDb.class, "takeKeyForAccount"));
|
||||
private static final Timer GET_KEY_COUNT_TIMER = Metrics.timer(name(KeysDynamoDb.class, "getKeyCount"));
|
||||
private static final Timer DELETE_KEYS_FOR_DEVICE_TIMER = Metrics.timer(name(KeysDynamoDb.class, "deleteKeysForDevice"));
|
||||
private static final Timer DELETE_KEYS_FOR_ACCOUNT_TIMER = Metrics.timer(name(KeysDynamoDb.class, "deleteKeysForAccount"));
|
||||
private static final DistributionSummary CONTESTED_KEY_DISTRIBUTION = Metrics.summary(name(KeysDynamoDb.class, "contestedKeys"));
|
||||
private static final DistributionSummary KEY_COUNT_DISTRIBUTION = Metrics.summary(name(KeysDynamoDb.class, "keyCount"));
|
||||
|
||||
public KeysDynamoDb(final DynamoDB dynamoDB, final String tableName) {
|
||||
super(dynamoDB);
|
||||
public KeysDynamoDb(final DynamoDbClient dynamoDB, final String tableName) {
|
||||
super(dynamoDB);
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
this.table = dynamoDB.getTable(tableName);
|
||||
}
|
||||
public void store(final Account account, final long deviceId, final List<PreKey> keys) {
|
||||
STORE_KEYS_TIMER.record(() -> {
|
||||
delete(account, deviceId);
|
||||
|
||||
public void store(final Account account, final long deviceId, final List<PreKey> keys) {
|
||||
STORE_KEYS_TIMER.record(() -> {
|
||||
delete(account, deviceId);
|
||||
writeInBatches(keys, batch -> {
|
||||
List<WriteRequest> items = new ArrayList<>();
|
||||
for (final PreKey preKey : batch) {
|
||||
items.add(WriteRequest.builder()
|
||||
.putRequest(PutRequest.builder()
|
||||
.item(getItemFromPreKey(account.getUuid(), deviceId, preKey))
|
||||
.build())
|
||||
.build());
|
||||
}
|
||||
executeTableWriteItemsUntilComplete(Map.of(tableName, items));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
writeInBatches(keys, batch -> {
|
||||
final TableWriteItems items = new TableWriteItems(table.getTableName());
|
||||
public Optional<PreKey> take(final Account account, final long deviceId) {
|
||||
return TAKE_KEY_FOR_DEVICE_TIMER.record(() -> {
|
||||
final AttributeValue partitionKey = getPartitionKey(account.getUuid());
|
||||
QueryRequest queryRequest = QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.keyConditionExpression("#uuid = :uuid AND begins_with (#sort, :sortprefix)")
|
||||
.expressionAttributeNames(Map.of("#uuid", KEY_ACCOUNT_UUID, "#sort", KEY_DEVICE_ID_KEY_ID))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":uuid", partitionKey,
|
||||
":sortprefix", getSortKeyPrefix(deviceId)))
|
||||
.projectionExpression(KEY_DEVICE_ID_KEY_ID)
|
||||
.consistentRead(false)
|
||||
.build();
|
||||
|
||||
for (final PreKey preKey : batch) {
|
||||
items.addItemToPut(getItemFromPreKey(account.getUuid(), deviceId, preKey));
|
||||
}
|
||||
int contestedKeys = 0;
|
||||
|
||||
executeTableWriteItemsUntilComplete(items);
|
||||
});
|
||||
});
|
||||
}
|
||||
try {
|
||||
QueryResponse response = db().query(queryRequest);
|
||||
for (Map<String, AttributeValue> candidate : response.items()) {
|
||||
DeleteItemRequest deleteItemRequest = DeleteItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(
|
||||
KEY_ACCOUNT_UUID, partitionKey,
|
||||
KEY_DEVICE_ID_KEY_ID, candidate.get(KEY_DEVICE_ID_KEY_ID)))
|
||||
.returnValues(ReturnValue.ALL_OLD)
|
||||
.build();
|
||||
DeleteItemResponse deleteItemResponse = db().deleteItem(deleteItemRequest);
|
||||
if (deleteItemResponse.hasAttributes()) {
|
||||
return Optional.of(getPreKeyFromItem(deleteItemResponse.attributes()));
|
||||
}
|
||||
|
||||
public Optional<PreKey> take(final Account account, final long deviceId) {
|
||||
return TAKE_KEY_FOR_DEVICE_TIMER.record(() -> {
|
||||
final byte[] partitionKey = getPartitionKey(account.getUuid());
|
||||
contestedKeys++;
|
||||
}
|
||||
|
||||
final QuerySpec querySpec = new QuerySpec().withKeyConditionExpression("#uuid = :uuid AND begins_with (#sort, :sortprefix)")
|
||||
.withNameMap(Map.of("#uuid", KEY_ACCOUNT_UUID, "#sort", KEY_DEVICE_ID_KEY_ID))
|
||||
.withValueMap(Map.of(":uuid", partitionKey,
|
||||
":sortprefix", getSortKeyPrefix(deviceId)))
|
||||
.withProjectionExpression(KEY_DEVICE_ID_KEY_ID)
|
||||
.withConsistentRead(false);
|
||||
return Optional.empty();
|
||||
} finally {
|
||||
CONTESTED_KEY_DISTRIBUTION.record(contestedKeys);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
int contestedKeys = 0;
|
||||
public Map<Long, PreKey> take(final Account account) {
|
||||
return TAKE_KEYS_FOR_ACCOUNT_TIMER.record(() -> {
|
||||
final Map<Long, PreKey> preKeysByDeviceId = new HashMap<>();
|
||||
|
||||
try {
|
||||
for (final Item candidate : table.query(querySpec)) {
|
||||
final DeleteItemSpec deleteItemSpec = new DeleteItemSpec().withPrimaryKey(KEY_ACCOUNT_UUID, partitionKey, KEY_DEVICE_ID_KEY_ID, candidate.getBinary(KEY_DEVICE_ID_KEY_ID))
|
||||
.withReturnValues(ReturnValue.ALL_OLD);
|
||||
for (final Device device : account.getDevices()) {
|
||||
take(account, device.getId()).ifPresent(preKey -> preKeysByDeviceId.put(device.getId(), preKey));
|
||||
}
|
||||
|
||||
final DeleteItemOutcome outcome = table.deleteItem(deleteItemSpec);
|
||||
return preKeysByDeviceId;
|
||||
});
|
||||
}
|
||||
|
||||
if (outcome.getItem() != null) {
|
||||
return Optional.of(getPreKeyFromItem(outcome.getItem()));
|
||||
}
|
||||
public int getCount(final Account account, final long deviceId) {
|
||||
return GET_KEY_COUNT_TIMER.record(() -> {
|
||||
QueryRequest queryRequest = QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.keyConditionExpression("#uuid = :uuid AND begins_with (#sort, :sortprefix)")
|
||||
.expressionAttributeNames(Map.of("#uuid", KEY_ACCOUNT_UUID, "#sort", KEY_DEVICE_ID_KEY_ID))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":uuid", getPartitionKey(account.getUuid()),
|
||||
":sortprefix", getSortKeyPrefix(deviceId)))
|
||||
.select(Select.COUNT)
|
||||
.consistentRead(false)
|
||||
.build();
|
||||
|
||||
contestedKeys++;
|
||||
}
|
||||
int keyCount = 0;
|
||||
// This is very confusing, but does appear to be the intended behavior. See:
|
||||
//
|
||||
// - https://github.com/aws/aws-sdk-java/issues/693
|
||||
// - https://github.com/aws/aws-sdk-java/issues/915
|
||||
// - https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html#Query.Count
|
||||
for (final QueryResponse page : db().queryPaginator(queryRequest)) {
|
||||
keyCount += page.count();
|
||||
}
|
||||
KEY_COUNT_DISTRIBUTION.record(keyCount);
|
||||
return keyCount;
|
||||
});
|
||||
}
|
||||
|
||||
return Optional.empty();
|
||||
} finally {
|
||||
CONTESTED_KEY_DISTRIBUTION.record(contestedKeys);
|
||||
}
|
||||
});
|
||||
}
|
||||
public void delete(final Account account) {
|
||||
DELETE_KEYS_FOR_ACCOUNT_TIMER.record(() -> {
|
||||
final QueryRequest queryRequest = QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.keyConditionExpression("#uuid = :uuid")
|
||||
.expressionAttributeNames(Map.of("#uuid", KEY_ACCOUNT_UUID))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":uuid", getPartitionKey(account.getUuid())))
|
||||
.projectionExpression(KEY_DEVICE_ID_KEY_ID)
|
||||
.consistentRead(true)
|
||||
.build();
|
||||
|
||||
public Map<Long, PreKey> take(final Account account) {
|
||||
return TAKE_KEYS_FOR_ACCOUNT_TIMER.record(() -> {
|
||||
final Map<Long, PreKey> preKeysByDeviceId = new HashMap<>();
|
||||
deleteItemsForAccountMatchingQuery(account, queryRequest);
|
||||
});
|
||||
}
|
||||
|
||||
for (final Device device : account.getDevices()) {
|
||||
take(account, device.getId()).ifPresent(preKey -> preKeysByDeviceId.put(device.getId(), preKey));
|
||||
}
|
||||
@VisibleForTesting
|
||||
void delete(final Account account, final long deviceId) {
|
||||
DELETE_KEYS_FOR_DEVICE_TIMER.record(() -> {
|
||||
final QueryRequest queryRequest = QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.keyConditionExpression("#uuid = :uuid AND begins_with (#sort, :sortprefix)")
|
||||
.expressionAttributeNames(Map.of("#uuid", KEY_ACCOUNT_UUID, "#sort", KEY_DEVICE_ID_KEY_ID))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":uuid", getPartitionKey(account.getUuid()),
|
||||
":sortprefix", getSortKeyPrefix(deviceId)))
|
||||
.projectionExpression(KEY_DEVICE_ID_KEY_ID)
|
||||
.consistentRead(true)
|
||||
.build();
|
||||
|
||||
return preKeysByDeviceId;
|
||||
});
|
||||
}
|
||||
deleteItemsForAccountMatchingQuery(account, queryRequest);
|
||||
});
|
||||
}
|
||||
|
||||
public int getCount(final Account account, final long deviceId) {
|
||||
return GET_KEY_COUNT_TIMER.record(() -> {
|
||||
final QuerySpec querySpec = new QuerySpec().withKeyConditionExpression("#uuid = :uuid AND begins_with (#sort, :sortprefix)")
|
||||
.withNameMap(Map.of("#uuid", KEY_ACCOUNT_UUID, "#sort", KEY_DEVICE_ID_KEY_ID))
|
||||
.withValueMap(Map.of(":uuid", getPartitionKey(account.getUuid()),
|
||||
":sortprefix", getSortKeyPrefix(deviceId)))
|
||||
.withSelect(Select.COUNT)
|
||||
.withConsistentRead(false);
|
||||
private void deleteItemsForAccountMatchingQuery(final Account account, final QueryRequest querySpec) {
|
||||
final AttributeValue partitionKey = getPartitionKey(account.getUuid());
|
||||
|
||||
final int keyCount = (int)countItemsMatchingQuery(table, querySpec);
|
||||
writeInBatches(db().query(querySpec).items(), batch -> {
|
||||
List<WriteRequest> deletes = new ArrayList<>();
|
||||
for (final Map<String, AttributeValue> item : batch) {
|
||||
deletes.add(WriteRequest.builder()
|
||||
.deleteRequest(DeleteRequest.builder()
|
||||
.key(Map.of(
|
||||
KEY_ACCOUNT_UUID, partitionKey,
|
||||
KEY_DEVICE_ID_KEY_ID, item.get(KEY_DEVICE_ID_KEY_ID)))
|
||||
.build())
|
||||
.build());
|
||||
}
|
||||
executeTableWriteItemsUntilComplete(Map.of(tableName, deletes));
|
||||
});
|
||||
}
|
||||
|
||||
KEY_COUNT_DISTRIBUTION.record(keyCount);
|
||||
return keyCount;
|
||||
});
|
||||
}
|
||||
private static AttributeValue getPartitionKey(final UUID accountUuid) {
|
||||
return AttributeValues.fromUUID(accountUuid);
|
||||
}
|
||||
|
||||
public void delete(final Account account) {
|
||||
DELETE_KEYS_FOR_ACCOUNT_TIMER.record(() -> {
|
||||
final QuerySpec querySpec = new QuerySpec().withKeyConditionExpression("#uuid = :uuid")
|
||||
.withNameMap(Map.of("#uuid", KEY_ACCOUNT_UUID))
|
||||
.withValueMap(Map.of(":uuid", getPartitionKey(account.getUuid())))
|
||||
.withProjectionExpression(KEY_DEVICE_ID_KEY_ID)
|
||||
.withConsistentRead(true);
|
||||
private static AttributeValue getSortKey(final long deviceId, final long keyId) {
|
||||
final ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]);
|
||||
byteBuffer.putLong(deviceId);
|
||||
byteBuffer.putLong(keyId);
|
||||
return AttributeValues.fromByteBuffer(byteBuffer.flip());
|
||||
}
|
||||
|
||||
deleteItemsForAccountMatchingQuery(account, querySpec);
|
||||
});
|
||||
}
|
||||
@VisibleForTesting
|
||||
static AttributeValue getSortKeyPrefix(final long deviceId) {
|
||||
final ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[8]);
|
||||
byteBuffer.putLong(deviceId);
|
||||
return AttributeValues.fromByteBuffer(byteBuffer.flip());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
void delete(final Account account, final long deviceId) {
|
||||
DELETE_KEYS_FOR_DEVICE_TIMER.record(() -> {
|
||||
final QuerySpec querySpec = new QuerySpec().withKeyConditionExpression("#uuid = :uuid AND begins_with (#sort, :sortprefix)")
|
||||
.withNameMap(Map.of("#uuid", KEY_ACCOUNT_UUID, "#sort", KEY_DEVICE_ID_KEY_ID))
|
||||
.withValueMap(Map.of(":uuid", getPartitionKey(account.getUuid()),
|
||||
":sortprefix", getSortKeyPrefix(deviceId)))
|
||||
.withProjectionExpression(KEY_DEVICE_ID_KEY_ID)
|
||||
.withConsistentRead(true);
|
||||
private Map<String, AttributeValue> getItemFromPreKey(final UUID accountUuid, final long deviceId, final PreKey preKey) {
|
||||
return Map.of(
|
||||
KEY_ACCOUNT_UUID, getPartitionKey(accountUuid),
|
||||
KEY_DEVICE_ID_KEY_ID, getSortKey(deviceId, preKey.getKeyId()),
|
||||
KEY_PUBLIC_KEY, AttributeValues.fromString(preKey.getPublicKey()));
|
||||
}
|
||||
|
||||
deleteItemsForAccountMatchingQuery(account, querySpec);
|
||||
});
|
||||
}
|
||||
|
||||
private void deleteItemsForAccountMatchingQuery(final Account account, final QuerySpec querySpec) {
|
||||
final byte[] partitionKey = getPartitionKey(account.getUuid());
|
||||
|
||||
writeInBatches(table.query(querySpec), batch -> {
|
||||
final TableWriteItems writeItems = new TableWriteItems(table.getTableName());
|
||||
|
||||
for (final Item item : batch) {
|
||||
writeItems.addPrimaryKeyToDelete(new PrimaryKey(KEY_ACCOUNT_UUID, partitionKey, KEY_DEVICE_ID_KEY_ID, item.getBinary(KEY_DEVICE_ID_KEY_ID)));
|
||||
}
|
||||
|
||||
executeTableWriteItemsUntilComplete(writeItems);
|
||||
});
|
||||
}
|
||||
|
||||
private static byte[] getPartitionKey(final UUID accountUuid) {
|
||||
return UUIDUtil.toBytes(accountUuid);
|
||||
}
|
||||
|
||||
private static byte[] getSortKey(final long deviceId, final long keyId) {
|
||||
final ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]);
|
||||
byteBuffer.putLong(deviceId);
|
||||
byteBuffer.putLong(keyId);
|
||||
return byteBuffer.array();
|
||||
}
|
||||
|
||||
private static byte[] getSortKeyPrefix(final long deviceId) {
|
||||
final ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[8]);
|
||||
byteBuffer.putLong(deviceId);
|
||||
return byteBuffer.array();
|
||||
}
|
||||
|
||||
private Item getItemFromPreKey(final UUID accountUuid, final long deviceId, final PreKey preKey) {
|
||||
return new Item().withBinary(KEY_ACCOUNT_UUID, getPartitionKey(accountUuid))
|
||||
.withBinary(KEY_DEVICE_ID_KEY_ID, getSortKey(deviceId, preKey.getKeyId()))
|
||||
.withString(KEY_PUBLIC_KEY, preKey.getPublicKey());
|
||||
}
|
||||
|
||||
private PreKey getPreKeyFromItem(final Item item) {
|
||||
final long keyId = ByteBuffer.wrap(item.getBinary(KEY_DEVICE_ID_KEY_ID)).getLong(8);
|
||||
return new PreKey(keyId, item.getString(KEY_PUBLIC_KEY));
|
||||
}
|
||||
private PreKey getPreKeyFromItem(Map<String, AttributeValue> item) {
|
||||
final long keyId = item.get(KEY_DEVICE_ID_KEY_ID).b().asByteBuffer().getLong(8);
|
||||
return new PreKey(keyId, item.get(KEY_PUBLIC_KEY).s());
|
||||
}
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Duration;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
public abstract class ManagedPeriodicWork implements Managed {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
|
||||
private static final String FUTURE_DONE_GAUGE_NAME = "futureDone";
|
||||
|
||||
private final ManagedPeriodicWorkLock lock;
|
||||
private final Duration workerTtl;
|
||||
private final Duration runInterval;
|
||||
private final String workerId;
|
||||
private final ScheduledExecutorService executorService;
|
||||
|
||||
private Duration sleepDurationAfterUnexpectedException = Duration.ofSeconds(10);
|
||||
|
||||
|
||||
@Nullable
|
||||
private ScheduledFuture<?> scheduledFuture;
|
||||
private AtomicReference<CompletableFuture<Void>> activeExecutionFuture = new AtomicReference<>(CompletableFuture.completedFuture(null));
|
||||
|
||||
public ManagedPeriodicWork(final ManagedPeriodicWorkLock lock, final Duration workerTtl, final Duration runInterval, final ScheduledExecutorService scheduledExecutorService) {
|
||||
this.lock = lock;
|
||||
this.workerTtl = workerTtl;
|
||||
this.runInterval = runInterval;
|
||||
this.workerId = UUID.randomUUID().toString();
|
||||
this.executorService = scheduledExecutorService;
|
||||
}
|
||||
|
||||
abstract protected void doPeriodicWork() throws Exception;
|
||||
|
||||
@Override
|
||||
public synchronized void start() throws Exception {
|
||||
|
||||
if (scheduledFuture != null) {
|
||||
return;
|
||||
}
|
||||
|
||||
scheduledFuture = executorService.scheduleAtFixedRate(() -> {
|
||||
try {
|
||||
execute();
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Error in execution", e);
|
||||
|
||||
// wait a bit, in case the error is caused by external instability
|
||||
Util.sleep(sleepDurationAfterUnexpectedException.toMillis());
|
||||
}
|
||||
}, 0, runInterval.getSeconds(), TimeUnit.SECONDS);
|
||||
|
||||
Metrics.gauge(name(getClass(), FUTURE_DONE_GAUGE_NAME), scheduledFuture, future -> future.isDone() ? 1 : 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void stop() throws Exception {
|
||||
|
||||
if (scheduledFuture != null) {
|
||||
|
||||
scheduledFuture.cancel(false);
|
||||
|
||||
try {
|
||||
activeExecutionFuture.get().join();
|
||||
} catch (final Exception e) {
|
||||
logger.warn("error while awaiting final execution", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void setSleepDurationAfterUnexpectedException(final Duration sleepDurationAfterUnexpectedException) {
|
||||
this.sleepDurationAfterUnexpectedException = sleepDurationAfterUnexpectedException;
|
||||
}
|
||||
|
||||
private void execute() {
|
||||
|
||||
if (lock.claimActiveWork(workerId, workerTtl)) {
|
||||
try {
|
||||
|
||||
activeExecutionFuture.set(new CompletableFuture<>());
|
||||
|
||||
logger.info("Starting execution");
|
||||
doPeriodicWork();
|
||||
logger.info("Execution complete");
|
||||
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Periodic work failed", e);
|
||||
|
||||
// wait a bit, in case the error is caused by external instability
|
||||
Util.sleep(sleepDurationAfterUnexpectedException.toMillis());
|
||||
|
||||
} finally {
|
||||
try {
|
||||
lock.releaseActiveWork(workerId);
|
||||
} finally {
|
||||
activeExecutionFuture.get().complete(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import io.lettuce.core.ScriptOutputType;
|
||||
import io.lettuce.core.SetArgs;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
|
||||
public class ManagedPeriodicWorkLock {
|
||||
|
||||
private final String activeWorkerKey;
|
||||
|
||||
private final FaultTolerantRedisCluster cacheCluster;
|
||||
private final ClusterLuaScript unlockClusterScript;
|
||||
|
||||
public ManagedPeriodicWorkLock(final String activeWorkerKey, final FaultTolerantRedisCluster cacheCluster) throws IOException {
|
||||
this.activeWorkerKey = activeWorkerKey;
|
||||
this.cacheCluster = cacheCluster;
|
||||
this.unlockClusterScript = ClusterLuaScript.fromResource(cacheCluster, "lua/periodic_worker/unlock.lua", ScriptOutputType.INTEGER);
|
||||
}
|
||||
|
||||
public boolean claimActiveWork(String workerId, Duration ttl) {
|
||||
return "OK".equals(cacheCluster.withCluster(connection -> connection.sync().set(activeWorkerKey, workerId, SetArgs.Builder.nx().px(ttl.toMillis()))));
|
||||
}
|
||||
|
||||
public void releaseActiveWork(String workerId) {
|
||||
unlockClusterScript.execute(List.of(activeWorkerKey), List.of(workerId));
|
||||
}
|
||||
}
|
||||
+144
-112
@@ -8,17 +8,7 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
import static io.micrometer.core.instrument.Metrics.timer;
|
||||
|
||||
import com.amazonaws.services.dynamodbv2.document.DeleteItemOutcome;
|
||||
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.document.Index;
|
||||
import com.amazonaws.services.dynamodbv2.document.Item;
|
||||
import com.amazonaws.services.dynamodbv2.document.PrimaryKey;
|
||||
import com.amazonaws.services.dynamodbv2.document.Table;
|
||||
import com.amazonaws.services.dynamodbv2.document.TableWriteItems;
|
||||
import com.amazonaws.services.dynamodbv2.document.api.QueryApi;
|
||||
import com.amazonaws.services.dynamodbv2.document.spec.DeleteItemSpec;
|
||||
import com.amazonaws.services.dynamodbv2.document.spec.QuerySpec;
|
||||
import com.amazonaws.services.dynamodbv2.model.ReturnValue;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.time.Duration;
|
||||
@@ -27,11 +17,22 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.Nonnull;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.entities.OutgoingMessageEntity;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteItemResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.PutRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.WriteRequest;
|
||||
|
||||
public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
|
||||
@@ -60,7 +61,7 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
private final String tableName;
|
||||
private final Duration timeToLive;
|
||||
|
||||
public MessagesDynamoDb(DynamoDB dynamoDb, String tableName, Duration timeToLive) {
|
||||
public MessagesDynamoDb(DynamoDbClient dynamoDb, String tableName, Duration timeToLive) {
|
||||
super(dynamoDb);
|
||||
|
||||
this.tableName = tableName;
|
||||
@@ -76,54 +77,61 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
throw new IllegalArgumentException("Maximum batch size of " + DYNAMO_DB_MAX_BATCH_SIZE + " execeeded with " + messages.size() + " messages");
|
||||
}
|
||||
|
||||
final byte[] partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
TableWriteItems items = new TableWriteItems(tableName);
|
||||
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
List<WriteRequest> writeItems = new ArrayList<>();
|
||||
for (MessageProtos.Envelope message : messages) {
|
||||
final UUID messageUuid = UUID.fromString(message.getServerGuid());
|
||||
final Item item = new Item().withBinary(KEY_PARTITION, partitionKey)
|
||||
.withBinary(KEY_SORT, convertSortKey(destinationDeviceId, message.getServerTimestamp(), messageUuid))
|
||||
.withBinary(LOCAL_INDEX_MESSAGE_UUID_KEY_SORT, convertLocalIndexMessageUuidSortKey(messageUuid))
|
||||
.withInt(KEY_TYPE, message.getType().getNumber())
|
||||
.withLong(KEY_TIMESTAMP, message.getTimestamp())
|
||||
.withLong(KEY_TTL, getTtlForMessage(message));
|
||||
final ImmutableMap.Builder<String, AttributeValue> item = ImmutableMap.<String, AttributeValue>builder()
|
||||
.put(KEY_PARTITION, partitionKey)
|
||||
.put(KEY_SORT, convertSortKey(destinationDeviceId, message.getServerTimestamp(), messageUuid))
|
||||
.put(LOCAL_INDEX_MESSAGE_UUID_KEY_SORT, convertLocalIndexMessageUuidSortKey(messageUuid))
|
||||
.put(KEY_TYPE, AttributeValues.fromInt(message.getType().getNumber()))
|
||||
.put(KEY_TIMESTAMP, AttributeValues.fromLong(message.getTimestamp()))
|
||||
.put(KEY_TTL, AttributeValues.fromLong(getTtlForMessage(message)));
|
||||
if (message.hasRelay() && message.getRelay().length() > 0) {
|
||||
item.withString(KEY_RELAY, message.getRelay());
|
||||
item.put(KEY_RELAY, AttributeValues.fromString(message.getRelay()));
|
||||
}
|
||||
if (message.hasSource()) {
|
||||
item.withString(KEY_SOURCE, message.getSource());
|
||||
item.put(KEY_SOURCE, AttributeValues.fromString(message.getSource()));
|
||||
}
|
||||
if (message.hasSourceUuid()) {
|
||||
item.withBinary(KEY_SOURCE_UUID, UUIDUtil.toBytes(UUID.fromString(message.getSourceUuid())));
|
||||
item.put(KEY_SOURCE_UUID, AttributeValues.fromUUID(UUID.fromString(message.getSourceUuid())));
|
||||
}
|
||||
if (message.hasSourceDevice()) {
|
||||
item.withInt(KEY_SOURCE_DEVICE, message.getSourceDevice());
|
||||
item.put(KEY_SOURCE_DEVICE, AttributeValues.fromInt(message.getSourceDevice()));
|
||||
}
|
||||
if (message.hasLegacyMessage()) {
|
||||
item.withBinary(KEY_MESSAGE, message.getLegacyMessage().toByteArray());
|
||||
item.put(KEY_MESSAGE, AttributeValues.fromByteArray(message.getLegacyMessage().toByteArray()));
|
||||
}
|
||||
if (message.hasContent()) {
|
||||
item.withBinary(KEY_CONTENT, message.getContent().toByteArray());
|
||||
item.put(KEY_CONTENT, AttributeValues.fromByteArray(message.getContent().toByteArray()));
|
||||
}
|
||||
items.addItemToPut(item);
|
||||
writeItems.add(WriteRequest.builder().putRequest(PutRequest.builder()
|
||||
.item(item.build())
|
||||
.build()).build());
|
||||
}
|
||||
|
||||
executeTableWriteItemsUntilComplete(items);
|
||||
executeTableWriteItemsUntilComplete(Map.of(tableName, writeItems));
|
||||
}
|
||||
|
||||
public List<OutgoingMessageEntity> load(final UUID destinationAccountUuid, final long destinationDeviceId, final int requestedNumberOfMessagesToFetch) {
|
||||
return loadTimer.record(() -> {
|
||||
final int numberOfMessagesToFetch = Math.min(requestedNumberOfMessagesToFetch, RESULT_SET_CHUNK_SIZE);
|
||||
final byte[] partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
final QuerySpec querySpec = new QuerySpec().withConsistentRead(true)
|
||||
.withKeyConditionExpression("#part = :part AND begins_with ( #sort , :sortprefix )")
|
||||
.withNameMap(Map.of("#part", KEY_PARTITION,
|
||||
"#sort", KEY_SORT))
|
||||
.withValueMap(Map.of(":part", partitionKey,
|
||||
":sortprefix", convertDestinationDeviceIdToSortKeyPrefix(destinationDeviceId)))
|
||||
.withMaxResultSize(numberOfMessagesToFetch);
|
||||
final Table table = getDynamoDb().getTable(tableName);
|
||||
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
final QueryRequest queryRequest = QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.consistentRead(true)
|
||||
.keyConditionExpression("#part = :part AND begins_with ( #sort , :sortprefix )")
|
||||
.expressionAttributeNames(Map.of(
|
||||
"#part", KEY_PARTITION,
|
||||
"#sort", KEY_SORT))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":part", partitionKey,
|
||||
":sortprefix", convertDestinationDeviceIdToSortKeyPrefix(destinationDeviceId)))
|
||||
.limit(numberOfMessagesToFetch)
|
||||
.build();
|
||||
List<OutgoingMessageEntity> messageEntities = new ArrayList<>(numberOfMessagesToFetch);
|
||||
for (Item message : table.query(querySpec)) {
|
||||
for (Map<String, AttributeValue> message : db().query(queryRequest).items()) {
|
||||
messageEntities.add(convertItemToOutgoingMessageEntity(message));
|
||||
}
|
||||
return messageEntities;
|
||||
@@ -136,53 +144,63 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
throw new IllegalArgumentException("must specify a source");
|
||||
}
|
||||
|
||||
final byte[] partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
final QuerySpec querySpec = new QuerySpec().withProjectionExpression(KEY_SORT)
|
||||
.withConsistentRead(true)
|
||||
.withKeyConditionExpression("#part = :part AND begins_with ( #sort , :sortprefix )")
|
||||
.withFilterExpression("#source = :source AND #timestamp = :timestamp")
|
||||
.withNameMap(Map.of("#part", KEY_PARTITION,
|
||||
"#sort", KEY_SORT,
|
||||
"#source", KEY_SOURCE,
|
||||
"#timestamp", KEY_TIMESTAMP))
|
||||
.withValueMap(Map.of(":part", partitionKey,
|
||||
":sortprefix", convertDestinationDeviceIdToSortKeyPrefix(destinationDeviceId),
|
||||
":source", source,
|
||||
":timestamp", timestamp));
|
||||
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
final QueryRequest queryRequest = QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.projectionExpression(KEY_SORT)
|
||||
.consistentRead(true)
|
||||
.keyConditionExpression("#part = :part AND begins_with ( #sort , :sortprefix )")
|
||||
.filterExpression("#source = :source AND #timestamp = :timestamp")
|
||||
.expressionAttributeNames(Map.of(
|
||||
"#part", KEY_PARTITION,
|
||||
"#sort", KEY_SORT,
|
||||
"#source", KEY_SOURCE,
|
||||
"#timestamp", KEY_TIMESTAMP))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":part", partitionKey,
|
||||
":sortprefix", convertDestinationDeviceIdToSortKeyPrefix(destinationDeviceId),
|
||||
":source", AttributeValues.fromString(source),
|
||||
":timestamp", AttributeValues.fromLong(timestamp)))
|
||||
.build();
|
||||
|
||||
final Table table = getDynamoDb().getTable(tableName);
|
||||
return deleteItemsMatchingQueryAndReturnFirstOneActuallyDeleted(table, partitionKey, querySpec, table);
|
||||
return deleteItemsMatchingQueryAndReturnFirstOneActuallyDeleted(partitionKey, queryRequest);
|
||||
});
|
||||
}
|
||||
|
||||
public Optional<OutgoingMessageEntity> deleteMessageByDestinationAndGuid(final UUID destinationAccountUuid, final long destinationDeviceId, final UUID messageUuid) {
|
||||
return deleteByGuid.record(() -> {
|
||||
final byte[] partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
final QuerySpec querySpec = new QuerySpec().withProjectionExpression(KEY_SORT)
|
||||
.withConsistentRead(true)
|
||||
.withKeyConditionExpression("#part = :part AND #uuid = :uuid")
|
||||
.withNameMap(Map.of("#part", KEY_PARTITION,
|
||||
"#uuid", LOCAL_INDEX_MESSAGE_UUID_KEY_SORT))
|
||||
.withValueMap(Map.of(":part", partitionKey,
|
||||
":uuid", convertLocalIndexMessageUuidSortKey(messageUuid)));
|
||||
final Table table = getDynamoDb().getTable(tableName);
|
||||
final Index index = table.getIndex(LOCAL_INDEX_MESSAGE_UUID_NAME);
|
||||
return deleteItemsMatchingQueryAndReturnFirstOneActuallyDeleted(table, partitionKey, querySpec, index);
|
||||
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
final QueryRequest queryRequest = QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.indexName(LOCAL_INDEX_MESSAGE_UUID_NAME)
|
||||
.projectionExpression(KEY_SORT)
|
||||
.consistentRead(true)
|
||||
.keyConditionExpression("#part = :part AND #uuid = :uuid")
|
||||
.expressionAttributeNames(Map.of(
|
||||
"#part", KEY_PARTITION,
|
||||
"#uuid", LOCAL_INDEX_MESSAGE_UUID_KEY_SORT))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":part", partitionKey,
|
||||
":uuid", convertLocalIndexMessageUuidSortKey(messageUuid)))
|
||||
.build();
|
||||
return deleteItemsMatchingQueryAndReturnFirstOneActuallyDeleted(partitionKey, queryRequest);
|
||||
});
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
private Optional<OutgoingMessageEntity> deleteItemsMatchingQueryAndReturnFirstOneActuallyDeleted(Table table, byte[] partitionKey, QuerySpec querySpec, QueryApi queryApi) {
|
||||
private Optional<OutgoingMessageEntity> deleteItemsMatchingQueryAndReturnFirstOneActuallyDeleted(AttributeValue partitionKey, QueryRequest queryRequest) {
|
||||
Optional<OutgoingMessageEntity> result = Optional.empty();
|
||||
for (Item item : queryApi.query(querySpec)) {
|
||||
final byte[] rangeKeyValue = item.getBinary(KEY_SORT);
|
||||
DeleteItemSpec deleteItemSpec = new DeleteItemSpec().withPrimaryKey(KEY_PARTITION, partitionKey, KEY_SORT, rangeKeyValue);
|
||||
for (Map<String, AttributeValue> item : db().query(queryRequest).items()) {
|
||||
final byte[] rangeKeyValue = item.get(KEY_SORT).b().asByteArray();
|
||||
DeleteItemRequest.Builder deleteItemRequest = DeleteItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(KEY_PARTITION, partitionKey, KEY_SORT, AttributeValues.fromByteArray(rangeKeyValue)));
|
||||
if (result.isEmpty()) {
|
||||
deleteItemSpec.withReturnValues(ReturnValue.ALL_OLD);
|
||||
deleteItemRequest.returnValues(ReturnValue.ALL_OLD);
|
||||
}
|
||||
final DeleteItemOutcome deleteItemOutcome = table.deleteItem(deleteItemSpec);
|
||||
if (deleteItemOutcome.getItem() != null && deleteItemOutcome.getItem().hasAttribute(KEY_PARTITION)) {
|
||||
result = Optional.of(convertItemToOutgoingMessageEntity(deleteItemOutcome.getItem()));
|
||||
final DeleteItemResponse deleteItemResponse = db().deleteItem(deleteItemRequest.build());
|
||||
if (deleteItemResponse.attributes() != null && deleteItemResponse.attributes().containsKey(KEY_PARTITION)) {
|
||||
result = Optional.of(convertItemToOutgoingMessageEntity(deleteItemResponse.attributes()));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
@@ -190,74 +208,88 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
|
||||
public void deleteAllMessagesForAccount(final UUID destinationAccountUuid) {
|
||||
deleteByAccount.record(() -> {
|
||||
final byte[] partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
final QuerySpec querySpec = new QuerySpec().withHashKey(KEY_PARTITION, partitionKey)
|
||||
.withProjectionExpression(KEY_SORT)
|
||||
.withConsistentRead(true);
|
||||
deleteRowsMatchingQuery(partitionKey, querySpec);
|
||||
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
final QueryRequest queryRequest = QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.projectionExpression(KEY_SORT)
|
||||
.consistentRead(true)
|
||||
.keyConditionExpression("#part = :part")
|
||||
.expressionAttributeNames(Map.of("#part", KEY_PARTITION))
|
||||
.expressionAttributeValues(Map.of(":part", partitionKey))
|
||||
.build();
|
||||
deleteRowsMatchingQuery(partitionKey, queryRequest);
|
||||
});
|
||||
}
|
||||
|
||||
public void deleteAllMessagesForDevice(final UUID destinationAccountUuid, final long destinationDeviceId) {
|
||||
deleteByDevice.record(() -> {
|
||||
final byte[] partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
final QuerySpec querySpec = new QuerySpec().withKeyConditionExpression("#part = :part AND begins_with ( #sort , :sortprefix )")
|
||||
.withNameMap(Map.of("#part", KEY_PARTITION,
|
||||
"#sort", KEY_SORT))
|
||||
.withValueMap(Map.of(":part", partitionKey,
|
||||
":sortprefix", convertDestinationDeviceIdToSortKeyPrefix(destinationDeviceId)))
|
||||
.withProjectionExpression(KEY_SORT)
|
||||
.withConsistentRead(true);
|
||||
deleteRowsMatchingQuery(partitionKey, querySpec);
|
||||
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
final QueryRequest queryRequest = QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.keyConditionExpression("#part = :part AND begins_with ( #sort , :sortprefix )")
|
||||
.expressionAttributeNames(Map.of(
|
||||
"#part", KEY_PARTITION,
|
||||
"#sort", KEY_SORT))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":part", partitionKey,
|
||||
":sortprefix", convertDestinationDeviceIdToSortKeyPrefix(destinationDeviceId)))
|
||||
.projectionExpression(KEY_SORT)
|
||||
.consistentRead(true)
|
||||
.build();
|
||||
deleteRowsMatchingQuery(partitionKey, queryRequest);
|
||||
});
|
||||
}
|
||||
|
||||
private OutgoingMessageEntity convertItemToOutgoingMessageEntity(Item message) {
|
||||
final SortKey sortKey = convertSortKey(message.getBinary(KEY_SORT));
|
||||
final UUID messageUuid = convertLocalIndexMessageUuidSortKey(message.getBinary(LOCAL_INDEX_MESSAGE_UUID_KEY_SORT));
|
||||
final int type = message.getInt(KEY_TYPE);
|
||||
final String relay = message.getString(KEY_RELAY);
|
||||
final long timestamp = message.getLong(KEY_TIMESTAMP);
|
||||
final String source = message.getString(KEY_SOURCE);
|
||||
final UUID sourceUuid = message.hasAttribute(KEY_SOURCE_UUID) ? convertUuidFromBytes(message.getBinary(KEY_SOURCE_UUID), "message source uuid") : null;
|
||||
final int sourceDevice = message.hasAttribute(KEY_SOURCE_DEVICE) ? message.getInt(KEY_SOURCE_DEVICE) : 0;
|
||||
final byte[] messageBytes = message.getBinary(KEY_MESSAGE);
|
||||
final byte[] content = message.getBinary(KEY_CONTENT);
|
||||
private OutgoingMessageEntity convertItemToOutgoingMessageEntity(Map<String, AttributeValue> message) {
|
||||
final SortKey sortKey = convertSortKey(message.get(KEY_SORT).b().asByteArray());
|
||||
final UUID messageUuid = convertLocalIndexMessageUuidSortKey(message.get(LOCAL_INDEX_MESSAGE_UUID_KEY_SORT).b().asByteArray());
|
||||
final int type = AttributeValues.getInt(message, KEY_TYPE, 0);
|
||||
final String relay = AttributeValues.getString(message, KEY_RELAY, null);
|
||||
final long timestamp = AttributeValues.getLong(message, KEY_TIMESTAMP, 0L);
|
||||
final String source = AttributeValues.getString(message, KEY_SOURCE, null);
|
||||
final UUID sourceUuid = AttributeValues.getUUID(message, KEY_SOURCE_UUID, null);
|
||||
final int sourceDevice = AttributeValues.getInt(message, KEY_SOURCE_DEVICE, 0);
|
||||
final byte[] messageBytes = AttributeValues.getByteArray(message, KEY_MESSAGE, null);
|
||||
final byte[] content = AttributeValues.getByteArray(message, KEY_CONTENT, null);
|
||||
return new OutgoingMessageEntity(-1L, false, messageUuid, type, relay, timestamp, source, sourceUuid, sourceDevice, messageBytes, content, sortKey.getServerTimestamp());
|
||||
}
|
||||
|
||||
private void deleteRowsMatchingQuery(byte[] partitionKey, QuerySpec querySpec) {
|
||||
final Table table = getDynamoDb().getTable(tableName);
|
||||
writeInBatches(table.query(querySpec), (itemBatch) -> deleteItems(partitionKey, itemBatch));
|
||||
private void deleteRowsMatchingQuery(AttributeValue partitionKey, QueryRequest querySpec) {
|
||||
writeInBatches(db().query(querySpec).items(), (itemBatch) -> deleteItems(partitionKey, itemBatch));
|
||||
}
|
||||
|
||||
private void deleteItems(byte[] partitionKey, List<Item> items) {
|
||||
final TableWriteItems tableWriteItems = new TableWriteItems(tableName);
|
||||
items.stream().map(item -> new PrimaryKey(KEY_PARTITION, partitionKey, KEY_SORT, item.getBinary(KEY_SORT))).forEach(tableWriteItems::addPrimaryKeyToDelete);
|
||||
executeTableWriteItemsUntilComplete(tableWriteItems);
|
||||
private void deleteItems(AttributeValue partitionKey, List<Map<String, AttributeValue>> items) {
|
||||
List<WriteRequest> deletes = items.stream()
|
||||
.map(item -> WriteRequest.builder()
|
||||
.deleteRequest(DeleteRequest.builder().key(Map.of(
|
||||
KEY_PARTITION, partitionKey,
|
||||
KEY_SORT, item.get(KEY_SORT))).build())
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
executeTableWriteItemsUntilComplete(Map.of(tableName, deletes));
|
||||
}
|
||||
|
||||
private long getTtlForMessage(MessageProtos.Envelope message) {
|
||||
return message.getServerTimestamp() / 1000 + timeToLive.getSeconds();
|
||||
}
|
||||
|
||||
private static byte[] convertPartitionKey(final UUID destinationAccountUuid) {
|
||||
return UUIDUtil.toBytes(destinationAccountUuid);
|
||||
private static AttributeValue convertPartitionKey(final UUID destinationAccountUuid) {
|
||||
return AttributeValues.fromUUID(destinationAccountUuid);
|
||||
}
|
||||
|
||||
private static byte[] convertSortKey(final long destinationDeviceId, final long serverTimestamp, final UUID messageUuid) {
|
||||
private static AttributeValue convertSortKey(final long destinationDeviceId, final long serverTimestamp, final UUID messageUuid) {
|
||||
ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[32]);
|
||||
byteBuffer.putLong(destinationDeviceId);
|
||||
byteBuffer.putLong(serverTimestamp);
|
||||
byteBuffer.putLong(messageUuid.getMostSignificantBits());
|
||||
byteBuffer.putLong(messageUuid.getLeastSignificantBits());
|
||||
return byteBuffer.array();
|
||||
return AttributeValues.fromByteBuffer(byteBuffer.flip());
|
||||
}
|
||||
|
||||
private static byte[] convertDestinationDeviceIdToSortKeyPrefix(final long destinationDeviceId) {
|
||||
private static AttributeValue convertDestinationDeviceIdToSortKeyPrefix(final long destinationDeviceId) {
|
||||
ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[8]);
|
||||
byteBuffer.putLong(destinationDeviceId);
|
||||
return byteBuffer.array();
|
||||
return AttributeValues.fromByteBuffer(byteBuffer.flip());
|
||||
}
|
||||
|
||||
private static SortKey convertSortKey(final byte[] bytes) {
|
||||
@@ -273,8 +305,8 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
return new SortKey(destinationDeviceId, serverTimestamp, new UUID(mostSigBits, leastSigBits));
|
||||
}
|
||||
|
||||
private static byte[] convertLocalIndexMessageUuidSortKey(final UUID messageUuid) {
|
||||
return UUIDUtil.toBytes(messageUuid);
|
||||
private static AttributeValue convertLocalIndexMessageUuidSortKey(final UUID messageUuid) {
|
||||
return AttributeValues.fromUUID(messageUuid);
|
||||
}
|
||||
|
||||
private static UUID convertLocalIndexMessageUuidSortKey(final byte[] bytes) {
|
||||
|
||||
+33
-26
@@ -1,42 +1,52 @@
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.document.Item;
|
||||
import com.amazonaws.services.dynamodbv2.document.PrimaryKey;
|
||||
import com.amazonaws.services.dynamodbv2.document.Table;
|
||||
import com.amazonaws.services.dynamodbv2.document.TableWriteItems;
|
||||
import com.amazonaws.services.dynamodbv2.document.spec.ScanSpec;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import java.util.stream.Collectors;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ScanRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ScanResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.WriteRequest;
|
||||
|
||||
public class MigrationDeletedAccounts extends AbstractDynamoDbStore {
|
||||
|
||||
private final Table table;
|
||||
private final String tableName;
|
||||
|
||||
static final String KEY_UUID = "U";
|
||||
|
||||
public MigrationDeletedAccounts(DynamoDB dynamoDb, String tableName) {
|
||||
public MigrationDeletedAccounts(DynamoDbClient dynamoDb, String tableName) {
|
||||
super(dynamoDb);
|
||||
|
||||
table = dynamoDb.getTable(tableName);
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
public void put(UUID uuid) {
|
||||
table.putItem(new Item()
|
||||
.withPrimaryKey(primaryKey(uuid)));
|
||||
db().putItem(PutItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.item(primaryKey(uuid))
|
||||
.build());
|
||||
}
|
||||
|
||||
public List<UUID> getRecentlyDeletedUuids() {
|
||||
|
||||
final List<UUID> uuids = new ArrayList<>();
|
||||
Optional<ScanResponse> firstPage = db().scanPaginator(ScanRequest.builder()
|
||||
.tableName(tableName)
|
||||
.build()).stream().findAny(); // get the first available response
|
||||
|
||||
for (Item item : table.scan(new ScanSpec()).firstPage()) {
|
||||
// only process one page each time. If we have a significant backlog at the end of the migration
|
||||
// we can handle it separately
|
||||
uuids.add(UUIDUtil.fromByteBuffer(item.getByteBuffer(KEY_UUID)));
|
||||
if (firstPage.isPresent()) {
|
||||
for (Map<String, AttributeValue> item : firstPage.get().items()) {
|
||||
// only process one page each time. If we have a significant backlog at the end of the migration
|
||||
// we can handle it separately
|
||||
uuids.add(AttributeValues.getUUID(item, KEY_UUID, null));
|
||||
}
|
||||
}
|
||||
|
||||
return uuids;
|
||||
@@ -45,20 +55,17 @@ public class MigrationDeletedAccounts extends AbstractDynamoDbStore {
|
||||
public void delete(List<UUID> uuids) {
|
||||
|
||||
writeInBatches(uuids, (batch) -> {
|
||||
List<WriteRequest> deletes = batch.stream().map((uuid) -> WriteRequest.builder().deleteRequest(DeleteRequest.builder()
|
||||
.key(primaryKey(uuid))
|
||||
.build()).build()).collect(Collectors.toList());
|
||||
|
||||
final TableWriteItems deleteItems = new TableWriteItems(table.getTableName());
|
||||
|
||||
for (UUID uuid : batch) {
|
||||
deleteItems.addPrimaryKeyToDelete(primaryKey(uuid));
|
||||
}
|
||||
|
||||
executeTableWriteItemsUntilComplete(deleteItems);
|
||||
executeTableWriteItemsUntilComplete(Map.of(tableName, deletes));
|
||||
});
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public static PrimaryKey primaryKey(UUID uuid) {
|
||||
return new PrimaryKey(KEY_UUID, UUIDUtil.toBytes(uuid));
|
||||
public static Map<String, AttributeValue> primaryKey(UUID uuid) {
|
||||
return Map.of(KEY_UUID, AttributeValues.fromUUID(uuid));
|
||||
}
|
||||
|
||||
}
|
||||
+34
-18
@@ -1,43 +1,47 @@
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.document.Item;
|
||||
import com.amazonaws.services.dynamodbv2.document.Page;
|
||||
import com.amazonaws.services.dynamodbv2.document.PrimaryKey;
|
||||
import com.amazonaws.services.dynamodbv2.document.ScanOutcome;
|
||||
import com.amazonaws.services.dynamodbv2.document.Table;
|
||||
import com.amazonaws.services.dynamodbv2.document.spec.ScanSpec;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import java.util.stream.Collectors;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ScanRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ScanResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.WriteRequest;
|
||||
|
||||
public class MigrationRetryAccounts extends AbstractDynamoDbStore {
|
||||
|
||||
private final Table table;
|
||||
private final String tableName;
|
||||
|
||||
static final String KEY_UUID = "U";
|
||||
|
||||
public MigrationRetryAccounts(DynamoDB dynamoDb, String tableName) {
|
||||
public MigrationRetryAccounts(DynamoDbClient dynamoDb, String tableName) {
|
||||
super(dynamoDb);
|
||||
|
||||
table = dynamoDb.getTable(tableName);
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
public void put(UUID uuid) {
|
||||
table.putItem(new Item()
|
||||
.withPrimaryKey(primaryKey(uuid)));
|
||||
db().putItem(PutItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.item(primaryKey(uuid))
|
||||
.build());
|
||||
}
|
||||
|
||||
public List<UUID> getUuids(int max) {
|
||||
|
||||
final List<UUID> uuids = new ArrayList<>();
|
||||
|
||||
for (Page<Item, ScanOutcome> page : table.scan(new ScanSpec()).pages()) {
|
||||
for (ScanResponse response : db().scanPaginator(ScanRequest.builder().tableName(tableName).build())) {
|
||||
|
||||
for (Item item : page) {
|
||||
uuids.add(UUIDUtil.fromByteBuffer(item.getByteBuffer(KEY_UUID)));
|
||||
for (Map<String, AttributeValue> item : response.items()) {
|
||||
uuids.add(AttributeValues.getUUID(item, KEY_UUID, null));
|
||||
|
||||
if (uuids.size() >= max) {
|
||||
break;
|
||||
@@ -53,8 +57,20 @@ public class MigrationRetryAccounts extends AbstractDynamoDbStore {
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public static PrimaryKey primaryKey(UUID uuid) {
|
||||
return new PrimaryKey(KEY_UUID, UUIDUtil.toBytes(uuid));
|
||||
public static Map<String, AttributeValue> primaryKey(UUID uuid) {
|
||||
return Map.of(KEY_UUID, AttributeValues.fromUUID(uuid));
|
||||
}
|
||||
|
||||
public void delete(final List<UUID> uuidsToDelete) {
|
||||
|
||||
writeInBatches(uuidsToDelete, (uuids -> {
|
||||
|
||||
final List<WriteRequest> deletes = uuids.stream()
|
||||
.map(uuid -> WriteRequest.builder().deleteRequest(
|
||||
DeleteRequest.builder().key(Map.of(KEY_UUID, AttributeValues.fromUUID(uuid))).build()).build())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
executeTableWriteItemsUntilComplete(Map.of(tableName, deletes));
|
||||
}));
|
||||
}
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
|
||||
public class MigrationRetryAccountsTableCrawler extends ManagedPeriodicWork {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MigrationRetryAccountsTableCrawler.class);
|
||||
|
||||
private static final Duration WORKER_TTL = Duration.ofMinutes(2);
|
||||
private static final Duration RUN_INTERVAL = Duration.ofMinutes(15);
|
||||
private static final String ACTIVE_WORKER_KEY = "migration_retry_accounts_crawler_cache_active_worker";
|
||||
|
||||
private static final int MAX_BATCH_SIZE = 5_000;
|
||||
|
||||
private static final Counter MIGRATED_COUNTER = Metrics.counter(name(MigrationRetryAccountsTableCrawler.class, "migrated"));
|
||||
private static final Counter ERROR_COUNTER = Metrics.counter(name(MigrationRetryAccountsTableCrawler.class, "error"));
|
||||
private static final Counter TOTAL_COUNTER = Metrics.counter(name(MigrationRetryAccountsTableCrawler.class, "total"));
|
||||
|
||||
private final MigrationRetryAccounts retryAccounts;
|
||||
private final AccountsManager accountsManager;
|
||||
private final AccountsDynamoDb accountsDynamoDb;
|
||||
|
||||
public MigrationRetryAccountsTableCrawler(
|
||||
final MigrationRetryAccounts retryAccounts,
|
||||
final AccountsManager accountsManager,
|
||||
final AccountsDynamoDb accountsDynamoDb,
|
||||
final FaultTolerantRedisCluster cluster,
|
||||
final ScheduledExecutorService executorService) throws IOException {
|
||||
|
||||
super(new ManagedPeriodicWorkLock(ACTIVE_WORKER_KEY, cluster), WORKER_TTL, RUN_INTERVAL, executorService);
|
||||
|
||||
this.retryAccounts = retryAccounts;
|
||||
this.accountsManager = accountsManager;
|
||||
this.accountsDynamoDb = accountsDynamoDb;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doPeriodicWork() {
|
||||
|
||||
final List<UUID> uuids = this.retryAccounts.getUuids(MAX_BATCH_SIZE);
|
||||
|
||||
final List<UUID> processedUuids = new ArrayList<>(uuids.size());
|
||||
|
||||
try {
|
||||
for (UUID uuid : uuids) {
|
||||
|
||||
try {
|
||||
final Optional<Account> maybeDynamoAccount = accountsDynamoDb.get(uuid);
|
||||
|
||||
if (maybeDynamoAccount.isEmpty()) {
|
||||
accountsManager.get(uuid).ifPresent(account -> {
|
||||
accountsDynamoDb.migrate(account);
|
||||
MIGRATED_COUNTER.increment();
|
||||
});
|
||||
}
|
||||
|
||||
processedUuids.add(uuid);
|
||||
|
||||
TOTAL_COUNTER.increment();
|
||||
|
||||
} catch (final Exception e) {
|
||||
ERROR_COUNTER.increment();
|
||||
logger.warn("Failed to migrate account");
|
||||
}
|
||||
|
||||
}
|
||||
} finally {
|
||||
this.retryAccounts.delete(processedUuids);
|
||||
}
|
||||
}
|
||||
}
|
||||
+10
-12
@@ -15,7 +15,7 @@ import org.whispersystems.textsecuregcm.auth.StoredVerificationCode;
|
||||
import org.whispersystems.textsecuregcm.storage.mappers.StoredVerificationCodeRowMapper;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
|
||||
public class PendingAccounts {
|
||||
public class PendingAccounts implements VerificationCodeStore {
|
||||
|
||||
private final MetricRegistry metricRegistry = SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME);
|
||||
private final Timer insertTimer = metricRegistry.timer(name(PendingAccounts.class, "insert" ));
|
||||
@@ -30,29 +30,26 @@ public class PendingAccounts {
|
||||
this.database.getDatabase().registerRowMapper(new StoredVerificationCodeRowMapper());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public void insert (String number, String verificationCode, long timestamp, String pushCode) {
|
||||
insert(number, verificationCode, timestamp, pushCode, null);
|
||||
}
|
||||
|
||||
public void insert(String number, String verificationCode, long timestamp, String pushCode, String twilioVerificationSid) {
|
||||
@Override
|
||||
public void insert(final String number, final StoredVerificationCode storedVerificationCode) {
|
||||
database.use(jdbi -> jdbi.useHandle(handle -> {
|
||||
try (Timer.Context ignored = insertTimer.time()) {
|
||||
handle.createUpdate("INSERT INTO pending_accounts (number, verification_code, timestamp, push_code, twilio_verification_sid) " +
|
||||
"VALUES (:number, :verification_code, :timestamp, :push_code, :twilio_verification_sid) " +
|
||||
"ON CONFLICT(number) DO UPDATE " +
|
||||
"SET verification_code = EXCLUDED.verification_code, timestamp = EXCLUDED.timestamp, push_code = EXCLUDED.push_code, twilio_verification_sid = EXCLUDED.twilio_verification_sid")
|
||||
.bind("verification_code", verificationCode)
|
||||
.bind("timestamp", timestamp)
|
||||
.bind("verification_code", storedVerificationCode.getCode())
|
||||
.bind("timestamp", storedVerificationCode.getTimestamp())
|
||||
.bind("number", number)
|
||||
.bind("push_code", pushCode)
|
||||
.bind("twilio_verification_sid", twilioVerificationSid)
|
||||
.bind("push_code", storedVerificationCode.getPushCode())
|
||||
.bind("twilio_verification_sid", storedVerificationCode.getTwilioVerificationSid().orElse(null))
|
||||
.execute();
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
public Optional<StoredVerificationCode> getCodeForNumber(String number) {
|
||||
@Override
|
||||
public Optional<StoredVerificationCode> findForNumber(String number) {
|
||||
return database.with(jdbi ->jdbi.withHandle(handle -> {
|
||||
try (Timer.Context ignored = getCodeForNumberTimer.time()) {
|
||||
return handle.createQuery("SELECT verification_code, timestamp, push_code, twilio_verification_sid FROM pending_accounts WHERE number = :number")
|
||||
@@ -63,6 +60,7 @@ public class PendingAccounts {
|
||||
}));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove(String number) {
|
||||
database.use(jdbi-> jdbi.useHandle(handle -> {
|
||||
try (Timer.Context ignored = removeTimer.time()) {
|
||||
|
||||
+29
-56
@@ -4,79 +4,52 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.StoredVerificationCode;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Optional;
|
||||
import org.whispersystems.textsecuregcm.auth.StoredVerificationCode;
|
||||
|
||||
public class PendingAccountsManager {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(PendingAccountsManager.class);
|
||||
private final PendingAccounts pendingAccounts;
|
||||
private final VerificationCodeStoreDynamoDb pendingAccountsDynamoDb;
|
||||
private final DynamicConfigurationManager dynamicConfigurationManager;
|
||||
|
||||
private static final String CACHE_PREFIX = "pending_account2::";
|
||||
public PendingAccountsManager(
|
||||
final PendingAccounts pendingAccounts,
|
||||
final VerificationCodeStoreDynamoDb pendingAccountsDynamoDb,
|
||||
final DynamicConfigurationManager dynamicConfigurationManager) {
|
||||
|
||||
private final PendingAccounts pendingAccounts;
|
||||
private final FaultTolerantRedisCluster cacheCluster;
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
public PendingAccountsManager(PendingAccounts pendingAccounts, FaultTolerantRedisCluster cacheCluster)
|
||||
{
|
||||
this.pendingAccounts = pendingAccounts;
|
||||
this.cacheCluster = cacheCluster;
|
||||
this.mapper = SystemMapper.getMapper();
|
||||
this.pendingAccountsDynamoDb = pendingAccountsDynamoDb;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
}
|
||||
|
||||
public void store(String number, StoredVerificationCode code) {
|
||||
memcacheSet(number, code);
|
||||
pendingAccounts.insert(number, code.getCode(), code.getTimestamp(), code.getPushCode(),
|
||||
code.getTwilioVerificationSid().orElse(null));
|
||||
switch (dynamicConfigurationManager.getConfiguration().getPendingAccountsMigrationConfiguration().getWriteDestination()) {
|
||||
|
||||
case POSTGRES:
|
||||
pendingAccounts.insert(number, code);
|
||||
break;
|
||||
|
||||
case DYNAMODB:
|
||||
pendingAccountsDynamoDb.insert(number, code);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public void remove(String number) {
|
||||
memcacheDelete(number);
|
||||
pendingAccounts.remove(number);
|
||||
pendingAccountsDynamoDb.remove(number);
|
||||
}
|
||||
|
||||
public Optional<StoredVerificationCode> getCodeForNumber(String number) {
|
||||
Optional<StoredVerificationCode> code = memcacheGet(number);
|
||||
final Optional<StoredVerificationCode> maybeCodeFromPostgres =
|
||||
dynamicConfigurationManager.getConfiguration().getPendingAccountsMigrationConfiguration().isReadPostgres()
|
||||
? pendingAccounts.findForNumber(number)
|
||||
: Optional.empty();
|
||||
|
||||
if (!code.isPresent()) {
|
||||
code = pendingAccounts.getCodeForNumber(number);
|
||||
code.ifPresent(storedVerificationCode -> memcacheSet(number, storedVerificationCode));
|
||||
}
|
||||
|
||||
return code;
|
||||
}
|
||||
|
||||
private void memcacheSet(String number, StoredVerificationCode code) {
|
||||
try {
|
||||
final String verificationCodeJson = mapper.writeValueAsString(code);
|
||||
|
||||
cacheCluster.useCluster(connection -> connection.sync().set(CACHE_PREFIX + number, verificationCodeJson));
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalArgumentException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<StoredVerificationCode> memcacheGet(String number) {
|
||||
try {
|
||||
final String json = cacheCluster.withCluster(connection -> connection.sync().get(CACHE_PREFIX + number));
|
||||
|
||||
if (json == null) return Optional.empty();
|
||||
else return Optional.of(mapper.readValue(json, StoredVerificationCode.class));
|
||||
} catch (IOException e) {
|
||||
logger.warn("Error deserializing value...", e);
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private void memcacheDelete(String number) {
|
||||
cacheCluster.useCluster(connection -> connection.sync().del(CACHE_PREFIX + number));
|
||||
return maybeCodeFromPostgres.or(
|
||||
() -> dynamicConfigurationManager.getConfiguration().getPendingAccountsMigrationConfiguration().isReadDynamoDb()
|
||||
? pendingAccountsDynamoDb.findForNumber(number)
|
||||
: Optional.empty());
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ import org.whispersystems.textsecuregcm.auth.StoredVerificationCode;
|
||||
import org.whispersystems.textsecuregcm.storage.mappers.StoredVerificationCodeRowMapper;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
|
||||
public class PendingDevices {
|
||||
public class PendingDevices implements VerificationCodeStore {
|
||||
|
||||
private final MetricRegistry metricRegistry = SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME);
|
||||
private final Timer insertTimer = metricRegistry.timer(name(PendingDevices.class, "insert" ));
|
||||
@@ -28,20 +28,22 @@ public class PendingDevices {
|
||||
this.database.getDatabase().registerRowMapper(new StoredVerificationCodeRowMapper());
|
||||
}
|
||||
|
||||
public void insert(String number, String verificationCode, long timestamp) {
|
||||
@Override
|
||||
public void insert(final String number, final StoredVerificationCode storedVerificationCode) {
|
||||
database.use(jdbi ->jdbi.useHandle(handle -> {
|
||||
try (Timer.Context timer = insertTimer.time()) {
|
||||
handle.createUpdate("WITH upsert AS (UPDATE pending_devices SET verification_code = :verification_code, timestamp = :timestamp WHERE number = :number RETURNING *) " +
|
||||
"INSERT INTO pending_devices (number, verification_code, timestamp) SELECT :number, :verification_code, :timestamp WHERE NOT EXISTS (SELECT * FROM upsert)")
|
||||
.bind("number", number)
|
||||
.bind("verification_code", verificationCode)
|
||||
.bind("timestamp", timestamp)
|
||||
.bind("verification_code", storedVerificationCode.getCode())
|
||||
.bind("timestamp", storedVerificationCode.getTimestamp())
|
||||
.execute();
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
public Optional<StoredVerificationCode> getCodeForNumber(String number) {
|
||||
@Override
|
||||
public Optional<StoredVerificationCode> findForNumber(String number) {
|
||||
return database.with(jdbi -> jdbi.withHandle(handle -> {
|
||||
try (Timer.Context timer = getCodeForNumberTimer.time()) {
|
||||
return handle.createQuery("SELECT verification_code, timestamp, NULL as push_code, NULL as twilio_verification_sid FROM pending_devices WHERE number = :number")
|
||||
@@ -52,6 +54,7 @@ public class PendingDevices {
|
||||
}));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove(String number) {
|
||||
database.use(jdbi -> jdbi.useHandle(handle -> {
|
||||
try (Timer.Context timer = removeTimer.time()) {
|
||||
|
||||
+28
-55
@@ -4,78 +4,51 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.StoredVerificationCode;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Optional;
|
||||
import org.whispersystems.textsecuregcm.auth.StoredVerificationCode;
|
||||
|
||||
public class PendingDevicesManager {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(PendingDevicesManager.class);
|
||||
private final PendingDevices pendingDevices;
|
||||
private final VerificationCodeStoreDynamoDb pendingDevicesDynamoDb;
|
||||
private final DynamicConfigurationManager dynamicConfigurationManager;
|
||||
|
||||
private static final String CACHE_PREFIX = "pending_devices2::";
|
||||
public PendingDevicesManager(
|
||||
final PendingDevices pendingDevices,
|
||||
final VerificationCodeStoreDynamoDb pendingDevicesDynamoDb,
|
||||
final DynamicConfigurationManager dynamicConfigurationManager) {
|
||||
|
||||
private final PendingDevices pendingDevices;
|
||||
private final FaultTolerantRedisCluster cacheCluster;
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
public PendingDevicesManager(PendingDevices pendingDevices, FaultTolerantRedisCluster cacheCluster) {
|
||||
this.pendingDevices = pendingDevices;
|
||||
this.cacheCluster = cacheCluster;
|
||||
this.mapper = SystemMapper.getMapper();
|
||||
this.pendingDevicesDynamoDb = pendingDevicesDynamoDb;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
}
|
||||
|
||||
public void store(String number, StoredVerificationCode code) {
|
||||
memcacheSet(number, code);
|
||||
pendingDevices.insert(number, code.getCode(), code.getTimestamp());
|
||||
switch (dynamicConfigurationManager.getConfiguration().getPendingDevicesMigrationConfiguration().getWriteDestination()) {
|
||||
case POSTGRES:
|
||||
pendingDevices.insert(number, code);
|
||||
break;
|
||||
|
||||
case DYNAMODB:
|
||||
pendingDevicesDynamoDb.insert(number, code);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public void remove(String number) {
|
||||
memcacheDelete(number);
|
||||
pendingDevices.remove(number);
|
||||
pendingDevicesDynamoDb.remove(number);
|
||||
}
|
||||
|
||||
public Optional<StoredVerificationCode> getCodeForNumber(String number) {
|
||||
Optional<StoredVerificationCode> code = memcacheGet(number);
|
||||
final Optional<StoredVerificationCode> maybeCodeFromPostgres =
|
||||
dynamicConfigurationManager.getConfiguration().getPendingDevicesMigrationConfiguration().isReadPostgres()
|
||||
? pendingDevices.findForNumber(number)
|
||||
: Optional.empty();
|
||||
|
||||
if (!code.isPresent()) {
|
||||
code = pendingDevices.getCodeForNumber(number);
|
||||
code.ifPresent(storedVerificationCode -> memcacheSet(number, storedVerificationCode));
|
||||
}
|
||||
|
||||
return code;
|
||||
return maybeCodeFromPostgres.or(
|
||||
() -> dynamicConfigurationManager.getConfiguration().getPendingDevicesMigrationConfiguration().isReadDynamoDb()
|
||||
? pendingDevicesDynamoDb.findForNumber(number)
|
||||
: Optional.empty());
|
||||
}
|
||||
|
||||
private void memcacheSet(String number, StoredVerificationCode code) {
|
||||
try {
|
||||
final String verificationCodeJson = mapper.writeValueAsString(code);
|
||||
|
||||
cacheCluster.useCluster(connection -> connection.sync().set(CACHE_PREFIX + number, verificationCodeJson));
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalArgumentException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<StoredVerificationCode> memcacheGet(String number) {
|
||||
try {
|
||||
final String json = cacheCluster.withCluster(connection -> connection.sync().get(CACHE_PREFIX + number));
|
||||
|
||||
if (json == null) return Optional.empty();
|
||||
else return Optional.of(mapper.readValue(json, StoredVerificationCode.class));
|
||||
} catch (IOException e) {
|
||||
logger.warn("Could not parse pending device stored verification json");
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private void memcacheDelete(String number) {
|
||||
cacheCluster.useCluster(connection -> connection.sync().del(CACHE_PREFIX + number));
|
||||
}
|
||||
|
||||
}
|
||||
+25
-23
@@ -5,25 +5,23 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.document.Item;
|
||||
import com.amazonaws.services.dynamodbv2.document.Table;
|
||||
import com.amazonaws.services.dynamodbv2.document.spec.DeleteItemSpec;
|
||||
import com.amazonaws.services.dynamodbv2.document.spec.PutItemSpec;
|
||||
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
|
||||
|
||||
/**
|
||||
* Stores push challenge tokens. Users may have at most one outstanding push challenge token at a time.
|
||||
*/
|
||||
public class PushChallengeDynamoDb extends AbstractDynamoDbStore {
|
||||
|
||||
private final Table table;
|
||||
private final String tableName;
|
||||
private final Clock clock;
|
||||
|
||||
static final String KEY_ACCOUNT_UUID = "U";
|
||||
@@ -33,15 +31,15 @@ public class PushChallengeDynamoDb extends AbstractDynamoDbStore {
|
||||
private static final Map<String, String> UUID_NAME_MAP = Map.of("#uuid", KEY_ACCOUNT_UUID);
|
||||
private static final Map<String, String> CHALLENGE_TOKEN_NAME_MAP = Map.of("#challenge", ATTR_CHALLENGE_TOKEN);
|
||||
|
||||
public PushChallengeDynamoDb(final DynamoDB dynamoDB, final String tableName) {
|
||||
public PushChallengeDynamoDb(final DynamoDbClient dynamoDB, final String tableName) {
|
||||
this(dynamoDB, tableName, Clock.systemUTC());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
PushChallengeDynamoDb(final DynamoDB dynamoDB, final String tableName, final Clock clock) {
|
||||
PushChallengeDynamoDb(final DynamoDbClient dynamoDB, final String tableName, final Clock clock) {
|
||||
super(dynamoDB);
|
||||
|
||||
this.table = dynamoDB.getTable(tableName);
|
||||
this.tableName = tableName;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@@ -57,13 +55,15 @@ public class PushChallengeDynamoDb extends AbstractDynamoDbStore {
|
||||
*/
|
||||
public boolean add(final UUID accountUuid, final byte[] challengeToken, final Duration ttl) {
|
||||
try {
|
||||
table.putItem( new PutItemSpec()
|
||||
.withItem(new Item()
|
||||
.withBinary(KEY_ACCOUNT_UUID, UUIDUtil.toByteBuffer(accountUuid))
|
||||
.withBinary(ATTR_CHALLENGE_TOKEN, challengeToken)
|
||||
.withNumber(ATTR_TTL, getExpirationTimestamp(ttl)))
|
||||
.withConditionExpression("attribute_not_exists(#uuid)")
|
||||
.withNameMap(UUID_NAME_MAP));
|
||||
db().putItem(PutItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.item(Map.of(
|
||||
KEY_ACCOUNT_UUID, AttributeValues.fromUUID(accountUuid),
|
||||
ATTR_CHALLENGE_TOKEN, AttributeValues.fromByteArray(challengeToken),
|
||||
ATTR_TTL, AttributeValues.fromLong(getExpirationTimestamp(ttl))))
|
||||
.conditionExpression("attribute_not_exists(#uuid)")
|
||||
.expressionAttributeNames(UUID_NAME_MAP)
|
||||
.build());
|
||||
return true;
|
||||
} catch (final ConditionalCheckFailedException e) {
|
||||
return false;
|
||||
@@ -84,11 +84,13 @@ public class PushChallengeDynamoDb extends AbstractDynamoDbStore {
|
||||
*/
|
||||
public boolean remove(final UUID accountUuid, final byte[] challengeToken) {
|
||||
try {
|
||||
table.deleteItem(new DeleteItemSpec()
|
||||
.withPrimaryKey(KEY_ACCOUNT_UUID, UUIDUtil.toByteBuffer(accountUuid))
|
||||
.withConditionExpression("#challenge = :challenge")
|
||||
.withNameMap(CHALLENGE_TOKEN_NAME_MAP)
|
||||
.withValueMap(Map.of(":challenge", challengeToken)));
|
||||
db().deleteItem(DeleteItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(KEY_ACCOUNT_UUID, AttributeValues.fromUUID(accountUuid)))
|
||||
.conditionExpression("#challenge = :challenge")
|
||||
.expressionAttributeNames(CHALLENGE_TOKEN_NAME_MAP)
|
||||
.expressionAttributeValues(Map.of(":challenge", AttributeValues.fromByteArray(challengeToken)))
|
||||
.build());
|
||||
return true;
|
||||
} catch (final ConditionalCheckFailedException e) {
|
||||
return false;
|
||||
|
||||
+25
-27
@@ -1,13 +1,14 @@
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.amazonaws.services.dynamodbv2.document.DeleteItemOutcome;
|
||||
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.document.Item;
|
||||
import com.amazonaws.services.dynamodbv2.document.Table;
|
||||
import com.amazonaws.services.dynamodbv2.document.spec.DeleteItemSpec;
|
||||
import com.amazonaws.services.dynamodbv2.model.ReturnValue;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteItemResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
|
||||
public class ReportMessageDynamoDb {
|
||||
|
||||
@@ -16,33 +17,30 @@ public class ReportMessageDynamoDb {
|
||||
|
||||
static final Duration TIME_TO_LIVE = Duration.ofDays(7);
|
||||
|
||||
private final Table table;
|
||||
private final DynamoDbClient db;
|
||||
private final String tableName;
|
||||
|
||||
public ReportMessageDynamoDb(final DynamoDB dynamoDB, final String tableName) {
|
||||
|
||||
this.table = dynamoDB.getTable(tableName);
|
||||
public ReportMessageDynamoDb(final DynamoDbClient dynamoDB, final String tableName) {
|
||||
this.db = dynamoDB;
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
public void store(byte[] hash) {
|
||||
|
||||
table.putItem(buildItemForHash(hash));
|
||||
}
|
||||
|
||||
private Item buildItemForHash(byte[] hash) {
|
||||
return new Item()
|
||||
.withBinary(KEY_HASH, hash)
|
||||
.withLong(ATTR_TTL, Instant.now().plus(TIME_TO_LIVE).getEpochSecond());
|
||||
db.putItem(PutItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.item(Map.of(
|
||||
KEY_HASH, AttributeValues.fromByteArray(hash),
|
||||
ATTR_TTL, AttributeValues.fromLong(Instant.now().plus(TIME_TO_LIVE).getEpochSecond())
|
||||
))
|
||||
.build());
|
||||
}
|
||||
|
||||
public boolean remove(byte[] hash) {
|
||||
|
||||
final DeleteItemSpec deleteItemSpec = new DeleteItemSpec()
|
||||
.withPrimaryKey(KEY_HASH, hash)
|
||||
.withReturnValues(ReturnValue.ALL_OLD);
|
||||
|
||||
final DeleteItemOutcome outcome = table.deleteItem(deleteItemSpec);
|
||||
|
||||
return outcome.getItem() != null;
|
||||
final DeleteItemResponse deleteItemResponse = db.deleteItem(DeleteItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(KEY_HASH, AttributeValues.fromByteArray(hash)))
|
||||
.returnValues(ReturnValue.ALL_OLD)
|
||||
.build());
|
||||
return !deleteItemResponse.attributes().isEmpty();
|
||||
}
|
||||
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import org.whispersystems.textsecuregcm.auth.StoredVerificationCode;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface VerificationCodeStore {
|
||||
|
||||
void insert(String number, StoredVerificationCode verificationCode);
|
||||
|
||||
Optional<StoredVerificationCode> findForNumber(String number);
|
||||
|
||||
void remove(String number);
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.StoredVerificationCode;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
public class VerificationCodeStoreDynamoDb implements VerificationCodeStore {
|
||||
|
||||
private final DynamoDbClient dynamoDbClient;
|
||||
private final String tableName;
|
||||
|
||||
private final Timer insertTimer;
|
||||
private final Timer getTimer;
|
||||
private final Timer removeTimer;
|
||||
|
||||
@VisibleForTesting
|
||||
static final String KEY_E164 = "P";
|
||||
|
||||
private static final String ATTR_STORED_CODE = "C";
|
||||
private static final String ATTR_TTL = "E";
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(VerificationCodeStoreDynamoDb.class);
|
||||
|
||||
public VerificationCodeStoreDynamoDb(final DynamoDbClient dynamoDbClient, final String tableName) {
|
||||
this.dynamoDbClient = dynamoDbClient;
|
||||
this.tableName = tableName;
|
||||
|
||||
this.insertTimer = Metrics.timer(name(getClass(), "insert"), "table", tableName);
|
||||
this.getTimer = Metrics.timer(name(getClass(), "get"), "table", tableName);
|
||||
this.removeTimer = Metrics.timer(name(getClass(), "remove"), "table", tableName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void insert(final String number, final StoredVerificationCode verificationCode) {
|
||||
insertTimer.record(() -> {
|
||||
try {
|
||||
dynamoDbClient.putItem(PutItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.item(Map.of(
|
||||
KEY_E164, AttributeValues.fromString(number),
|
||||
ATTR_STORED_CODE, AttributeValues.fromString(SystemMapper.getMapper().writeValueAsString(verificationCode)),
|
||||
ATTR_TTL, AttributeValues.fromLong(getExpirationTimestamp(verificationCode))))
|
||||
.build());
|
||||
} catch (final JsonProcessingException e) {
|
||||
// This should never happen when writing directly to a string except in cases of serious misconfiguration, which
|
||||
// would be caught by tests.
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private long getExpirationTimestamp(final StoredVerificationCode storedVerificationCode) {
|
||||
return Instant.ofEpochMilli(storedVerificationCode.getTimestamp()).plus(StoredVerificationCode.EXPIRATION).getEpochSecond();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<StoredVerificationCode> findForNumber(final String number) {
|
||||
return getTimer.record(() -> {
|
||||
final GetItemResponse response = dynamoDbClient.getItem(GetItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.consistentRead(true)
|
||||
.key(Map.of(KEY_E164, AttributeValues.fromString(number)))
|
||||
.build());
|
||||
|
||||
try {
|
||||
return response.hasItem()
|
||||
? Optional.of(SystemMapper.getMapper().readValue(response.item().get(ATTR_STORED_CODE).s(), StoredVerificationCode.class))
|
||||
: Optional.empty();
|
||||
} catch (final JsonProcessingException e) {
|
||||
log.error("Failed to parse stored verification code", e);
|
||||
return Optional.empty();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove(final String number) {
|
||||
removeTimer.record(() -> {
|
||||
dynamoDbClient.deleteItem(DeleteItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(KEY_E164, AttributeValues.fromString(number)))
|
||||
.build());
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import software.amazon.awssdk.core.SdkBytes;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
/** AwsAV provides static helper methods for working with AWS AttributeValues. */
|
||||
public class AttributeValues {
|
||||
|
||||
public static AttributeValue fromString(String value) {
|
||||
return AttributeValue.builder().s(value).build();
|
||||
}
|
||||
|
||||
public static AttributeValue fromLong(long value) {
|
||||
return AttributeValue.builder().n(Long.toString(value)).build();
|
||||
}
|
||||
|
||||
public static AttributeValue fromInt(int value) {
|
||||
return AttributeValue.builder().n(Integer.toString(value)).build();
|
||||
}
|
||||
|
||||
public static AttributeValue fromByteArray(byte[] value) {
|
||||
return AttributeValues.fromSdkBytes(SdkBytes.fromByteArray(value));
|
||||
}
|
||||
|
||||
public static AttributeValue fromByteBuffer(ByteBuffer value) {
|
||||
return AttributeValues.fromSdkBytes(SdkBytes.fromByteBuffer(value));
|
||||
}
|
||||
|
||||
public static AttributeValue fromUUID(UUID uuid) {
|
||||
return AttributeValues.fromSdkBytes(SdkBytes.fromByteArrayUnsafe(UUIDUtil.toBytes(uuid)));
|
||||
}
|
||||
|
||||
public static AttributeValue fromSdkBytes(SdkBytes value) {
|
||||
return AttributeValue.builder().b(value).build();
|
||||
}
|
||||
|
||||
private static int toInt(AttributeValue av) {
|
||||
return Integer.parseInt(av.n());
|
||||
}
|
||||
|
||||
private static long toLong(AttributeValue av) {
|
||||
return Long.parseLong(av.n());
|
||||
}
|
||||
|
||||
private static UUID toUUID(AttributeValue av) {
|
||||
return UUIDUtil.fromBytes(av.b().asByteArrayUnsafe()); // We're guaranteed not to modify the byte array
|
||||
}
|
||||
|
||||
private static byte[] toByteArray(AttributeValue av) {
|
||||
return av.b().asByteArray();
|
||||
}
|
||||
|
||||
private static String toString(AttributeValue av) {
|
||||
return av.s();
|
||||
}
|
||||
|
||||
public static Optional<AttributeValue> get(Map<String, AttributeValue> item, String key) {
|
||||
return Optional.ofNullable(item.get(key));
|
||||
}
|
||||
|
||||
public static int getInt(Map<String, AttributeValue> item, String key, int defaultValue) {
|
||||
return AttributeValues.get(item, key).map(AttributeValues::toInt).orElse(defaultValue);
|
||||
}
|
||||
|
||||
public static String getString(Map<String, AttributeValue> item, String key, String defaultValue) {
|
||||
return AttributeValues.get(item, key).map(AttributeValues::toString).orElse(defaultValue);
|
||||
}
|
||||
|
||||
public static long getLong(Map<String, AttributeValue> item, String key, long defaultValue) {
|
||||
return AttributeValues.get(item, key).map(AttributeValues::toLong).orElse(defaultValue);
|
||||
}
|
||||
|
||||
public static byte[] getByteArray(Map<String, AttributeValue> item, String key, byte[] defaultValue) {
|
||||
return AttributeValues.get(item, key).map(AttributeValues::toByteArray).orElse(defaultValue);
|
||||
}
|
||||
|
||||
public static UUID getUUID(Map<String, AttributeValue> item, String key, UUID defaultValue) {
|
||||
return AttributeValues.get(item, key).map(AttributeValues::toUUID).orElse(defaultValue);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import org.whispersystems.textsecuregcm.configuration.DynamoDbConfiguration;
|
||||
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
|
||||
import software.amazon.awssdk.core.client.config.ClientAsyncConfiguration;
|
||||
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
|
||||
import software.amazon.awssdk.core.client.config.SdkAdvancedAsyncClientOption;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClientBuilder;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import java.util.concurrent.Executor;
|
||||
|
||||
public class DynamoDbFromConfig {
|
||||
private static ClientOverrideConfiguration clientOverrideConfiguration(DynamoDbConfiguration config) {
|
||||
return ClientOverrideConfiguration.builder()
|
||||
.apiCallTimeout(config.getClientExecutionTimeout())
|
||||
.apiCallAttemptTimeout(config.getClientRequestTimeout())
|
||||
.build();
|
||||
}
|
||||
public static DynamoDbClient client(DynamoDbConfiguration config, AwsCredentialsProvider credentialsProvider) {
|
||||
return DynamoDbClient.builder()
|
||||
.region(Region.of(config.getRegion()))
|
||||
.credentialsProvider(credentialsProvider)
|
||||
.overrideConfiguration(clientOverrideConfiguration(config))
|
||||
.build();
|
||||
}
|
||||
public static DynamoDbAsyncClient asyncClient(DynamoDbConfiguration config, AwsCredentialsProvider credentialsProvider, Executor executor) {
|
||||
DynamoDbAsyncClientBuilder builder = DynamoDbAsyncClient.builder()
|
||||
.region(Region.of(config.getRegion()))
|
||||
.credentialsProvider(credentialsProvider)
|
||||
.overrideConfiguration(clientOverrideConfiguration(config));
|
||||
if (executor != null) {
|
||||
builder.asyncConfiguration(ClientAsyncConfiguration.builder()
|
||||
.advancedOption(SdkAdvancedAsyncClientOption.FUTURE_COMPLETION_EXECUTOR,
|
||||
executor)
|
||||
.build());
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.Locale;
|
||||
|
||||
public class HostnameUtil {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(HostnameUtil.class);
|
||||
|
||||
public static String getLocalHostname() {
|
||||
try {
|
||||
return InetAddress.getLocalHost().getHostName().toLowerCase(Locale.US);
|
||||
} catch (final UnknownHostException e) {
|
||||
log.warn("Failed to get hostname", e);
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import java.nio.BufferUnderflowException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.UUID;
|
||||
|
||||
@@ -26,12 +27,15 @@ public class UUIDUtil {
|
||||
}
|
||||
|
||||
public static UUID fromByteBuffer(final ByteBuffer byteBuffer) {
|
||||
if (byteBuffer.array().length != 16) {
|
||||
throw new IllegalArgumentException("unexpected byte array length; was " + byteBuffer.array().length + " but expected 16");
|
||||
try {
|
||||
final long mostSigBits = byteBuffer.getLong();
|
||||
final long leastSigBits = byteBuffer.getLong();
|
||||
if (byteBuffer.hasRemaining()) {
|
||||
throw new IllegalArgumentException("unexpected byte array length; was greater than 16");
|
||||
}
|
||||
return new UUID(mostSigBits, leastSigBits);
|
||||
} catch (BufferUnderflowException e) {
|
||||
throw new IllegalArgumentException("unexpected byte array length; was less than 16");
|
||||
}
|
||||
|
||||
final long mostSigBits = byteBuffer.getLong();
|
||||
final long leastSigBits = byteBuffer.getLong();
|
||||
return new UUID(mostSigBits, leastSigBits);
|
||||
}
|
||||
}
|
||||
+5
@@ -68,6 +68,11 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
context.getClient(),
|
||||
retrySchedulingExecutor);
|
||||
|
||||
// TODO Remove once PIN-based reglocks have been deprecated
|
||||
if (account.getRegistrationLock().requiresClientRegistrationLock() && account.getRegistrationLock().hasDeprecatedPin()) {
|
||||
log.info("User-Agent with deprecated PIN-based registration lock: {}", context.getClient().getUserAgent());
|
||||
}
|
||||
|
||||
openWebsocketCounter.inc();
|
||||
RedisOperation.unchecked(() -> apnFallbackManager.cancel(account, device));
|
||||
|
||||
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import io.dropwizard.cli.Command;
|
||||
import io.dropwizard.setup.Bootstrap;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
|
||||
public class CheckDynamicConfigurationCommand extends Command {
|
||||
|
||||
public CheckDynamicConfigurationCommand() {
|
||||
super("check-dynamic-config", "Check validity of a dynamic configuration file");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(final Subparser subparser) {
|
||||
subparser.addArgument("file")
|
||||
.type(String.class)
|
||||
.required(true)
|
||||
.help("Dynamic configuration file to check");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(final Bootstrap<?> bootstrap, final Namespace namespace) throws Exception {
|
||||
final Path path = Path.of(namespace.getString("file"));
|
||||
|
||||
if (DynamicConfigurationManager.parseConfiguration(Files.readString(path)).isPresent()) {
|
||||
System.out.println("Dynamic configuration file at " + path + " is valid");
|
||||
} else {
|
||||
System.err.println("Dynamic configuration file at " + path + " is not valid");
|
||||
}
|
||||
}
|
||||
}
|
||||
+24
-66
@@ -7,13 +7,6 @@ package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.amazonaws.ClientConfiguration;
|
||||
import com.amazonaws.auth.InstanceProfileCredentialsProvider;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBAsync;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBAsyncClientBuilder;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
|
||||
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import io.dropwizard.Application;
|
||||
import io.dropwizard.cli.EnvironmentCommand;
|
||||
@@ -44,6 +37,7 @@ import org.whispersystems.textsecuregcm.storage.Accounts;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager.DeletionReason;
|
||||
import org.whispersystems.textsecuregcm.storage.DeletedAccounts;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.FaultTolerantDatabase;
|
||||
import org.whispersystems.textsecuregcm.storage.KeysDynamoDb;
|
||||
@@ -59,6 +53,9 @@ import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ReservedUsernames;
|
||||
import org.whispersystems.textsecuregcm.storage.Usernames;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernamesManager;
|
||||
import org.whispersystems.textsecuregcm.util.DynamoDbFromConfig;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
|
||||
public class DeleteUserCommand extends EnvironmentCommand<WhisperServerConfiguration> {
|
||||
|
||||
@@ -100,64 +97,22 @@ public class DeleteUserCommand extends EnvironmentCommand<WhisperServerConfigura
|
||||
FaultTolerantDatabase accountDatabase = new FaultTolerantDatabase("account_database_delete_user", accountJdbi, configuration.getAccountsDatabaseConfiguration().getCircuitBreakerConfiguration());
|
||||
ClientResources redisClusterClientResources = ClientResources.builder().build();
|
||||
|
||||
AmazonDynamoDBClientBuilder clientBuilder = AmazonDynamoDBClientBuilder
|
||||
.standard()
|
||||
.withRegion(configuration.getMessageDynamoDbConfiguration().getRegion())
|
||||
.withClientConfiguration(new ClientConfiguration().withClientExecutionTimeout(((int) configuration.getMessageDynamoDbConfiguration().getClientExecutionTimeout().toMillis()))
|
||||
.withRequestTimeout((int) configuration.getMessageDynamoDbConfiguration().getClientRequestTimeout().toMillis()))
|
||||
.withCredentials(InstanceProfileCredentialsProvider.getInstance());
|
||||
|
||||
AmazonDynamoDBClientBuilder keysDynamoDbClientBuilder = AmazonDynamoDBClientBuilder
|
||||
.standard()
|
||||
.withRegion(configuration.getKeysDynamoDbConfiguration().getRegion())
|
||||
.withClientConfiguration(new ClientConfiguration().withClientExecutionTimeout(((int) configuration.getKeysDynamoDbConfiguration().getClientExecutionTimeout().toMillis()))
|
||||
.withRequestTimeout((int) configuration.getKeysDynamoDbConfiguration().getClientRequestTimeout().toMillis()))
|
||||
.withCredentials(InstanceProfileCredentialsProvider.getInstance());
|
||||
|
||||
AmazonDynamoDBClientBuilder accountsDynamoDbClientBuilder = AmazonDynamoDBClientBuilder
|
||||
.standard()
|
||||
.withRegion(configuration.getAccountsDynamoDbConfiguration().getRegion())
|
||||
.withClientConfiguration(new ClientConfiguration().withClientExecutionTimeout(((int) configuration.getAccountsDynamoDbConfiguration().getClientExecutionTimeout().toMillis()))
|
||||
.withRequestTimeout((int) configuration.getAccountsDynamoDbConfiguration().getClientRequestTimeout().toMillis()))
|
||||
.withCredentials(InstanceProfileCredentialsProvider.getInstance());
|
||||
|
||||
ThreadPoolExecutor accountsDynamoDbMigrationThreadPool = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS,
|
||||
new LinkedBlockingDeque<>());
|
||||
|
||||
AmazonDynamoDBAsyncClientBuilder accountsDynamoDbAsyncClientBuilder = AmazonDynamoDBAsyncClientBuilder
|
||||
.standard()
|
||||
.withRegion(accountsDynamoDbClientBuilder.getRegion())
|
||||
.withClientConfiguration(accountsDynamoDbClientBuilder.getClientConfiguration())
|
||||
.withCredentials(accountsDynamoDbClientBuilder.getCredentials())
|
||||
.withExecutorFactory(() -> accountsDynamoDbMigrationThreadPool);
|
||||
|
||||
AmazonDynamoDBClientBuilder migrationDeletedAccountsDynamoDbClientBuilder = AmazonDynamoDBClientBuilder
|
||||
.standard()
|
||||
.withRegion(configuration.getMigrationDeletedAccountsDynamoDbConfiguration().getRegion())
|
||||
.withClientConfiguration(new ClientConfiguration().withClientExecutionTimeout(((int) configuration.getMigrationDeletedAccountsDynamoDbConfiguration().getClientExecutionTimeout().toMillis()))
|
||||
.withRequestTimeout((int) configuration.getMigrationDeletedAccountsDynamoDbConfiguration().getClientRequestTimeout().toMillis()))
|
||||
.withCredentials(InstanceProfileCredentialsProvider.getInstance());
|
||||
|
||||
AmazonDynamoDBClientBuilder migrationRetryAccountsDynamoDbClientBuilder = AmazonDynamoDBClientBuilder
|
||||
.standard()
|
||||
.withRegion(configuration.getMigrationRetryAccountsDynamoDbConfiguration().getRegion())
|
||||
.withClientConfiguration(new ClientConfiguration().withClientExecutionTimeout(((int) configuration.getMigrationRetryAccountsDynamoDbConfiguration().getClientExecutionTimeout().toMillis()))
|
||||
.withRequestTimeout((int) configuration.getMigrationRetryAccountsDynamoDbConfiguration().getClientRequestTimeout().toMillis()))
|
||||
.withCredentials(InstanceProfileCredentialsProvider.getInstance());
|
||||
|
||||
AmazonDynamoDBClientBuilder reportMessageDynamoDbClientBuilder = AmazonDynamoDBClientBuilder
|
||||
.standard()
|
||||
.withRegion(configuration.getReportMessageDynamoDbConfiguration().getRegion())
|
||||
.withClientConfiguration(new ClientConfiguration().withClientExecutionTimeout(((int) configuration.getReportMessageDynamoDbConfiguration().getClientExecutionTimeout().toMillis()))
|
||||
.withRequestTimeout((int) configuration.getReportMessageDynamoDbConfiguration().getClientRequestTimeout().toMillis()))
|
||||
.withCredentials(InstanceProfileCredentialsProvider.getInstance());
|
||||
|
||||
DynamoDB messageDynamoDb = new DynamoDB(clientBuilder.build());
|
||||
DynamoDB preKeysDynamoDb = new DynamoDB(keysDynamoDbClientBuilder.build());
|
||||
DynamoDB reportMessagesDynamoDb = new DynamoDB(reportMessageDynamoDbClientBuilder.build());
|
||||
|
||||
AmazonDynamoDB accountsDynamoDbClient = accountsDynamoDbClientBuilder.build();
|
||||
AmazonDynamoDBAsync accountsDynamoDbAsyncClient = accountsDynamoDbAsyncClientBuilder.build();
|
||||
DynamoDbClient reportMessagesDynamoDb = DynamoDbFromConfig.client(configuration.getReportMessageDynamoDbConfiguration(),
|
||||
software.amazon.awssdk.auth.credentials.InstanceProfileCredentialsProvider.create());
|
||||
DynamoDbClient messageDynamoDb = DynamoDbFromConfig.client(configuration.getMessageDynamoDbConfiguration(),
|
||||
software.amazon.awssdk.auth.credentials.InstanceProfileCredentialsProvider.create());
|
||||
DynamoDbClient preKeysDynamoDb = DynamoDbFromConfig.client(configuration.getKeysDynamoDbConfiguration(),
|
||||
software.amazon.awssdk.auth.credentials.InstanceProfileCredentialsProvider.create());
|
||||
DynamoDbClient accountsDynamoDbClient = DynamoDbFromConfig.client(configuration.getAccountsDynamoDbConfiguration(),
|
||||
software.amazon.awssdk.auth.credentials.InstanceProfileCredentialsProvider.create());
|
||||
DynamoDbAsyncClient accountsDynamoDbAsyncClient = DynamoDbFromConfig.asyncClient(configuration.getAccountsDynamoDbConfiguration(),
|
||||
software.amazon.awssdk.auth.credentials.InstanceProfileCredentialsProvider.create(),
|
||||
accountsDynamoDbMigrationThreadPool);
|
||||
DynamoDbClient deletedAccountsDynamoDbClient = DynamoDbFromConfig.client(configuration.getDeletedAccountsDynamoDbConfiguration(),
|
||||
software.amazon.awssdk.auth.credentials.InstanceProfileCredentialsProvider.create());
|
||||
|
||||
FaultTolerantRedisCluster cacheCluster = new FaultTolerantRedisCluster("main_cache_cluster", configuration.getCacheClusterConfiguration(), redisClusterClientResources);
|
||||
|
||||
@@ -173,14 +128,17 @@ public class DeleteUserCommand extends EnvironmentCommand<WhisperServerConfigura
|
||||
|
||||
ExperimentEnrollmentManager experimentEnrollmentManager = new ExperimentEnrollmentManager(dynamicConfigurationManager);
|
||||
|
||||
DynamoDB migrationDeletedAccountsDynamoDb = new DynamoDB(migrationDeletedAccountsDynamoDbClientBuilder.build());
|
||||
DynamoDB migrationRetryAccountsDynamoDb = new DynamoDB(migrationRetryAccountsDynamoDbClientBuilder.build());
|
||||
DynamoDbClient migrationDeletedAccountsDynamoDb = DynamoDbFromConfig.client(configuration.getMigrationDeletedAccountsDynamoDbConfiguration(),
|
||||
software.amazon.awssdk.auth.credentials.InstanceProfileCredentialsProvider.create());
|
||||
DynamoDbClient migrationRetryAccountsDynamoDb = DynamoDbFromConfig.client(configuration.getMigrationRetryAccountsDynamoDbConfiguration(),
|
||||
software.amazon.awssdk.auth.credentials.InstanceProfileCredentialsProvider.create());
|
||||
|
||||
DeletedAccounts deletedAccounts = new DeletedAccounts(deletedAccountsDynamoDbClient, configuration.getDeletedAccountsDynamoDbConfiguration().getTableName(), configuration.getDeletedAccountsDynamoDbConfiguration().getNeedsReconciliationIndexName());
|
||||
MigrationDeletedAccounts migrationDeletedAccounts = new MigrationDeletedAccounts(migrationDeletedAccountsDynamoDb, configuration.getMigrationDeletedAccountsDynamoDbConfiguration().getTableName());
|
||||
MigrationRetryAccounts migrationRetryAccounts = new MigrationRetryAccounts(migrationRetryAccountsDynamoDb, configuration.getMigrationRetryAccountsDynamoDbConfiguration().getTableName());
|
||||
|
||||
Accounts accounts = new Accounts(accountDatabase);
|
||||
AccountsDynamoDb accountsDynamoDb = new AccountsDynamoDb(accountsDynamoDbClient, accountsDynamoDbAsyncClient, accountsDynamoDbMigrationThreadPool, new DynamoDB(accountsDynamoDbClient), configuration.getAccountsDynamoDbConfiguration().getTableName(), configuration.getAccountsDynamoDbConfiguration().getPhoneNumberTableName(), migrationDeletedAccounts, migrationRetryAccounts);
|
||||
AccountsDynamoDb accountsDynamoDb = new AccountsDynamoDb(accountsDynamoDbClient, accountsDynamoDbAsyncClient, accountsDynamoDbMigrationThreadPool, configuration.getAccountsDynamoDbConfiguration().getTableName(), configuration.getAccountsDynamoDbConfiguration().getPhoneNumberTableName(), migrationDeletedAccounts, migrationRetryAccounts);
|
||||
Usernames usernames = new Usernames(accountDatabase);
|
||||
Profiles profiles = new Profiles(accountDatabase);
|
||||
ReservedUsernames reservedUsernames = new ReservedUsernames(accountDatabase);
|
||||
@@ -199,7 +157,7 @@ public class DeleteUserCommand extends EnvironmentCommand<WhisperServerConfigura
|
||||
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(reportMessagesDynamoDb, configuration.getReportMessageDynamoDbConfiguration().getTableName());
|
||||
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, Metrics.globalRegistry);
|
||||
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, pushLatencyManager, reportMessageManager);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, accountsDynamoDb, cacheCluster, directoryQueue, keysDynamoDb, messagesManager, usernamesManager, profilesManager, secureStorageClient, secureBackupClient, experimentEnrollmentManager, dynamicConfigurationManager);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, accountsDynamoDb, cacheCluster, deletedAccounts, directoryQueue, keysDynamoDb, messagesManager, usernamesManager, profilesManager, secureStorageClient, secureBackupClient, experimentEnrollmentManager, dynamicConfigurationManager);
|
||||
|
||||
for (String user: users) {
|
||||
Optional<Account> account = accountsManager.get(user);
|
||||
|
||||
-43
@@ -1,43 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import io.dropwizard.cli.ConfiguredCommand;
|
||||
import io.dropwizard.setup.Bootstrap;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class GetRedisCommandStatsCommand extends ConfiguredCommand<WhisperServerConfiguration> {
|
||||
|
||||
public GetRedisCommandStatsCommand() {
|
||||
super("rediscommandstats", "Dump Redis command stats");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void run(final Bootstrap<WhisperServerConfiguration> bootstrap, final Namespace namespace, final WhisperServerConfiguration config) {
|
||||
final ClientResources redisClusterClientResources = ClientResources.builder().build();
|
||||
|
||||
final FaultTolerantRedisCluster cacheCluster = new FaultTolerantRedisCluster("main_cache_cluster", config.getCacheClusterConfiguration(), redisClusterClientResources);
|
||||
final FaultTolerantRedisCluster messagesCacheCluster = new FaultTolerantRedisCluster("messages_cluster", config.getMessageCacheConfiguration().getRedisClusterConfiguration(), redisClusterClientResources);
|
||||
final FaultTolerantRedisCluster metricsCluster = new FaultTolerantRedisCluster("metrics_cluster", config.getMetricsClusterConfiguration(), redisClusterClientResources);
|
||||
|
||||
for (final FaultTolerantRedisCluster cluster : List.of(cacheCluster, messagesCacheCluster, metricsCluster)) {
|
||||
cluster.useCluster(connection -> connection.sync()
|
||||
.upstream()
|
||||
.commands()
|
||||
.info("commandstats")
|
||||
.asMap()
|
||||
.forEach((node, commandStats) -> {
|
||||
System.out.format("# %s - %s\n\n", cluster.getName(), node.getUri());
|
||||
System.out.println(commandStats);
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
-62
@@ -1,62 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import io.dropwizard.cli.ConfiguredCommand;
|
||||
import io.dropwizard.setup.Bootstrap;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class GetRedisSlowlogCommand extends ConfiguredCommand<WhisperServerConfiguration> {
|
||||
|
||||
public GetRedisSlowlogCommand() {
|
||||
super("redisslowlog", "Dump a JSON blob describing slow Redis operations");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(final Subparser subparser) {
|
||||
super.configure(subparser);
|
||||
|
||||
subparser.addArgument("-n", "--entries")
|
||||
.dest("entries")
|
||||
.type(Integer.class)
|
||||
.required(false)
|
||||
.setDefault(128)
|
||||
.help("The maximum number of SLOWLOG entries to retrieve per cluster node");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void run(final Bootstrap<WhisperServerConfiguration> bootstrap, final Namespace namespace, final WhisperServerConfiguration config) throws Exception {
|
||||
final int entries = namespace.getInt("entries");
|
||||
|
||||
final ClientResources redisClusterClientResources = ClientResources.builder().build();
|
||||
|
||||
final FaultTolerantRedisCluster cacheCluster = new FaultTolerantRedisCluster("main_cache_cluster", config.getCacheClusterConfiguration(), redisClusterClientResources);
|
||||
final FaultTolerantRedisCluster messagesCacheCluster = new FaultTolerantRedisCluster("messages_cluster", config.getMessageCacheConfiguration().getRedisClusterConfiguration(), redisClusterClientResources);
|
||||
final FaultTolerantRedisCluster metricsCluster = new FaultTolerantRedisCluster("metrics_cluster", config.getMetricsClusterConfiguration(), redisClusterClientResources);
|
||||
|
||||
final Map<String, List<Object>> slowlogsByUri = new HashMap<>();
|
||||
|
||||
for (final FaultTolerantRedisCluster cluster : List.of(cacheCluster, messagesCacheCluster, metricsCluster)) {
|
||||
cluster.useCluster(connection -> connection.sync()
|
||||
.upstream()
|
||||
.commands()
|
||||
.slowlogGet(entries)
|
||||
.asMap()
|
||||
.forEach((node, slowlogs) -> slowlogsByUri.put(node.getUri().toString(), slowlogs)));
|
||||
}
|
||||
|
||||
SystemMapper.getMapper().writeValue(System.out, slowlogsByUri);
|
||||
}
|
||||
}
|
||||
@@ -1 +1,2 @@
|
||||
org.whispersystems.textsecuregcm.metrics.JsonMetricsReporterFactory
|
||||
org.whispersystems.textsecuregcm.metrics.SignalDatadogReporterFactory
|
||||
@@ -0,0 +1,8 @@
|
||||
-- keys: lock_key
|
||||
-- argv: lock_value
|
||||
|
||||
if redis.call("GET", KEYS[1]) == ARGV[1] then
|
||||
return redis.call("DEL", KEYS[1])
|
||||
else
|
||||
return 0
|
||||
end
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
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 java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class StoredVerificationCodeTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void isValid(final StoredVerificationCode storedVerificationCode, final String code, final Instant currentTime, final boolean expectValid) {
|
||||
assertEquals(expectValid, storedVerificationCode.isValid(code, currentTime));
|
||||
}
|
||||
|
||||
private static Stream<Arguments> isValid() {
|
||||
final Instant now = Instant.now();
|
||||
|
||||
return Stream.of(
|
||||
Arguments.of(new StoredVerificationCode("code", now.toEpochMilli(), null, null), "code", now, true),
|
||||
Arguments.of(new StoredVerificationCode("code", now.toEpochMilli(), null, null), "incorrect", now, false),
|
||||
Arguments.of(new StoredVerificationCode("code", now.toEpochMilli(), null, null), "code", now.plus(Duration.ofHours(1)), false),
|
||||
Arguments.of(new StoredVerificationCode("", now.toEpochMilli(), null, null), "", now, false)
|
||||
);
|
||||
}
|
||||
}
|
||||
+57
-53
@@ -31,8 +31,8 @@ class DynamicConfigurationTest {
|
||||
void testParseExperimentConfig() throws JsonProcessingException {
|
||||
{
|
||||
final String emptyConfigYaml = "test: true";
|
||||
final DynamicConfiguration emptyConfig = DynamicConfigurationManager.OBJECT_MAPPER
|
||||
.readValue(emptyConfigYaml, DynamicConfiguration.class);
|
||||
final DynamicConfiguration emptyConfig =
|
||||
DynamicConfigurationManager.parseConfiguration(emptyConfigYaml).orElseThrow();
|
||||
|
||||
assertFalse(emptyConfig.getExperimentEnrollmentConfiguration("test").isPresent());
|
||||
}
|
||||
@@ -51,8 +51,8 @@ class DynamicConfigurationTest {
|
||||
" enrolledUuids:\n" +
|
||||
" - 71618739-114c-4b1f-bb0d-6478a44eb600";
|
||||
|
||||
final DynamicConfiguration config = DynamicConfigurationManager.OBJECT_MAPPER
|
||||
.readValue(experimentConfigYaml, DynamicConfiguration.class);
|
||||
final DynamicConfiguration config =
|
||||
DynamicConfigurationManager.parseConfiguration(experimentConfigYaml).orElseThrow();
|
||||
|
||||
assertFalse(config.getExperimentEnrollmentConfiguration("unconfigured").isPresent());
|
||||
|
||||
@@ -79,8 +79,8 @@ class DynamicConfigurationTest {
|
||||
void testParsePreRegistrationExperiments() throws JsonProcessingException {
|
||||
{
|
||||
final String emptyConfigYaml = "test: true";
|
||||
final DynamicConfiguration emptyConfig = DynamicConfigurationManager.OBJECT_MAPPER
|
||||
.readValue(emptyConfigYaml, DynamicConfiguration.class);
|
||||
final DynamicConfiguration emptyConfig =
|
||||
DynamicConfigurationManager.parseConfiguration(emptyConfigYaml).orElseThrow();
|
||||
|
||||
assertFalse(emptyConfig.getPreRegistrationEnrollmentConfiguration("test").isPresent());
|
||||
}
|
||||
@@ -105,8 +105,8 @@ class DynamicConfigurationTest {
|
||||
" excludedCountryCodes:\n" +
|
||||
" - 47";
|
||||
|
||||
final DynamicConfiguration config = DynamicConfigurationManager.OBJECT_MAPPER
|
||||
.readValue(experimentConfigYaml, DynamicConfiguration.class);
|
||||
final DynamicConfiguration config =
|
||||
DynamicConfigurationManager.parseConfiguration(experimentConfigYaml).orElseThrow();
|
||||
|
||||
assertFalse(config.getPreRegistrationEnrollmentConfiguration("unconfigured").isPresent());
|
||||
|
||||
@@ -152,14 +152,14 @@ class DynamicConfigurationTest {
|
||||
void testParseRemoteDeprecationConfig() throws JsonProcessingException {
|
||||
{
|
||||
final String emptyConfigYaml = "test: true";
|
||||
final DynamicConfiguration emptyConfig = DynamicConfigurationManager.OBJECT_MAPPER
|
||||
.readValue(emptyConfigYaml, DynamicConfiguration.class);
|
||||
final DynamicConfiguration emptyConfig =
|
||||
DynamicConfigurationManager.parseConfiguration(emptyConfigYaml).orElseThrow();
|
||||
|
||||
assertNotNull(emptyConfig.getRemoteDeprecationConfiguration());
|
||||
}
|
||||
|
||||
{
|
||||
final String experimentConfigYaml =
|
||||
final String remoteDeprecationConfig =
|
||||
"remoteDeprecation:\n" +
|
||||
" minimumVersions:\n" +
|
||||
" IOS: 1.2.3\n" +
|
||||
@@ -172,8 +172,9 @@ class DynamicConfigurationTest {
|
||||
" DESKTOP:\n" +
|
||||
" - 1.4.0-beta.2";
|
||||
|
||||
final DynamicConfiguration config = DynamicConfigurationManager.OBJECT_MAPPER
|
||||
.readValue(experimentConfigYaml, DynamicConfiguration.class);
|
||||
final DynamicConfiguration config =
|
||||
DynamicConfigurationManager.parseConfiguration(remoteDeprecationConfig).orElseThrow();
|
||||
|
||||
final DynamicRemoteDeprecationConfiguration remoteDeprecationConfiguration = config
|
||||
.getRemoteDeprecationConfiguration();
|
||||
|
||||
@@ -191,8 +192,8 @@ class DynamicConfigurationTest {
|
||||
void testParseMessageRateConfiguration() throws JsonProcessingException {
|
||||
{
|
||||
final String emptyConfigYaml = "test: true";
|
||||
final DynamicConfiguration emptyConfig = DynamicConfigurationManager.OBJECT_MAPPER
|
||||
.readValue(emptyConfigYaml, DynamicConfiguration.class);
|
||||
final DynamicConfiguration emptyConfig =
|
||||
DynamicConfigurationManager.parseConfiguration(emptyConfigYaml).orElseThrow();
|
||||
|
||||
assertFalse(emptyConfig.getMessageRateConfiguration().isEnforceUnsealedSenderRateLimit());
|
||||
}
|
||||
@@ -202,8 +203,8 @@ class DynamicConfigurationTest {
|
||||
"messageRate:\n" +
|
||||
" enforceUnsealedSenderRateLimit: true";
|
||||
|
||||
final DynamicConfiguration emptyConfig = DynamicConfigurationManager.OBJECT_MAPPER
|
||||
.readValue(messageRateConfigYaml, DynamicConfiguration.class);
|
||||
final DynamicConfiguration emptyConfig =
|
||||
DynamicConfigurationManager.parseConfiguration(messageRateConfigYaml).orElseThrow();
|
||||
|
||||
assertTrue(emptyConfig.getMessageRateConfiguration().isEnforceUnsealedSenderRateLimit());
|
||||
}
|
||||
@@ -213,19 +214,19 @@ class DynamicConfigurationTest {
|
||||
void testParseFeatureFlags() throws JsonProcessingException {
|
||||
{
|
||||
final String emptyConfigYaml = "test: true";
|
||||
final DynamicConfiguration emptyConfig = DynamicConfigurationManager.OBJECT_MAPPER
|
||||
.readValue(emptyConfigYaml, DynamicConfiguration.class);
|
||||
final DynamicConfiguration emptyConfig =
|
||||
DynamicConfigurationManager.parseConfiguration(emptyConfigYaml).orElseThrow();
|
||||
|
||||
assertTrue(emptyConfig.getActiveFeatureFlags().isEmpty());
|
||||
}
|
||||
|
||||
{
|
||||
final String emptyConfigYaml =
|
||||
final String featureFlagYaml =
|
||||
"featureFlags:\n"
|
||||
+ " - testFlag";
|
||||
|
||||
final DynamicConfiguration emptyConfig = DynamicConfigurationManager.OBJECT_MAPPER
|
||||
.readValue(emptyConfigYaml, DynamicConfiguration.class);
|
||||
final DynamicConfiguration emptyConfig =
|
||||
DynamicConfigurationManager.parseConfiguration(featureFlagYaml).orElseThrow();
|
||||
|
||||
assertTrue(emptyConfig.getActiveFeatureFlags().contains("testFlag"));
|
||||
}
|
||||
@@ -235,22 +236,22 @@ class DynamicConfigurationTest {
|
||||
void testParseTwilioConfiguration() throws JsonProcessingException {
|
||||
{
|
||||
final String emptyConfigYaml = "test: true";
|
||||
final DynamicConfiguration emptyConfig = DynamicConfigurationManager.OBJECT_MAPPER
|
||||
.readValue(emptyConfigYaml, DynamicConfiguration.class);
|
||||
final DynamicConfiguration emptyConfig =
|
||||
DynamicConfigurationManager.parseConfiguration(emptyConfigYaml).orElseThrow();
|
||||
|
||||
assertTrue(emptyConfig.getTwilioConfiguration().getNumbers().isEmpty());
|
||||
}
|
||||
|
||||
{
|
||||
final String emptyConfigYaml =
|
||||
final String twilioConfigYaml =
|
||||
"twilio:\n"
|
||||
+ " numbers:\n"
|
||||
+ " - 2135551212\n"
|
||||
+ " - 2135551313";
|
||||
|
||||
final DynamicTwilioConfiguration config = DynamicConfigurationManager.OBJECT_MAPPER
|
||||
.readValue(emptyConfigYaml, DynamicConfiguration.class)
|
||||
.getTwilioConfiguration();
|
||||
final DynamicTwilioConfiguration config =
|
||||
DynamicConfigurationManager.parseConfiguration(twilioConfigYaml).orElseThrow()
|
||||
.getTwilioConfiguration();
|
||||
|
||||
assertEquals(List.of("2135551212", "2135551313"), config.getNumbers());
|
||||
}
|
||||
@@ -260,8 +261,8 @@ class DynamicConfigurationTest {
|
||||
void testParsePaymentsConfiguration() throws JsonProcessingException {
|
||||
{
|
||||
final String emptyConfigYaml = "test: true";
|
||||
final DynamicConfiguration emptyConfig = DynamicConfigurationManager.OBJECT_MAPPER
|
||||
.readValue(emptyConfigYaml, DynamicConfiguration.class);
|
||||
final DynamicConfiguration emptyConfig =
|
||||
DynamicConfigurationManager.parseConfiguration(emptyConfigYaml).orElseThrow();
|
||||
|
||||
assertTrue(emptyConfig.getPaymentsConfiguration().getAllowedCountryCodes().isEmpty());
|
||||
}
|
||||
@@ -272,9 +273,9 @@ class DynamicConfigurationTest {
|
||||
+ " allowedCountryCodes:\n"
|
||||
+ " - 44";
|
||||
|
||||
final DynamicPaymentsConfiguration config = DynamicConfigurationManager.OBJECT_MAPPER
|
||||
.readValue(paymentsConfigYaml, DynamicConfiguration.class)
|
||||
.getPaymentsConfiguration();
|
||||
final DynamicPaymentsConfiguration config =
|
||||
DynamicConfigurationManager.parseConfiguration(paymentsConfigYaml).orElseThrow()
|
||||
.getPaymentsConfiguration();
|
||||
|
||||
assertEquals(Set.of("44"), config.getAllowedCountryCodes());
|
||||
}
|
||||
@@ -284,8 +285,8 @@ class DynamicConfigurationTest {
|
||||
void testParseSignupCaptchaConfiguration() throws JsonProcessingException {
|
||||
{
|
||||
final String emptyConfigYaml = "test: true";
|
||||
final DynamicConfiguration emptyConfig = DynamicConfigurationManager.OBJECT_MAPPER
|
||||
.readValue(emptyConfigYaml, DynamicConfiguration.class);
|
||||
final DynamicConfiguration emptyConfig =
|
||||
DynamicConfigurationManager.parseConfiguration(emptyConfigYaml).orElseThrow();
|
||||
|
||||
assertTrue(emptyConfig.getSignupCaptchaConfiguration().getCountryCodes().isEmpty());
|
||||
}
|
||||
@@ -296,9 +297,9 @@ class DynamicConfigurationTest {
|
||||
+ " countryCodes:\n"
|
||||
+ " - 1";
|
||||
|
||||
final DynamicSignupCaptchaConfiguration config = DynamicConfigurationManager.OBJECT_MAPPER
|
||||
.readValue(signupCaptchaConfig, DynamicConfiguration.class)
|
||||
.getSignupCaptchaConfiguration();
|
||||
final DynamicSignupCaptchaConfiguration config =
|
||||
DynamicConfigurationManager.parseConfiguration(signupCaptchaConfig).orElseThrow()
|
||||
.getSignupCaptchaConfiguration();
|
||||
|
||||
assertEquals(Set.of("1"), config.getCountryCodes());
|
||||
}
|
||||
@@ -308,8 +309,8 @@ class DynamicConfigurationTest {
|
||||
void testParseAccountsDynamoDbMigrationConfiguration() throws JsonProcessingException {
|
||||
{
|
||||
final String emptyConfigYaml = "test: true";
|
||||
final DynamicConfiguration emptyConfig = DynamicConfigurationManager.OBJECT_MAPPER
|
||||
.readValue(emptyConfigYaml, DynamicConfiguration.class);
|
||||
final DynamicConfiguration emptyConfig =
|
||||
DynamicConfigurationManager.parseConfiguration(emptyConfigYaml).orElseThrow();
|
||||
|
||||
assertFalse(emptyConfig.getAccountsDynamoDbMigrationConfiguration().isBackgroundMigrationEnabled());
|
||||
assertFalse(emptyConfig.getAccountsDynamoDbMigrationConfiguration().isDeleteEnabled());
|
||||
@@ -326,9 +327,9 @@ class DynamicConfigurationTest {
|
||||
+ " readEnabled: true\n"
|
||||
+ " writeEnabled: true";
|
||||
|
||||
final DynamicAccountsDynamoDbMigrationConfiguration config = DynamicConfigurationManager.OBJECT_MAPPER
|
||||
.readValue(accountsDynamoDbMigrationConfig, DynamicConfiguration.class)
|
||||
.getAccountsDynamoDbMigrationConfiguration();
|
||||
final DynamicAccountsDynamoDbMigrationConfiguration config =
|
||||
DynamicConfigurationManager.parseConfiguration(accountsDynamoDbMigrationConfig).orElseThrow()
|
||||
.getAccountsDynamoDbMigrationConfiguration();
|
||||
|
||||
assertTrue(config.isBackgroundMigrationEnabled());
|
||||
assertEquals(100, config.getBackgroundMigrationExecutorThreads());
|
||||
@@ -342,8 +343,8 @@ class DynamicConfigurationTest {
|
||||
void testParseLimits() throws JsonProcessingException {
|
||||
{
|
||||
final String emptyConfigYaml = "test: true";
|
||||
final DynamicConfiguration emptyConfig = DynamicConfigurationManager.OBJECT_MAPPER.readValue(
|
||||
emptyConfigYaml, DynamicConfiguration.class);
|
||||
final DynamicConfiguration emptyConfig =
|
||||
DynamicConfigurationManager.parseConfiguration(emptyConfigYaml).orElseThrow();
|
||||
|
||||
assertThat(emptyConfig.getLimits().getUnsealedSenderNumber().getMaxCardinality()).isEqualTo(100);
|
||||
assertThat(emptyConfig.getLimits().getUnsealedSenderNumber().getTtl()).isEqualTo(Duration.ofDays(1));
|
||||
@@ -355,9 +356,10 @@ class DynamicConfigurationTest {
|
||||
+ " unsealedSenderNumber:\n"
|
||||
+ " maxCardinality: 99\n"
|
||||
+ " ttl: PT23H";
|
||||
final CardinalityRateLimitConfiguration unsealedSenderNumber = DynamicConfigurationManager.OBJECT_MAPPER
|
||||
.readValue(limitsConfig, DynamicConfiguration.class)
|
||||
.getLimits().getUnsealedSenderNumber();
|
||||
|
||||
final CardinalityRateLimitConfiguration unsealedSenderNumber =
|
||||
DynamicConfigurationManager.parseConfiguration(limitsConfig).orElseThrow()
|
||||
.getLimits().getUnsealedSenderNumber();
|
||||
|
||||
assertThat(unsealedSenderNumber.getMaxCardinality()).isEqualTo(99);
|
||||
assertThat(unsealedSenderNumber.getTtl()).isEqualTo(Duration.ofHours(23));
|
||||
@@ -368,8 +370,8 @@ class DynamicConfigurationTest {
|
||||
void testParseRateLimitReset() throws JsonProcessingException {
|
||||
{
|
||||
final String emptyConfigYaml = "test: true";
|
||||
final DynamicConfiguration emptyConfig = DynamicConfigurationManager.OBJECT_MAPPER.readValue(
|
||||
emptyConfigYaml, DynamicConfiguration.class);
|
||||
final DynamicConfiguration emptyConfig =
|
||||
DynamicConfigurationManager.parseConfiguration(emptyConfigYaml).orElseThrow();
|
||||
|
||||
assertThat(emptyConfig.getRateLimitChallengeConfiguration().getClientSupportedVersions()).isEmpty();
|
||||
assertThat(emptyConfig.getRateLimitChallengeConfiguration().isPreKeyLimitEnforced()).isFalse();
|
||||
@@ -384,9 +386,11 @@ class DynamicConfigurationTest {
|
||||
+ " IOS: 5.1.0\n"
|
||||
+ " ANDROID: 5.2.0\n"
|
||||
+ " DESKTOP: 5.0.0";
|
||||
DynamicRateLimitChallengeConfiguration rateLimitChallengeConfiguration = DynamicConfigurationManager.OBJECT_MAPPER
|
||||
.readValue(rateLimitChallengeConfig, DynamicConfiguration.class)
|
||||
.getRateLimitChallengeConfiguration();
|
||||
|
||||
DynamicRateLimitChallengeConfiguration rateLimitChallengeConfiguration =
|
||||
DynamicConfigurationManager.parseConfiguration(rateLimitChallengeConfig).orElseThrow()
|
||||
.getRateLimitChallengeConfiguration();
|
||||
|
||||
final Map<ClientPlatform, Semver> clientSupportedVersions = rateLimitChallengeConfiguration.getClientSupportedVersions();
|
||||
|
||||
assertThat(clientSupportedVersions.get(ClientPlatform.IOS)).isEqualTo(new Semver("5.1.0"));
|
||||
|
||||
+21
-23
@@ -5,17 +5,15 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.sqs;
|
||||
|
||||
import com.amazonaws.services.sqs.AmazonSQS;
|
||||
import com.amazonaws.services.sqs.model.MessageAttributeValue;
|
||||
import com.amazonaws.services.sqs.model.SendMessageBatchRequest;
|
||||
import com.amazonaws.services.sqs.model.SendMessageRequest;
|
||||
import junitparams.JUnitParamsRunner;
|
||||
import junitparams.Parameters;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import software.amazon.awssdk.services.sqs.SqsClient;
|
||||
import software.amazon.awssdk.services.sqs.model.MessageAttributeValue;
|
||||
import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequest;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -33,7 +31,7 @@ public class DirectoryQueueTest {
|
||||
@Test
|
||||
@Parameters(method = "argumentsForTestRefreshRegisteredUser")
|
||||
public void testRefreshRegisteredUser(final boolean accountEnabled, final boolean accountDiscoverableByPhoneNumber, final String expectedAction) {
|
||||
final AmazonSQS sqs = mock(AmazonSQS.class);
|
||||
final SqsClient sqs = mock(SqsClient.class);
|
||||
final DirectoryQueue directoryQueue = new DirectoryQueue(List.of("sqs://test"), sqs);
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
@@ -47,15 +45,15 @@ public class DirectoryQueueTest {
|
||||
final ArgumentCaptor<SendMessageBatchRequest> requestCaptor = ArgumentCaptor.forClass(SendMessageBatchRequest.class);
|
||||
verify(sqs).sendMessageBatch(requestCaptor.capture());
|
||||
|
||||
assertEquals(1, requestCaptor.getValue().getEntries().size());
|
||||
assertEquals(1, requestCaptor.getValue().entries().size());
|
||||
|
||||
final Map<String, MessageAttributeValue> messageAttributes = requestCaptor.getValue().getEntries().get(0).getMessageAttributes();
|
||||
assertEquals(new MessageAttributeValue().withDataType("String").withStringValue(expectedAction), messageAttributes.get("action"));
|
||||
final Map<String, MessageAttributeValue> messageAttributes = requestCaptor.getValue().entries().get(0).messageAttributes();
|
||||
assertEquals(MessageAttributeValue.builder().dataType("String").stringValue(expectedAction).build(), messageAttributes.get("action"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRefreshBatch() {
|
||||
final AmazonSQS sqs = mock(AmazonSQS.class);
|
||||
final SqsClient sqs = mock(SqsClient.class);
|
||||
final DirectoryQueue directoryQueue = new DirectoryQueue(List.of("sqs://test"), sqs);
|
||||
|
||||
final Account discoverableAccount = mock(Account.class);
|
||||
@@ -75,22 +73,22 @@ public class DirectoryQueueTest {
|
||||
final ArgumentCaptor<SendMessageBatchRequest> requestCaptor = ArgumentCaptor.forClass(SendMessageBatchRequest.class);
|
||||
verify(sqs).sendMessageBatch(requestCaptor.capture());
|
||||
|
||||
assertEquals(2, requestCaptor.getValue().getEntries().size());
|
||||
assertEquals(2, requestCaptor.getValue().entries().size());
|
||||
|
||||
final Map<String, MessageAttributeValue> discoverableAccountAttributes = requestCaptor.getValue().getEntries().get(0).getMessageAttributes();
|
||||
assertEquals(new MessageAttributeValue().withDataType("String").withStringValue(discoverableAccount.getNumber()), discoverableAccountAttributes.get("id"));
|
||||
assertEquals(new MessageAttributeValue().withDataType("String").withStringValue(discoverableAccount.getUuid().toString()), discoverableAccountAttributes.get("uuid"));
|
||||
assertEquals(new MessageAttributeValue().withDataType("String").withStringValue("add"), discoverableAccountAttributes.get("action"));
|
||||
final Map<String, MessageAttributeValue> discoverableAccountAttributes = requestCaptor.getValue().entries().get(0).messageAttributes();
|
||||
assertEquals(MessageAttributeValue.builder().dataType("String").stringValue(discoverableAccount.getNumber()).build(), discoverableAccountAttributes.get("id"));
|
||||
assertEquals(MessageAttributeValue.builder().dataType("String").stringValue(discoverableAccount.getUuid().toString()).build(), discoverableAccountAttributes.get("uuid"));
|
||||
assertEquals(MessageAttributeValue.builder().dataType("String").stringValue("add").build(), discoverableAccountAttributes.get("action"));
|
||||
|
||||
final Map<String, MessageAttributeValue> undiscoverableAccountAttributes = requestCaptor.getValue().getEntries().get(1).getMessageAttributes();
|
||||
assertEquals(new MessageAttributeValue().withDataType("String").withStringValue(undiscoverableAccount.getNumber()), undiscoverableAccountAttributes.get("id"));
|
||||
assertEquals(new MessageAttributeValue().withDataType("String").withStringValue(undiscoverableAccount.getUuid().toString()), undiscoverableAccountAttributes.get("uuid"));
|
||||
assertEquals(new MessageAttributeValue().withDataType("String").withStringValue("delete"), undiscoverableAccountAttributes.get("action"));
|
||||
final Map<String, MessageAttributeValue> undiscoverableAccountAttributes = requestCaptor.getValue().entries().get(1).messageAttributes();
|
||||
assertEquals(MessageAttributeValue.builder().dataType("String").stringValue(undiscoverableAccount.getNumber()).build(), undiscoverableAccountAttributes.get("id"));
|
||||
assertEquals(MessageAttributeValue.builder().dataType("String").stringValue(undiscoverableAccount.getUuid().toString()).build(), undiscoverableAccountAttributes.get("uuid"));
|
||||
assertEquals(MessageAttributeValue.builder().dataType("String").stringValue("delete").build(), undiscoverableAccountAttributes.get("action"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSendMessageMultipleQueues() {
|
||||
final AmazonSQS sqs = mock(AmazonSQS.class);
|
||||
final SqsClient sqs = mock(SqsClient.class);
|
||||
final DirectoryQueue directoryQueue = new DirectoryQueue(List.of("sqs://first", "sqs://second"), sqs);
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
@@ -105,10 +103,10 @@ public class DirectoryQueueTest {
|
||||
verify(sqs, times(2)).sendMessageBatch(requestCaptor.capture());
|
||||
|
||||
for (final SendMessageBatchRequest sendMessageBatchRequest : requestCaptor.getAllValues()) {
|
||||
assertEquals(1, requestCaptor.getValue().getEntries().size());
|
||||
assertEquals(1, requestCaptor.getValue().entries().size());
|
||||
|
||||
final Map<String, MessageAttributeValue> messageAttributes = sendMessageBatchRequest.getEntries().get(0).getMessageAttributes();
|
||||
assertEquals(new MessageAttributeValue().withDataType("String").withStringValue("add"), messageAttributes.get("action"));
|
||||
final Map<String, MessageAttributeValue> messageAttributes = sendMessageBatchRequest.entries().get(0).messageAttributes();
|
||||
assertEquals(MessageAttributeValue.builder().dataType("String").stringValue("add").build(), messageAttributes.get("action"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+98
-64
@@ -11,26 +11,12 @@ import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBAsync;
|
||||
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.document.Item;
|
||||
import com.amazonaws.services.dynamodbv2.document.Page;
|
||||
import com.amazonaws.services.dynamodbv2.document.ScanOutcome;
|
||||
import com.amazonaws.services.dynamodbv2.document.Table;
|
||||
import com.amazonaws.services.dynamodbv2.document.spec.GetItemSpec;
|
||||
import com.amazonaws.services.dynamodbv2.document.spec.ScanSpec;
|
||||
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
|
||||
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException;
|
||||
import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
|
||||
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
|
||||
import com.amazonaws.services.dynamodbv2.model.KeyType;
|
||||
import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType;
|
||||
import io.github.resilience4j.circuitbreaker.CallNotPermittedException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Random;
|
||||
import java.util.Set;
|
||||
@@ -46,62 +32,103 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.SignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
|
||||
import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;
|
||||
import software.amazon.awssdk.services.dynamodb.model.KeyType;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ScanRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ScanResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
|
||||
|
||||
class AccountsDynamoDbTest {
|
||||
|
||||
private static final String ACCOUNTS_TABLE_NAME = "accounts_test";
|
||||
private static final String NUMBERS_TABLE_NAME = "numbers_test";
|
||||
private static final String MIGRATION_DELETED_ACCOUNTS_TABLE_NAME = "migration_deleted_accounts_test";
|
||||
private static final String MIGRATION_RETRY_ACCOUNTS_TABLE_NAME = "miration_retry_accounts_test";
|
||||
private static final String MIGRATION_RETRY_ACCOUNTS_TABLE_NAME = "migration_retry_accounts_test";
|
||||
|
||||
@RegisterExtension
|
||||
static DynamoDbExtension dynamoDbExtension = DynamoDbExtension.builder()
|
||||
.tableName(ACCOUNTS_TABLE_NAME)
|
||||
.hashKey(AccountsDynamoDb.KEY_ACCOUNT_UUID)
|
||||
.attributeDefinition(new AttributeDefinition(AccountsDynamoDb.KEY_ACCOUNT_UUID, ScalarAttributeType.B))
|
||||
.attributeDefinition(AttributeDefinition.builder()
|
||||
.attributeName(AccountsDynamoDb.KEY_ACCOUNT_UUID)
|
||||
.attributeType(ScalarAttributeType.B)
|
||||
.build())
|
||||
.build();
|
||||
|
||||
private AccountsDynamoDb accountsDynamoDb;
|
||||
|
||||
private Table migrationDeletedAccountsTable;
|
||||
private Table migrationRetryAccountsTable;
|
||||
|
||||
@BeforeEach
|
||||
void setupAccountsDao() {
|
||||
CreateTableRequest createNumbersTableRequest = CreateTableRequest.builder()
|
||||
.tableName(NUMBERS_TABLE_NAME)
|
||||
.keySchema(KeySchemaElement.builder()
|
||||
.attributeName(AccountsDynamoDb.ATTR_ACCOUNT_E164)
|
||||
.keyType(KeyType.HASH)
|
||||
.build())
|
||||
.attributeDefinitions(AttributeDefinition.builder()
|
||||
.attributeName(AccountsDynamoDb.ATTR_ACCOUNT_E164)
|
||||
.attributeType(ScalarAttributeType.S)
|
||||
.build())
|
||||
.provisionedThroughput(DynamoDbExtension.DEFAULT_PROVISIONED_THROUGHPUT)
|
||||
.build();
|
||||
|
||||
CreateTableRequest createNumbersTableRequest = new CreateTableRequest()
|
||||
.withTableName(NUMBERS_TABLE_NAME)
|
||||
.withKeySchema(new KeySchemaElement(AccountsDynamoDb.ATTR_ACCOUNT_E164, KeyType.HASH))
|
||||
.withAttributeDefinitions(new AttributeDefinition(AccountsDynamoDb.ATTR_ACCOUNT_E164, ScalarAttributeType.S))
|
||||
.withProvisionedThroughput(DynamoDbExtension.DEFAULT_PROVISIONED_THROUGHPUT);
|
||||
dynamoDbExtension.getDynamoDbClient().createTable(createNumbersTableRequest);
|
||||
|
||||
final Table numbersTable = dynamoDbExtension.getDynamoDB().createTable(createNumbersTableRequest);
|
||||
final CreateTableRequest createMigrationDeletedAccountsTableRequest = CreateTableRequest.builder()
|
||||
.tableName(MIGRATION_DELETED_ACCOUNTS_TABLE_NAME)
|
||||
.keySchema(KeySchemaElement.builder()
|
||||
.attributeName(MigrationDeletedAccounts.KEY_UUID)
|
||||
.keyType(KeyType.HASH)
|
||||
.build())
|
||||
.attributeDefinitions(AttributeDefinition.builder()
|
||||
.attributeName(MigrationDeletedAccounts.KEY_UUID)
|
||||
.attributeType(ScalarAttributeType.B)
|
||||
.build())
|
||||
.provisionedThroughput(DynamoDbExtension.DEFAULT_PROVISIONED_THROUGHPUT)
|
||||
.build();
|
||||
|
||||
final CreateTableRequest createMigrationDeletedAccountsTableRequest = new CreateTableRequest()
|
||||
.withTableName(MIGRATION_DELETED_ACCOUNTS_TABLE_NAME)
|
||||
.withKeySchema(new KeySchemaElement(MigrationDeletedAccounts.KEY_UUID, KeyType.HASH))
|
||||
.withAttributeDefinitions(new AttributeDefinition(MigrationDeletedAccounts.KEY_UUID, ScalarAttributeType.B))
|
||||
.withProvisionedThroughput(DynamoDbExtension.DEFAULT_PROVISIONED_THROUGHPUT);
|
||||
dynamoDbExtension.getDynamoDbClient().createTable(createMigrationDeletedAccountsTableRequest);
|
||||
|
||||
migrationDeletedAccountsTable = dynamoDbExtension.getDynamoDB().createTable(createMigrationDeletedAccountsTableRequest);
|
||||
MigrationDeletedAccounts migrationDeletedAccounts = new MigrationDeletedAccounts(
|
||||
dynamoDbExtension.getDynamoDbClient(), MIGRATION_DELETED_ACCOUNTS_TABLE_NAME);
|
||||
|
||||
MigrationDeletedAccounts migrationDeletedAccounts = new MigrationDeletedAccounts(dynamoDbExtension.getDynamoDB(),
|
||||
migrationDeletedAccountsTable.getTableName());
|
||||
final CreateTableRequest createMigrationRetryAccountsTableRequest = CreateTableRequest.builder()
|
||||
.tableName(MIGRATION_RETRY_ACCOUNTS_TABLE_NAME)
|
||||
.keySchema(KeySchemaElement.builder()
|
||||
.attributeName(MigrationRetryAccounts.KEY_UUID)
|
||||
.keyType(KeyType.HASH)
|
||||
.build())
|
||||
.attributeDefinitions(AttributeDefinition.builder()
|
||||
.attributeName(MigrationRetryAccounts.KEY_UUID)
|
||||
.attributeType(ScalarAttributeType.B)
|
||||
.build())
|
||||
.provisionedThroughput(DynamoDbExtension.DEFAULT_PROVISIONED_THROUGHPUT)
|
||||
.build();
|
||||
|
||||
final CreateTableRequest createMigrationRetryAccountsTableRequest = new CreateTableRequest()
|
||||
.withTableName(MIGRATION_RETRY_ACCOUNTS_TABLE_NAME)
|
||||
.withKeySchema(new KeySchemaElement(MigrationRetryAccounts.KEY_UUID, KeyType.HASH))
|
||||
.withAttributeDefinitions(new AttributeDefinition(MigrationRetryAccounts.KEY_UUID, ScalarAttributeType.B))
|
||||
.withProvisionedThroughput(DynamoDbExtension.DEFAULT_PROVISIONED_THROUGHPUT);
|
||||
dynamoDbExtension.getDynamoDbClient().createTable(createMigrationRetryAccountsTableRequest);
|
||||
|
||||
migrationRetryAccountsTable = dynamoDbExtension.getDynamoDB().createTable(createMigrationRetryAccountsTableRequest);
|
||||
MigrationRetryAccounts migrationRetryAccounts = new MigrationRetryAccounts((dynamoDbExtension.getDynamoDbClient()),
|
||||
MIGRATION_RETRY_ACCOUNTS_TABLE_NAME);
|
||||
|
||||
MigrationRetryAccounts migrationRetryAccounts = new MigrationRetryAccounts((dynamoDbExtension.getDynamoDB()),
|
||||
migrationRetryAccountsTable.getTableName());
|
||||
|
||||
this.accountsDynamoDb = new AccountsDynamoDb(dynamoDbExtension.getClient(), dynamoDbExtension.getAsyncClient(), new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS, new LinkedBlockingDeque<>()), dynamoDbExtension.getDynamoDB(), dynamoDbExtension.getTableName(), numbersTable.getTableName(),
|
||||
migrationDeletedAccounts, migrationRetryAccounts);
|
||||
this.accountsDynamoDb = new AccountsDynamoDb(
|
||||
dynamoDbExtension.getDynamoDbClient(),
|
||||
dynamoDbExtension.getDynamoDbAsyncClient(),
|
||||
new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS, new LinkedBlockingDeque<>()),
|
||||
dynamoDbExtension.getTableName(),
|
||||
NUMBERS_TABLE_NAME,
|
||||
migrationDeletedAccounts,
|
||||
migrationRetryAccounts);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -262,8 +289,12 @@ class AccountsDynamoDbTest {
|
||||
|
||||
verifyRecentlyDeletedAccountsTableItemCount(1);
|
||||
|
||||
assertThat(migrationDeletedAccountsTable
|
||||
.getItem(MigrationDeletedAccounts.primaryKey(deletedAccount.getUuid()))).isNotNull();
|
||||
Map<String, AttributeValue> primaryKey = MigrationDeletedAccounts.primaryKey(deletedAccount.getUuid());
|
||||
assertThat(dynamoDbExtension.getDynamoDbClient().getItem(GetItemRequest.builder()
|
||||
.tableName(MIGRATION_DELETED_ACCOUNTS_TABLE_NAME)
|
||||
.key(Map.of(MigrationDeletedAccounts.KEY_UUID, primaryKey.get(MigrationDeletedAccounts.KEY_UUID)))
|
||||
.build()))
|
||||
.isNotNull();
|
||||
|
||||
accountsDynamoDb.deleteRecentlyDeletedUuids();
|
||||
|
||||
@@ -273,8 +304,10 @@ class AccountsDynamoDbTest {
|
||||
private void verifyRecentlyDeletedAccountsTableItemCount(int expectedItemCount) {
|
||||
int totalItems = 0;
|
||||
|
||||
for (Page<Item, ScanOutcome> page : migrationDeletedAccountsTable.scan(new ScanSpec()).pages()) {
|
||||
for (Item ignored : page) {
|
||||
for (ScanResponse page : dynamoDbExtension.getDynamoDbClient().scanPaginator(ScanRequest.builder()
|
||||
.tableName(MIGRATION_DELETED_ACCOUNTS_TABLE_NAME)
|
||||
.build())) {
|
||||
for (Map<String, AttributeValue> item : page.items()) {
|
||||
totalItems++;
|
||||
}
|
||||
}
|
||||
@@ -306,16 +339,15 @@ class AccountsDynamoDbTest {
|
||||
configuration.setRingBufferSizeInClosedState(2);
|
||||
configuration.setFailureRateThreshold(50);
|
||||
|
||||
final AmazonDynamoDB client = mock(AmazonDynamoDB.class);
|
||||
final DynamoDB dynamoDB = new DynamoDB(client);
|
||||
final DynamoDbClient client = mock(DynamoDbClient.class);
|
||||
|
||||
when(client.transactWriteItems(any()))
|
||||
when(client.transactWriteItems(any(TransactWriteItemsRequest.class)))
|
||||
.thenThrow(RuntimeException.class);
|
||||
|
||||
when(client.updateItem(any()))
|
||||
when(client.updateItem(any(UpdateItemRequest.class)))
|
||||
.thenThrow(RuntimeException.class);
|
||||
|
||||
AccountsDynamoDb accounts = new AccountsDynamoDb(client, mock(AmazonDynamoDBAsync.class), mock(ThreadPoolExecutor.class), dynamoDB, ACCOUNTS_TABLE_NAME, NUMBERS_TABLE_NAME, mock(
|
||||
AccountsDynamoDb accounts = new AccountsDynamoDb(client, mock(DynamoDbAsyncClient.class), mock(ThreadPoolExecutor.class), ACCOUNTS_TABLE_NAME, NUMBERS_TABLE_NAME, mock(
|
||||
MigrationDeletedAccounts.class), mock(MigrationRetryAccounts.class));
|
||||
Account account = generateAccount("+14151112222", UUID.randomUUID());
|
||||
|
||||
@@ -391,7 +423,7 @@ class AccountsDynamoDbTest {
|
||||
SignedPreKey signedPreKey = new SignedPreKey(random.nextInt(), "testPublicKey-" + random.nextInt(), "testSignature-" + random.nextInt());
|
||||
return new Device(id, "testName-" + random.nextInt(), "testAuthToken-" + random.nextInt(), "testSalt-" + random.nextInt(),
|
||||
"testGcmId-" + random.nextInt(), "testApnId-" + random.nextInt(), "testVoipApnId-" + random.nextInt(), random.nextBoolean(), random.nextInt(), signedPreKey, random.nextInt(), random.nextInt(), "testUserAgent-" + random.nextInt() , 0, new Device.DeviceCapabilities(random.nextBoolean(), random.nextBoolean(), random.nextBoolean(), random.nextBoolean(), random.nextBoolean(), random.nextBoolean(),
|
||||
false));
|
||||
random.nextBoolean(), random.nextBoolean()));
|
||||
}
|
||||
|
||||
private Account generateAccount(String number, UUID uuid) {
|
||||
@@ -408,20 +440,22 @@ class AccountsDynamoDbTest {
|
||||
}
|
||||
|
||||
private void verifyStoredState(String number, UUID uuid, Account expecting) {
|
||||
final Table accounts = dynamoDbExtension.getDynamoDB().getTable(dynamoDbExtension.getTableName());
|
||||
final DynamoDbClient db = dynamoDbExtension.getDynamoDbClient();
|
||||
|
||||
Item item = accounts.getItem(new GetItemSpec()
|
||||
.withPrimaryKey(AccountsDynamoDb.KEY_ACCOUNT_UUID, UUIDUtil.toByteBuffer(uuid))
|
||||
.withConsistentRead(true));
|
||||
final GetItemResponse get = db.getItem(GetItemRequest.builder()
|
||||
.tableName(dynamoDbExtension.getTableName())
|
||||
.key(Map.of(AccountsDynamoDb.KEY_ACCOUNT_UUID, AttributeValues.fromUUID(uuid)))
|
||||
.consistentRead(true)
|
||||
.build());
|
||||
|
||||
if (item != null) {
|
||||
String data = new String(item.getBinary(AccountsDynamoDb.ATTR_ACCOUNT_DATA), StandardCharsets.UTF_8);
|
||||
if (get.hasItem()) {
|
||||
String data = new String(get.item().get(AccountsDynamoDb.ATTR_ACCOUNT_DATA).b().asByteArray(), StandardCharsets.UTF_8);
|
||||
assertThat(data).isNotEmpty();
|
||||
|
||||
assertThat(item.getNumber(AccountsDynamoDb.ATTR_MIGRATION_VERSION).intValue())
|
||||
assertThat(AttributeValues.getInt(get.item(), AccountsDynamoDb.ATTR_MIGRATION_VERSION, -1))
|
||||
.isEqualTo(expecting.getDynamoDbMigrationVersion());
|
||||
|
||||
Account result = AccountsDynamoDb.fromItem(item);
|
||||
Account result = AccountsDynamoDb.fromItem(get.item());
|
||||
verifyStoredState(number, uuid, result, expecting);
|
||||
} else {
|
||||
throw new AssertionError("No data");
|
||||
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex;
|
||||
import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;
|
||||
import software.amazon.awssdk.services.dynamodb.model.KeyType;
|
||||
import software.amazon.awssdk.services.dynamodb.model.Projection;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ProjectionType;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;
|
||||
|
||||
class DeletedAccountsTest {
|
||||
|
||||
private static final String NEEDS_RECONCILIATION_INDEX_NAME = "needs_reconciliation_test";
|
||||
|
||||
@RegisterExtension
|
||||
static DynamoDbExtension dynamoDbExtension = DynamoDbExtension.builder()
|
||||
.tableName("deleted_accounts_test")
|
||||
.hashKey(DeletedAccounts.KEY_ACCOUNT_E164)
|
||||
.attributeDefinition(AttributeDefinition.builder()
|
||||
.attributeName(DeletedAccounts.KEY_ACCOUNT_E164)
|
||||
.attributeType(ScalarAttributeType.S).build())
|
||||
.attributeDefinition(AttributeDefinition.builder()
|
||||
.attributeName(DeletedAccounts.ATTR_NEEDS_CDS_RECONCILIATION)
|
||||
.attributeType(ScalarAttributeType.N)
|
||||
.build())
|
||||
.globalSecondaryIndex(GlobalSecondaryIndex.builder()
|
||||
.indexName(NEEDS_RECONCILIATION_INDEX_NAME)
|
||||
.keySchema(KeySchemaElement.builder().attributeName(DeletedAccounts.KEY_ACCOUNT_E164).keyType(KeyType.HASH).build(),
|
||||
KeySchemaElement.builder().attributeName(DeletedAccounts.ATTR_NEEDS_CDS_RECONCILIATION).keyType(KeyType.RANGE).build())
|
||||
.projection(Projection.builder().projectionType(ProjectionType.INCLUDE).nonKeyAttributes(DeletedAccounts.ATTR_ACCOUNT_UUID).build())
|
||||
.provisionedThroughput(ProvisionedThroughput.builder().readCapacityUnits(10L).writeCapacityUnits(10L).build())
|
||||
.build())
|
||||
.build();
|
||||
|
||||
@Test
|
||||
void test() {
|
||||
|
||||
final DeletedAccounts deletedAccounts = new DeletedAccounts(dynamoDbExtension.getDynamoDbClient(),
|
||||
dynamoDbExtension.getTableName(),
|
||||
NEEDS_RECONCILIATION_INDEX_NAME);
|
||||
|
||||
UUID firstUuid = UUID.randomUUID();
|
||||
UUID secondUuid = UUID.randomUUID();
|
||||
UUID thirdUuid = UUID.randomUUID();
|
||||
|
||||
String firstNumber = "+14152221234";
|
||||
String secondNumber = "+14152225678";
|
||||
String thirdNumber = "+14159998765";
|
||||
|
||||
assertTrue(deletedAccounts.listAccountsToReconcile(1).isEmpty());
|
||||
|
||||
deletedAccounts.put(firstUuid, firstNumber);
|
||||
deletedAccounts.put(secondUuid, secondNumber);
|
||||
deletedAccounts.put(thirdUuid, thirdNumber);
|
||||
|
||||
assertEquals(1, deletedAccounts.listAccountsToReconcile(1).size());
|
||||
|
||||
assertTrue(deletedAccounts.listAccountsToReconcile(10).containsAll(
|
||||
List.of(
|
||||
new Pair<>(firstUuid, firstNumber),
|
||||
new Pair<>(secondUuid, secondNumber))));
|
||||
|
||||
deletedAccounts.markReconciled(List.of(firstNumber, secondNumber));
|
||||
|
||||
assertEquals(List.of(new Pair<>(thirdUuid, thirdNumber)), deletedAccounts.listAccountsToReconcile(10));
|
||||
|
||||
deletedAccounts.markReconciled(List.of(thirdNumber));
|
||||
|
||||
assertTrue(deletedAccounts.listAccountsToReconcile(1).isEmpty());
|
||||
}
|
||||
}
|
||||
@@ -70,7 +70,7 @@ public class DeviceTest {
|
||||
@Parameters(method = "argumentsForTestIsGroupsV2Supported")
|
||||
public void testIsGroupsV2Supported(final boolean master, final String apnId, final boolean gv2Capability, final boolean gv2_2Capability, final boolean gv2_3Capability, final boolean expectGv2Supported) {
|
||||
final Device.DeviceCapabilities capabilities = new Device.DeviceCapabilities(gv2Capability, gv2_2Capability, gv2_3Capability, false, false, false,
|
||||
false);
|
||||
false, false);
|
||||
final Device device = new Device(master ? 1 : 2, "test", "auth-token", "salt",
|
||||
null, apnId, null, false, 1, null, 0, 0, "user-agent", 0, capabilities);
|
||||
|
||||
|
||||
+53
-49
@@ -1,33 +1,35 @@
|
||||
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.AmazonDynamoDBAsync;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBAsyncClientBuilder;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
|
||||
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.local.main.ServerRunner;
|
||||
import com.amazonaws.services.dynamodbv2.local.server.DynamoDBProxyServer;
|
||||
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
|
||||
import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
|
||||
import com.amazonaws.services.dynamodbv2.model.GlobalSecondaryIndex;
|
||||
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
|
||||
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.URI;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.extension.AfterEachCallback;
|
||||
import org.junit.jupiter.api.extension.BeforeEachCallback;
|
||||
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
|
||||
import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex;
|
||||
import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;
|
||||
import software.amazon.awssdk.services.dynamodb.model.KeyType;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput;
|
||||
|
||||
public class DynamoDbExtension implements BeforeEachCallback, AfterEachCallback {
|
||||
|
||||
static final String DEFAULT_TABLE_NAME = "test_table";
|
||||
|
||||
static final ProvisionedThroughput DEFAULT_PROVISIONED_THROUGHPUT = new ProvisionedThroughput(20L, 20L);
|
||||
static final ProvisionedThroughput DEFAULT_PROVISIONED_THROUGHPUT = ProvisionedThroughput.builder()
|
||||
.readCapacityUnits(20L)
|
||||
.writeCapacityUnits(20L)
|
||||
.build();
|
||||
|
||||
private DynamoDBProxyServer server;
|
||||
private int port;
|
||||
@@ -42,9 +44,8 @@ public class DynamoDbExtension implements BeforeEachCallback, AfterEachCallback
|
||||
private final long readCapacityUnits;
|
||||
private final long writeCapacityUnits;
|
||||
|
||||
private AmazonDynamoDB client;
|
||||
private AmazonDynamoDBAsync asyncClient;
|
||||
private DynamoDB dynamoDB;
|
||||
private DynamoDbClient dynamoDB2;
|
||||
private DynamoDbAsyncClient dynamoAsyncDB2;
|
||||
|
||||
private DynamoDbExtension(String tableName, String hashKey, String rangeKey, List<AttributeDefinition> attributeDefinitions, List<GlobalSecondaryIndex> globalSecondaryIndexes, long readCapacityUnits,
|
||||
long writeCapacityUnits) {
|
||||
@@ -87,26 +88,33 @@ public class DynamoDbExtension implements BeforeEachCallback, AfterEachCallback
|
||||
KeySchemaElement[] keySchemaElements;
|
||||
if (rangeKeyName == null) {
|
||||
keySchemaElements = new KeySchemaElement[] {
|
||||
new KeySchemaElement(hashKeyName, "HASH"),
|
||||
KeySchemaElement.builder().attributeName(hashKeyName).keyType(KeyType.HASH).build(),
|
||||
};
|
||||
} else {
|
||||
keySchemaElements = new KeySchemaElement[] {
|
||||
new KeySchemaElement(hashKeyName, "HASH"),
|
||||
new KeySchemaElement(rangeKeyName, "RANGE")
|
||||
KeySchemaElement.builder().attributeName(hashKeyName).keyType(KeyType.HASH).build(),
|
||||
KeySchemaElement.builder().attributeName(rangeKeyName).keyType(KeyType.RANGE).build(),
|
||||
};
|
||||
}
|
||||
|
||||
final CreateTableRequest createTableRequest = new CreateTableRequest()
|
||||
.withTableName(tableName)
|
||||
.withKeySchema(keySchemaElements)
|
||||
.withAttributeDefinitions(attributeDefinitions.isEmpty() ? null : attributeDefinitions)
|
||||
.withGlobalSecondaryIndexes(globalSecondaryIndexes.isEmpty() ? null : globalSecondaryIndexes)
|
||||
.withProvisionedThroughput(new ProvisionedThroughput(readCapacityUnits, writeCapacityUnits));
|
||||
final CreateTableRequest createTableRequest = CreateTableRequest.builder()
|
||||
.tableName(tableName)
|
||||
.keySchema(keySchemaElements)
|
||||
.attributeDefinitions(attributeDefinitions.isEmpty() ? null : attributeDefinitions)
|
||||
.globalSecondaryIndexes(globalSecondaryIndexes.isEmpty() ? null : globalSecondaryIndexes)
|
||||
.provisionedThroughput(ProvisionedThroughput.builder()
|
||||
.readCapacityUnits(readCapacityUnits)
|
||||
.writeCapacityUnits(writeCapacityUnits)
|
||||
.build())
|
||||
.build();
|
||||
|
||||
getDynamoDB().createTable(createTableRequest);
|
||||
getDynamoDbClient().createTable(createTableRequest);
|
||||
}
|
||||
|
||||
private void startServer() throws Exception {
|
||||
// Even though we're using AWS SDK v2, Dynamo's local implementation's canonical location
|
||||
// is within v1 (https://github.com/aws/aws-sdk-java-v2/issues/982). This does support
|
||||
// v2 clients, though.
|
||||
SQLite.setLibraryPath("target/lib"); // if you see a library failed to load error, you need to run mvn test-compile at least once first
|
||||
ServerSocket serverSocket = new ServerSocket(0);
|
||||
serverSocket.setReuseAddress(false);
|
||||
@@ -117,18 +125,18 @@ public class DynamoDbExtension implements BeforeEachCallback, AfterEachCallback
|
||||
}
|
||||
|
||||
private void initializeClient() {
|
||||
AmazonDynamoDBClientBuilder clientBuilder = AmazonDynamoDBClientBuilder.standard()
|
||||
.withEndpointConfiguration(
|
||||
new AwsClientBuilder.EndpointConfiguration("http://localhost:" + port, "local-test-region"))
|
||||
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("accessKey", "secretKey")));
|
||||
client = clientBuilder.build();
|
||||
|
||||
asyncClient = AmazonDynamoDBAsyncClientBuilder.standard()
|
||||
.withEndpointConfiguration(clientBuilder.getEndpoint())
|
||||
.withCredentials(clientBuilder.getCredentials())
|
||||
.build();
|
||||
|
||||
dynamoDB = new DynamoDB(client);
|
||||
dynamoDB2 = DynamoDbClient.builder()
|
||||
.endpointOverride(URI.create("http://localhost:" + port))
|
||||
.region(Region.of("local-test-region"))
|
||||
.credentialsProvider(StaticCredentialsProvider.create(
|
||||
AwsBasicCredentials.create("accessKey", "secretKey")))
|
||||
.build();
|
||||
dynamoAsyncDB2 = DynamoDbAsyncClient.builder()
|
||||
.endpointOverride(URI.create("http://localhost:" + port))
|
||||
.region(Region.of("local-test-region"))
|
||||
.credentialsProvider(StaticCredentialsProvider.create(
|
||||
AwsBasicCredentials.create("accessKey", "secretKey")))
|
||||
.build();
|
||||
}
|
||||
|
||||
static class DynamoDbExtensionBuilder {
|
||||
@@ -140,8 +148,8 @@ public class DynamoDbExtension implements BeforeEachCallback, AfterEachCallback
|
||||
private List<AttributeDefinition> attributeDefinitions = new ArrayList<>();
|
||||
private List<GlobalSecondaryIndex> globalSecondaryIndexes = new ArrayList<>();
|
||||
|
||||
private long readCapacityUnits = DEFAULT_PROVISIONED_THROUGHPUT.getReadCapacityUnits();
|
||||
private long writeCapacityUnits = DEFAULT_PROVISIONED_THROUGHPUT.getWriteCapacityUnits();
|
||||
private long readCapacityUnits = DEFAULT_PROVISIONED_THROUGHPUT.readCapacityUnits();
|
||||
private long writeCapacityUnits = DEFAULT_PROVISIONED_THROUGHPUT.writeCapacityUnits();
|
||||
|
||||
private DynamoDbExtensionBuilder() {
|
||||
|
||||
@@ -178,16 +186,12 @@ public class DynamoDbExtension implements BeforeEachCallback, AfterEachCallback
|
||||
}
|
||||
}
|
||||
|
||||
public AmazonDynamoDB getClient() {
|
||||
return client;
|
||||
public DynamoDbClient getDynamoDbClient() {
|
||||
return dynamoDB2;
|
||||
}
|
||||
|
||||
public AmazonDynamoDBAsync getAsyncClient() {
|
||||
return asyncClient;
|
||||
}
|
||||
|
||||
public DynamoDB getDynamoDB() {
|
||||
return dynamoDB;
|
||||
public DynamoDbAsyncClient getDynamoDbAsyncClient() {
|
||||
return dynamoAsyncDB2;
|
||||
}
|
||||
|
||||
public String getTableName() {
|
||||
|
||||
+22
-18
@@ -5,13 +5,13 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
|
||||
import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
|
||||
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
|
||||
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
|
||||
import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType;
|
||||
import org.whispersystems.textsecuregcm.tests.util.LocalDynamoDbRule;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
|
||||
import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;
|
||||
import software.amazon.awssdk.services.dynamodb.model.KeyType;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;
|
||||
|
||||
public class KeysDynamoDbRule extends LocalDynamoDbRule {
|
||||
public static final String TABLE_NAME = "Signal_Keys_Test";
|
||||
@@ -19,18 +19,22 @@ public class KeysDynamoDbRule extends LocalDynamoDbRule {
|
||||
@Override
|
||||
protected void before() throws Throwable {
|
||||
super.before();
|
||||
|
||||
final DynamoDB dynamoDB = getDynamoDB();
|
||||
|
||||
final CreateTableRequest createTableRequest = new CreateTableRequest()
|
||||
.withTableName(TABLE_NAME)
|
||||
.withKeySchema(new KeySchemaElement(KeysDynamoDb.KEY_ACCOUNT_UUID, "HASH"),
|
||||
new KeySchemaElement(KeysDynamoDb.KEY_DEVICE_ID_KEY_ID, "RANGE"))
|
||||
.withAttributeDefinitions(new AttributeDefinition(KeysDynamoDb.KEY_ACCOUNT_UUID, ScalarAttributeType.B),
|
||||
new AttributeDefinition(KeysDynamoDb.KEY_DEVICE_ID_KEY_ID, ScalarAttributeType.B))
|
||||
.withProvisionedThroughput(new ProvisionedThroughput(20L, 20L));
|
||||
|
||||
dynamoDB.createTable(createTableRequest);
|
||||
getDynamoDbClient().createTable(CreateTableRequest.builder()
|
||||
.tableName(TABLE_NAME)
|
||||
.keySchema(
|
||||
KeySchemaElement.builder().attributeName(KeysDynamoDb.KEY_ACCOUNT_UUID).keyType(KeyType.HASH).build(),
|
||||
KeySchemaElement.builder().attributeName(KeysDynamoDb.KEY_DEVICE_ID_KEY_ID).keyType(KeyType.RANGE)
|
||||
.build())
|
||||
.attributeDefinitions(AttributeDefinition.builder()
|
||||
.attributeName(KeysDynamoDb.KEY_ACCOUNT_UUID)
|
||||
.attributeType(ScalarAttributeType.B)
|
||||
.build(),
|
||||
AttributeDefinition.builder()
|
||||
.attributeName(KeysDynamoDb.KEY_DEVICE_ID_KEY_ID)
|
||||
.attributeType(ScalarAttributeType.B)
|
||||
.build())
|
||||
.provisionedThroughput(ProvisionedThroughput.builder().readCapacityUnits(20L).writeCapacityUnits(20L).build())
|
||||
.build());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+9
-1
@@ -9,6 +9,7 @@ import org.junit.Before;
|
||||
import org.junit.ClassRule;
|
||||
import org.junit.Test;
|
||||
import org.whispersystems.textsecuregcm.entities.PreKey;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
@@ -17,6 +18,7 @@ import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -34,7 +36,7 @@ public class KeysDynamoDbTest {
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
keysDynamoDb = new KeysDynamoDb(dynamoDbRule.getDynamoDB(), KeysDynamoDbRule.TABLE_NAME);
|
||||
keysDynamoDb = new KeysDynamoDb(dynamoDbRule.getDynamoDbClient(), KeysDynamoDbRule.TABLE_NAME);
|
||||
|
||||
account = mock(Account.class);
|
||||
when(account.getNumber()).thenReturn(ACCOUNT_NUMBER);
|
||||
@@ -133,4 +135,10 @@ public class KeysDynamoDbTest {
|
||||
assertEquals(0, keysDynamoDb.getCount(account, DEVICE_ID));
|
||||
assertEquals(1, keysDynamoDb.getCount(account, DEVICE_ID + 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSortKeyPrefix() {
|
||||
AttributeValue got = KeysDynamoDb.getSortKeyPrefix(123);
|
||||
assertArrayEquals(new byte[]{0, 0, 0, 0, 0, 0, 0, 123}, got.b().asByteArray());
|
||||
}
|
||||
}
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.atLeastOnce;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
class ManagedPeriodicWorkTest {
|
||||
|
||||
private ScheduledExecutorService scheduledExecutorService;
|
||||
private ManagedPeriodicWorkLock lock;
|
||||
private TestWork testWork;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
|
||||
lock = mock(ManagedPeriodicWorkLock.class);
|
||||
|
||||
testWork = new TestWork(lock, Duration.ofMinutes(5), Duration.ofMinutes(5),
|
||||
scheduledExecutorService);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void teardown() throws Exception {
|
||||
scheduledExecutorService.shutdown();
|
||||
|
||||
assertTrue(scheduledExecutorService.awaitTermination(5, TimeUnit.SECONDS));
|
||||
}
|
||||
|
||||
@Test
|
||||
void test() throws Exception {
|
||||
when(lock.claimActiveWork(any(), any())).thenReturn(true);
|
||||
|
||||
testWork.start();
|
||||
|
||||
synchronized (testWork) {
|
||||
Util.wait(testWork);
|
||||
}
|
||||
|
||||
testWork.stop();
|
||||
|
||||
verify(lock, atLeastOnce()).claimActiveWork(anyString(), any(Duration.class));
|
||||
verify(lock, atLeastOnce()).releaseActiveWork(anyString());
|
||||
|
||||
assertTrue(1 <= testWork.getCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSlowWorkShutdown() throws Exception {
|
||||
|
||||
when(lock.claimActiveWork(any(), any())).thenReturn(true);
|
||||
|
||||
testWork.setWorkSleepDuration(Duration.ofSeconds(1));
|
||||
|
||||
testWork.start();
|
||||
|
||||
synchronized (testWork) {
|
||||
Util.wait(testWork);
|
||||
}
|
||||
|
||||
long startMillis = System.currentTimeMillis();
|
||||
|
||||
testWork.stop();
|
||||
|
||||
long runMillis = System.currentTimeMillis() - startMillis;
|
||||
|
||||
assertTrue(runMillis > 500);
|
||||
|
||||
verify(lock, atLeastOnce()).claimActiveWork(anyString(), any(Duration.class));
|
||||
verify(lock, atLeastOnce()).releaseActiveWork(anyString());
|
||||
|
||||
assertTrue(1 <= testWork.getCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testWorkExceptionReleasesLock() throws Exception {
|
||||
when(lock.claimActiveWork(any(), any())).thenReturn(true);
|
||||
|
||||
testWork = new ExceptionalTestWork(lock, Duration.ofMinutes(5), Duration.ofMinutes(5), scheduledExecutorService);
|
||||
|
||||
testWork.setSleepDurationAfterUnexpectedException(Duration.ZERO);
|
||||
|
||||
testWork.start();
|
||||
|
||||
synchronized (testWork) {
|
||||
Util.wait(testWork);
|
||||
}
|
||||
|
||||
testWork.stop();
|
||||
|
||||
verify(lock, atLeastOnce()).claimActiveWork(anyString(), any(Duration.class));
|
||||
verify(lock, atLeastOnce()).releaseActiveWork(anyString());
|
||||
|
||||
assertEquals(0, testWork.getCount());
|
||||
}
|
||||
|
||||
|
||||
private static class TestWork extends ManagedPeriodicWork {
|
||||
|
||||
private final AtomicInteger workCounter = new AtomicInteger();
|
||||
private Duration workSleepDuration = Duration.ZERO;
|
||||
|
||||
public TestWork(final ManagedPeriodicWorkLock lock, final Duration workerTtl, final Duration runInterval,
|
||||
final ScheduledExecutorService scheduledExecutorService) {
|
||||
super(lock, workerTtl, runInterval, scheduledExecutorService);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doPeriodicWork() throws Exception {
|
||||
|
||||
notifyStarted();
|
||||
|
||||
if (!workSleepDuration.isZero()) {
|
||||
Util.sleep(workSleepDuration.toMillis());
|
||||
}
|
||||
|
||||
workCounter.incrementAndGet();
|
||||
}
|
||||
|
||||
synchronized void notifyStarted() {
|
||||
notifyAll();
|
||||
}
|
||||
|
||||
int getCount() {
|
||||
return workCounter.get();
|
||||
}
|
||||
|
||||
void setWorkSleepDuration(final Duration workSleepDuration) {
|
||||
this.workSleepDuration = workSleepDuration;
|
||||
}
|
||||
}
|
||||
|
||||
private static class ExceptionalTestWork extends TestWork {
|
||||
|
||||
|
||||
public ExceptionalTestWork(final ManagedPeriodicWorkLock lock, final Duration workerTtl, final Duration runInterval,
|
||||
final ScheduledExecutorService scheduledExecutorService) {
|
||||
super(lock, workerTtl, runInterval, scheduledExecutorService);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doPeriodicWork() throws Exception {
|
||||
|
||||
notifyStarted();
|
||||
|
||||
throw new RuntimeException();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+16
-18
@@ -9,12 +9,6 @@ import static org.junit.Assert.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.document.Item;
|
||||
import com.amazonaws.services.dynamodbv2.document.ItemCollection;
|
||||
import com.amazonaws.services.dynamodbv2.document.ScanOutcome;
|
||||
import com.amazonaws.services.dynamodbv2.document.Table;
|
||||
import com.amazonaws.services.dynamodbv2.document.spec.ScanSpec;
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.lettuce.core.cluster.SlotHash;
|
||||
import java.nio.ByteBuffer;
|
||||
@@ -22,6 +16,7 @@ import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
@@ -38,6 +33,10 @@ import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.metrics.PushLatencyManager;
|
||||
import org.whispersystems.textsecuregcm.redis.AbstractRedisClusterTest;
|
||||
import org.whispersystems.textsecuregcm.tests.util.MessagesDynamoDbRule;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ScanRequest;
|
||||
|
||||
public class MessagePersisterIntegrationTest extends AbstractRedisClusterTest {
|
||||
|
||||
@@ -62,7 +61,7 @@ public class MessagePersisterIntegrationTest extends AbstractRedisClusterTest {
|
||||
connection.sync().upstream().commands().configSet("notify-keyspace-events", "K$glz");
|
||||
});
|
||||
|
||||
final MessagesDynamoDb messagesDynamoDb = new MessagesDynamoDb(messagesDynamoDbRule.getDynamoDB(), MessagesDynamoDbRule.TABLE_NAME, Duration.ofDays(7));
|
||||
final MessagesDynamoDb messagesDynamoDb = new MessagesDynamoDb(messagesDynamoDbRule.getDynamoDbClient(), MessagesDynamoDbRule.TABLE_NAME, Duration.ofDays(7));
|
||||
final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
final DynamicConfigurationManager dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
|
||||
|
||||
@@ -142,17 +141,16 @@ public class MessagePersisterIntegrationTest extends AbstractRedisClusterTest {
|
||||
|
||||
final List<MessageProtos.Envelope> persistedMessages = new ArrayList<>(messageCount);
|
||||
|
||||
DynamoDB dynamoDB = messagesDynamoDbRule.getDynamoDB();
|
||||
Table table = dynamoDB.getTable(MessagesDynamoDbRule.TABLE_NAME);
|
||||
final ItemCollection<ScanOutcome> scan = table.scan(new ScanSpec());
|
||||
for (Item item : scan) {
|
||||
persistedMessages.add(MessageProtos.Envelope.newBuilder()
|
||||
.setServerGuid(convertBinaryToUuid(item.getBinary("U")).toString())
|
||||
.setType(MessageProtos.Envelope.Type.valueOf(item.getInt("T")))
|
||||
.setTimestamp(item.getLong("TS"))
|
||||
.setServerTimestamp(extractServerTimestamp(item.getBinary("S")))
|
||||
.setContent(ByteString.copyFrom(item.getBinary("C")))
|
||||
.build());
|
||||
DynamoDbClient dynamoDB = messagesDynamoDbRule.getDynamoDbClient();
|
||||
for (Map<String, AttributeValue> item : dynamoDB
|
||||
.scan(ScanRequest.builder().tableName(MessagesDynamoDbRule.TABLE_NAME).build()).items()) {
|
||||
persistedMessages.add(MessageProtos.Envelope.newBuilder()
|
||||
.setServerGuid(AttributeValues.getUUID(item, "U", null).toString())
|
||||
.setType(MessageProtos.Envelope.Type.valueOf(AttributeValues.getInt(item, "T", -1)))
|
||||
.setTimestamp(AttributeValues.getLong(item, "TS", -1))
|
||||
.setServerTimestamp(extractServerTimestamp(AttributeValues.getByteArray(item, "S", null)))
|
||||
.setContent(ByteString.copyFrom(AttributeValues.getByteArray(item, "C", null)))
|
||||
.build());
|
||||
}
|
||||
|
||||
assertEquals(expectedMessages, persistedMessages);
|
||||
|
||||
+7
-4
@@ -4,10 +4,10 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
|
||||
import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;
|
||||
|
||||
class MigrationDeletedAccountsTest {
|
||||
|
||||
@@ -15,13 +15,16 @@ class MigrationDeletedAccountsTest {
|
||||
static DynamoDbExtension dynamoDbExtension = DynamoDbExtension.builder()
|
||||
.tableName("deleted_accounts_test")
|
||||
.hashKey(MigrationDeletedAccounts.KEY_UUID)
|
||||
.attributeDefinition(new AttributeDefinition(MigrationDeletedAccounts.KEY_UUID, ScalarAttributeType.B))
|
||||
.attributeDefinition(AttributeDefinition.builder()
|
||||
.attributeName(MigrationDeletedAccounts.KEY_UUID)
|
||||
.attributeType(ScalarAttributeType.B)
|
||||
.build())
|
||||
.build();
|
||||
|
||||
@Test
|
||||
void test() {
|
||||
|
||||
final MigrationDeletedAccounts migrationDeletedAccounts = new MigrationDeletedAccounts(dynamoDbExtension.getDynamoDB(),
|
||||
final MigrationDeletedAccounts migrationDeletedAccounts = new MigrationDeletedAccounts(dynamoDbExtension.getDynamoDbClient(),
|
||||
dynamoDbExtension.getTableName());
|
||||
|
||||
UUID firstUuid = UUID.randomUUID();
|
||||
|
||||
+7
-4
@@ -2,12 +2,12 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
|
||||
import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;
|
||||
|
||||
class MigrationRetryAccountsTest {
|
||||
|
||||
@@ -15,13 +15,16 @@ class MigrationRetryAccountsTest {
|
||||
static DynamoDbExtension dynamoDbExtension = DynamoDbExtension.builder()
|
||||
.tableName("account_migration_errors_test")
|
||||
.hashKey(MigrationRetryAccounts.KEY_UUID)
|
||||
.attributeDefinition(new AttributeDefinition(MigrationRetryAccounts.KEY_UUID, ScalarAttributeType.B))
|
||||
.attributeDefinition(AttributeDefinition.builder()
|
||||
.attributeName(MigrationRetryAccounts.KEY_UUID)
|
||||
.attributeType(ScalarAttributeType.B)
|
||||
.build())
|
||||
.build();
|
||||
|
||||
@Test
|
||||
void test() {
|
||||
|
||||
final MigrationRetryAccounts migrationRetryAccounts = new MigrationRetryAccounts(dynamoDbExtension.getDynamoDB(),
|
||||
final MigrationRetryAccounts migrationRetryAccounts = new MigrationRetryAccounts(dynamoDbExtension.getDynamoDbClient(),
|
||||
dynamoDbExtension.getTableName());
|
||||
|
||||
UUID firstUuid = UUID.randomUUID();
|
||||
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
/*
|
||||
* Copyright 2013-2021 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.whispersystems.textsecuregcm.auth.StoredVerificationCode;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicVerificationCodeStoreMigrationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicVerificationCodeStoreMigrationConfiguration.WriteDestination;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class PendingAccountsManagerTest {
|
||||
|
||||
private PendingAccounts postgresPendingAccounts;
|
||||
private VerificationCodeStoreDynamoDb dynamoDbPendingAccounts;
|
||||
private DynamicVerificationCodeStoreMigrationConfiguration migrationConfiguration;
|
||||
|
||||
private PendingAccountsManager pendingAccountsManager;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
final DynamicConfigurationManager dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
migrationConfiguration = mock(DynamicVerificationCodeStoreMigrationConfiguration.class);
|
||||
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
when(dynamicConfiguration.getPendingAccountsMigrationConfiguration()).thenReturn(migrationConfiguration);
|
||||
|
||||
postgresPendingAccounts = mock(PendingAccounts.class);
|
||||
dynamoDbPendingAccounts = mock(VerificationCodeStoreDynamoDb.class);
|
||||
|
||||
pendingAccountsManager = new PendingAccountsManager(postgresPendingAccounts, dynamoDbPendingAccounts, dynamicConfigurationManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
void storePostgres() {
|
||||
final String number = "+18005551234";
|
||||
final StoredVerificationCode code = mock(StoredVerificationCode.class);
|
||||
|
||||
when(migrationConfiguration.getWriteDestination()).thenReturn(WriteDestination.POSTGRES);
|
||||
|
||||
pendingAccountsManager.store(number, code);
|
||||
|
||||
verify(postgresPendingAccounts).insert(number, code);
|
||||
verify(dynamoDbPendingAccounts, never()).insert(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void storeDynamoDb() {
|
||||
final String number = "+18005551234";
|
||||
final StoredVerificationCode code = mock(StoredVerificationCode.class);
|
||||
|
||||
when(migrationConfiguration.getWriteDestination()).thenReturn(WriteDestination.DYNAMODB);
|
||||
|
||||
pendingAccountsManager.store(number, code);
|
||||
|
||||
verify(dynamoDbPendingAccounts).insert(number, code);
|
||||
verify(postgresPendingAccounts, never()).insert(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void remove() {
|
||||
final String number = "+18005551234";
|
||||
|
||||
pendingAccountsManager.remove(number);
|
||||
|
||||
verify(postgresPendingAccounts).remove(number);
|
||||
verify(dynamoDbPendingAccounts).remove(number);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCodeForNumber() {
|
||||
final String number = "+18005551234";
|
||||
|
||||
final StoredVerificationCode postgresCode = mock(StoredVerificationCode.class);
|
||||
final StoredVerificationCode dynamoDbCode = mock(StoredVerificationCode.class);
|
||||
|
||||
{
|
||||
when(migrationConfiguration.isReadPostgres()).thenReturn(false);
|
||||
when(migrationConfiguration.isReadDynamoDb()).thenReturn(false);
|
||||
when(postgresPendingAccounts.findForNumber(number)).thenReturn(Optional.empty());
|
||||
when(dynamoDbPendingAccounts.findForNumber(number)).thenReturn(Optional.empty());
|
||||
|
||||
assertEquals(Optional.empty(), pendingAccountsManager.getCodeForNumber(number));
|
||||
|
||||
when(migrationConfiguration.isReadPostgres()).thenReturn(true);
|
||||
|
||||
assertEquals(Optional.empty(), pendingAccountsManager.getCodeForNumber(number));
|
||||
|
||||
when(dynamoDbPendingAccounts.findForNumber(number)).thenReturn(Optional.of(dynamoDbCode));
|
||||
|
||||
assertEquals(Optional.empty(), pendingAccountsManager.getCodeForNumber(number));
|
||||
|
||||
when(postgresPendingAccounts.findForNumber(number)).thenReturn(Optional.of(postgresCode));
|
||||
|
||||
assertEquals(Optional.of(postgresCode), pendingAccountsManager.getCodeForNumber(number));
|
||||
}
|
||||
|
||||
{
|
||||
when(migrationConfiguration.isReadPostgres()).thenReturn(false);
|
||||
when(migrationConfiguration.isReadDynamoDb()).thenReturn(false);
|
||||
when(postgresPendingAccounts.findForNumber(number)).thenReturn(Optional.empty());
|
||||
when(dynamoDbPendingAccounts.findForNumber(number)).thenReturn(Optional.empty());
|
||||
|
||||
assertEquals(Optional.empty(), pendingAccountsManager.getCodeForNumber(number));
|
||||
|
||||
when(migrationConfiguration.isReadDynamoDb()).thenReturn(true);
|
||||
|
||||
assertEquals(Optional.empty(), pendingAccountsManager.getCodeForNumber(number));
|
||||
|
||||
when(postgresPendingAccounts.findForNumber(number)).thenReturn(Optional.of(postgresCode));
|
||||
|
||||
assertEquals(Optional.empty(), pendingAccountsManager.getCodeForNumber(number));
|
||||
|
||||
when(dynamoDbPendingAccounts.findForNumber(number)).thenReturn(Optional.of(dynamoDbCode));
|
||||
|
||||
assertEquals(Optional.of(dynamoDbCode), pendingAccountsManager.getCodeForNumber(number));
|
||||
}
|
||||
|
||||
{
|
||||
when(migrationConfiguration.isReadPostgres()).thenReturn(false);
|
||||
when(migrationConfiguration.isReadDynamoDb()).thenReturn(false);
|
||||
when(postgresPendingAccounts.findForNumber(number)).thenReturn(Optional.of(postgresCode));
|
||||
when(dynamoDbPendingAccounts.findForNumber(number)).thenReturn(Optional.of(dynamoDbCode));
|
||||
|
||||
assertEquals(Optional.empty(), pendingAccountsManager.getCodeForNumber(number));
|
||||
|
||||
when(migrationConfiguration.isReadDynamoDb()).thenReturn(true);
|
||||
|
||||
assertEquals(Optional.of(dynamoDbCode), pendingAccountsManager.getCodeForNumber(number));
|
||||
|
||||
when(migrationConfiguration.isReadDynamoDb()).thenReturn(false);
|
||||
when(migrationConfiguration.isReadPostgres()).thenReturn(true);
|
||||
|
||||
assertEquals(Optional.of(postgresCode), pendingAccountsManager.getCodeForNumber(number));
|
||||
|
||||
when(migrationConfiguration.isReadDynamoDb()).thenReturn(true);
|
||||
|
||||
assertEquals(Optional.of(postgresCode), pendingAccountsManager.getCodeForNumber(number));
|
||||
}
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.opentable.db.postgres.embedded.LiquibasePreparer;
|
||||
import com.opentable.db.postgres.junit5.EmbeddedPostgresExtension;
|
||||
import com.opentable.db.postgres.junit5.PreparedDbExtension;
|
||||
import org.jdbi.v3.core.Jdbi;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
class PendingAccountsTest extends VerificationCodeStoreTest {
|
||||
|
||||
@RegisterExtension
|
||||
public static PreparedDbExtension db = EmbeddedPostgresExtension.preparedDatabase(LiquibasePreparer.forClasspathLocation("accountsdb.xml"));
|
||||
|
||||
private PendingAccounts pendingAccounts;
|
||||
|
||||
@BeforeEach
|
||||
void setupAccountsDao() throws SQLException {
|
||||
this.pendingAccounts = new PendingAccounts(new FaultTolerantDatabase("pending_accounts-test", Jdbi.create(db.getTestDatabase()), new CircuitBreakerConfiguration()));
|
||||
|
||||
try (final Statement deleteStatement = db.getTestDatabase().getConnection().createStatement()) {
|
||||
deleteStatement.execute("DELETE FROM pending_accounts");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected VerificationCodeStore getVerificationCodeStore() {
|
||||
return pendingAccounts;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean expectNullPushCode() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean expectEmptyTwilioSid() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.Optional;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.auth.StoredVerificationCode;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicVerificationCodeStoreMigrationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicVerificationCodeStoreMigrationConfiguration.WriteDestination;
|
||||
|
||||
class PendingDevicesManagerTest {
|
||||
|
||||
private PendingDevices postgresPendingDevices;
|
||||
private VerificationCodeStoreDynamoDb dynamoDbPendingDevices;
|
||||
private DynamicVerificationCodeStoreMigrationConfiguration migrationConfiguration;
|
||||
|
||||
private PendingDevicesManager pendingDevicesManager;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
final DynamicConfigurationManager dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
migrationConfiguration = mock(DynamicVerificationCodeStoreMigrationConfiguration.class);
|
||||
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
when(dynamicConfiguration.getPendingDevicesMigrationConfiguration()).thenReturn(migrationConfiguration);
|
||||
|
||||
postgresPendingDevices = mock(PendingDevices.class);
|
||||
dynamoDbPendingDevices = mock(VerificationCodeStoreDynamoDb.class);
|
||||
|
||||
pendingDevicesManager = new PendingDevicesManager(postgresPendingDevices, dynamoDbPendingDevices, dynamicConfigurationManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
void storePostgres() {
|
||||
final String number = "+18005551234";
|
||||
final StoredVerificationCode code = mock(StoredVerificationCode.class);
|
||||
|
||||
when(migrationConfiguration.getWriteDestination()).thenReturn(WriteDestination.POSTGRES);
|
||||
|
||||
pendingDevicesManager.store(number, code);
|
||||
|
||||
verify(postgresPendingDevices).insert(number, code);
|
||||
verify(dynamoDbPendingDevices, never()).insert(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void storeDynamoDb() {
|
||||
final String number = "+18005551234";
|
||||
final StoredVerificationCode code = mock(StoredVerificationCode.class);
|
||||
|
||||
when(migrationConfiguration.getWriteDestination()).thenReturn(WriteDestination.DYNAMODB);
|
||||
|
||||
pendingDevicesManager.store(number, code);
|
||||
|
||||
verify(dynamoDbPendingDevices).insert(number, code);
|
||||
verify(postgresPendingDevices, never()).insert(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void remove() {
|
||||
final String number = "+18005551234";
|
||||
|
||||
pendingDevicesManager.remove(number);
|
||||
|
||||
verify(postgresPendingDevices).remove(number);
|
||||
verify(dynamoDbPendingDevices).remove(number);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCodeForNumber() {
|
||||
final String number = "+18005551234";
|
||||
|
||||
final StoredVerificationCode postgresCode = mock(StoredVerificationCode.class);
|
||||
final StoredVerificationCode dynamoDbCode = mock(StoredVerificationCode.class);
|
||||
|
||||
{
|
||||
when(migrationConfiguration.isReadPostgres()).thenReturn(false);
|
||||
when(migrationConfiguration.isReadDynamoDb()).thenReturn(false);
|
||||
when(postgresPendingDevices.findForNumber(number)).thenReturn(Optional.empty());
|
||||
when(dynamoDbPendingDevices.findForNumber(number)).thenReturn(Optional.empty());
|
||||
|
||||
assertEquals(Optional.empty(), pendingDevicesManager.getCodeForNumber(number));
|
||||
|
||||
when(migrationConfiguration.isReadPostgres()).thenReturn(true);
|
||||
|
||||
assertEquals(Optional.empty(), pendingDevicesManager.getCodeForNumber(number));
|
||||
|
||||
when(dynamoDbPendingDevices.findForNumber(number)).thenReturn(Optional.of(dynamoDbCode));
|
||||
|
||||
assertEquals(Optional.empty(), pendingDevicesManager.getCodeForNumber(number));
|
||||
|
||||
when(postgresPendingDevices.findForNumber(number)).thenReturn(Optional.of(postgresCode));
|
||||
|
||||
assertEquals(Optional.of(postgresCode), pendingDevicesManager.getCodeForNumber(number));
|
||||
}
|
||||
|
||||
{
|
||||
when(migrationConfiguration.isReadPostgres()).thenReturn(false);
|
||||
when(migrationConfiguration.isReadDynamoDb()).thenReturn(false);
|
||||
when(postgresPendingDevices.findForNumber(number)).thenReturn(Optional.empty());
|
||||
when(dynamoDbPendingDevices.findForNumber(number)).thenReturn(Optional.empty());
|
||||
|
||||
assertEquals(Optional.empty(), pendingDevicesManager.getCodeForNumber(number));
|
||||
|
||||
when(migrationConfiguration.isReadDynamoDb()).thenReturn(true);
|
||||
|
||||
assertEquals(Optional.empty(), pendingDevicesManager.getCodeForNumber(number));
|
||||
|
||||
when(postgresPendingDevices.findForNumber(number)).thenReturn(Optional.of(postgresCode));
|
||||
|
||||
assertEquals(Optional.empty(), pendingDevicesManager.getCodeForNumber(number));
|
||||
|
||||
when(dynamoDbPendingDevices.findForNumber(number)).thenReturn(Optional.of(dynamoDbCode));
|
||||
|
||||
assertEquals(Optional.of(dynamoDbCode), pendingDevicesManager.getCodeForNumber(number));
|
||||
}
|
||||
|
||||
{
|
||||
when(migrationConfiguration.isReadPostgres()).thenReturn(false);
|
||||
when(migrationConfiguration.isReadDynamoDb()).thenReturn(false);
|
||||
when(postgresPendingDevices.findForNumber(number)).thenReturn(Optional.of(postgresCode));
|
||||
when(dynamoDbPendingDevices.findForNumber(number)).thenReturn(Optional.of(dynamoDbCode));
|
||||
|
||||
assertEquals(Optional.empty(), pendingDevicesManager.getCodeForNumber(number));
|
||||
|
||||
when(migrationConfiguration.isReadDynamoDb()).thenReturn(true);
|
||||
|
||||
assertEquals(Optional.of(dynamoDbCode), pendingDevicesManager.getCodeForNumber(number));
|
||||
|
||||
when(migrationConfiguration.isReadDynamoDb()).thenReturn(false);
|
||||
when(migrationConfiguration.isReadPostgres()).thenReturn(true);
|
||||
|
||||
assertEquals(Optional.of(postgresCode), pendingDevicesManager.getCodeForNumber(number));
|
||||
|
||||
when(migrationConfiguration.isReadDynamoDb()).thenReturn(true);
|
||||
|
||||
assertEquals(Optional.of(postgresCode), pendingDevicesManager.getCodeForNumber(number));
|
||||
}
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.opentable.db.postgres.embedded.LiquibasePreparer;
|
||||
import com.opentable.db.postgres.junit5.EmbeddedPostgresExtension;
|
||||
import com.opentable.db.postgres.junit5.PreparedDbExtension;
|
||||
import org.jdbi.v3.core.Jdbi;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
public class PendingDevicesTest extends VerificationCodeStoreTest {
|
||||
|
||||
@RegisterExtension
|
||||
public static PreparedDbExtension db = EmbeddedPostgresExtension.preparedDatabase(LiquibasePreparer.forClasspathLocation("accountsdb.xml"));
|
||||
|
||||
private PendingDevices pendingDevices;
|
||||
|
||||
@BeforeEach
|
||||
public void setupAccountsDao() throws SQLException {
|
||||
this.pendingDevices = new PendingDevices(new FaultTolerantDatabase("peding_devices-test", Jdbi.create(db.getTestDatabase()), new CircuitBreakerConfiguration()));
|
||||
|
||||
try (final Statement deleteStatement = db.getTestDatabase().getConnection().createStatement()) {
|
||||
deleteStatement.execute("DELETE FROM pending_devices");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected VerificationCodeStore getVerificationCodeStore() {
|
||||
return pendingDevices;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean expectNullPushCode() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean expectEmptyTwilioSid() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+7
-4
@@ -9,8 +9,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
|
||||
import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
@@ -20,6 +18,8 @@ import java.util.UUID;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;
|
||||
|
||||
class PushChallengeDynamoDbTest {
|
||||
|
||||
@@ -34,12 +34,15 @@ class PushChallengeDynamoDbTest {
|
||||
static DynamoDbExtension dynamoDbExtension = DynamoDbExtension.builder()
|
||||
.tableName(TABLE_NAME)
|
||||
.hashKey(PushChallengeDynamoDb.KEY_ACCOUNT_UUID)
|
||||
.attributeDefinition(new AttributeDefinition(PushChallengeDynamoDb.KEY_ACCOUNT_UUID, ScalarAttributeType.B))
|
||||
.attributeDefinition(AttributeDefinition.builder()
|
||||
.attributeName(PushChallengeDynamoDb.KEY_ACCOUNT_UUID)
|
||||
.attributeType(ScalarAttributeType.B)
|
||||
.build())
|
||||
.build();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
this.pushChallengeDynamoDb = new PushChallengeDynamoDb(dynamoDbExtension.getDynamoDB(), TABLE_NAME, Clock.fixed(
|
||||
this.pushChallengeDynamoDb = new PushChallengeDynamoDb(dynamoDbExtension.getDynamoDbClient(), TABLE_NAME, Clock.fixed(
|
||||
Instant.ofEpochMilli(CURRENT_TIME_MILLIS), ZoneId.systemDefault()));
|
||||
}
|
||||
|
||||
|
||||
+7
-4
@@ -4,13 +4,13 @@ import static org.junit.jupiter.api.Assertions.assertAll;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
|
||||
import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType;
|
||||
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.util.UUIDUtil;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;
|
||||
|
||||
class ReportMessageDynamoDbTest {
|
||||
|
||||
@@ -22,13 +22,16 @@ class ReportMessageDynamoDbTest {
|
||||
static DynamoDbExtension dynamoDbExtension = DynamoDbExtension.builder()
|
||||
.tableName(TABLE_NAME)
|
||||
.hashKey(ReportMessageDynamoDb.KEY_HASH)
|
||||
.attributeDefinition(new AttributeDefinition(ReportMessageDynamoDb.KEY_HASH, ScalarAttributeType.B))
|
||||
.attributeDefinition(AttributeDefinition.builder()
|
||||
.attributeName(ReportMessageDynamoDb.KEY_HASH)
|
||||
.attributeType(ScalarAttributeType.B)
|
||||
.build())
|
||||
.build();
|
||||
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
this.reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbExtension.getDynamoDB(), TABLE_NAME);
|
||||
this.reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbExtension.getDynamoDbClient(), TABLE_NAME);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* Copyright 2013-2021 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.extension.RegisterExtension;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;
|
||||
|
||||
class VerificationCodeStoreDynamoDbTest extends VerificationCodeStoreTest {
|
||||
|
||||
private VerificationCodeStoreDynamoDb verificationCodeStore;
|
||||
|
||||
private static final String TABLE_NAME = "verification_code_test";
|
||||
|
||||
@RegisterExtension
|
||||
static final DynamoDbExtension DYNAMO_DB_EXTENSION = DynamoDbExtension.builder()
|
||||
.tableName(TABLE_NAME)
|
||||
.hashKey(VerificationCodeStoreDynamoDb.KEY_E164)
|
||||
.attributeDefinition(AttributeDefinition.builder()
|
||||
.attributeName(VerificationCodeStoreDynamoDb.KEY_E164)
|
||||
.attributeType(ScalarAttributeType.S)
|
||||
.build())
|
||||
.build();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
verificationCodeStore = new VerificationCodeStoreDynamoDb(DYNAMO_DB_EXTENSION.getDynamoDbClient(), TABLE_NAME);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected VerificationCodeStore getVerificationCodeStore() {
|
||||
return verificationCodeStore;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean expectNullPushCode() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean expectEmptyTwilioSid() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.auth.StoredVerificationCode;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
abstract class VerificationCodeStoreTest {
|
||||
|
||||
private static final String PHONE_NUMBER = "+14151112222";
|
||||
|
||||
protected abstract VerificationCodeStore getVerificationCodeStore();
|
||||
|
||||
protected abstract boolean expectNullPushCode();
|
||||
|
||||
protected abstract boolean expectEmptyTwilioSid();
|
||||
|
||||
@Test
|
||||
void testStoreAndFind() {
|
||||
assertEquals(Optional.empty(), getVerificationCodeStore().findForNumber(PHONE_NUMBER));
|
||||
|
||||
final StoredVerificationCode originalCode = new StoredVerificationCode("1234", 1111, "abcd", "0987");
|
||||
final StoredVerificationCode secondCode = new StoredVerificationCode("5678", 2222, "efgh", "7890");
|
||||
|
||||
getVerificationCodeStore().insert(PHONE_NUMBER, originalCode);
|
||||
|
||||
{
|
||||
final Optional<StoredVerificationCode> maybeRetrievedCode = getVerificationCodeStore().findForNumber(PHONE_NUMBER);
|
||||
|
||||
assertTrue(maybeRetrievedCode.isPresent());
|
||||
compareStoredVerificationCode(originalCode, maybeRetrievedCode.get());
|
||||
}
|
||||
|
||||
getVerificationCodeStore().insert(PHONE_NUMBER, secondCode);
|
||||
|
||||
{
|
||||
final Optional<StoredVerificationCode> maybeRetrievedCode = getVerificationCodeStore().findForNumber(PHONE_NUMBER);
|
||||
|
||||
assertTrue(maybeRetrievedCode.isPresent());
|
||||
compareStoredVerificationCode(secondCode, maybeRetrievedCode.get());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRemove() {
|
||||
assertEquals(Optional.empty(), getVerificationCodeStore().findForNumber(PHONE_NUMBER));
|
||||
|
||||
getVerificationCodeStore().insert(PHONE_NUMBER, new StoredVerificationCode("1234", 1111, "abcd", "0987"));
|
||||
assertTrue(getVerificationCodeStore().findForNumber(PHONE_NUMBER).isPresent());
|
||||
|
||||
getVerificationCodeStore().remove(PHONE_NUMBER);
|
||||
assertFalse(getVerificationCodeStore().findForNumber(PHONE_NUMBER).isPresent());
|
||||
}
|
||||
|
||||
private void compareStoredVerificationCode(final StoredVerificationCode original, final StoredVerificationCode retrieved) {
|
||||
assertEquals(original.getCode(), retrieved.getCode());
|
||||
assertEquals(original.getTimestamp(), retrieved.getTimestamp());
|
||||
|
||||
if (expectNullPushCode()) {
|
||||
assertNull(retrieved.getPushCode());
|
||||
} else {
|
||||
assertEquals(original.getPushCode(), retrieved.getPushCode());
|
||||
}
|
||||
|
||||
if (expectEmptyTwilioSid()) {
|
||||
assertEquals(Optional.empty(), retrieved.getTwilioVerificationSid());
|
||||
} else {
|
||||
assertEquals(original.getTwilioVerificationSid(), retrieved.getTwilioVerificationSid());
|
||||
}
|
||||
}
|
||||
}
|
||||
+10
-10
@@ -192,15 +192,15 @@ class AccountControllerTest {
|
||||
when(senderRegLockAccount.getLastSeen()).thenReturn(System.currentTimeMillis());
|
||||
when(senderRegLockAccount.getUuid()).thenReturn(SENDER_REG_LOCK_UUID);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER)).thenReturn(Optional.of(new StoredVerificationCode("1234", System.currentTimeMillis(), "1234-push")));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_OLD)).thenReturn(Optional.of(new StoredVerificationCode("1234", System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(31), null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_PIN)).thenReturn(Optional.of(new StoredVerificationCode("333333", System.currentTimeMillis(), null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_REG_LOCK)).thenReturn(Optional.of(new StoredVerificationCode("666666", System.currentTimeMillis(), null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_OVER_PIN)).thenReturn(Optional.of(new StoredVerificationCode("444444", System.currentTimeMillis(), null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_OVER_PREFIX)).thenReturn(Optional.of(new StoredVerificationCode("777777", System.currentTimeMillis(), "1234-push")));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_PREAUTH)).thenReturn(Optional.of(new StoredVerificationCode("555555", System.currentTimeMillis(), "validchallenge")));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_HAS_STORAGE)).thenReturn(Optional.of(new StoredVerificationCode("666666", System.currentTimeMillis(), null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_TRANSFER)).thenReturn(Optional.of(new StoredVerificationCode("1234", System.currentTimeMillis(), null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER)).thenReturn(Optional.of(new StoredVerificationCode("1234", System.currentTimeMillis(), "1234-push", null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_OLD)).thenReturn(Optional.of(new StoredVerificationCode("1234", System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(31), null, null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_PIN)).thenReturn(Optional.of(new StoredVerificationCode("333333", System.currentTimeMillis(), null, null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_REG_LOCK)).thenReturn(Optional.of(new StoredVerificationCode("666666", System.currentTimeMillis(), null, null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_OVER_PIN)).thenReturn(Optional.of(new StoredVerificationCode("444444", System.currentTimeMillis(), null, null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_OVER_PREFIX)).thenReturn(Optional.of(new StoredVerificationCode("777777", System.currentTimeMillis(), "1234-push", null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_PREAUTH)).thenReturn(Optional.of(new StoredVerificationCode("555555", System.currentTimeMillis(), "validchallenge", null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_HAS_STORAGE)).thenReturn(Optional.of(new StoredVerificationCode("666666", System.currentTimeMillis(), null, null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_TRANSFER)).thenReturn(Optional.of(new StoredVerificationCode("1234", System.currentTimeMillis(), null, null)));
|
||||
|
||||
when(accountsManager.get(eq(SENDER_PIN))).thenReturn(Optional.of(senderPinAccount));
|
||||
when(accountsManager.get(eq(SENDER_REG_LOCK))).thenReturn(Optional.of(senderRegLockAccount));
|
||||
@@ -884,7 +884,7 @@ class AccountControllerTest {
|
||||
final String number = "+12345678901";
|
||||
final String challenge = "challenge";
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(number)).thenReturn(Optional.of(new StoredVerificationCode("123456", System.currentTimeMillis(), challenge)));
|
||||
when(pendingAccountsManager.getCodeForNumber(number)).thenReturn(Optional.of(new StoredVerificationCode("123456", System.currentTimeMillis(), challenge, null)));
|
||||
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
|
||||
+60
-7
@@ -6,8 +6,10 @@ package org.whispersystems.textsecuregcm.tests.controllers;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.mockito.Mockito.clearInvocations;
|
||||
import static org.mockito.Mockito.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -116,9 +118,10 @@ public class DeviceControllerTest {
|
||||
when(account.isGroupsV2Supported()).thenReturn(true);
|
||||
when(account.isGv1MigrationSupported()).thenReturn(true);
|
||||
when(account.isSenderKeySupported()).thenReturn(true);
|
||||
when(account.isAnnouncementGroupSupported()).thenReturn(true);
|
||||
|
||||
when(pendingDevicesManager.getCodeForNumber(AuthHelper.VALID_NUMBER)).thenReturn(Optional.of(new StoredVerificationCode("5678901", System.currentTimeMillis(), null)));
|
||||
when(pendingDevicesManager.getCodeForNumber(AuthHelper.VALID_NUMBER_TWO)).thenReturn(Optional.of(new StoredVerificationCode("1112223", System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(31), null)));
|
||||
when(pendingDevicesManager.getCodeForNumber(AuthHelper.VALID_NUMBER)).thenReturn(Optional.of(new StoredVerificationCode("5678901", System.currentTimeMillis(), null, null)));
|
||||
when(pendingDevicesManager.getCodeForNumber(AuthHelper.VALID_NUMBER_TWO)).thenReturn(Optional.of(new StoredVerificationCode("1112223", System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(31), null, null)));
|
||||
when(accountsManager.get(AuthHelper.VALID_NUMBER)).thenReturn(Optional.of(account));
|
||||
when(accountsManager.get(AuthHelper.VALID_NUMBER_TWO)).thenReturn(Optional.of(maxedAccount));
|
||||
}
|
||||
@@ -223,7 +226,7 @@ public class DeviceControllerTest {
|
||||
@Test
|
||||
@Parameters(method = "argumentsForDeviceDowngradeCapabilitiesTest")
|
||||
public void deviceDowngradeCapabilitiesTest(final String userAgent, final boolean gv2, final boolean gv2_2, final boolean gv2_3, final int expectedStatus) throws Exception {
|
||||
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(gv2, gv2_2, gv2_3, true, false, true, true);
|
||||
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(gv2, gv2_2, gv2_3, true, false, true, true, true);
|
||||
AccountAttributes accountAttributes = new AccountAttributes(false, 1234, null, null, null, true, deviceCapabilities);
|
||||
Response response = resources.getJerseyTest()
|
||||
.target("/v1/devices/5678901")
|
||||
@@ -263,7 +266,7 @@ public class DeviceControllerTest {
|
||||
|
||||
@Test
|
||||
public void deviceDowngradeGv1MigrationTest() {
|
||||
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true, true, true, false, false, true);
|
||||
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true, true, true, false, false, true, true);
|
||||
AccountAttributes accountAttributes = new AccountAttributes(false, 1234, null, null, null, true, deviceCapabilities);
|
||||
Response response = resources.getJerseyTest()
|
||||
.target("/v1/devices/5678901")
|
||||
@@ -274,7 +277,7 @@ public class DeviceControllerTest {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(409);
|
||||
|
||||
deviceCapabilities = new DeviceCapabilities(true, true, true, true, false, true, true);
|
||||
deviceCapabilities = new DeviceCapabilities(true, true, true, true, false, true, true, true);
|
||||
accountAttributes = new AccountAttributes(false, 1234, null, null, null, true, deviceCapabilities);
|
||||
response = resources.getJerseyTest()
|
||||
.target("/v1/devices/5678901")
|
||||
@@ -288,7 +291,7 @@ public class DeviceControllerTest {
|
||||
|
||||
@Test
|
||||
public void deviceDowngradeSenderKeyTest() {
|
||||
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, false);
|
||||
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, false, true);
|
||||
AccountAttributes accountAttributes =
|
||||
new AccountAttributes(false, 1234, null, null, null, true, deviceCapabilities);
|
||||
Response response = resources
|
||||
@@ -300,7 +303,7 @@ public class DeviceControllerTest {
|
||||
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
|
||||
assertThat(response.getStatus()).isEqualTo(409);
|
||||
|
||||
deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true);
|
||||
deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, true);
|
||||
accountAttributes = new AccountAttributes(false, 1234, null, null, null, true, deviceCapabilities);
|
||||
response = resources
|
||||
.getJerseyTest()
|
||||
@@ -311,4 +314,54 @@ public class DeviceControllerTest {
|
||||
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deviceDowngradeAnnouncementGroupTest() {
|
||||
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, false);
|
||||
AccountAttributes accountAttributes =
|
||||
new AccountAttributes(false, 1234, null, null, null, true, deviceCapabilities);
|
||||
Response response = resources
|
||||
.getJerseyTest()
|
||||
.target("/v1/devices/5678901")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_NUMBER, AuthHelper.VALID_PASSWORD))
|
||||
.header("User-Agent", "Signal-Android/5.42.8675309 Android/30")
|
||||
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
|
||||
assertThat(response.getStatus()).isEqualTo(409);
|
||||
|
||||
deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, true);
|
||||
accountAttributes = new AccountAttributes(false, 1234, null, null, null, true, deviceCapabilities);
|
||||
response = resources
|
||||
.getJerseyTest()
|
||||
.target("/v1/devices/5678901")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_NUMBER, AuthHelper.VALID_PASSWORD))
|
||||
.header("User-Agent", "Signal-Android/5.42.8675309 Android/30")
|
||||
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deviceRemovalClearsMessages() {
|
||||
|
||||
// this is a static mock, so it might have previous invocations
|
||||
clearInvocations(AuthHelper.VALID_ACCOUNT);
|
||||
|
||||
final long deviceId = 2;
|
||||
|
||||
final Response response = resources
|
||||
.getJerseyTest()
|
||||
.target("/v1/devices/" + deviceId)
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_NUMBER, AuthHelper.VALID_PASSWORD))
|
||||
.header("User-Agent", "Signal-Android/5.42.8675309 Android/30")
|
||||
.delete();
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(204);
|
||||
|
||||
verify(messagesManager, times(2)).clear(AuthHelper.VALID_UUID, deviceId);
|
||||
verify(accountsManager, times(1)).update(AuthHelper.VALID_ACCOUNT);
|
||||
verify(AuthHelper.VALID_ACCOUNT).removeDevice(deviceId);
|
||||
}
|
||||
|
||||
}
|
||||
+6
-4
@@ -70,6 +70,7 @@ import org.mockito.stubbing.Answer;
|
||||
import org.whispersystems.textsecuregcm.auth.AmbiguousIdentifier;
|
||||
import org.whispersystems.textsecuregcm.auth.DisabledPermittedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.OptionalAccess;
|
||||
import org.whispersystems.textsecuregcm.auth.StoredRegistrationLock;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicMessageRateConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicRateLimitChallengeConfiguration;
|
||||
@@ -157,19 +158,19 @@ class MessageControllerTest {
|
||||
Set<Device> singleDeviceList = new HashSet<Device>() {{
|
||||
add(new Device(1, null, "foo", "bar",
|
||||
"isgcm", null, null, false, 111, new SignedPreKey(333, "baz", "boop"), System.currentTimeMillis(), System.currentTimeMillis(), "Test", 0, new Device.DeviceCapabilities(true, false, false, true, true, false,
|
||||
false)));
|
||||
false, false)));
|
||||
}};
|
||||
|
||||
Set<Device> multiDeviceList = new HashSet<Device>() {{
|
||||
add(new Device(1, null, "foo", "bar",
|
||||
"isgcm", null, null, false, 222, new SignedPreKey(111, "foo", "bar"), System.currentTimeMillis(), System.currentTimeMillis(), "Test", 0, new Device.DeviceCapabilities(true, false, false, true, false, false,
|
||||
false)));
|
||||
false, false)));
|
||||
add(new Device(2, null, "foo", "bar",
|
||||
"isgcm", null, null, false, 333, new SignedPreKey(222, "oof", "rab"), System.currentTimeMillis(), System.currentTimeMillis(), "Test", 0, new Device.DeviceCapabilities(true, false, false, true, false, false,
|
||||
false)));
|
||||
false, false)));
|
||||
add(new Device(3, null, "foo", "bar",
|
||||
"isgcm", null, null, false, 444, null, System.currentTimeMillis() - TimeUnit.DAYS.toMillis(31), System.currentTimeMillis(), "Test", 0, new Device.DeviceCapabilities(false, false, false, false, false, false,
|
||||
false)));
|
||||
false, false)));
|
||||
}};
|
||||
|
||||
Account singleDeviceAccount = new Account(SINGLE_DEVICE_RECIPIENT, SINGLE_DEVICE_UUID, singleDeviceList, "1234".getBytes());
|
||||
@@ -484,6 +485,7 @@ class MessageControllerTest {
|
||||
OutgoingMessageEntityList messagesList = new OutgoingMessageEntityList(messages, false);
|
||||
|
||||
when(messagesManager.getMessagesForDevice(eq(AuthHelper.VALID_UUID), eq(1L), anyString(), anyBoolean())).thenReturn(messagesList);
|
||||
when(AuthHelper.VALID_ACCOUNT.getRegistrationLock()).thenReturn(mock(StoredRegistrationLock.class));
|
||||
|
||||
OutgoingMessageEntityList response =
|
||||
resources.getJerseyTest().target("/v1/messages/")
|
||||
|
||||
+9
-4
@@ -18,7 +18,6 @@ import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.amazonaws.services.s3.AmazonS3;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import io.dropwizard.auth.PolymorphicAuthValueFactoryProvider;
|
||||
import io.dropwizard.testing.junit.ResourceTestRule;
|
||||
@@ -61,6 +60,8 @@ import org.whispersystems.textsecuregcm.storage.VersionedProfile;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import software.amazon.awssdk.services.s3.S3Client;
|
||||
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
|
||||
|
||||
public class ProfileControllerTest {
|
||||
|
||||
@@ -71,7 +72,7 @@ public class ProfileControllerTest {
|
||||
private static RateLimiter rateLimiter = mock(RateLimiter.class );
|
||||
private static RateLimiter usernameRateLimiter = mock(RateLimiter.class );
|
||||
|
||||
private static AmazonS3 s3client = mock(AmazonS3.class);
|
||||
private static S3Client s3client = mock(S3Client.class);
|
||||
private static PostPolicyGenerator postPolicyGenerator = new PostPolicyGenerator("us-west-1", "profile-bucket", "accessKey");
|
||||
private static PolicySigner policySigner = new PolicySigner("accessSecret", "us-west-1");
|
||||
private static ServerZkProfileOperations zkProfileOperations = mock(ServerZkProfileOperations.class);
|
||||
@@ -125,6 +126,7 @@ public class ProfileControllerTest {
|
||||
when(profileAccount.isGroupsV2Supported()).thenReturn(false);
|
||||
when(profileAccount.isGv1MigrationSupported()).thenReturn(false);
|
||||
when(profileAccount.isSenderKeySupported()).thenReturn(false);
|
||||
when(profileAccount.isAnnouncementGroupSupported()).thenReturn(false);
|
||||
when(profileAccount.getCurrentProfileVersion()).thenReturn(Optional.empty());
|
||||
|
||||
Account capabilitiesAccount = mock(Account.class);
|
||||
@@ -136,6 +138,7 @@ public class ProfileControllerTest {
|
||||
when(capabilitiesAccount.isGroupsV2Supported()).thenReturn(true);
|
||||
when(capabilitiesAccount.isGv1MigrationSupported()).thenReturn(true);
|
||||
when(capabilitiesAccount.isSenderKeySupported()).thenReturn(true);
|
||||
when(capabilitiesAccount.isAnnouncementGroupSupported()).thenReturn(true);
|
||||
|
||||
when(accountsManager.get(AuthHelper.VALID_NUMBER_TWO)).thenReturn(Optional.of(profileAccount));
|
||||
when(accountsManager.get(AuthHelper.VALID_UUID_TWO)).thenReturn(Optional.of(profileAccount));
|
||||
@@ -274,6 +277,7 @@ public class ProfileControllerTest {
|
||||
assertThat(profile.getCapabilities().isGv2()).isTrue();
|
||||
assertThat(profile.getCapabilities().isGv1Migration()).isTrue();
|
||||
assertThat(profile.getCapabilities().isSenderKey()).isTrue();
|
||||
assertThat(profile.getCapabilities().isAnnouncementGroup()).isTrue();
|
||||
|
||||
profile = resources
|
||||
.getJerseyTest()
|
||||
@@ -285,6 +289,7 @@ public class ProfileControllerTest {
|
||||
assertThat(profile.getCapabilities().isGv2()).isFalse();
|
||||
assertThat(profile.getCapabilities().isGv1Migration()).isFalse();
|
||||
assertThat(profile.getCapabilities().isSenderKey()).isFalse();
|
||||
assertThat(profile.getCapabilities().isAnnouncementGroup()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -415,7 +420,7 @@ public class ProfileControllerTest {
|
||||
|
||||
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq("validversion"));
|
||||
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
|
||||
verify(s3client, times(1)).deleteObject(eq("profilesBucket"), eq("profiles/validavatar"));
|
||||
verify(s3client, times(1)).deleteObject(eq(DeleteObjectRequest.builder().bucket("profilesBucket").key("profiles/validavatar").build()));
|
||||
|
||||
assertThat(profileArgumentCaptor.getValue().getCommitment()).isEqualTo(commitment.serialize());
|
||||
assertThat(profileArgumentCaptor.getValue().getAvatar()).startsWith("profiles/");
|
||||
@@ -440,7 +445,7 @@ public class ProfileControllerTest {
|
||||
|
||||
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq("validversion"));
|
||||
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
|
||||
verify(s3client, times(1)).deleteObject(eq("profilesBucket"), eq("profiles/validavatar"));
|
||||
verify(s3client, times(1)).deleteObject(eq(DeleteObjectRequest.builder().bucket("profilesBucket").key("profiles/validavatar").build()));
|
||||
|
||||
assertThat(profileArgumentCaptor.getValue().getCommitment()).isEqualTo(commitment.serialize());
|
||||
assertThat(profileArgumentCaptor.getValue().getAvatar()).startsWith("profiles/");
|
||||
|
||||
+35
-6
@@ -43,6 +43,10 @@ public class AccountTest {
|
||||
private final Device senderKeyIncapableDevice = mock(Device.class);
|
||||
private final Device senderKeyIncapableExpiredDevice = mock(Device.class);
|
||||
|
||||
private final Device announcementGroupCapableDevice = mock(Device.class);
|
||||
private final Device announcementGroupIncapableDevice = mock(Device.class);
|
||||
private final Device announcementGroupIncapableExpiredDevice = mock(Device.class);
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
when(oldMasterDevice.getLastSeen()).thenReturn(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(366));
|
||||
@@ -78,28 +82,40 @@ public class AccountTest {
|
||||
when(gv2IncapableExpiredDevice.isEnabled()).thenReturn(false);
|
||||
|
||||
when(gv1MigrationCapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, true, true, true, false));
|
||||
new DeviceCapabilities(true, true, true, true, true, true, false, false));
|
||||
when(gv1MigrationCapableDevice.isEnabled()).thenReturn(true);
|
||||
|
||||
when(gv1MigrationIncapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, true, true, false, false));
|
||||
new DeviceCapabilities(true, true, true, true, true, false, false, false));
|
||||
when(gv1MigrationIncapableDevice.isEnabled()).thenReturn(true);
|
||||
|
||||
when(gv1MigrationIncapableExpiredDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, true, true, false, false));
|
||||
new DeviceCapabilities(true, true, true, true, true, false, false, false));
|
||||
when(gv1MigrationIncapableExpiredDevice.isEnabled()).thenReturn(false);
|
||||
|
||||
when(senderKeyCapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, true, true, true, true));
|
||||
new DeviceCapabilities(true, true, true, true, true, true, true, false));
|
||||
when(senderKeyCapableDevice.isEnabled()).thenReturn(true);
|
||||
|
||||
when(senderKeyIncapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, true, true, true, false));
|
||||
new DeviceCapabilities(true, true, true, true, true, true, false, false));
|
||||
when(senderKeyIncapableDevice.isEnabled()).thenReturn(true);
|
||||
|
||||
when(senderKeyIncapableExpiredDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, true, true, true, false));
|
||||
new DeviceCapabilities(true, true, true, true, true, true, false, false));
|
||||
when(senderKeyIncapableExpiredDevice.isEnabled()).thenReturn(false);
|
||||
|
||||
when(announcementGroupCapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, true, true, true, true, true));
|
||||
when(announcementGroupCapableDevice.isEnabled()).thenReturn(true);
|
||||
|
||||
when(announcementGroupIncapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, true, true, true, true, false));
|
||||
when(announcementGroupIncapableDevice.isEnabled()).thenReturn(true);
|
||||
|
||||
when(announcementGroupIncapableExpiredDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, true, true, true, true, false));
|
||||
when(announcementGroupIncapableExpiredDevice.isEnabled()).thenReturn(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -233,4 +249,17 @@ public class AccountTest {
|
||||
Set.of(senderKeyCapableDevice, senderKeyIncapableExpiredDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isSenderKeySupported()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isAnnouncementGroupSupported() {
|
||||
assertThat(new Account("+18005551234", UUID.randomUUID(),
|
||||
Set.of(announcementGroupCapableDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isAnnouncementGroupSupported()).isTrue();
|
||||
assertThat(new Account("+18005551234", UUID.randomUUID(),
|
||||
Set.of(announcementGroupCapableDevice, announcementGroupIncapableDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isAnnouncementGroupSupported()).isFalse();
|
||||
assertThat(new Account("+18005551234", UUID.randomUUID(),
|
||||
Set.of(announcementGroupCapableDevice, announcementGroupIncapableExpiredDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isAnnouncementGroupSupported()).isTrue();
|
||||
}
|
||||
}
|
||||
+29
-10
@@ -20,7 +20,6 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
import static org.mockito.Mockito.verifyZeroInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException;
|
||||
import io.lettuce.core.RedisException;
|
||||
import io.lettuce.core.cluster.api.sync.RedisAdvancedClusterCommands;
|
||||
import java.util.HashSet;
|
||||
@@ -42,6 +41,7 @@ import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Accounts;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DeletedAccounts;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.KeysDynamoDb;
|
||||
@@ -49,6 +49,7 @@ import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernamesManager;
|
||||
import org.whispersystems.textsecuregcm.tests.util.RedisClusterHelper;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
|
||||
|
||||
class AccountsManagerTest {
|
||||
|
||||
@@ -70,6 +71,7 @@ class AccountsManagerTest {
|
||||
FaultTolerantRedisCluster cacheCluster = RedisClusterHelper.buildMockRedisCluster(commands);
|
||||
Accounts accounts = mock(Accounts.class);
|
||||
AccountsDynamoDb accountsDynamoDb = mock(AccountsDynamoDb.class);
|
||||
DeletedAccounts deletedAccounts = mock(DeletedAccounts.class);
|
||||
DirectoryQueue directoryQueue = mock(DirectoryQueue.class);
|
||||
KeysDynamoDb keysDynamoDb = mock(KeysDynamoDb.class);
|
||||
MessagesManager messagesManager = mock(MessagesManager.class);
|
||||
@@ -85,7 +87,8 @@ class AccountsManagerTest {
|
||||
when(commands.get(eq("AccountMap::+14152222222"))).thenReturn(uuid.toString());
|
||||
when(commands.get(eq("Account3::" + uuid.toString()))).thenReturn("{\"number\": \"+14152222222\", \"name\": \"test\"}");
|
||||
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, accountsDynamoDb, cacheCluster, directoryQueue, keysDynamoDb, messagesManager, usernamesManager, profilesManager, secureStorageClient, secureBackupClient, experimentEnrollmentManager, dynamicConfigurationManager);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, accountsDynamoDb, cacheCluster, deletedAccounts,
|
||||
directoryQueue, keysDynamoDb, messagesManager, usernamesManager, profilesManager, secureStorageClient, secureBackupClient, experimentEnrollmentManager, dynamicConfigurationManager);
|
||||
Optional<Account> account = accountsManager.get("+14152222222");
|
||||
|
||||
assertTrue(account.isPresent());
|
||||
@@ -120,6 +123,7 @@ class AccountsManagerTest {
|
||||
FaultTolerantRedisCluster cacheCluster = RedisClusterHelper.buildMockRedisCluster(commands);
|
||||
Accounts accounts = mock(Accounts.class);
|
||||
AccountsDynamoDb accountsDynamoDb = mock(AccountsDynamoDb.class);
|
||||
DeletedAccounts deletedAccounts = mock(DeletedAccounts.class);
|
||||
DirectoryQueue directoryQueue = mock(DirectoryQueue.class);
|
||||
KeysDynamoDb keysDynamoDb = mock(KeysDynamoDb.class);
|
||||
MessagesManager messagesManager = mock(MessagesManager.class);
|
||||
@@ -134,7 +138,8 @@ class AccountsManagerTest {
|
||||
|
||||
when(commands.get(eq("Account3::" + uuid.toString()))).thenReturn("{\"number\": \"+14152222222\", \"name\": \"test\"}");
|
||||
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, accountsDynamoDb, cacheCluster, directoryQueue, keysDynamoDb, messagesManager, usernamesManager, profilesManager, secureStorageClient, secureBackupClient, experimentEnrollmentManager, dynamicConfigurationManager);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, accountsDynamoDb, cacheCluster, deletedAccounts,
|
||||
directoryQueue, keysDynamoDb, messagesManager, usernamesManager, profilesManager, secureStorageClient, secureBackupClient, experimentEnrollmentManager, dynamicConfigurationManager);
|
||||
Optional<Account> account = accountsManager.get(uuid);
|
||||
|
||||
assertTrue(account.isPresent());
|
||||
@@ -157,6 +162,7 @@ class AccountsManagerTest {
|
||||
FaultTolerantRedisCluster cacheCluster = RedisClusterHelper.buildMockRedisCluster(commands);
|
||||
Accounts accounts = mock(Accounts.class);
|
||||
AccountsDynamoDb accountsDynamoDb = mock(AccountsDynamoDb.class);
|
||||
DeletedAccounts deletedAccounts = mock(DeletedAccounts.class);
|
||||
DirectoryQueue directoryQueue = mock(DirectoryQueue.class);
|
||||
KeysDynamoDb keysDynamoDb = mock(KeysDynamoDb.class);
|
||||
MessagesManager messagesManager = mock(MessagesManager.class);
|
||||
@@ -172,7 +178,8 @@ class AccountsManagerTest {
|
||||
when(commands.get(eq("AccountMap::+14152222222"))).thenReturn(null);
|
||||
when(accounts.get(eq("+14152222222"))).thenReturn(Optional.of(account));
|
||||
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, accountsDynamoDb, cacheCluster, directoryQueue, keysDynamoDb, messagesManager, usernamesManager, profilesManager, secureStorageClient, secureBackupClient, experimentEnrollmentManager, dynamicConfigurationManager);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, accountsDynamoDb, cacheCluster, deletedAccounts,
|
||||
directoryQueue, keysDynamoDb, messagesManager, usernamesManager, profilesManager, secureStorageClient, secureBackupClient, experimentEnrollmentManager, dynamicConfigurationManager);
|
||||
Optional<Account> retrieved = accountsManager.get("+14152222222");
|
||||
|
||||
assertTrue(retrieved.isPresent());
|
||||
@@ -198,6 +205,7 @@ class AccountsManagerTest {
|
||||
FaultTolerantRedisCluster cacheCluster = RedisClusterHelper.buildMockRedisCluster(commands);
|
||||
Accounts accounts = mock(Accounts.class);
|
||||
AccountsDynamoDb accountsDynamoDb = mock(AccountsDynamoDb.class);
|
||||
DeletedAccounts deletedAccounts = mock(DeletedAccounts.class);
|
||||
DirectoryQueue directoryQueue = mock(DirectoryQueue.class);
|
||||
KeysDynamoDb keysDynamoDb = mock(KeysDynamoDb.class);
|
||||
MessagesManager messagesManager = mock(MessagesManager.class);
|
||||
@@ -213,7 +221,8 @@ class AccountsManagerTest {
|
||||
when(commands.get(eq("Account3::" + uuid))).thenReturn(null);
|
||||
when(accounts.get(eq(uuid))).thenReturn(Optional.of(account));
|
||||
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, accountsDynamoDb, cacheCluster, directoryQueue, keysDynamoDb, messagesManager, usernamesManager, profilesManager, secureStorageClient, secureBackupClient, experimentEnrollmentManager, dynamicConfigurationManager);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, accountsDynamoDb, cacheCluster, deletedAccounts,
|
||||
directoryQueue, keysDynamoDb, messagesManager, usernamesManager, profilesManager, secureStorageClient, secureBackupClient, experimentEnrollmentManager, dynamicConfigurationManager);
|
||||
Optional<Account> retrieved = accountsManager.get(uuid);
|
||||
|
||||
assertTrue(retrieved.isPresent());
|
||||
@@ -238,6 +247,7 @@ class AccountsManagerTest {
|
||||
FaultTolerantRedisCluster cacheCluster = RedisClusterHelper.buildMockRedisCluster(commands);
|
||||
Accounts accounts = mock(Accounts.class);
|
||||
AccountsDynamoDb accountsDynamoDb = mock(AccountsDynamoDb.class);
|
||||
DeletedAccounts deletedAccounts = mock(DeletedAccounts.class);
|
||||
DirectoryQueue directoryQueue = mock(DirectoryQueue.class);
|
||||
KeysDynamoDb keysDynamoDb = mock(KeysDynamoDb.class);
|
||||
MessagesManager messagesManager = mock(MessagesManager.class);
|
||||
@@ -253,7 +263,8 @@ class AccountsManagerTest {
|
||||
when(commands.get(eq("AccountMap::+14152222222"))).thenThrow(new RedisException("Connection lost!"));
|
||||
when(accounts.get(eq("+14152222222"))).thenReturn(Optional.of(account));
|
||||
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, accountsDynamoDb, cacheCluster, directoryQueue, keysDynamoDb, messagesManager, usernamesManager, profilesManager, secureStorageClient, secureBackupClient, experimentEnrollmentManager, dynamicConfigurationManager);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, accountsDynamoDb, cacheCluster, deletedAccounts,
|
||||
directoryQueue, keysDynamoDb, messagesManager, usernamesManager, profilesManager, secureStorageClient, secureBackupClient, experimentEnrollmentManager, dynamicConfigurationManager);
|
||||
Optional<Account> retrieved = accountsManager.get("+14152222222");
|
||||
|
||||
assertTrue(retrieved.isPresent());
|
||||
@@ -278,6 +289,7 @@ class AccountsManagerTest {
|
||||
FaultTolerantRedisCluster cacheCluster = RedisClusterHelper.buildMockRedisCluster(commands);
|
||||
Accounts accounts = mock(Accounts.class);
|
||||
AccountsDynamoDb accountsDynamoDb = mock(AccountsDynamoDb.class);
|
||||
DeletedAccounts deletedAccounts = mock(DeletedAccounts.class);
|
||||
DirectoryQueue directoryQueue = mock(DirectoryQueue.class);
|
||||
KeysDynamoDb keysDynamoDb = mock(KeysDynamoDb.class);
|
||||
MessagesManager messagesManager = mock(MessagesManager.class);
|
||||
@@ -293,7 +305,8 @@ class AccountsManagerTest {
|
||||
when(commands.get(eq("Account3::" + uuid))).thenThrow(new RedisException("Connection lost!"));
|
||||
when(accounts.get(eq(uuid))).thenReturn(Optional.of(account));
|
||||
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, accountsDynamoDb, cacheCluster, directoryQueue, keysDynamoDb, messagesManager, usernamesManager, profilesManager, secureStorageClient, secureBackupClient, experimentEnrollmentManager, dynamicConfigurationManager);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, accountsDynamoDb, cacheCluster, deletedAccounts,
|
||||
directoryQueue, keysDynamoDb, messagesManager, usernamesManager, profilesManager, secureStorageClient, secureBackupClient, experimentEnrollmentManager, dynamicConfigurationManager);
|
||||
Optional<Account> retrieved = accountsManager.get(uuid);
|
||||
|
||||
assertTrue(retrieved.isPresent());
|
||||
@@ -318,6 +331,7 @@ class AccountsManagerTest {
|
||||
FaultTolerantRedisCluster cacheCluster = RedisClusterHelper.buildMockRedisCluster(commands);
|
||||
Accounts accounts = mock(Accounts.class);
|
||||
AccountsDynamoDb accountsDynamoDb = mock(AccountsDynamoDb.class);
|
||||
DeletedAccounts deletedAccounts = mock(DeletedAccounts.class);
|
||||
DirectoryQueue directoryQueue = mock(DirectoryQueue.class);
|
||||
KeysDynamoDb keysDynamoDb = mock(KeysDynamoDb.class);
|
||||
MessagesManager messagesManager = mock(MessagesManager.class);
|
||||
@@ -332,7 +346,8 @@ class AccountsManagerTest {
|
||||
|
||||
when(commands.get(eq("Account3::" + uuid))).thenReturn(null);
|
||||
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, accountsDynamoDb, cacheCluster, directoryQueue, keysDynamoDb, messagesManager, usernamesManager, profilesManager, secureStorageClient, secureBackupClient, experimentEnrollmentManager, dynamicConfigurationManager);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, accountsDynamoDb, cacheCluster, deletedAccounts,
|
||||
directoryQueue, keysDynamoDb, messagesManager, usernamesManager, profilesManager, secureStorageClient, secureBackupClient, experimentEnrollmentManager, dynamicConfigurationManager);
|
||||
|
||||
assertEquals(0, account.getDynamoDbMigrationVersion());
|
||||
|
||||
@@ -353,6 +368,7 @@ class AccountsManagerTest {
|
||||
FaultTolerantRedisCluster cacheCluster = RedisClusterHelper.buildMockRedisCluster(commands);
|
||||
Accounts accounts = mock(Accounts.class);
|
||||
AccountsDynamoDb accountsDynamoDb = mock(AccountsDynamoDb.class);
|
||||
DeletedAccounts deletedAccounts = mock(DeletedAccounts.class);
|
||||
DirectoryQueue directoryQueue = mock(DirectoryQueue.class);
|
||||
KeysDynamoDb keysDynamoDb = mock(KeysDynamoDb.class);
|
||||
MessagesManager messagesManager = mock(MessagesManager.class);
|
||||
@@ -368,7 +384,8 @@ class AccountsManagerTest {
|
||||
when(commands.get(eq("Account3::" + uuid))).thenReturn(null);
|
||||
doThrow(ConditionalCheckFailedException.class).when(accountsDynamoDb).update(any(Account.class));
|
||||
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, accountsDynamoDb, cacheCluster, directoryQueue, keysDynamoDb, messagesManager, usernamesManager, profilesManager, secureStorageClient, secureBackupClient, experimentEnrollmentManager, dynamicConfigurationManager);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, accountsDynamoDb, cacheCluster, deletedAccounts,
|
||||
directoryQueue, keysDynamoDb, messagesManager, usernamesManager, profilesManager, secureStorageClient, secureBackupClient, experimentEnrollmentManager, dynamicConfigurationManager);
|
||||
|
||||
assertEquals(0, account.getDynamoDbMigrationVersion());
|
||||
|
||||
@@ -390,6 +407,7 @@ class AccountsManagerTest {
|
||||
FaultTolerantRedisCluster cacheCluster = RedisClusterHelper.buildMockRedisCluster(commands);
|
||||
Accounts accounts = mock(Accounts.class);
|
||||
AccountsDynamoDb accountsDynamoDb = mock(AccountsDynamoDb.class);
|
||||
DeletedAccounts deletedAccounts = mock(DeletedAccounts.class);
|
||||
DirectoryQueue directoryQueue = mock(DirectoryQueue.class);
|
||||
KeysDynamoDb keysDynamoDb = mock(KeysDynamoDb.class);
|
||||
MessagesManager messagesManager = mock(MessagesManager.class);
|
||||
@@ -398,7 +416,8 @@ class AccountsManagerTest {
|
||||
SecureBackupClient secureBackupClient = mock(SecureBackupClient.class);
|
||||
SecureStorageClient secureStorageClient = mock(SecureStorageClient.class);
|
||||
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, accountsDynamoDb, cacheCluster, directoryQueue, keysDynamoDb, messagesManager, usernamesManager, profilesManager, secureStorageClient, secureBackupClient, experimentEnrollmentManager, dynamicConfigurationManager);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, accountsDynamoDb, cacheCluster, deletedAccounts,
|
||||
directoryQueue, keysDynamoDb, messagesManager, usernamesManager, profilesManager, secureStorageClient, secureBackupClient, experimentEnrollmentManager, dynamicConfigurationManager);
|
||||
|
||||
assertEquals(Optional.empty(), accountsManager.compareAccounts(Optional.empty(), Optional.empty()));
|
||||
|
||||
|
||||
+1
-1
@@ -318,7 +318,7 @@ public class AccountsTest {
|
||||
SignedPreKey signedPreKey = new SignedPreKey(random.nextInt(), "testPublicKey-" + random.nextInt(), "testSignature-" + random.nextInt());
|
||||
return new Device(id, "testName-" + random.nextInt(), "testAuthToken-" + random.nextInt(), "testSalt-" + random.nextInt(),
|
||||
"testGcmId-" + random.nextInt(), "testApnId-" + random.nextInt(), "testVoipApnId-" + random.nextInt(), random.nextBoolean(), random.nextInt(), signedPreKey, random.nextInt(), random.nextInt(), "testUserAgent-" + random.nextInt() , 0, new Device.DeviceCapabilities(random.nextBoolean(), random.nextBoolean(), random.nextBoolean(), random.nextBoolean(), random.nextBoolean(), random.nextBoolean(),
|
||||
false));
|
||||
random.nextBoolean(), random.nextBoolean()));
|
||||
}
|
||||
|
||||
private Account generateAccount(String number, UUID uuid) {
|
||||
|
||||
+1
-1
@@ -67,7 +67,7 @@ public class MessagesDynamoDbTest {
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
messagesDynamoDb = new MessagesDynamoDb(dynamoDbRule.getDynamoDB(), MessagesDynamoDbRule.TABLE_NAME, Duration.ofDays(7));
|
||||
messagesDynamoDb = new MessagesDynamoDb(dynamoDbRule.getDynamoDbClient(), MessagesDynamoDbRule.TABLE_NAME, Duration.ofDays(7));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
-222
@@ -1,222 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.tests.storage;
|
||||
|
||||
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
|
||||
|
||||
import com.opentable.db.postgres.embedded.LiquibasePreparer;
|
||||
import com.opentable.db.postgres.junit5.EmbeddedPostgresExtension;
|
||||
import com.opentable.db.postgres.junit5.PreparedDbExtension;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Optional;
|
||||
import org.jdbi.v3.core.Jdbi;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.auth.StoredVerificationCode;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.storage.FaultTolerantDatabase;
|
||||
import org.whispersystems.textsecuregcm.storage.PendingAccounts;
|
||||
|
||||
class PendingAccountsTest {
|
||||
|
||||
@RegisterExtension
|
||||
static PreparedDbExtension db = EmbeddedPostgresExtension.preparedDatabase(LiquibasePreparer.forClasspathLocation("accountsdb.xml"));
|
||||
|
||||
private PendingAccounts pendingAccounts;
|
||||
|
||||
@BeforeEach
|
||||
void setupAccountsDao() {
|
||||
this.pendingAccounts = new PendingAccounts(new FaultTolerantDatabase("pending_accounts-test", Jdbi.create(db.getTestDatabase()), new CircuitBreakerConfiguration()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testStore() throws SQLException {
|
||||
pendingAccounts.insert("+14151112222", "1234", 1111, null);
|
||||
|
||||
PreparedStatement statement = db.getTestDatabase().getConnection().prepareStatement("SELECT * FROM pending_accounts WHERE number = ?");
|
||||
statement.setString(1, "+14151112222");
|
||||
|
||||
ResultSet resultSet = statement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
assertThat(resultSet.getString("verification_code")).isEqualTo("1234");
|
||||
assertThat(resultSet.getLong("timestamp")).isEqualTo(1111);
|
||||
assertThat(resultSet.getString("push_code")).isNull();
|
||||
} else {
|
||||
throw new AssertionError("no results");
|
||||
}
|
||||
|
||||
assertThat(resultSet.next()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testStoreWithPushChallenge() throws SQLException {
|
||||
pendingAccounts.insert("+14151112222", null, 1111, "112233");
|
||||
|
||||
PreparedStatement statement = db.getTestDatabase().getConnection().prepareStatement("SELECT * FROM pending_accounts WHERE number = ?");
|
||||
statement.setString(1, "+14151112222");
|
||||
|
||||
ResultSet resultSet = statement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
assertThat(resultSet.getString("verification_code")).isNull();
|
||||
assertThat(resultSet.getLong("timestamp")).isEqualTo(1111);
|
||||
assertThat(resultSet.getString("push_code")).isEqualTo("112233");
|
||||
} else {
|
||||
throw new AssertionError("no results");
|
||||
}
|
||||
|
||||
assertThat(resultSet.next()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testStoreWithTwilioVerificationSid() throws SQLException {
|
||||
pendingAccounts.insert("+14151112222", null, 1111, null, "id1");
|
||||
|
||||
PreparedStatement statement = db.getTestDatabase().getConnection()
|
||||
.prepareStatement("SELECT * FROM pending_accounts WHERE number = ?");
|
||||
statement.setString(1, "+14151112222");
|
||||
|
||||
ResultSet resultSet = statement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
assertThat(resultSet.getString("verification_code")).isNull();
|
||||
assertThat(resultSet.getLong("timestamp")).isEqualTo(1111);
|
||||
assertThat(resultSet.getString("push_code")).isNull();
|
||||
assertThat(resultSet.getString("twilio_verification_sid")).isEqualTo("id1");
|
||||
} else {
|
||||
throw new AssertionError("no results");
|
||||
}
|
||||
|
||||
assertThat(resultSet.next()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRetrieve() throws Exception {
|
||||
pendingAccounts.insert("+14151112222", "4321", 2222, null);
|
||||
pendingAccounts.insert("+14151113333", "1212", 5555, null);
|
||||
|
||||
Optional<StoredVerificationCode> verificationCode = pendingAccounts.getCodeForNumber("+14151112222");
|
||||
|
||||
assertThat(verificationCode.isPresent()).isTrue();
|
||||
assertThat(verificationCode.get().getCode()).isEqualTo("4321");
|
||||
assertThat(verificationCode.get().getTimestamp()).isEqualTo(2222);
|
||||
|
||||
Optional<StoredVerificationCode> missingCode = pendingAccounts.getCodeForNumber("+11111111111");
|
||||
assertThat(missingCode.isPresent()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRetrieveWithPushChallenge() throws Exception {
|
||||
pendingAccounts.insert("+14151112222", "4321", 2222, "bar");
|
||||
pendingAccounts.insert("+14151113333", "1212", 5555, "bang");
|
||||
|
||||
Optional<StoredVerificationCode> verificationCode = pendingAccounts.getCodeForNumber("+14151112222");
|
||||
|
||||
assertThat(verificationCode.isPresent()).isTrue();
|
||||
assertThat(verificationCode.get().getCode()).isEqualTo("4321");
|
||||
assertThat(verificationCode.get().getTimestamp()).isEqualTo(2222);
|
||||
assertThat(verificationCode.get().getPushCode()).isEqualTo("bar");
|
||||
|
||||
Optional<StoredVerificationCode> missingCode = pendingAccounts.getCodeForNumber("+11111111111");
|
||||
assertThat(missingCode.isPresent()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRetrieveWithTwilioVerificationSid() throws Exception {
|
||||
pendingAccounts.insert("+14151112222", "4321", 2222, "bar", "id1");
|
||||
pendingAccounts.insert("+14151113333", "1212", 5555, "bang", "id2");
|
||||
|
||||
Optional<StoredVerificationCode> verificationCode = pendingAccounts.getCodeForNumber("+14151112222");
|
||||
|
||||
assertThat(verificationCode).isPresent();
|
||||
assertThat(verificationCode.get().getCode()).isEqualTo("4321");
|
||||
assertThat(verificationCode.get().getTimestamp()).isEqualTo(2222);
|
||||
assertThat(verificationCode.get().getPushCode()).isEqualTo("bar");
|
||||
assertThat(verificationCode.get().getTwilioVerificationSid()).contains("id1");
|
||||
|
||||
Optional<StoredVerificationCode> missingCode = pendingAccounts.getCodeForNumber("+11111111111");
|
||||
assertThat(missingCode).isNotPresent();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testOverwrite() throws Exception {
|
||||
pendingAccounts.insert("+14151112222", "4321", 2222, null);
|
||||
pendingAccounts.insert("+14151112222", "4444", 3333, null);
|
||||
|
||||
Optional<StoredVerificationCode> verificationCode = pendingAccounts.getCodeForNumber("+14151112222");
|
||||
|
||||
assertThat(verificationCode.isPresent()).isTrue();
|
||||
assertThat(verificationCode.get().getCode()).isEqualTo("4444");
|
||||
assertThat(verificationCode.get().getTimestamp()).isEqualTo(3333);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testOverwriteWithPushToken() throws Exception {
|
||||
pendingAccounts.insert("+14151112222", "4321", 2222, "bar");
|
||||
pendingAccounts.insert("+14151112222", "4444", 3333, "bang");
|
||||
|
||||
Optional<StoredVerificationCode> verificationCode = pendingAccounts.getCodeForNumber("+14151112222");
|
||||
|
||||
assertThat(verificationCode.isPresent()).isTrue();
|
||||
assertThat(verificationCode.get().getCode()).isEqualTo("4444");
|
||||
assertThat(verificationCode.get().getTimestamp()).isEqualTo(3333);
|
||||
assertThat(verificationCode.get().getPushCode()).isEqualTo("bang");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testOverwriteWithTwilioVerificationSid() throws Exception {
|
||||
pendingAccounts.insert("+14151112222", "4321", 2222, "bar", "id1");
|
||||
pendingAccounts.insert("+14151112222", "4444", 3333, "bang", "id2");
|
||||
|
||||
Optional<StoredVerificationCode> verificationCode = pendingAccounts.getCodeForNumber("+14151112222");
|
||||
|
||||
assertThat(verificationCode.isPresent()).isTrue();
|
||||
assertThat(verificationCode.get().getCode()).isEqualTo("4444");
|
||||
assertThat(verificationCode.get().getTimestamp()).isEqualTo(3333);
|
||||
assertThat(verificationCode.get().getPushCode()).isEqualTo("bang");
|
||||
assertThat(verificationCode.get().getTwilioVerificationSid()).contains("id2");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testVacuum() {
|
||||
pendingAccounts.insert("+14151112222", "4321", 2222, null);
|
||||
pendingAccounts.insert("+14151112222", "4444", 3333, null);
|
||||
pendingAccounts.vacuum();
|
||||
|
||||
Optional<StoredVerificationCode> verificationCode = pendingAccounts.getCodeForNumber("+14151112222");
|
||||
|
||||
assertThat(verificationCode.isPresent()).isTrue();
|
||||
assertThat(verificationCode.get().getCode()).isEqualTo("4444");
|
||||
assertThat(verificationCode.get().getTimestamp()).isEqualTo(3333);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRemove() {
|
||||
pendingAccounts.insert("+14151112222", "4321", 2222, "bar");
|
||||
pendingAccounts.insert("+14151113333", "1212", 5555, null);
|
||||
|
||||
Optional<StoredVerificationCode> verificationCode = pendingAccounts.getCodeForNumber("+14151112222");
|
||||
|
||||
assertThat(verificationCode.isPresent()).isTrue();
|
||||
assertThat(verificationCode.get().getCode()).isEqualTo("4321");
|
||||
assertThat(verificationCode.get().getTimestamp()).isEqualTo(2222);
|
||||
|
||||
pendingAccounts.remove("+14151112222");
|
||||
|
||||
verificationCode = pendingAccounts.getCodeForNumber("+14151112222");
|
||||
assertThat(verificationCode.isPresent()).isFalse();
|
||||
|
||||
verificationCode = pendingAccounts.getCodeForNumber("+14151113333");
|
||||
assertThat(verificationCode.isPresent()).isTrue();
|
||||
assertThat(verificationCode.get().getCode()).isEqualTo("1212");
|
||||
assertThat(verificationCode.get().getTimestamp()).isEqualTo(5555);
|
||||
assertThat(verificationCode.get().getPushCode()).isNull();
|
||||
}
|
||||
}
|
||||
-107
@@ -1,107 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.tests.storage;
|
||||
|
||||
import com.opentable.db.postgres.embedded.LiquibasePreparer;
|
||||
import com.opentable.db.postgres.junit.EmbeddedPostgresRules;
|
||||
import com.opentable.db.postgres.junit.PreparedDbRule;
|
||||
import org.jdbi.v3.core.Jdbi;
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.whispersystems.textsecuregcm.auth.StoredVerificationCode;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.storage.FaultTolerantDatabase;
|
||||
import org.whispersystems.textsecuregcm.storage.PendingDevices;
|
||||
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
|
||||
|
||||
public class PendingDevicesTest {
|
||||
|
||||
@Rule
|
||||
public PreparedDbRule db = EmbeddedPostgresRules.preparedDatabase(LiquibasePreparer.forClasspathLocation("accountsdb.xml"));
|
||||
|
||||
private PendingDevices pendingDevices;
|
||||
|
||||
@Before
|
||||
public void setupAccountsDao() {
|
||||
this.pendingDevices = new PendingDevices(new FaultTolerantDatabase("peding_devices-test", Jdbi.create(db.getTestDatabase()), new CircuitBreakerConfiguration()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStore() throws SQLException {
|
||||
pendingDevices.insert("+14151112222", "1234", 1111);
|
||||
|
||||
PreparedStatement statement = db.getTestDatabase().getConnection().prepareStatement("SELECT * FROM pending_devices WHERE number = ?");
|
||||
statement.setString(1, "+14151112222");
|
||||
|
||||
ResultSet resultSet = statement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
assertThat(resultSet.getString("verification_code")).isEqualTo("1234");
|
||||
assertThat(resultSet.getLong("timestamp")).isEqualTo(1111);
|
||||
} else {
|
||||
throw new AssertionError("no results");
|
||||
}
|
||||
|
||||
assertThat(resultSet.next()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRetrieve() throws Exception {
|
||||
pendingDevices.insert("+14151112222", "4321", 2222);
|
||||
pendingDevices.insert("+14151113333", "1212", 5555);
|
||||
|
||||
Optional<StoredVerificationCode> verificationCode = pendingDevices.getCodeForNumber("+14151112222");
|
||||
|
||||
assertThat(verificationCode.isPresent()).isTrue();
|
||||
assertThat(verificationCode.get().getCode()).isEqualTo("4321");
|
||||
assertThat(verificationCode.get().getTimestamp()).isEqualTo(2222);
|
||||
|
||||
Optional<StoredVerificationCode> missingCode = pendingDevices.getCodeForNumber("+11111111111");
|
||||
assertThat(missingCode.isPresent()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOverwrite() throws Exception {
|
||||
pendingDevices.insert("+14151112222", "4321", 2222);
|
||||
pendingDevices.insert("+14151112222", "4444", 3333);
|
||||
|
||||
Optional<StoredVerificationCode> verificationCode = pendingDevices.getCodeForNumber("+14151112222");
|
||||
|
||||
assertThat(verificationCode.isPresent()).isTrue();
|
||||
assertThat(verificationCode.get().getCode()).isEqualTo("4444");
|
||||
assertThat(verificationCode.get().getTimestamp()).isEqualTo(3333);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRemove() {
|
||||
pendingDevices.insert("+14151112222", "4321", 2222);
|
||||
pendingDevices.insert("+14151113333", "1212", 5555);
|
||||
|
||||
Optional<StoredVerificationCode> verificationCode = pendingDevices.getCodeForNumber("+14151112222");
|
||||
|
||||
assertThat(verificationCode.isPresent()).isTrue();
|
||||
assertThat(verificationCode.get().getCode()).isEqualTo("4321");
|
||||
assertThat(verificationCode.get().getTimestamp()).isEqualTo(2222);
|
||||
|
||||
pendingDevices.remove("+14151112222");
|
||||
|
||||
verificationCode = pendingDevices.getCodeForNumber("+14151112222");
|
||||
assertThat(verificationCode.isPresent()).isFalse();
|
||||
|
||||
verificationCode = pendingDevices.getCodeForNumber("+14151113333");
|
||||
assertThat(verificationCode.isPresent()).isTrue();
|
||||
assertThat(verificationCode.get().getCode()).isEqualTo("1212");
|
||||
assertThat(verificationCode.get().getTimestamp()).isEqualTo(5555);
|
||||
}
|
||||
|
||||
}
|
||||
+12
-11
@@ -6,16 +6,16 @@
|
||||
package org.whispersystems.textsecuregcm.tests.util;
|
||||
|
||||
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.AmazonDynamoDBClientBuilder;
|
||||
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.local.main.ServerRunner;
|
||||
import com.amazonaws.services.dynamodbv2.local.server.DynamoDBProxyServer;
|
||||
import org.junit.rules.ExternalResource;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
|
||||
import java.net.ServerSocket;
|
||||
import java.net.URI;
|
||||
|
||||
public class LocalDynamoDbRule extends ExternalResource {
|
||||
private DynamoDBProxyServer server;
|
||||
@@ -43,11 +43,12 @@ public class LocalDynamoDbRule extends ExternalResource {
|
||||
super.after();
|
||||
}
|
||||
|
||||
public DynamoDB getDynamoDB() {
|
||||
AmazonDynamoDBClientBuilder clientBuilder =
|
||||
AmazonDynamoDBClientBuilder.standard()
|
||||
.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:" + port, "local-test-region"))
|
||||
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("accessKey", "secretKey")));
|
||||
return new DynamoDB(clientBuilder.build());
|
||||
public DynamoDbClient getDynamoDbClient() {
|
||||
return DynamoDbClient.builder()
|
||||
.endpointOverride(URI.create("http://localhost:" + port))
|
||||
.region(Region.of("local-test-region"))
|
||||
.credentialsProvider(StaticCredentialsProvider.create(
|
||||
AwsBasicCredentials.create("accessKey", "secretKey")))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+24
-23
@@ -5,15 +5,15 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.tests.util;
|
||||
|
||||
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
|
||||
import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
|
||||
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
|
||||
import com.amazonaws.services.dynamodbv2.model.LocalSecondaryIndex;
|
||||
import com.amazonaws.services.dynamodbv2.model.Projection;
|
||||
import com.amazonaws.services.dynamodbv2.model.ProjectionType;
|
||||
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
|
||||
import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
|
||||
import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;
|
||||
import software.amazon.awssdk.services.dynamodb.model.KeyType;
|
||||
import software.amazon.awssdk.services.dynamodb.model.LocalSecondaryIndex;
|
||||
import software.amazon.awssdk.services.dynamodb.model.Projection;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ProjectionType;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;
|
||||
|
||||
public class MessagesDynamoDbRule extends LocalDynamoDbRule {
|
||||
|
||||
@@ -22,20 +22,21 @@ public class MessagesDynamoDbRule extends LocalDynamoDbRule {
|
||||
@Override
|
||||
protected void before() throws Throwable {
|
||||
super.before();
|
||||
DynamoDB dynamoDB = getDynamoDB();
|
||||
CreateTableRequest createTableRequest = new CreateTableRequest()
|
||||
.withTableName(TABLE_NAME)
|
||||
.withKeySchema(new KeySchemaElement("H", "HASH"),
|
||||
new KeySchemaElement("S", "RANGE"))
|
||||
.withAttributeDefinitions(new AttributeDefinition("H", ScalarAttributeType.B),
|
||||
new AttributeDefinition("S", ScalarAttributeType.B),
|
||||
new AttributeDefinition("U", ScalarAttributeType.B))
|
||||
.withProvisionedThroughput(new ProvisionedThroughput(20L, 20L))
|
||||
.withLocalSecondaryIndexes(new LocalSecondaryIndex().withIndexName("Message_UUID_Index")
|
||||
.withKeySchema(new KeySchemaElement("H", "HASH"),
|
||||
new KeySchemaElement("U", "RANGE"))
|
||||
.withProjection(new Projection().withProjectionType(ProjectionType.KEYS_ONLY)));
|
||||
dynamoDB.createTable(createTableRequest);
|
||||
getDynamoDbClient().createTable(CreateTableRequest.builder()
|
||||
.tableName(TABLE_NAME)
|
||||
.keySchema(KeySchemaElement.builder().attributeName("H").keyType(KeyType.HASH).build(),
|
||||
KeySchemaElement.builder().attributeName("S").keyType(KeyType.RANGE).build())
|
||||
.attributeDefinitions(
|
||||
AttributeDefinition.builder().attributeName("H").attributeType(ScalarAttributeType.B).build(),
|
||||
AttributeDefinition.builder().attributeName("S").attributeType(ScalarAttributeType.B).build(),
|
||||
AttributeDefinition.builder().attributeName("U").attributeType(ScalarAttributeType.B).build())
|
||||
.provisionedThroughput(ProvisionedThroughput.builder().readCapacityUnits(20L).writeCapacityUnits(20L).build())
|
||||
.localSecondaryIndexes(LocalSecondaryIndex.builder().indexName("Message_UUID_Index")
|
||||
.keySchema(KeySchemaElement.builder().attributeName("H").keyType(KeyType.HASH).build(),
|
||||
KeySchemaElement.builder().attributeName("U").keyType(KeyType.RANGE).build())
|
||||
.projection(Projection.builder().projectionType(ProjectionType.KEYS_ONLY).build())
|
||||
.build())
|
||||
.build());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -12,7 +12,6 @@ import java.io.InputStreamReader;
|
||||
import java.net.Inet4Address;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.Optional;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class AttributeValuesTest {
|
||||
@Test
|
||||
void testUUIDRoundTrip() {
|
||||
UUID orig = UUID.randomUUID();
|
||||
AttributeValue av = AttributeValues.fromUUID(orig);
|
||||
UUID returned = AttributeValues.getUUID(Map.of("foo", av), "foo", null);
|
||||
assertEquals(orig, returned);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testLongRoundTrip() {
|
||||
long orig = 12345;
|
||||
AttributeValue av = AttributeValues.fromLong(orig);
|
||||
long returned = AttributeValues.getLong(Map.of("foo", av), "foo", -1);
|
||||
assertEquals(orig, returned);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIntRoundTrip() {
|
||||
int orig = 12345;
|
||||
AttributeValue av = AttributeValues.fromInt(orig);
|
||||
int returned = AttributeValues.getInt(Map.of("foo", av), "foo", -1);
|
||||
assertEquals(orig, returned);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testByteBuffer() {
|
||||
byte[] bytes = {1, 2, 3};
|
||||
ByteBuffer bb = ByteBuffer.wrap(bytes);
|
||||
AttributeValue av = AttributeValues.fromByteBuffer(bb);
|
||||
byte[] returned = av.b().asByteArray();
|
||||
assertArrayEquals(bytes, returned);
|
||||
returned = AttributeValues.getByteArray(Map.of("foo", av), "foo", null);
|
||||
assertArrayEquals(bytes, returned);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testByteBuffer2() {
|
||||
final ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[8]);
|
||||
byteBuffer.putLong(123);
|
||||
assertEquals(byteBuffer.remaining(), 0);
|
||||
AttributeValue av = AttributeValues.fromByteBuffer(byteBuffer.flip());
|
||||
assertArrayEquals(new byte[]{0, 0, 0, 0, 0, 0, 0, 123}, AttributeValues.getByteArray(Map.of("foo", av), "foo", null));
|
||||
}
|
||||
}
|
||||
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user