Compare commits

..
68 Commits
Author SHA1 Message Date
Ravi Khadiwala c70d7535b9 Make TURN configuration dynamic
Also enables conditionally including more TURN servers for gradual
rollouts
2022-03-23 14:38:02 -05:00
Ravi Khadiwala 8541360bf3 Update to the latest version of the abusive message filter 2022-03-23 14:32:55 -05:00
Jon Chambers 2a832d36d7 Remove AcceptNumericOnlineFlagRequestFilter 2022-03-23 14:31:01 -05:00
gram-signal 1578c89475 Only allow primary device to update identity key. 2022-03-22 14:39:04 -06:00
Chris Eager 5c13e54149 Various dependency updates
- protobuf-java to 3.19.4
- libphonenumber to 8.12.45
- logstash-logback-encoder to 7.0.1
- mockito to 4.3.1
2022-03-22 09:58:08 -04:00
Jon Chambers 8e74cf6633 Update to the latest version of the abusive message filter 2022-03-22 09:56:27 -04:00
Jon Chambers bab6b36e4d Count reported messages by destination country code in addition to source country code 2022-03-22 09:56:27 -04:00
Jon Chambers f75e616397 Introduce a listener pattern for reported messages 2022-03-22 09:56:27 -04:00
Jon Chambers 941a9c3b39 Update to the latest version of the abusive message filter 2022-03-17 16:08:20 -04:00
Jon Chambers 7ba0f604e6 Tag the push challenge request counter by country 2022-03-17 16:07:48 -04:00
Chris Eager cf8a4cc939 Decrease receipt sender executor thread pool 2022-03-17 13:07:03 -07:00
Jon Chambers ee78daeeef Update to the latest version of the abusive message filter 2022-03-16 15:30:43 -04:00
Jon Chambers 2f6b0b1a55 Tag push challenge attempt metrics by country code 2022-03-16 15:00:04 -04:00
Jon Chambers c048074c31 Tag captcha attempt metrics with UA platform 2022-03-16 15:00:04 -04:00
Ravi Khadiwala 5ca89709e3 Update to the latest version of the abusive message filter 2022-03-14 14:15:51 -05:00
Ravi Khadiwala 5a88ff0811 Use the async dynamo client to batch uak updates 2022-03-14 14:02:16 -05:00
Chris Eager de68c251f8 Instrument the receipt sender executor 2022-03-11 17:20:52 -08:00
Chris Eager 7c9ae3561d Send delivery receipts asynchronously 2022-03-11 16:34:22 -08:00
Chris Eager b608ece57e Remove supportsAnnouncementGroups metric 2022-03-11 16:18:00 -08:00
Chris Eager 8dfffebaf1 Remove unnecessary check for destination UUID 2022-03-11 16:17:54 -08:00
Jon Chambers 109a3bb2b9 Update to Pushy 0.15.1 2022-03-10 11:08:53 -05:00
Chris Eager fef37f739b Remove unused classes and methods 2022-03-10 11:08:38 -05:00
Jon Chambers 7a5615182a Update to the latest version of the abusive message filter 2022-03-10 11:06:04 -05:00
Ravi Khadiwala 02a7003ffe Update to the latest version of the abusive message filter 2022-03-09 14:14:47 -06:00
Ravi Khadiwala 1571f14815 Add a feature flag to disable account normalization 2022-03-09 14:03:21 -06:00
Ravi Khadiwala 9cb098ad8a Add a top-level uak to existing items
Items wirtten before we started storing the uak at
the top level only store the uak in the
account blob. The will be updated on account
crawl
2022-03-09 14:03:21 -06:00
Jon Chambers 6283f5952d Update to the latest version of the abusive message filter 2022-03-08 10:03:38 -05:00
Jon Chambers 9b9edbae0e Drop DeadLetterHandler (which is functionally unused) 2022-03-08 10:03:06 -05:00
Chris Eager 491155d1cf Remove @Consumes from GET/DELETE in /v1/subscriptions 2022-03-04 15:36:02 -08:00
Chris Eager 54207254f1 Remove unused configuration 2022-03-04 11:44:17 -08:00
Chris Eager 1395dcc0be Make the enterprise client canonical 2022-03-04 11:44:17 -08:00
Chris Eager 2a68d9095d Remove transitional and legacy client 2022-03-04 11:44:17 -08:00
Chris Eager a984b3640e Further refine score distribution summary 2022-03-04 11:44:17 -08:00
Jon Chambers f9c1e411aa Remove netty-tcnative as a dependency 2022-03-04 10:45:18 -05:00
Jon Chambers f6cbc32ee7 Align "link device" and "fetch pre-keys" rate limits 2022-03-04 10:45:06 -05:00
Chris Eager 602614acf6 Refine assessment metrics 2022-03-03 16:09:49 -08:00
Chris Eager 3854b7d472 Remove @Consumes from GET /v1/config 2022-03-03 16:08:55 -08:00
Jon Chambers 5e25481088 Fix a trivial typo in a constant's name 2022-03-03 10:59:19 -05:00
Jon Chambers fe86e15d80 Remove PNI repair code 2022-03-03 10:25:11 -05:00
Jon Chambers 179b4a69eb Clear one-time pre-keys when PNIs are assigned 2022-03-03 10:24:54 -05:00
Chris Eager eee6307789 Move score floor to dynamic configuration, add distribution summary 2022-03-02 15:18:33 -08:00
Chris Eager 9fc5002619 Add stories capability 2022-03-02 15:16:21 -08:00
Ravi Khadiwala faa6ae284a Add uak as a top level attribute 2022-03-02 10:41:09 -06:00
Jon Chambers 8b4355b21d Add a "challenge issued" counter tagged by country and platform 2022-03-02 10:40:47 -06:00
Jon Chambers e8835da740 Tag captcha success rate counter by country 2022-03-02 10:40:47 -06:00
Dimitris ApostolouandChris Eager 75854e104e Fix typo
Co-authored-by: Chris Eager <79161849+eager-signal@users.noreply.github.com>
2022-03-01 14:14:52 -08:00
Dimitris Apostolou 93d06e3f4d Fix typos 2022-03-01 14:14:52 -08:00
Chris Eager c560b9229c Update to the latest version of the abusive message filter 2022-03-01 10:43:12 -08:00
Chris Eager 935e268dec Parameterize sitekey 2022-03-01 10:40:42 -08:00
Jon Chambers 3a1c716c73 Remove an unused rate limiter 2022-02-25 13:50:17 -08:00
Chris Eager f3457502a6 Support different v2 captcha actions 2022-02-25 13:49:47 -08:00
Ravi Khadiwala 7ded802df4 Update to the latest version of the abusive message filter 2022-02-24 17:30:02 -06:00
Ravi Khadiwala d3cd1d1b15 Use GetLatestConfiguration in config manager
Use StartConfigurationSession/GetLatestConfiguration instead of
GetConfiguration since the latter has been deprecated
2022-02-23 15:36:33 -06:00
Ravi Khadiwala f5a75c6319 Simplify RateLimitExceeded with no retry-duration
- Avoid passing negative durations in error cases
- Drop unused message
- Return a duration for a bad forwarded-for
2022-02-23 15:25:24 -06:00
Ravi Khadiwala ae3a5c5f5e Return a Retry-After on rate-limited responses
Previously, only endpoints throwing a RetryLaterException would include
a Retry-After header in the 413 response. Now, by default, all
RateLimitExceededExceptions will be marshalled into a 413 with a
Retry-After included if possible.
2022-02-23 15:25:24 -06:00
Jon Chambers 43792e2426 Update to the latest version of the abusive message filter 2022-02-22 11:03:41 -05:00
Jon Chambers 551d639951 Update Postgres driver to 42.3.3 2022-02-18 10:41:29 -05:00
Jordan Rose c367a71223 APNS: include a collapse-id for non-VOIP notifications
This has two benefits:

- The APNS server should only send an iOS client a single push
  notification for any missed messages while the device is offline
  (server-side coalescing). Note that the client can still turn that
  into multiple "user notifications" as it pulls from its queue.

- If multiple notifications get delivered but iOS is unable to process
  them (say, because the phone just restarted and hasn't been unlocked
  yet), the user should only get one "You may have received messages"
  notification (client-side coalescing).
2022-02-18 10:41:10 -05:00
Chris Eager d259ef0348 Update rate limit exceeded counter 2022-02-17 13:23:48 -08:00
Chris Eager 288cbf4a80 Clean up null-ability of incoming message entity fields 2022-02-17 13:23:48 -08:00
Chris Eager ba5e5a780f Throw an exception instead of using Optional<Resposne> 2022-02-17 13:23:48 -08:00
Chris Eager 73fa3c3fe4 Add test for content length validation 2022-02-17 13:23:48 -08:00
Chris Eager 579eb85175 Reject invalid envelope types 2022-02-17 13:23:48 -08:00
Chris Eager b2b20072ae Add MicrometerRegistryManager 2022-02-17 13:18:30 -08:00
Chris Eager a2c4d3fe95 Use a strong reference to the application shutdown gauge 2022-02-17 13:18:30 -08:00
Ravi Khadiwala 31e2be2e4d Fixup invalid accept-language counter
- Fix name
- Add platform/version tags to the counter
2022-02-10 11:57:25 -06:00
Ravi Khadiwala 9f5d97e1c6 Silence noisy warnings for invalid Accept-Language 2022-02-10 11:57:25 -06:00
Ravi Khadiwala baaae6cd9f Add @NotNull to controller args where appropriate
Notably, `@Valid` doesn't imply `@NotNull`
2022-02-10 11:57:04 -06:00
99 changed files with 2193 additions and 1398 deletions

No files matched your search

@@ -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()
+6 -13
View File
@@ -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>9.4-1201-jdbc41</postgresql.version>
<protobuf.version>3.17.1</protobuf.version>
<pushy.version>0.15.0</pushy.version>
<postgresql.version>42.3.3</postgresql.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>
-16
View File
@@ -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
+4 -6
View File
@@ -277,6 +277,10 @@
<groupId>software.amazon.awssdk</groupId>
<artifactId>appconfig</artifactId>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>appconfigdata</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-core</artifactId>
@@ -322,12 +326,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>
@@ -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;
@@ -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;
@@ -123,7 +123,6 @@ import org.whispersystems.textsecuregcm.mappers.InvalidWebsocketAddressException
import org.whispersystems.textsecuregcm.mappers.NonNormalizedPhoneNumberExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.RateLimitChallengeExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.RetryLaterExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.ServerRejectedExceptionMapper;
import org.whispersystems.textsecuregcm.metrics.ApplicationShutdownMonitor;
import org.whispersystems.textsecuregcm.metrics.BufferPoolGauges;
@@ -134,6 +133,7 @@ import org.whispersystems.textsecuregcm.metrics.GarbageCollectionGauges;
import org.whispersystems.textsecuregcm.metrics.MaxFileDescriptorGauge;
import org.whispersystems.textsecuregcm.metrics.MetricsApplicationEventListener;
import org.whispersystems.textsecuregcm.metrics.MetricsRequestEventListener;
import org.whispersystems.textsecuregcm.metrics.MicrometerRegistryManager;
import org.whispersystems.textsecuregcm.metrics.NetworkReceivedGauge;
import org.whispersystems.textsecuregcm.metrics.NetworkSentGauge;
import org.whispersystems.textsecuregcm.metrics.OperatingSystemMemoryGauge;
@@ -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;
@@ -296,6 +294,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
Metrics.addRegistry(datadogMeterRegistry);
}
environment.lifecycle().manage(new MicrometerRegistryManager(Metrics.globalRegistry));
environment.getObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
environment.getObjectMapper().setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
environment.getObjectMapper().setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
@@ -340,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(),
@@ -384,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();
@@ -400,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());
@@ -434,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());
@@ -442,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());
@@ -463,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);
@@ -470,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);
@@ -580,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));
@@ -608,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));
@@ -618,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));
@@ -727,7 +731,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
environment.healthChecks().register("cacheCluster", new RedisClusterHealthCheck(cacheCluster));
environment.lifecycle().manage(new ApplicationShutdownMonitor());
environment.lifecycle().manage(new ApplicationShutdownMonitor(Metrics.globalRegistry));
environment.metrics().register(name(CpuUsageGauge.class, "cpu"), new CpuUsageGauge(3, TimeUnit.SECONDS));
environment.metrics().register(name(FreeMemoryGauge.class, "free_memory"), new FreeMemoryGauge());
@@ -755,7 +759,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new RateLimitExceededExceptionMapper(),
new InvalidWebsocketAddressExceptionMapper(),
new DeviceLimitExceededExceptionMapper(),
new RetryLaterExceptionMapper(),
new ServerRejectedExceptionMapper(),
new ImpossiblePhoneNumberExceptionMapper(),
new NonNormalizedPhoneNumberExceptionMapper()
@@ -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);
}
}
@@ -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;
}
}
@@ -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());
}
}
@@ -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;
}
}
@@ -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);
@@ -164,28 +164,4 @@ public class RateLimitsConfiguration {
return leakRatePerMinute;
}
}
public static class CardinalityRateLimitConfiguration {
@JsonProperty
private int maxCardinality;
@JsonProperty
private Duration ttl;
public CardinalityRateLimitConfiguration() {
}
public CardinalityRateLimitConfiguration(int maxCardinality, Duration ttl) {
this.maxCardinality = maxCardinality;
this.ttl = ttl;
}
public int getMaxCardinality() {
return maxCardinality;
}
public Duration getTtl() {
return ttl;
}
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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);
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -1,9 +1,7 @@
package org.whispersystems.textsecuregcm.configuration.dynamic;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.whispersystems.textsecuregcm.configuration.RateLimitsConfiguration.CardinalityRateLimitConfiguration;
import org.whispersystems.textsecuregcm.configuration.RateLimitsConfiguration.RateLimitConfiguration;
import java.time.Duration;
public class DynamicRateLimitsConfiguration {
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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());
}
}
}
}
@@ -29,6 +29,7 @@ import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
@@ -45,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;
@@ -59,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;
@@ -111,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";
@@ -212,7 +215,7 @@ public class AccountController {
@QueryParam("client") Optional<String> client,
@QueryParam("captcha") Optional<String> captcha,
@QueryParam("challenge") Optional<String> pushChallenge)
throws RateLimitExceededException, RetryLaterException, ImpossiblePhoneNumberException, NonNormalizedPhoneNumberException {
throws RateLimitExceededException, ImpossiblePhoneNumberException, NonNormalizedPhoneNumberException {
Util.requireNormalizedNumber(number);
@@ -225,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");
@@ -233,24 +242,16 @@ public class AccountController {
return Response.status(402).build();
}
try {
switch (transport) {
case "sms":
rateLimiters.getSmsDestinationLimiter().validate(number);
break;
case "voice":
rateLimiters.getVoiceDestinationLimiter().validate(number);
rateLimiters.getVoiceDestinationDailyLimiter().validate(number);
break;
default:
throw new WebApplicationException(Response.status(422).build());
}
} catch (RateLimitExceededException e) {
if (!e.getRetryDuration().isNegative()) {
throw new RetryLaterException(e);
} else {
throw e;
}
switch (transport) {
case "sms":
rateLimiters.getSmsDestinationLimiter().validate(number);
break;
case "voice":
rateLimiters.getVoiceDestinationLimiter().validate(number);
rateLimiters.getVoiceDestinationDailyLimiter().validate(number);
break;
default:
throw new WebApplicationException(Response.status(422).build());
}
VerificationCode verificationCode = generateVerificationCode(number);
@@ -319,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)));
@@ -339,7 +340,7 @@ public class AccountController {
@HeaderParam("X-Signal-Agent") String signalAgent,
@HeaderParam("User-Agent") String userAgent,
@QueryParam("transfer") Optional<Boolean> availableForTransfer,
@Valid AccountAttributes accountAttributes)
@NotNull @Valid AccountAttributes accountAttributes)
throws RateLimitExceededException, InterruptedException {
String number = authorizationHeader.getUsername();
@@ -399,7 +400,7 @@ public class AccountController {
@PUT
@Path("/number")
@Produces(MediaType.APPLICATION_JSON)
public AccountIdentityResponse changeNumber(@Auth final AuthenticatedAccount authenticatedAccount, @Valid final ChangePhoneNumberRequest request)
public AccountIdentityResponse changeNumber(@Auth final AuthenticatedAccount authenticatedAccount, @NotNull @Valid final ChangePhoneNumberRequest request)
throws RateLimitExceededException, InterruptedException, ImpossiblePhoneNumberException, NonNormalizedPhoneNumberException {
final Account updatedAccount;
@@ -448,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
@@ -457,7 +458,7 @@ public class AccountController {
@Consumes(MediaType.APPLICATION_JSON)
@ChangesDeviceEnabledState
public void setGcmRegistrationId(@Auth DisabledPermittedAuthenticatedAccount disabledPermittedAuth,
@Valid GcmRegistrationId registrationId) {
@NotNull @Valid GcmRegistrationId registrationId) {
Account account = disabledPermittedAuth.getAccount();
Device device = disabledPermittedAuth.getAuthenticatedDevice();
@@ -495,7 +496,7 @@ public class AccountController {
@Consumes(MediaType.APPLICATION_JSON)
@ChangesDeviceEnabledState
public void setApnRegistrationId(@Auth DisabledPermittedAuthenticatedAccount disabledPermittedAuth,
@Valid ApnRegistrationId registrationId) {
@NotNull @Valid ApnRegistrationId registrationId) {
Account account = disabledPermittedAuth.getAccount();
Device device = disabledPermittedAuth.getAuthenticatedDevice();
@@ -530,7 +531,7 @@ public class AccountController {
@PUT
@Produces(MediaType.APPLICATION_JSON)
@Path("/registration_lock")
public void setRegistrationLock(@Auth AuthenticatedAccount auth, @Valid RegistrationLock accountLock) {
public void setRegistrationLock(@Auth AuthenticatedAccount auth, @NotNull @Valid RegistrationLock accountLock) {
AuthenticationCredentials credentials = new AuthenticationCredentials(accountLock.getRegistrationLock());
accounts.update(auth.getAccount(),
@@ -547,7 +548,7 @@ public class AccountController {
@Timed
@PUT
@Path("/name/")
public void setName(@Auth DisabledPermittedAuthenticatedAccount disabledPermittedAuth, @Valid DeviceName deviceName) {
public void setName(@Auth DisabledPermittedAuthenticatedAccount disabledPermittedAuth, @NotNull @Valid DeviceName deviceName) {
Account account = disabledPermittedAuth.getAccount();
Device device = disabledPermittedAuth.getAuthenticatedDevice();
accounts.updateDevice(account, device.getId(), d -> d.setName(deviceName.getDeviceName()));
@@ -567,7 +568,7 @@ public class AccountController {
@ChangesDeviceEnabledState
public void setAccountAttributes(@Auth DisabledPermittedAuthenticatedAccount disabledPermittedAuth,
@HeaderParam("X-Signal-Agent") String userAgent,
@Valid AccountAttributes attributes) {
@NotNull @Valid AccountAttributes attributes) {
Account account = disabledPermittedAuth.getAccount();
long deviceId = disabledPermittedAuth.getAuthenticatedDevice().getId();
@@ -642,7 +643,13 @@ public class AccountController {
}
final String mostRecentProxy = ForwardedIpUtil.getMostRecentProxy(forwardedFor)
.orElseThrow(() -> new RateLimitExceededException(Duration.ofHours(1)));
.orElseThrow(() -> {
// Missing/malformed Forwarded-For, so we cannot check for a rate-limit.
// This shouldn't happen, so conservatively assume we're over the rate-limit
// and indicate that the client should retry
logger.error("Missing/bad Forwarded-For, cannot check account {}", uuid.toString());
return new RateLimitExceededException(Duration.ofHours(1));
});
rateLimiters.getCheckAccountExistenceLimiter().validate(mostRecentProxy);
@@ -683,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);
@@ -691,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();
}
@@ -701,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));
@@ -762,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);
}
@@ -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))));
}
@@ -51,7 +51,7 @@ public class ChallengeController {
public Response handleChallengeResponse(@Auth final AuthenticatedAccount auth,
@Valid final AnswerChallengeRequest answerRequest,
@HeaderParam("X-Forwarded-For") final String forwardedFor,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws RetryLaterException {
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws RateLimitExceededException {
Tags tags = Tags.of(UserAgentTagUtil.getPlatformTag(userAgent));
@@ -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();
@@ -76,8 +76,6 @@ public class ChallengeController {
} else {
tags = tags.and(CHALLENGE_TYPE_TAG, "unrecognized");
}
} catch (final RateLimitExceededException e) {
throw new RetryLaterException(e);
} finally {
Metrics.counter(CHALLENGE_RESPONSE_COUNTER_NAME, tags).increment();
}
@@ -224,7 +224,7 @@ public class DeviceController {
@Timed
@PUT
@Path("/capabilities")
public void setCapabiltities(@Auth AuthenticatedAccount auth, @Valid DeviceCapabilities capabilities) {
public void setCapabiltities(@Auth AuthenticatedAccount auth, @NotNull @Valid DeviceCapabilities capabilities) {
assert (auth.getAuthenticatedDevice() != null);
final long deviceId = auth.getAuthenticatedDevice().getId();
accounts.updateDevice(auth.getAccount(), deviceId, d -> d.setCapabilities(capabilities));
@@ -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();
@@ -35,6 +35,7 @@ import java.util.concurrent.ForkJoinPool.ManagedBlocker;
import java.util.function.Function;
import javax.annotation.Nonnull;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
@@ -124,7 +125,7 @@ public class DonationController {
@Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN})
public CompletionStage<Response> redeemReceipt(
@Auth final AuthenticatedAccount auth,
@Valid final RedeemReceiptRequest request) {
@NotNull @Valid final RedeemReceiptRequest request) {
return CompletableFuture.supplyAsync(() -> {
ReceiptCredentialPresentation receiptCredentialPresentation;
try {
@@ -192,7 +193,7 @@ public class DonationController {
@Path("/authorize-apple-pay")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public CompletableFuture<Response> getApplePayAuthorization(@Auth AuthenticatedAccount auth, @Valid ApplePayAuthorizationRequest request) {
public CompletableFuture<Response> getApplePayAuthorization(@Auth AuthenticatedAccount auth, @NotNull @Valid ApplePayAuthorizationRequest request) {
if (!supportedCurrencies.contains(request.getCurrency())) {
return CompletableFuture.completedFuture(Response.status(422).build());
}
@@ -18,7 +18,9 @@ import java.util.Map;
import java.util.Optional;
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;
@@ -85,22 +87,25 @@ public class KeysController {
@Consumes(MediaType.APPLICATION_JSON)
@ChangesDeviceEnabledState
public void setKeys(@Auth final DisabledPermittedAuthenticatedAccount disabledPermittedAuth,
@Valid final PreKeyState preKeys,
@NotNull @Valid final PreKeyState preKeys,
@QueryParam("identity") final Optional<String> identityType) {
Account account = disabledPermittedAuth.getAccount();
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 -> {
@@ -38,6 +38,7 @@ import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nonnull;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
@@ -125,17 +126,20 @@ public class MessageController {
private static final String CONTENT_SIZE_DISTRIBUTION_NAME = name(MessageController.class, "messageContentSize");
private static final String OUTGOING_MESSAGE_LIST_SIZE_BYTES_DISTRIBUTION_NAME = name(MessageController.class, "outgoingMessageListSizeBytes");
private static final String RATE_LIMITED_MESSAGE_COUNTER_NAME = name(MessageController.class, "rateLimitedMessage");
private static final String REJECT_INVALID_ENVELOPE_TYPE = name(MessageController.class, "rejectInvalidEnvelopeType");
private static final String EPHEMERAL_TAG_NAME = "ephemeral";
private static final String SENDER_TYPE_TAG_NAME = "senderType";
private static final String SENDER_COUNTRY_TAG_NAME = "senderCountry";
private static final String RATE_LIMIT_REASON_TAG_NAME = "rateLimitReason";
private static final String ENVELOPE_TYPE_TAG_NAME = "envelopeType";
private static final String SENDER_TYPE_IDENTIFIED = "identified";
private static final String SENDER_TYPE_UNIDENTIFIED = "unidentified";
private static final String SENDER_TYPE_SELF = "self";
private static final long MAX_MESSAGE_SIZE = DataSize.kibibytes(256).toBytes();
@VisibleForTesting
static final long MAX_MESSAGE_SIZE = DataSize.kibibytes(256).toBytes();
public MessageController(
RateLimiters rateLimiters,
@@ -167,7 +171,7 @@ public class MessageController {
@HeaderParam("User-Agent") String userAgent,
@HeaderParam("X-Forwarded-For") String forwardedFor,
@PathParam("destination") UUID destinationUuid,
@Valid IncomingMessageList messages)
@NotNull @Valid IncomingMessageList messages)
throws RateLimitExceededException, RateLimitChallengeException {
if (source.isEmpty() && accessKey.isEmpty()) {
@@ -187,6 +191,7 @@ public class MessageController {
}
for (final IncomingMessage message : messages.getMessages()) {
int contentLength = 0;
if (!Util.isEmpty(message.getContent())) {
@@ -197,12 +202,8 @@ public class MessageController {
contentLength += message.getBody().length();
}
Metrics.summary(CONTENT_SIZE_DISTRIBUTION_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent))).record(contentLength);
if (contentLength > MAX_MESSAGE_SIZE) {
Metrics.counter(REJECT_OVERSIZE_MESSAGE_COUNTER, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent))).increment();
return Response.status(Response.Status.REQUEST_ENTITY_TOO_LARGE).build();
}
validateContentLength(contentLength, userAgent);
validateEnvelopeType(message.getType(), userAgent);
}
try {
@@ -221,7 +222,7 @@ public class MessageController {
assert (destination.isPresent());
if (source.isPresent() && !isSyncMessage) {
checkRateLimit(source.get(), destination.get());
checkRateLimit(source.get(), destination.get(), userAgent);
}
validateCompleteDeviceList(destination.get(), messages.getMessages(),
@@ -274,8 +275,8 @@ public class MessageController {
@PathParam("destination") UUID destinationUuid,
@QueryParam("online") boolean online,
@QueryParam("ts") long timestamp,
@Valid IncomingDeviceMessage[] messages)
throws RateLimitExceededException, RateLimitChallengeException {
@NotNull @Valid IncomingDeviceMessage[] messages)
throws RateLimitExceededException {
if (source.isEmpty() && accessKey.isEmpty()) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
@@ -294,14 +295,8 @@ public class MessageController {
}
for (final IncomingDeviceMessage message : messages) {
int contentLength = message.getContent().length;
Metrics.summary(CONTENT_SIZE_DISTRIBUTION_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent))).record(contentLength);
if (contentLength > MAX_MESSAGE_SIZE) {
Metrics.counter(REJECT_OVERSIZE_MESSAGE_COUNTER, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent))).increment();
return Response.status(Response.Status.REQUEST_ENTITY_TOO_LARGE).build();
}
validateContentLength(message.getContent().length, userAgent);
validateEnvelopeType(message.getType(), userAgent);
}
try {
@@ -320,7 +315,7 @@ public class MessageController {
assert (destination.isPresent());
if (source.isPresent() && !isSyncMessage) {
checkRateLimit(source.get(), destination.get());
checkRateLimit(source.get(), destination.get(), userAgent);
}
final List<IncomingDeviceMessage> messagesAsList = Arrays.asList(messages);
@@ -340,7 +335,7 @@ public class MessageController {
if (destinationDevice.isPresent()) {
Metrics.counter(SENT_MESSAGE_COUNTER_NAME, tags).increment();
sendMessage(source, destination.get(), destinationDevice.get(), destinationUuid, timestamp, online, message, userAgent);
sendMessage(source, destination.get(), destinationDevice.get(), destinationUuid, timestamp, online, message);
}
}
@@ -374,7 +369,7 @@ public class MessageController {
@HeaderParam("X-Forwarded-For") String forwardedFor,
@QueryParam("online") boolean online,
@QueryParam("ts") long timestamp,
@Valid MultiRecipientMessage multiRecipientMessage) {
@NotNull @Valid MultiRecipientMessage multiRecipientMessage) {
Map<UUID, Account> uuidToAccountMap = Arrays.stream(multiRecipientMessage.getRecipients())
.map(Recipient::getUuid)
@@ -638,7 +633,8 @@ public class MessageController {
}
}
private void sendMessage(Optional<AuthenticatedAccount> source, Account destinationAccount, Device destinationDevice, UUID destinationUuid, long timestamp, boolean online, IncomingDeviceMessage message, String userAgentString) throws NoSuchUserException {
private void sendMessage(Optional<AuthenticatedAccount> source, Account destinationAccount, Device destinationDevice,
UUID destinationUuid, long timestamp, boolean online, IncomingDeviceMessage message) throws NoSuchUserException {
try {
Envelope.Builder messageBuilder = Envelope.newBuilder();
long serverTimestamp = System.currentTimeMillis();
@@ -698,15 +694,18 @@ public class MessageController {
}
}
private void checkRateLimit(AuthenticatedAccount source, Account destination) throws RateLimitExceededException {
private void checkRateLimit(AuthenticatedAccount source, Account destination, String userAgent)
throws RateLimitExceededException {
final String senderCountryCode = Util.getCountryCode(source.getAccount().getNumber());
try {
rateLimiters.getMessagesLimiter().validate(source.getAccount().getUuid(), destination.getUuid());
} catch (final RateLimitExceededException e) {
Metrics.counter(RATE_LIMITED_MESSAGE_COUNTER_NAME,
SENDER_COUNTRY_TAG_NAME, senderCountryCode,
RATE_LIMIT_REASON_TAG_NAME, "singleDestinationRate").increment();
Tags.of(
UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(SENDER_COUNTRY_TAG_NAME, senderCountryCode),
Tag.of(RATE_LIMIT_REASON_TAG_NAME, "singleDestinationRate"))).increment();
throw e;
}
@@ -778,6 +777,27 @@ public class MessageController {
}
}
private void validateContentLength(final int contentLength, final String userAgent) {
Metrics.summary(CONTENT_SIZE_DISTRIBUTION_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)))
.record(contentLength);
if (contentLength > MAX_MESSAGE_SIZE) {
Metrics.counter(REJECT_OVERSIZE_MESSAGE_COUNTER, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)))
.increment();
throw new WebApplicationException(Status.REQUEST_ENTITY_TOO_LARGE);
}
}
private void validateEnvelopeType(final int type, final String userAgent) {
if (type == Type.SERVER_DELIVERY_RECEIPT_VALUE) {
Metrics.counter(REJECT_INVALID_ENVELOPE_TYPE,
Tags.of(UserAgentTagUtil.getPlatformTag(userAgent), Tag.of(ENVELOPE_TYPE_TAG_NAME, String.valueOf(type))))
.increment();
throw new BadRequestException("reserved envelope type");
}
}
private Optional<byte[]> getMessageBody(IncomingMessage message) {
if (Util.isEmpty(message.getBody())) return Optional.empty();
@@ -23,6 +23,7 @@ import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
@@ -46,6 +47,7 @@ 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.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
@@ -76,6 +78,7 @@ import org.whispersystems.textsecuregcm.entities.BaseProfileResponse;
import org.whispersystems.textsecuregcm.entities.UserCapabilities;
import org.whispersystems.textsecuregcm.entities.VersionedProfileResponse;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.s3.PolicySigner;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.storage.Account;
@@ -115,6 +118,7 @@ public class ProfileController {
private static final String PNI_CREDENTIAL_TYPE = "pni";
private static final Counter VERSION_NOT_FOUND_COUNTER = Metrics.counter(name(ProfileController.class, "versionNotFound"));
private static final String INVALID_ACCEPT_LANGUAGE_COUNTER_NAME = name(ProfileController.class, "invalidAcceptLanguage");
public ProfileController(
Clock clock,
@@ -148,7 +152,7 @@ public class ProfileController {
@PUT
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response setProfile(@Auth AuthenticatedAccount auth, @Valid CreateProfileRequest request) {
public Response setProfile(@Auth AuthenticatedAccount auth, @NotNull @Valid CreateProfileRequest request) {
if (StringUtils.isNotBlank(request.getPaymentAddress())) {
final boolean hasDisallowedPrefix =
dynamicConfigurationManager.getConfiguration().getPaymentsConfiguration().getDisallowedPrefixes().stream()
@@ -436,9 +440,11 @@ public class ProfileController {
try {
return containerRequestContext.getAcceptableLanguages();
} catch (final ProcessingException e) {
logger.warn("Could not get acceptable languages; Accept-Language: {}; User-Agent: {}",
final String userAgent = containerRequestContext.getHeaderString(HttpHeaders.USER_AGENT);
Metrics.counter(INVALID_ACCEPT_LANGUAGE_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent))).increment();
logger.debug("Could not get acceptable languages; Accept-Language: {}; User-Agent: {}",
containerRequestContext.getHeaderString(HttpHeaders.ACCEPT_LANGUAGE),
containerRequestContext.getHeaderString(HttpHeaders.USER_AGENT),
userAgent,
e);
return List.of();
@@ -9,6 +9,7 @@ import com.codahale.metrics.annotation.Timed;
import io.dropwizard.auth.Auth;
import java.util.Base64;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
@@ -41,7 +42,7 @@ public class ProvisioningController {
@Produces(MediaType.APPLICATION_JSON)
public void sendProvisioningMessage(@Auth AuthenticatedAccount auth,
@PathParam("destination") String destinationName,
@Valid ProvisioningMessage message)
@NotNull @Valid ProvisioningMessage message)
throws RateLimitExceededException {
rateLimiters.getMessagesLimiter().validate(auth.getAccount().getUuid());
@@ -4,20 +4,26 @@
*/
package org.whispersystems.textsecuregcm.controllers;
import javax.annotation.Nullable;
import java.time.Duration;
import java.util.Optional;
public class RateLimitExceededException extends Exception {
private final Duration retryDuration;
private final @Nullable
Duration retryDuration;
public RateLimitExceededException(final Duration retryDuration) {
this(null, retryDuration);
}
public RateLimitExceededException(final String message, final Duration retryDuration) {
super(message, null, true, false);
/**
* Constructs a new exception indicating when it may become safe to retry
*
* @param retryDuration A duration to wait before retrying, null if no duration can be indicated
*/
public RateLimitExceededException(final @Nullable Duration retryDuration) {
super(null, null, true, false);
this.retryDuration = retryDuration;
}
public Duration getRetryDuration() { return retryDuration; }
public Optional<Duration> getRetryDuration() {
return Optional.ofNullable(retryDuration);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2021 Signal Messenger, LLC
* Copyright 2013-2022 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
@@ -19,6 +19,7 @@ import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
@@ -54,7 +55,6 @@ public class RemoteConfigController {
@Timed
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public UserRemoteConfigList getAll(@Auth AuthenticatedAccount auth) {
try {
@@ -79,7 +79,7 @@ public class RemoteConfigController {
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public void set(@HeaderParam("Config-Token") String configToken, @Valid RemoteConfig config) {
public void set(@HeaderParam("Config-Token") String configToken, @NotNull @Valid RemoteConfig config) {
if (!isAuthorized(configToken)) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
@@ -1,19 +0,0 @@
/*
* Copyright 2013-2021 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.controllers;
import java.time.Duration;
public class RetryLaterException extends Exception {
private final Duration backoffDuration;
public RetryLaterException(RateLimitExceededException e) {
super(null, e, true, false);
this.backoffDuration = e.getRetryDuration();
}
public Duration getBackoffDuration() { return backoffDuration; }
}
@@ -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;
@@ -35,6 +39,7 @@ import javax.crypto.spec.SecretKeySpec;
import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
@@ -71,6 +76,7 @@ import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionLevelConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionPriceConfiguration;
import org.whispersystems.textsecuregcm.entities.Badge;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
import org.whispersystems.textsecuregcm.storage.SubscriptionManager.GetResult;
@@ -92,6 +98,8 @@ public class SubscriptionController {
private final BadgeTranslator badgeTranslator;
private final LevelTranslator levelTranslator;
private static final String INVALID_ACCEPT_LANGUAGE_COUNTER_NAME = name(SubscriptionController.class, "invalidAcceptLanguage");
public SubscriptionController(
@Nonnull Clock clock,
@Nonnull SubscriptionConfiguration subscriptionConfiguration,
@@ -116,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,
@@ -395,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(() -> {
@@ -443,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(() -> {
@@ -459,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(
@@ -512,7 +516,7 @@ public class SubscriptionController {
@Path("/boost/create")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public CompletableFuture<Response> createBoostPaymentIntent(CreateBoostRequest request) {
public CompletableFuture<Response> createBoostPaymentIntent(@NotNull @Valid CreateBoostRequest request) {
return stripeManager.createPaymentIntent(request.getCurrency(), request.getAmount())
.thenApply(paymentIntent -> Response.ok(new CreateBoostResponse(paymentIntent.getClientSecret())).build());
}
@@ -530,10 +534,12 @@ public class SubscriptionController {
this.receiptCredentialRequest = receiptCredentialRequest;
}
@NotNull
public String getPaymentIntentId() {
return paymentIntentId;
}
@NotNull
public byte[] getReceiptCredentialRequest() {
return receiptCredentialRequest;
}
@@ -559,7 +565,7 @@ public class SubscriptionController {
@Path("/boost/receipt_credentials")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public CompletableFuture<Response> createBoostReceiptCredentials(CreateBoostReceiptCredentialsRequest request) {
public CompletableFuture<Response> createBoostReceiptCredentials(@NotNull @Valid CreateBoostReceiptCredentialsRequest request) {
return stripeManager.getPaymentIntent(request.getPaymentIntentId())
.thenCompose(paymentIntent -> {
if (paymentIntent == null) {
@@ -677,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,
@@ -745,7 +750,7 @@ public class SubscriptionController {
public CompletableFuture<Response> createSubscriptionReceiptCredentials(
@Auth Optional<AuthenticatedAccount> authenticatedAccount,
@PathParam("subscriberId") String subscriberId,
@Valid GetReceiptCredentialsRequest request) {
@NotNull @Valid GetReceiptCredentialsRequest request) {
RequestData requestData = RequestData.process(authenticatedAccount, subscriberId, clock);
return subscriptionManager.get(requestData.subscriberUser, requestData.hmac)
.thenApply(this::requireRecordFromGetResult)
@@ -856,9 +861,11 @@ public class SubscriptionController {
try {
return containerRequestContext.getAcceptableLanguages();
} catch (final ProcessingException e) {
logger.warn("Could not get acceptable languages; Accept-Language: {}; User-Agent: {}",
final String userAgent = containerRequestContext.getHeaderString(HttpHeaders.USER_AGENT);
Metrics.counter(INVALID_ACCEPT_LANGUAGE_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent))).increment();
logger.debug("Could not get acceptable languages; Accept-Language: {}; User-Agent: {}",
containerRequestContext.getHeaderString(HttpHeaders.ACCEPT_LANGUAGE),
containerRequestContext.getHeaderString(HttpHeaders.USER_AGENT),
userAgent,
e);
return List.of();
@@ -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);
}
}
@@ -4,33 +4,52 @@
*/
package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class IncomingMessage {
@JsonProperty
private int type;
private final int type;
@JsonProperty
private String destination;
private final String destination;
@JsonProperty
private long destinationDeviceId = 1;
private final long destinationDeviceId;
@JsonProperty
private int destinationRegistrationId;
private final int destinationRegistrationId;
@JsonProperty
private String body;
private final String body;
@JsonProperty
private String content;
private final String content;
@JsonProperty
private String relay;
private final String relay;
@JsonProperty
private long timestamp; // deprecated
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) {
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;
@@ -4,6 +4,7 @@
*/
package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import javax.validation.Valid;
@@ -14,15 +15,23 @@ public class IncomingMessageList {
@JsonProperty
@NotNull
@Valid
private List<@NotNull IncomingMessage> messages;
private final List<@NotNull IncomingMessage> messages;
@JsonProperty
private long timestamp;
private final long timestamp;
@JsonProperty
private boolean online;
private final boolean online;
public IncomingMessageList() {}
@JsonCreator
public IncomingMessageList(
@JsonProperty("messages") final List<@NotNull IncomingMessage> messages,
@JsonProperty("online") final boolean online,
@JsonProperty("timestamp") final long timestamp) {
this.messages = messages;
this.timestamp = timestamp;
this.online = online;
}
public List<IncomingMessage> getMessages() {
return messages;
@@ -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;
}
}
@@ -1,81 +0,0 @@
/*
* Copyright 2021 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.limits;
import java.time.Duration;
import org.whispersystems.textsecuregcm.configuration.RateLimitsConfiguration.CardinalityRateLimitConfiguration;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
/**
* A cardinality rate limiter prevents an actor from taking some action if that actor has attempted to take that action
* on too many targets in a fixed period of time. Behind the scenes, we estimate the target count using a
* hyper-log-log data structure; as a consequence, the number of targets is an approximation, and this rate limiter
* should not be used in cases where precise time or target limits are required.
*/
public class CardinalityRateLimiter {
private final FaultTolerantRedisCluster cacheCluster;
private final String name;
private final Duration ttl;
private final int defaultMaxCardinality;
public CardinalityRateLimiter(final FaultTolerantRedisCluster cacheCluster, final String name, final Duration ttl, final int defaultMaxCardinality) {
this.cacheCluster = cacheCluster;
this.name = name;
this.ttl = ttl;
this.defaultMaxCardinality = defaultMaxCardinality;
}
public void validate(final String key, final String target, final int maxCardinality) throws RateLimitExceededException {
final boolean rateLimitExceeded = cacheCluster.withCluster(connection -> {
final String hllKey = getHllKey(key);
final boolean changed = connection.sync().pfadd(hllKey, target) == 1;
final long cardinality = connection.sync().pfcount(hllKey);
final boolean mayNeedExpiration = changed && cardinality == 1;
// If the set already existed, we can assume it already had an expiration time and can save a round trip by
// skipping the ttl check.
if (mayNeedExpiration && connection.sync().ttl(hllKey) == -1) {
connection.sync().expire(hllKey, ttl.toSeconds());
}
return cardinality > maxCardinality;
});
if (rateLimitExceeded) {
throw new RateLimitExceededException(Duration.ofSeconds(getRemainingTtl(key)));
}
}
private String getHllKey(final String key) {
return "hll_rate_limit::" + name + "::" + key;
}
public Duration getInitialTtl() {
return ttl;
}
public long getRemainingTtl(final String key) {
return cacheCluster.withCluster(connection -> connection.sync().ttl(getHllKey(key)));
}
public int getDefaultMaxCardinality() {
return defaultMaxCardinality;
}
public boolean hasConfiguration(final CardinalityRateLimitConfiguration configuration) {
return defaultMaxCardinality == configuration.getMaxCardinality() && ttl.equals(configuration.getTtl());
}
}
@@ -31,7 +31,7 @@ public class LockingRateLimiter extends RateLimiter {
public void validate(String key, int amount) throws RateLimitExceededException {
if (!acquireLock(key)) {
meter.mark();
throw new RateLimitExceededException("Locked", Duration.ZERO);
throw new RateLimitExceededException(Duration.ZERO);
}
try {
@@ -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;
@@ -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());
@@ -57,7 +57,7 @@ public class RateLimiter {
setBucket(key, bucket);
} else {
meter.mark();
throw new RateLimitExceededException(key + " , " + amount, bucket.getTimeUntilSpaceAvailable(amount));
throw new RateLimitExceededException(bucket.getTimeUntilSpaceAvailable(amount));
}
}
}
@@ -4,6 +4,8 @@
*/
package org.whispersystems.textsecuregcm.mappers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import javax.ws.rs.core.Response;
@@ -12,8 +14,26 @@ import javax.ws.rs.ext.Provider;
@Provider
public class RateLimitExceededExceptionMapper implements ExceptionMapper<RateLimitExceededException> {
private static final Logger logger = LoggerFactory.getLogger(RateLimitExceededExceptionMapper.class);
/**
* Convert a RateLimitExceededException to a 413 response with a
* Retry-After header.
*
* @param e A RateLimitExceededException potentially containing a recommended retry duration
* @return the response
*/
@Override
public Response toResponse(RateLimitExceededException e) {
return Response.status(413).build();
return e.getRetryDuration()
.filter(d -> {
if (d.isNegative()) {
logger.warn("Encountered a negative retry duration: {}, will not include a Retry-After header in response", d);
}
// only include non-negative durations in retry headers
return !d.isNegative();
})
.map(d -> Response.status(413).header("Retry-After", d.toSeconds()))
.orElseGet(() -> Response.status(413)).build();
}
}
@@ -1,23 +0,0 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.mappers;
import org.whispersystems.textsecuregcm.controllers.RetryLaterException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
@Provider
public class RetryLaterExceptionMapper implements ExceptionMapper<RetryLaterException> {
@Override
public Response toResponse(RetryLaterException e) {
return Response.status(413)
.header("Retry-After", e.getBackoffDuration().toSeconds())
.build();
}
}
@@ -5,12 +5,14 @@
package org.whispersystems.textsecuregcm.metrics;
import io.dropwizard.lifecycle.Managed;
import io.micrometer.core.instrument.Metrics;
import java.util.concurrent.atomic.AtomicBoolean;
import static com.codahale.metrics.MetricRegistry.name;
import io.dropwizard.lifecycle.Managed;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* A managed monitor that reports whether the application is shutting down as a metric. That metric can then be used in
* conjunction with other indicators to conditionally fire or suppress alerts.
@@ -19,8 +21,12 @@ public class ApplicationShutdownMonitor implements Managed {
private final AtomicBoolean shuttingDown = new AtomicBoolean(false);
public ApplicationShutdownMonitor() {
Metrics.gauge(name(getClass().getSimpleName(), "shuttingDown"), shuttingDown, b -> b.get() ? 1 : 0);
public ApplicationShutdownMonitor(final MeterRegistry meterRegistry) {
// without a strong reference to the gauge’s value supplier, shutdown garbage collection
// might prevent the final value from being reported
Gauge.builder(name(getClass().getSimpleName(), "shuttingDown"), () -> shuttingDown.get() ? 1 : 0)
.strongReference(true)
.register(meterRegistry);
}
@Override
@@ -0,0 +1,29 @@
/*
* Copyright 2022 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.metrics;
import io.dropwizard.lifecycle.Managed;
import io.micrometer.core.instrument.MeterRegistry;
public class MicrometerRegistryManager implements Managed {
private final MeterRegistry meterRegistry;
public MicrometerRegistryManager(final MeterRegistry meterRegistry) {
this.meterRegistry = meterRegistry;
}
@Override
public void start() throws Exception {
}
@Override
public void stop() throws Exception {
// closing the registry publishes one final set of metrics
meterRegistry.close();
}
}
@@ -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());
}
}
@@ -16,6 +16,7 @@ import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.NoContentException;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import org.whispersystems.textsecuregcm.entities.IncomingDeviceMessage;
@@ -66,7 +67,7 @@ public class MultiDeviceMessageListProvider extends BinaryProviderBase implement
long messageLength = readVarint(entityStream);
if (messageLength > MAX_MESSAGE_SIZE) {
throw new BadRequestException("Message body too large");
throw new WebApplicationException("Message body too large", Status.REQUEST_ENTITY_TOO_LARGE);
}
byte[] contents = entityStream.readNBytes(Math.toIntExact(messageLength));
if (contents.length != messageLength) {
@@ -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();
}
}
}
@@ -82,7 +82,8 @@ public class APNSender implements Managed {
ListenableFuture<ApnResult> future = apnsClient.send(message.getApnId(), topic,
message.getMessage(),
Instant.ofEpochMilli(message.getExpirationTime()),
message.isVoip());
message.isVoip(),
message.getCollapseId());
Futures.addCallback(future, new FutureCallback<>() {
@Override
@@ -66,6 +66,14 @@ public class ApnMessage {
}
}
@Nullable
public String getCollapseId() {
if (type == Type.NOTIFICATION && !isVoip) {
return "incoming-message";
}
return null;
}
@VisibleForTesting
public Optional<String> getChallengeData() {
return challengeData;
@@ -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);
}
}
@@ -67,9 +67,9 @@ public class RetryingApnsClient {
this.apnsClient = apnsClient;
}
ListenableFuture<ApnResult> send(final String apnId, final String topic, final String payload, final Instant expiration, final boolean isVoip) {
ListenableFuture<ApnResult> send(final String apnId, final String topic, final String payload, final Instant expiration, final boolean isVoip, final String collapseId) {
SettableFuture<ApnResult> result = SettableFuture.create();
SimpleApnsPushNotification notification = new SimpleApnsPushNotification(apnId, topic, payload, expiration, DeliveryPriority.IMMEDIATE, isVoip ? PushType.VOIP : PushType.ALERT);
SimpleApnsPushNotification notification = new SimpleApnsPushNotification(apnId, topic, payload, expiration, DeliveryPriority.IMMEDIATE, isVoip ? PushType.VOIP : PushType.ALERT, collapseId);
apnsClient.sendNotification(notification).whenComplete(new ResponseHandler(result));
@@ -1,60 +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 java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import javax.annotation.Nonnull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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) {
Event event = Event.newBuilder()
.setExpectedAction("challenge")
.setSiteKey(siteKey)
.setToken(token)
.setUserIpAddress(ip)
.build();
final Assessment assessment = client.createAssessment(projectPath, Assessment.newBuilder().setEvent(event).build());
return assessment.getTokenProperties().getValid() && assessment.getRiskAnalysis().getScore() >= scoreFloor;
}
}
@@ -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;
}
}
}
@@ -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;
}
}
}
@@ -1,33 +0,0 @@
/*
* Copyright 2021 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.recaptcha;
import java.util.Objects;
import javax.annotation.Nonnull;
public class TransitionalRecaptchaClient implements RecaptchaClient {
private static final String V2_PREFIX = "signal-recaptcha-v2:";
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)) {
return enterpriseRecaptchaClient.verify(token.substring(V2_PREFIX.length()), ip);
} else {
return legacyRecaptchaClient.verify(token, ip);
}
}
}
@@ -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;
}
}
}
@@ -6,24 +6,26 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.google.common.annotations.VisibleForTesting;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import io.micrometer.core.instrument.Metrics;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.util.Util;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.services.appconfig.AppConfigClient;
import software.amazon.awssdk.services.appconfig.model.GetConfigurationRequest;
import software.amazon.awssdk.services.appconfig.model.GetConfigurationResponse;
import software.amazon.awssdk.services.appconfigdata.AppConfigDataClient;
import software.amazon.awssdk.services.appconfigdata.model.GetLatestConfigurationRequest;
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 static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
@@ -32,17 +34,15 @@ public class DynamicConfigurationManager<T> {
private final String application;
private final String environment;
private final String configurationName;
private final String clientId;
private final AppConfigClient appConfigClient;
private final AppConfigDataClient appConfigClient;
private final Class<T> configurationClass;
// Set on initial config fetch
private final AtomicReference<T> configuration = new AtomicReference<>();
private GetConfigurationResponse lastConfigResult;
private String configurationToken = null;
private boolean initialized = false;
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(new YAMLFactory())
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.registerModule(new JavaTimeModule());
@@ -57,22 +57,22 @@ public class DynamicConfigurationManager<T> {
public DynamicConfigurationManager(String application, String environment, String configurationName,
Class<T> configurationClass) {
this(AppConfigClient.builder()
this(AppConfigDataClient
.builder()
.overrideConfiguration(ClientOverrideConfiguration.builder()
.apiCallTimeout(Duration.ofMillis(10000))
.apiCallAttemptTimeout(Duration.ofMillis(10000)).build())
.apiCallTimeout(Duration.ofSeconds(10))
.apiCallAttemptTimeout(Duration.ofSeconds(10)).build())
.build(),
application, environment, configurationName, UUID.randomUUID().toString(), configurationClass);
application, environment, configurationName, configurationClass);
}
@VisibleForTesting
DynamicConfigurationManager(AppConfigClient appConfigClient, String application, String environment,
String configurationName, String clientId, Class<T> configurationClass) {
DynamicConfigurationManager(AppConfigDataClient appConfigClient, String application, String environment,
String configurationName, Class<T> configurationClass) {
this.appConfigClient = appConfigClient;
this.application = application;
this.environment = environment;
this.configurationName = configurationName;
this.clientId = clientId;
this.configurationClass = configurationClass;
}
@@ -82,13 +82,11 @@ public class DynamicConfigurationManager<T> {
Util.wait(this);
}
}
return configuration.get();
}
public void start() {
configuration.set(retrieveInitialDynamicConfiguration());
synchronized (this) {
this.initialized = true;
this.notifyAll();
@@ -98,8 +96,8 @@ public class DynamicConfigurationManager<T> {
while (true) {
try {
retrieveDynamicConfiguration().ifPresent(configuration::set);
} catch (Throwable t) {
logger.warn("Error retrieving dynamic configuration", t);
} catch (Exception e) {
logger.warn("Error retrieving dynamic configuration", e);
}
Util.sleep(5000);
@@ -111,44 +109,38 @@ public class DynamicConfigurationManager<T> {
}
private Optional<T> retrieveDynamicConfiguration() throws JsonProcessingException {
final String previousVersion = lastConfigResult != null ? lastConfigResult.configurationVersion() : null;
if (configurationToken == null) {
logger.error("Invalid configuration token, will not be able to fetch configuration updates");
}
GetLatestConfigurationResponse latestConfiguration;
try {
lastConfigResult = appConfigClient.getConfiguration(GetConfigurationRequest.builder()
.application(application)
.environment(environment)
.configuration(configurationName)
.clientId(clientId)
.clientConfigurationVersion(previousVersion)
latestConfiguration = appConfigClient.getLatestConfiguration(GetLatestConfigurationRequest.builder()
.configurationToken(configurationToken)
.build());
// token to use in the next fetch
configurationToken = latestConfiguration.nextPollConfigurationToken();
logger.debug("next token: {}", configurationToken);
} catch (final RuntimeException e) {
Metrics.counter(ERROR_COUNTER_NAME, ERROR_TYPE_TAG_NAME, "fetch").increment();
throw e;
}
final Optional<T> maybeDynamicConfiguration;
if (!StringUtils.equals(lastConfigResult.configurationVersion(), previousVersion)) {
logger.info("Received new config version: {}", lastConfigResult.configurationVersion());
try {
maybeDynamicConfiguration =
parseConfiguration(
StandardCharsets.UTF_8.decode(lastConfigResult.content().asByteBuffer().asReadOnlyBuffer()).toString(),
configurationClass);
} catch (final JsonProcessingException e) {
Metrics.counter(ERROR_COUNTER_NAME,
ERROR_TYPE_TAG_NAME, "parse",
CONFIG_CLASS_TAG_NAME, configurationClass.getName()).increment();
throw e;
}
} else {
// No change since last version
maybeDynamicConfiguration = Optional.empty();
if (!latestConfiguration.configuration().asByteBuffer().hasRemaining()) {
// empty configuration means nothing has changed
return Optional.empty();
}
logger.info("Received new config of length {}, next configuration token: {}",
latestConfiguration.configuration().asByteBuffer().remaining(),
configurationToken);
return maybeDynamicConfiguration;
try {
return parseConfiguration(latestConfiguration.configuration().asUtf8String(), configurationClass);
} catch (final JsonProcessingException e) {
Metrics.counter(ERROR_COUNTER_NAME,
ERROR_TYPE_TAG_NAME, "parse",
CONFIG_CLASS_TAG_NAME, configurationClass.getName()).increment();
throw e;
}
}
@VisibleForTesting
@@ -172,15 +164,18 @@ public class DynamicConfigurationManager<T> {
private T retrieveInitialDynamicConfiguration() {
for (;;) {
try {
final Optional<T> maybeDynamicConfiguration = retrieveDynamicConfiguration();
if (maybeDynamicConfiguration.isPresent()) {
return maybeDynamicConfiguration.get();
} else {
throw new IllegalStateException("No initial configuration available");
if (configurationToken == null) {
// first time around, start the configuration session
final StartConfigurationSessionResponse startResponse = appConfigClient
.startConfigurationSession(StartConfigurationSessionRequest.builder()
.applicationIdentifier(application)
.environmentIdentifier(environment)
.configurationProfileIdentifier(configurationName).build());
configurationToken = startResponse.initialConfigurationToken();
}
} catch (Throwable t) {
logger.warn("Error retrieving initial dynamic configuration", t);
return retrieveDynamicConfiguration().orElseThrow(() -> new IllegalStateException("No initial configuration available"));
} catch (Exception e) {
logger.warn("Error retrieving initial dynamic configuration", e);
Util.sleep(1000);
}
}
@@ -73,7 +73,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,10 +88,7 @@ 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()));
@@ -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);
}
});
}
}
@@ -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();
}
}
@@ -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);
}
}
@@ -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,
@@ -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,
@@ -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,
@@ -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");
}
}
@@ -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");
}
}
}
@@ -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);
}
}
@@ -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;
@@ -27,7 +29,7 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
import org.whispersystems.textsecuregcm.auth.DisabledPermittedAuthenticatedAccount;
import org.whispersystems.textsecuregcm.limits.RateLimitChallengeManager;
import org.whispersystems.textsecuregcm.mappers.RetryLaterExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.util.SystemMapper;
@@ -45,7 +47,7 @@ class ChallengeControllerTest {
Set.of(AuthenticatedAccount.class, DisabledPermittedAuthenticatedAccount.class)))
.setMapper(SystemMapper.getMapper())
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
.addResource(new RetryLaterExceptionMapper())
.addResource(new RateLimitExceededExceptionMapper())
.addResource(challengeController)
.build();
@@ -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()
@@ -36,6 +36,7 @@ import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
import io.dropwizard.testing.junit5.ResourceExtension;
import io.lettuce.core.cluster.api.sync.RedisAdvancedClusterCommands;
import java.io.ByteArrayOutputStream;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collection;
import java.util.HashSet;
@@ -63,6 +64,7 @@ import org.mockito.ArgumentCaptor;
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
import org.whispersystems.textsecuregcm.auth.DisabledPermittedAuthenticatedAccount;
import org.whispersystems.textsecuregcm.auth.OptionalAccess;
import org.whispersystems.textsecuregcm.entities.IncomingMessage;
import org.whispersystems.textsecuregcm.entities.IncomingMessageList;
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
import org.whispersystems.textsecuregcm.entities.MismatchedDevices;
@@ -132,22 +134,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());
@@ -612,6 +614,90 @@ class MessageControllerTest {
verify(reportMessageManager).report(senderNumber, messageGuid, AuthHelper.VALID_UUID);
}
@ParameterizedTest
@MethodSource
void testValidateContentLength(Entity<?> payload) throws Exception {
Response response =
resources.getJerseyTest()
.target(String.format("/v1/messages/%s", SINGLE_DEVICE_UUID))
.request()
.header(OptionalAccess.UNIDENTIFIED, Base64.getEncoder().encodeToString("1234".getBytes()))
.put(payload);
assertThat("Bad response", response.getStatus(), is(equalTo(413)));
verify(messageSender, never()).sendMessage(any(Account.class), any(Device.class), any(Envelope.class),
anyBoolean());
}
private static Stream<Entity<?>> testValidateContentLength() {
final int contentLength = Math.toIntExact(MessageController.MAX_MESSAGE_SIZE + 1);
ByteArrayOutputStream messageStream = new ByteArrayOutputStream();
messageStream.write(1); // version
messageStream.write(1); // count
messageStream.write(1); // device ID
messageStream.writeBytes(new byte[]{(byte) 0, (byte) 111}); // registration ID
messageStream.write(1); // message type
writeVarint(contentLength, messageStream); // message length
final byte[] contentBytes = new byte[contentLength];
Arrays.fill(contentBytes, (byte) 1);
messageStream.writeBytes(contentBytes); // message contents
try {
return Stream.of(
Entity.entity(new IncomingMessageList(
List.of(new IncomingMessage(1, null, 1L, 1, new String(contentBytes), null, null)), false,
System.currentTimeMillis()),
MediaType.APPLICATION_JSON_TYPE),
Entity.entity(messageStream.toByteArray(), MultiDeviceMessageListProvider.MEDIA_TYPE)
);
} catch (Exception e) {
throw new AssertionError(e);
}
}
private static void writeVarint(int value, ByteArrayOutputStream outputStream) {
while (true) {
int bits = value & 0x7f;
value >>>= 7;
if (value == 0) {
outputStream.write((byte) bits);
return;
}
outputStream.write((byte) (bits | 0x80));
}
}
@ParameterizedTest
@MethodSource
void testValidateEnvelopeType(String payloadFilename, boolean expectOk) throws Exception {
Response response =
resources.getJerseyTest()
.target(String.format("/v1/messages/%s", SINGLE_DEVICE_UUID))
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.header("User-Agent", "FIXME")
.put(Entity.entity(mapper.readValue(jsonFixture(payloadFilename), IncomingMessageList.class),
MediaType.APPLICATION_JSON_TYPE));
if (expectOk) {
assertEquals(200, response.getStatus());
final ArgumentCaptor<Envelope> captor = ArgumentCaptor.forClass(Envelope.class);
verify(messageSender).sendMessage(any(Account.class), any(Device.class), captor.capture(), eq(false));
} else {
assertEquals(400, response.getStatus());
verify(messageSender, never()).sendMessage(any(), any(), any(), anyBoolean());
}
}
private static Stream<Arguments> testValidateEnvelopeType() {
return Stream.of(
Arguments.of("fixtures/current_message_single_device.json", true),
Arguments.of("fixtures/current_message_single_device_server_receipt_type.json", false)
);
}
static Account mockAccountWithDeviceAndRegId(Object... deviceAndRegistrationIds) {
Account account = mock(Account.class);
if (deviceAndRegistrationIds.length % 2 != 0) {
@@ -34,6 +34,7 @@ import org.whispersystems.textsecuregcm.configuration.BoostConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionLevelConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionPriceConfiguration;
import org.whispersystems.textsecuregcm.controllers.SubscriptionController.CreateBoostReceiptCredentialsRequest;
import org.whispersystems.textsecuregcm.controllers.SubscriptionController.GetLevelsResponse;
import org.whispersystems.textsecuregcm.entities.Badge;
import org.whispersystems.textsecuregcm.entities.BadgeSvg;
@@ -42,6 +43,8 @@ import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
import org.whispersystems.textsecuregcm.stripe.StripeManager;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
@ExtendWith(DropwizardExtensionsSupport.class)
class SubscriptionControllerTest {
@@ -74,6 +77,23 @@ class SubscriptionControllerTest {
BADGE_TRANSLATOR, LEVEL_TRANSLATOR);
}
@Test
void createBoostReceiptInvalid() {
final Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/receipt_credentials")
.request()
// invalid, request body should have receiptCredentialRequest
.post(Entity.json("{\"paymentIntentId\": \"foo\"}"));
assertThat(response.getStatus()).isEqualTo(422);
}
@Test
void createBoostReceiptNoRequest() {
final Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/receipt_credentials")
.request()
.post(Entity.json(""));
assertThat(response.getStatus()).isEqualTo(422);
}
@Test
void getLevels() {
when(SUBSCRIPTION_CONFIG.getLevels()).thenReturn(Map.of(
@@ -1,54 +0,0 @@
/*
* Copyright 2021 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.limits;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
class CardinalityRateLimiterTest {
@RegisterExtension
static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
@Test
void testValidate() {
final int maxCardinality = 10;
final CardinalityRateLimiter rateLimiter =
new CardinalityRateLimiter(REDIS_CLUSTER_EXTENSION.getRedisCluster(), "test", Duration.ofDays(1),
maxCardinality);
final String source = "+18005551234";
int validatedAttempts = 0;
int blockedAttempts = 0;
for (int i = 0; i < maxCardinality * 2; i++) {
try {
rateLimiter.validate(source, String.valueOf(i), rateLimiter.getDefaultMaxCardinality());
validatedAttempts++;
} catch (final RateLimitExceededException e) {
blockedAttempts++;
}
}
assertTrue(validatedAttempts >= maxCardinality);
assertTrue(blockedAttempts > 0);
final String secondSource = "+18005554321";
try {
rateLimiter.validate(secondSource, "test", rateLimiter.getDefaultMaxCardinality());
} catch (final RateLimitExceededException e) {
fail("New source should not trigger a rate limit exception on first attempted validation");
}
}
}
@@ -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);
@@ -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")
);
}
}
@@ -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);
@@ -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())
);
}
@@ -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);
@@ -1,42 +1,149 @@
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.mockito.ArgumentCaptor;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.appconfig.AppConfigClient;
import software.amazon.awssdk.services.appconfig.model.GetConfigurationRequest;
import software.amazon.awssdk.services.appconfig.model.GetConfigurationResponse;
import software.amazon.awssdk.services.appconfigdata.AppConfigDataClient;
import software.amazon.awssdk.services.appconfigdata.model.GetLatestConfigurationRequest;
import software.amazon.awssdk.services.appconfigdata.model.GetLatestConfigurationResponse;
import software.amazon.awssdk.services.appconfigdata.model.StartConfigurationSessionRequest;
import software.amazon.awssdk.services.appconfigdata.model.StartConfigurationSessionResponse;
class DynamicConfigurationManagerTest {
private static final SdkBytes VALID_CONFIG = SdkBytes.fromUtf8String("""
test: true
captcha:
scoreFloor: 1.0
""");
private DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private AppConfigClient appConfig;
private AppConfigDataClient appConfig;
private StartConfigurationSessionRequest startConfigurationSession;
@BeforeEach
void setup() {
this.appConfig = mock(AppConfigClient.class);
this.dynamicConfigurationManager = new DynamicConfigurationManager<>(appConfig, "foo", "bar", "baz", "poof", DynamicConfiguration.class);
this.appConfig = mock(AppConfigDataClient.class);
this.dynamicConfigurationManager = new DynamicConfigurationManager<>(
appConfig, "foo", "bar", "baz", DynamicConfiguration.class);
this.startConfigurationSession = StartConfigurationSessionRequest.builder()
.applicationIdentifier("foo")
.environmentIdentifier("bar")
.configurationProfileIdentifier("baz")
.build();
}
@Test
void testGetConfig() {
ArgumentCaptor<GetConfigurationRequest> captor = ArgumentCaptor.forClass(GetConfigurationRequest.class);
when(appConfig.getConfiguration(captor.capture())).thenReturn(
GetConfigurationResponse.builder().content(SdkBytes.fromByteArray("test: true".getBytes())).configurationVersion("1").build());
void testGetInitialConfig() {
when(appConfig.startConfigurationSession(startConfigurationSession))
.thenReturn(StartConfigurationSessionResponse.builder()
.initialConfigurationToken("initial")
.build());
dynamicConfigurationManager.start();
// call with initial token will return a real config
when(appConfig.getLatestConfiguration(GetLatestConfigurationRequest.builder()
.configurationToken("initial").build()))
.thenReturn(GetLatestConfigurationResponse.builder()
.configuration(VALID_CONFIG)
.nextPollConfigurationToken("next").build());
assertThat(captor.getValue().application()).isEqualTo("foo");
assertThat(captor.getValue().environment()).isEqualTo("bar");
assertThat(captor.getValue().configuration()).isEqualTo("baz");
assertThat(captor.getValue().clientId()).isEqualTo("poof");
// subsequent config calls will return empty (no update)
when(appConfig.getLatestConfiguration(GetLatestConfigurationRequest.builder().
configurationToken("next").build()))
.thenReturn(GetLatestConfigurationResponse.builder()
.configuration(SdkBytes.fromUtf8String(""))
.nextPollConfigurationToken("next").build());
assertTimeoutPreemptively(Duration.ofSeconds(5), () -> {
dynamicConfigurationManager.start();
assertThat(dynamicConfigurationManager.getConfiguration()).isNotNull();
});
}
@Test
void testBadConfig() {
when(appConfig.startConfigurationSession(startConfigurationSession))
.thenReturn(StartConfigurationSessionResponse.builder()
.initialConfigurationToken("initial")
.build());
// call with initial token will return a bad config
when(appConfig.getLatestConfiguration(GetLatestConfigurationRequest.builder()
.configurationToken("initial").build()))
.thenReturn(GetLatestConfigurationResponse.builder()
.configuration(SdkBytes.fromUtf8String("zzz"))
.nextPollConfigurationToken("goodconfig").build());
// next config call will return a good config
when(appConfig.getLatestConfiguration(GetLatestConfigurationRequest.builder().
configurationToken("goodconfig").build()))
.thenReturn(GetLatestConfigurationResponse.builder()
.configuration(VALID_CONFIG)
.nextPollConfigurationToken("next").build());
// all subsequent config calls will return an empty config (no update)
when(appConfig.getLatestConfiguration(GetLatestConfigurationRequest.builder().
configurationToken("next").build()))
.thenReturn(GetLatestConfigurationResponse.builder()
.configuration(SdkBytes.fromUtf8String(""))
.nextPollConfigurationToken("next").build());
assertTimeoutPreemptively(Duration.ofSeconds(5), () -> {
dynamicConfigurationManager.start();
assertThat(dynamicConfigurationManager.getConfiguration()).isNotNull();
});
}
@Test
void testGetConfigMultiple() {
when(appConfig.startConfigurationSession(startConfigurationSession))
.thenReturn(StartConfigurationSessionResponse.builder()
.initialConfigurationToken("0")
.build());
// initial config
when(appConfig.getLatestConfiguration(GetLatestConfigurationRequest.builder().
configurationToken("0").build()))
.thenReturn(GetLatestConfigurationResponse.builder()
.configuration(VALID_CONFIG)
.nextPollConfigurationToken("1").build());
// config update with a real config
when(appConfig.getLatestConfiguration(GetLatestConfigurationRequest.builder().
configurationToken("1").build()))
.thenReturn(GetLatestConfigurationResponse.builder()
.configuration(SdkBytes.fromUtf8String("""
featureFlags:
- testFlag
captcha:
scoreFloor: 1.0
"""))
.nextPollConfigurationToken("2").build());
// all subsequent are no update
when(appConfig.getLatestConfiguration(GetLatestConfigurationRequest.builder().
configurationToken("2").build()))
.thenReturn(GetLatestConfigurationResponse.builder()
.configuration(SdkBytes.fromUtf8String(""))
.nextPollConfigurationToken("2").build());
// 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");
});
assertThat(dynamicConfigurationManager.getConfiguration()).isNotNull();
}
}
@@ -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
@@ -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);
}
@@ -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"))));
@@ -274,14 +273,14 @@ class AccountControllerTest {
when(recaptchaClient.verify(eq(INVALID_CAPTCHA_TOKEN), anyString())).thenReturn(false);
when(recaptchaClient.verify(eq(VALID_CAPTCHA_TOKEN), anyString())).thenReturn(true);
doThrow(new RateLimitExceededException(SENDER_OVER_PIN, Duration.ZERO)).when(pinLimiter).validate(eq(SENDER_OVER_PIN));
doThrow(new RateLimitExceededException(Duration.ZERO)).when(pinLimiter).validate(eq(SENDER_OVER_PIN));
doThrow(new RateLimitExceededException(RATE_LIMITED_PREFIX_HOST, Duration.ZERO)).when(autoBlockLimiter).validate(eq(RATE_LIMITED_PREFIX_HOST));
doThrow(new RateLimitExceededException(RATE_LIMITED_IP_HOST, Duration.ZERO)).when(autoBlockLimiter).validate(eq(RATE_LIMITED_IP_HOST));
doThrow(new RateLimitExceededException(Duration.ZERO)).when(autoBlockLimiter).validate(eq(RATE_LIMITED_PREFIX_HOST));
doThrow(new RateLimitExceededException(Duration.ZERO)).when(autoBlockLimiter).validate(eq(RATE_LIMITED_IP_HOST));
doThrow(new RateLimitExceededException(SENDER_OVER_PREFIX, Duration.ZERO)).when(smsVoicePrefixLimiter).validate(SENDER_OVER_PREFIX.substring(0, 4+2));
doThrow(new RateLimitExceededException(RATE_LIMITED_IP_HOST, Duration.ZERO)).when(smsVoiceIpLimiter).validate(RATE_LIMITED_IP_HOST);
doThrow(new RateLimitExceededException(RATE_LIMITED_HOST2, Duration.ZERO)).when(smsVoiceIpLimiter).validate(RATE_LIMITED_HOST2);
doThrow(new RateLimitExceededException(Duration.ZERO)).when(smsVoicePrefixLimiter).validate(SENDER_OVER_PREFIX.substring(0, 4+2));
doThrow(new RateLimitExceededException(Duration.ZERO)).when(smsVoiceIpLimiter).validate(RATE_LIMITED_IP_HOST);
doThrow(new RateLimitExceededException(Duration.ZERO)).when(smsVoiceIpLimiter).validate(RATE_LIMITED_HOST2);
}
@AfterEach
@@ -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 =
@@ -1804,6 +1803,38 @@ class AccountControllerTest {
.getStatus()).isEqualTo(404);
}
@Test
void testAccountExistsRateLimited() throws RateLimitExceededException {
final Account account = mock(Account.class);
final UUID accountIdentifier = UUID.randomUUID();
when(accountsManager.getByAccountIdentifier(accountIdentifier)).thenReturn(Optional.of(account));
final RateLimiter checkAccountLimiter = mock(RateLimiter.class);
when(rateLimiters.getCheckAccountExistenceLimiter()).thenReturn(checkAccountLimiter);
doThrow(new RateLimitExceededException(Duration.ofSeconds(13))).when(checkAccountLimiter).validate("127.0.0.1");
final Response response = resources.getJerseyTest()
.target(String.format("/v1/accounts/account/%s", accountIdentifier))
.request()
.header("X-Forwarded-For", "127.0.0.1")
.head();
assertThat(response.getStatus()).isEqualTo(413);
assertThat(response.getHeaderString("Retry-After")).isEqualTo(String.valueOf(Duration.ofSeconds(13).toSeconds()));
}
@Test
void testAccountExistsNoForwardedFor() throws RateLimitExceededException {
final Response response = resources.getJerseyTest()
.target(String.format("/v1/accounts/account/%s", UUID.randomUUID()))
.request()
.header("X-Forwarded-For", "")
.head();
assertThat(response.getStatus()).isEqualTo(413);
assertThat(Long.parseLong(response.getHeaderString("Retry-After"))).isNotNegative();
}
@Test
void testAccountExistsAuthenticated() {
assertThat(resources.getJerseyTest()
@@ -305,7 +305,7 @@ class DeviceControllerTest {
void deviceDowngradeCapabilitiesTest(final String userAgent, final boolean gv2, final boolean gv2_2,
final boolean gv2_3, final int expectedStatus) {
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(gv2, gv2_2, gv2_3, true, false, true, true, true,
true, true);
true, true, true);
AccountAttributes accountAttributes = new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
Response response = resources.getJerseyTest()
.target("/v1/devices/5678901")
@@ -346,7 +346,7 @@ class DeviceControllerTest {
@Test
void deviceDowngradeGv1MigrationTest() {
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true, true, true, false, false, true, true,
true, true);
true, true, true);
AccountAttributes accountAttributes = new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
Response response = resources.getJerseyTest()
.target("/v1/devices/5678901")
@@ -357,7 +357,7 @@ class DeviceControllerTest {
assertThat(response.getStatus()).isEqualTo(409);
deviceCapabilities = new DeviceCapabilities(true, true, true, true, false, true, true, true, true, true);
deviceCapabilities = new DeviceCapabilities(true, true, true, true, false, true, true, true, true, true, true);
accountAttributes = new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
response = resources.getJerseyTest()
.target("/v1/devices/5678901")
@@ -372,7 +372,7 @@ class DeviceControllerTest {
@Test
void deviceDowngradeSenderKeyTest() {
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, false, true,
true, true);
true, true, true);
AccountAttributes accountAttributes =
new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
Response response = resources
@@ -384,7 +384,7 @@ class DeviceControllerTest {
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
assertThat(response.getStatus()).isEqualTo(409);
deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, true, true, true);
deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, true, true, true, true);
accountAttributes = new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
response = resources
.getJerseyTest()
@@ -399,7 +399,7 @@ class DeviceControllerTest {
@Test
void deviceDowngradeAnnouncementGroupTest() {
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, false,
true, true);
true, true, true);
AccountAttributes accountAttributes =
new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
Response response = resources
@@ -411,7 +411,7 @@ class DeviceControllerTest {
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
assertThat(response.getStatus()).isEqualTo(409);
deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, true, true, true);
deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, true, true, true, true);
accountAttributes = new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
response = resources
.getJerseyTest()
@@ -425,7 +425,8 @@ class DeviceControllerTest {
@Test
void deviceDowngradeChangeNumberTest() {
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, true, false, true);
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, true,
false, true, true);
AccountAttributes accountAttributes =
new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
Response response = resources
@@ -438,7 +439,7 @@ class DeviceControllerTest {
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
assertThat(response.getStatus()).isEqualTo(409);
deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, true, true, true);
deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, true, true, true, true);
accountAttributes = new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
response = resources
.getJerseyTest()
@@ -454,7 +455,7 @@ class DeviceControllerTest {
@Test
void deviceDowngradePniTest() {
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, true, true,
false);
false, true);
AccountAttributes accountAttributes =
new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
Response response = resources
@@ -466,13 +467,45 @@ class DeviceControllerTest {
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
assertThat(response.getStatus()).isEqualTo(409);
deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, true, true, true);
deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, true, true, true, true);
accountAttributes = new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
response = resources
.getJerseyTest()
.target("/v1/devices/5678901")
.request()
.header("Authorization", AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, AuthHelper.VALID_PASSWORD))
.header("Authorization",
AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, AuthHelper.VALID_PASSWORD))
.header("User-Agent", "Signal-Android/5.42.8675309 Android/30")
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
assertThat(response.getStatus()).isEqualTo(200);
}
@Test
void deviceDowngradeStoriesTest() {
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, true, true,
true, false);
AccountAttributes accountAttributes =
new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
Response response = resources
.getJerseyTest()
.target("/v1/devices/5678901")
.request()
.header("Authorization",
AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, AuthHelper.VALID_PASSWORD))
.header("User-Agent", "Signal-Android/5.42.8675309 Android/30")
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
assertThat(response.getStatus()).isEqualTo(200); // Downgrade is currently supported
// TODO stories capability
// assertThat(response.getStatus()).isEqualTo(409);
deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, true, true, true, true);
accountAttributes = new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
response = resources
.getJerseyTest()
.target("/v1/devices/5678901")
.request()
.header("Authorization",
AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, AuthHelper.VALID_PASSWORD))
.header("User-Agent", "Signal-Android/5.42.8675309 Android/30")
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
assertThat(response.getStatus()).isEqualTo(200);
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.tests.controllers;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.eq;
@@ -38,8 +39,6 @@ import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
import org.whispersystems.textsecuregcm.auth.DisabledPermittedAuthenticatedAccount;
@@ -50,11 +49,11 @@ import org.whispersystems.textsecuregcm.entities.PreKey;
import org.whispersystems.textsecuregcm.entities.PreKeyCount;
import org.whispersystems.textsecuregcm.entities.PreKeyResponse;
import org.whispersystems.textsecuregcm.entities.PreKeyState;
import org.whispersystems.textsecuregcm.entities.RateLimitChallenge;
import org.whispersystems.textsecuregcm.entities.SignedPreKey;
import org.whispersystems.textsecuregcm.limits.RateLimitChallengeManager;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.mappers.RateLimitChallengeExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.ServerRejectedExceptionMapper;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
@@ -107,6 +106,7 @@ class KeysControllerTest {
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
.addResource(new ServerRejectedExceptionMapper())
.addResource(new KeysController(rateLimiters, KEYS, accounts))
.addResource(new RateLimitExceededExceptionMapper())
.build();
@BeforeEach
@@ -316,6 +316,21 @@ class KeysControllerTest {
verifyNoMoreInteractions(KEYS);
}
@Test
void testGetKeysRateLimited() throws RateLimitExceededException {
Duration retryAfter = Duration.ofSeconds(31);
doThrow(new RateLimitExceededException(retryAfter)).when(rateLimiter).validate(anyString());
Response result = resources.getJerseyTest()
.target(String.format("/v2/keys/%s/*", EXISTS_PNI))
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get();
assertThat(result.getStatus()).isEqualTo(413);
assertThat(result.getHeaderString("Retry-After")).isEqualTo(String.valueOf(retryAfter.toSeconds()));
}
@Test
void testUnidentifiedRequest() {
PreKeyResponse result = resources.getJerseyTest()
@@ -555,10 +570,10 @@ class KeysControllerTest {
Response response =
resources.getJerseyTest()
.target("/v2/keys")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.DISABLED_UUID, AuthHelper.DISABLED_PASSWORD))
.put(Entity.entity(preKeyState, MediaType.APPLICATION_JSON_TYPE));
.target("/v2/keys")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.DISABLED_UUID, AuthHelper.DISABLED_PASSWORD))
.put(Entity.entity(preKeyState, MediaType.APPLICATION_JSON_TYPE));
assertThat(response.getStatus()).isEqualTo(204);
@@ -574,4 +589,24 @@ class KeysControllerTest {
verify(AuthHelper.DISABLED_DEVICE).setSignedPreKey(eq(signedPreKey));
verify(accounts).update(eq(AuthHelper.DISABLED_ACCOUNT), any());
}
@Test
void putIdentityKeyNonPrimary() {
final PreKey preKey = new PreKey(31337, "foobar");
final SignedPreKey signedPreKey = new SignedPreKey(31338, "foobaz", "myvalidsig");
final String identityKey = "barbar";
List<PreKey> preKeys = List.of(preKey);
PreKeyState preKeyState = new PreKeyState(identityKey, signedPreKey, preKeys);
Response response =
resources.getJerseyTest()
.target("/v2/keys")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_3, 2L, AuthHelper.VALID_PASSWORD_3_LINKED))
.put(Entity.entity(preKeyState, MediaType.APPLICATION_JSON_TYPE));
assertThat(response.getStatus()).isEqualTo(403);
}
}
@@ -10,6 +10,7 @@ import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.mockito.ArgumentMatchers.refEq;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -26,6 +27,7 @@ import io.dropwizard.testing.junit5.ResourceExtension;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
import java.util.Collections;
@@ -82,6 +84,7 @@ import org.whispersystems.textsecuregcm.entities.ProfileKeyCredentialProfileResp
import org.whispersystems.textsecuregcm.entities.VersionedProfileResponse;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.s3.PolicySigner;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.storage.Account;
@@ -123,6 +126,7 @@ class ProfileControllerTest {
.addProvider(AuthHelper.getAuthFilter())
.addProvider(new PolymorphicAuthValueFactoryProvider.Binder<>(
ImmutableSet.of(AuthenticatedAccount.class, DisabledPermittedAuthenticatedAccount.class)))
.addProvider(new RateLimitExceededExceptionMapper())
.setMapper(SystemMapper.getMapper())
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
.addResource(new ProfileController(
@@ -210,6 +214,7 @@ class ProfileControllerTest {
@AfterEach
void teardown() {
reset(accountsManager);
reset(rateLimiter);
}
@Test
@@ -228,6 +233,20 @@ class ProfileControllerTest {
verify(rateLimiter, times(1)).validate(AuthHelper.VALID_UUID);
}
@Test
void testProfileGetByUuidRateLimited() throws RateLimitExceededException {
doThrow(new RateLimitExceededException(Duration.ofSeconds(13))).when(rateLimiter).validate(AuthHelper.VALID_UUID);
Response response= resources.getJerseyTest()
.target("/v1/profile/" + AuthHelper.VALID_UUID_TWO)
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get();
assertThat(response.getStatus()).isEqualTo(413);
assertThat(response.getHeaderString("Retry-After")).isEqualTo(String.valueOf(Duration.ofSeconds(13).toSeconds()));
}
@Test
void testProfileGetByUuidUnidentified() throws RateLimitExceededException {
BaseProfileResponse profile = resources.getJerseyTest()
@@ -62,6 +62,10 @@ class AccountTest {
private final Device pniIncapableDevice = mock(Device.class);
private final Device pniIncapableExpiredDevice = mock(Device.class);
private final Device storiesCapableDevice = mock(Device.class);
private final Device storiesIncapableDevice = mock(Device.class);
private final Device storiesIncapableExpiredDevice = mock(Device.class);
@BeforeEach
void setup() {
when(oldMasterDevice.getLastSeen()).thenReturn(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(366));
@@ -97,64 +101,76 @@ class AccountTest {
when(gv2IncapableExpiredDevice.isEnabled()).thenReturn(false);
when(gv1MigrationCapableDevice.getCapabilities()).thenReturn(
new DeviceCapabilities(true, true, true, true, true, true, false, false, false, false));
new DeviceCapabilities(true, true, true, true, true, true, false, false, false, false, false));
when(gv1MigrationCapableDevice.isEnabled()).thenReturn(true);
when(gv1MigrationIncapableDevice.getCapabilities()).thenReturn(
new DeviceCapabilities(true, true, true, true, true, false, false, false, false, false));
new DeviceCapabilities(true, true, true, true, true, false, false, false, false, false, false));
when(gv1MigrationIncapableDevice.isEnabled()).thenReturn(true);
when(gv1MigrationIncapableExpiredDevice.getCapabilities()).thenReturn(
new DeviceCapabilities(true, true, true, true, true, false, false, false, false, false));
new DeviceCapabilities(true, true, true, true, true, false, false, false, false, false, false));
when(gv1MigrationIncapableExpiredDevice.isEnabled()).thenReturn(false);
when(senderKeyCapableDevice.getCapabilities()).thenReturn(
new DeviceCapabilities(true, true, true, true, true, true, true, false, false, false));
new DeviceCapabilities(true, true, true, true, true, true, true, false, false, false, false));
when(senderKeyCapableDevice.isEnabled()).thenReturn(true);
when(senderKeyIncapableDevice.getCapabilities()).thenReturn(
new DeviceCapabilities(true, true, true, true, true, true, false, false, false, false));
new DeviceCapabilities(true, true, true, true, true, true, false, false, false, false, false));
when(senderKeyIncapableDevice.isEnabled()).thenReturn(true);
when(senderKeyIncapableExpiredDevice.getCapabilities()).thenReturn(
new DeviceCapabilities(true, true, true, true, true, true, false, false, false, false));
new DeviceCapabilities(true, true, true, true, true, true, false, false, false, false, false));
when(senderKeyIncapableExpiredDevice.isEnabled()).thenReturn(false);
when(announcementGroupCapableDevice.getCapabilities()).thenReturn(
new DeviceCapabilities(true, true, true, true, true, true, true, true, false, false));
new DeviceCapabilities(true, true, true, true, true, true, true, true, false, false, false));
when(announcementGroupCapableDevice.isEnabled()).thenReturn(true);
when(announcementGroupIncapableDevice.getCapabilities()).thenReturn(
new DeviceCapabilities(true, true, true, true, true, true, true, false, false, false));
new DeviceCapabilities(true, true, true, true, true, true, true, false, false, false, false));
when(announcementGroupIncapableDevice.isEnabled()).thenReturn(true);
when(announcementGroupIncapableExpiredDevice.getCapabilities()).thenReturn(
new DeviceCapabilities(true, true, true, true, true, true, true, false, false, false));
new DeviceCapabilities(true, true, true, true, true, true, true, false, false, false, false));
when(announcementGroupIncapableExpiredDevice.isEnabled()).thenReturn(false);
when(changeNumberCapableDevice.getCapabilities()).thenReturn(
new DeviceCapabilities(true, true, true, true, true, true, true, false, true, false));
new DeviceCapabilities(true, true, true, true, true, true, true, false, true, false, false));
when(changeNumberCapableDevice.isEnabled()).thenReturn(true);
when(changeNumberIncapableDevice.getCapabilities()).thenReturn(
new DeviceCapabilities(true, true, true, true, true, true, true, false, false, false));
new DeviceCapabilities(true, true, true, true, true, true, true, false, false, false, false));
when(changeNumberIncapableDevice.isEnabled()).thenReturn(true);
when(changeNumberIncapableExpiredDevice.getCapabilities()).thenReturn(
new DeviceCapabilities(true, true, true, true, true, true, true, false, false, false));
new DeviceCapabilities(true, true, true, true, true, true, true, false, false, false, false));
when(changeNumberIncapableExpiredDevice.isEnabled()).thenReturn(false);
when(pniCapableDevice.getCapabilities()).thenReturn(
new DeviceCapabilities(true, true, true, true, true, true, true, false, false, true));
new DeviceCapabilities(true, true, true, true, true, true, true, false, false, true, false));
when(pniCapableDevice.isEnabled()).thenReturn(true);
when(pniIncapableDevice.getCapabilities()).thenReturn(
new DeviceCapabilities(true, true, true, true, true, true, true, false, false, false));
new DeviceCapabilities(true, true, true, true, true, true, true, false, false, false, false));
when(pniIncapableDevice.isEnabled()).thenReturn(true);
when(pniIncapableExpiredDevice.getCapabilities()).thenReturn(
new DeviceCapabilities(true, true, true, true, true, true, true, false, false, false));
new DeviceCapabilities(true, true, true, true, true, true, true, false, false, false, false));
when(pniIncapableExpiredDevice.isEnabled()).thenReturn(false);
when(storiesCapableDevice.getCapabilities()).thenReturn(
new DeviceCapabilities(true, true, true, true, true, true, true, false, false, false, true));
when(storiesCapableDevice.isEnabled()).thenReturn(true);
when(storiesIncapableDevice.getCapabilities()).thenReturn(
new DeviceCapabilities(true, true, true, true, true, true, true, false, false, false, false));
when(storiesIncapableDevice.isEnabled()).thenReturn(true);
when(storiesIncapableExpiredDevice.getCapabilities()).thenReturn(
new DeviceCapabilities(true, true, true, true, true, true, true, false, false, false, false));
when(storiesIncapableExpiredDevice.isEnabled()).thenReturn(false);
}
@Test
@@ -346,9 +362,25 @@ class AccountTest {
"1234".getBytes(StandardCharsets.UTF_8)).isPniSupported()).isTrue();
}
@Test
void isStoriesSupported() {
assertThat(new Account("+18005551234", UUID.randomUUID(),
UUID.randomUUID(), Set.of(storiesCapableDevice),
"1234".getBytes(StandardCharsets.UTF_8)).isStoriesSupported()).isTrue();
assertThat(new Account("+18005551234", UUID.randomUUID(),
UUID.randomUUID(), Set.of(storiesCapableDevice, storiesIncapableDevice),
"1234".getBytes(StandardCharsets.UTF_8)).isStoriesSupported()).isTrue();
// TODO stories capability
// "1234".getBytes(StandardCharsets.UTF_8)).isStoriesSupported()).isFalse();
assertThat(new Account("+18005551234", UUID.randomUUID(),
UUID.randomUUID(), Set.of(storiesCapableDevice, storiesIncapableExpiredDevice),
"1234".getBytes(StandardCharsets.UTF_8)).isStoriesSupported()).isTrue();
}
@Test
void stale() {
final Account account = new Account("+14151234567", UUID.randomUUID(), UUID.randomUUID(), Collections.emptySet(), new byte[0]);
final Account account = new Account("+14151234567", UUID.randomUUID(), UUID.randomUUID(), Collections.emptySet(),
new byte[0]);
assertDoesNotThrow(account::getNumber);
@@ -157,13 +157,12 @@ public class AccountsHelper {
when(updatedAccount.isPniSupported()).thenAnswer(stubbing);
break;
}
case "getEnabledDeviceCount": {
when(updatedAccount.getEnabledDeviceCount()).thenAnswer(stubbing);
case "isStoriesSupported": {
when(updatedAccount.isStoriesSupported()).thenAnswer(stubbing);
break;
}
case "getRelay": {
// TODO unused
when(updatedAccount.getRelay()).thenAnswer(stubbing);
case "getEnabledDeviceCount": {
when(updatedAccount.getEnabledDeviceCount()).thenAnswer(stubbing);
break;
}
case "getRegistrationLock": {
@@ -44,7 +44,12 @@ public class AuthHelper {
public static final UUID VALID_UUID_TWO = UUID.randomUUID();
public static final String VALID_PASSWORD_TWO = "baz";
public static final String INVALID_NUMBER = "+14151111111";
public static final String VALID_NUMBER_3 = "+14445556666";
public static final UUID VALID_UUID_3 = UUID.randomUUID();
public static final UUID VALID_PNI_3 = UUID.randomUUID();
public static final String VALID_PASSWORD_3_PRIMARY = "3primary";
public static final String VALID_PASSWORD_3_LINKED = "3linked";
public static final UUID INVALID_UUID = UUID.randomUUID();
public static final String INVALID_PASSWORD = "bar";
@@ -63,25 +68,34 @@ public class AuthHelper {
public static Account VALID_ACCOUNT_TWO = mock(Account.class );
public static Account DISABLED_ACCOUNT = mock(Account.class );
public static Account UNDISCOVERABLE_ACCOUNT = mock(Account.class );
public static Account VALID_ACCOUNT_3 = mock(Account.class );
public static Device VALID_DEVICE = mock(Device.class);
public static Device VALID_DEVICE_TWO = mock(Device.class);
public static Device DISABLED_DEVICE = mock(Device.class);
public static Device UNDISCOVERABLE_DEVICE = mock(Device.class);
public static Device VALID_DEVICE = mock(Device.class);
public static Device VALID_DEVICE_TWO = mock(Device.class);
public static Device DISABLED_DEVICE = mock(Device.class);
public static Device UNDISCOVERABLE_DEVICE = mock(Device.class);
public static Device VALID_DEVICE_3_PRIMARY = mock(Device.class);
public static Device VALID_DEVICE_3_LINKED = mock(Device.class);
private static AuthenticationCredentials VALID_CREDENTIALS = mock(AuthenticationCredentials.class);
private static AuthenticationCredentials VALID_CREDENTIALS_TWO = mock(AuthenticationCredentials.class);
private static AuthenticationCredentials DISABLED_CREDENTIALS = mock(AuthenticationCredentials.class);
private static AuthenticationCredentials UNDISCOVERABLE_CREDENTIALS = mock(AuthenticationCredentials.class);
private static AuthenticationCredentials VALID_CREDENTIALS = mock(AuthenticationCredentials.class);
private static AuthenticationCredentials VALID_CREDENTIALS_TWO = mock(AuthenticationCredentials.class);
private static AuthenticationCredentials VALID_CREDENTIALS_3_PRIMARY = mock(AuthenticationCredentials.class);
private static AuthenticationCredentials VALID_CREDENTIALS_3_LINKED = mock(AuthenticationCredentials.class);
private static AuthenticationCredentials DISABLED_CREDENTIALS = mock(AuthenticationCredentials.class);
private static AuthenticationCredentials UNDISCOVERABLE_CREDENTIALS = mock(AuthenticationCredentials.class);
public static PolymorphicAuthDynamicFeature<? extends Principal> getAuthFilter() {
when(VALID_CREDENTIALS.verify("foo")).thenReturn(true);
when(VALID_CREDENTIALS_TWO.verify("baz")).thenReturn(true);
when(VALID_CREDENTIALS_3_PRIMARY.verify(VALID_PASSWORD_3_PRIMARY)).thenReturn(true);
when(VALID_CREDENTIALS_3_LINKED.verify(VALID_PASSWORD_3_LINKED)).thenReturn(true);
when(DISABLED_CREDENTIALS.verify(DISABLED_PASSWORD)).thenReturn(true);
when(UNDISCOVERABLE_CREDENTIALS.verify(UNDISCOVERABLE_PASSWORD)).thenReturn(true);
when(VALID_DEVICE.getAuthenticationCredentials()).thenReturn(VALID_CREDENTIALS);
when(VALID_DEVICE_TWO.getAuthenticationCredentials()).thenReturn(VALID_CREDENTIALS_TWO);
when(VALID_DEVICE_3_PRIMARY.getAuthenticationCredentials()).thenReturn(VALID_CREDENTIALS_3_PRIMARY);
when(VALID_DEVICE_3_LINKED.getAuthenticationCredentials()).thenReturn(VALID_CREDENTIALS_3_LINKED);
when(DISABLED_DEVICE.getAuthenticationCredentials()).thenReturn(DISABLED_CREDENTIALS);
when(UNDISCOVERABLE_DEVICE.getAuthenticationCredentials()).thenReturn(UNDISCOVERABLE_CREDENTIALS);
@@ -89,16 +103,22 @@ public class AuthHelper {
when(VALID_DEVICE_TWO.isMaster()).thenReturn(true);
when(DISABLED_DEVICE.isMaster()).thenReturn(true);
when(UNDISCOVERABLE_DEVICE.isMaster()).thenReturn(true);
when(VALID_DEVICE_3_PRIMARY.isMaster()).thenReturn(true);
when(VALID_DEVICE_3_LINKED.isMaster()).thenReturn(false);
when(VALID_DEVICE.getId()).thenReturn(1L);
when(VALID_DEVICE_TWO.getId()).thenReturn(1L);
when(DISABLED_DEVICE.getId()).thenReturn(1L);
when(UNDISCOVERABLE_DEVICE.getId()).thenReturn(1L);
when(VALID_DEVICE_3_PRIMARY.getId()).thenReturn(1L);
when(VALID_DEVICE_3_LINKED.getId()).thenReturn(2L);
when(VALID_DEVICE.isEnabled()).thenReturn(true);
when(VALID_DEVICE_TWO.isEnabled()).thenReturn(true);
when(DISABLED_DEVICE.isEnabled()).thenReturn(false);
when(UNDISCOVERABLE_DEVICE.isMaster()).thenReturn(true);
when(VALID_DEVICE_3_PRIMARY.isEnabled()).thenReturn(true);
when(VALID_DEVICE_3_LINKED.isEnabled()).thenReturn(true);
when(VALID_ACCOUNT.getDevice(1L)).thenReturn(Optional.of(VALID_DEVICE));
when(VALID_ACCOUNT.getMasterDevice()).thenReturn(Optional.of(VALID_DEVICE));
@@ -108,6 +128,9 @@ public class AuthHelper {
when(DISABLED_ACCOUNT.getMasterDevice()).thenReturn(Optional.of(DISABLED_DEVICE));
when(UNDISCOVERABLE_ACCOUNT.getDevice(eq(1L))).thenReturn(Optional.of(UNDISCOVERABLE_DEVICE));
when(UNDISCOVERABLE_ACCOUNT.getMasterDevice()).thenReturn(Optional.of(UNDISCOVERABLE_DEVICE));
when(VALID_ACCOUNT_3.getDevice(1L)).thenReturn(Optional.of(VALID_DEVICE_3_PRIMARY));
when(VALID_ACCOUNT_3.getMasterDevice()).thenReturn(Optional.of(VALID_DEVICE_3_PRIMARY));
when(VALID_ACCOUNT_3.getDevice(2L)).thenReturn(Optional.of(VALID_DEVICE_3_LINKED));
when(VALID_ACCOUNT_TWO.getEnabledDeviceCount()).thenReturn(6);
@@ -120,20 +143,21 @@ public class AuthHelper {
when(DISABLED_ACCOUNT.getUuid()).thenReturn(DISABLED_UUID);
when(UNDISCOVERABLE_ACCOUNT.getNumber()).thenReturn(UNDISCOVERABLE_NUMBER);
when(UNDISCOVERABLE_ACCOUNT.getUuid()).thenReturn(UNDISCOVERABLE_UUID);
when(VALID_ACCOUNT.getRelay()).thenReturn(Optional.empty());
when(VALID_ACCOUNT_TWO.getRelay()).thenReturn(Optional.empty());
when(UNDISCOVERABLE_ACCOUNT.getRelay()).thenReturn(Optional.empty());
when(VALID_ACCOUNT_3.getNumber()).thenReturn(VALID_NUMBER_3);
when(VALID_ACCOUNT_3.getUuid()).thenReturn(VALID_UUID_3);
when(VALID_ACCOUNT_3.getPhoneNumberIdentifier()).thenReturn(VALID_PNI_3);
when(VALID_ACCOUNT.isEnabled()).thenReturn(true);
when(VALID_ACCOUNT_TWO.isEnabled()).thenReturn(true);
when(DISABLED_ACCOUNT.isEnabled()).thenReturn(false);
when(UNDISCOVERABLE_ACCOUNT.isEnabled()).thenReturn(true);
when(VALID_ACCOUNT_3.isEnabled()).thenReturn(true);
when(VALID_ACCOUNT.isDiscoverableByPhoneNumber()).thenReturn(true);
when(VALID_ACCOUNT_TWO.isDiscoverableByPhoneNumber()).thenReturn(true);
when(DISABLED_ACCOUNT.isDiscoverableByPhoneNumber()).thenReturn(true);
when(UNDISCOVERABLE_ACCOUNT.isDiscoverableByPhoneNumber()).thenReturn(false);
when(VALID_ACCOUNT_3.isDiscoverableByPhoneNumber()).thenReturn(true);
when(VALID_ACCOUNT.getIdentityKey()).thenReturn(VALID_IDENTITY);
@@ -152,6 +176,10 @@ public class AuthHelper {
when(ACCOUNTS_MANAGER.getByE164(UNDISCOVERABLE_NUMBER)).thenReturn(Optional.of(UNDISCOVERABLE_ACCOUNT));
when(ACCOUNTS_MANAGER.getByAccountIdentifier(UNDISCOVERABLE_UUID)).thenReturn(Optional.of(UNDISCOVERABLE_ACCOUNT));
when(ACCOUNTS_MANAGER.getByE164(VALID_NUMBER_3)).thenReturn(Optional.of(VALID_ACCOUNT_3));
when(ACCOUNTS_MANAGER.getByAccountIdentifier(VALID_UUID_3)).thenReturn(Optional.of(VALID_ACCOUNT_3));
when(ACCOUNTS_MANAGER.getByPhoneNumberIdentifier(VALID_PNI_3)).thenReturn(Optional.of(VALID_ACCOUNT_3));
AccountsHelper.setupMockUpdateForAuthHelper(ACCOUNTS_MANAGER);
for (TestAccount testAccount : TEST_ACCOUNTS) {
@@ -167,6 +195,10 @@ public class AuthHelper {
DisabledPermittedAuthenticatedAccount.class, disabledPermittedAccountAuthFilter));
}
public static String getAuthHeader(UUID uuid, long deviceId, String password) {
return getAuthHeader(uuid.toString() + "." + deviceId, password);
}
public static String getAuthHeader(UUID uuid, String password) {
return getAuthHeader(uuid.toString(), password);
}
@@ -221,7 +253,6 @@ public class AuthHelper {
when(account.getMasterDevice()).thenReturn(Optional.of(device));
when(account.getNumber()).thenReturn(number);
when(account.getUuid()).thenReturn(uuid);
when(account.getRelay()).thenReturn(Optional.empty());
when(account.isEnabled()).thenReturn(true);
when(accountsManager.getByE164(number)).thenReturn(Optional.of(account));
when(accountsManager.getByAccountIdentifier(uuid)).thenReturn(Optional.of(account));
@@ -0,0 +1,46 @@
package org.whispersystems.textsecuregcm.util;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
public class WeightedRandomSelectTest {
@Test
public void test5050() {
final WeightedRandomSelect<String> selector = new WeightedRandomSelect<>(
List.of(new Pair<>("a", 1L), new Pair<>("b", 1L)));
final Map<String, Long> counts = Stream.generate(selector::select)
.limit(1000)
.collect(Collectors.groupingBy(s -> s, Collectors.counting()));
assertThat(counts.get("a")).isGreaterThan(1);
assertThat(counts.get("b")).isGreaterThan(1);
}
@Test
public void testAlways() {
final WeightedRandomSelect<String> selector = new WeightedRandomSelect<>(
List.of(new Pair<>("a", 1L), new Pair<>("b", 0L)));
final Map<String, Long> counts = Stream.generate(selector::select)
.limit(1000)
.collect(Collectors.groupingBy(s -> s, Collectors.counting()));
assertThat(counts.get("a")).isEqualTo(1000);
assertThat(counts).doesNotContainKey("b");
}
@Test
public void testThree() {
final WeightedRandomSelect<String> selector = new WeightedRandomSelect<>(
List.of(new Pair<>("a", 33L), new Pair<>("b", 33L), new Pair<>("c", 33L)));
final Map<String, Long> counts = Stream.generate(selector::select)
.limit(1000)
.collect(Collectors.groupingBy(s -> s, Collectors.counting()));
assertThat(counts.get("a")).isGreaterThan(1);
assertThat(counts.get("b")).isGreaterThan(1);
assertThat(counts.get("c")).isGreaterThan(1);
}
}
@@ -0,0 +1,10 @@
{
"messages": [
{
"type": 5,
"destinationDeviceId": 1,
"body": "Zm9vYmFyego",
"timestamp": 1234
}
]
}