mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-11-30 23:16:47 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
33467b42da | ||
|
|
13fb641113 | ||
|
|
53f17c2baa | ||
|
|
06a57ef811 | ||
|
|
86a09b16ff | ||
|
|
c70d7535b9 | ||
|
|
8541360bf3 | ||
|
|
2a832d36d7 | ||
|
|
1578c89475 | ||
|
|
5c13e54149 | ||
|
|
8e74cf6633 | ||
|
|
bab6b36e4d | ||
|
|
f75e616397 | ||
|
|
941a9c3b39 | ||
|
|
7ba0f604e6 | ||
|
|
cf8a4cc939 | ||
|
|
ee78daeeef | ||
|
|
2f6b0b1a55 | ||
|
|
c048074c31 | ||
|
|
5ca89709e3 | ||
|
|
5a88ff0811 | ||
|
|
de68c251f8 | ||
|
|
7c9ae3561d | ||
|
|
b608ece57e | ||
|
|
8dfffebaf1 | ||
|
|
109a3bb2b9 | ||
|
|
fef37f739b | ||
|
|
7a5615182a | ||
|
|
02a7003ffe | ||
|
|
1571f14815 | ||
|
|
9cb098ad8a | ||
|
|
6283f5952d | ||
|
|
9b9edbae0e | ||
|
|
491155d1cf | ||
|
|
54207254f1 | ||
|
|
1395dcc0be | ||
|
|
2a68d9095d | ||
|
|
a984b3640e | ||
|
|
f9c1e411aa | ||
|
|
f6cbc32ee7 | ||
|
|
602614acf6 | ||
|
|
3854b7d472 | ||
|
|
5e25481088 | ||
|
|
fe86e15d80 | ||
|
|
179b4a69eb | ||
|
|
eee6307789 | ||
|
|
9fc5002619 | ||
|
|
faa6ae284a | ||
|
|
8b4355b21d | ||
|
|
e8835da740 | ||
|
|
75854e104e | ||
|
|
93d06e3f4d | ||
|
|
c560b9229c | ||
|
|
935e268dec |
No files matched your search
+1
-1
Submodule abusive-message-filter updated: 00e8b75003...5f4e692e02.
@@ -141,7 +141,7 @@ class SenderTest {
|
||||
CompletableFuture<Result> future = sender.send(Message.newBuilder().withDestination("1").build());
|
||||
|
||||
// up to three failures can happen, with 100ms exponential backoff
|
||||
// if we end up using the fourth, and finaly try, it would be after ~700 ms
|
||||
// if we end up using the fourth, and final try, it would be after ~700 ms
|
||||
CompletableFuture.delayedExecutor(300, TimeUnit.MILLISECONDS).execute(() ->
|
||||
wireMock.stubFor(any(anyUrl())
|
||||
.willReturn(aResponse()
|
||||
|
||||
@@ -54,16 +54,15 @@
|
||||
<jaxb.version>2.3.1</jaxb.version>
|
||||
<jedis.version>2.9.0</jedis.version>
|
||||
<lettuce.version>6.0.4.RELEASE</lettuce.version>
|
||||
<libphonenumber.version>8.12.42</libphonenumber.version>
|
||||
<logstash.logback.version>6.6</logstash.logback.version>
|
||||
<libphonenumber.version>8.12.45</libphonenumber.version>
|
||||
<logstash.logback.version>7.0.1</logstash.logback.version>
|
||||
<micrometer.version>1.5.3</micrometer.version>
|
||||
<mockito.version>4.0.0</mockito.version>
|
||||
<mockito.version>4.3.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>
|
||||
<postgresql.version>42.3.3</postgresql.version>
|
||||
<protobuf.version>3.17.1</protobuf.version>
|
||||
<pushy.version>0.15.0</pushy.version>
|
||||
<protobuf.version>3.19.4</protobuf.version>
|
||||
<pushy.version>0.15.1</pushy.version>
|
||||
<resilience4j.version>1.5.0</resilience4j.version>
|
||||
<semver4j.version>3.1.0</semver4j.version>
|
||||
<slf4j.version>1.7.30</slf4j.version>
|
||||
@@ -173,12 +172,6 @@
|
||||
<artifactId>lettuce-core</artifactId>
|
||||
<version>${lettuce.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty-tcnative-boringssl-static</artifactId>
|
||||
<version>${netty.tcnative-boringssl-static.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.xml.bind</groupId>
|
||||
<artifactId>jaxb-api</artifactId>
|
||||
|
||||
@@ -78,17 +78,6 @@ twilio: # Twilio gateway configuration
|
||||
androidAppHash: example # Hash appended to Android
|
||||
verifyServiceFriendlyName: example # Service name used in template. Requires Twilio account rep to enable
|
||||
|
||||
push:
|
||||
queueSize: 1000 # Size of push pending queue
|
||||
|
||||
turn: # TURN server configuration
|
||||
secret: example # TURN server secret
|
||||
uris:
|
||||
- stun:example.com:80
|
||||
- stun:another.example.com:443
|
||||
- turn:example.com:443?transport=udp
|
||||
- turn:ya.example.com:80?transport=udp
|
||||
|
||||
cacheCluster: # Redis server configuration for cache cluster
|
||||
configurationUri: redis://redis.example.com:6379/
|
||||
|
||||
@@ -243,11 +232,6 @@ voiceVerification:
|
||||
- en
|
||||
|
||||
recaptcha:
|
||||
secret: unset
|
||||
|
||||
recaptchaV2:
|
||||
siteKey: unset
|
||||
scoreFloor: 1.0
|
||||
projectPath: projects/example
|
||||
credentialConfigurationJson: "{ }" # service account configuration for backend authentication
|
||||
|
||||
|
||||
+2
-13
@@ -41,13 +41,8 @@
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.signal</groupId>
|
||||
<artifactId>zkgroup-java</artifactId>
|
||||
<version>0.9.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.whispersystems</groupId>
|
||||
<artifactId>curve25519-java</artifactId>
|
||||
<version>0.5.0</version>
|
||||
<artifactId>libsignal-server</artifactId>
|
||||
<version>0.15.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
@@ -326,12 +321,6 @@
|
||||
<artifactId>pushy-dropwizard-metrics-listener</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty-tcnative-boringssl-static</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.vdurmont</groupId>
|
||||
<artifactId>semver4j</artifactId>
|
||||
|
||||
-46
@@ -6,7 +6,6 @@ package org.whispersystems.textsecuregcm;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.dropwizard.Configuration;
|
||||
import io.dropwizard.client.JerseyClientConfiguration;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
@@ -33,10 +32,8 @@ import org.whispersystems.textsecuregcm.configuration.GcpAttachmentsConfiguratio
|
||||
import org.whispersystems.textsecuregcm.configuration.MaxDeviceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.MessageCacheConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.PaymentsServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.PushConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.RateLimitsConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.RecaptchaConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.RecaptchaV2Configuration;
|
||||
import org.whispersystems.textsecuregcm.configuration.RedisClusterConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.RedisConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.RemoteConfigConfiguration;
|
||||
@@ -46,7 +43,6 @@ import org.whispersystems.textsecuregcm.configuration.SecureStorageServiceConfig
|
||||
import org.whispersystems.textsecuregcm.configuration.StripeConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.TestDeviceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.TurnConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.TwilioConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.UnidentifiedDeliveryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.VoiceVerificationConfiguration;
|
||||
@@ -76,11 +72,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private TwilioConfiguration twilio;
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private PushConfiguration push;
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
@@ -171,21 +162,11 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private RateLimitsConfiguration limits = new RateLimitsConfiguration();
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private JerseyClientConfiguration httpClient = new JerseyClientConfiguration();
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private WebSocketConfiguration webSocket = new WebSocketConfiguration();
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private TurnConfiguration turn;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
@@ -211,11 +192,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private RecaptchaConfiguration recaptcha;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private RecaptchaV2Configuration recaptchaV2;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
@@ -275,8 +251,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private AbusiveMessageFilterConfiguration abusiveMessageFilter;
|
||||
|
||||
private Map<String, String> transparentDataIndex = new HashMap<>();
|
||||
|
||||
public StripeConfiguration getStripe() {
|
||||
return stripe;
|
||||
}
|
||||
@@ -293,10 +267,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return recaptcha;
|
||||
}
|
||||
|
||||
public RecaptchaV2Configuration getRecaptchaV2Configuration() {
|
||||
return recaptchaV2;
|
||||
}
|
||||
|
||||
public VoiceVerificationConfiguration getVoiceVerificationConfiguration() {
|
||||
return voiceVerification;
|
||||
}
|
||||
@@ -309,14 +279,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return twilio;
|
||||
}
|
||||
|
||||
public PushConfiguration getPushConfiguration() {
|
||||
return push;
|
||||
}
|
||||
|
||||
public JerseyClientConfiguration getJerseyClientConfiguration() {
|
||||
return httpClient;
|
||||
}
|
||||
|
||||
public AwsAttachmentsConfiguration getAwsAttachmentsConfiguration() {
|
||||
return awsAttachments;
|
||||
}
|
||||
@@ -377,10 +339,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return limits;
|
||||
}
|
||||
|
||||
public TurnConfiguration getTurnConfiguration() {
|
||||
return turn;
|
||||
}
|
||||
|
||||
public GcmConfiguration getGcmConfiguration() {
|
||||
return gcm;
|
||||
}
|
||||
@@ -423,10 +381,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return results;
|
||||
}
|
||||
|
||||
public Map<String, String> getTransparentDataIndex() {
|
||||
return transparentDataIndex;
|
||||
}
|
||||
|
||||
public SecureBackupServiceConfiguration getSecureBackupServiceConfiguration() {
|
||||
return backupService;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* Copyright 2013-2022 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm;
|
||||
@@ -48,6 +48,7 @@ import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import javax.servlet.DispatcherType;
|
||||
import javax.servlet.FilterRegistration;
|
||||
@@ -56,11 +57,11 @@ import org.eclipse.jetty.servlets.CrossOriginFilter;
|
||||
import org.glassfish.jersey.server.ServerProperties;
|
||||
import org.jdbi.v3.core.Jdbi;
|
||||
import org.signal.i18n.HeaderControlledResourceBundleLookup;
|
||||
import org.signal.zkgroup.ServerSecretParams;
|
||||
import org.signal.zkgroup.auth.ServerZkAuthOperations;
|
||||
import org.signal.zkgroup.profiles.ServerZkProfileOperations;
|
||||
import org.signal.zkgroup.receipts.ReceiptCredentialPresentation;
|
||||
import org.signal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.auth.ServerZkAuthOperations;
|
||||
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
|
||||
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.dispatch.DispatchManager;
|
||||
@@ -79,7 +80,6 @@ import org.whispersystems.textsecuregcm.badges.ConfiguredProfileBadgeConverter;
|
||||
import org.whispersystems.textsecuregcm.badges.ResourceBundleLevelTranslator;
|
||||
import org.whispersystems.textsecuregcm.configuration.DirectoryServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.AcceptNumericOnlineFlagRequestFilter;
|
||||
import org.whispersystems.textsecuregcm.controllers.AccountController;
|
||||
import org.whispersystems.textsecuregcm.controllers.AttachmentControllerV1;
|
||||
import org.whispersystems.textsecuregcm.controllers.AttachmentControllerV2;
|
||||
@@ -150,9 +150,7 @@ import org.whispersystems.textsecuregcm.push.GCMSender;
|
||||
import org.whispersystems.textsecuregcm.push.MessageSender;
|
||||
import org.whispersystems.textsecuregcm.push.ProvisioningManager;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
import org.whispersystems.textsecuregcm.recaptcha.EnterpriseRecaptchaClient;
|
||||
import org.whispersystems.textsecuregcm.recaptcha.LegacyRecaptchaClient;
|
||||
import org.whispersystems.textsecuregcm.recaptcha.TransitionalRecaptchaClient;
|
||||
import org.whispersystems.textsecuregcm.recaptcha.RecaptchaClient;
|
||||
import org.whispersystems.textsecuregcm.redis.ConnectionEventLogger;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.ReplicatedJedisPool;
|
||||
@@ -198,6 +196,7 @@ import org.whispersystems.textsecuregcm.storage.RemoteConfigs;
|
||||
import org.whispersystems.textsecuregcm.storage.RemoteConfigsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
|
||||
import org.whispersystems.textsecuregcm.metrics.ReportedMessageMetricsListener;
|
||||
import org.whispersystems.textsecuregcm.storage.ReservedUsernames;
|
||||
import org.whispersystems.textsecuregcm.storage.StoredVerificationCodeManager;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
|
||||
@@ -209,7 +208,6 @@ import org.whispersystems.textsecuregcm.util.HostnameUtil;
|
||||
import org.whispersystems.textsecuregcm.util.logging.LoggingUnhandledExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.util.logging.UncaughtExceptionHandler;
|
||||
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.AssignUsernameCommand;
|
||||
@@ -342,7 +340,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getAppConfig().getConfigurationName(),
|
||||
DynamicConfiguration.class);
|
||||
|
||||
Accounts accounts = new Accounts(dynamoDbClient,
|
||||
Accounts accounts = new Accounts(dynamicConfigurationManager,
|
||||
dynamoDbClient,
|
||||
dynamoDbAsyncClient,
|
||||
config.getDynamoDbTables().getAccounts().getTableName(),
|
||||
config.getDynamoDbTables().getAccounts().getPhoneNumberTableName(),
|
||||
config.getDynamoDbTables().getAccounts().getPhoneNumberIdentifierTableName(),
|
||||
@@ -386,6 +386,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
BlockingQueue<Runnable> keyspaceNotificationDispatchQueue = new ArrayBlockingQueue<>(10_000);
|
||||
Metrics.gaugeCollectionSize(name(getClass(), "keyspaceNotificationDispatchQueueSize"), Collections.emptyList(), keyspaceNotificationDispatchQueue);
|
||||
final ArrayBlockingQueue<Runnable> receiptSenderQueue = new ArrayBlockingQueue<>(10_000);
|
||||
Metrics.gaugeCollectionSize(name(getClass(), "receiptSenderQueue"), Collections.emptyList(), receiptSenderQueue);
|
||||
|
||||
ScheduledExecutorService recurringJobExecutor = environment.lifecycle()
|
||||
.scheduledExecutorService(name(getClass(), "recurringJob-%d")).threads(6).build();
|
||||
@@ -402,6 +404,13 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
minThreads(availableProcessors). // mostly this is IO bound so tying to number of processors is tenuous at best
|
||||
allowCoreThreadTimeOut(true).
|
||||
build();
|
||||
ExecutorService receiptSenderExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "receiptSender-%d"))
|
||||
.maxThreads(2)
|
||||
.minThreads(2)
|
||||
.workQueue(receiptSenderQueue)
|
||||
.rejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy())
|
||||
.build();
|
||||
|
||||
StripeManager stripeManager = new StripeManager(config.getStripe().getApiKey(), stripeExecutor,
|
||||
config.getStripe().getIdempotencyKeyGenerator(), config.getStripe().getBoostDescription());
|
||||
@@ -436,7 +445,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster);
|
||||
MessagesCache messagesCache = new MessagesCache(messagesCluster, messagesCluster, keyspaceNotificationDispatchExecutor);
|
||||
PushLatencyManager pushLatencyManager = new PushLatencyManager(metricsCluster, dynamicConfigurationManager);
|
||||
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster, Metrics.globalRegistry, config.getReportMessageConfiguration().getCounterTtl());
|
||||
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster, config.getReportMessageConfiguration().getCounterTtl());
|
||||
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, pushLatencyManager, reportMessageManager);
|
||||
DeletedAccountsManager deletedAccountsManager = new DeletedAccountsManager(deletedAccounts,
|
||||
deletedAccountsLockDynamoDbClient, config.getDynamoDbTables().getDeletedAccountsLock().getTableName());
|
||||
@@ -444,8 +453,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
deletedAccountsManager, directoryQueue, keys, messagesManager, reservedUsernames, profilesManager,
|
||||
pendingAccountsManager, secureStorageClient, secureBackupClient, clientPresenceManager, clock);
|
||||
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs);
|
||||
DeadLetterHandler deadLetterHandler = new DeadLetterHandler(accountsManager, messagesManager);
|
||||
DispatchManager dispatchManager = new DispatchManager(pubSubClientFactory, Optional.of(deadLetterHandler));
|
||||
DispatchManager dispatchManager = new DispatchManager(pubSubClientFactory, Optional.empty());
|
||||
PubSubManager pubSubManager = new PubSubManager(pubsubClient, dispatchManager);
|
||||
APNSender apnSender = new APNSender(apnSenderExecutor, accountsManager, config.getApnConfiguration());
|
||||
GCMSender gcmSender = new GCMSender(gcmSenderExecutor, accountsManager, config.getGcmConfiguration().getApiKey());
|
||||
@@ -465,6 +473,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
SubscriptionManager subscriptionManager = new SubscriptionManager(
|
||||
config.getDynamoDbTables().getSubscriptions().getTableName(), dynamoDbAsyncClient);
|
||||
|
||||
ReportedMessageMetricsListener reportedMessageMetricsListener = new ReportedMessageMetricsListener(accountsManager);
|
||||
reportMessageManager.addListener(reportedMessageMetricsListener);
|
||||
|
||||
AccountAuthenticator accountAuthenticator = new AccountAuthenticator(accountsManager);
|
||||
DisabledPermittedAccountAuthenticator disabledPermittedAccountAuthenticator = new DisabledPermittedAccountAuthenticator(accountsManager);
|
||||
|
||||
@@ -472,18 +483,15 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
TwilioSmsSender twilioSmsSender = new TwilioSmsSender(config.getTwilioConfiguration(), dynamicConfigurationManager);
|
||||
SmsSender smsSender = new SmsSender(twilioSmsSender);
|
||||
MessageSender messageSender = new MessageSender(apnFallbackManager, clientPresenceManager, messagesManager, gcmSender, apnSender, pushLatencyManager);
|
||||
ReceiptSender receiptSender = new ReceiptSender(accountsManager, messageSender);
|
||||
TurnTokenGenerator turnTokenGenerator = new TurnTokenGenerator(config.getTurnConfiguration());
|
||||
LegacyRecaptchaClient legacyRecaptchaClient = new LegacyRecaptchaClient(config.getRecaptchaConfiguration().getSecret());
|
||||
EnterpriseRecaptchaClient enterpriseRecaptchaClient = new EnterpriseRecaptchaClient(
|
||||
config.getRecaptchaV2Configuration().getScoreFloor().doubleValue(),
|
||||
config.getRecaptchaV2Configuration().getSiteKey(),
|
||||
config.getRecaptchaV2Configuration().getProjectPath(),
|
||||
config.getRecaptchaV2Configuration().getCredentialConfigurationJson());
|
||||
TransitionalRecaptchaClient transitionalRecaptchaClient = new TransitionalRecaptchaClient(legacyRecaptchaClient, enterpriseRecaptchaClient);
|
||||
PushChallengeManager pushChallengeManager = new PushChallengeManager(apnSender, gcmSender, pushChallengeDynamoDb);
|
||||
ReceiptSender receiptSender = new ReceiptSender(accountsManager, messageSender, receiptSenderExecutor);
|
||||
TurnTokenGenerator turnTokenGenerator = new TurnTokenGenerator(dynamicConfigurationManager);
|
||||
RecaptchaClient recaptchaClient = new RecaptchaClient(
|
||||
config.getRecaptchaConfiguration().getProjectPath(),
|
||||
config.getRecaptchaConfiguration().getCredentialConfigurationJson(),
|
||||
dynamicConfigurationManager);
|
||||
PushChallengeManager pushChallengeManager = new PushChallengeManager(apnSender, gcmSender, pushChallengeDynamoDb);
|
||||
RateLimitChallengeManager rateLimitChallengeManager = new RateLimitChallengeManager(pushChallengeManager,
|
||||
transitionalRecaptchaClient, dynamicRateLimiters);
|
||||
recaptchaClient, dynamicRateLimiters);
|
||||
RateLimitChallengeOptionManager rateLimitChallengeOptionManager =
|
||||
new RateLimitChallengeOptionManager(dynamicRateLimiters, dynamicConfigurationManager);
|
||||
|
||||
@@ -582,12 +590,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.addFilter("RemoteDeprecationFilter", new RemoteDeprecationFilter(dynamicConfigurationManager))
|
||||
.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");
|
||||
|
||||
// TODO Remove on or after 2022-03-01
|
||||
final AcceptNumericOnlineFlagRequestFilter acceptNumericOnlineFlagRequestFilter =
|
||||
new AcceptNumericOnlineFlagRequestFilter("v1/messages/multi_recipient");
|
||||
|
||||
environment.jersey().register(new ContentLengthFilter(TrafficSource.HTTP));
|
||||
environment.jersey().register(acceptNumericOnlineFlagRequestFilter);
|
||||
environment.jersey().register(MultiDeviceMessageListProvider.class);
|
||||
environment.jersey().register(MultiRecipientMessageProvider.class);
|
||||
environment.jersey().register(new MetricsApplicationEventListener(TrafficSource.HTTP));
|
||||
@@ -610,7 +613,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
clientPresenceManager, retrySchedulingExecutor));
|
||||
webSocketEnvironment.jersey().register(new WebsocketRefreshApplicationEventListener(accountsManager, clientPresenceManager));
|
||||
webSocketEnvironment.jersey().register(new ContentLengthFilter(TrafficSource.WEBSOCKET));
|
||||
webSocketEnvironment.jersey().register(acceptNumericOnlineFlagRequestFilter);
|
||||
webSocketEnvironment.jersey().register(MultiDeviceMessageListProvider.class);
|
||||
webSocketEnvironment.jersey().register(MultiRecipientMessageProvider.class);
|
||||
webSocketEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET));
|
||||
@@ -620,7 +622,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
environment.jersey().register(
|
||||
new AccountController(pendingAccountsManager, accountsManager, abusiveHostRules, rateLimiters,
|
||||
smsSender, dynamicConfigurationManager, turnTokenGenerator, config.getTestDevices(),
|
||||
transitionalRecaptchaClient, gcmSender, apnSender, backupCredentialsGenerator,
|
||||
recaptchaClient, gcmSender, apnSender, backupCredentialsGenerator,
|
||||
verifyExperimentEnrollmentManager));
|
||||
environment.jersey().register(new KeysController(rateLimiters, keys, accountsManager));
|
||||
|
||||
|
||||
+1
-15
@@ -7,32 +7,18 @@ package org.whispersystems.textsecuregcm.auth;
|
||||
import io.dropwizard.auth.Authenticator;
|
||||
import io.dropwizard.auth.basic.BasicCredentials;
|
||||
import java.util.Optional;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
public class AccountAuthenticator extends BaseAccountAuthenticator implements
|
||||
Authenticator<BasicCredentials, AuthenticatedAccount> {
|
||||
|
||||
private static final String AUTHENTICATION_COUNTER_NAME = name(AccountAuthenticator.class, "authenticate");
|
||||
|
||||
public AccountAuthenticator(AccountsManager accountsManager) {
|
||||
super(accountsManager);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<AuthenticatedAccount> authenticate(BasicCredentials basicCredentials) {
|
||||
final Optional<AuthenticatedAccount> maybeAuthenticatedAccount = super.authenticate(basicCredentials, true);
|
||||
|
||||
// TODO Remove after announcement groups have launched
|
||||
maybeAuthenticatedAccount.ifPresent(authenticatedAccount ->
|
||||
Metrics.counter(AUTHENTICATION_COUNTER_NAME,
|
||||
"supportsAnnouncementGroups",
|
||||
String.valueOf(authenticatedAccount.getAccount().isAnnouncementGroupSupported()))
|
||||
.increment());
|
||||
|
||||
return maybeAuthenticatedAccount;
|
||||
return super.authenticate(basicCredentials, true);
|
||||
}
|
||||
|
||||
}
|
||||
+8
-3
@@ -7,8 +7,8 @@ package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import org.whispersystems.textsecuregcm.crypto.Curve;
|
||||
import org.whispersystems.textsecuregcm.crypto.ECPrivateKey;
|
||||
import org.signal.libsignal.protocol.ecc.Curve;
|
||||
import org.signal.libsignal.protocol.ecc.ECPrivateKey;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.SenderCertificate;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.ServerCertificate;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
@@ -46,7 +46,12 @@ public class CertificateGenerator {
|
||||
}
|
||||
|
||||
byte[] certificate = builder.build().toByteArray();
|
||||
byte[] signature = Curve.calculateSignature(privateKey, certificate);
|
||||
byte[] signature;
|
||||
try {
|
||||
signature = Curve.calculateSignature(privateKey, certificate);
|
||||
} catch (org.signal.libsignal.protocol.InvalidKeyException e) {
|
||||
throw new InvalidKeyException(e);
|
||||
}
|
||||
|
||||
return SenderCertificate.newBuilder()
|
||||
.setCertificate(ByteString.copyFrom(certificate))
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@@ -25,4 +26,9 @@ public class TurnToken {
|
||||
this.password = password;
|
||||
this.urls = urls;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
List<String> getUrls() {
|
||||
return urls;
|
||||
}
|
||||
}
|
||||
+31
-7
@@ -5,7 +5,12 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import org.whispersystems.textsecuregcm.configuration.TurnConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.TurnUriConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicTurnConfiguration;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.WeightedRandomSelect;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
@@ -14,20 +19,21 @@ import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class TurnTokenGenerator {
|
||||
|
||||
private final byte[] key;
|
||||
private final List<String> urls;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfiguration;
|
||||
|
||||
public TurnTokenGenerator(TurnConfiguration configuration) {
|
||||
this.key = configuration.getSecret().getBytes();
|
||||
this.urls = configuration.getUris();
|
||||
public TurnTokenGenerator(final DynamicConfigurationManager<DynamicConfiguration> config) {
|
||||
this.dynamicConfiguration = config;
|
||||
}
|
||||
|
||||
public TurnToken generate() {
|
||||
public TurnToken generate(final String e164) {
|
||||
try {
|
||||
byte[] key = dynamicConfiguration.getConfiguration().getTurnConfiguration().getSecret().getBytes();
|
||||
List<String> urls = urls(e164);
|
||||
Mac mac = Mac.getInstance("HmacSHA1");
|
||||
long validUntilSeconds = (System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1)) / 1000;
|
||||
long user = Math.abs(new SecureRandom().nextInt());
|
||||
@@ -41,4 +47,22 @@ public class TurnTokenGenerator {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
private List<String> urls(final String e164) {
|
||||
final DynamicTurnConfiguration turnConfig = dynamicConfiguration.getConfiguration().getTurnConfiguration();
|
||||
|
||||
// Check if number is enrolled to test out specific turn servers
|
||||
final Optional<TurnUriConfiguration> enrolled = turnConfig.getUriConfigs().stream()
|
||||
.filter(config -> config.getEnrolledNumbers().contains(e164))
|
||||
.findFirst();
|
||||
if (enrolled.isPresent()) {
|
||||
return enrolled.get().getUris();
|
||||
}
|
||||
|
||||
// Otherwise, select from turn server sets by weighted choice
|
||||
return WeightedRandomSelect.select(turnConfig
|
||||
.getUriConfigs()
|
||||
.stream()
|
||||
.map(c -> new Pair<List<String>, Long>(c.getUris(), c.getWeight())).toList());
|
||||
}
|
||||
}
|
||||
-20
@@ -1,20 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import javax.validation.constraints.Min;
|
||||
|
||||
public class PushConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@Min(0)
|
||||
private int queueSize = 200;
|
||||
|
||||
public int getQueueSize() {
|
||||
return queueSize;
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -37,7 +37,7 @@ public class RateLimitsConfiguration {
|
||||
private RateLimitConfiguration attachments = new RateLimitConfiguration(50, 50);
|
||||
|
||||
@JsonProperty
|
||||
private RateLimitConfiguration prekeys = new RateLimitConfiguration(3, 1.0 / 10.0);
|
||||
private RateLimitConfiguration prekeys = new RateLimitConfiguration(6, 1.0 / 10.0);
|
||||
|
||||
@JsonProperty
|
||||
private RateLimitConfiguration messages = new RateLimitConfiguration(60, 60);
|
||||
@@ -46,7 +46,7 @@ public class RateLimitsConfiguration {
|
||||
private RateLimitConfiguration allocateDevice = new RateLimitConfiguration(2, 1.0 / 2.0);
|
||||
|
||||
@JsonProperty
|
||||
private RateLimitConfiguration verifyDevice = new RateLimitConfiguration(2, 2);
|
||||
private RateLimitConfiguration verifyDevice = new RateLimitConfiguration(6, 1.0 / 10.0);
|
||||
|
||||
@JsonProperty
|
||||
private RateLimitConfiguration turnAllocations = new RateLimitConfiguration(60, 60);
|
||||
|
||||
+10
-7
@@ -1,21 +1,24 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* Copyright 2021-2022 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
|
||||
public class RecaptchaConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@NotEmpty
|
||||
private String secret;
|
||||
private String projectPath;
|
||||
private String credentialConfigurationJson;
|
||||
|
||||
public String getSecret() {
|
||||
return secret;
|
||||
@NotEmpty
|
||||
public String getProjectPath() {
|
||||
return projectPath;
|
||||
}
|
||||
|
||||
@NotEmpty
|
||||
public String getCredentialConfigurationJson() {
|
||||
return credentialConfigurationJson;
|
||||
}
|
||||
}
|
||||
-42
@@ -1,42 +0,0 @@
|
||||
/*
|
||||
* Copyright 2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import javax.validation.constraints.DecimalMax;
|
||||
import javax.validation.constraints.DecimalMin;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
public class RecaptchaV2Configuration {
|
||||
|
||||
private BigDecimal scoreFloor;
|
||||
private String projectPath;
|
||||
private String siteKey;
|
||||
private String credentialConfigurationJson;
|
||||
|
||||
@DecimalMin("0")
|
||||
@DecimalMax("1")
|
||||
@NotNull
|
||||
public BigDecimal getScoreFloor() {
|
||||
return scoreFloor;
|
||||
}
|
||||
|
||||
@NotEmpty
|
||||
public String getProjectPath() {
|
||||
return projectPath;
|
||||
}
|
||||
|
||||
@NotEmpty
|
||||
public String getSiteKey() {
|
||||
return siteKey;
|
||||
}
|
||||
|
||||
@NotEmpty
|
||||
public String getCredentialConfigurationJson() {
|
||||
return credentialConfigurationJson;
|
||||
}
|
||||
}
|
||||
-30
@@ -1,30 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import java.util.List;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
public class TurnConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@NotEmpty
|
||||
private String secret;
|
||||
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
private List<String> uris;
|
||||
|
||||
public List<String> getUris() {
|
||||
return uris;
|
||||
}
|
||||
|
||||
public String getSecret() {
|
||||
return secret;
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import javax.validation.constraints.Min;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
public class TurnUriConfiguration {
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
private List<String> uris;
|
||||
|
||||
/**
|
||||
* The weight of this entry for weighted random selection
|
||||
*/
|
||||
@JsonProperty
|
||||
@Min(0)
|
||||
private long weight = 1;
|
||||
|
||||
/**
|
||||
* Enrolled numbers will always get this uri list
|
||||
*/
|
||||
private Set<String> enrolledNumbers = Collections.emptySet();
|
||||
|
||||
public List<String> getUris() {
|
||||
return uris;
|
||||
}
|
||||
|
||||
public long getWeight() {
|
||||
return weight;
|
||||
}
|
||||
|
||||
public Set<String> getEnrolledNumbers() {
|
||||
return Collections.unmodifiableSet(enrolledNumbers);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -8,8 +8,8 @@ package org.whispersystems.textsecuregcm.configuration;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import org.whispersystems.textsecuregcm.crypto.Curve;
|
||||
import org.whispersystems.textsecuregcm.crypto.ECPrivateKey;
|
||||
import org.signal.libsignal.protocol.ecc.Curve;
|
||||
import org.signal.libsignal.protocol.ecc.ECPrivateKey;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Collections;
|
||||
import java.util.Set;
|
||||
import javax.validation.constraints.DecimalMax;
|
||||
import javax.validation.constraints.DecimalMin;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
public class DynamicCaptchaConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@DecimalMin("0")
|
||||
@DecimalMax("1")
|
||||
@NotNull
|
||||
private BigDecimal scoreFloor;
|
||||
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
private Set<String> signupCountryCodes = Collections.emptySet();
|
||||
|
||||
public Set<String> getSignupCountryCodes() {
|
||||
return signupCountryCodes;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public void setSignupCountryCodes(Set<String> numbers) {
|
||||
this.signupCountryCodes = numbers;
|
||||
}
|
||||
|
||||
public BigDecimal getScoreFloor() {
|
||||
return scoreFloor;
|
||||
}
|
||||
}
|
||||
+18
-3
@@ -38,7 +38,8 @@ public class DynamicConfiguration {
|
||||
private DynamicTwilioConfiguration twilio = new DynamicTwilioConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
private DynamicSignupCaptchaConfiguration signupCaptcha = new DynamicSignupCaptchaConfiguration();
|
||||
@Valid
|
||||
private DynamicCaptchaConfiguration captcha = new DynamicCaptchaConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
@@ -51,6 +52,14 @@ public class DynamicConfiguration {
|
||||
@Valid
|
||||
private DynamicPushLatencyConfiguration pushLatency = new DynamicPushLatencyConfiguration(Collections.emptyMap());
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
private DynamicUakMigrationConfiguration uakMigrationConfiguration = new DynamicUakMigrationConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
private DynamicTurnConfiguration turn = new DynamicTurnConfiguration();
|
||||
|
||||
public Optional<DynamicExperimentEnrollmentConfiguration> getExperimentEnrollmentConfiguration(
|
||||
final String experimentName) {
|
||||
return Optional.ofNullable(experiments.get(experimentName));
|
||||
@@ -86,8 +95,8 @@ public class DynamicConfiguration {
|
||||
this.twilio = twilioConfiguration;
|
||||
}
|
||||
|
||||
public DynamicSignupCaptchaConfiguration getSignupCaptchaConfiguration() {
|
||||
return signupCaptcha;
|
||||
public DynamicCaptchaConfiguration getCaptchaConfiguration() {
|
||||
return captcha;
|
||||
}
|
||||
|
||||
public DynamicRateLimitChallengeConfiguration getRateLimitChallengeConfiguration() {
|
||||
@@ -102,4 +111,10 @@ public class DynamicConfiguration {
|
||||
return pushLatency;
|
||||
}
|
||||
|
||||
public DynamicUakMigrationConfiguration getUakMigrationConfiguration() { return uakMigrationConfiguration; }
|
||||
|
||||
public DynamicTurnConfiguration getTurnConfiguration() {
|
||||
return turn;
|
||||
}
|
||||
|
||||
}
|
||||
-23
@@ -1,23 +0,0 @@
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.util.Collections;
|
||||
import java.util.Set;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
public class DynamicSignupCaptchaConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
private Set<String> countryCodes = Collections.emptySet();
|
||||
|
||||
public Set<String> getCountryCodes() {
|
||||
return countryCodes;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public void setCountryCodes(Set<String> numbers) {
|
||||
this.countryCodes = numbers;
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import org.whispersystems.textsecuregcm.configuration.TurnUriConfiguration;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
public class DynamicTurnConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
private String secret;
|
||||
|
||||
@JsonProperty
|
||||
private List<@Valid TurnUriConfiguration> uriConfigs = Collections.emptyList();
|
||||
|
||||
public List<TurnUriConfiguration> getUriConfigs() {
|
||||
return uriConfigs;
|
||||
}
|
||||
|
||||
public String getSecret() {
|
||||
return secret;
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
public class DynamicUakMigrationConfiguration {
|
||||
@JsonProperty
|
||||
private boolean enabled = true;
|
||||
|
||||
@JsonProperty
|
||||
private int maxOutstandingNormalizes = 25;
|
||||
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public int getMaxOutstandingNormalizes() {
|
||||
return maxOutstandingNormalizes;
|
||||
}
|
||||
}
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import java.io.IOException;
|
||||
import javax.ws.rs.container.ContainerRequestContext;
|
||||
import javax.ws.rs.container.ContainerRequestFilter;
|
||||
import javax.ws.rs.container.PreMatching;
|
||||
|
||||
@PreMatching
|
||||
public class AcceptNumericOnlineFlagRequestFilter implements ContainerRequestFilter {
|
||||
|
||||
private final String pathPrefix;
|
||||
|
||||
public AcceptNumericOnlineFlagRequestFilter(final String pathPrefix) {
|
||||
this.pathPrefix = pathPrefix;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void filter(final ContainerRequestContext requestContext) throws IOException {
|
||||
if (requestContext.getUriInfo().getPath().startsWith(pathPrefix)) {
|
||||
if ("1".equals(requestContext.getUriInfo().getQueryParameters().getFirst("online"))) {
|
||||
requestContext.setRequestUri(requestContext.getUriInfo().getRequestUriBuilder()
|
||||
.replaceQueryParam("online", "true")
|
||||
.build());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+17
-7
@@ -46,6 +46,7 @@ import javax.ws.rs.core.Context;
|
||||
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;
|
||||
@@ -60,8 +61,8 @@ import org.whispersystems.textsecuregcm.auth.StoredRegistrationLock;
|
||||
import org.whispersystems.textsecuregcm.auth.StoredVerificationCode;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnToken;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicCaptchaConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicSignupCaptchaConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ApnRegistrationId;
|
||||
@@ -112,13 +113,14 @@ public class AccountController {
|
||||
private static final String ACCOUNT_CREATE_COUNTER_NAME = name(AccountController.class, "create");
|
||||
private static final String ACCOUNT_VERIFY_COUNTER_NAME = name(AccountController.class, "verify");
|
||||
private static final String CAPTCHA_ATTEMPT_COUNTER_NAME = name(AccountController.class, "captcha");
|
||||
private static final String CHALLENGE_ISSUED_COUNTER_NAME = name(AccountController.class, "challengeIssued");
|
||||
|
||||
private static final String TWILIO_VERIFY_ERROR_COUNTER_NAME = name(AccountController.class, "twilioVerifyError");
|
||||
|
||||
private static final String CHALLENGE_PRESENT_TAG_NAME = "present";
|
||||
private static final String CHALLENGE_MATCH_TAG_NAME = "matches";
|
||||
private static final String COUNTRY_CODE_TAG_NAME = "countryCode";
|
||||
private static final String VERFICATION_TRANSPORT_TAG_NAME = "transport";
|
||||
private static final String VERIFICATION_TRANSPORT_TAG_NAME = "transport";
|
||||
|
||||
private static final String VERIFY_EXPERIMENT_TAG_NAME = "twilioVerify";
|
||||
|
||||
@@ -226,6 +228,12 @@ public class AccountController {
|
||||
if (requirement.isCaptchaRequired()) {
|
||||
captchaRequiredMeter.mark();
|
||||
|
||||
final Tags tags = Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(COUNTRY_CODE_TAG_NAME, Util.getCountryCode(number)));
|
||||
|
||||
Metrics.counter(CHALLENGE_ISSUED_COUNTER_NAME, tags).increment();
|
||||
|
||||
if (requirement.isAutoBlock() && shouldAutoBlock(sourceHost)) {
|
||||
logger.info("Auto-block: {}", sourceHost);
|
||||
abusiveHostRules.setBlockedHost(sourceHost, "Auto-Block");
|
||||
@@ -312,7 +320,7 @@ public class AccountController {
|
||||
{
|
||||
final List<Tag> tags = new ArrayList<>();
|
||||
tags.add(Tag.of(COUNTRY_CODE_TAG_NAME, Util.getCountryCode(number)));
|
||||
tags.add(Tag.of(VERFICATION_TRANSPORT_TAG_NAME, transport));
|
||||
tags.add(Tag.of(VERIFICATION_TRANSPORT_TAG_NAME, transport));
|
||||
tags.add(UserAgentTagUtil.getPlatformTag(userAgent));
|
||||
tags.add(Tag.of(VERIFY_EXPERIMENT_TAG_NAME, String.valueOf(enrolledInVerifyExperiment)));
|
||||
|
||||
@@ -441,7 +449,7 @@ public class AccountController {
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public TurnToken getTurnToken(@Auth AuthenticatedAccount auth) throws RateLimitExceededException {
|
||||
rateLimiters.getTurnLimiter().validate(auth.getAccount().getUuid());
|
||||
return turnTokenGenerator.generate();
|
||||
return turnTokenGenerator.generate(auth.getAccount().getNumber());
|
||||
}
|
||||
|
||||
@Timed
|
||||
@@ -682,6 +690,7 @@ public class AccountController {
|
||||
Optional<String> pushChallenge,
|
||||
String userAgent)
|
||||
{
|
||||
final String countryCode = Util.getCountryCode(number);
|
||||
|
||||
if (captchaToken.isPresent()) {
|
||||
boolean validToken = recaptchaClient.verify(captchaToken.get(), sourceHost);
|
||||
@@ -690,6 +699,7 @@ public class AccountController {
|
||||
final List<Tag> tags = new ArrayList<>();
|
||||
tags.add(Tag.of("success", String.valueOf(validToken)));
|
||||
tags.add(UserAgentTagUtil.getPlatformTag(userAgent));
|
||||
tags.add(Tag.of(COUNTRY_CODE_TAG_NAME, countryCode));
|
||||
Metrics.counter(CAPTCHA_ATTEMPT_COUNTER_NAME, tags).increment();
|
||||
}
|
||||
|
||||
@@ -700,7 +710,6 @@ public class AccountController {
|
||||
}
|
||||
}
|
||||
|
||||
final String countryCode = Util.getCountryCode(number);
|
||||
{
|
||||
final List<Tag> tags = new ArrayList<>();
|
||||
tags.add(Tag.of(COUNTRY_CODE_TAG_NAME, countryCode));
|
||||
@@ -761,8 +770,9 @@ public class AccountController {
|
||||
return new CaptchaRequirement(true, true);
|
||||
}
|
||||
|
||||
DynamicSignupCaptchaConfiguration signupCaptchaConfig = dynamicConfigurationManager.getConfiguration().getSignupCaptchaConfiguration();
|
||||
if (signupCaptchaConfig.getCountryCodes().contains(countryCode)) {
|
||||
DynamicCaptchaConfiguration captchaConfig = dynamicConfigurationManager.getConfiguration()
|
||||
.getCaptchaConfiguration();
|
||||
if (captchaConfig.getSignupCountryCodes().contains(countryCode)) {
|
||||
return new CaptchaRequirement(true, false);
|
||||
}
|
||||
|
||||
|
||||
+4
-9
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
import com.amazonaws.HttpMethod;
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.util.stream.Stream;
|
||||
import javax.ws.rs.GET;
|
||||
@@ -43,18 +42,15 @@ public class AttachmentControllerV1 extends AttachmentControllerBase {
|
||||
@Timed
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public AttachmentDescriptorV1 allocateAttachment(@Auth AuthenticatedAccount auth)
|
||||
throws RateLimitExceededException {
|
||||
if (auth.getAccount().isRateLimited()) {
|
||||
rateLimiters.getAttachmentLimiter().validate(auth.getAccount().getUuid());
|
||||
}
|
||||
public AttachmentDescriptorV1 allocateAttachment(@Auth AuthenticatedAccount auth) throws RateLimitExceededException {
|
||||
|
||||
rateLimiters.getAttachmentLimiter().validate(auth.getAccount().getUuid());
|
||||
|
||||
long attachmentId = generateAttachmentId();
|
||||
URL url = urlSigner.getPreSignedUrl(attachmentId, HttpMethod.PUT,
|
||||
Stream.of(UNACCELERATED_REGIONS).anyMatch(region -> auth.getAccount().getNumber().startsWith(region)));
|
||||
|
||||
return new AttachmentDescriptorV1(attachmentId, url.toExternalForm());
|
||||
|
||||
}
|
||||
|
||||
@Timed
|
||||
@@ -62,8 +58,7 @@ public class AttachmentControllerV1 extends AttachmentControllerBase {
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/{attachmentId}")
|
||||
public AttachmentUri redirectToAttachment(@Auth AuthenticatedAccount auth,
|
||||
@PathParam("attachmentId") long attachmentId)
|
||||
throws IOException {
|
||||
@PathParam("attachmentId") long attachmentId) {
|
||||
return new AttachmentUri(urlSigner.getPreSignedUrl(attachmentId, HttpMethod.GET,
|
||||
Stream.of(UNACCELERATED_REGIONS).anyMatch(region -> auth.getAccount().getNumber().startsWith(region))));
|
||||
}
|
||||
|
||||
+1
-1
@@ -23,7 +23,7 @@ import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import org.signal.zkgroup.auth.ServerZkAuthOperations;
|
||||
import org.signal.libsignal.zkgroup.auth.ServerZkAuthOperations;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
|
||||
import org.whispersystems.textsecuregcm.entities.DeliveryCertificate;
|
||||
|
||||
+1
-1
@@ -68,7 +68,7 @@ public class ChallengeController {
|
||||
final String mostRecentProxy = ForwardedIpUtil.getMostRecentProxy(forwardedFor).orElseThrow();
|
||||
|
||||
rateLimitChallengeManager.answerRecaptchaChallenge(auth.getAccount(), recaptchaChallengeRequest.getCaptcha(),
|
||||
mostRecentProxy);
|
||||
mostRecentProxy, userAgent);
|
||||
|
||||
} catch (final NoSuchElementException e) {
|
||||
return Response.status(400).build();
|
||||
|
||||
+2
@@ -239,6 +239,8 @@ public class DeviceController {
|
||||
private boolean isCapabilityDowngrade(Account account, DeviceCapabilities capabilities, String userAgent) {
|
||||
boolean isDowngrade = false;
|
||||
|
||||
// TODO stories capability
|
||||
// isDowngrade |= account.isStoriesSupported() && !capabilities.isStories();
|
||||
isDowngrade |= account.isPniSupported() && !capabilities.isPni();
|
||||
isDowngrade |= account.isChangeNumberSupported() && !capabilities.isChangeNumber();
|
||||
isDowngrade |= account.isAnnouncementGroupSupported() && !capabilities.isAnnouncementGroup();
|
||||
|
||||
+5
-5
@@ -43,11 +43,11 @@ import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.core.Response.Status;
|
||||
import org.signal.zkgroup.InvalidInputException;
|
||||
import org.signal.zkgroup.VerificationFailedException;
|
||||
import org.signal.zkgroup.receipts.ReceiptCredentialPresentation;
|
||||
import org.signal.zkgroup.receipts.ReceiptSerial;
|
||||
import org.signal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
|
||||
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
|
||||
+12
-8
@@ -20,6 +20,7 @@ import java.util.UUID;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.ForbiddenException;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.HeaderParam;
|
||||
import javax.ws.rs.PUT;
|
||||
@@ -92,16 +93,19 @@ public class KeysController {
|
||||
Device device = disabledPermittedAuth.getAuthenticatedDevice();
|
||||
boolean updateAccount = false;
|
||||
|
||||
if (!preKeys.getSignedPreKey().equals(device.getSignedPreKey())) {
|
||||
updateAccount = true;
|
||||
}
|
||||
|
||||
if (!preKeys.getIdentityKey().equals(account.getIdentityKey())) {
|
||||
updateAccount = true;
|
||||
}
|
||||
|
||||
final boolean usePhoneNumberIdentity = usePhoneNumberIdentity(identityType);
|
||||
|
||||
if (!preKeys.getSignedPreKey().equals(usePhoneNumberIdentity ? device.getPhoneNumberIdentitySignedPreKey() : device.getSignedPreKey())) {
|
||||
updateAccount = true;
|
||||
}
|
||||
|
||||
if (!preKeys.getIdentityKey().equals(usePhoneNumberIdentity ? account.getPhoneNumberIdentityKey() : account.getIdentityKey())) {
|
||||
updateAccount = true;
|
||||
if (!device.isMaster()) {
|
||||
throw new ForbiddenException();
|
||||
}
|
||||
}
|
||||
|
||||
if (updateAccount) {
|
||||
account = accounts.update(account, a -> {
|
||||
a.getDevice(device.getId()).ifPresent(d -> {
|
||||
|
||||
-23
@@ -198,10 +198,6 @@ public class MessageController {
|
||||
contentLength += message.getContent().length();
|
||||
}
|
||||
|
||||
if (!Util.isEmpty(message.getBody())) {
|
||||
contentLength += message.getBody().length();
|
||||
}
|
||||
|
||||
validateContentLength(contentLength, userAgent);
|
||||
validateEnvelopeType(message.getType(), userAgent);
|
||||
}
|
||||
@@ -529,9 +525,7 @@ public class MessageController {
|
||||
|
||||
for (final OutgoingMessageEntity message : messageList.getMessages()) {
|
||||
size += message.getContent() == null ? 0 : message.getContent().length;
|
||||
size += message.getMessage() == null ? 0 : message.getMessage().length;
|
||||
size += Util.isEmpty(message.getSource()) ? 0 : message.getSource().length();
|
||||
size += Util.isEmpty(message.getRelay()) ? 0 : message.getRelay().length();
|
||||
}
|
||||
|
||||
return size;
|
||||
@@ -582,7 +576,6 @@ public class MessageController {
|
||||
String userAgentString)
|
||||
throws NoSuchUserException {
|
||||
try {
|
||||
Optional<byte[]> messageBody = getMessageBody(incomingMessage);
|
||||
Optional<byte[]> messageContent = getMessageContent(incomingMessage);
|
||||
Envelope.Builder messageBuilder = Envelope.newBuilder();
|
||||
|
||||
@@ -619,11 +612,6 @@ public class MessageController {
|
||||
.setSourceUuid(authenticatedAccount.getAccount().getUuid().toString())
|
||||
.setSourceDevice((int) authenticatedAccount.getAuthenticatedDevice().getId()));
|
||||
|
||||
messageBody.ifPresent(bytes -> {
|
||||
Metrics.counter(LEGACY_MESSAGE_SENT_COUNTER).increment();
|
||||
messageBuilder.setLegacyMessage(ByteString.copyFrom(messageBody.get()));
|
||||
});
|
||||
|
||||
messageContent.ifPresent(bytes -> messageBuilder.setContent(ByteString.copyFrom(bytes)));
|
||||
|
||||
messageSender.sendMessage(destinationAccount, destinationDevice, messageBuilder.build(), online);
|
||||
@@ -798,17 +786,6 @@ public class MessageController {
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<byte[]> getMessageBody(IncomingMessage message) {
|
||||
if (Util.isEmpty(message.getBody())) return Optional.empty();
|
||||
|
||||
try {
|
||||
return Optional.of(Base64.getDecoder().decode(message.getBody()));
|
||||
} catch (IllegalArgumentException e) {
|
||||
logger.debug("Bad B64", e);
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<byte[]> getMessageContent(IncomingMessage message) {
|
||||
if (Util.isEmpty(message.getContent())) return Optional.empty();
|
||||
|
||||
|
||||
+7
-7
@@ -52,13 +52,13 @@ import org.apache.commons.codec.DecoderException;
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.apache.commons.codec.binary.Hex;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.signal.zkgroup.InvalidInputException;
|
||||
import org.signal.zkgroup.VerificationFailedException;
|
||||
import org.signal.zkgroup.profiles.PniCredentialResponse;
|
||||
import org.signal.zkgroup.profiles.ProfileKeyCommitment;
|
||||
import org.signal.zkgroup.profiles.ProfileKeyCredentialRequest;
|
||||
import org.signal.zkgroup.profiles.ProfileKeyCredentialResponse;
|
||||
import org.signal.zkgroup.profiles.ServerZkProfileOperations;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.profiles.PniCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCommitment;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.Anonymous;
|
||||
|
||||
+1
-2
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* Copyright 2013-2022 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
@@ -55,7 +55,6 @@ public class RemoteConfigController {
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public UserRemoteConfigList getAll(@Auth AuthenticatedAccount auth) {
|
||||
try {
|
||||
|
||||
+12
-18
@@ -1,10 +1,12 @@
|
||||
/*
|
||||
* Copyright 2021 Signal Messenger, LLC
|
||||
* Copyright 2021-2022 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
@@ -13,6 +15,8 @@ import com.stripe.model.Invoice;
|
||||
import com.stripe.model.InvoiceLineItem;
|
||||
import com.stripe.model.Subscription;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.math.BigDecimal;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
@@ -56,15 +60,12 @@ import javax.ws.rs.core.HttpHeaders;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.core.Response.Status;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.signal.zkgroup.InvalidInputException;
|
||||
import org.signal.zkgroup.VerificationFailedException;
|
||||
import org.signal.zkgroup.receipts.ReceiptCredentialRequest;
|
||||
import org.signal.zkgroup.receipts.ReceiptCredentialResponse;
|
||||
import org.signal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
@@ -82,8 +83,6 @@ import org.whispersystems.textsecuregcm.storage.SubscriptionManager.GetResult;
|
||||
import org.whispersystems.textsecuregcm.stripe.StripeManager;
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
@Path("/v1/subscription")
|
||||
public class SubscriptionController {
|
||||
|
||||
@@ -125,7 +124,6 @@ public class SubscriptionController {
|
||||
@Timed
|
||||
@DELETE
|
||||
@Path("/{subscriberId}")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CompletableFuture<Response> deleteSubscriber(
|
||||
@Auth Optional<AuthenticatedAccount> authenticatedAccount,
|
||||
@@ -404,7 +402,6 @@ public class SubscriptionController {
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/levels")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CompletableFuture<Response> getLevels(@Context ContainerRequestContext containerRequestContext) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
@@ -452,7 +449,6 @@ public class SubscriptionController {
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/boost/badges")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CompletableFuture<Response> getBoostBadges(@Context ContainerRequestContext containerRequestContext) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
@@ -468,7 +464,6 @@ public class SubscriptionController {
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/boost/amounts")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CompletableFuture<Response> getBoostAmounts() {
|
||||
return CompletableFuture.supplyAsync(() -> Response.ok(
|
||||
@@ -688,7 +683,6 @@ public class SubscriptionController {
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/{subscriberId}")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CompletableFuture<Response> getSubscriptionInformation(
|
||||
@Auth Optional<AuthenticatedAccount> authenticatedAccount,
|
||||
@@ -726,7 +720,7 @@ public class SubscriptionController {
|
||||
this.receiptCredentialRequest = receiptCredentialRequest;
|
||||
}
|
||||
|
||||
@ExactlySize(ReceiptCredentialRequest.SIZE)
|
||||
@NotEmpty
|
||||
public byte[] getReceiptCredentialRequest() {
|
||||
return receiptCredentialRequest;
|
||||
}
|
||||
@@ -742,7 +736,7 @@ public class SubscriptionController {
|
||||
this.receiptCredentialResponse = receiptCredentialResponse;
|
||||
}
|
||||
|
||||
@ExactlySize(ReceiptCredentialResponse.SIZE)
|
||||
@NotEmpty
|
||||
public byte[] getReceiptCredentialResponse() {
|
||||
return receiptCredentialResponse;
|
||||
}
|
||||
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
|
||||
public class ValidationException extends Exception {
|
||||
public ValidationException(String s) {
|
||||
super(s);
|
||||
}
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.crypto;
|
||||
|
||||
import org.whispersystems.curve25519.Curve25519;
|
||||
import org.whispersystems.curve25519.Curve25519KeyPair;
|
||||
|
||||
import java.security.InvalidKeyException;
|
||||
|
||||
import static org.whispersystems.curve25519.Curve25519.BEST;
|
||||
|
||||
public class Curve {
|
||||
|
||||
public static final int DJB_TYPE = 0x05;
|
||||
|
||||
public static ECKeyPair generateKeyPair() {
|
||||
Curve25519KeyPair keyPair = Curve25519.getInstance(BEST).generateKeyPair();
|
||||
|
||||
return new ECKeyPair(new DjbECPublicKey(keyPair.getPublicKey()),
|
||||
new DjbECPrivateKey(keyPair.getPrivateKey()));
|
||||
}
|
||||
|
||||
public static ECPublicKey decodePoint(byte[] bytes, int offset)
|
||||
throws InvalidKeyException
|
||||
{
|
||||
if (bytes == null || bytes.length - offset < 1) {
|
||||
throw new InvalidKeyException("No key type identifier");
|
||||
}
|
||||
|
||||
int type = bytes[offset] & 0xFF;
|
||||
|
||||
switch (type) {
|
||||
case Curve.DJB_TYPE:
|
||||
if (bytes.length - offset < 33) {
|
||||
throw new InvalidKeyException("Bad key length: " + bytes.length);
|
||||
}
|
||||
|
||||
byte[] keyBytes = new byte[32];
|
||||
System.arraycopy(bytes, offset+1, keyBytes, 0, keyBytes.length);
|
||||
return new DjbECPublicKey(keyBytes);
|
||||
default:
|
||||
throw new InvalidKeyException("Bad key type: " + type);
|
||||
}
|
||||
}
|
||||
|
||||
public static ECPrivateKey decodePrivatePoint(byte[] bytes) {
|
||||
return new DjbECPrivateKey(bytes);
|
||||
}
|
||||
|
||||
public static byte[] calculateAgreement(ECPublicKey publicKey, ECPrivateKey privateKey)
|
||||
throws InvalidKeyException
|
||||
{
|
||||
if (publicKey == null) {
|
||||
throw new InvalidKeyException("public value is null");
|
||||
}
|
||||
|
||||
if (privateKey == null) {
|
||||
throw new InvalidKeyException("private value is null");
|
||||
}
|
||||
|
||||
if (publicKey.getType() != privateKey.getType()) {
|
||||
throw new InvalidKeyException("Public and private keys must be of the same type!");
|
||||
}
|
||||
|
||||
if (publicKey.getType() == DJB_TYPE) {
|
||||
return Curve25519.getInstance(BEST)
|
||||
.calculateAgreement(((DjbECPublicKey) publicKey).getPublicKey(),
|
||||
((DjbECPrivateKey) privateKey).getPrivateKey());
|
||||
} else {
|
||||
throw new InvalidKeyException("Unknown type: " + publicKey.getType());
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] calculateSignature(ECPrivateKey signingKey, byte[] message)
|
||||
throws InvalidKeyException
|
||||
{
|
||||
if (signingKey == null || message == null) {
|
||||
throw new InvalidKeyException("Values must not be null");
|
||||
}
|
||||
|
||||
if (signingKey.getType() == DJB_TYPE) {
|
||||
return Curve25519.getInstance(BEST)
|
||||
.calculateSignature(((DjbECPrivateKey) signingKey).getPrivateKey(), message);
|
||||
} else {
|
||||
throw new InvalidKeyException("Unknown type: " + signingKey.getType());
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean verifySignature(ECPublicKey signingKey, byte[] message, byte[] signature)
|
||||
throws InvalidKeyException
|
||||
{
|
||||
if (signingKey.getType() == DJB_TYPE) {
|
||||
return Curve25519.getInstance(BEST)
|
||||
.verifySignature(((DjbECPublicKey) signingKey).getPublicKey(), message, signature);
|
||||
} else {
|
||||
throw new InvalidKeyException("Unknown type: " + signingKey.getType());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.crypto;
|
||||
|
||||
public class DjbECPrivateKey implements ECPrivateKey {
|
||||
|
||||
private final byte[] privateKey;
|
||||
|
||||
DjbECPrivateKey(byte[] privateKey) {
|
||||
this.privateKey = privateKey;
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] serialize() {
|
||||
return privateKey;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getType() {
|
||||
return Curve.DJB_TYPE;
|
||||
}
|
||||
|
||||
public byte[] getPrivateKey() {
|
||||
return privateKey;
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.crypto;
|
||||
|
||||
import org.whispersystems.textsecuregcm.util.ByteUtil;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.Arrays;
|
||||
|
||||
public class DjbECPublicKey implements ECPublicKey {
|
||||
|
||||
private final byte[] publicKey;
|
||||
|
||||
DjbECPublicKey(byte[] publicKey) {
|
||||
this.publicKey = publicKey;
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] serialize() {
|
||||
byte[] type = {Curve.DJB_TYPE};
|
||||
return ByteUtil.combine(type, publicKey);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getType() {
|
||||
return Curve.DJB_TYPE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
if (other == null) return false;
|
||||
if (!(other instanceof DjbECPublicKey)) return false;
|
||||
|
||||
DjbECPublicKey that = (DjbECPublicKey)other;
|
||||
return Arrays.equals(this.publicKey, that.publicKey);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Arrays.hashCode(publicKey);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(ECPublicKey another) {
|
||||
return new BigInteger(publicKey).compareTo(new BigInteger(((DjbECPublicKey)another).publicKey));
|
||||
}
|
||||
|
||||
public byte[] getPublicKey() {
|
||||
return publicKey;
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.crypto;
|
||||
|
||||
public class ECKeyPair {
|
||||
|
||||
private final ECPublicKey publicKey;
|
||||
private final ECPrivateKey privateKey;
|
||||
|
||||
ECKeyPair(ECPublicKey publicKey, ECPrivateKey privateKey) {
|
||||
this.publicKey = publicKey;
|
||||
this.privateKey = privateKey;
|
||||
}
|
||||
|
||||
public ECPublicKey getPublicKey() {
|
||||
return publicKey;
|
||||
}
|
||||
|
||||
public ECPrivateKey getPrivateKey() {
|
||||
return privateKey;
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.crypto;
|
||||
|
||||
public interface ECPrivateKey {
|
||||
public byte[] serialize();
|
||||
public int getType();
|
||||
}
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.crypto;
|
||||
|
||||
public interface ECPublicKey extends Comparable<ECPublicKey> {
|
||||
|
||||
public static final int KEY_SIZE = 33;
|
||||
|
||||
public byte[] serialize();
|
||||
|
||||
public int getType();
|
||||
}
|
||||
+1
-1
@@ -14,7 +14,7 @@ import javax.annotation.Nullable;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.signal.zkgroup.profiles.ProfileKeyCommitment;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCommitment;
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
|
||||
public class CreateProfileRequest {
|
||||
|
||||
+1
-22
@@ -21,52 +21,31 @@ public class IncomingMessage {
|
||||
@JsonProperty
|
||||
private final int destinationRegistrationId;
|
||||
|
||||
@JsonProperty
|
||||
private final String body;
|
||||
|
||||
@JsonProperty
|
||||
private final String content;
|
||||
|
||||
@JsonProperty
|
||||
private final String relay;
|
||||
|
||||
@JsonProperty
|
||||
private long timestamp; // deprecated
|
||||
|
||||
@JsonCreator
|
||||
public IncomingMessage(
|
||||
@JsonProperty("id") final int type,
|
||||
@JsonProperty("destination") final String destination,
|
||||
@JsonProperty("destinationDeviceId") final long destinationDeviceId,
|
||||
@JsonProperty("destinationRegistrationId") final int destinationRegistrationId,
|
||||
@JsonProperty("body") final String body,
|
||||
@JsonProperty("content") final String content,
|
||||
@JsonProperty("relay") final String relay) {
|
||||
@JsonProperty("content") final String content) {
|
||||
this.type = type;
|
||||
this.destination = destination;
|
||||
this.destinationDeviceId = destinationDeviceId;
|
||||
this.destinationRegistrationId = destinationRegistrationId;
|
||||
this.body = body;
|
||||
this.content = content;
|
||||
this.relay = relay;
|
||||
}
|
||||
|
||||
public String getDestination() {
|
||||
return destination;
|
||||
}
|
||||
|
||||
public String getBody() {
|
||||
return body;
|
||||
}
|
||||
|
||||
public int getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public String getRelay() {
|
||||
return relay;
|
||||
}
|
||||
|
||||
public long getDestinationDeviceId() {
|
||||
return destinationDeviceId;
|
||||
}
|
||||
|
||||
+1
-18
@@ -15,38 +15,32 @@ public class OutgoingMessageEntity {
|
||||
|
||||
private final UUID guid;
|
||||
private final int type;
|
||||
private final String relay;
|
||||
private final long timestamp;
|
||||
private final String source;
|
||||
private final UUID sourceUuid;
|
||||
private final int sourceDevice;
|
||||
private final UUID destinationUuid;
|
||||
private final byte[] message;
|
||||
private final byte[] content;
|
||||
private final long serverTimestamp;
|
||||
|
||||
@JsonCreator
|
||||
public OutgoingMessageEntity(@JsonProperty("guid") final UUID guid,
|
||||
@JsonProperty("type") final int type,
|
||||
@JsonProperty("relay") final String relay,
|
||||
@JsonProperty("timestamp") final long timestamp,
|
||||
@JsonProperty("source") final String source,
|
||||
@JsonProperty("sourceUuid") final UUID sourceUuid,
|
||||
@JsonProperty("sourceDevice") final int sourceDevice,
|
||||
@JsonProperty("destinationUuid") final UUID destinationUuid,
|
||||
@JsonProperty("message") final byte[] message,
|
||||
@JsonProperty("content") final byte[] content,
|
||||
@JsonProperty("serverTimestamp") final long serverTimestamp)
|
||||
{
|
||||
this.guid = guid;
|
||||
this.type = type;
|
||||
this.relay = relay;
|
||||
this.timestamp = timestamp;
|
||||
this.source = source;
|
||||
this.sourceUuid = sourceUuid;
|
||||
this.sourceDevice = sourceDevice;
|
||||
this.destinationUuid = destinationUuid;
|
||||
this.message = message;
|
||||
this.content = content;
|
||||
this.serverTimestamp = serverTimestamp;
|
||||
}
|
||||
@@ -59,10 +53,6 @@ public class OutgoingMessageEntity {
|
||||
return type;
|
||||
}
|
||||
|
||||
public String getRelay() {
|
||||
return relay;
|
||||
}
|
||||
|
||||
public long getTimestamp() {
|
||||
return timestamp;
|
||||
}
|
||||
@@ -83,10 +73,6 @@ public class OutgoingMessageEntity {
|
||||
return destinationUuid;
|
||||
}
|
||||
|
||||
public byte[] getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public byte[] getContent() {
|
||||
return content;
|
||||
}
|
||||
@@ -105,18 +91,15 @@ public class OutgoingMessageEntity {
|
||||
sourceDevice == that.sourceDevice &&
|
||||
serverTimestamp == that.serverTimestamp &&
|
||||
guid.equals(that.guid) &&
|
||||
Objects.equals(relay, that.relay) &&
|
||||
Objects.equals(source, that.source) &&
|
||||
Objects.equals(sourceUuid, that.sourceUuid) &&
|
||||
destinationUuid.equals(that.destinationUuid) &&
|
||||
Arrays.equals(message, that.message) &&
|
||||
Arrays.equals(content, that.content);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = Objects.hash(guid, type, relay, timestamp, source, sourceUuid, sourceDevice, destinationUuid, serverTimestamp);
|
||||
result = 31 * result + Arrays.hashCode(message);
|
||||
int result = Objects.hash(guid, type, timestamp, source, sourceUuid, sourceDevice, destinationUuid, serverTimestamp);
|
||||
result = 31 * result + Arrays.hashCode(content);
|
||||
return result;
|
||||
}
|
||||
|
||||
+1
-1
@@ -9,7 +9,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import javax.annotation.Nullable;
|
||||
import org.signal.zkgroup.profiles.PniCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.profiles.PniCredentialResponse;
|
||||
|
||||
public class PniCredentialProfileResponse extends CredentialProfileResponse {
|
||||
|
||||
|
||||
+2
-2
@@ -13,8 +13,8 @@ import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import java.io.IOException;
|
||||
import java.util.Base64;
|
||||
import org.signal.zkgroup.InvalidInputException;
|
||||
import org.signal.zkgroup.profiles.PniCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.profiles.PniCredentialResponse;
|
||||
|
||||
public class PniCredentialResponseAdapter {
|
||||
|
||||
|
||||
+2
-2
@@ -13,8 +13,8 @@ import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import java.io.IOException;
|
||||
import java.util.Base64;
|
||||
import org.signal.zkgroup.InvalidInputException;
|
||||
import org.signal.zkgroup.profiles.ProfileKeyCommitment;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCommitment;
|
||||
|
||||
public class ProfileKeyCommitmentAdapter {
|
||||
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import org.signal.zkgroup.profiles.ProfileKeyCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialResponse;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
public class ProfileKeyCredentialProfileResponse extends CredentialProfileResponse {
|
||||
|
||||
+2
-2
@@ -13,8 +13,8 @@ import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import java.io.IOException;
|
||||
import java.util.Base64;
|
||||
import org.signal.zkgroup.InvalidInputException;
|
||||
import org.signal.zkgroup.profiles.ProfileKeyCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialResponse;
|
||||
|
||||
public class ProfileKeyCredentialResponseAdapter {
|
||||
|
||||
|
||||
+1
-2
@@ -8,7 +8,7 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
import org.signal.zkgroup.receipts.ReceiptCredentialPresentation;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
|
||||
public class RedeemReceiptRequest {
|
||||
@@ -28,7 +28,6 @@ public class RedeemReceiptRequest {
|
||||
}
|
||||
|
||||
@NotEmpty
|
||||
@ExactlySize({ReceiptCredentialPresentation.SIZE})
|
||||
public byte[] getReceiptCredentialPresentation() {
|
||||
return receiptCredentialPresentation;
|
||||
}
|
||||
|
||||
+16
-5
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* Copyright 2013-2022 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
@@ -16,7 +16,8 @@ public class UserCapabilities {
|
||||
account.isGv1MigrationSupported(),
|
||||
account.isSenderKeySupported(),
|
||||
account.isAnnouncementGroupSupported(),
|
||||
account.isChangeNumberSupported());
|
||||
account.isChangeNumberSupported(),
|
||||
account.isStoriesSupported());
|
||||
}
|
||||
|
||||
@JsonProperty
|
||||
@@ -34,19 +35,25 @@ public class UserCapabilities {
|
||||
@JsonProperty
|
||||
private boolean changeNumber;
|
||||
|
||||
public UserCapabilities() {}
|
||||
@JsonProperty
|
||||
private boolean stories;
|
||||
|
||||
public UserCapabilities() {
|
||||
}
|
||||
|
||||
public UserCapabilities(final boolean gv2,
|
||||
boolean gv1Migration,
|
||||
final boolean senderKey,
|
||||
final boolean announcementGroup,
|
||||
final boolean changeNumber) {
|
||||
final boolean changeNumber,
|
||||
final boolean stories) {
|
||||
|
||||
this.gv2 = gv2;
|
||||
this.gv2 = gv2;
|
||||
this.gv1Migration = gv1Migration;
|
||||
this.senderKey = senderKey;
|
||||
this.announcementGroup = announcementGroup;
|
||||
this.changeNumber = changeNumber;
|
||||
this.stories = stories;
|
||||
}
|
||||
|
||||
public boolean isGv2() {
|
||||
@@ -68,4 +75,8 @@ public class UserCapabilities {
|
||||
public boolean isChangeNumber() {
|
||||
return changeNumber;
|
||||
}
|
||||
|
||||
public boolean isStories() {
|
||||
return stories;
|
||||
}
|
||||
}
|
||||
+4
@@ -23,6 +23,7 @@ import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.PushChallengeDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
|
||||
public class PushChallengeManager {
|
||||
@@ -42,6 +43,7 @@ public class PushChallengeManager {
|
||||
private static final String PLATFORM_TAG_NAME = "platform";
|
||||
private static final String SENT_TAG_NAME = "sent";
|
||||
private static final String SUCCESS_TAG_NAME = "success";
|
||||
private static final String SOURCE_COUNTRY_TAG_NAME = "sourceCountry";
|
||||
|
||||
public PushChallengeManager(final APNSender apnSender, final GCMSender gcmSender,
|
||||
final PushChallengeDynamoDb pushChallengeDynamoDb) {
|
||||
@@ -84,6 +86,7 @@ public class PushChallengeManager {
|
||||
|
||||
Metrics.counter(CHALLENGE_REQUESTED_COUNTER_NAME,
|
||||
PLATFORM_TAG_NAME, platform,
|
||||
SOURCE_COUNTRY_TAG_NAME, Util.getCountryCode(account.getNumber()),
|
||||
SENT_TAG_NAME, String.valueOf(sent)).increment();
|
||||
}
|
||||
|
||||
@@ -108,6 +111,7 @@ public class PushChallengeManager {
|
||||
|
||||
Metrics.counter(CHALLENGE_ANSWERED_COUNTER_NAME,
|
||||
PLATFORM_TAG_NAME, platform,
|
||||
SOURCE_COUNTRY_TAG_NAME, Util.getCountryCode(account.getNumber()),
|
||||
SUCCESS_TAG_NAME, String.valueOf(success)).increment();
|
||||
|
||||
return success;
|
||||
|
||||
+12
-4
@@ -6,12 +6,16 @@ import io.micrometer.core.instrument.Metrics;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import org.whispersystems.textsecuregcm.abuse.RateLimitChallengeListener;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
|
||||
import org.whispersystems.textsecuregcm.recaptcha.RecaptchaClient;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
|
||||
public class RateLimitChallengeManager {
|
||||
|
||||
@@ -54,16 +58,20 @@ public class RateLimitChallengeManager {
|
||||
}
|
||||
}
|
||||
|
||||
public void answerRecaptchaChallenge(final Account account, final String captcha, final String mostRecentProxyIp)
|
||||
public void answerRecaptchaChallenge(final Account account, final String captcha, final String mostRecentProxyIp, final String userAgent)
|
||||
throws RateLimitExceededException {
|
||||
|
||||
rateLimiters.getRecaptchaChallengeAttemptLimiter().validate(account.getUuid());
|
||||
|
||||
final boolean challengeSuccess = recaptchaClient.verify(captcha, mostRecentProxyIp);
|
||||
|
||||
Metrics.counter(RECAPTCHA_ATTEMPT_COUNTER_NAME,
|
||||
SOURCE_COUNTRY_TAG_NAME, Util.getCountryCode(account.getNumber()),
|
||||
SUCCESS_TAG_NAME, String.valueOf(challengeSuccess)).increment();
|
||||
final Tags tags = Tags.of(
|
||||
Tag.of(SOURCE_COUNTRY_TAG_NAME, Util.getCountryCode(account.getNumber())),
|
||||
Tag.of(SUCCESS_TAG_NAME, String.valueOf(challengeSuccess)),
|
||||
UserAgentTagUtil.getPlatformTag(userAgent)
|
||||
);
|
||||
|
||||
Metrics.counter(RECAPTCHA_ATTEMPT_COUNTER_NAME, tags).increment();
|
||||
|
||||
if (challengeSuccess) {
|
||||
rateLimiters.getRecaptchaChallengeSuccessLimiter().validate(account.getUuid());
|
||||
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Copyright 2013-2022 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.metrics;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.util.UUID;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportedMessageListener;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
public class ReportedMessageMetricsListener implements ReportedMessageListener {
|
||||
|
||||
private final AccountsManager accountsManager;
|
||||
|
||||
// ReportMessageManager name used deliberately to preserve continuity of metrics
|
||||
private static final String REPORTED_COUNTER_NAME = name(ReportMessageManager.class, "reported");
|
||||
private static final String REPORTER_COUNTER_NAME = name(ReportMessageManager.class, "reporter");
|
||||
|
||||
private static final String COUNTRY_CODE_TAG_NAME = "countryCode";
|
||||
|
||||
public ReportedMessageMetricsListener(final AccountsManager accountsManager) {
|
||||
this.accountsManager = accountsManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleMessageReported(final String sourceNumber, final UUID messageGuid, final UUID reporterUuid) {
|
||||
Metrics.counter(REPORTED_COUNTER_NAME, COUNTRY_CODE_TAG_NAME, Util.getCountryCode(sourceNumber)).increment();
|
||||
|
||||
accountsManager.getByAccountIdentifier(reporterUuid).ifPresent(reporter ->
|
||||
Metrics.counter(REPORTER_COUNTER_NAME, COUNTRY_CODE_TAG_NAME, Util.getCountryCode(reporter.getNumber())).increment());
|
||||
}
|
||||
}
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.providers;
|
||||
|
||||
import com.codahale.metrics.health.HealthCheck;
|
||||
import org.whispersystems.textsecuregcm.redis.ReplicatedJedisPool;
|
||||
|
||||
import redis.clients.jedis.Jedis;
|
||||
|
||||
public class RedisHealthCheck extends HealthCheck {
|
||||
|
||||
private final ReplicatedJedisPool clientPool;
|
||||
|
||||
public RedisHealthCheck(ReplicatedJedisPool clientPool) {
|
||||
this.clientPool = clientPool;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Result check() throws Exception {
|
||||
try (Jedis client = clientPool.getWriteResource()) {
|
||||
client.set("HEALTH", "test");
|
||||
|
||||
if (!"test".equals(client.get("HEALTH"))) {
|
||||
return Result.unhealthy("fetch failed");
|
||||
}
|
||||
|
||||
return Result.healthy();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,36 +1,47 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* Copyright 2013-2022 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.push;
|
||||
|
||||
import com.codahale.metrics.InstrumentedExecutorService;
|
||||
import com.codahale.metrics.SharedMetricRegistries;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.controllers.NoSuchUserException;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
|
||||
public class ReceiptSender {
|
||||
|
||||
private final MessageSender messageSender;
|
||||
private final MessageSender messageSender;
|
||||
private final AccountsManager accountManager;
|
||||
private final ExecutorService executor;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ReceiptSender.class);
|
||||
|
||||
public ReceiptSender(final AccountsManager accountManager, final MessageSender messageSender) {
|
||||
public ReceiptSender(final AccountsManager accountManager, final MessageSender messageSender,
|
||||
final ExecutorService executor) {
|
||||
this.accountManager = accountManager;
|
||||
this.messageSender = messageSender;
|
||||
this.executor = new InstrumentedExecutorService(executor,
|
||||
SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME),
|
||||
MetricsUtil.name(ReceiptSender.class, "executor"));
|
||||
}
|
||||
|
||||
public void sendReceipt(AuthenticatedAccount source, UUID destinationUuid, long messageId) throws NoSuchUserException {
|
||||
public CompletableFuture<Void> sendReceipt(AuthenticatedAccount source, UUID destinationUuid, long messageId) throws NoSuchUserException {
|
||||
final Account sourceAccount = source.getAccount();
|
||||
if (sourceAccount.getUuid().equals(destinationUuid)) {
|
||||
return;
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
|
||||
final Account destinationAccount = accountManager.getByAccountIdentifier(destinationUuid)
|
||||
@@ -45,16 +56,16 @@ public class ReceiptSender {
|
||||
.setTimestamp(messageId)
|
||||
.setType(Envelope.Type.SERVER_DELIVERY_RECEIPT);
|
||||
|
||||
if (sourceAccount.getRelay().isPresent()) {
|
||||
message.setRelay(sourceAccount.getRelay().get());
|
||||
}
|
||||
|
||||
for (final Device destinationDevice : destinationAccount.getDevices()) {
|
||||
try {
|
||||
messageSender.sendMessage(destinationAccount, destinationDevice, message.build(), false);
|
||||
} catch (final NotPushRegisteredException e) {
|
||||
logger.info("User no longer push registered for delivery receipt: " + e.getMessage());
|
||||
return CompletableFuture.runAsync(() -> {
|
||||
for (final Device destinationDevice : destinationAccount.getDevices()) {
|
||||
try {
|
||||
messageSender.sendMessage(destinationAccount, destinationDevice, message.build(), false);
|
||||
} catch (final NotPushRegisteredException e) {
|
||||
logger.info("User no longer push registered for delivery receipt: " + e.getMessage());
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Could not send delivery receipt", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}, executor);
|
||||
}
|
||||
}
|
||||
-69
@@ -1,69 +0,0 @@
|
||||
/*
|
||||
* Copyright 2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.recaptcha;
|
||||
|
||||
import com.google.api.gax.core.FixedCredentialsProvider;
|
||||
import com.google.auth.oauth2.GoogleCredentials;
|
||||
import com.google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseServiceClient;
|
||||
import com.google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseServiceSettings;
|
||||
import com.google.recaptchaenterprise.v1.Assessment;
|
||||
import com.google.recaptchaenterprise.v1.Event;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.annotation.Nullable;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Objects;
|
||||
|
||||
public class EnterpriseRecaptchaClient implements RecaptchaClient {
|
||||
private static final Logger logger = LoggerFactory.getLogger(EnterpriseRecaptchaClient.class);
|
||||
|
||||
private final double scoreFloor;
|
||||
private final String siteKey;
|
||||
private final String projectPath;
|
||||
private final RecaptchaEnterpriseServiceClient client;
|
||||
|
||||
public EnterpriseRecaptchaClient(
|
||||
final double scoreFloor,
|
||||
@Nonnull final String siteKey,
|
||||
@Nonnull final String projectPath,
|
||||
@Nonnull final String recaptchaCredentialConfigurationJson) {
|
||||
try {
|
||||
this.scoreFloor = scoreFloor;
|
||||
this.siteKey = Objects.requireNonNull(siteKey);
|
||||
this.projectPath = Objects.requireNonNull(projectPath);
|
||||
this.client = RecaptchaEnterpriseServiceClient.create(RecaptchaEnterpriseServiceSettings.newBuilder()
|
||||
.setCredentialsProvider(FixedCredentialsProvider.create(GoogleCredentials.fromStream(
|
||||
new ByteArrayInputStream(recaptchaCredentialConfigurationJson.getBytes(StandardCharsets.UTF_8)))))
|
||||
.build());
|
||||
} catch (IOException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean verify(final String token, final String ip) {
|
||||
return verify(token, ip, null);
|
||||
}
|
||||
|
||||
public boolean verify(final String token, final String ip, @Nullable final String expectedAction) {
|
||||
Event.Builder eventBuilder = Event.newBuilder()
|
||||
.setSiteKey(siteKey)
|
||||
.setToken(token)
|
||||
.setUserIpAddress(ip);
|
||||
|
||||
if (expectedAction != null) {
|
||||
eventBuilder.setExpectedAction(expectedAction);
|
||||
}
|
||||
|
||||
final Event event = eventBuilder.build();
|
||||
final Assessment assessment = client.createAssessment(projectPath, Assessment.newBuilder().setEvent(event).build());
|
||||
|
||||
return assessment.getTokenProperties().getValid() && assessment.getRiskAnalysis().getScore() >= scoreFloor;
|
||||
}
|
||||
}
|
||||
-70
@@ -1,70 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.recaptcha;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
|
||||
import org.glassfish.jersey.client.ClientConfig;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.ws.rs.client.Client;
|
||||
import javax.ws.rs.client.ClientBuilder;
|
||||
import javax.ws.rs.client.Entity;
|
||||
import javax.ws.rs.core.MultivaluedHashMap;
|
||||
import javax.ws.rs.core.MultivaluedMap;
|
||||
|
||||
public class LegacyRecaptchaClient implements RecaptchaClient {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(LegacyRecaptchaClient.class);
|
||||
|
||||
private final Client client;
|
||||
private final String recaptchaSecret;
|
||||
|
||||
public LegacyRecaptchaClient(String recaptchaSecret) {
|
||||
this.client = ClientBuilder.newClient(new ClientConfig(new JacksonJaxbJsonProvider().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)));
|
||||
this.recaptchaSecret = recaptchaSecret;
|
||||
}
|
||||
|
||||
public boolean verify(String captchaToken, String ip) {
|
||||
MultivaluedMap<String, String> formData = new MultivaluedHashMap<>();
|
||||
formData.add("secret", recaptchaSecret);
|
||||
formData.add("response", captchaToken);
|
||||
formData.add("remoteip", ip);
|
||||
|
||||
VerifyResponse response = client.target("https://www.google.com/recaptcha/api/siteverify")
|
||||
.request()
|
||||
.post(Entity.form(formData), VerifyResponse.class);
|
||||
|
||||
if (response.success) {
|
||||
logger.debug("Got successful captcha time: " + response.challenge_ts + ", current time: " + System.currentTimeMillis());
|
||||
}
|
||||
|
||||
return response.success;
|
||||
}
|
||||
|
||||
private static class VerifyResponse {
|
||||
@JsonProperty
|
||||
private boolean success;
|
||||
|
||||
@JsonProperty("error-codes")
|
||||
private String[] errorCodes;
|
||||
|
||||
@JsonProperty
|
||||
private String hostname;
|
||||
|
||||
@JsonProperty
|
||||
private String challenge_ts;
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "success: " + success + ", errorCodes: " + String.join(", ", errorCodes == null ? new String[0] : errorCodes) + ", hostname: " + hostname + ", challenge_ts: " + challenge_ts;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+118
-3
@@ -1,10 +1,125 @@
|
||||
/*
|
||||
* Copyright 2021 Signal Messenger, LLC
|
||||
* Copyright 2021-2022 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.recaptcha;
|
||||
|
||||
public interface RecaptchaClient {
|
||||
boolean verify(String token, String ip);
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.api.gax.core.FixedCredentialsProvider;
|
||||
import com.google.auth.oauth2.GoogleCredentials;
|
||||
import com.google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseServiceClient;
|
||||
import com.google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseServiceSettings;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.recaptchaenterprise.v1.Assessment;
|
||||
import com.google.recaptchaenterprise.v1.Event;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Objects;
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.ws.rs.BadRequestException;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
|
||||
public class RecaptchaClient {
|
||||
|
||||
@VisibleForTesting
|
||||
static final String SEPARATOR = ".";
|
||||
@VisibleForTesting
|
||||
static final String V2_PREFIX = "signal-recaptcha-v2" + RecaptchaClient.SEPARATOR;
|
||||
private static final String ASSESSMENTS_COUNTER_NAME = name(RecaptchaClient.class, "assessments");
|
||||
private static final String SCORE_DISTRIBUTION_NAME = name(RecaptchaClient.class, "scoreDistribution");
|
||||
|
||||
private final String projectPath;
|
||||
private final RecaptchaEnterpriseServiceClient client;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
|
||||
public RecaptchaClient(
|
||||
@Nonnull final String projectPath,
|
||||
@Nonnull final String recaptchaCredentialConfigurationJson,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
try {
|
||||
this.projectPath = Objects.requireNonNull(projectPath);
|
||||
this.client = RecaptchaEnterpriseServiceClient.create(RecaptchaEnterpriseServiceSettings.newBuilder()
|
||||
.setCredentialsProvider(FixedCredentialsProvider.create(GoogleCredentials.fromStream(
|
||||
new ByteArrayInputStream(recaptchaCredentialConfigurationJson.getBytes(StandardCharsets.UTF_8)))))
|
||||
.build());
|
||||
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
} catch (IOException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the sitekey, token, and action (if any) from {@code input}. The expected input format is: {@code [version
|
||||
* prefix.]sitekey.[action.]token}.
|
||||
* <p>
|
||||
* For action to be optional, there is a strong assumption that the token will never contain a {@value SEPARATOR}.
|
||||
* Observation suggests {@code token} is base-64 encoded. In practice, an action should always be present, but we
|
||||
* don’t need to be strict.
|
||||
*/
|
||||
static String[] parseInputToken(final String input) {
|
||||
String[] parts = StringUtils.removeStart(input, V2_PREFIX).split("\\" + SEPARATOR, 3);
|
||||
|
||||
if (parts.length == 1) {
|
||||
throw new BadRequestException("too few parts");
|
||||
}
|
||||
|
||||
if (parts.length == 2) {
|
||||
// we got some parts, assume it is action that is missing
|
||||
return new String[]{parts[0], null, parts[1]};
|
||||
}
|
||||
|
||||
return parts;
|
||||
}
|
||||
|
||||
public boolean verify(final String input, final String ip) {
|
||||
final String[] parts = parseInputToken(input);
|
||||
|
||||
final String sitekey = parts[0];
|
||||
final String expectedAction = parts[1];
|
||||
final String token = parts[2];
|
||||
|
||||
Event.Builder eventBuilder = Event.newBuilder()
|
||||
.setSiteKey(sitekey)
|
||||
.setToken(token)
|
||||
.setUserIpAddress(ip);
|
||||
|
||||
if (expectedAction != null) {
|
||||
eventBuilder.setExpectedAction(expectedAction);
|
||||
}
|
||||
|
||||
final Event event = eventBuilder.build();
|
||||
final Assessment assessment = client.createAssessment(projectPath, Assessment.newBuilder().setEvent(event).build());
|
||||
|
||||
Metrics.counter(ASSESSMENTS_COUNTER_NAME,
|
||||
"action", String.valueOf(expectedAction),
|
||||
"valid", String.valueOf(assessment.getTokenProperties().getValid()))
|
||||
.increment();
|
||||
|
||||
if (assessment.getTokenProperties().getValid()) {
|
||||
final float score = assessment.getRiskAnalysis().getScore();
|
||||
|
||||
final DistributionSummary.Builder distributionSummaryBuilder = DistributionSummary.builder(
|
||||
SCORE_DISTRIBUTION_NAME)
|
||||
// score is 0.0…1.0, which doesn’t play well with distribution summary bucketing, so scale to 0…100
|
||||
.scale(100)
|
||||
.maximumExpectedValue(100.0d)
|
||||
.tags("action", String.valueOf(expectedAction));
|
||||
|
||||
distributionSummaryBuilder.register(Metrics.globalRegistry).record(score);
|
||||
|
||||
return score >= dynamicConfigurationManager.getConfiguration().getCaptchaConfiguration().getScoreFloor()
|
||||
.floatValue();
|
||||
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
-56
@@ -1,56 +0,0 @@
|
||||
/*
|
||||
* Copyright 2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.recaptcha;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.util.Objects;
|
||||
import javax.annotation.Nonnull;
|
||||
|
||||
public class TransitionalRecaptchaClient implements RecaptchaClient {
|
||||
|
||||
@VisibleForTesting
|
||||
static final String SEPARATOR = ".";
|
||||
@VisibleForTesting
|
||||
static final String V2_PREFIX = "signal-recaptcha-v2" + SEPARATOR;
|
||||
|
||||
private final LegacyRecaptchaClient legacyRecaptchaClient;
|
||||
private final EnterpriseRecaptchaClient enterpriseRecaptchaClient;
|
||||
|
||||
public TransitionalRecaptchaClient(
|
||||
@Nonnull final LegacyRecaptchaClient legacyRecaptchaClient,
|
||||
@Nonnull final EnterpriseRecaptchaClient enterpriseRecaptchaClient) {
|
||||
this.legacyRecaptchaClient = Objects.requireNonNull(legacyRecaptchaClient);
|
||||
this.enterpriseRecaptchaClient = Objects.requireNonNull(enterpriseRecaptchaClient);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean verify(@Nonnull final String token, @Nonnull final String ip) {
|
||||
if (token.startsWith(V2_PREFIX)) {
|
||||
final String[] actionAndToken = parseV2ActionAndToken(token.substring(V2_PREFIX.length()));
|
||||
return enterpriseRecaptchaClient.verify(actionAndToken[1], ip, actionAndToken[0]);
|
||||
} else {
|
||||
return legacyRecaptchaClient.verify(token, ip);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the token and action (if any) from {@code input}. The expected input format is: {@code [action:]token}.
|
||||
* <p>
|
||||
* For action to be optional, there is a strong assumption that the token will never contain a {@value SEPARATOR}.
|
||||
* Observation suggests {@code token} is base-64 encoded. In practice, an action should always be present, but we
|
||||
* don’t need to be strict.
|
||||
*/
|
||||
static String[] parseV2ActionAndToken(final String input) {
|
||||
String[] actionAndToken = input.split("\\" + SEPARATOR, 2);
|
||||
|
||||
if (actionAndToken.length == 1) {
|
||||
// there was no ":" delimiter; assume we only have a token
|
||||
return new String[]{null, actionAndToken[0]};
|
||||
}
|
||||
|
||||
return actionAndToken;
|
||||
}
|
||||
}
|
||||
@@ -242,6 +242,16 @@ public class Account {
|
||||
.allMatch(device -> device.getCapabilities() != null && device.getCapabilities().isPni());
|
||||
}
|
||||
|
||||
public boolean isStoriesSupported() {
|
||||
requireNotStale();
|
||||
|
||||
return devices.stream()
|
||||
.filter(Device::isEnabled)
|
||||
// TODO stories capability
|
||||
// .allMatch(device -> device.getCapabilities() != null && device.getCapabilities().isStories());
|
||||
.anyMatch(device -> device.getCapabilities() != null && device.getCapabilities().isStories());
|
||||
}
|
||||
|
||||
public boolean isEnabled() {
|
||||
requireNotStale();
|
||||
|
||||
@@ -272,12 +282,6 @@ public class Account {
|
||||
return count;
|
||||
}
|
||||
|
||||
public boolean isRateLimited() {
|
||||
requireNotStale();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean isCanonicallyDiscoverable() {
|
||||
requireNotStale();
|
||||
|
||||
@@ -290,12 +294,6 @@ public class Account {
|
||||
this.canonicallyDiscoverable = canonicallyDiscoverable;
|
||||
}
|
||||
|
||||
public Optional<String> getRelay() {
|
||||
requireNotStale();
|
||||
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
public void setIdentityKey(String identityKey) {
|
||||
requireNotStale();
|
||||
|
||||
|
||||
@@ -8,24 +8,39 @@ import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.base.Throwables;
|
||||
import com.google.common.collect.Lists;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicUakMigrationConfiguration;
|
||||
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;
|
||||
@@ -33,6 +48,7 @@ import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedExce
|
||||
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.ProvisionedThroughputExceededException;
|
||||
import software.amazon.awssdk.services.dynamodb.model.Put;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ReturnValuesOnConditionCheckFailure;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ScanRequest;
|
||||
@@ -42,7 +58,7 @@ import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledExcepti
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactionConflictException;
|
||||
import software.amazon.awssdk.services.dynamodb.model.Update;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;
|
||||
import software.amazon.awssdk.utils.CompletableFutureUtils;
|
||||
|
||||
public class Accounts extends AbstractDynamoDbStore {
|
||||
|
||||
@@ -60,8 +76,12 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
static final String ATTR_CANONICALLY_DISCOVERABLE = "C";
|
||||
// username; string
|
||||
static final String ATTR_USERNAME = "N";
|
||||
// unidentified access key; byte[] or null
|
||||
static final String ATTR_UAK = "UAK";
|
||||
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
private final DynamoDbClient client;
|
||||
private final DynamoDbAsyncClient asyncClient;
|
||||
|
||||
private final String phoneNumberConstraintTableName;
|
||||
private final String phoneNumberIdentifierConstraintTableName;
|
||||
@@ -82,16 +102,24 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
private static final Timer GET_ALL_FROM_START_TIMER = Metrics.timer(name(Accounts.class, "getAllFrom"));
|
||||
private static final Timer GET_ALL_FROM_OFFSET_TIMER = Metrics.timer(name(Accounts.class, "getAllFromOffset"));
|
||||
private static final Timer DELETE_TIMER = Metrics.timer(name(Accounts.class, "delete"));
|
||||
private static final Timer NORMALIZE_ITEM_TIMER = Metrics.timer(name(Accounts.class, "normalizeItem"));
|
||||
|
||||
private static final Counter UAK_NORMALIZE_SUCCESS_COUNT = Metrics.counter(name(Accounts.class, "normalizeUakSuccess"));
|
||||
private static final String UAK_NORMALIZE_ERROR_NAME = name(Accounts.class, "normalizeUakError");
|
||||
private static final String UAK_NORMALIZE_FAILURE_REASON_TAG_NAME = "reason";
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(Accounts.class);
|
||||
|
||||
public Accounts(DynamoDbClient client, String accountsTableName, String phoneNumberConstraintTableName,
|
||||
public Accounts(final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
DynamoDbClient client, DynamoDbAsyncClient asyncClient,
|
||||
String accountsTableName, String phoneNumberConstraintTableName,
|
||||
String phoneNumberIdentifierConstraintTableName, final String usernamesConstraintTableName,
|
||||
final int scanPageSize) {
|
||||
|
||||
super(client);
|
||||
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
this.client = client;
|
||||
this.asyncClient = asyncClient;
|
||||
this.phoneNumberConstraintTableName = phoneNumberConstraintTableName;
|
||||
this.phoneNumberIdentifierConstraintTableName = phoneNumberIdentifierConstraintTableName;
|
||||
this.accountsTableName = accountsTableName;
|
||||
@@ -147,6 +175,11 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
ATTR_VERSION, AttributeValues.fromInt(account.getVersion()),
|
||||
ATTR_CANONICALLY_DISCOVERABLE, AttributeValues.fromBool(account.shouldBeVisibleInDirectory())));
|
||||
|
||||
// Add the UAK if it's in the account
|
||||
account.getUnidentifiedAccessKey()
|
||||
.map(AttributeValues::fromByteArray)
|
||||
.ifPresent(uak -> item.put(ATTR_UAK, uak));
|
||||
|
||||
TransactWriteItem accountPut = TransactWriteItem.builder()
|
||||
.put(Put.builder()
|
||||
.conditionExpression("attribute_not_exists(#number) OR #number = :number")
|
||||
@@ -448,45 +481,89 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
});
|
||||
}
|
||||
|
||||
public void update(Account account) throws ContestedOptimisticLockException {
|
||||
UPDATE_TIMER.record(() -> {
|
||||
final UpdateItemRequest updateItemRequest;
|
||||
/**
|
||||
* Extract the cause from a CompletionException
|
||||
*/
|
||||
private static Throwable unwrap(Throwable throwable) {
|
||||
while (throwable instanceof CompletionException e && throwable.getCause() != null) {
|
||||
throwable = e.getCause();
|
||||
}
|
||||
return throwable;
|
||||
}
|
||||
|
||||
public CompletionStage<Void> updateAsync(Account account) {
|
||||
return record(UPDATE_TIMER, () -> {
|
||||
final UpdateItemRequest updateItemRequest;
|
||||
try {
|
||||
// username, e164, and pni cannot be modified through this method
|
||||
Map<String, String> attrNames = new HashMap<>(Map.of(
|
||||
"#number", ATTR_ACCOUNT_E164,
|
||||
"#data", ATTR_ACCOUNT_DATA,
|
||||
"#cds", ATTR_CANONICALLY_DISCOVERABLE,
|
||||
"#version", ATTR_VERSION));
|
||||
Map<String, AttributeValue> attrValues = new HashMap<>(Map.of(
|
||||
":data", AttributeValues.fromByteArray(SystemMapper.getMapper().writeValueAsBytes(account)),
|
||||
":cds", AttributeValues.fromBool(account.shouldBeVisibleInDirectory()),
|
||||
":version", AttributeValues.fromInt(account.getVersion()),
|
||||
":version_increment", AttributeValues.fromInt(1)));
|
||||
|
||||
final String updateExpression;
|
||||
if (account.getUnidentifiedAccessKey().isPresent()) {
|
||||
// if it's present in the account, also set the uak
|
||||
attrNames.put("#uak", ATTR_UAK);
|
||||
attrValues.put(":uak", AttributeValues.fromByteArray(account.getUnidentifiedAccessKey().get()));
|
||||
updateExpression = "SET #data = :data, #cds = :cds, #uak = :uak ADD #version :version_increment";
|
||||
} else {
|
||||
updateExpression = "SET #data = :data, #cds = :cds ADD #version :version_increment";
|
||||
}
|
||||
|
||||
updateItemRequest = UpdateItemRequest.builder()
|
||||
.tableName(accountsTableName)
|
||||
.key(Map.of(KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getUuid())))
|
||||
.updateExpression("SET #data = :data, #cds = :cds ADD #version :version_increment")
|
||||
.conditionExpression("attribute_exists(#number) AND #version = :version")
|
||||
.expressionAttributeNames(Map.of("#number", ATTR_ACCOUNT_E164,
|
||||
"#data", ATTR_ACCOUNT_DATA,
|
||||
"#cds", ATTR_CANONICALLY_DISCOVERABLE,
|
||||
"#version", ATTR_VERSION))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":data", AttributeValues.fromByteArray(SystemMapper.getMapper().writeValueAsBytes(account)),
|
||||
":cds", AttributeValues.fromBool(account.shouldBeVisibleInDirectory()),
|
||||
":version", AttributeValues.fromInt(account.getVersion()),
|
||||
":version_increment", AttributeValues.fromInt(1)))
|
||||
.build();
|
||||
.tableName(accountsTableName)
|
||||
.key(Map.of(KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getUuid())))
|
||||
.updateExpression(updateExpression)
|
||||
.conditionExpression("attribute_exists(#number) AND #version = :version")
|
||||
.expressionAttributeNames(attrNames)
|
||||
.expressionAttributeValues(attrValues)
|
||||
.build();
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalArgumentException(e);
|
||||
}
|
||||
|
||||
try {
|
||||
final UpdateItemResponse response = client.updateItem(updateItemRequest);
|
||||
account.setVersion(AttributeValues.getInt(response.attributes(), "V", account.getVersion() + 1));
|
||||
} catch (final TransactionConflictException e) {
|
||||
|
||||
throw new ContestedOptimisticLockException();
|
||||
|
||||
} catch (final ConditionalCheckFailedException e) {
|
||||
// the exception doesn't give details about which condition failed,
|
||||
// but we can infer it was an optimistic locking failure if the UUID is known
|
||||
throw getByAccountIdentifier(account.getUuid()).isPresent() ? new ContestedOptimisticLockException() : e;
|
||||
}
|
||||
return asyncClient.updateItem(updateItemRequest)
|
||||
.thenApply(response -> {
|
||||
account.setVersion(AttributeValues.getInt(response.attributes(), "V", account.getVersion() + 1));
|
||||
return (Void) null;
|
||||
})
|
||||
.exceptionally(throwable -> {
|
||||
final Throwable unwrapped = unwrap(throwable);
|
||||
if (unwrapped instanceof TransactionConflictException) {
|
||||
throw new ContestedOptimisticLockException();
|
||||
} else if (unwrapped instanceof ConditionalCheckFailedException e) {
|
||||
// the exception doesn't give details about which condition failed,
|
||||
// but we can infer it was an optimistic locking failure if the UUID is known
|
||||
throw getByAccountIdentifier(account.getUuid()).isPresent() ? new ContestedOptimisticLockException() : e;
|
||||
} else {
|
||||
// rethrow
|
||||
throw CompletableFutureUtils.errorAsCompletionException(throwable);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public void update(Account account) throws ContestedOptimisticLockException {
|
||||
try {
|
||||
this.updateAsync(account).toCompletableFuture().join();
|
||||
} catch (CompletionException e) {
|
||||
// unwrap CompletionExceptions, throw as long is it's unchecked
|
||||
Throwables.throwIfUnchecked(unwrap(e));
|
||||
|
||||
// if we otherwise somehow got a wrapped checked exception,
|
||||
// rethrow the checked exception wrapped by the original CompletionException
|
||||
log.error("Unexpected checked exception thrown from dynamo update", e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
public Optional<Account> getByE164(String number) {
|
||||
return GET_BY_NUMBER_TIMER.record(() -> {
|
||||
|
||||
@@ -498,7 +575,7 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
return Optional.ofNullable(response.item())
|
||||
.map(item -> item.get(KEY_ACCOUNT_UUID))
|
||||
.map(this::accountByUuid)
|
||||
.map(this::fromItem);
|
||||
.map(Accounts::fromItem);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -513,7 +590,7 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
return Optional.ofNullable(response.item())
|
||||
.map(item -> item.get(KEY_ACCOUNT_UUID))
|
||||
.map(this::accountByUuid)
|
||||
.map(this::fromItem);
|
||||
.map(Accounts::fromItem);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -528,7 +605,7 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
return Optional.ofNullable(response.item())
|
||||
.map(item -> item.get(KEY_ACCOUNT_UUID))
|
||||
.map(this::accountByUuid)
|
||||
.map(this::fromItem);
|
||||
.map(Accounts::fromItem);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -544,7 +621,7 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
public Optional<Account> getByAccountIdentifier(UUID uuid) {
|
||||
return GET_BY_UUID_TIMER.record(() ->
|
||||
Optional.ofNullable(accountByUuid(AttributeValues.fromUUID(uuid)))
|
||||
.map(this::fromItem));
|
||||
.map(Accounts::fromItem));
|
||||
}
|
||||
|
||||
public void delete(UUID uuid) {
|
||||
@@ -605,15 +682,87 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
return scanForChunk(scanRequestBuilder, maxCount, GET_ALL_FROM_START_TIMER);
|
||||
}
|
||||
|
||||
private static <T> CompletionStage<T> record(final Timer timer, Supplier<CompletionStage<T>> toRecord) {
|
||||
final Instant start = Instant.now();
|
||||
return toRecord.get().whenComplete((ignoreT, ignoreE) -> timer.record(Duration.between(start, Instant.now())));
|
||||
}
|
||||
|
||||
private List<Account> normalizeIfRequired(final List<Map<String, AttributeValue>> items) {
|
||||
|
||||
// The UAK top-level attribute may not exist on older records,
|
||||
// if it is absent and there is a UAK in the account blob we'll
|
||||
// add the UAK as a top-level attribute
|
||||
// TODO: Can eliminate this once all uaks exist as top-level attributes
|
||||
final List<Account> allAccounts = new ArrayList<>();
|
||||
final List<Account> accountsToNormalize = new ArrayList<>();
|
||||
for (Map<String, AttributeValue> item : items) {
|
||||
final Account account = fromItem(item);
|
||||
allAccounts.add(account);
|
||||
|
||||
boolean hasAttrUak = item.containsKey(ATTR_UAK);
|
||||
if (!hasAttrUak && account.getUnidentifiedAccessKey().isPresent()) {
|
||||
// the top level uak attribute doesn't exist, but there's a uak in the account
|
||||
accountsToNormalize.add(account);
|
||||
} else if (hasAttrUak && account.getUnidentifiedAccessKey().isPresent()) {
|
||||
final AttributeValue attr = item.get(ATTR_UAK);
|
||||
final byte[] nestedUak = account.getUnidentifiedAccessKey().get();
|
||||
if (!Arrays.equals(attr.b().asByteArray(), nestedUak)) {
|
||||
log.warn("Discovered mismatch between attribute UAK data UAK, normalizing");
|
||||
accountsToNormalize.add(account);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final DynamicUakMigrationConfiguration currentConfig = this.dynamicConfigurationManager.getConfiguration().getUakMigrationConfiguration();
|
||||
if (!currentConfig.isEnabled()) {
|
||||
log.debug("Account normalization is disabled, skipping normalization for {} accounts", accountsToNormalize.size());
|
||||
return allAccounts;
|
||||
}
|
||||
|
||||
for (List<Account> accounts : Lists.partition(accountsToNormalize, currentConfig.getMaxOutstandingNormalizes())) {
|
||||
try {
|
||||
final CompletableFuture<?>[] accountFutures = accounts.stream()
|
||||
.map(account -> record(NORMALIZE_ITEM_TIMER,
|
||||
() -> this.updateAsync(account).whenComplete((result, throwable) -> {
|
||||
if (throwable == null) {
|
||||
UAK_NORMALIZE_SUCCESS_COUNT.increment();
|
||||
return;
|
||||
}
|
||||
|
||||
throwable = unwrap(throwable);
|
||||
if (throwable instanceof ContestedOptimisticLockException) {
|
||||
// Could succeed on retry, but just backoff since this is a housekeeping operation
|
||||
Metrics.counter(UAK_NORMALIZE_ERROR_NAME,
|
||||
Tags.of(UAK_NORMALIZE_FAILURE_REASON_TAG_NAME, "ContestedOptimisticLock")).increment();
|
||||
} else if (throwable instanceof ProvisionedThroughputExceededException) {
|
||||
Metrics.counter(UAK_NORMALIZE_ERROR_NAME,
|
||||
Tags.of(UAK_NORMALIZE_FAILURE_REASON_TAG_NAME, "ProvisionedThroughPutExceeded"))
|
||||
.increment();
|
||||
} else {
|
||||
log.warn("Failed to normalize account, skipping", throwable);
|
||||
Metrics.counter(UAK_NORMALIZE_ERROR_NAME,
|
||||
Tags.of(UAK_NORMALIZE_FAILURE_REASON_TAG_NAME, "unknown"))
|
||||
.increment();
|
||||
}
|
||||
})).toCompletableFuture()).toArray(CompletableFuture[]::new);
|
||||
|
||||
// wait for a futures in batch to complete
|
||||
CompletableFuture
|
||||
.allOf(accountFutures)
|
||||
// exceptions handled in individual futures
|
||||
.exceptionally(e -> null)
|
||||
.join();
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to update batch of {} accounts, skipping", accounts.size(), e);
|
||||
}
|
||||
}
|
||||
return allAccounts;
|
||||
}
|
||||
|
||||
private AccountCrawlChunk scanForChunk(final ScanRequest.Builder scanRequestBuilder, final int maxCount, final Timer timer) {
|
||||
|
||||
scanRequestBuilder.tableName(accountsTableName);
|
||||
|
||||
final List<Account> accounts = timer.record(() -> scan(scanRequestBuilder.build(), maxCount)
|
||||
.stream()
|
||||
.map(this::fromItem)
|
||||
.collect(Collectors.toList()));
|
||||
|
||||
final List<Map<String, AttributeValue>> items = timer.record(() -> scan(scanRequestBuilder.build(), maxCount));
|
||||
final List<Account> accounts = normalizeIfRequired(items);
|
||||
return new AccountCrawlChunk(accounts, accounts.size() > 0 ? accounts.get(accounts.size() - 1).getUuid() : null);
|
||||
}
|
||||
|
||||
@@ -623,9 +772,8 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
.collect(Collectors.joining(", "));
|
||||
}
|
||||
|
||||
// TODO Make this static once PNI repairs are complete and the call to #update(Account) is no longer needed
|
||||
@VisibleForTesting
|
||||
Account fromItem(Map<String, AttributeValue> item) {
|
||||
static Account fromItem(Map<String, AttributeValue> item) {
|
||||
if (!item.containsKey(ATTR_ACCOUNT_DATA) ||
|
||||
!item.containsKey(ATTR_ACCOUNT_E164) ||
|
||||
// TODO: eventually require ATTR_CANONICALLY_DISCOVERABLE
|
||||
@@ -645,27 +793,12 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
accountIdentifier, account.getPhoneNumberIdentifier(), phoneNumberIdentifierFromAttribute);
|
||||
}
|
||||
|
||||
boolean shouldResetPni = false;
|
||||
|
||||
if (account.getPhoneNumberIdentifier() == null && phoneNumberIdentifierFromAttribute != null) {
|
||||
log.info("Account {} has a PNI in its attributes, but not JSON blob; will repair", accountIdentifier);
|
||||
shouldResetPni = true;
|
||||
}
|
||||
|
||||
account.setNumber(item.get(ATTR_ACCOUNT_E164).s(), phoneNumberIdentifierFromAttribute);
|
||||
account.setUuid(accountIdentifier);
|
||||
account.setUsername(AttributeValues.getString(item, ATTR_USERNAME, null));
|
||||
account.setVersion(Integer.parseInt(item.get(ATTR_VERSION).n()));
|
||||
account.setCanonicallyDiscoverable(Optional.ofNullable(item.get(ATTR_CANONICALLY_DISCOVERABLE)).map(av -> av.bool()).orElse(false));
|
||||
|
||||
if (shouldResetPni) {
|
||||
try {
|
||||
update(account);
|
||||
} catch (final Exception e) {
|
||||
log.warn("Failed to reset PNI for account {}", accountIdentifier, e);
|
||||
}
|
||||
}
|
||||
|
||||
return account;
|
||||
|
||||
} catch (IOException e) {
|
||||
|
||||
@@ -194,6 +194,7 @@ public class AccountsManager {
|
||||
if (!originalUuid.equals(actualUuid)) {
|
||||
messagesManager.clear(actualUuid);
|
||||
keys.delete(actualUuid);
|
||||
keys.delete(account.getPhoneNumberIdentifier());
|
||||
profilesManager.deleteAll(actualUuid);
|
||||
}
|
||||
|
||||
@@ -221,6 +222,7 @@ public class AccountsManager {
|
||||
|
||||
public Account changeNumber(final Account account, final String number) throws InterruptedException {
|
||||
final String originalNumber = account.getNumber();
|
||||
final UUID originalPhoneNumberIdentifier = account.getPhoneNumberIdentifier();
|
||||
|
||||
if (originalNumber.equals(number)) {
|
||||
return account;
|
||||
@@ -261,6 +263,9 @@ public class AccountsManager {
|
||||
updatedAccount.set(numberChangedAccount);
|
||||
directoryQueue.changePhoneNumber(numberChangedAccount, originalNumber, number);
|
||||
|
||||
keys.delete(phoneNumberIdentifier);
|
||||
keys.delete(originalPhoneNumberIdentifier);
|
||||
|
||||
return displacedUuid;
|
||||
});
|
||||
|
||||
|
||||
@@ -188,7 +188,7 @@ public class Device {
|
||||
return (id == MASTER_ID && hasChannel && signedPreKey != null) ||
|
||||
(id != MASTER_ID && hasChannel && signedPreKey != null && lastSeen > (System.currentTimeMillis() - TimeUnit.DAYS.toMillis(30)));
|
||||
}
|
||||
|
||||
|
||||
public boolean getFetchesMessages() {
|
||||
return fetchesMessages;
|
||||
}
|
||||
@@ -295,12 +295,15 @@ public class Device {
|
||||
@JsonProperty
|
||||
private boolean pni;
|
||||
|
||||
@JsonProperty
|
||||
private boolean stories;
|
||||
|
||||
public DeviceCapabilities() {
|
||||
}
|
||||
|
||||
public DeviceCapabilities(boolean gv2, final boolean gv2_2, final boolean gv2_3, boolean storage, boolean transfer,
|
||||
boolean gv1Migration, final boolean senderKey, final boolean announcementGroup, final boolean changeNumber,
|
||||
final boolean pni) {
|
||||
final boolean pni, final boolean stories) {
|
||||
this.gv2 = gv2;
|
||||
this.gv2_2 = gv2_2;
|
||||
this.gv2_3 = gv2_3;
|
||||
@@ -311,6 +314,7 @@ public class Device {
|
||||
this.announcementGroup = announcementGroup;
|
||||
this.changeNumber = changeNumber;
|
||||
this.pni = pni;
|
||||
this.stories = stories;
|
||||
}
|
||||
|
||||
public boolean isGv2() {
|
||||
@@ -352,5 +356,9 @@ public class Device {
|
||||
public boolean isPni() {
|
||||
return pni;
|
||||
}
|
||||
|
||||
public boolean isStories() {
|
||||
return stories;
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -25,7 +25,7 @@ import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import javax.ws.rs.ClientErrorException;
|
||||
import javax.ws.rs.core.Response.Status;
|
||||
import org.signal.zkgroup.receipts.ReceiptCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
|
||||
|
||||
@@ -380,13 +380,11 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
return new OutgoingMessageEntity(
|
||||
envelope.hasServerGuid() ? UUID.fromString(envelope.getServerGuid()) : null,
|
||||
envelope.getType().getNumber(),
|
||||
envelope.getRelay(),
|
||||
envelope.getTimestamp(),
|
||||
envelope.getSource(),
|
||||
envelope.hasSourceUuid() ? UUID.fromString(envelope.getSourceUuid()) : null,
|
||||
envelope.getSourceDevice(),
|
||||
envelope.hasDestinationUuid() ? UUID.fromString(envelope.getDestinationUuid()) : null,
|
||||
envelope.hasLegacyMessage() ? envelope.getLegacyMessage().toByteArray() : null,
|
||||
envelope.hasContent() ? envelope.getContent().toByteArray() : null,
|
||||
envelope.hasServerTimestamp() ? envelope.getServerTimestamp() : 0);
|
||||
}
|
||||
|
||||
+3
-16
@@ -41,13 +41,11 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
private static final String LOCAL_INDEX_MESSAGE_UUID_KEY_SORT = "U";
|
||||
|
||||
private static final String KEY_TYPE = "T";
|
||||
private static final String KEY_RELAY = "R";
|
||||
private static final String KEY_TIMESTAMP = "TS";
|
||||
private static final String KEY_SOURCE = "SN";
|
||||
private static final String KEY_SOURCE_UUID = "SU";
|
||||
private static final String KEY_SOURCE_DEVICE = "SD";
|
||||
private static final String KEY_DESTINATION_UUID = "DU";
|
||||
private static final String KEY_MESSAGE = "M";
|
||||
private static final String KEY_CONTENT = "C";
|
||||
private static final String KEY_TTL = "E";
|
||||
|
||||
@@ -73,7 +71,7 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
|
||||
private void storeBatch(final List<MessageProtos.Envelope> messages, final UUID destinationAccountUuid, final long destinationDeviceId) {
|
||||
if (messages.size() > DYNAMO_DB_MAX_BATCH_SIZE) {
|
||||
throw new IllegalArgumentException("Maximum batch size of " + DYNAMO_DB_MAX_BATCH_SIZE + " execeeded with " + messages.size() + " messages");
|
||||
throw new IllegalArgumentException("Maximum batch size of " + DYNAMO_DB_MAX_BATCH_SIZE + " exceeded with " + messages.size() + " messages");
|
||||
}
|
||||
|
||||
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
@@ -88,14 +86,8 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
.put(KEY_TIMESTAMP, AttributeValues.fromLong(message.getTimestamp()))
|
||||
.put(KEY_TTL, AttributeValues.fromLong(getTtlForMessage(message)));
|
||||
|
||||
// TODO All messages should have a destination UUID by 2021-12-03, and this can be set unconditionally
|
||||
if (message.hasDestinationUuid()) {
|
||||
item.put(KEY_DESTINATION_UUID, AttributeValues.fromUUID(UUID.fromString(message.getDestinationUuid())));
|
||||
}
|
||||
item.put(KEY_DESTINATION_UUID, AttributeValues.fromUUID(UUID.fromString(message.getDestinationUuid())));
|
||||
|
||||
if (message.hasRelay() && message.getRelay().length() > 0) {
|
||||
item.put(KEY_RELAY, AttributeValues.fromString(message.getRelay()));
|
||||
}
|
||||
if (message.hasSource()) {
|
||||
item.put(KEY_SOURCE, AttributeValues.fromString(message.getSource()));
|
||||
}
|
||||
@@ -105,9 +97,6 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
if (message.hasSourceDevice()) {
|
||||
item.put(KEY_SOURCE_DEVICE, AttributeValues.fromInt(message.getSourceDevice()));
|
||||
}
|
||||
if (message.hasLegacyMessage()) {
|
||||
item.put(KEY_MESSAGE, AttributeValues.fromByteArray(message.getLegacyMessage().toByteArray()));
|
||||
}
|
||||
if (message.hasContent()) {
|
||||
item.put(KEY_CONTENT, AttributeValues.fromByteArray(message.getContent().toByteArray()));
|
||||
}
|
||||
@@ -226,15 +215,13 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
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 UUID destinationUuid = AttributeValues.getUUID(message, KEY_DESTINATION_UUID, null);
|
||||
final byte[] messageBytes = AttributeValues.getByteArray(message, KEY_MESSAGE, null);
|
||||
final byte[] content = AttributeValues.getByteArray(message, KEY_CONTENT, null);
|
||||
return new OutgoingMessageEntity(messageUuid, type, relay, timestamp, source, sourceUuid, sourceDevice, destinationUuid, messageBytes, content, sortKey.getServerTimestamp());
|
||||
return new OutgoingMessageEntity(messageUuid, type, timestamp, source, sourceUuid, sourceDevice, destinationUuid, content, sortKey.getServerTimestamp());
|
||||
}
|
||||
|
||||
private void deleteRowsMatchingQuery(AttributeValue partitionKey, QueryRequest querySpec) {
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import javax.annotation.Nonnull;
|
||||
import org.signal.zkgroup.receipts.ReceiptSerial;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
|
||||
+15
-16
@@ -1,48 +1,44 @@
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.lettuce.core.RedisException;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.MeterRegistry;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
public class ReportMessageManager {
|
||||
|
||||
@VisibleForTesting
|
||||
static final String REPORT_COUNTER_NAME = name(ReportMessageManager.class, "reported");
|
||||
|
||||
private final ReportMessageDynamoDb reportMessageDynamoDb;
|
||||
private final FaultTolerantRedisCluster rateLimitCluster;
|
||||
private final MeterRegistry meterRegistry;
|
||||
|
||||
private final Duration counterTtl;
|
||||
|
||||
private final List<ReportedMessageListener> reportedMessageListeners = new ArrayList<>();
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ReportMessageManager.class);
|
||||
|
||||
public ReportMessageManager(final ReportMessageDynamoDb reportMessageDynamoDb,
|
||||
final FaultTolerantRedisCluster rateLimitCluster,
|
||||
final MeterRegistry meterRegistry,
|
||||
final Duration counterTtl) {
|
||||
|
||||
this.reportMessageDynamoDb = reportMessageDynamoDb;
|
||||
this.rateLimitCluster = rateLimitCluster;
|
||||
this.meterRegistry = meterRegistry;
|
||||
|
||||
this.counterTtl = counterTtl;
|
||||
}
|
||||
|
||||
public void addListener(final ReportedMessageListener listener) {
|
||||
this.reportedMessageListeners.add(listener);
|
||||
}
|
||||
|
||||
public void store(String sourceNumber, UUID messageGuid) {
|
||||
|
||||
try {
|
||||
@@ -66,10 +62,13 @@ public class ReportMessageManager {
|
||||
connection.sync().expire(reportedSenderKey, counterTtl.toSeconds());
|
||||
});
|
||||
|
||||
Counter.builder(REPORT_COUNTER_NAME)
|
||||
.tag("countryCode", Util.getCountryCode(sourceNumber))
|
||||
.register(meterRegistry)
|
||||
.increment();
|
||||
reportedMessageListeners.forEach(listener -> {
|
||||
try {
|
||||
listener.handleMessageReported(sourceNumber, messageGuid, reporterUuid);
|
||||
} catch (final Exception e) {
|
||||
logger.error("Failed to notify listener of reported message", e);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
/*
|
||||
* Copyright 2013-2022 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public interface ReportedMessageListener {
|
||||
|
||||
void handleMessageReported(String sourceNumber, UUID messageGuid, UUID reporterUuid);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
/**
|
||||
* Select a random item according to its weight
|
||||
*
|
||||
* @param <T> the type of the objects to select from
|
||||
*/
|
||||
public class WeightedRandomSelect<T> {
|
||||
|
||||
List<Pair<T, Long>> weightedItems;
|
||||
long totalWeight;
|
||||
|
||||
public WeightedRandomSelect(List<Pair<T, Long>> weightedItems) throws IllegalArgumentException {
|
||||
this.weightedItems = weightedItems;
|
||||
this.totalWeight = weightedItems.stream().mapToLong(Pair::second).sum();
|
||||
|
||||
weightedItems.stream().map(Pair::second).filter(w -> w < 0).findFirst().ifPresent(invalid -> {
|
||||
throw new IllegalArgumentException("Illegal selection weight " + invalid);
|
||||
});
|
||||
|
||||
if (weightedItems.isEmpty() || totalWeight == 0) {
|
||||
throw new IllegalArgumentException("Cannot create an empty weighted random selector");
|
||||
}
|
||||
}
|
||||
|
||||
public T select() {
|
||||
if (weightedItems.size() == 1) {
|
||||
return weightedItems.get(0).first();
|
||||
}
|
||||
long select = ThreadLocalRandom.current().nextLong(0, totalWeight);
|
||||
long current = 0;
|
||||
for (Pair<T, Long> item : weightedItems) {
|
||||
/*
|
||||
Accumulate weights for each item and select the first item whose
|
||||
cumulative weight exceeds the selected value. nextLong() is exclusive,
|
||||
so by the last item we're guaranteed to find a value as the
|
||||
last item's weight is one more than the maximum value of select.
|
||||
*/
|
||||
current += item.second();
|
||||
if (current > select) {
|
||||
return item.first();
|
||||
}
|
||||
}
|
||||
throw new IllegalStateException("totalWeight " + totalWeight + " exceeds item weights");
|
||||
}
|
||||
|
||||
public static <T> T select(List<Pair<T, Long>> weightedItems) {
|
||||
return new WeightedRandomSelect<T>(weightedItems).select();
|
||||
}
|
||||
|
||||
}
|
||||
-76
@@ -1,76 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.websocket;
|
||||
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.dispatch.DispatchChannel;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PubSubProtos.PubSubMessage;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
public class DeadLetterHandler implements DispatchChannel {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(DeadLetterHandler.class);
|
||||
|
||||
private final AccountsManager accountsManager;
|
||||
private final MessagesManager messagesManager;
|
||||
|
||||
private final Counter deadLetterCounter = Metrics.counter(name(getClass(), "deadLetterCounter"));
|
||||
|
||||
public DeadLetterHandler(AccountsManager accountsManager, MessagesManager messagesManager) {
|
||||
this.accountsManager = accountsManager;
|
||||
this.messagesManager = messagesManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDispatchMessage(String channel, byte[] data) {
|
||||
try {
|
||||
logger.info("Handling dead letter to: " + channel);
|
||||
deadLetterCounter.increment();
|
||||
|
||||
WebsocketAddress address = new WebsocketAddress(channel);
|
||||
PubSubMessage pubSubMessage = PubSubMessage.parseFrom(data);
|
||||
|
||||
switch (pubSubMessage.getType().getNumber()) {
|
||||
case PubSubMessage.Type.DELIVER_VALUE:
|
||||
Envelope message = Envelope.parseFrom(pubSubMessage.getContent());
|
||||
Optional<Account> maybeAccount = accountsManager.getByE164(address.getNumber());
|
||||
|
||||
if (maybeAccount.isPresent()) {
|
||||
messagesManager.insert(maybeAccount.get().getUuid(), address.getDeviceId(), message);
|
||||
} else {
|
||||
logger.warn("Dead letter for account that no longer exists: {}", address);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
} catch (InvalidProtocolBufferException e) {
|
||||
logger.warn("Bad pubsub message", e);
|
||||
} catch (InvalidWebsocketAddressException e) {
|
||||
logger.warn("Invalid websocket address", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDispatchSubscribed(String channel) {
|
||||
logger.warn("DeadLetterHandler subscription notice! " + channel);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDispatchUnsubscribed(String channel) {
|
||||
logger.warn("DeadLetterHandler unsubscribe notice! " + channel);
|
||||
}
|
||||
}
|
||||
-8
@@ -326,18 +326,10 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
}
|
||||
}
|
||||
|
||||
if (message.getMessage() != null) {
|
||||
builder.setLegacyMessage(ByteString.copyFrom(message.getMessage()));
|
||||
}
|
||||
|
||||
if (message.getContent() != null) {
|
||||
builder.setContent(ByteString.copyFrom(message.getContent()));
|
||||
}
|
||||
|
||||
if (message.getRelay() != null && !message.getRelay().isEmpty()) {
|
||||
builder.setRelay(message.getRelay());
|
||||
}
|
||||
|
||||
builder.setDestinationUuid(message.getDestinationUuid().toString());
|
||||
|
||||
builder.setServerGuid(message.getGuid().toString());
|
||||
|
||||
+4
-3
@@ -16,7 +16,6 @@ import io.dropwizard.Application;
|
||||
import io.dropwizard.cli.EnvironmentCommand;
|
||||
import io.dropwizard.setup.Environment;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Clock;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
@@ -135,7 +134,9 @@ public class AssignUsernameCommand extends EnvironmentCommand<WhisperServerConfi
|
||||
VerificationCodeStore pendingAccounts = new VerificationCodeStore(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getPendingAccounts().getTableName());
|
||||
|
||||
Accounts accounts = new Accounts(dynamoDbClient,
|
||||
Accounts accounts = new Accounts(dynamicConfigurationManager,
|
||||
dynamoDbClient,
|
||||
dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getAccounts().getTableName(),
|
||||
configuration.getDynamoDbTables().getAccounts().getPhoneNumberTableName(),
|
||||
configuration.getDynamoDbTables().getAccounts().getPhoneNumberIdentifierTableName(),
|
||||
@@ -178,7 +179,7 @@ public class AssignUsernameCommand extends EnvironmentCommand<WhisperServerConfi
|
||||
configuration.getDynamoDbTables().getReportMessage().getTableName(),
|
||||
configuration.getReportMessageConfiguration().getReportTtl());
|
||||
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster,
|
||||
Metrics.globalRegistry, configuration.getReportMessageConfiguration().getCounterTtl());
|
||||
configuration.getReportMessageConfiguration().getCounterTtl());
|
||||
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, pushLatencyManager,
|
||||
reportMessageManager);
|
||||
DeletedAccountsManager deletedAccountsManager = new DeletedAccountsManager(deletedAccounts,
|
||||
|
||||
+9
-4
@@ -10,9 +10,9 @@ import com.google.protobuf.ByteString;
|
||||
import net.sourceforge.argparse4j.impl.Arguments;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.whispersystems.textsecuregcm.crypto.Curve;
|
||||
import org.whispersystems.textsecuregcm.crypto.ECKeyPair;
|
||||
import org.whispersystems.textsecuregcm.crypto.ECPrivateKey;
|
||||
import org.signal.libsignal.protocol.ecc.Curve;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.signal.libsignal.protocol.ecc.ECPrivateKey;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
|
||||
import java.io.IOException;
|
||||
@@ -91,7 +91,12 @@ public class CertificateCommand extends Command {
|
||||
.build()
|
||||
.toByteArray();
|
||||
|
||||
byte[] signature = Curve.calculateSignature(key, certificate);
|
||||
byte[] signature;
|
||||
try {
|
||||
signature = Curve.calculateSignature(key, certificate);
|
||||
} catch (org.signal.libsignal.protocol.InvalidKeyException e) {
|
||||
throw new InvalidKeyException(e);
|
||||
}
|
||||
|
||||
byte[] signedCertificate = MessageProtos.ServerCertificate.newBuilder()
|
||||
.setCertificate(ByteString.copyFrom(certificate))
|
||||
|
||||
+4
-3
@@ -16,7 +16,6 @@ import io.dropwizard.Application;
|
||||
import io.dropwizard.cli.EnvironmentCommand;
|
||||
import io.dropwizard.setup.Environment;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Clock;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
@@ -138,7 +137,9 @@ public class DeleteUserCommand extends EnvironmentCommand<WhisperServerConfigura
|
||||
VerificationCodeStore pendingAccounts = new VerificationCodeStore(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getPendingAccounts().getTableName());
|
||||
|
||||
Accounts accounts = new Accounts(dynamoDbClient,
|
||||
Accounts accounts = new Accounts(dynamicConfigurationManager,
|
||||
dynamoDbClient,
|
||||
dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getAccounts().getTableName(),
|
||||
configuration.getDynamoDbTables().getAccounts().getPhoneNumberTableName(),
|
||||
configuration.getDynamoDbTables().getAccounts().getPhoneNumberIdentifierTableName(),
|
||||
@@ -181,7 +182,7 @@ public class DeleteUserCommand extends EnvironmentCommand<WhisperServerConfigura
|
||||
configuration.getDynamoDbTables().getReportMessage().getTableName(),
|
||||
configuration.getReportMessageConfiguration().getReportTtl());
|
||||
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster,
|
||||
Metrics.globalRegistry, configuration.getReportMessageConfiguration().getCounterTtl());
|
||||
configuration.getReportMessageConfiguration().getCounterTtl());
|
||||
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, pushLatencyManager,
|
||||
reportMessageManager);
|
||||
DeletedAccountsManager deletedAccountsManager = new DeletedAccountsManager(deletedAccounts,
|
||||
|
||||
+4
-3
@@ -16,7 +16,6 @@ import io.dropwizard.Application;
|
||||
import io.dropwizard.cli.EnvironmentCommand;
|
||||
import io.dropwizard.setup.Environment;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Clock;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
@@ -141,7 +140,9 @@ public class SetUserDiscoverabilityCommand extends EnvironmentCommand<WhisperSer
|
||||
VerificationCodeStore pendingAccounts = new VerificationCodeStore(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getPendingAccounts().getTableName());
|
||||
|
||||
Accounts accounts = new Accounts(dynamoDbClient,
|
||||
Accounts accounts = new Accounts(dynamicConfigurationManager,
|
||||
dynamoDbClient,
|
||||
dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getAccounts().getTableName(),
|
||||
configuration.getDynamoDbTables().getAccounts().getPhoneNumberTableName(),
|
||||
configuration.getDynamoDbTables().getAccounts().getPhoneNumberIdentifierTableName(),
|
||||
@@ -182,7 +183,7 @@ public class SetUserDiscoverabilityCommand extends EnvironmentCommand<WhisperSer
|
||||
configuration.getDynamoDbTables().getReportMessage().getTableName(),
|
||||
configuration.getReportMessageConfiguration().getReportTtl());
|
||||
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster,
|
||||
Metrics.globalRegistry, configuration.getReportMessageConfiguration().getCounterTtl());
|
||||
configuration.getReportMessageConfiguration().getCounterTtl());
|
||||
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, pushLatencyManager,
|
||||
reportMessageManager);
|
||||
DeletedAccountsManager deletedAccountsManager = new DeletedAccountsManager(deletedAccounts,
|
||||
|
||||
@@ -7,8 +7,8 @@ package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.signal.zkgroup.ServerPublicParams;
|
||||
import org.signal.zkgroup.ServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.ServerPublicParams;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
|
||||
import io.dropwizard.cli.Command;
|
||||
import io.dropwizard.setup.Bootstrap;
|
||||
|
||||
@@ -33,16 +33,14 @@ message Envelope {
|
||||
|
||||
optional Type type = 1;
|
||||
optional string source = 2;
|
||||
optional string sourceUuid = 11;
|
||||
optional uint32 sourceDevice = 7;
|
||||
optional string relay = 3;
|
||||
optional string source_uuid = 11;
|
||||
optional uint32 source_device = 7;
|
||||
optional uint64 timestamp = 5;
|
||||
optional bytes legacyMessage = 6; // Contains an encrypted DataMessage XXX -- Remove after 10/01/15
|
||||
optional bytes content = 8; // Contains an encrypted Content
|
||||
optional string serverGuid = 9;
|
||||
optional string server_guid = 9;
|
||||
optional uint64 server_timestamp = 10;
|
||||
optional bool ephemeral = 12; // indicates that the message should not be persisted if the recipient is offline
|
||||
optional string destinationUuid = 13;
|
||||
optional string destination_uuid = 13;
|
||||
}
|
||||
|
||||
message ProvisioningUuid {
|
||||
@@ -62,10 +60,10 @@ message ServerCertificate {
|
||||
message SenderCertificate {
|
||||
message Certificate {
|
||||
optional string sender = 1;
|
||||
optional string senderUuid = 6;
|
||||
optional uint32 senderDevice = 2;
|
||||
optional string sender_uuid = 6;
|
||||
optional uint32 sender_device = 2;
|
||||
optional fixed64 expires = 3;
|
||||
optional bytes identityKey = 4;
|
||||
optional bytes identity_key = 4;
|
||||
optional ServerCertificate signer = 5;
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@ import java.security.InvalidKeyException;
|
||||
import java.util.Base64;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.crypto.Curve;
|
||||
import org.signal.libsignal.protocol.ecc.Curve;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
|
||||
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class TurnTokenGeneratorTest {
|
||||
|
||||
@Test
|
||||
public void testAlwaysSelectFirst() throws JsonProcessingException {
|
||||
final String configString = """
|
||||
captcha:
|
||||
scoreFloor: 1.0
|
||||
turn:
|
||||
secret: bloop
|
||||
uriConfigs:
|
||||
- uris:
|
||||
- always1.org
|
||||
- always2.org
|
||||
- uris:
|
||||
- never.org
|
||||
weight: 0
|
||||
""";
|
||||
DynamicConfiguration config = DynamicConfigurationManager
|
||||
.parseConfiguration(configString, DynamicConfiguration.class)
|
||||
.orElseThrow();
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
DynamicConfigurationManager<DynamicConfiguration> mockDynamicConfigManager = mock(
|
||||
DynamicConfigurationManager.class);
|
||||
|
||||
when(mockDynamicConfigManager.getConfiguration()).thenReturn(config);
|
||||
final TurnTokenGenerator turnTokenGenerator = new TurnTokenGenerator(mockDynamicConfigManager);
|
||||
|
||||
final long COUNT = 1000;
|
||||
|
||||
final Map<String, Long> urlCounts = Stream
|
||||
.generate(() -> turnTokenGenerator.generate(""))
|
||||
.limit(COUNT)
|
||||
.flatMap(token -> token.getUrls().stream())
|
||||
.collect(Collectors.groupingBy(i -> i, Collectors.counting()));
|
||||
|
||||
assertThat(urlCounts.get("always1.org")).isEqualTo(COUNT);
|
||||
assertThat(urlCounts.get("always2.org")).isEqualTo(COUNT);
|
||||
assertThat(urlCounts).doesNotContainKey("never.org");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testProbabilisticUrls() throws JsonProcessingException {
|
||||
final String configString = """
|
||||
captcha:
|
||||
scoreFloor: 1.0
|
||||
turn:
|
||||
secret: bloop
|
||||
uriConfigs:
|
||||
- uris:
|
||||
- always.org
|
||||
- sometimes1.org
|
||||
weight: 5
|
||||
- uris:
|
||||
- always.org
|
||||
- sometimes2.org
|
||||
weight: 5
|
||||
""";
|
||||
DynamicConfiguration config = DynamicConfigurationManager
|
||||
.parseConfiguration(configString, DynamicConfiguration.class)
|
||||
.orElseThrow();
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
DynamicConfigurationManager<DynamicConfiguration> mockDynamicConfigManager = mock(
|
||||
DynamicConfigurationManager.class);
|
||||
|
||||
when(mockDynamicConfigManager.getConfiguration()).thenReturn(config);
|
||||
final TurnTokenGenerator turnTokenGenerator = new TurnTokenGenerator(mockDynamicConfigManager);
|
||||
|
||||
final long COUNT = 1000;
|
||||
|
||||
final Map<String, Long> urlCounts = Stream
|
||||
.generate(() -> turnTokenGenerator.generate(""))
|
||||
.limit(COUNT)
|
||||
.flatMap(token -> token.getUrls().stream())
|
||||
.collect(Collectors.groupingBy(i -> i, Collectors.counting()));
|
||||
|
||||
assertThat(urlCounts.get("always.org")).isEqualTo(COUNT);
|
||||
assertThat(urlCounts.get("sometimes1.org")).isGreaterThan(0);
|
||||
assertThat(urlCounts.get("sometimes2.org")).isGreaterThan(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExplicitEnrollment() throws JsonProcessingException {
|
||||
final String configString = """
|
||||
captcha:
|
||||
scoreFloor: 1.0
|
||||
turn:
|
||||
secret: bloop
|
||||
uriConfigs:
|
||||
- uris:
|
||||
- enrolled.org
|
||||
weight: 0
|
||||
enrolledNumbers:
|
||||
- +15555555555
|
||||
- uris:
|
||||
- unenrolled.org
|
||||
weight: 1
|
||||
""";
|
||||
DynamicConfiguration config = DynamicConfigurationManager
|
||||
.parseConfiguration(configString, DynamicConfiguration.class)
|
||||
.orElseThrow();
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
DynamicConfigurationManager<DynamicConfiguration> mockDynamicConfigManager = mock(
|
||||
DynamicConfigurationManager.class);
|
||||
|
||||
when(mockDynamicConfigManager.getConfiguration()).thenReturn(config);
|
||||
|
||||
final TurnTokenGenerator turnTokenGenerator = new TurnTokenGenerator(mockDynamicConfigManager);
|
||||
TurnToken token = turnTokenGenerator.generate("+15555555555");
|
||||
assertThat(token.getUrls().get(0)).isEqualTo("enrolled.org");
|
||||
token = turnTokenGenerator.generate("+15555555556");
|
||||
assertThat(token.getUrls().get(0)).isEqualTo("unenrolled.org");
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+98
-38
@@ -26,10 +26,15 @@ import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
|
||||
class DynamicConfigurationTest {
|
||||
|
||||
private static final String REQUIRED_CONFIG = """
|
||||
captcha:
|
||||
scoreFloor: 1.0
|
||||
""";
|
||||
|
||||
@Test
|
||||
void testParseExperimentConfig() throws JsonProcessingException {
|
||||
{
|
||||
final String emptyConfigYaml = "test: true";
|
||||
final String emptyConfigYaml = REQUIRED_CONFIG.concat("test: true");
|
||||
final DynamicConfiguration emptyConfig =
|
||||
DynamicConfigurationManager.parseConfiguration(emptyConfigYaml, DynamicConfiguration.class).orElseThrow();
|
||||
|
||||
@@ -37,7 +42,7 @@ class DynamicConfigurationTest {
|
||||
}
|
||||
|
||||
{
|
||||
final String experimentConfigYaml = """
|
||||
final String experimentConfigYaml = REQUIRED_CONFIG.concat("""
|
||||
experiments:
|
||||
percentageOnly:
|
||||
enrollmentPercentage: 12
|
||||
@@ -49,7 +54,7 @@ class DynamicConfigurationTest {
|
||||
uuidsOnly:
|
||||
enrolledUuids:
|
||||
- 71618739-114c-4b1f-bb0d-6478a44eb600
|
||||
""";
|
||||
""");
|
||||
|
||||
final DynamicConfiguration config =
|
||||
DynamicConfigurationManager.parseConfiguration(experimentConfigYaml, DynamicConfiguration.class).orElseThrow();
|
||||
@@ -78,7 +83,7 @@ class DynamicConfigurationTest {
|
||||
@Test
|
||||
void testParsePreRegistrationExperiments() throws JsonProcessingException {
|
||||
{
|
||||
final String emptyConfigYaml = "test: true";
|
||||
final String emptyConfigYaml = REQUIRED_CONFIG.concat("test: true");
|
||||
final DynamicConfiguration emptyConfig =
|
||||
DynamicConfigurationManager.parseConfiguration(emptyConfigYaml, DynamicConfiguration.class).orElseThrow();
|
||||
|
||||
@@ -86,7 +91,7 @@ class DynamicConfigurationTest {
|
||||
}
|
||||
|
||||
{
|
||||
final String experimentConfigYaml = """
|
||||
final String experimentConfigYaml = REQUIRED_CONFIG.concat("""
|
||||
preRegistrationExperiments:
|
||||
percentageOnly:
|
||||
enrollmentPercentage: 17
|
||||
@@ -107,7 +112,7 @@ class DynamicConfigurationTest {
|
||||
- +120255551212
|
||||
excludedCountryCodes:
|
||||
- 47
|
||||
""";
|
||||
""");
|
||||
|
||||
final DynamicConfiguration config =
|
||||
DynamicConfigurationManager.parseConfiguration(experimentConfigYaml, DynamicConfiguration.class).orElseThrow();
|
||||
@@ -160,7 +165,7 @@ class DynamicConfigurationTest {
|
||||
@Test
|
||||
void testParseRemoteDeprecationConfig() throws JsonProcessingException {
|
||||
{
|
||||
final String emptyConfigYaml = "test: true";
|
||||
final String emptyConfigYaml = REQUIRED_CONFIG.concat("test: true");
|
||||
final DynamicConfiguration emptyConfig =
|
||||
DynamicConfigurationManager.parseConfiguration(emptyConfigYaml, DynamicConfiguration.class).orElseThrow();
|
||||
|
||||
@@ -168,7 +173,7 @@ class DynamicConfigurationTest {
|
||||
}
|
||||
|
||||
{
|
||||
final String remoteDeprecationConfig = """
|
||||
final String remoteDeprecationConfig = REQUIRED_CONFIG.concat("""
|
||||
remoteDeprecation:
|
||||
minimumVersions:
|
||||
IOS: 1.2.3
|
||||
@@ -178,7 +183,7 @@ class DynamicConfigurationTest {
|
||||
blockedVersions:
|
||||
DESKTOP:
|
||||
- 1.4.0-beta.2
|
||||
""";
|
||||
""");
|
||||
|
||||
final DynamicConfiguration config =
|
||||
DynamicConfigurationManager.parseConfiguration(remoteDeprecationConfig, DynamicConfiguration.class).orElseThrow();
|
||||
@@ -199,7 +204,7 @@ class DynamicConfigurationTest {
|
||||
@Test
|
||||
void testParseFeatureFlags() throws JsonProcessingException {
|
||||
{
|
||||
final String emptyConfigYaml = "test: true";
|
||||
final String emptyConfigYaml = REQUIRED_CONFIG.concat("test: true");
|
||||
final DynamicConfiguration emptyConfig =
|
||||
DynamicConfigurationManager.parseConfiguration(emptyConfigYaml, DynamicConfiguration.class).orElseThrow();
|
||||
|
||||
@@ -207,10 +212,10 @@ class DynamicConfigurationTest {
|
||||
}
|
||||
|
||||
{
|
||||
final String featureFlagYaml = """
|
||||
final String featureFlagYaml = REQUIRED_CONFIG.concat("""
|
||||
featureFlags:
|
||||
- testFlag
|
||||
""";
|
||||
""");
|
||||
|
||||
final DynamicConfiguration emptyConfig =
|
||||
DynamicConfigurationManager.parseConfiguration(featureFlagYaml, DynamicConfiguration.class).orElseThrow();
|
||||
@@ -222,7 +227,7 @@ class DynamicConfigurationTest {
|
||||
@Test
|
||||
void testParseTwilioConfiguration() throws JsonProcessingException {
|
||||
{
|
||||
final String emptyConfigYaml = "test: true";
|
||||
final String emptyConfigYaml = REQUIRED_CONFIG.concat("test: true");
|
||||
final DynamicConfiguration emptyConfig =
|
||||
DynamicConfigurationManager.parseConfiguration(emptyConfigYaml, DynamicConfiguration.class).orElseThrow();
|
||||
|
||||
@@ -230,12 +235,12 @@ class DynamicConfigurationTest {
|
||||
}
|
||||
|
||||
{
|
||||
final String twilioConfigYaml = """
|
||||
final String twilioConfigYaml = REQUIRED_CONFIG.concat("""
|
||||
twilio:
|
||||
numbers:
|
||||
- 2135551212
|
||||
- 2135551313
|
||||
""";
|
||||
""");
|
||||
|
||||
final DynamicTwilioConfiguration config =
|
||||
DynamicConfigurationManager.parseConfiguration(twilioConfigYaml, DynamicConfiguration.class).orElseThrow()
|
||||
@@ -248,7 +253,7 @@ class DynamicConfigurationTest {
|
||||
@Test
|
||||
void testParsePaymentsConfiguration() throws JsonProcessingException {
|
||||
{
|
||||
final String emptyConfigYaml = "test: true";
|
||||
final String emptyConfigYaml = REQUIRED_CONFIG.concat("test: true");
|
||||
final DynamicConfiguration emptyConfig =
|
||||
DynamicConfigurationManager.parseConfiguration(emptyConfigYaml, DynamicConfiguration.class).orElseThrow();
|
||||
|
||||
@@ -256,11 +261,11 @@ class DynamicConfigurationTest {
|
||||
}
|
||||
|
||||
{
|
||||
final String paymentsConfigYaml = """
|
||||
final String paymentsConfigYaml = REQUIRED_CONFIG.concat("""
|
||||
payments:
|
||||
disallowedPrefixes:
|
||||
- +44
|
||||
""";
|
||||
""");
|
||||
|
||||
final DynamicPaymentsConfiguration config =
|
||||
DynamicConfigurationManager.parseConfiguration(paymentsConfigYaml, DynamicConfiguration.class).orElseThrow()
|
||||
@@ -271,34 +276,47 @@ class DynamicConfigurationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testParseSignupCaptchaConfiguration() throws JsonProcessingException {
|
||||
void testParseCaptchaConfiguration() throws JsonProcessingException {
|
||||
{
|
||||
final String emptyConfigYaml = "test: true";
|
||||
final DynamicConfiguration emptyConfig =
|
||||
DynamicConfigurationManager.parseConfiguration(emptyConfigYaml, DynamicConfiguration.class).orElseThrow();
|
||||
|
||||
assertTrue(emptyConfig.getSignupCaptchaConfiguration().getCountryCodes().isEmpty());
|
||||
assertTrue(DynamicConfigurationManager.parseConfiguration(emptyConfigYaml, DynamicConfiguration.class).isEmpty(),
|
||||
"empty config should not validate");
|
||||
}
|
||||
|
||||
{
|
||||
final String signupCaptchaConfig = """
|
||||
signupCaptcha:
|
||||
countryCodes:
|
||||
final String captchaConfig = """
|
||||
captcha:
|
||||
signupCountryCodes:
|
||||
- 1
|
||||
scoreFloor: null
|
||||
""";
|
||||
|
||||
final DynamicSignupCaptchaConfiguration config =
|
||||
DynamicConfigurationManager.parseConfiguration(signupCaptchaConfig, DynamicConfiguration.class).orElseThrow()
|
||||
.getSignupCaptchaConfiguration();
|
||||
assertTrue(DynamicConfigurationManager.parseConfiguration(captchaConfig, DynamicConfiguration.class).isEmpty(),
|
||||
"score floor must not be null");
|
||||
}
|
||||
|
||||
assertEquals(Set.of("1"), config.getCountryCodes());
|
||||
{
|
||||
final String captchaConfig = """
|
||||
captcha:
|
||||
signupCountryCodes:
|
||||
- 1
|
||||
scoreFloor: 0.9
|
||||
""";
|
||||
|
||||
final DynamicCaptchaConfiguration config =
|
||||
DynamicConfigurationManager.parseConfiguration(captchaConfig, DynamicConfiguration.class).orElseThrow()
|
||||
.getCaptchaConfiguration();
|
||||
|
||||
assertEquals(Set.of("1"), config.getSignupCountryCodes());
|
||||
assertEquals(0.9f, config.getScoreFloor().floatValue());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testParseLimits() throws JsonProcessingException {
|
||||
{
|
||||
final String emptyConfigYaml = "test: true";
|
||||
final String emptyConfigYaml = REQUIRED_CONFIG.concat("test: true");
|
||||
final DynamicConfiguration emptyConfig =
|
||||
DynamicConfigurationManager.parseConfiguration(emptyConfigYaml, DynamicConfiguration.class).orElseThrow();
|
||||
|
||||
@@ -307,12 +325,12 @@ class DynamicConfigurationTest {
|
||||
}
|
||||
|
||||
{
|
||||
final String limitsConfig = """
|
||||
final String limitsConfig = REQUIRED_CONFIG.concat("""
|
||||
limits:
|
||||
rateLimitReset:
|
||||
bucketSize: 17
|
||||
leakRatePerMinute: 44
|
||||
""";
|
||||
""");
|
||||
|
||||
final RateLimitConfiguration resetRateLimitConfiguration =
|
||||
DynamicConfigurationManager.parseConfiguration(limitsConfig, DynamicConfiguration.class).orElseThrow()
|
||||
@@ -326,7 +344,7 @@ class DynamicConfigurationTest {
|
||||
@Test
|
||||
void testParseRateLimitReset() throws JsonProcessingException {
|
||||
{
|
||||
final String emptyConfigYaml = "test: true";
|
||||
final String emptyConfigYaml = REQUIRED_CONFIG.concat("test: true");
|
||||
final DynamicConfiguration emptyConfig =
|
||||
DynamicConfigurationManager.parseConfiguration(emptyConfigYaml, DynamicConfiguration.class).orElseThrow();
|
||||
|
||||
@@ -334,13 +352,13 @@ class DynamicConfigurationTest {
|
||||
}
|
||||
|
||||
{
|
||||
final String rateLimitChallengeConfig = """
|
||||
final String rateLimitChallengeConfig = REQUIRED_CONFIG.concat("""
|
||||
rateLimitChallenge:
|
||||
clientSupportedVersions:
|
||||
IOS: 5.1.0
|
||||
ANDROID: 5.2.0
|
||||
DESKTOP: 5.0.0
|
||||
""";
|
||||
""");
|
||||
|
||||
DynamicRateLimitChallengeConfiguration rateLimitChallengeConfiguration =
|
||||
DynamicConfigurationManager.parseConfiguration(rateLimitChallengeConfig, DynamicConfiguration.class).orElseThrow()
|
||||
@@ -357,7 +375,7 @@ class DynamicConfigurationTest {
|
||||
@Test
|
||||
void testParseDirectoryReconciler() throws JsonProcessingException {
|
||||
{
|
||||
final String emptyConfigYaml = "test: true";
|
||||
final String emptyConfigYaml = REQUIRED_CONFIG.concat("test: true");
|
||||
final DynamicConfiguration emptyConfig =
|
||||
DynamicConfigurationManager.parseConfiguration(emptyConfigYaml, DynamicConfiguration.class).orElseThrow();
|
||||
|
||||
@@ -365,10 +383,10 @@ class DynamicConfigurationTest {
|
||||
}
|
||||
|
||||
{
|
||||
final String directoryReconcilerConfig = """
|
||||
final String directoryReconcilerConfig = REQUIRED_CONFIG.concat("""
|
||||
directoryReconciler:
|
||||
enabled: false
|
||||
""";
|
||||
""");
|
||||
|
||||
DynamicDirectoryReconcilerConfiguration directoryReconcilerConfiguration =
|
||||
DynamicConfigurationManager.parseConfiguration(directoryReconcilerConfig, DynamicConfiguration.class).orElseThrow()
|
||||
@@ -377,4 +395,46 @@ class DynamicConfigurationTest {
|
||||
assertThat(directoryReconcilerConfiguration.isEnabled()).isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testParseTurnConfig() throws JsonProcessingException {
|
||||
{
|
||||
final String config = REQUIRED_CONFIG.concat("""
|
||||
turn:
|
||||
secret: bloop
|
||||
uriConfigs:
|
||||
- uris:
|
||||
- turn:test.org
|
||||
weight: -1
|
||||
""");
|
||||
assertThat(DynamicConfigurationManager.parseConfiguration(config, DynamicConfiguration.class)).isEmpty();
|
||||
}
|
||||
{
|
||||
final String config = REQUIRED_CONFIG.concat("""
|
||||
turn:
|
||||
secret: bloop
|
||||
uriConfigs:
|
||||
- uris:
|
||||
- turn:test0.org
|
||||
- turn:test1.org
|
||||
- uris:
|
||||
- turn:test2.org
|
||||
weight: 2
|
||||
enrolledNumbers:
|
||||
- +15555555555
|
||||
""");
|
||||
DynamicTurnConfiguration turnConfiguration = DynamicConfigurationManager
|
||||
.parseConfiguration(config, DynamicConfiguration.class)
|
||||
.orElseThrow()
|
||||
.getTurnConfiguration();
|
||||
assertThat(turnConfiguration.getSecret()).isEqualTo("bloop");
|
||||
assertThat(turnConfiguration.getUriConfigs().get(0).getUris()).hasSize(2);
|
||||
assertThat(turnConfiguration.getUriConfigs().get(1).getUris()).hasSize(1);
|
||||
assertThat(turnConfiguration.getUriConfigs().get(0).getWeight()).isEqualTo(1);
|
||||
assertThat(turnConfiguration.getUriConfigs().get(1).getWeight()).isEqualTo(2);
|
||||
assertThat(turnConfiguration.getUriConfigs().get(1).getEnrolledNumbers()).containsExactly("+15555555555");
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
-66
@@ -1,66 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import io.dropwizard.testing.junit5.ResourceExtension;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.QueryParam;
|
||||
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
@ExtendWith(DropwizardExtensionsSupport.class)
|
||||
class AcceptNumericOnlineFlagRequestFilterTest {
|
||||
|
||||
@Path("/test")
|
||||
public static class TestResource {
|
||||
|
||||
@Path("/convert-boolean")
|
||||
@GET
|
||||
public boolean convertBoolean(@QueryParam("online") final boolean online) {
|
||||
return online;
|
||||
}
|
||||
|
||||
@Path("/no-conversion")
|
||||
@GET
|
||||
public boolean noConversion(@QueryParam("online") final boolean online) {
|
||||
return online;
|
||||
}
|
||||
}
|
||||
|
||||
private static final ResourceExtension RESOURCE_EXTENSION = ResourceExtension.builder()
|
||||
.addProvider(new AcceptNumericOnlineFlagRequestFilter("test/convert-boolean"))
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addResource(new TestResource())
|
||||
.build();
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"/test/convert-boolean, true, true",
|
||||
"/test/convert-boolean, false, false",
|
||||
"/test/convert-boolean, 1, true",
|
||||
"/test/convert-boolean, 0, false",
|
||||
"/test/no-conversion, true, true",
|
||||
"/test/no-conversion, false, false",
|
||||
"/test/no-conversion, 1, false",
|
||||
"/test/no-conversion, 0, false"
|
||||
})
|
||||
void filter(final String path, final String value, final boolean expected) {
|
||||
final boolean response =
|
||||
RESOURCE_EXTENSION.getJerseyTest()
|
||||
.target(path)
|
||||
.queryParam("online", value)
|
||||
.request()
|
||||
.get(boolean.class);
|
||||
|
||||
assertEquals(expected, response);
|
||||
}
|
||||
}
|
||||
+4
-2
@@ -7,6 +7,8 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.reset;
|
||||
@@ -110,7 +112,7 @@ class ChallengeControllerTest {
|
||||
.put(Entity.json(recaptchaChallengeJson));
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
verify(rateLimitChallengeManager).answerRecaptchaChallenge(AuthHelper.VALID_ACCOUNT, "The value of the solved captcha token", "10.0.0.1");
|
||||
verify(rateLimitChallengeManager).answerRecaptchaChallenge(eq(AuthHelper.VALID_ACCOUNT), eq("The value of the solved captcha token"), eq("10.0.0.1"), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -124,7 +126,7 @@ class ChallengeControllerTest {
|
||||
""";
|
||||
|
||||
final Duration retryAfter = Duration.ofMinutes(17);
|
||||
doThrow(new RateLimitExceededException(retryAfter)).when(rateLimitChallengeManager).answerRecaptchaChallenge(any(), any(), any());
|
||||
doThrow(new RateLimitExceededException(retryAfter)).when(rateLimitChallengeManager).answerRecaptchaChallenge(any(), any(), any(), any());
|
||||
|
||||
final Response response = EXTENSION.target("/v1/challenge")
|
||||
.request()
|
||||
|
||||
+19
-21
@@ -28,7 +28,6 @@ import static org.mockito.Mockito.when;
|
||||
import static org.whispersystems.textsecuregcm.tests.util.JsonHelpers.asJson;
|
||||
import static org.whispersystems.textsecuregcm.tests.util.JsonHelpers.jsonFixture;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.vdurmont.semver4j.Semver;
|
||||
import io.dropwizard.auth.PolymorphicAuthValueFactoryProvider;
|
||||
@@ -86,6 +85,7 @@ import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
|
||||
@ExtendWith(DropwizardExtensionsSupport.class)
|
||||
class MessageControllerTest {
|
||||
@@ -115,8 +115,6 @@ class MessageControllerTest {
|
||||
private static final ReportMessageManager reportMessageManager = mock(ReportMessageManager.class);
|
||||
private static final ExecutorService multiRecipientMessageExecutor = mock(ExecutorService.class);
|
||||
|
||||
private static final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
private static final ResourceExtension resources = ResourceExtension.builder()
|
||||
.addProvider(AuthHelper.getAuthFilter())
|
||||
.addProvider(new PolymorphicAuthValueFactoryProvider.Binder<>(
|
||||
@@ -134,22 +132,22 @@ class MessageControllerTest {
|
||||
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, false)));
|
||||
false, false, false, false, false)));
|
||||
}};
|
||||
|
||||
Set<Device> multiDeviceList = new HashSet<>() {{
|
||||
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, false)));
|
||||
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, false)));
|
||||
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, false)));
|
||||
false, false, false, false, false)));
|
||||
}};
|
||||
|
||||
Account singleDeviceAccount = new Account(SINGLE_DEVICE_RECIPIENT, SINGLE_DEVICE_UUID, SINGLE_DEVICE_PNI, singleDeviceList, "1234".getBytes());
|
||||
@@ -191,7 +189,7 @@ class MessageControllerTest {
|
||||
|
||||
try {
|
||||
return Stream.of(
|
||||
Entity.entity(mapper.readValue(jsonFixture("fixtures/current_message_single_device.json"),
|
||||
Entity.entity(SystemMapper.getMapper().readValue(jsonFixture("fixtures/current_message_single_device.json"),
|
||||
IncomingMessageList.class),
|
||||
MediaType.APPLICATION_JSON_TYPE),
|
||||
Entity.entity(messageStream.toByteArray(), MultiDeviceMessageListProvider.MEDIA_TYPE)
|
||||
@@ -242,7 +240,7 @@ class MessageControllerTest {
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.header("User-Agent", userAgentString)
|
||||
.put(Entity.entity(mapper.readValue(jsonFixture("fixtures/current_message_single_device_bad_type.json"), IncomingMessageList.class),
|
||||
.put(Entity.entity(SystemMapper.getMapper().readValue(jsonFixture("fixtures/current_message_single_device_bad_type.json"), IncomingMessageList.class),
|
||||
MediaType.APPLICATION_JSON_TYPE));
|
||||
|
||||
if (expectAcceptMessage) {
|
||||
@@ -292,7 +290,7 @@ class MessageControllerTest {
|
||||
.target(String.format("/v1/messages/%s", SINGLE_DEVICE_UUID))
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.put(Entity.entity(mapper.readValue(jsonFixture("fixtures/current_message_null_message_in_list.json"), IncomingMessageList.class),
|
||||
.put(Entity.entity(SystemMapper.getMapper().readValue(jsonFixture("fixtures/current_message_null_message_in_list.json"), IncomingMessageList.class),
|
||||
MediaType.APPLICATION_JSON_TYPE));
|
||||
|
||||
assertThat("Bad request", response.getStatus(), is(equalTo(422)));
|
||||
@@ -386,7 +384,7 @@ class MessageControllerTest {
|
||||
|
||||
try {
|
||||
return Stream.of(
|
||||
Entity.entity(mapper.readValue(jsonFixture("fixtures/current_message_extra_device.json"),
|
||||
Entity.entity(SystemMapper.getMapper().readValue(jsonFixture("fixtures/current_message_extra_device.json"),
|
||||
IncomingMessageList.class),
|
||||
MediaType.APPLICATION_JSON_TYPE),
|
||||
Entity.entity(messageStream.toByteArray(), MultiDeviceMessageListProvider.MEDIA_TYPE)
|
||||
@@ -430,7 +428,7 @@ class MessageControllerTest {
|
||||
|
||||
try {
|
||||
return Stream.of(
|
||||
Entity.entity(mapper.readValue(jsonFixture("fixtures/current_message_multi_device.json"),
|
||||
Entity.entity(SystemMapper.getMapper().readValue(jsonFixture("fixtures/current_message_multi_device.json"),
|
||||
IncomingMessageList.class),
|
||||
MediaType.APPLICATION_JSON_TYPE),
|
||||
Entity.entity(messageStream.toByteArray(), MultiDeviceMessageListProvider.MEDIA_TYPE)
|
||||
@@ -477,7 +475,7 @@ class MessageControllerTest {
|
||||
|
||||
try {
|
||||
return Stream.of(
|
||||
Entity.entity(mapper.readValue(jsonFixture("fixtures/current_message_registration_id.json"),
|
||||
Entity.entity(SystemMapper.getMapper().readValue(jsonFixture("fixtures/current_message_registration_id.json"),
|
||||
IncomingMessageList.class),
|
||||
MediaType.APPLICATION_JSON_TYPE),
|
||||
Entity.entity(messageStream.toByteArray(), MultiDeviceMessageListProvider.MEDIA_TYPE)
|
||||
@@ -497,8 +495,8 @@ class MessageControllerTest {
|
||||
final UUID sourceUuid = UUID.randomUUID();
|
||||
|
||||
List<OutgoingMessageEntity> messages = new LinkedList<>() {{
|
||||
add(new OutgoingMessageEntity(messageGuidOne, Envelope.Type.CIPHERTEXT_VALUE, null, timestampOne, "+14152222222", sourceUuid, 2, AuthHelper.VALID_UUID, "hi there".getBytes(), null, 0));
|
||||
add(new OutgoingMessageEntity(null, Envelope.Type.SERVER_DELIVERY_RECEIPT_VALUE, null, timestampTwo, "+14152222222", sourceUuid, 2, AuthHelper.VALID_UUID, null, null, 0));
|
||||
add(new OutgoingMessageEntity(messageGuidOne, Envelope.Type.CIPHERTEXT_VALUE, timestampOne, "+14152222222", sourceUuid, 2, AuthHelper.VALID_UUID, "hi there".getBytes(), 0));
|
||||
add(new OutgoingMessageEntity(null, Envelope.Type.SERVER_DELIVERY_RECEIPT_VALUE, timestampTwo, "+14152222222", sourceUuid, 2, AuthHelper.VALID_UUID, null, 0));
|
||||
}};
|
||||
|
||||
OutgoingMessageEntityList messagesList = new OutgoingMessageEntityList(messages, false);
|
||||
@@ -530,8 +528,8 @@ class MessageControllerTest {
|
||||
final long timestampTwo = 313388;
|
||||
|
||||
List<OutgoingMessageEntity> messages = new LinkedList<OutgoingMessageEntity>() {{
|
||||
add(new OutgoingMessageEntity(UUID.randomUUID(), Envelope.Type.CIPHERTEXT_VALUE, null, timestampOne, "+14152222222", UUID.randomUUID(), 2, AuthHelper.VALID_UUID, "hi there".getBytes(), null, 0));
|
||||
add(new OutgoingMessageEntity(UUID.randomUUID(), Envelope.Type.SERVER_DELIVERY_RECEIPT_VALUE, null, timestampTwo, "+14152222222", UUID.randomUUID(), 2, AuthHelper.VALID_UUID, null, null, 0));
|
||||
add(new OutgoingMessageEntity(UUID.randomUUID(), Envelope.Type.CIPHERTEXT_VALUE, timestampOne, "+14152222222", UUID.randomUUID(), 2, AuthHelper.VALID_UUID, "hi there".getBytes(), 0));
|
||||
add(new OutgoingMessageEntity(UUID.randomUUID(), Envelope.Type.SERVER_DELIVERY_RECEIPT_VALUE, timestampTwo, "+14152222222", UUID.randomUUID(), 2, AuthHelper.VALID_UUID, null, 0));
|
||||
}};
|
||||
|
||||
OutgoingMessageEntityList messagesList = new OutgoingMessageEntityList(messages, false);
|
||||
@@ -557,12 +555,12 @@ class MessageControllerTest {
|
||||
UUID uuid1 = UUID.randomUUID();
|
||||
when(messagesManager.delete(AuthHelper.VALID_UUID, 1, uuid1)).thenReturn(Optional.of(new OutgoingMessageEntity(
|
||||
uuid1, Envelope.Type.CIPHERTEXT_VALUE,
|
||||
null, timestamp, "+14152222222", sourceUuid, 1, AuthHelper.VALID_UUID, "hi".getBytes(), null, 0)));
|
||||
timestamp, "+14152222222", sourceUuid, 1, AuthHelper.VALID_UUID, "hi".getBytes(), 0)));
|
||||
|
||||
UUID uuid2 = UUID.randomUUID();
|
||||
when(messagesManager.delete(AuthHelper.VALID_UUID, 1, uuid2)).thenReturn(Optional.of(new OutgoingMessageEntity(
|
||||
uuid2, Envelope.Type.SERVER_DELIVERY_RECEIPT_VALUE,
|
||||
null, System.currentTimeMillis(), "+14152222222", sourceUuid, 1, AuthHelper.VALID_UUID, null, null, 0)));
|
||||
System.currentTimeMillis(), "+14152222222", sourceUuid, 1, AuthHelper.VALID_UUID, null, 0)));
|
||||
|
||||
UUID uuid3 = UUID.randomUUID();
|
||||
when(messagesManager.delete(AuthHelper.VALID_UUID, 1, uuid3)).thenReturn(Optional.empty());
|
||||
@@ -646,7 +644,7 @@ class MessageControllerTest {
|
||||
try {
|
||||
return Stream.of(
|
||||
Entity.entity(new IncomingMessageList(
|
||||
List.of(new IncomingMessage(1, null, 1L, 1, new String(contentBytes), null, null)), false,
|
||||
List.of(new IncomingMessage(1, null, 1L, 1, new String(contentBytes))), false,
|
||||
System.currentTimeMillis()),
|
||||
MediaType.APPLICATION_JSON_TYPE),
|
||||
Entity.entity(messageStream.toByteArray(), MultiDeviceMessageListProvider.MEDIA_TYPE)
|
||||
@@ -677,7 +675,7 @@ class MessageControllerTest {
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.header("User-Agent", "FIXME")
|
||||
.put(Entity.entity(mapper.readValue(jsonFixture(payloadFilename), IncomingMessageList.class),
|
||||
.put(Entity.entity(SystemMapper.getMapper().readValue(jsonFixture(payloadFilename), IncomingMessageList.class),
|
||||
MediaType.APPLICATION_JSON_TYPE));
|
||||
|
||||
if (expectOk) {
|
||||
|
||||
+1
-1
@@ -25,7 +25,7 @@ import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.signal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.DisabledPermittedAuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
|
||||
|
||||
+1
-1
@@ -75,7 +75,7 @@ class RateLimitChallengeManagerTest {
|
||||
when(rateLimiters.getRecaptchaChallengeSuccessLimiter()).thenReturn(mock(RateLimiter.class));
|
||||
when(rateLimiters.getRateLimitResetLimiter()).thenReturn(mock(RateLimiter.class));
|
||||
|
||||
rateLimitChallengeManager.answerRecaptchaChallenge(account, "captcha", "10.0.0.1");
|
||||
rateLimitChallengeManager.answerRecaptchaChallenge(account, "captcha", "10.0.0.1", "Test User-Agent");
|
||||
|
||||
if (successfulChallenge) {
|
||||
verify(rateLimitChallengeListener).handleRateLimitChallengeAnswered(account);
|
||||
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
/*
|
||||
* Copyright 2022 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.recaptcha;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.whispersystems.textsecuregcm.recaptcha.RecaptchaClient.SEPARATOR;
|
||||
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.ws.rs.BadRequestException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
|
||||
class RecaptchaClientTest {
|
||||
|
||||
private static final String PREFIX = RecaptchaClient.V2_PREFIX.substring(0,
|
||||
RecaptchaClient.V2_PREFIX.lastIndexOf(SEPARATOR));
|
||||
private static final String SITE_KEY = "site-key";
|
||||
private static final String TOKEN = "some-token";
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void parseInputToken(final String input, final String expectedToken, final String siteKey,
|
||||
@Nullable final String expectedAction) {
|
||||
|
||||
final String[] parts = RecaptchaClient.parseInputToken(input);
|
||||
|
||||
assertEquals(siteKey, parts[0]);
|
||||
assertEquals(expectedAction, parts[1]);
|
||||
assertEquals(expectedToken, parts[2]);
|
||||
}
|
||||
|
||||
@Test
|
||||
void parseInputTokenBadRequest() {
|
||||
assertThrows(BadRequestException.class, () -> {
|
||||
RecaptchaClient.parseInputToken(TOKEN);
|
||||
});
|
||||
}
|
||||
|
||||
static Stream<Arguments> parseInputToken() {
|
||||
return Stream.of(
|
||||
Arguments.of(
|
||||
String.join(SEPARATOR, SITE_KEY, TOKEN),
|
||||
TOKEN,
|
||||
SITE_KEY,
|
||||
null),
|
||||
Arguments.of(
|
||||
String.join(SEPARATOR, SITE_KEY, "an-action", TOKEN),
|
||||
TOKEN,
|
||||
SITE_KEY,
|
||||
"an-action"),
|
||||
Arguments.of(
|
||||
String.join(SEPARATOR, SITE_KEY, "an-action", TOKEN, "something-else"),
|
||||
TOKEN + SEPARATOR + "something-else",
|
||||
SITE_KEY,
|
||||
"an-action"),
|
||||
Arguments.of(
|
||||
String.join(SEPARATOR, PREFIX, SITE_KEY, TOKEN),
|
||||
TOKEN,
|
||||
SITE_KEY,
|
||||
null),
|
||||
Arguments.of(
|
||||
String.join(SEPARATOR, PREFIX, SITE_KEY, "an-action", TOKEN),
|
||||
TOKEN,
|
||||
SITE_KEY,
|
||||
"an-action"),
|
||||
Arguments.of(
|
||||
String.join(SEPARATOR, PREFIX, SITE_KEY, "an-action", TOKEN, "something-else"),
|
||||
TOKEN + SEPARATOR + "something-else",
|
||||
SITE_KEY,
|
||||
"an-action")
|
||||
);
|
||||
}
|
||||
}
|
||||
-79
@@ -1,79 +0,0 @@
|
||||
/*
|
||||
* Copyright 2022 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.recaptcha;
|
||||
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.whispersystems.textsecuregcm.recaptcha.TransitionalRecaptchaClient.SEPARATOR;
|
||||
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
|
||||
class TransitionalRecaptchaClientTest {
|
||||
|
||||
private TransitionalRecaptchaClient transitionalRecaptchaClient;
|
||||
private EnterpriseRecaptchaClient enterpriseRecaptchaClient;
|
||||
private LegacyRecaptchaClient legacyRecaptchaClient;
|
||||
|
||||
private static final String PREFIX = TransitionalRecaptchaClient.V2_PREFIX.substring(0,
|
||||
TransitionalRecaptchaClient.V2_PREFIX.lastIndexOf(SEPARATOR));
|
||||
private static final String TOKEN = "some-token";
|
||||
private static final String IP_ADDRESS = "127.0.0.1";
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
enterpriseRecaptchaClient = mock(EnterpriseRecaptchaClient.class);
|
||||
legacyRecaptchaClient = mock(LegacyRecaptchaClient.class);
|
||||
transitionalRecaptchaClient = new TransitionalRecaptchaClient(legacyRecaptchaClient, enterpriseRecaptchaClient);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void testVerify(final String inputToken, final boolean expectLegacy, final String expectedToken,
|
||||
final String expectedAction) {
|
||||
|
||||
transitionalRecaptchaClient.verify(inputToken, IP_ADDRESS);
|
||||
|
||||
if (expectLegacy) {
|
||||
verifyNoInteractions(enterpriseRecaptchaClient);
|
||||
verify(legacyRecaptchaClient).verify(expectedToken, IP_ADDRESS);
|
||||
} else {
|
||||
verifyNoInteractions(legacyRecaptchaClient);
|
||||
verify(enterpriseRecaptchaClient).verify(expectedToken, IP_ADDRESS, expectedAction);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static Stream<Arguments> testVerify() {
|
||||
return Stream.of(
|
||||
Arguments.of(
|
||||
TOKEN,
|
||||
true,
|
||||
TOKEN,
|
||||
null),
|
||||
Arguments.of(
|
||||
String.join(SEPARATOR, PREFIX, TOKEN),
|
||||
false,
|
||||
TOKEN,
|
||||
null),
|
||||
Arguments.of(
|
||||
String.join(SEPARATOR, PREFIX, "an-action", TOKEN),
|
||||
false,
|
||||
TOKEN,
|
||||
"an-action"),
|
||||
Arguments.of(
|
||||
String.join(SEPARATOR, PREFIX, "an-action", TOKEN, "something-else"),
|
||||
false,
|
||||
TOKEN + SEPARATOR + "something-else",
|
||||
"an-action")
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
+10
-8
@@ -144,14 +144,6 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
ACCOUNTS_DYNAMO_EXTENSION.getDynamoDbClient().createTable(createPhoneNumberIdentifierTableRequest);
|
||||
}
|
||||
|
||||
final Accounts accounts = new Accounts(
|
||||
ACCOUNTS_DYNAMO_EXTENSION.getDynamoDbClient(),
|
||||
ACCOUNTS_DYNAMO_EXTENSION.getTableName(),
|
||||
NUMBERS_TABLE_NAME,
|
||||
PNI_ASSIGNMENT_TABLE_NAME,
|
||||
USERNAMES_TABLE_NAME,
|
||||
SCAN_PAGE_SIZE);
|
||||
|
||||
{
|
||||
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
|
||||
mock(DynamicConfigurationManager.class);
|
||||
@@ -159,6 +151,16 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
DynamicConfiguration dynamicConfiguration = new DynamicConfiguration();
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
|
||||
final Accounts accounts = new Accounts(
|
||||
dynamicConfigurationManager,
|
||||
ACCOUNTS_DYNAMO_EXTENSION.getDynamoDbClient(),
|
||||
ACCOUNTS_DYNAMO_EXTENSION.getDynamoDbAsyncClient(),
|
||||
ACCOUNTS_DYNAMO_EXTENSION.getTableName(),
|
||||
NUMBERS_TABLE_NAME,
|
||||
PNI_ASSIGNMENT_TABLE_NAME,
|
||||
USERNAMES_TABLE_NAME,
|
||||
SCAN_PAGE_SIZE);
|
||||
|
||||
deletedAccounts = new DeletedAccounts(DELETED_ACCOUNTS_DYNAMO_EXTENSION.getDynamoDbClient(),
|
||||
DELETED_ACCOUNTS_DYNAMO_EXTENSION.getTableName(),
|
||||
NEEDS_RECONCILIATION_INDEX_NAME);
|
||||
|
||||
+10
-3
@@ -39,6 +39,7 @@ import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.stubbing.Answer;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticationCredentials;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.SignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
@@ -118,8 +119,14 @@ class AccountsManagerConcurrentModificationIntegrationTest {
|
||||
dynamoDbExtension.getDynamoDbClient().createTable(createPhoneNumberIdentifierTableRequest);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
|
||||
mock(DynamicConfigurationManager.class);
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(new DynamicConfiguration());
|
||||
|
||||
accounts = new Accounts(
|
||||
dynamicConfigurationManager,
|
||||
dynamoDbExtension.getDynamoDbClient(),
|
||||
dynamoDbExtension.getDynamoDbAsyncClient(),
|
||||
dynamoDbExtension.getTableName(),
|
||||
NUMBERS_TABLE_NAME,
|
||||
PNI_TABLE_NAME,
|
||||
@@ -183,7 +190,7 @@ class AccountsManagerConcurrentModificationIntegrationTest {
|
||||
"testUserAgent-" + random.nextInt(), 0,
|
||||
new Device.DeviceCapabilities(random.nextBoolean(), random.nextBoolean(), random.nextBoolean(),
|
||||
random.nextBoolean(), random.nextBoolean(), random.nextBoolean(), random.nextBoolean(),
|
||||
random.nextBoolean(), random.nextBoolean(), random.nextBoolean())));
|
||||
random.nextBoolean(), random.nextBoolean(), random.nextBoolean(), random.nextBoolean())));
|
||||
});
|
||||
|
||||
uuid = account.getUuid();
|
||||
@@ -233,7 +240,7 @@ class AccountsManagerConcurrentModificationIntegrationTest {
|
||||
return JsonHelpers.fromJson(redisSetArgumentCapture.getValue(), Account.class);
|
||||
}
|
||||
|
||||
private void verifyAccount(final String name, final Account account, final boolean discoverableByPhoneNumber, final String currentProfileVersion, final String identityKey, final byte[] unidentifiedAccessKey, final String pin, final String clientRegistrationLock, final boolean unrestrictedUnidentifiedAcces, final long lastSeen) {
|
||||
private void verifyAccount(final String name, final Account account, final boolean discoverableByPhoneNumber, final String currentProfileVersion, final String identityKey, final byte[] unidentifiedAccessKey, final String pin, final String clientRegistrationLock, final boolean unrestrictedUnidentifiedAccess, final long lastSeen) {
|
||||
|
||||
assertAll(name,
|
||||
() -> assertEquals(discoverableByPhoneNumber, account.isDiscoverableByPhoneNumber()),
|
||||
@@ -241,7 +248,7 @@ class AccountsManagerConcurrentModificationIntegrationTest {
|
||||
() -> assertEquals(identityKey, account.getIdentityKey()),
|
||||
() -> assertArrayEquals(unidentifiedAccessKey, account.getUnidentifiedAccessKey().orElseThrow()),
|
||||
() -> assertTrue(account.getRegistrationLock().verify(clientRegistrationLock)),
|
||||
() -> assertEquals(unrestrictedUnidentifiedAcces, account.isUnrestrictedUnidentifiedAccess())
|
||||
() -> assertEquals(unrestrictedUnidentifiedAccess, account.isUnrestrictedUnidentifiedAccess())
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+25
-7
@@ -65,6 +65,8 @@ class AccountsManagerTest {
|
||||
private ProfilesManager profilesManager;
|
||||
private ReservedUsernames reservedUsernames;
|
||||
|
||||
private Map<String, UUID> phoneNumberIdentifiersByE164;
|
||||
|
||||
private RedisAdvancedClusterCommands<String, String> commands;
|
||||
private AccountsManager accountsManager;
|
||||
|
||||
@@ -112,7 +114,7 @@ class AccountsManagerTest {
|
||||
when(backupClient.deleteBackups(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers = mock(PhoneNumberIdentifiers.class);
|
||||
final Map<String, UUID> phoneNumberIdentifiersByE164 = new HashMap<>();
|
||||
phoneNumberIdentifiersByE164 = new HashMap<>();
|
||||
|
||||
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(anyString())).thenAnswer((Answer<UUID>) invocation -> {
|
||||
final String number = invocation.getArgument(0, String.class);
|
||||
@@ -532,9 +534,13 @@ class AccountsManagerTest {
|
||||
final AccountAttributes attributes = new AccountAttributes(false, 0, null, null, true, null);
|
||||
accountsManager.create(e164, "password", null, attributes, new ArrayList<>());
|
||||
|
||||
verify(accounts).create(
|
||||
argThat(account -> e164.equals(account.getNumber()) && existingUuid.equals(account.getUuid())));
|
||||
assertTrue(phoneNumberIdentifiersByE164.containsKey(e164));
|
||||
|
||||
verify(accounts)
|
||||
.create(argThat(account -> e164.equals(account.getNumber()) && existingUuid.equals(account.getUuid())));
|
||||
|
||||
verify(keys).delete(existingUuid);
|
||||
verify(keys).delete(phoneNumberIdentifiersByE164.get(e164));
|
||||
verify(messagesManager).clear(existingUuid);
|
||||
verify(profilesManager).deleteAll(existingUuid);
|
||||
}
|
||||
@@ -579,7 +585,7 @@ class AccountsManagerTest {
|
||||
@ValueSource(booleans = {true, false})
|
||||
void testCreateWithStorageCapability(final boolean hasStorage) throws InterruptedException {
|
||||
final AccountAttributes attributes = new AccountAttributes(false, 0, null, null, true,
|
||||
new DeviceCapabilities(false, false, false, hasStorage, false, false, false, false, false, false));
|
||||
new DeviceCapabilities(false, false, false, hasStorage, false, false, false, false, false, false, false));
|
||||
|
||||
final Account account = accountsManager.create("+18005550123", "password", null, attributes, new ArrayList<>());
|
||||
|
||||
@@ -646,13 +652,18 @@ class AccountsManagerTest {
|
||||
final String originalNumber = "+14152222222";
|
||||
final String targetNumber = "+14153333333";
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
final UUID originalPni = UUID.randomUUID();
|
||||
|
||||
Account account = new Account(originalNumber, uuid, UUID.randomUUID(), new HashSet<>(), new byte[16]);
|
||||
Account account = new Account(originalNumber, uuid, originalPni, new HashSet<>(), new byte[16]);
|
||||
account = accountsManager.changeNumber(account, targetNumber);
|
||||
|
||||
assertEquals(targetNumber, account.getNumber());
|
||||
|
||||
assertTrue(phoneNumberIdentifiersByE164.containsKey(targetNumber));
|
||||
|
||||
verify(directoryQueue).changePhoneNumber(argThat(a -> a.getUuid().equals(uuid)), eq(originalNumber), eq(targetNumber));
|
||||
verify(keys).delete(originalPni);
|
||||
verify(keys).delete(phoneNumberIdentifiersByE164.get(targetNumber));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -665,6 +676,7 @@ class AccountsManagerTest {
|
||||
assertEquals(number, account.getNumber());
|
||||
verify(deletedAccountsManager, never()).lockAndPut(anyString(), anyString(), any());
|
||||
verify(directoryQueue, never()).changePhoneNumber(any(), any(), any());
|
||||
verify(keys, never()).delete(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -676,17 +688,23 @@ class AccountsManagerTest {
|
||||
final String targetNumber = "+14153333333";
|
||||
final UUID existingAccountUuid = UUID.randomUUID();
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
final UUID originalPni = UUID.randomUUID();
|
||||
final UUID targetPni = UUID.randomUUID();
|
||||
|
||||
final Account existingAccount = new Account(targetNumber, existingAccountUuid, UUID.randomUUID(), new HashSet<>(), new byte[16]);
|
||||
final Account existingAccount = new Account(targetNumber, existingAccountUuid, targetPni, new HashSet<>(), new byte[16]);
|
||||
when(accounts.getByE164(targetNumber)).thenReturn(Optional.of(existingAccount));
|
||||
|
||||
Account account = new Account(originalNumber, uuid, UUID.randomUUID(), new HashSet<>(), new byte[16]);
|
||||
Account account = new Account(originalNumber, uuid, originalPni, new HashSet<>(), new byte[16]);
|
||||
account = accountsManager.changeNumber(account, targetNumber);
|
||||
|
||||
assertEquals(targetNumber, account.getNumber());
|
||||
|
||||
assertTrue(phoneNumberIdentifiersByE164.containsKey(targetNumber));
|
||||
|
||||
verify(directoryQueue).changePhoneNumber(argThat(a -> a.getUuid().equals(uuid)), eq(originalNumber), eq(targetNumber));
|
||||
verify(directoryQueue).deleteAccount(existingAccount);
|
||||
verify(keys).delete(originalPni);
|
||||
verify(keys).delete(targetPni);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -28,17 +28,26 @@ import java.util.Optional;
|
||||
import java.util.Random;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import org.jdbi.v3.core.transaction.TransactionException;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Disabled;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.SignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
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;
|
||||
@@ -74,6 +83,7 @@ class AccountsTest {
|
||||
.build())
|
||||
.build();
|
||||
|
||||
private DynamicConfigurationManager<DynamicConfiguration> mockDynamicConfigManager;
|
||||
private Accounts accounts;
|
||||
|
||||
@BeforeEach
|
||||
@@ -123,8 +133,16 @@ class AccountsTest {
|
||||
|
||||
dynamoDbExtension.getDynamoDbClient().createTable(createUsernamesTableRequest);
|
||||
|
||||
@SuppressWarnings("unchecked") DynamicConfigurationManager<DynamicConfiguration> m = mock(DynamicConfigurationManager.class);
|
||||
mockDynamicConfigManager = m;
|
||||
|
||||
when(mockDynamicConfigManager.getConfiguration())
|
||||
.thenReturn(new DynamicConfiguration());
|
||||
|
||||
this.accounts = new Accounts(
|
||||
mockDynamicConfigManager,
|
||||
dynamoDbExtension.getDynamoDbClient(),
|
||||
dynamoDbExtension.getDynamoDbAsyncClient(),
|
||||
dynamoDbExtension.getTableName(),
|
||||
NUMBER_CONSTRAINT_TABLE_NAME,
|
||||
PNI_CONSTRAINT_TABLE_NAME,
|
||||
@@ -363,15 +381,20 @@ class AccountsTest {
|
||||
verifyStoredState("+14151112222", account.getUuid(), account.getPhoneNumberIdentifier(), account, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdateWithMockTransactionConflictException() {
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void testUpdateWithMockTransactionConflictException(boolean wrapException) {
|
||||
|
||||
final DynamoDbClient dynamoDbClient = mock(DynamoDbClient.class);
|
||||
accounts = new Accounts(dynamoDbClient,
|
||||
dynamoDbExtension.getTableName(), NUMBER_CONSTRAINT_TABLE_NAME, PNI_CONSTRAINT_TABLE_NAME, USERNAME_CONSTRAINT_TABLE_NAME, SCAN_PAGE_SIZE);
|
||||
final DynamoDbAsyncClient dynamoDbAsyncClient = mock(DynamoDbAsyncClient.class);
|
||||
accounts = new Accounts(mockDynamicConfigManager, mock(DynamoDbClient.class),
|
||||
dynamoDbAsyncClient, dynamoDbExtension.getTableName(),
|
||||
NUMBER_CONSTRAINT_TABLE_NAME, PNI_CONSTRAINT_TABLE_NAME, USERNAME_CONSTRAINT_TABLE_NAME, SCAN_PAGE_SIZE);
|
||||
|
||||
when(dynamoDbClient.updateItem(any(UpdateItemRequest.class)))
|
||||
.thenThrow(TransactionConflictException.class);
|
||||
Exception e = TransactionConflictException.builder().build();
|
||||
e = wrapException ? new CompletionException(e) : e;
|
||||
|
||||
when(dynamoDbAsyncClient.updateItem(any(UpdateItemRequest.class)))
|
||||
.thenReturn(CompletableFuture.failedFuture(e));
|
||||
|
||||
Account account = generateAccount("+14151112222", UUID.randomUUID(), UUID.randomUUID());
|
||||
|
||||
@@ -498,14 +521,15 @@ class AccountsTest {
|
||||
configuration.setFailureRateThreshold(50);
|
||||
|
||||
final DynamoDbClient client = mock(DynamoDbClient.class);
|
||||
final DynamoDbAsyncClient asyncClient = mock(DynamoDbAsyncClient.class);
|
||||
|
||||
when(client.transactWriteItems(any(TransactWriteItemsRequest.class)))
|
||||
.thenThrow(RuntimeException.class);
|
||||
|
||||
when(client.updateItem(any(UpdateItemRequest.class)))
|
||||
.thenThrow(RuntimeException.class);
|
||||
when(asyncClient.updateItem(any(UpdateItemRequest.class)))
|
||||
.thenReturn(CompletableFuture.failedFuture(new RuntimeException()));
|
||||
|
||||
Accounts accounts = new Accounts(client, ACCOUNTS_TABLE_NAME, NUMBER_CONSTRAINT_TABLE_NAME,
|
||||
Accounts accounts = new Accounts(mockDynamicConfigManager, client, asyncClient, ACCOUNTS_TABLE_NAME, NUMBER_CONSTRAINT_TABLE_NAME,
|
||||
PNI_CONSTRAINT_TABLE_NAME, USERNAME_CONSTRAINT_TABLE_NAME, SCAN_PAGE_SIZE);
|
||||
Account account = generateAccount("+14151112222", UUID.randomUUID(), UUID.randomUUID());
|
||||
|
||||
@@ -769,64 +793,162 @@ class AccountsTest {
|
||||
assertThat(account.getUsername()).hasValueSatisfying(u -> assertThat(u).isEqualTo(username));
|
||||
}
|
||||
|
||||
// TODO Remove when PNI repair pass is complete
|
||||
@Test
|
||||
void testRepairMissingPni() throws JsonProcessingException {
|
||||
final String number = "+18005551234";
|
||||
void testAddUakMissingInJson() {
|
||||
// If there's no uak in the json, we shouldn't add an attribute on crawl
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
final UUID phoneNumberIdentifier = UUID.randomUUID();
|
||||
|
||||
{
|
||||
final Account account = generateAccount(number, accountIdentifier, phoneNumberIdentifier);
|
||||
accounts.create(account);
|
||||
final Account account = generateAccount("+18005551234", accountIdentifier, UUID.randomUUID());
|
||||
account.setUnidentifiedAccessKey(null);
|
||||
accounts.create(account);
|
||||
|
||||
// Artificially inject data with a null PNI in the JSON blob into the backing table
|
||||
account.setNumber(number, null);
|
||||
// there should be no top level uak
|
||||
Map<String, AttributeValue> item = dynamoDbExtension.getDynamoDbClient()
|
||||
.getItem(GetItemRequest.builder()
|
||||
.tableName(ACCOUNTS_TABLE_NAME)
|
||||
.key(Map.of(Accounts.KEY_ACCOUNT_UUID, AttributeValues.fromUUID(accountIdentifier)))
|
||||
.consistentRead(true)
|
||||
.build()).item();
|
||||
assertThat(item).doesNotContainKey(Accounts.ATTR_UAK);
|
||||
|
||||
// crawling should return 1 account
|
||||
final AccountCrawlChunk allFromStart = accounts.getAllFromStart(1);
|
||||
assertThat(allFromStart.getAccounts()).hasSize(1);
|
||||
assertThat(allFromStart.getAccounts().get(0).getUuid()).isEqualTo(accountIdentifier);
|
||||
|
||||
// there should still be no top level uak
|
||||
item = dynamoDbExtension.getDynamoDbClient()
|
||||
.getItem(GetItemRequest.builder()
|
||||
.tableName(ACCOUNTS_TABLE_NAME)
|
||||
.key(Map.of(Accounts.KEY_ACCOUNT_UUID, AttributeValues.fromUUID(accountIdentifier)))
|
||||
.consistentRead(true)
|
||||
.build()).item();
|
||||
assertThat(item).doesNotContainKey(Accounts.ATTR_UAK);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUakMismatch() {
|
||||
// If there's a UAK mismatch, we should correct it
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
|
||||
final Account account = generateAccount("+18005551234", accountIdentifier, UUID.randomUUID());
|
||||
accounts.create(account);
|
||||
|
||||
// set the uak to garbage in the attributes
|
||||
dynamoDbExtension.getDynamoDbClient().updateItem(UpdateItemRequest.builder()
|
||||
.tableName(ACCOUNTS_TABLE_NAME)
|
||||
.key(Map.of(Accounts.KEY_ACCOUNT_UUID, AttributeValues.fromUUID(accountIdentifier)))
|
||||
.expressionAttributeNames(Map.of("#uak", Accounts.ATTR_UAK))
|
||||
.expressionAttributeValues(Map.of(":uak", AttributeValues.fromByteArray("bad-uak".getBytes())))
|
||||
.updateExpression("SET #uak = :uak").build());
|
||||
|
||||
// crawling should return 1 account and fix the uak mismatch
|
||||
final AccountCrawlChunk allFromStart = accounts.getAllFromStart(1);
|
||||
assertThat(allFromStart.getAccounts()).hasSize(1);
|
||||
assertThat(allFromStart.getAccounts().get(0).getUuid()).isEqualTo(accountIdentifier);
|
||||
assertThat(allFromStart.getAccounts().get(0).getUnidentifiedAccessKey().get()).isEqualTo(account.getUnidentifiedAccessKey().get());
|
||||
|
||||
// the top level uak should be the original
|
||||
final Map<String, AttributeValue> item = dynamoDbExtension.getDynamoDbClient()
|
||||
.getItem(GetItemRequest.builder()
|
||||
.tableName(ACCOUNTS_TABLE_NAME)
|
||||
.key(Map.of(Accounts.KEY_ACCOUNT_UUID, AttributeValues.fromUUID(accountIdentifier)))
|
||||
.consistentRead(true)
|
||||
.build()).item();
|
||||
assertThat(item).containsEntry(
|
||||
Accounts.ATTR_UAK,
|
||||
AttributeValues.fromByteArray(account.getUnidentifiedAccessKey().get()));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void testAddMissingUakAttribute(boolean normalizeDisabled) throws JsonProcessingException {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
|
||||
if (normalizeDisabled) {
|
||||
final DynamicConfiguration config = DynamicConfigurationManager.parseConfiguration("""
|
||||
captcha:
|
||||
scoreFloor: 1.0
|
||||
uakMigrationConfiguration:
|
||||
enabled: false
|
||||
""", DynamicConfiguration.class).orElseThrow();
|
||||
when(mockDynamicConfigManager.getConfiguration()).thenReturn(config);
|
||||
}
|
||||
|
||||
final Account account = generateAccount("+18005551234", accountIdentifier, UUID.randomUUID());
|
||||
accounts.create(account);
|
||||
|
||||
// remove the top level uak (simulates old format)
|
||||
dynamoDbExtension.getDynamoDbClient().updateItem(UpdateItemRequest.builder()
|
||||
.tableName(ACCOUNTS_TABLE_NAME)
|
||||
.key(Map.of(Accounts.KEY_ACCOUNT_UUID, AttributeValues.fromUUID(accountIdentifier)))
|
||||
.expressionAttributeNames(Map.of("#uak", Accounts.ATTR_UAK))
|
||||
.updateExpression("REMOVE #uak").build());
|
||||
|
||||
// crawling should return 1 account, and fix the discrepancy between
|
||||
// the json blob and the top level attributes if normalization is enabled
|
||||
final AccountCrawlChunk allFromStart = accounts.getAllFromStart(1);
|
||||
assertThat(allFromStart.getAccounts()).hasSize(1);
|
||||
assertThat(allFromStart.getAccounts().get(0).getUuid()).isEqualTo(accountIdentifier);
|
||||
|
||||
// check whether normalization happened
|
||||
final Map<String, AttributeValue> item = dynamoDbExtension.getDynamoDbClient()
|
||||
.getItem(GetItemRequest.builder()
|
||||
.tableName(ACCOUNTS_TABLE_NAME)
|
||||
.key(Map.of(Accounts.KEY_ACCOUNT_UUID, AttributeValues.fromUUID(accountIdentifier)))
|
||||
.consistentRead(true)
|
||||
.build()).item();
|
||||
if (normalizeDisabled) {
|
||||
assertThat(item).doesNotContainKey(Accounts.ATTR_UAK);
|
||||
} else {
|
||||
assertThat(item).containsEntry(Accounts.ATTR_UAK,
|
||||
AttributeValues.fromByteArray(account.getUnidentifiedAccessKey().get()));
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(ints = {24, 25, 26, 101})
|
||||
void testAddMissingUakAttributeBatched(int n) {
|
||||
// generate N + 5 accounts
|
||||
List<Account> allAccounts = IntStream.range(0, n + 5)
|
||||
.mapToObj(i -> generateAccount(String.format("+1800555%04d", i), UUID.randomUUID(), UUID.randomUUID()))
|
||||
.collect(Collectors.toList());
|
||||
allAccounts.forEach(accounts::create);
|
||||
|
||||
// delete the UAK on n of them
|
||||
Collections.shuffle(allAccounts);
|
||||
allAccounts.stream().limit(n).forEach(account ->
|
||||
dynamoDbExtension.getDynamoDbClient().updateItem(UpdateItemRequest.builder()
|
||||
.tableName(ACCOUNTS_TABLE_NAME)
|
||||
.key(Map.of(Accounts.KEY_ACCOUNT_UUID, AttributeValues.fromUUID(accountIdentifier)))
|
||||
.updateExpression("SET #data = :data")
|
||||
.expressionAttributeNames(Map.of("#data", Accounts.ATTR_ACCOUNT_DATA))
|
||||
.expressionAttributeValues(
|
||||
Map.of(":data", AttributeValues.fromByteArray(SystemMapper.getMapper().writeValueAsBytes(account))))
|
||||
.build());
|
||||
}
|
||||
.key(Map.of(Accounts.KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getUuid())))
|
||||
.expressionAttributeNames(Map.of("#uak", Accounts.ATTR_UAK))
|
||||
.updateExpression("REMOVE #uak")
|
||||
.build()));
|
||||
|
||||
{
|
||||
final GetItemResponse response = dynamoDbExtension.getDynamoDbClient().getItem(GetItemRequest.builder()
|
||||
.tableName(ACCOUNTS_TABLE_NAME)
|
||||
.key(Map.of(Accounts.KEY_ACCOUNT_UUID, AttributeValues.fromUUID(accountIdentifier)))
|
||||
.consistentRead(true)
|
||||
.build());
|
||||
|
||||
final String accountJson = new String(
|
||||
AttributeValues.getByteArray(response.item(), Accounts.ATTR_ACCOUNT_DATA, null), StandardCharsets.UTF_8);
|
||||
|
||||
final Account accountFromJson = SystemMapper.getMapper().readValue(accountJson, Account.class);
|
||||
assertThat(accountFromJson.getPhoneNumberIdentifier()).isNull();
|
||||
}
|
||||
|
||||
{
|
||||
// Loading the account should auto-repair the missing PNI
|
||||
final Account account = accounts.getByAccountIdentifier(accountIdentifier).orElseThrow();
|
||||
assertThat(account.getPhoneNumberIdentifier()).isEqualTo(phoneNumberIdentifier);
|
||||
assertThat(account.isStale()).isFalse();
|
||||
}
|
||||
|
||||
{
|
||||
final GetItemResponse response = dynamoDbExtension.getDynamoDbClient().getItem(GetItemRequest.builder()
|
||||
.tableName(ACCOUNTS_TABLE_NAME)
|
||||
.key(Map.of(Accounts.KEY_ACCOUNT_UUID, AttributeValues.fromUUID(accountIdentifier)))
|
||||
.consistentRead(true)
|
||||
.build());
|
||||
|
||||
final String accountJson = new String(
|
||||
AttributeValues.getByteArray(response.item(), Accounts.ATTR_ACCOUNT_DATA, null), StandardCharsets.UTF_8);
|
||||
|
||||
final Account accountFromJson = SystemMapper.getMapper().readValue(accountJson, Account.class);
|
||||
assertThat(accountFromJson.getPhoneNumberIdentifier()).isEqualTo(phoneNumberIdentifier);
|
||||
// crawling should fix the discrepancy between
|
||||
// the json blob and the top level attributes
|
||||
AccountCrawlChunk chunk = accounts.getAllFromStart(7);
|
||||
long verifiedCount = 0;
|
||||
while (true) {
|
||||
for (Account account : chunk.getAccounts()) {
|
||||
// check that the attribute now exists at top level
|
||||
final Map<String, AttributeValue> item = dynamoDbExtension.getDynamoDbClient()
|
||||
.getItem(GetItemRequest.builder()
|
||||
.tableName(ACCOUNTS_TABLE_NAME)
|
||||
.key(Map.of(Accounts.KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getUuid())))
|
||||
.consistentRead(true)
|
||||
.build()).item();
|
||||
assertThat(item).containsEntry(Accounts.ATTR_UAK,
|
||||
AttributeValues.fromByteArray(account.getUnidentifiedAccessKey().get()));
|
||||
verifiedCount++;
|
||||
}
|
||||
if (chunk.getLastUuid().isPresent()) {
|
||||
chunk = accounts.getAllFrom(chunk.getLastUuid().get(), 7);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assertThat(verifiedCount).isEqualTo(n + 5);
|
||||
}
|
||||
|
||||
private Device generateDevice(long id) {
|
||||
@@ -840,7 +962,8 @@ class AccountsTest {
|
||||
"testUserAgent-" + random.nextInt(), 0,
|
||||
new Device.DeviceCapabilities(random.nextBoolean(), random.nextBoolean(), random.nextBoolean(),
|
||||
random.nextBoolean(), random.nextBoolean(), random.nextBoolean(),
|
||||
random.nextBoolean(), random.nextBoolean(), random.nextBoolean(), random.nextBoolean()));
|
||||
random.nextBoolean(), random.nextBoolean(), random.nextBoolean(), random.nextBoolean(),
|
||||
random.nextBoolean()));
|
||||
}
|
||||
|
||||
private Account generateAccount(String number, UUID uuid, final UUID pni) {
|
||||
@@ -917,7 +1040,10 @@ class AccountsTest {
|
||||
assertThat(AttributeValues.getBool(get.item(), Accounts.ATTR_CANONICALLY_DISCOVERABLE,
|
||||
!canonicallyDiscoverable)).isEqualTo(canonicallyDiscoverable);
|
||||
|
||||
Account result = accounts.fromItem(get.item());
|
||||
assertThat(AttributeValues.getByteArray(get.item(), Accounts.ATTR_UAK, null))
|
||||
.isEqualTo(expecting.getUnidentifiedAccessKey().orElse(null));
|
||||
|
||||
Account result = Accounts.fromItem(get.item());
|
||||
verifyStoredState(number, uuid, pni, result, expecting);
|
||||
} else {
|
||||
throw new AssertionError("No data");
|
||||
|
||||
@@ -72,7 +72,7 @@ class DeviceTest {
|
||||
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, 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);
|
||||
|
||||
|
||||
+35
-18
@@ -1,12 +1,13 @@
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.time.Duration;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import software.amazon.awssdk.core.SdkBytes;
|
||||
import software.amazon.awssdk.services.appconfigdata.AppConfigDataClient;
|
||||
@@ -14,10 +15,15 @@ import software.amazon.awssdk.services.appconfigdata.model.GetLatestConfiguratio
|
||||
import software.amazon.awssdk.services.appconfigdata.model.GetLatestConfigurationResponse;
|
||||
import software.amazon.awssdk.services.appconfigdata.model.StartConfigurationSessionRequest;
|
||||
import software.amazon.awssdk.services.appconfigdata.model.StartConfigurationSessionResponse;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
class DynamicConfigurationManagerTest {
|
||||
|
||||
private static final SdkBytes VALID_CONFIG = SdkBytes.fromUtf8String("""
|
||||
test: true
|
||||
captcha:
|
||||
scoreFloor: 1.0
|
||||
""");
|
||||
|
||||
private DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
private AppConfigDataClient appConfig;
|
||||
private StartConfigurationSessionRequest startConfigurationSession;
|
||||
@@ -35,7 +41,7 @@ class DynamicConfigurationManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetInitalConfig() {
|
||||
void testGetInitialConfig() {
|
||||
when(appConfig.startConfigurationSession(startConfigurationSession))
|
||||
.thenReturn(StartConfigurationSessionResponse.builder()
|
||||
.initialConfigurationToken("initial")
|
||||
@@ -45,7 +51,7 @@ class DynamicConfigurationManagerTest {
|
||||
when(appConfig.getLatestConfiguration(GetLatestConfigurationRequest.builder()
|
||||
.configurationToken("initial").build()))
|
||||
.thenReturn(GetLatestConfigurationResponse.builder()
|
||||
.configuration(SdkBytes.fromUtf8String("test: true"))
|
||||
.configuration(VALID_CONFIG)
|
||||
.nextPollConfigurationToken("next").build());
|
||||
|
||||
// subsequent config calls will return empty (no update)
|
||||
@@ -55,8 +61,10 @@ class DynamicConfigurationManagerTest {
|
||||
.configuration(SdkBytes.fromUtf8String(""))
|
||||
.nextPollConfigurationToken("next").build());
|
||||
|
||||
dynamicConfigurationManager.start();
|
||||
assertThat(dynamicConfigurationManager.getConfiguration()).isNotNull();
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(5), () -> {
|
||||
dynamicConfigurationManager.start();
|
||||
assertThat(dynamicConfigurationManager.getConfiguration()).isNotNull();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -77,7 +85,7 @@ class DynamicConfigurationManagerTest {
|
||||
when(appConfig.getLatestConfiguration(GetLatestConfigurationRequest.builder().
|
||||
configurationToken("goodconfig").build()))
|
||||
.thenReturn(GetLatestConfigurationResponse.builder()
|
||||
.configuration(SdkBytes.fromUtf8String("test: true"))
|
||||
.configuration(VALID_CONFIG)
|
||||
.nextPollConfigurationToken("next").build());
|
||||
|
||||
// all subsequent config calls will return an empty config (no update)
|
||||
@@ -86,13 +94,15 @@ class DynamicConfigurationManagerTest {
|
||||
.thenReturn(GetLatestConfigurationResponse.builder()
|
||||
.configuration(SdkBytes.fromUtf8String(""))
|
||||
.nextPollConfigurationToken("next").build());
|
||||
dynamicConfigurationManager.start();
|
||||
assertThat(dynamicConfigurationManager.getConfiguration()).isNotNull();
|
||||
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(5), () -> {
|
||||
dynamicConfigurationManager.start();
|
||||
assertThat(dynamicConfigurationManager.getConfiguration()).isNotNull();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(value=5, unit= TimeUnit.SECONDS)
|
||||
void testGetConfigMultiple() throws InterruptedException {
|
||||
void testGetConfigMultiple() {
|
||||
when(appConfig.startConfigurationSession(startConfigurationSession))
|
||||
.thenReturn(StartConfigurationSessionResponse.builder()
|
||||
.initialConfigurationToken("0")
|
||||
@@ -102,7 +112,7 @@ class DynamicConfigurationManagerTest {
|
||||
when(appConfig.getLatestConfiguration(GetLatestConfigurationRequest.builder().
|
||||
configurationToken("0").build()))
|
||||
.thenReturn(GetLatestConfigurationResponse.builder()
|
||||
.configuration(SdkBytes.fromUtf8String("test: true"))
|
||||
.configuration(VALID_CONFIG)
|
||||
.nextPollConfigurationToken("1").build());
|
||||
|
||||
// config update with a real config
|
||||
@@ -112,6 +122,8 @@ class DynamicConfigurationManagerTest {
|
||||
.configuration(SdkBytes.fromUtf8String("""
|
||||
featureFlags:
|
||||
- testFlag
|
||||
captcha:
|
||||
scoreFloor: 1.0
|
||||
"""))
|
||||
.nextPollConfigurationToken("2").build());
|
||||
|
||||
@@ -122,11 +134,16 @@ class DynamicConfigurationManagerTest {
|
||||
.configuration(SdkBytes.fromUtf8String(""))
|
||||
.nextPollConfigurationToken("2").build());
|
||||
|
||||
// we should eventually get the updated config (or the test will timeout)
|
||||
dynamicConfigurationManager.start();
|
||||
while (dynamicConfigurationManager.getConfiguration().getActiveFeatureFlags().isEmpty()) {
|
||||
Thread.sleep(100);
|
||||
}
|
||||
assertThat(dynamicConfigurationManager.getConfiguration().getActiveFeatureFlags()).containsExactly("testFlag");
|
||||
// the internal waiting done by dynamic configuration manager catches the InterruptedException used
|
||||
// by JUnit’s @Timeout, so we use assertTimeoutPreemptively
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(5), () -> {
|
||||
// we should eventually get the updated config (or the test will timeout)
|
||||
dynamicConfigurationManager.start();
|
||||
while (dynamicConfigurationManager.getConfiguration().getActiveFeatureFlags().isEmpty()) {
|
||||
Thread.sleep(100);
|
||||
}
|
||||
assertThat(dynamicConfigurationManager.getConfiguration().getActiveFeatureFlags()).containsExactly("testFlag");
|
||||
});
|
||||
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -18,7 +18,7 @@ import org.assertj.core.api.Condition;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.signal.zkgroup.receipts.ReceiptCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;
|
||||
|
||||
@@ -56,7 +56,7 @@ class IssuedReceiptsManagerTest {
|
||||
@Test
|
||||
void testRecordIssuance() {
|
||||
Instant now = Instant.ofEpochSecond(NOW_EPOCH_SECONDS);
|
||||
byte[] request1 = new byte[ReceiptCredentialRequest.SIZE];
|
||||
byte[] request1 = new byte[20];
|
||||
SECURE_RANDOM.nextBytes(request1);
|
||||
when(receiptCredentialRequest.serialize()).thenReturn(request1);
|
||||
CompletableFuture<Void> future = issuedReceiptsManager.recordIssuance("item-1", receiptCredentialRequest, now);
|
||||
@@ -67,7 +67,7 @@ class IssuedReceiptsManagerTest {
|
||||
assertThat(future).succeedsWithin(Duration.ofSeconds(3));
|
||||
|
||||
// same item with new request should fail
|
||||
byte[] request2 = new byte[ReceiptCredentialRequest.SIZE];
|
||||
byte[] request2 = new byte[20];
|
||||
SECURE_RANDOM.nextBytes(request2);
|
||||
when(receiptCredentialRequest.serialize()).thenReturn(request2);
|
||||
future = issuedReceiptsManager.recordIssuance("item-1", receiptCredentialRequest, now);
|
||||
|
||||
+5
-13
@@ -23,8 +23,6 @@ import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
class ReportMessageManagerTest {
|
||||
|
||||
private ReportMessageDynamoDb reportMessageDynamoDb;
|
||||
private MeterRegistry meterRegistry;
|
||||
|
||||
private ReportMessageManager reportMessageManager;
|
||||
|
||||
@RegisterExtension
|
||||
@@ -33,10 +31,9 @@ class ReportMessageManagerTest {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
reportMessageDynamoDb = mock(ReportMessageDynamoDb.class);
|
||||
meterRegistry = new SimpleMeterRegistry();
|
||||
|
||||
reportMessageManager = new ReportMessageManager(reportMessageDynamoDb,
|
||||
RATE_LIMIT_CLUSTER_EXTENSION.getRedisCluster(), meterRegistry, Duration.ofDays(1));
|
||||
RATE_LIMIT_CLUSTER_EXTENSION.getRedisCluster(), Duration.ofDays(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -65,24 +62,19 @@ class ReportMessageManagerTest {
|
||||
final UUID messageGuid = UUID.randomUUID();
|
||||
final UUID reporterUuid = UUID.randomUUID();
|
||||
|
||||
final ReportedMessageListener listener = mock(ReportedMessageListener.class);
|
||||
reportMessageManager.addListener(listener);
|
||||
|
||||
when(reportMessageDynamoDb.remove(any())).thenReturn(false);
|
||||
reportMessageManager.report(sourceNumber, messageGuid, reporterUuid);
|
||||
|
||||
assertEquals(0, getCounterTotal(ReportMessageManager.REPORT_COUNTER_NAME));
|
||||
assertEquals(0, reportMessageManager.getRecentReportCount(sourceNumber));
|
||||
|
||||
when(reportMessageDynamoDb.remove(any())).thenReturn(true);
|
||||
reportMessageManager.report(sourceNumber, messageGuid, reporterUuid);
|
||||
|
||||
assertEquals(1, getCounterTotal(ReportMessageManager.REPORT_COUNTER_NAME));
|
||||
assertEquals(1, reportMessageManager.getRecentReportCount(sourceNumber));
|
||||
}
|
||||
|
||||
private double getCounterTotal(final String counterName) {
|
||||
return meterRegistry.find(counterName).counters().stream()
|
||||
.map(Counter::count)
|
||||
.reduce(Double::sum)
|
||||
.orElse(0.0);
|
||||
verify(listener).handleMessageReported(sourceNumber, messageGuid, reporterUuid);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+1
-1
@@ -94,7 +94,7 @@ class OptionalAccessTest {
|
||||
|
||||
try {
|
||||
OptionalAccess.verify(Optional.empty(), Optional.empty(), Optional.of(account));
|
||||
throw new AssertionError("shold fai");
|
||||
throw new AssertionError("should fail");
|
||||
} catch (WebApplicationException e) {
|
||||
assertEquals(e.getResponse().getStatus(), 401);
|
||||
}
|
||||
|
||||
+6
-7
@@ -52,7 +52,6 @@ import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.stubbing.Answer;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticationCredentials;
|
||||
@@ -61,8 +60,8 @@ import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.StoredRegistrationLock;
|
||||
import org.whispersystems.textsecuregcm.auth.StoredVerificationCode;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicCaptchaConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicSignupCaptchaConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.AccountController;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
@@ -263,9 +262,9 @@ class AccountControllerTest {
|
||||
when(dynamicConfigurationManager.getConfiguration())
|
||||
.thenReturn(dynamicConfiguration);
|
||||
|
||||
DynamicSignupCaptchaConfiguration signupCaptchaConfig = new DynamicSignupCaptchaConfiguration();
|
||||
DynamicCaptchaConfiguration signupCaptchaConfig = new DynamicCaptchaConfiguration();
|
||||
|
||||
when(dynamicConfiguration.getSignupCaptchaConfiguration()).thenReturn(signupCaptchaConfig);
|
||||
when(dynamicConfiguration.getCaptchaConfiguration()).thenReturn(signupCaptchaConfig);
|
||||
}
|
||||
when(abusiveHostRules.getAbusiveHostRulesFor(eq(ABUSIVE_HOST))).thenReturn(Collections.singletonList(new AbusiveHostRule(ABUSIVE_HOST, true, Collections.emptyList())));
|
||||
when(abusiveHostRules.getAbusiveHostRulesFor(eq(RESTRICTED_HOST))).thenReturn(Collections.singletonList(new AbusiveHostRule(RESTRICTED_HOST, false, Collections.singletonList("+123"))));
|
||||
@@ -1741,9 +1740,9 @@ class AccountControllerTest {
|
||||
when(dynamicConfigurationManager.getConfiguration())
|
||||
.thenReturn(dynamicConfiguration);
|
||||
|
||||
DynamicSignupCaptchaConfiguration signupCaptchaConfig = new DynamicSignupCaptchaConfiguration();
|
||||
signupCaptchaConfig.setCountryCodes(countryCodes);
|
||||
when(dynamicConfiguration.getSignupCaptchaConfiguration())
|
||||
DynamicCaptchaConfiguration signupCaptchaConfig = new DynamicCaptchaConfiguration();
|
||||
signupCaptchaConfig.setSignupCountryCodes(countryCodes);
|
||||
when(dynamicConfiguration.getCaptchaConfiguration())
|
||||
.thenReturn(signupCaptchaConfig);
|
||||
|
||||
Response response =
|
||||
|
||||
Loaded 100 of 120 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user