Compare commits

...
Author SHA1 Message Date
Ravi Khadiwala 794e254d90 Add null check to FCM error log condition 2025-02-07 13:48:36 -06:00
Ravi Khadiwala 760c5737f9 Add field to RestoreAccountRequest for device transfer initialization 2025-02-07 13:43:57 -06:00
Jonathan Klabunde Tomer ea17eee320 Make logging of message delivery loops configurable, default off 2025-02-07 13:43:28 -06:00
Adel Lahlou 09ce79bd43 Remove /v1/calling/relays API endpoint 2025-02-07 13:41:59 -06:00
Chris Eager 2dfd17af4a Add counter with WebSocket close codes 2025-02-07 13:41:37 -06:00
Ravi Khadiwala a9975e524b Add logs to FCM quota failures 2025-02-07 13:41:14 -06:00
Jonathan Klabunde Tomer 5d062285c2 Filter to block old REST API for specified client versions 2025-02-05 12:26:47 -08:00
Chris Eager e4b0f3ced5 Use HTTP status code if FCM error code is unavailable 2025-02-05 14:17:05 -06:00
Jon Chambers 6545bb9edb Update to the latest version of the spam filter 2025-01-31 12:58:16 -05:00
Jon Chambers 70ce6eff9e Include ephemeral flag in individual messages 2025-01-31 12:57:54 -05:00
Chris Eager c84d96abee Remove deprecated svr3Credentials field 2025-01-31 11:57:15 -06:00
Chris Eager 09eb42e5c6 Add tag for requests made with libsignal 2025-01-31 11:56:56 -06:00
Chris Eager 06388b514c Add timeout to GitHub test action 2025-01-31 11:56:39 -06:00
Jon Chambers 7c17a4067c Update to the latest version of the spam filter 2025-01-31 10:34:14 -05:00
Jon Chambers 48ada8e8ca Clarify roles/responsibilities of components in the message-handling pathway 2025-01-31 10:24:50 -05:00
Ravi Khadiwala 282bcf6f34 Add persistent timer utility backed by redis 2025-01-29 11:32:13 -06:00
Ravi Khadiwala 1446d1acf8 Fix blocking call in waitForLinkedDevice 2025-01-29 11:32:13 -06:00
Ravi Khadiwala aae94ffae3 Add a timer to waitForTransferArchive 2025-01-29 11:32:13 -06:00
Ameya Lokare ebd906a45d Update to the latest version of the spam filter 2025-01-28 12:21:09 -08:00
Ravi Khadiwala e30beb9c9f Remove ZeroTtlDevicePushNotificationExperiment 2025-01-27 16:24:50 -06:00
Ravi Khadiwala 5a2e297991 Add ZeroTtlDevicePushNotificationExperiment 2025-01-27 12:58:28 -06:00
adel-signal ae1e7fbaa0 Return empty lists instead of null in GetCallingRelaysV2 2025-01-24 17:33:45 -05:00
adel-signal 7e616a4056 Update calling routing to return urls only, no instance IPs 2025-01-24 13:46:32 -05:00
Chris Eager c9e192564c Add fail-fast HMAC init to RegistrationServiceClient constructor 2025-01-22 18:20:45 -06:00
Chris Eager 47550d48e7 Add collation key to registration service session creation rpc call 2025-01-22 17:43:53 -06:00
Chris Eager 5cc76f48aa Add CoinGecko to CurrencyConversionManager 2025-01-19 09:37:38 -06:00
Katherine 3ceaa8bd20 Remove authentication via query parameters for websocket upgrade requests 2025-01-15 14:06:46 -05:00
Ameya Lokare 790b9bbf01 Update to the latest version of the spam filter 2025-01-14 12:38:44 -08:00
ravi-signal ee1016523f Add request information to createPayPalOneTimePayment failure log 2025-01-14 09:45:22 -05:00
Katherine 2f51778421 Use camel casing for entry position field on key transparency monitor requests 2025-01-14 09:45:08 -05:00
Katherine Yen d3d68c2a60 Enforce one entry position per identifier in monitor request 2025-01-10 10:06:31 -05:00
Jon Chambers 0628b3e41c Update chat service dependencies 2025-01-10 10:04:40 -05:00
Jon Chambers eac183495a Update deployment Docker image 2025-01-10 10:04:40 -05:00
Jon Chambers 0ae02da9be Update GitHub Actions versions 2025-01-10 10:04:40 -05:00
Jon Chambers 90fe634ddd Update to the latest version of Maven 2025-01-10 10:04:40 -05:00
Ravi Khadiwala 1cae841ed6 Remove deprecated /v1/accounts/turn 2025-01-10 10:04:25 -05:00
113 changed files with 2948 additions and 2651 deletions

No files matched your search

+2 -2
View File
@@ -11,8 +11,8 @@ jobs:
contents: write
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
- uses: actions/setup-java@99b8673ff64fbf99d8d325f52d9a5bdedb8483e9 # v4.2.1
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- uses: actions/setup-java@7a6d8a8234af8eb26422e24e3006232cccaa061b # v4.6.0
with:
distribution: 'temurin'
java-version: '21'
+3 -3
View File
@@ -13,13 +13,13 @@ jobs:
id-token: write
contents: read
steps:
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
- uses: actions/setup-java@99b8673ff64fbf99d8d325f52d9a5bdedb8483e9 # v4.2.1
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- uses: actions/setup-java@7a6d8a8234af8eb26422e24e3006232cccaa061b # v4.6.0
with:
distribution: 'temurin'
java-version: '21'
cache: 'maven'
- uses: aws-actions/configure-aws-credentials@5579c002bb4778aa43395ef1df492868a9a1c83f # v4.0.2
- uses: aws-actions/configure-aws-credentials@e3dd6a429d7300a6a4c196c26e071d42e0343502 # v4.0.2
name: Configure AWS credentials from Test account
with:
role-to-assume: ${{ vars.AWS_ROLE }}
+3 -2
View File
@@ -9,11 +9,12 @@ jobs:
build:
runs-on: ubuntu-latest
container: ubuntu:22.04
timeout-minutes: 20
steps:
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- name: Set up JDK 21
uses: actions/setup-java@99b8673ff64fbf99d8d325f52d9a5bdedb8483e9 # v4.2.1
uses: actions/setup-java@7a6d8a8234af8eb26422e24e3006232cccaa061b # v4.6.0
with:
distribution: 'temurin'
java-version: 21
+2 -2
View File
@@ -14,7 +14,7 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.8/apache-maven-3.9.8-bin.zip
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.2/maven-wrapper-3.3.2.jar
distributionSha256Sum=8351955a9acf2f83c136c4eee0f6db894ab6265fdbe0a94b32a380307dbaa3e1
distributionSha256Sum=4ec3f26fb1a692473aea0235c300bd20f0f9fe741947c82c1234cefd76ac3a3c
wrapperSha256Sum=3d8f20ce6103913be8b52aef6d994e0c54705fb527324ceb9b835b338739c7a8
+18 -19
View File
@@ -37,45 +37,44 @@
</modules>
<properties>
<aws.sdk2.version>2.29.7</aws.sdk2.version>
<aws.sdk2.version>2.29.48</aws.sdk2.version>
<braintree.version>3.37.0</braintree.version>
<commons-csv.version>1.12.0</commons-csv.version>
<commons-io.version>2.17.0</commons-io.version>
<dropwizard.version>4.0.10</dropwizard.version>
<commons-io.version>2.18.0</commons-io.version>
<dropwizard.version>4.0.11</dropwizard.version>
<dropwizard-metrics-datadog.version>1.1.13</dropwizard-metrics-datadog.version>
<!-- can be updated to latest version with Dropwizard 5 (Jetty 12); will then need to disable telemetry -->
<dynamodblocal.version>2.2.1</dynamodblocal.version>
<google-cloud-libraries.version>26.50.0</google-cloud-libraries.version>
<grpc.version>1.61.1</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
<google-cloud-libraries.version>26.52.0</google-cloud-libraries.version>
<grpc.version>1.69.0</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
<gson.version>2.11.0</gson.version>
<!-- several libraries (AWS, Google Cloud) use Apache http components transitively, and we need to align them -->
<httpcore.version>4.4.16</httpcore.version>
<httpclient.version>4.5.14</httpclient.version>
<jackson.version>2.18.1</jackson.version>
<jackson.version>2.18.2</jackson.version>
<jaxb.version>2.3.1</jaxb.version>
<junit-pioneer.version>2.3.0</junit-pioneer.version>
<jsr305.version>3.0.2</jsr305.version>
<kotlin.version>1.9.24</kotlin.version>
<kotlinx-serialization.version>1.5.1</kotlinx-serialization.version>
<kotlin.version>1.9.25</kotlin.version>
<lettuce.version>6.5.1.RELEASE</lettuce.version>
<libphonenumber.version>8.13.50</libphonenumber.version>
<libphonenumber.version>8.13.52</libphonenumber.version>
<logstash.logback.version>7.3</logstash.logback.version>
<log4j-bom.version>2.23.1</log4j-bom.version>
<luajava.version>3.4.0</luajava.version>
<micrometer.version>1.13.6</micrometer.version>
<netty.version>4.1.111.Final</netty.version>
<log4j-bom.version>2.24.3</log4j-bom.version>
<luajava.version>3.5.0</luajava.version>
<micrometer.version>1.14.2</micrometer.version>
<netty.version>4.1.116.Final</netty.version>
<protobuf.version>3.25.5</protobuf.version> <!-- must be greater than or equal to the value from Google libraries-bom, see https://protobuf.dev/support/cross-version-runtime-guarantee/ -->
<pushy.version>0.15.4</pushy.version>
<reactive.grpc.version>1.2.4</reactive.grpc.version>
<reactor-bom.version>2023.0.11</reactor-bom.version> <!-- 3.6.x, see https://github.com/reactor/reactor#bom-versioning-scheme -->
<reactor-bom.version>2024.0.1</reactor-bom.version> <!-- 3.7.1, see https://github.com/reactor/reactor#bom-versioning-scheme -->
<resilience4j.version>2.2.0</resilience4j.version>
<semver4j.version>3.1.0</semver4j.version>
<slf4j.version>2.0.13</slf4j.version>
<slf4j.version>2.0.16</slf4j.version>
<stripe.version>23.10.0</stripe.version>
<swagger.version>2.2.25</swagger.version>
<swagger.version>2.2.27</swagger.version>
<!-- 21.0.4_7-jre-jammy (note: always use the multi-arch manifest *LIST* here) -->
<docker.image.sha256>870aae69d4521fdaf26e952f8026f75b37cb721e6302d4d4d7100f6b09823057</docker.image.sha256>
<!-- eclipse-temurin:21.0.5_11-jre-jammy (note: always use the multi-arch manifest *LIST* here) -->
<docker.image.sha256>5f8358c9d5615c18e95728e8b8528bda7ff40a7a5da2ac9a35b7a01f5d9b231a</docker.image.sha256>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
@@ -511,7 +510,7 @@
<rules>
<dependencyConvergence/>
<requireMavenVersion>
<version>3.8.6</version>
<version>3.9.9</version>
</requireMavenVersion>
</rules>
</configuration>
+3 -1
View File
@@ -87,11 +87,13 @@ backupsZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijkl
paymentsService.userAuthenticationTokenSharedSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= # base64-encoded 32-byte secret shared with MobileCoin services used to generate auth tokens for Signal users
paymentsService.fixerApiKey: unset
paymentsService.coinMarketCapApiKey: unset
paymentsService.coinGeckoApiKey: unset
currentReportingKey.secret: AAAAAAAAAAA=
currentReportingKey.salt: AAAAAAAAAAA=
registrationService.collationKeySalt: AAAAAAAAAAA=
turn.secret: AAAAAAAAAAA=
turn.cloudflare.apiToken: ABCDEFGHIJKLM
+4 -3
View File
@@ -327,9 +327,9 @@ paymentsService:
- MOB
externalClients:
fixerApiKey: secret://paymentsService.fixerApiKey
coinMarketCapApiKey: secret://paymentsService.coinMarketCapApiKey
coinMarketCapCurrencyIds:
MOB: 7878
coinGeckoApiKey: secret://paymentsService.coinGeckoApiKey
coinGeckoCurrencyIds:
MOB: mobilecoin
badges:
badges:
@@ -399,6 +399,7 @@ registrationService:
"example": "example"
}
identityTokenAudience: https://registration.example.com
collationKeySalt: secret://registrationService.collationKeySalt
registrationCaCertificate: | # Registration service TLS certificate trust root
-----BEGIN CERTIFICATE-----
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
+9 -9
View File
@@ -11,11 +11,11 @@
<artifactId>service</artifactId>
<properties>
<firebase-admin.version>9.4.1</firebase-admin.version>
<firebase-admin.version>9.4.2</firebase-admin.version>
<java-uuid-generator.version>5.1.0</java-uuid-generator.version>
<google-androidpublisher.version>v3-rev20241016-2.0.0</google-androidpublisher.version>
<google-androidpublisher.version>v3-rev20250102-2.0.0</google-androidpublisher.version>
<storekit.version>3.2.0</storekit.version>
<webauthn4j.version>0.28.0.RELEASE</webauthn4j.version>
<webauthn4j.version>0.28.4.RELEASE</webauthn4j.version>
</properties>
<dependencies>
@@ -229,13 +229,13 @@
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.26.0</version>
<version>1.27.1</version>
</dependency>
<dependency>
<groupId>com.maxmind.geoip2</groupId>
<artifactId>geoip2</artifactId>
<version>4.2.0</version>
<version>4.2.1</version>
</dependency>
<dependency>
@@ -251,13 +251,13 @@
<dependency>
<groupId>io.opentelemetry.semconv</groupId>
<artifactId>opentelemetry-semconv</artifactId>
<version>1.25.0-alpha</version>
<version>1.27.0-alpha</version>
</dependency>
<!-- resolve opentelemetry-semconv conflict from lower in firebase-admin dependency tree -->
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-firestore</artifactId>
<version>3.28.0</version>
<version>3.30.2</version>
<exclusions>
<exclusion>
<groupId>io.opentelemetry.semconv</groupId>
@@ -368,7 +368,7 @@
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>dynamodb-lock-client</artifactId>
<version>1.2.0</version>
<version>1.3.0</version>
</dependency>
<dependency>
@@ -410,7 +410,7 @@
<dependency>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>geocoder</artifactId>
<version>2.234</version>
<version>2.246</version>
</dependency>
<dependency>
@@ -336,6 +336,9 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private KeyTransparencyServiceConfiguration keyTransparencyService;
@JsonProperty
private boolean logMessageDeliveryLoops;
public TlsKeyStoreConfiguration getTlsKeyStoreConfiguration() {
return tlsKeyStore;
}
@@ -558,4 +561,9 @@ public class WhisperServerConfiguration extends Configuration {
public KeyTransparencyServiceConfiguration getKeyTransparencyServiceConfiguration() {
return keyTransparencyService;
}
public boolean logMessageDeliveryLoops() {
return logMessageDeliveryLoops;
}
}
@@ -110,7 +110,6 @@ import org.whispersystems.textsecuregcm.controllers.AccountControllerV2;
import org.whispersystems.textsecuregcm.controllers.ArchiveController;
import org.whispersystems.textsecuregcm.controllers.AttachmentControllerV4;
import org.whispersystems.textsecuregcm.controllers.CallLinkController;
import org.whispersystems.textsecuregcm.controllers.CallRoutingController;
import org.whispersystems.textsecuregcm.controllers.CallRoutingControllerV2;
import org.whispersystems.textsecuregcm.controllers.CertificateController;
import org.whispersystems.textsecuregcm.controllers.ChallengeController;
@@ -133,7 +132,7 @@ import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery2Controll
import org.whispersystems.textsecuregcm.controllers.StickerController;
import org.whispersystems.textsecuregcm.controllers.SubscriptionController;
import org.whispersystems.textsecuregcm.controllers.VerificationController;
import org.whispersystems.textsecuregcm.currency.CoinMarketCapClient;
import org.whispersystems.textsecuregcm.currency.CoinGeckoClient;
import org.whispersystems.textsecuregcm.currency.CurrencyConversionManager;
import org.whispersystems.textsecuregcm.currency.FixerClient;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
@@ -141,6 +140,7 @@ import org.whispersystems.textsecuregcm.filters.ExternalRequestFilter;
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
import org.whispersystems.textsecuregcm.filters.RemoteDeprecationFilter;
import org.whispersystems.textsecuregcm.filters.RequestStatisticsFilter;
import org.whispersystems.textsecuregcm.filters.RestDeprecationFilter;
import org.whispersystems.textsecuregcm.filters.TimestampResponseFilter;
import org.whispersystems.textsecuregcm.geo.MaxMindDatabaseManager;
import org.whispersystems.textsecuregcm.grpc.AccountsAnonymousGrpcService;
@@ -164,10 +164,12 @@ import org.whispersystems.textsecuregcm.jetty.JettyHttpConfigurationCustomizer;
import org.whispersystems.textsecuregcm.keytransparency.KeyTransparencyServiceClient;
import org.whispersystems.textsecuregcm.limits.CardinalityEstimator;
import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor;
import org.whispersystems.textsecuregcm.limits.NoopMessageDeliveryLoopMonitor;
import org.whispersystems.textsecuregcm.limits.PushChallengeManager;
import org.whispersystems.textsecuregcm.limits.RateLimitByIpFilter;
import org.whispersystems.textsecuregcm.limits.RateLimitChallengeManager;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.limits.RedisMessageDeliveryLoopMonitor;
import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.DeviceLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.GrpcStatusRuntimeExceptionMapper;
@@ -227,6 +229,7 @@ import org.whispersystems.textsecuregcm.storage.MessagesCache;
import org.whispersystems.textsecuregcm.storage.MessagesDynamoDb;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
import org.whispersystems.textsecuregcm.storage.PersistentTimer;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.Profiles;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
@@ -331,6 +334,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
bootstrap.addCommand(new BackupMetricsCommand(Clock.systemUTC()));
bootstrap.addCommand(new RemoveExpiredLinkedDevicesCommand());
bootstrap.addCommand(new NotifyIdleDevicesCommand());
bootstrap.addCommand(new ProcessScheduledJobsServiceCommand("process-idle-device-notification-jobs",
"Processes scheduled jobs to send notifications to idle devices",
new IdleDeviceNotificationSchedulerFactory()));
@@ -429,7 +433,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getDynamoDbTables().getRemoteConfig().getTableName());
PushChallengeDynamoDb pushChallengeDynamoDb = new PushChallengeDynamoDb(dynamoDbClient,
config.getDynamoDbTables().getPushChallenge().getTableName());
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbClient,
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
config.getDynamoDbTables().getReportMessage().getTableName(),
config.getReportMessageConfiguration().getReportTtl());
RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
@@ -616,7 +620,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster,
config.getReportMessageConfiguration().getCounterTtl());
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager,
messageDeletionAsyncExecutor);
messageDeletionAsyncExecutor, Clock.systemUTC());
AccountLockManager accountLockManager = new AccountLockManager(dynamoDbClient,
config.getDynamoDbTables().getDeletedAccountsLock().getTableName());
ClientPublicKeysManager clientPublicKeysManager =
@@ -653,7 +657,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
Subscriptions subscriptions = new Subscriptions(
config.getDynamoDbTables().getSubscriptions().getTableName(), dynamoDbAsyncClient);
MessageDeliveryLoopMonitor messageDeliveryLoopMonitor =
new MessageDeliveryLoopMonitor(rateLimitersCluster);
config.logMessageDeliveryLoops() ? new RedisMessageDeliveryLoopMonitor(rateLimitersCluster) : new NoopMessageDeliveryLoopMonitor();
disconnectionRequestManager.addListener(webSocketConnectionEventManager);
@@ -669,8 +673,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final MessageSender messageSender = new MessageSender(messagesManager, pushNotificationManager);
final ReceiptSender receiptSender = new ReceiptSender(accountsManager, messageSender, receiptSenderExecutor);
final TurnTokenGenerator turnTokenGenerator = new TurnTokenGenerator(dynamicConfigurationManager,
config.getTurnConfiguration().secret().value());
final TurnTokenGenerator turnTokenGenerator = new TurnTokenGenerator(config.getTurnConfiguration().secret().value());
final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager = new CloudflareTurnCredentialsManager(
config.getTurnConfiguration().cloudflare().apiToken().value(),
config.getTurnConfiguration().cloudflare().endpoint(),
@@ -699,9 +702,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
HttpClient currencyClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2).connectTimeout(Duration.ofSeconds(10)).build();
FixerClient fixerClient = config.getPaymentsServiceConfiguration().externalClients()
.buildFixerClient(currencyClient);
CoinMarketCapClient coinMarketCapClient = config.getPaymentsServiceConfiguration().externalClients()
.buildCoinMarketCapClient(currencyClient);
CurrencyConversionManager currencyManager = new CurrencyConversionManager(fixerClient, coinMarketCapClient,
CoinGeckoClient coinGeckoClient = config.getPaymentsServiceConfiguration().externalClients()
.buildCoinGeckoClient(currencyClient);
CurrencyConversionManager currencyManager = new CurrencyConversionManager(fixerClient, coinGeckoClient,
cacheCluster, config.getPaymentsServiceConfiguration().paymentCurrencies(), recurringJobExecutor, Clock.systemUTC());
VirtualThreadPinEventMonitor virtualThreadPinEventMonitor = new VirtualThreadPinEventMonitor(
virtualThreadEventLoggerExecutor,
@@ -1000,7 +1003,12 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
metricsHttpChannelListener.configure(environment);
final MessageMetrics messageMetrics = new MessageMetrics();
// BufferingInterceptor is needed on the base environment but not the WebSocketEnvironment,
// because we handle serialization of http responses on the websocket on our own and can
// compute content lengths without it
environment.jersey().register(new BufferingInterceptor());
environment.jersey().register(new RestDeprecationFilter(dynamicConfigurationManager, experimentEnrollmentManager));
environment.jersey().register(new VirtualExecutorServiceProvider("managed-async-virtual-thread-"));
environment.jersey().register(new RateLimitByIpFilter(rateLimiters));
environment.jersey().register(new RequestStatisticsFilter(TrafficSource.HTTP));
@@ -1097,25 +1105,25 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
log.info("Registered spam filter: {}", filter.getClass().getName());
});
final PersistentTimer persistentTimer = new PersistentTimer(rateLimitersCluster, clock);
final PhoneVerificationTokenManager phoneVerificationTokenManager = new PhoneVerificationTokenManager(
phoneNumberIdentifiers, registrationServiceClient, registrationRecoveryPasswordsManager, registrationRecoveryChecker);
final List<Object> commonControllers = Lists.newArrayList(
new AccountController(accountsManager, rateLimiters, turnTokenGenerator, registrationRecoveryPasswordsManager,
new AccountController(accountsManager, rateLimiters, registrationRecoveryPasswordsManager,
usernameHashZkProofVerifier),
new AccountControllerV2(accountsManager, changeNumberManager, phoneVerificationTokenManager,
registrationLockVerificationManager, rateLimiters),
new AttachmentControllerV4(rateLimiters, gcsAttachmentGenerator, tusAttachmentGenerator,
experimentEnrollmentManager),
new ArchiveController(backupAuthManager, backupManager),
new CallRoutingController(rateLimiters, callRouter, turnTokenGenerator, experimentEnrollmentManager, cloudflareTurnCredentialsManager),
new CallRoutingControllerV2(rateLimiters, callRouter, turnTokenGenerator, experimentEnrollmentManager, cloudflareTurnCredentialsManager),
new CallLinkController(rateLimiters, callingGenericZkSecretParams),
new CertificateController(new CertificateGenerator(config.getDeliveryCertificate().certificate().value(),
config.getDeliveryCertificate().ecPrivateKey(), config.getDeliveryCertificate().expiresDays()),
zkAuthOperations, callingGenericZkSecretParams, clock),
new ChallengeController(rateLimitChallengeManager, challengeConstraintChecker),
new DeviceController(accountsManager, clientPublicKeysManager, rateLimiters, config.getMaxDevices()),
new DeviceController(accountsManager, clientPublicKeysManager, rateLimiters, persistentTimer, config.getMaxDevices()),
new DeviceCheckController(clock, backupAuthManager, appleDeviceCheckManager, rateLimiters,
config.getDeviceCheck().backupRedemptionLevel(),
config.getDeviceCheck().backupRedemptionDuration()),
@@ -1126,7 +1134,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new KeyTransparencyController(keyTransparencyServiceClient),
new MessageController(rateLimiters, messageByteLimitCardinalityEstimator, messageSender, receiptSender,
accountsManager, messagesManager, phoneNumberIdentifiers, pushNotificationManager, pushNotificationScheduler,
reportMessageManager, multiRecipientMessageExecutor, messageDeliveryScheduler, clientReleaseManager,
reportMessageManager, messageDeliveryScheduler, clientReleaseManager,
dynamicConfigurationManager, zkSecretParams, spamChecker, messageMetrics, messageDeliveryLoopMonitor,
Clock.systemUTC()),
new PaymentsController(currencyManager, paymentsCredentialsGenerator),
@@ -16,6 +16,7 @@ import java.net.URI;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
@@ -126,8 +127,12 @@ public class CloudflareTurnCredentialsManager {
final CloudflareTurnResponse cloudflareTurnResponse = SystemMapper.jsonMapper()
.readValue(response.body(), CloudflareTurnResponse.class);
return new TurnToken(cloudflareTurnResponse.iceServers().username(),
return TurnTokenGenerator.from(
cloudflareTurnResponse.iceServers().username(),
cloudflareTurnResponse.iceServers().credential(),
cloudflareTurnUrls, cloudflareTurnComposedUrls, cloudflareTurnHostname);
Optional.ofNullable(cloudflareTurnUrls),
Optional.ofNullable(cloudflareTurnComposedUrls),
cloudflareTurnHostname
);
}
}
@@ -169,8 +169,7 @@ public class RegistrationLockVerificationManager {
throw new WebApplicationException(Response.status(FAILURE_HTTP_STATUS)
.entity(new RegistrationLockFailure(
existingRegistrationLock.getTimeRemaining().toMillis(),
svr2FailureCredentials(existingRegistrationLock, updatedAccount),
null))
svr2FailureCredentials(existingRegistrationLock, updatedAccount)))
.build());
}
@@ -5,9 +5,14 @@
package org.whispersystems.textsecuregcm.auth;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.List;
public record TurnToken(String username, String password, List<String> urls, @Nullable List<String> urlsWithIps,
@Nullable String hostname) {
public record TurnToken(
String username,
String password,
@Nonnull List<String> urls,
@Nonnull List<String> urlsWithIps,
@Nullable String hostname) {
}
@@ -11,24 +11,16 @@ import java.security.SecureRandom;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.whispersystems.textsecuregcm.calls.routing.TurnServerOptions;
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.Util;
import org.whispersystems.textsecuregcm.util.WeightedRandomSelect;
public class TurnTokenGenerator {
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private final byte[] turnSecret;
private static final String ALGORITHM = "HmacSHA1";
@@ -37,57 +29,59 @@ public class TurnTokenGenerator {
private static final String WithIpsProtocol = "01";
public TurnTokenGenerator(final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final byte[] turnSecret) {
this.dynamicConfigurationManager = dynamicConfigurationManager;
public TurnTokenGenerator(final byte[] turnSecret) {
this.turnSecret = turnSecret;
}
@Deprecated
public TurnToken generate(final UUID aci) {
return generateToken(null, null, urls(aci));
}
public TurnToken generateWithTurnServerOptions(TurnServerOptions options) {
return generateToken(options.hostname(), options.urlsWithIps(), options.urlsWithHostname());
}
private TurnToken generateToken(String hostname, List<String> urlsWithIps, List<String> urlsWithHostname) {
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
private TurnToken generateToken(
String hostname,
Optional<List<String>> urlsWithIps,
Optional<List<String>> urlsWithHostname
) {
try {
final Mac mac = Mac.getInstance(ALGORITHM);
final long validUntilSeconds = Instant.now().plus(Duration.ofDays(1)).getEpochSecond();
final long user = Util.ensureNonNegativeInt(new SecureRandom().nextInt());
final String userTime = validUntilSeconds + ":" + user;
final String protocol = urlsWithIps != null && !urlsWithIps.isEmpty()
? WithIpsProtocol
: WithUrlsProtocol;
final String protocol = urlsWithIps.isEmpty() || urlsWithIps.get().isEmpty()
? WithUrlsProtocol
: WithIpsProtocol;
final String protocolUserTime = userTime + "#" + protocol;
mac.init(new SecretKeySpec(turnSecret, ALGORITHM));
final String password = Base64.getEncoder().encodeToString(mac.doFinal(protocolUserTime.getBytes()));
return new TurnToken(protocolUserTime, password, urlsWithHostname, urlsWithIps, hostname);
return from(
protocolUserTime,
password,
urlsWithHostname,
urlsWithIps,
hostname
);
} catch (final NoSuchAlgorithmException | InvalidKeyException e) {
throw new AssertionError(e);
}
}
private List<String> urls(final UUID aci) {
final DynamicTurnConfiguration turnConfig = dynamicConfigurationManager.getConfiguration().getTurnConfiguration();
// Check if number is enrolled to test out specific turn servers
final Optional<TurnUriConfiguration> enrolled = turnConfig.getUriConfigs().stream()
.filter(config -> config.getEnrolledAcis().contains(aci))
.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<>(c.getUris(), c.getWeight())).toList());
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public static TurnToken from(
String username,
String password,
Optional<List<String>> urls,
Optional<List<String>> urlsWithIps,
String hostname
) {
return new TurnToken(
username,
password,
urls.orElse(Collections.emptyList()),
urlsWithIps.orElse(Collections.emptyList()),
hostname
);
}
}
@@ -7,6 +7,9 @@ package org.whispersystems.textsecuregcm.auth;
import org.whispersystems.textsecuregcm.storage.Account;
import java.security.MessageDigest;
import java.util.Collection;
import java.util.function.Predicate;
import java.util.stream.IntStream;
public class UnidentifiedAccessUtil {
@@ -31,4 +34,42 @@ public class UnidentifiedAccessUtil {
.map(targetUnidentifiedAccessKey -> MessageDigest.isEqual(targetUnidentifiedAccessKey, unidentifiedAccessKey))
.orElse(false);
}
/**
* Checks whether an action (e.g. sending a message or retrieving pre-keys) may be taken on the collection of target
* accounts by an actor presenting the given combined unidentified access key.
*
* @param targetAccounts the accounts on which an actor wishes to take an action
* @param combinedUnidentifiedAccessKey the unidentified access key presented by the actor
*
* @return {@code true} if an actor presenting the given unidentified access key has permission to take an action on
* the target accounts or {@code false} otherwise
*/
public static boolean checkUnidentifiedAccess(final Collection<Account> targetAccounts, final byte[] combinedUnidentifiedAccessKey) {
return MessageDigest.isEqual(getCombinedUnidentifiedAccessKey(targetAccounts), combinedUnidentifiedAccessKey);
}
/**
* Calculates a combined unidentified access key for the given collection of accounts.
*
* @param accounts the accounts from which to derive a combined unidentified access key
* @return a combined unidentified access key
*
* @throws IllegalArgumentException if one or more of the given accounts had an unidentified access key with an
* unexpected length
*/
public static byte[] getCombinedUnidentifiedAccessKey(final Collection<Account> accounts) {
return accounts.stream()
.filter(Predicate.not(Account::isUnrestrictedUnidentifiedAccess))
.map(account ->
account.getUnidentifiedAccessKey()
.filter(b -> b.length == UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH)
.orElseThrow(IllegalArgumentException::new))
.reduce(new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH],
(a, b) -> {
final byte[] xor = new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH];
IntStream.range(0, UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH).forEach(i -> xor[i] = (byte) (a[i] ^ b[i]));
return xor;
});
}
}
@@ -62,6 +62,11 @@ public class DynamicConfigTurnRouter {
return turnConfig.getRandomizeRate();
}
public int getDefaultInstanceIpCount() {
final DynamicTurnConfiguration turnConfig = dynamicConfigurationManager.getConfiguration().getTurnConfiguration();
return turnConfig.getDefaultInstanceIpCount();
}
public boolean shouldRandomize() {
long rate = getRandomizeRate();
return rate >= RANDOMIZE_RATE_BASIS || rng.nextLong(0, DynamicConfigTurnRouter.RANDOMIZE_RATE_BASIS) < rate;
@@ -52,6 +52,13 @@ public class TurnCallRouter {
this.stableSelect = stableSelect;
}
public TurnServerOptions getRoutingFor(
@Nonnull final UUID aci,
@Nonnull final Optional<InetAddress> clientAddress
) {
return getRoutingFor(aci, clientAddress, this.configTurnRouter.getDefaultInstanceIpCount());
}
/**
* Gets Turn Instance addresses. Returns both the IPv4 and IPv6 addresses. Prefers to match the IP protocol of the
* client address in datacenter selection. Returns 2 instance options of the preferred protocol for every one instance
@@ -70,7 +77,7 @@ public class TurnCallRouter {
return getRoutingForInner(aci, clientAddress, instanceLimit);
} catch(Exception e) {
logger.error("Failed to perform routing", e);
return new TurnServerOptions(this.configTurnRouter.getHostname(), null, this.configTurnRouter.randomUrls());
return new TurnServerOptions(this.configTurnRouter.getHostname(), null, Optional.of(this.configTurnRouter.randomUrls()));
}
}
@@ -79,19 +86,15 @@ public class TurnCallRouter {
@Nonnull final Optional<InetAddress> clientAddress,
final int instanceLimit
) {
if (instanceLimit < 1) {
throw new IllegalArgumentException("Limit cannot be less than one");
}
String hostname = this.configTurnRouter.getHostname();
List<String> targetedUrls = this.configTurnRouter.targetedUrls(aci);
if(!targetedUrls.isEmpty()) {
return new TurnServerOptions(hostname, null, targetedUrls);
return new TurnServerOptions(hostname, Optional.empty(), Optional.ofNullable(targetedUrls));
}
if(clientAddress.isEmpty() || this.configTurnRouter.shouldRandomize()) {
return new TurnServerOptions(hostname, null, this.configTurnRouter.randomUrls());
if(clientAddress.isEmpty() || this.configTurnRouter.shouldRandomize() || instanceLimit < 1) {
return new TurnServerOptions(hostname, Optional.empty(), Optional.ofNullable(this.configTurnRouter.randomUrls()));
}
CityResponse geoInfo;
@@ -125,7 +128,7 @@ public class TurnCallRouter {
datacenters,
instanceLimit
));
return new TurnServerOptions(hostname, urlsWithIps, minimalRandomUrls());
return new TurnServerOptions(hostname, Optional.of(urlsWithIps), Optional.of(minimalRandomUrls()));
}
// Includes only the udp options in the randomUrls
@@ -6,6 +6,11 @@
package org.whispersystems.textsecuregcm.calls.routing;
import java.util.List;
import java.util.Optional;
public record TurnServerOptions(String hostname, List<String> urlsWithIps, List<String> urlsWithHostname) {
public record TurnServerOptions(
String hostname,
Optional<List<String>> urlsWithIps,
Optional<List<String>> urlsWithHostname
) {
}
@@ -12,13 +12,13 @@ import jakarta.validation.constraints.NotNull;
import java.net.http.HttpClient;
import java.util.Map;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
import org.whispersystems.textsecuregcm.currency.CoinMarketCapClient;
import org.whispersystems.textsecuregcm.currency.CoinGeckoClient;
import org.whispersystems.textsecuregcm.currency.FixerClient;
@JsonTypeName("default")
public record PaymentsServiceClientsConfiguration(@NotNull SecretString coinMarketCapApiKey,
public record PaymentsServiceClientsConfiguration(@NotNull SecretString coinGeckoApiKey,
@NotNull SecretString fixerApiKey,
@NotEmpty Map<@NotBlank String, Integer> coinMarketCapCurrencyIds) implements
@NotEmpty Map<@NotBlank String, String> coinGeckoCurrencyIds) implements
PaymentsServiceClientsFactory {
@Override
@@ -27,7 +27,7 @@ public record PaymentsServiceClientsConfiguration(@NotNull SecretString coinMark
}
@Override
public CoinMarketCapClient buildCoinMarketCapClient(final HttpClient httpClient) {
return new CoinMarketCapClient(httpClient, coinMarketCapApiKey.value(), coinMarketCapCurrencyIds);
public CoinGeckoClient buildCoinGeckoClient(final HttpClient httpClient) {
return new CoinGeckoClient(httpClient, coinGeckoApiKey.value(), coinGeckoCurrencyIds);
}
}
@@ -7,7 +7,7 @@ package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import io.dropwizard.jackson.Discoverable;
import org.whispersystems.textsecuregcm.currency.CoinMarketCapClient;
import org.whispersystems.textsecuregcm.currency.CoinGeckoClient;
import org.whispersystems.textsecuregcm.currency.FixerClient;
import java.net.http.HttpClient;
@@ -16,5 +16,5 @@ public interface PaymentsServiceClientsFactory extends Discoverable {
FixerClient buildFixerClient(final HttpClient httpClient);
CoinMarketCapClient buildCoinMarketCapClient(HttpClient httpClient);
CoinGeckoClient buildCoinGeckoClient(HttpClient httpClient);
}
@@ -3,9 +3,11 @@ package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonTypeName;
import io.dropwizard.core.setup.Environment;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.io.IOException;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
import org.whispersystems.textsecuregcm.registration.IdentityTokenCallCredentials;
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
@@ -14,7 +16,8 @@ public record RegistrationServiceConfiguration(@NotBlank String host,
int port,
@NotBlank String credentialConfigurationJson,
@NotBlank String identityTokenAudience,
@NotBlank String registrationCaCertificate) implements
@NotBlank String registrationCaCertificate,
@NotNull SecretBytes collationKeySalt) implements
RegistrationServiceClientFactory {
@Override
@@ -26,7 +29,7 @@ public record RegistrationServiceConfiguration(@NotBlank String host,
environment.lifecycle().manage(callCredentials);
return new RegistrationServiceClient(host, port, callCredentials, registrationCaCertificate,
return new RegistrationServiceClient(host, port, callCredentials, registrationCaCertificate, collationKeySalt.value(),
identityRefreshExecutor);
} catch (IOException e) {
throw new RuntimeException(e);
@@ -6,6 +6,7 @@
package org.whispersystems.textsecuregcm.configuration.dynamic;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.vdurmont.semver4j.Semver;
import jakarta.validation.Valid;
import java.util.Collections;
import java.util.HashMap;
@@ -13,6 +14,7 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.whispersystems.textsecuregcm.limits.RateLimiterConfig;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
public class DynamicConfiguration {
@@ -72,6 +74,10 @@ public class DynamicConfiguration {
@Valid
List<String> svrStatusCodesToIgnoreForAccountDeletion = Collections.emptyList();
@JsonProperty
@Valid
Map<ClientPlatform, Semver> minimumRestFreeVersion = Map.of();
public Optional<DynamicExperimentEnrollmentConfiguration> getExperimentEnrollmentConfiguration(
final String experimentName) {
return Optional.ofNullable(experiments.get(experimentName));
@@ -130,4 +136,8 @@ public class DynamicConfiguration {
return svrStatusCodesToIgnoreForAccountDeletion;
}
public Map<ClientPlatform, Semver> minimumRestFreeVersion() {
return minimumRestFreeVersion;
}
}
@@ -23,6 +23,12 @@ public class DynamicTurnConfiguration {
@JsonProperty
private long randomizeRate = 5_000;
/**
* Number of instance ips to return in TURN routing request
*/
@JsonProperty
private int defaultInstanceIpCount = 0;
@JsonProperty
private List<@Valid TurnUriConfiguration> uriConfigs = Collections.emptyList();
@@ -34,6 +40,10 @@ public class DynamicTurnConfiguration {
return randomizeRate;
}
public int getDefaultInstanceIpCount() {
return defaultInstanceIpCount;
}
public String getHostname() {
return hostname;
}
@@ -35,11 +35,8 @@ import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import javax.annotation.Nullable;
import org.signal.libsignal.usernames.BaseUsernameException;
import org.whispersystems.textsecuregcm.auth.AccountAndAuthenticatedDeviceHolder;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.auth.TurnToken;
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.entities.AccountIdentifierResponse;
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
@@ -61,7 +58,6 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableException;
import org.whispersystems.textsecuregcm.storage.UsernameReservationNotFoundException;
@@ -82,33 +78,20 @@ public class AccountController {
private final AccountsManager accounts;
private final RateLimiters rateLimiters;
private final TurnTokenGenerator turnTokenGenerator;
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
private final UsernameHashZkProofVerifier usernameHashZkProofVerifier;
public AccountController(
AccountsManager accounts,
RateLimiters rateLimiters,
TurnTokenGenerator turnTokenGenerator,
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
UsernameHashZkProofVerifier usernameHashZkProofVerifier) {
this.accounts = accounts;
this.rateLimiters = rateLimiters;
this.turnTokenGenerator = turnTokenGenerator;
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
this.usernameHashZkProofVerifier = usernameHashZkProofVerifier;
}
// may be removed after 2024-07-16
@Deprecated(forRemoval = true)
@GET
@Path("/turn/")
@Produces(MediaType.APPLICATION_JSON)
public TurnToken getTurnToken(@ReadOnly @Auth AuthenticatedDevice auth) throws RateLimitExceededException {
rateLimiters.getTurnLimiter().validate(auth.getAccount().getUuid());
return turnTokenGenerator.generate(auth.getAccount().getUuid());
}
@PUT
@Path("/gcm/")
@Consumes(MediaType.APPLICATION_JSON)
@@ -1,103 +0,0 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.controllers;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Optional;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.CloudflareTurnCredentialsManager;
import org.whispersystems.textsecuregcm.auth.TurnToken;
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
import org.whispersystems.textsecuregcm.calls.routing.TurnCallRouter;
import org.whispersystems.textsecuregcm.calls.routing.TurnServerOptions;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.websocket.auth.ReadOnly;
@Path("/v1/calling")
@io.swagger.v3.oas.annotations.tags.Tag(name = "Calling")
public class CallRoutingController {
private static final int TURN_INSTANCE_LIMIT = 2;
private static final Counter INVALID_IP_COUNTER = Metrics.counter(name(CallRoutingController.class, "invalidIP"));
private static final Logger log = LoggerFactory.getLogger(CallRoutingController.class);
private final RateLimiters rateLimiters;
private final TurnCallRouter turnCallRouter;
private final TurnTokenGenerator tokenGenerator;
private final ExperimentEnrollmentManager experimentEnrollmentManager;
private final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager;
public CallRoutingController(
final RateLimiters rateLimiters,
final TurnCallRouter turnCallRouter,
final TurnTokenGenerator tokenGenerator,
final ExperimentEnrollmentManager experimentEnrollmentManager,
final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager
) {
this.rateLimiters = rateLimiters;
this.turnCallRouter = turnCallRouter;
this.tokenGenerator = tokenGenerator;
this.experimentEnrollmentManager = experimentEnrollmentManager;
this.cloudflareTurnCredentialsManager = cloudflareTurnCredentialsManager;
}
@GET
@Path("/relays")
@Produces(MediaType.APPLICATION_JSON)
@Operation(
summary = "Get 1:1 calling relay options for the client",
description = """
Get 1:1 relay addresses in IpV4, Ipv6, and URL formats.
"""
)
@ApiResponse(responseCode = "200", description = "`JSON` with call endpoints.", useReturnTypeSchema = true)
@ApiResponse(responseCode = "400", description = "Invalid get call endpoint request.")
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
@ApiResponse(responseCode = "422", description = "Invalid request format.")
@ApiResponse(responseCode = "429", description = "Rate limited.")
public TurnToken getCallingRelays(
final @ReadOnly @Auth AuthenticatedDevice auth,
@Context ContainerRequestContext requestContext
) throws RateLimitExceededException, IOException {
UUID aci = auth.getAccount().getUuid();
rateLimiters.getCallEndpointLimiter().validate(aci);
if (experimentEnrollmentManager.isEnrolled(auth.getAccount().getNumber(), aci, "cloudflareTurn")) {
return cloudflareTurnCredentialsManager.retrieveFromCloudflare();
}
Optional<InetAddress> address = Optional.empty();
try {
final String remoteAddress = (String) requestContext.getProperty(
RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
address = Optional.of(InetAddress.getByName(remoteAddress));
} catch (UnknownHostException e) {
INVALID_IP_COUNTER.increment();
}
TurnServerOptions options = turnCallRouter.getRoutingFor(aci, address, TURN_INSTANCE_LIMIT);
return tokenGenerator.generateWithTurnServerOptions(options);
}
}
@@ -18,7 +18,6 @@ import jakarta.ws.rs.Produces;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
@@ -40,8 +39,8 @@ import org.whispersystems.websocket.auth.ReadOnly;
@Path("/v2/calling")
public class CallRoutingControllerV2 {
private static final int TURN_INSTANCE_LIMIT = 2;
private static final Counter INVALID_IP_COUNTER = Metrics.counter(name(CallRoutingControllerV2.class, "invalidIP"));
private static final Counter CLOUDFLARE_TURN_ERROR_COUNTER = Metrics.counter(name(CallRoutingControllerV2.class, "cloudflareTurnError"));
private final RateLimiters rateLimiters;
private final TurnCallRouter turnCallRouter;
private final TurnTokenGenerator tokenGenerator;
@@ -79,13 +78,18 @@ public class CallRoutingControllerV2 {
public GetCallingRelaysResponse getCallingRelays(
final @ReadOnly @Auth AuthenticatedDevice auth,
@Context ContainerRequestContext requestContext
) throws RateLimitExceededException, IOException {
) throws RateLimitExceededException {
UUID aci = auth.getAccount().getUuid();
rateLimiters.getCallEndpointLimiter().validate(aci);
List<TurnToken> tokens = new ArrayList<>();
if (experimentEnrollmentManager.isEnrolled(auth.getAccount().getNumber(), aci, "cloudflareTurn")) {
tokens.add(cloudflareTurnCredentialsManager.retrieveFromCloudflare());
try {
if (experimentEnrollmentManager.isEnrolled(auth.getAccount().getNumber(), aci, "cloudflareTurn")) {
tokens.add(cloudflareTurnCredentialsManager.retrieveFromCloudflare());
}
} catch (Exception e) {
// emit counter, rely on Signal URL fallback
CallRoutingControllerV2.CLOUDFLARE_TURN_ERROR_COUNTER.increment();
}
Optional<InetAddress> address = Optional.empty();
@@ -97,7 +101,7 @@ public class CallRoutingControllerV2 {
INVALID_IP_COUNTER.increment();
}
TurnServerOptions options = turnCallRouter.getRoutingFor(aci, address, TURN_INSTANCE_LIMIT);
TurnServerOptions options = turnCallRouter.getRoutingFor(aci, address);
tokens.add(tokenGenerator.generateWithTurnServerOptions(options));
return new GetCallingRelaysResponse(tokens);
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.net.HttpHeaders;
import io.dropwizard.auth.Auth;
import io.lettuce.core.RedisException;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.Timer;
@@ -81,6 +80,7 @@ import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.DeviceSpec;
import org.whispersystems.textsecuregcm.storage.LinkDeviceTokenAlreadyUsedException;
import org.whispersystems.textsecuregcm.storage.PersistentTimer;
import org.whispersystems.textsecuregcm.util.DeviceCapabilityAdapter;
import org.whispersystems.textsecuregcm.util.EnumMapUtil;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
@@ -100,6 +100,7 @@ public class DeviceController {
private final AccountsManager accounts;
private final ClientPublicKeysManager clientPublicKeysManager;
private final RateLimiters rateLimiters;
private final PersistentTimer persistentTimer;
private final Map<String, Integer> maxDeviceConfiguration;
private final EnumMap<ClientPlatform, AtomicInteger> linkedDeviceListenersByPlatform;
@@ -108,9 +109,15 @@ public class DeviceController {
private static final String LINKED_DEVICE_LISTENER_GAUGE_NAME =
MetricsUtil.name(DeviceController.class, "linkedDeviceListeners");
private static final String WAIT_FOR_LINKED_DEVICE_TIMER_NAMESPACE = "wait_for_linked_device";
private static final String WAIT_FOR_LINKED_DEVICE_TIMER_NAME =
MetricsUtil.name(DeviceController.class, "waitForLinkedDeviceDuration");
private static final String WAIT_FOR_TRANSFER_ARCHIVE_TIMER_NAMESPACE = "wait_for_transfer_archive";
private static final String WAIT_FOR_TRANSFER_ARCHIVE_TIMER_NAME =
MetricsUtil.name(DeviceController.class, "waitForTransferArchiveDuration");
@VisibleForTesting
static final int MIN_TOKEN_IDENTIFIER_LENGTH = 32;
@@ -120,11 +127,13 @@ public class DeviceController {
public DeviceController(final AccountsManager accounts,
final ClientPublicKeysManager clientPublicKeysManager,
final RateLimiters rateLimiters,
final PersistentTimer persistentTimer,
final Map<String, Integer> maxDeviceConfiguration) {
this.accounts = accounts;
this.clientPublicKeysManager = clientPublicKeysManager;
this.rateLimiters = rateLimiters;
this.persistentTimer = persistentTimer;
this.maxDeviceConfiguration = maxDeviceConfiguration;
linkedDeviceListenersByPlatform =
@@ -339,7 +348,7 @@ public class DeviceController {
@ApiResponse(responseCode = "204", description = "No device was linked to the account before the call completed; clients may repeat the call to continue waiting")
@ApiResponse(responseCode = "400", description = "The given token identifier or timeout was invalid")
@ApiResponse(responseCode = "429", description = "Rate-limited; try again after the prescribed delay")
public CompletableFuture<Response> waitForLinkedDevice(
public CompletionStage<Response> waitForLinkedDevice(
@ReadOnly @Auth final AuthenticatedDevice authenticatedDevice,
@PathParam("tokenIdentifier")
@@ -359,40 +368,33 @@ public class DeviceController {
given amount of time, this endpoint will return a status of HTTP/204.
""") final int timeoutSeconds,
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent) throws RateLimitExceededException {
rateLimiters.getWaitForLinkedDeviceLimiter().validate(authenticatedDevice.getAccount().getIdentifier(IdentityType.ACI));
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent) {
final AtomicInteger linkedDeviceListenerCounter = getCounterForLinkedDeviceListeners(userAgent);
linkedDeviceListenerCounter.incrementAndGet();
final Timer.Sample sample = Timer.start();
try {
return accounts.waitForNewLinkedDevice(authenticatedDevice.getAccount().getUuid(),
authenticatedDevice.getAuthenticatedDevice(), tokenIdentifier, Duration.ofSeconds(timeoutSeconds))
.thenApply(maybeDeviceInfo -> maybeDeviceInfo
.map(deviceInfo -> Response.status(Response.Status.OK).entity(deviceInfo).build())
.orElseGet(() -> Response.status(Response.Status.NO_CONTENT).build()))
.exceptionally(ExceptionUtils.exceptionallyHandler(IllegalArgumentException.class,
e -> Response.status(Response.Status.BAD_REQUEST).build()))
.whenComplete((response, throwable) -> {
linkedDeviceListenerCounter.decrementAndGet();
return rateLimiters.getWaitForLinkedDeviceLimiter()
.validateAsync(authenticatedDevice.getAccount().getIdentifier(IdentityType.ACI))
.thenCompose(ignored -> persistentTimer.start(WAIT_FOR_LINKED_DEVICE_TIMER_NAMESPACE, tokenIdentifier))
.thenCompose(sample -> accounts.waitForNewLinkedDevice(
authenticatedDevice.getAccount().getUuid(),
authenticatedDevice.getAuthenticatedDevice(),
tokenIdentifier,
Duration.ofSeconds(timeoutSeconds))
.thenApply(maybeDeviceInfo -> maybeDeviceInfo
.map(deviceInfo -> Response.status(Response.Status.OK).entity(deviceInfo).build())
.orElseGet(() -> Response.status(Response.Status.NO_CONTENT).build()))
.exceptionally(ExceptionUtils.exceptionallyHandler(IllegalArgumentException.class,
e -> Response.status(Response.Status.BAD_REQUEST).build()))
.whenComplete((response, throwable) -> {
linkedDeviceListenerCounter.decrementAndGet();
if (response != null) {
sample.stop(Timer.builder(WAIT_FOR_LINKED_DEVICE_TIMER_NAME)
.publishPercentileHistogram(true)
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
io.micrometer.core.instrument.Tag.of("deviceFound",
String.valueOf(response.getStatus() == Response.Status.OK.getStatusCode()))))
.register(Metrics.globalRegistry));
}
});
} catch (final RedisException e) {
// `waitForNewLinkedDevice` could fail synchronously if the Redis circuit breaker is open; prevent counter drift
// if that happens
linkedDeviceListenerCounter.decrementAndGet();
throw e;
}
if (response != null && response.getStatus() == Response.Status.OK.getStatusCode()) {
sample.stop(Timer.builder(WAIT_FOR_LINKED_DEVICE_TIMER_NAME)
.publishPercentileHistogram(true)
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)))
.register(Metrics.globalRegistry));
}
}));
}
private AtomicInteger getCounterForLinkedDeviceListeners(final String userAgent) {
@@ -530,7 +532,8 @@ public class DeviceController {
public CompletionStage<Void> recordTransferArchiveUploaded(@ReadOnly @Auth final AuthenticatedDevice authenticatedDevice,
@NotNull @Valid final TransferArchiveUploadedRequest transferArchiveUploadedRequest) {
return rateLimiters.getUploadTransferArchiveLimiter().validateAsync(authenticatedDevice.getAccount().getIdentifier(IdentityType.ACI))
return rateLimiters.getUploadTransferArchiveLimiter()
.validateAsync(authenticatedDevice.getAccount().getIdentifier(IdentityType.ACI))
.thenCompose(ignored -> accounts.recordTransferArchiveUpload(authenticatedDevice.getAccount(),
transferArchiveUploadedRequest.destinationDeviceId(),
Instant.ofEpochMilli(transferArchiveUploadedRequest.destinationDeviceCreated()),
@@ -565,17 +568,29 @@ public class DeviceController {
description = """
The amount of time (in seconds) to wait for a response. If a transfer archive for the authenticated
device is not available within the given amount of time, this endpoint will return a status of HTTP/204.
""") final int timeoutSeconds) {
""") final int timeoutSeconds,
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable String userAgent) {
final String rateLimiterKey = authenticatedDevice.getAccount().getIdentifier(IdentityType.ACI) +
":" + authenticatedDevice.getAuthenticatedDevice().getId();
return rateLimiters.getWaitForTransferArchiveLimiter().validateAsync(rateLimiterKey)
.thenCompose(ignored -> accounts.waitForTransferArchive(authenticatedDevice.getAccount(),
authenticatedDevice.getAuthenticatedDevice(),
Duration.ofSeconds(timeoutSeconds)))
.thenApply(maybeTransferArchive -> maybeTransferArchive
.map(transferArchive -> Response.status(Response.Status.OK).entity(transferArchive).build())
.orElseGet(() -> Response.status(Response.Status.NO_CONTENT).build()));
.thenCompose(ignored -> persistentTimer.start(WAIT_FOR_TRANSFER_ARCHIVE_TIMER_NAMESPACE, rateLimiterKey))
.thenCompose(sample -> accounts.waitForTransferArchive(authenticatedDevice.getAccount(),
authenticatedDevice.getAuthenticatedDevice(),
Duration.ofSeconds(timeoutSeconds))
.thenApply(maybeTransferArchive -> maybeTransferArchive
.map(transferArchive -> Response.status(Response.Status.OK).entity(transferArchive).build())
.orElseGet(() -> Response.status(Response.Status.NO_CONTENT).build()))
.whenComplete((response, throwable) -> {
if (response != null && response.getStatus() == Response.Status.OK.getStatusCode()) {
sample.stop(Timer.builder(WAIT_FOR_TRANSFER_ARCHIVE_TIMER_NAME)
.publishPercentileHistogram(true)
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)))
.register(Metrics.globalRegistry));
}
}));
}
}
@@ -151,21 +151,21 @@ public class KeyTransparencyController {
try {
final AciMonitorRequest aciMonitorRequest = AciMonitorRequest.newBuilder()
.setAci(ByteString.copyFrom(request.aci().value().toCompactByteArray()))
.addAllEntries(request.aci().positions())
.setEntryPosition(request.aci().entryPosition())
.setCommitmentIndex(ByteString.copyFrom(request.aci().commitmentIndex()))
.build();
final Optional<UsernameHashMonitorRequest> usernameHashMonitorRequest = request.usernameHash().map(usernameHash ->
UsernameHashMonitorRequest.newBuilder()
.setUsernameHash(ByteString.copyFrom(usernameHash.value()))
.addAllEntries(usernameHash.positions())
.setEntryPosition(usernameHash.entryPosition())
.setCommitmentIndex(ByteString.copyFrom(usernameHash.commitmentIndex()))
.build());
final Optional<E164MonitorRequest> e164MonitorRequest = request.e164().map(e164 ->
E164MonitorRequest.newBuilder()
.setE164(e164.value())
.addAllEntries(e164.positions())
.setEntryPosition(e164.entryPosition())
.setCommitmentIndex(ByteString.copyFrom(e164.commitmentIndex()))
.build());
@@ -9,10 +9,8 @@ import static com.codahale.metrics.MetricRegistry.name;
import com.codahale.metrics.annotation.Timed;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.net.HttpHeaders;
import com.google.protobuf.ByteString;
import io.dropwizard.auth.Auth;
import io.dropwizard.util.DataSize;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
@@ -47,33 +45,26 @@ import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import java.security.MessageDigest;
import java.time.Clock;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.glassfish.jersey.server.ManagedAsync;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage.Recipient;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.protocol.util.Pair;
import org.signal.libsignal.zkgroup.ServerSecretParams;
@@ -135,6 +126,7 @@ import org.whispersystems.websocket.auth.ReadOnly;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuples;
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@@ -142,14 +134,6 @@ import reactor.util.function.Tuples;
@io.swagger.v3.oas.annotations.tags.Tag(name = "Messages")
public class MessageController {
private record MultiRecipientDeliveryData(
ServiceIdentifier serviceIdentifier,
Account account,
Recipient recipient,
Map<Byte, Short> deviceIdToRegistrationId) {
}
private static final Logger logger = LoggerFactory.getLogger(MessageController.class);
private final RateLimiters rateLimiters;
@@ -162,7 +146,6 @@ public class MessageController {
private final PushNotificationManager pushNotificationManager;
private final PushNotificationScheduler pushNotificationScheduler;
private final ReportMessageManager reportMessageManager;
private final ExecutorService multiRecipientMessageExecutor;
private final Scheduler messageDeliveryScheduler;
private final ClientReleaseManager clientReleaseManager;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
@@ -229,7 +212,6 @@ public class MessageController {
PushNotificationManager pushNotificationManager,
PushNotificationScheduler pushNotificationScheduler,
ReportMessageManager reportMessageManager,
@Nonnull ExecutorService multiRecipientMessageExecutor,
Scheduler messageDeliveryScheduler,
final ClientReleaseManager clientReleaseManager,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
@@ -248,7 +230,6 @@ public class MessageController {
this.pushNotificationManager = pushNotificationManager;
this.pushNotificationScheduler = pushNotificationScheduler;
this.reportMessageManager = reportMessageManager;
this.multiRecipientMessageExecutor = Objects.requireNonNull(multiRecipientMessageExecutor);
this.messageDeliveryScheduler = messageDeliveryScheduler;
this.clientReleaseManager = clientReleaseManager;
this.dynamicConfigurationManager = dynamicConfigurationManager;
@@ -332,15 +313,15 @@ public class MessageController {
throw new WebApplicationException(Status.FORBIDDEN);
}
final Optional<Account> destination;
final Optional<Account> maybeDestination;
if (!isSyncMessage) {
destination = accountsManager.getByServiceIdentifier(destinationIdentifier);
maybeDestination = accountsManager.getByServiceIdentifier(destinationIdentifier);
} else {
destination = source.map(AuthenticatedDevice::getAccount);
maybeDestination = source.map(AuthenticatedDevice::getAccount);
}
final SpamChecker.SpamCheckResult spamCheck = spamChecker.checkForSpam(
context, source, destination, Optional.of(destinationIdentifier));
context, source, maybeDestination, Optional.of(destinationIdentifier));
final Optional<byte[]> reportSpamToken;
switch (spamCheck) {
case final SpamChecker.Spam spam: return spam.response();
@@ -376,11 +357,11 @@ public class MessageController {
// Stories will be checked by the client; we bypass access checks here for stories.
} else if (groupSendToken != null) {
checkGroupSendToken(List.of(destinationIdentifier.toLibsignal()), groupSendToken);
if (destination.isEmpty()) {
if (maybeDestination.isEmpty()) {
throw new NotFoundException();
}
} else {
OptionalAccess.verify(source.map(AuthenticatedDevice::getAccount), accessKey, destination,
OptionalAccess.verify(source.map(AuthenticatedDevice::getAccount), accessKey, maybeDestination,
destinationIdentifier);
}
@@ -389,20 +370,20 @@ public class MessageController {
// We return 200 when stories are sent to a non-existent account. Since story sends bypass OptionalAccess.verify
// we leak information about whether a destination UUID exists if we return any other code (e.g. 404) from
// these requests.
if (isStory && destination.isEmpty()) {
if (isStory && maybeDestination.isEmpty()) {
return Response.ok(new SendMessageResponse(needsSync)).build();
}
// if destination is empty we would either throw an exception in OptionalAccess.verify when isStory is false
// or else return a 200 response when isStory is true.
assert destination.isPresent();
final Account destination = maybeDestination.orElseThrow();
if (source.isPresent() && !isSyncMessage) {
checkMessageRateLimit(source.get(), destination.get(), userAgent);
checkMessageRateLimit(source.get(), destination, userAgent);
}
if (isStory) {
rateLimiters.getStoriesLimiter().validate(destination.get().getUuid());
rateLimiters.getStoriesLimiter().validate(destination.getUuid());
}
final Set<Byte> excludedDeviceIds;
@@ -413,15 +394,33 @@ public class MessageController {
excludedDeviceIds = Collections.emptySet();
}
DestinationDeviceValidator.validateCompleteDeviceList(destination.get(),
messages.messages().stream().map(IncomingMessage::destinationDeviceId).collect(Collectors.toSet()),
final Map<Byte, Envelope> messagesByDeviceId = messages.messages().stream()
.collect(Collectors.toMap(IncomingMessage::destinationDeviceId, message -> {
try {
return message.toEnvelope(
destinationIdentifier,
source.map(AuthenticatedDevice::getAccount).orElse(null),
source.map(account -> account.getAuthenticatedDevice().getId()).orElse(null),
messages.timestamp() == 0 ? System.currentTimeMillis() : messages.timestamp(),
isStory,
messages.online(),
messages.urgent(),
reportSpamToken.orElse(null));
} catch (final IllegalArgumentException e) {
logger.warn("Received bad envelope type {} from {}", message.type(), userAgent);
throw new BadRequestException(e);
}
}));
DestinationDeviceValidator.validateCompleteDeviceList(destination,
messagesByDeviceId.keySet(),
excludedDeviceIds);
DestinationDeviceValidator.validateRegistrationIds(destination.get(),
DestinationDeviceValidator.validateRegistrationIds(destination,
messages.messages(),
IncomingMessage::destinationDeviceId,
IncomingMessage::destinationRegistrationId,
destination.get().getPhoneNumberIdentifier().equals(destinationIdentifier.uuid()));
destination.getPhoneNumberIdentifier().equals(destinationIdentifier.uuid()));
final String authType;
if (SENDER_TYPE_IDENTIFIED.equals(senderType)) {
@@ -434,31 +433,15 @@ public class MessageController {
authType = AUTH_TYPE_ACCESS_KEY;
}
final List<Tag> tags = List.of(UserAgentTagUtil.getPlatformTag(userAgent),
messageSender.sendMessages(destination, messagesByDeviceId);
Metrics.counter(SENT_MESSAGE_COUNTER_NAME, List.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(ENDPOINT_TYPE_TAG_NAME, ENDPOINT_TYPE_SINGLE),
Tag.of(EPHEMERAL_TAG_NAME, String.valueOf(messages.online())),
Tag.of(SENDER_TYPE_TAG_NAME, senderType),
Tag.of(AUTH_TYPE_TAG_NAME, authType),
Tag.of(IDENTITY_TYPE_TAG_NAME, destinationIdentifier.identityType().name()));
for (final IncomingMessage incomingMessage : messages.messages()) {
destination.get().getDevice(incomingMessage.destinationDeviceId())
.ifPresent(destinationDevice -> {
Metrics.counter(SENT_MESSAGE_COUNTER_NAME, tags).increment();
sendIndividualMessage(
source,
destination.get(),
destinationDevice,
destinationIdentifier,
messages.timestamp(),
messages.online(),
isStory,
messages.urgent(),
incomingMessage,
userAgent,
reportSpamToken);
});
}
Tag.of(IDENTITY_TYPE_TAG_NAME, destinationIdentifier.identityType().name())))
.increment(messagesByDeviceId.size());
return Response.ok(new SendMessageResponse(needsSync)).build();
} catch (final MismatchedDevicesException e) {
@@ -481,34 +464,6 @@ public class MessageController {
}
}
/**
* Build mapping of service IDs to resolved accounts and device/registration IDs
*/
private Map<ServiceIdentifier, MultiRecipientDeliveryData> buildRecipientMap(
SealedSenderMultiRecipientMessage multiRecipientMessage, boolean isStory) {
return Flux.fromIterable(multiRecipientMessage.getRecipients().entrySet())
.switchIfEmpty(Flux.error(BadRequestException::new))
.map(e -> Tuples.of(ServiceIdentifier.fromLibsignal(e.getKey()), e.getValue()))
.flatMap(
t -> Mono.fromFuture(() -> accountsManager.getByServiceIdentifierAsync(t.getT1()))
.flatMap(Mono::justOrEmpty)
.switchIfEmpty(isStory ? Mono.empty() : Mono.error(NotFoundException::new))
.map(
account ->
new MultiRecipientDeliveryData(
t.getT1(),
account,
t.getT2(),
t.getT2().getDevicesAndRegistrationIds().collect(
Collectors.toMap(Pair<Byte, Short>::first, Pair<Byte, Short>::second))))
// IllegalStateException is thrown by Collectors#toMap when we have multiple entries for the same device
.onErrorMap(e -> e instanceof IllegalStateException ? new BadRequestException() : e),
MAX_FETCH_ACCOUNT_CONCURRENCY)
.collectMap(MultiRecipientDeliveryData::serviceIdentifier)
.block();
}
@Timed
@Path("/multi_recipient")
@PUT
@@ -565,6 +520,32 @@ public class MessageController {
throw new BadRequestException("Illegal timestamp");
}
if (multiRecipientMessage.getRecipients().isEmpty()) {
throw new BadRequestException("Recipient list is empty");
}
// Verify that the message isn't too large before performing more expensive validations
multiRecipientMessage.getRecipients().values().forEach(recipient ->
validateContentLength(multiRecipientMessage.messageSizeForRecipient(recipient), true, userAgent));
// Check that the request is well-formed and doesn't contain repeated entries for the same device for the same
// recipient
{
final boolean[] usedDeviceIds = new boolean[Device.MAXIMUM_DEVICE_ID];
for (final SealedSenderMultiRecipientMessage.Recipient recipient : multiRecipientMessage.getRecipients().values()) {
Arrays.fill(usedDeviceIds, false);
for (final byte deviceId : recipient.getDevices()) {
if (usedDeviceIds[deviceId]) {
throw new BadRequestException();
}
usedDeviceIds[deviceId] = true;
}
}
}
final SpamChecker.SpamCheckResult spamCheck = spamChecker.checkForSpam(context, Optional.empty(), Optional.empty(), Optional.empty());
if (spamCheck instanceof final SpamChecker.Spam spam) {
return spam.response();
@@ -584,28 +565,43 @@ public class MessageController {
if (groupSendToken != null) {
// Group send endorsements are checked before we even attempt to resolve any accounts, since
// the lists of service IDs in the envelope are all that we need to check against
checkGroupSendToken(
multiRecipientMessage.getRecipients().keySet(), groupSendToken);
checkGroupSendToken(multiRecipientMessage.getRecipients().keySet(), groupSendToken);
}
final Map<ServiceIdentifier, MultiRecipientDeliveryData> recipients = buildRecipientMap(multiRecipientMessage, isStory);
// At this point, the caller has at least superficially provided the information needed to send a multi-recipient
// message. Attempt to resolve the destination service identifiers to Signal accounts.
final Map<SealedSenderMultiRecipientMessage.Recipient, Account> resolvedRecipients =
Flux.fromIterable(multiRecipientMessage.getRecipients().entrySet())
.flatMap(serviceIdAndRecipient -> {
final ServiceIdentifier serviceIdentifier =
ServiceIdentifier.fromLibsignal(serviceIdAndRecipient.getKey());
return Mono.fromFuture(() -> accountsManager.getByServiceIdentifierAsync(serviceIdentifier))
.flatMap(Mono::justOrEmpty)
.switchIfEmpty(isStory ? Mono.empty() : Mono.error(NotFoundException::new))
.map(account -> Tuples.of(serviceIdAndRecipient.getValue(), account));
}, MAX_FETCH_ACCOUNT_CONCURRENCY)
.collectMap(Tuple2::getT1, Tuple2::getT2)
.blockOptional()
.orElse(Collections.emptyMap());
// Access keys are checked against the UAK in the resolved accounts, so we have to check after resolving accounts above.
// Group send endorsements are checked earlier; for stories, we don't check permissions at all because only clients check them
if (groupSendToken == null && !isStory) {
checkAccessKeys(accessKeys, recipients.values());
checkAccessKeys(accessKeys, multiRecipientMessage, resolvedRecipients);
}
// We might filter out all the recipients of a story (if none exist).
// In this case there is no error so we should just return 200 now.
if (isStory) {
if (recipients.isEmpty()) {
if (resolvedRecipients.isEmpty()) {
return Response.ok(new SendMultiRecipientMessageResponse(List.of())).build();
}
try {
CompletableFuture.allOf(recipients.values()
CompletableFuture.allOf(resolvedRecipients.values()
.stream()
.map(recipient -> recipient.account().getUuid())
.map(account -> account.getIdentifier(IdentityType.ACI))
.map(accountIdentifier ->
rateLimiters.getStoriesLimiter().validateAsync(accountIdentifier).toCompletableFuture())
.toList()
@@ -620,31 +616,42 @@ public class MessageController {
}
}
Collection<AccountMismatchedDevices> accountMismatchedDevices = new ArrayList<>();
Collection<AccountStaleDevices> accountStaleDevices = new ArrayList<>();
recipients.values().forEach(recipient -> {
final Account account = recipient.account();
final Collection<AccountMismatchedDevices> accountMismatchedDevices = new ArrayList<>();
final Collection<AccountStaleDevices> accountStaleDevices = new ArrayList<>();
multiRecipientMessage.getRecipients().forEach((serviceId, recipient) -> {
if (!resolvedRecipients.containsKey(recipient)) {
// When sending stories, we might not be able to resolve all recipients to existing accounts. That's okay! We
// can just skip them.
return;
}
final Account account = resolvedRecipients.get(recipient);
try {
DestinationDeviceValidator.validateCompleteDeviceList(account, recipient.deviceIdToRegistrationId().keySet(),
final Map<Byte, Short> deviceIdsToRegistrationIds = recipient.getDevicesAndRegistrationIds()
.collect(Collectors.toMap(Pair<Byte, Short>::first, Pair<Byte, Short>::second));
DestinationDeviceValidator.validateCompleteDeviceList(account, deviceIdsToRegistrationIds.keySet(),
Collections.emptySet());
DestinationDeviceValidator.validateRegistrationIds(
account,
recipient.deviceIdToRegistrationId().entrySet(),
deviceIdsToRegistrationIds.entrySet(),
Map.Entry<Byte, Short>::getKey,
e -> Integer.valueOf(e.getValue()),
recipient.serviceIdentifier().identityType() == IdentityType.PNI);
} catch (MismatchedDevicesException e) {
serviceId instanceof ServiceId.Pni);
} catch (final MismatchedDevicesException e) {
accountMismatchedDevices.add(
new AccountMismatchedDevices(
recipient.serviceIdentifier(),
ServiceIdentifier.fromLibsignal(serviceId),
new MismatchedDevices(e.getMissingDevices(), e.getExtraDevices())));
} catch (StaleDevicesException e) {
} catch (final StaleDevicesException e) {
accountStaleDevices.add(
new AccountStaleDevices(recipient.serviceIdentifier(), new StaleDevices(e.getStaleDevices())));
new AccountStaleDevices(ServiceIdentifier.fromLibsignal(serviceId), new StaleDevices(e.getStaleDevices())));
}
});
if (!accountMismatchedDevices.isEmpty()) {
return Response
.status(409)
@@ -670,39 +677,30 @@ public class MessageController {
}
try {
final byte[] sharedMrmKey = messagesManager.insertSharedMultiRecipientMessagePayload(multiRecipientMessage);
messageSender.sendMultiRecipientMessage(multiRecipientMessage, resolvedRecipients, timestamp, isStory, online, isUrgent).get();
CompletableFuture.allOf(
recipients.values().stream()
.flatMap(recipientData -> {
final Counter sentMessageCounter = Metrics.counter(SENT_MESSAGE_COUNTER_NAME, Tags.of(
UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(ENDPOINT_TYPE_TAG_NAME, ENDPOINT_TYPE_MULTI),
Tag.of(EPHEMERAL_TAG_NAME, String.valueOf(online)),
Tag.of(SENDER_TYPE_TAG_NAME, SENDER_TYPE_UNIDENTIFIED),
Tag.of(AUTH_TYPE_TAG_NAME, authType),
Tag.of(IDENTITY_TYPE_TAG_NAME, recipientData.serviceIdentifier().identityType().name())));
multiRecipientMessage.getRecipients().forEach((serviceId, recipient) -> {
if (!resolvedRecipients.containsKey(recipient)) {
// We skipped sending to this recipient because we're sending a story and couldn't resolve the recipient to
// an existing account; don't increment the counter for this recipient.
return;
}
validateContentLength(multiRecipientMessage.messageSizeForRecipient(recipientData.recipient()), true, userAgent);
final String identityType = switch (serviceId) {
case ServiceId.Aci ignored -> "ACI";
case ServiceId.Pni ignored -> "PNI";
default -> "unknown";
};
return recipientData.deviceIdToRegistrationId().keySet().stream().map(
deviceId -> CompletableFuture.runAsync(
() -> {
final Account destinationAccount = recipientData.account();
final byte[] payload = multiRecipientMessage.messageForRecipient(recipientData.recipient());
// we asserted this must exist in validateCompleteDeviceList
final Device destinationDevice = destinationAccount.getDevice(deviceId).orElseThrow();
sentMessageCounter.increment();
sendCommonPayloadMessage(
destinationAccount, destinationDevice, recipientData.serviceIdentifier(), timestamp,
online, isStory, isUrgent, payload, sharedMrmKey);
},
multiRecipientMessageExecutor));
})
.toArray(CompletableFuture[]::new))
.get();
Metrics.counter(SENT_MESSAGE_COUNTER_NAME, Tags.of(
UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(ENDPOINT_TYPE_TAG_NAME, ENDPOINT_TYPE_MULTI),
Tag.of(EPHEMERAL_TAG_NAME, String.valueOf(online)),
Tag.of(SENDER_TYPE_TAG_NAME, SENDER_TYPE_UNIDENTIFIED),
Tag.of(AUTH_TYPE_TAG_NAME, authType),
Tag.of(IDENTITY_TYPE_TAG_NAME, identityType)))
.increment(recipient.getDevices().length);
});
} catch (InterruptedException e) {
logger.error("interrupted while delivering multi-recipient messages", e);
throw new InternalServerErrorException("interrupted during delivery");
@@ -729,29 +727,21 @@ public class MessageController {
private void checkAccessKeys(
final @NotNull CombinedUnidentifiedSenderAccessKeys accessKeys,
final Collection<MultiRecipientDeliveryData> destinations) {
final int keyLength = UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH;
final SealedSenderMultiRecipientMessage multiRecipientMessage,
final Map<SealedSenderMultiRecipientMessage.Recipient, Account> resolvedRecipients) {
if (multiRecipientMessage.getRecipients().keySet().stream()
.anyMatch(serviceId -> serviceId instanceof ServiceId.Pni)) {
if (destinations.stream()
.anyMatch(destination -> IdentityType.PNI.equals(destination.serviceIdentifier.identityType()))) {
throw new WebApplicationException("Multi-recipient messages must be addressed to ACI service IDs",
Status.UNAUTHORIZED);
}
final byte[] combinedUnidentifiedAccessKeys = destinations.stream()
.map(MultiRecipientDeliveryData::account)
.filter(Predicate.not(Account::isUnrestrictedUnidentifiedAccess))
.map(account ->
account.getUnidentifiedAccessKey()
.filter(b -> b.length == keyLength)
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED)))
.reduce(new byte[keyLength],
(a, b) -> {
final byte[] xor = new byte[keyLength];
IntStream.range(0, keyLength).forEach(i -> xor[i] = (byte) (a[i] ^ b[i]));
return xor;
});
if (!MessageDigest.isEqual(combinedUnidentifiedAccessKeys, accessKeys.getAccessKeys())) {
try {
if (!UnidentifiedAccessUtil.checkUnidentifiedAccess(resolvedRecipients.values(), accessKeys.getAccessKeys())) {
throw new WebApplicationException(Status.UNAUTHORIZED);
}
} catch (final IllegalArgumentException ignored) {
throw new WebApplicationException(Status.UNAUTHORIZED);
}
}
@@ -912,65 +902,6 @@ public class MessageController {
.build();
}
private void sendIndividualMessage(
Optional<AuthenticatedDevice> source,
Account destinationAccount,
Device destinationDevice,
ServiceIdentifier destinationIdentifier,
long timestamp,
boolean online,
boolean story,
boolean urgent,
IncomingMessage incomingMessage,
String userAgentString,
Optional<byte[]> spamReportToken) {
final Envelope envelope;
try {
final Account sourceAccount = source.map(AuthenticatedDevice::getAccount).orElse(null);
final Byte sourceDeviceId = source.map(account -> account.getAuthenticatedDevice().getId()).orElse(null);
envelope = incomingMessage.toEnvelope(
destinationIdentifier,
sourceAccount,
sourceDeviceId,
timestamp == 0 ? System.currentTimeMillis() : timestamp,
story,
urgent,
spamReportToken.orElse(null));
} catch (final IllegalArgumentException e) {
logger.warn("Received bad envelope type {} from {}", incomingMessage.type(), userAgentString);
throw new BadRequestException(e);
}
messageSender.sendMessage(destinationAccount, destinationDevice, envelope, online);
}
private void sendCommonPayloadMessage(Account destinationAccount,
Device destinationDevice,
ServiceIdentifier serviceIdentifier,
long timestamp,
boolean online,
boolean story,
boolean urgent,
byte[] payload,
byte[] sharedMrmKey) {
final Envelope.Builder messageBuilder = Envelope.newBuilder();
final long serverTimestamp = System.currentTimeMillis();
messageBuilder
.setType(Type.UNIDENTIFIED_SENDER)
.setClientTimestamp(timestamp == 0 ? serverTimestamp : timestamp)
.setServerTimestamp(serverTimestamp)
.setStory(story)
.setUrgent(urgent)
.setDestinationServiceId(serviceIdentifier.toServiceIdentifierString())
.setSharedMrmKey(ByteString.copyFrom(sharedMrmKey));
messageSender.sendMessage(destinationAccount, destinationDevice, messageBuilder.build(), online);
}
private void checkMessageRateLimit(AuthenticatedDevice source, Account destination, String userAgent)
throws RateLimitExceededException {
final String senderCountryCode = Util.getCountryCode(source.getAccount().getNumber());
@@ -1020,15 +951,4 @@ public class MessageController {
throw new BadRequestException("reserved envelope type");
}
}
public static Optional<byte[]> getMessageContent(IncomingMessage message) {
if (StringUtils.isEmpty(message.content())) return Optional.empty();
try {
return Optional.of(Base64.getDecoder().decode(message.content()));
} catch (IllegalArgumentException e) {
logger.debug("Bad B64", e);
return Optional.empty();
}
}
}
@@ -173,7 +173,8 @@ public class VerificationController {
name = "Retry-After",
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed",
schema = @Schema(implementation = Integer.class)))
public VerificationSessionResponse createSession(@NotNull @Valid final CreateVerificationSessionRequest request)
public VerificationSessionResponse createSession(@NotNull @Valid final CreateVerificationSessionRequest request,
@Context final ContainerRequestContext requestContext)
throws RateLimitExceededException, ObsoletePhoneNumberFormatException {
final Pair<String, PushNotification.TokenType> pushTokenAndType = validateAndExtractPushToken(
@@ -188,7 +189,9 @@ public class VerificationController {
final RegistrationServiceSession registrationServiceSession;
try {
registrationServiceSession = registrationServiceClient.createRegistrationSession(phoneNumber,
final String sourceHost = (String) requestContext.getProperty(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
registrationServiceSession = registrationServiceClient.createRegistrationSession(phoneNumber, sourceHost,
accountsManager.getByE164(request.getNumber()).isPresent(),
REGISTRATION_RPC_TIMEOUT).join();
} catch (final CancellationException e) {
@@ -5,8 +5,8 @@
package org.whispersystems.textsecuregcm.currency;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.annotations.VisibleForTesting;
import java.io.IOException;
import java.math.BigDecimal;
@@ -14,26 +14,23 @@ import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Locale;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.util.SystemMapper;
public class CoinMarketCapClient {
public class CoinGeckoClient {
private final HttpClient httpClient;
private final String apiKey;
private final Map<String, Integer> currencyIdsBySymbol;
private final Map<String, String> currencyIdsBySymbol;
private static final Logger logger = LoggerFactory.getLogger(CoinMarketCapClient.class);
private static final Logger logger = LoggerFactory.getLogger(CoinGeckoClient.class);
record CoinMarketCapResponse(@JsonProperty("data") PriceConversionResponse priceConversionResponse) {};
private static final TypeReference<Map<String, Map<String, BigDecimal>>> RESPONSE_TYPE = new TypeReference<>() {};
record PriceConversionResponse(int id, String symbol, Map<String, PriceConversionQuote> quote) {};
record PriceConversionQuote(BigDecimal price) {};
public CoinMarketCapClient(final HttpClient httpClient, final String apiKey, final Map<String, Integer> currencyIdsBySymbol) {
public CoinGeckoClient(final HttpClient httpClient, final String apiKey, final Map<String, String> currencyIdsBySymbol) {
this.httpClient = httpClient;
this.apiKey = apiKey;
this.currencyIdsBySymbol = currencyIdsBySymbol;
@@ -45,40 +42,41 @@ public class CoinMarketCapClient {
}
final URI quoteUri = URI.create(
String.format("https://pro-api.coinmarketcap.com/v2/tools/price-conversion?amount=1&id=%d&convert=%s",
currencyIdsBySymbol.get(currency), base));
String.format("https://pro-api.coingecko.com/api/v3/simple/price?ids=%s&vs_currencies=%s",
currencyIdsBySymbol.get(currency), base.toLowerCase(Locale.ROOT)));
try {
final HttpResponse<String> response = httpClient.send(HttpRequest.newBuilder()
.GET()
.uri(quoteUri)
.header("X-CMC_PRO_API_KEY", apiKey)
.build(),
HttpResponse.BodyHandlers.ofString());
.GET()
.uri(quoteUri)
.header("Accept", "application/json")
.header("x-cg-pro-api-key", apiKey)
.build(),
HttpResponse.BodyHandlers.ofString());
if (response.statusCode() < 200 || response.statusCode() >= 300) {
logger.warn("CoinMarketCapRequest failed with response: {}", response);
throw new IOException("CoinMarketCap request failed with status code " + response.statusCode());
logger.warn("CoinGecko request failed with response: {}", response);
throw new IOException("CoinGecko request failed with status code " + response.statusCode());
}
return extractConversionRate(parseResponse(response.body()), base);
return extractConversionRate(parseResponse(response.body()).get(currencyIdsBySymbol.get(currency)), base.toLowerCase(Locale.ROOT));
} catch (final InterruptedException e) {
throw new IOException("Interrupted while waiting for a response", e);
}
}
@VisibleForTesting
static CoinMarketCapResponse parseResponse(final String responseJson) throws JsonProcessingException {
return SystemMapper.jsonMapper().readValue(responseJson, CoinMarketCapResponse.class);
static Map<String, Map<String,BigDecimal>> parseResponse(final String responseJson) throws JsonProcessingException {
return SystemMapper.jsonMapper().readValue(responseJson, RESPONSE_TYPE);
}
@VisibleForTesting
static BigDecimal extractConversionRate(final CoinMarketCapResponse response, final String destinationCurrency)
static BigDecimal extractConversionRate(final Map<String,BigDecimal> response, final String destinationCurrency)
throws IOException {
if (!response.priceConversionResponse().quote.containsKey(destinationCurrency)) {
if (!response.containsKey(destinationCurrency)) {
throw new IOException("Response does not contain conversion rate for " + destinationCurrency);
}
return response.priceConversionResponse().quote.get(destinationCurrency).price();
return response.get(destinationCurrency);
}
}
@@ -36,16 +36,16 @@ public class CurrencyConversionManager implements Managed {
@VisibleForTesting
static final Duration FIXER_REFRESH_INTERVAL = Duration.ofHours(2);
private static final Duration COIN_MARKET_CAP_REFRESH_INTERVAL = Duration.ofMinutes(5);
private static final Duration COIN_GECKO_CAP_REFRESH_INTERVAL = Duration.ofMinutes(5);
@VisibleForTesting
static final String COIN_MARKET_CAP_SHARED_CACHE_CURRENT_KEY = "CurrencyConversionManager::CoinMarketCapCacheCurrent";
static final String COIN_GECKO_CAP_SHARED_CACHE_CURRENT_KEY = "CurrencyConversionManager::CoinGeckoCacheCurrent";
private static final String COIN_MARKET_CAP_SHARED_CACHE_DATA_KEY = "CurrencyConversionManager::CoinMarketCapCacheData";
private static final String COIN_GECKO_SHARED_CACHE_DATA_KEY = "CurrencyConversionManager::CoinGeckoCacheData";
private final FixerClient fixerClient;
private final CoinMarketCapClient coinMarketCapClient;
private final CoinGeckoClient coinGeckoClient;
private final FaultTolerantRedisClusterClient cacheCluster;
@@ -61,18 +61,18 @@ public class CurrencyConversionManager implements Managed {
private Map<String, BigDecimal> cachedFixerValues;
private Map<String, BigDecimal> cachedCoinMarketCapValues;
private Map<String, BigDecimal> cachedCoinGeckoValues;
public CurrencyConversionManager(
final FixerClient fixerClient,
final CoinMarketCapClient coinMarketCapClient,
final CoinGeckoClient coinGeckoClient,
final FaultTolerantRedisClusterClient cacheCluster,
final List<String> currencies,
final ScheduledExecutorService executor,
final Clock clock) {
this.fixerClient = fixerClient;
this.coinMarketCapClient = coinMarketCapClient;
this.coinGeckoClient = coinGeckoClient;
this.cacheCluster = cacheCluster;
this.currencies = currencies;
this.executor = executor;
@@ -102,49 +102,49 @@ public class CurrencyConversionManager implements Managed {
}
{
final Map<String, BigDecimal> coinMarketCapValuesFromSharedCache = cacheCluster.withCluster(connection -> {
final Map<String, BigDecimal> CoinGeckoValuesFromSharedCache = cacheCluster.withCluster(connection -> {
final Map<String, BigDecimal> parsedSharedCacheData = new HashMap<>();
connection.sync().hgetall(COIN_MARKET_CAP_SHARED_CACHE_DATA_KEY).forEach((currency, conversionRate) ->
connection.sync().hgetall(COIN_GECKO_SHARED_CACHE_DATA_KEY).forEach((currency, conversionRate) ->
parsedSharedCacheData.put(currency, new BigDecimal(conversionRate)));
return parsedSharedCacheData;
});
if (coinMarketCapValuesFromSharedCache != null && !coinMarketCapValuesFromSharedCache.isEmpty()) {
cachedCoinMarketCapValues = coinMarketCapValuesFromSharedCache;
if (CoinGeckoValuesFromSharedCache != null && !CoinGeckoValuesFromSharedCache.isEmpty()) {
cachedCoinGeckoValues = CoinGeckoValuesFromSharedCache;
}
}
final boolean shouldUpdateSharedCache = cacheCluster.withCluster(connection ->
"OK".equals(connection.sync().set(COIN_MARKET_CAP_SHARED_CACHE_CURRENT_KEY,
"OK".equals(connection.sync().set(COIN_GECKO_CAP_SHARED_CACHE_CURRENT_KEY,
"true",
SetArgs.Builder.nx().ex(COIN_MARKET_CAP_REFRESH_INTERVAL))));
SetArgs.Builder.nx().ex(COIN_GECKO_CAP_REFRESH_INTERVAL))));
if (shouldUpdateSharedCache || cachedCoinMarketCapValues == null) {
final Map<String, BigDecimal> conversionRatesFromCoinMarketCap = new HashMap<>(currencies.size());
if (shouldUpdateSharedCache || cachedCoinGeckoValues == null) {
final Map<String, BigDecimal> conversionRatesFromCoinGecko = new HashMap<>(currencies.size());
for (final String currency : currencies) {
conversionRatesFromCoinMarketCap.put(currency, coinMarketCapClient.getSpotPrice(currency, "USD"));
conversionRatesFromCoinGecko.put(currency, coinGeckoClient.getSpotPrice(currency, "USD"));
}
cachedCoinMarketCapValues = conversionRatesFromCoinMarketCap;
cachedCoinGeckoValues = conversionRatesFromCoinGecko;
if (shouldUpdateSharedCache) {
cacheCluster.useCluster(connection -> {
final Map<String, String> sharedCoinMarketCapValues = new HashMap<>();
final Map<String, String> sharedCoinGeckoValues = new HashMap<>();
cachedCoinMarketCapValues.forEach((currency, conversionRate) ->
sharedCoinMarketCapValues.put(currency, conversionRate.toString()));
cachedCoinGeckoValues.forEach((currency, conversionRate) ->
sharedCoinGeckoValues.put(currency, conversionRate.toString()));
connection.sync().hset(COIN_MARKET_CAP_SHARED_CACHE_DATA_KEY, sharedCoinMarketCapValues);
connection.sync().hset(COIN_GECKO_SHARED_CACHE_DATA_KEY, sharedCoinGeckoValues);
});
}
}
List<CurrencyConversionEntity> entities = new LinkedList<>();
for (Map.Entry<String, BigDecimal> currency : cachedCoinMarketCapValues.entrySet()) {
for (Map.Entry<String, BigDecimal> currency : cachedCoinGeckoValues.entrySet()) {
BigDecimal usdValue = stripTrailingZerosAfterDecimal(currency.getValue());
Map<String, BigDecimal> values = new HashMap<>();
@@ -19,6 +19,7 @@ public record IncomingMessage(int type, byte destinationDeviceId, int destinatio
@Nullable Byte sourceDeviceId,
final long timestamp,
final boolean story,
final boolean ephemeral,
final boolean urgent,
@Nullable byte[] reportSpamToken) {
@@ -35,6 +36,7 @@ public record IncomingMessage(int type, byte destinationDeviceId, int destinatio
.setServerTimestamp(System.currentTimeMillis())
.setDestinationServiceId(destinationIdentifier.toServiceIdentifierString())
.setStory(story)
.setEphemeral(ephemeral)
.setUrgent(urgent);
if (sourceAccount != null && sourceDeviceId != null) {
@@ -13,7 +13,6 @@ import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import java.util.List;
import java.util.Optional;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
@@ -49,11 +48,9 @@ public record KeyTransparencyMonitorRequest(
@Schema(description = "The aci identifier to monitor")
AciServiceIdentifier value,
@Schema(description = "A list of log tree positions maintained by the client for the aci search key.")
@Valid
@NotNull
@NotEmpty
List<@Positive Long> positions,
@Schema(description = "A log tree position maintained by the client for the aci.")
@Positive
long entryPosition,
@Schema(description = "The commitment index derived from a previous search request, encoded in standard unpadded base64")
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@@ -68,11 +65,9 @@ public record KeyTransparencyMonitorRequest(
@NotBlank
String value,
@Schema(description = "A list of log tree positions maintained by the client for the e164 search key.")
@NotNull
@NotEmpty
@Valid
List<@Positive Long> positions,
@Schema(description = "A log tree position maintained by the client for the e164.")
@Positive
long entryPosition,
@Schema(description = "The commitment index derived from a previous search request, encoded in standard unpadded base64")
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@@ -91,10 +86,9 @@ public record KeyTransparencyMonitorRequest(
@NotEmpty
byte[] value,
@Schema(description = "A list of log tree positions maintained by the client for the username hash search key.")
@NotNull
@NotEmpty
@Valid List<@Positive Long> positions,
@Schema(description = "A log tree position maintained by the client for the username hash.")
@Positive
long entryPosition,
@Schema(description = "The commitment index derived from a previous search request, encoded in standard unpadded base64")
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@@ -18,8 +18,5 @@ public record RegistrationLockFailure(
long timeRemaining,
@Schema(description = "Credentials that can be used with SVR2")
@Nullable
ExternalServiceCredentials svr2Credentials,
@Deprecated
@Nullable
ExternalServiceCredentials svr3Credentials) {
ExternalServiceCredentials svr2Credentials) {
}
@@ -5,8 +5,13 @@
package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
@Schema(description = """
Represents a request from a new device to restore account data by some method.
@@ -14,7 +19,14 @@ import jakarta.validation.constraints.NotNull;
public record RestoreAccountRequest(
@NotNull
@Schema(description = "The method by which the new device has requested account data restoration")
Method method) {
Method method,
@Schema(description = "Additional data to use to bootstrap a connection between devices, in standard unpadded base64.",
implementation = String.class)
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
@Size(max = 4096)
@Nullable byte[] deviceTransferBootstrap) {
public enum Method {
@Schema(description = "Restore account data from a remote message history backup")
@@ -6,18 +6,17 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.workers.IdleWakeupEligibilityChecker;
import reactor.core.publisher.Flux;
import javax.annotation.Nullable;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.EnumMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
abstract class IdleDevicePushNotificationExperiment implements PushNotificationExperiment<DeviceLastSeenState> {
private final Clock clock;
private final IdleWakeupEligibilityChecker idleWakeupEligibilityChecker;
private final Logger log = LoggerFactory.getLogger(getClass());
@@ -37,19 +36,8 @@ abstract class IdleDevicePushNotificationExperiment implements PushNotificationE
UNCHANGED
}
protected IdleDevicePushNotificationExperiment(final Clock clock) {
this.clock = clock;
}
protected abstract Duration getMinIdleDuration();
protected abstract Duration getMaxIdleDuration();
@VisibleForTesting
boolean isIdle(final Device device) {
final Duration idleDuration = Duration.between(Instant.ofEpochMilli(device.getLastSeen()), clock.instant());
return idleDuration.compareTo(getMinIdleDuration()) >= 0 && idleDuration.compareTo(getMaxIdleDuration()) < 0;
protected IdleDevicePushNotificationExperiment(final IdleWakeupEligibilityChecker idleWakeupEligibilityChecker) {
this.idleWakeupEligibilityChecker = idleWakeupEligibilityChecker;
}
@VisibleForTesting
@@ -57,11 +45,18 @@ abstract class IdleDevicePushNotificationExperiment implements PushNotificationE
return !StringUtils.isAllBlank(device.getApnId(), device.getGcmId());
}
abstract boolean isIdleDeviceEligible(final Account account, final Device idleDevice, final DeviceLastSeenState state);
@Override
public CompletableFuture<Boolean> isDeviceEligible(final Account account, final Device device) {
return idleWakeupEligibilityChecker.isDeviceEligible(account, device).thenApply(idle ->
idle && isIdleDeviceEligible(account, device, getState(account, device)));
}
@Override
public DeviceLastSeenState getState(@Nullable final Account account, @Nullable final Device device) {
if (account != null && device != null) {
final DeviceLastSeenState.PushTokenType pushTokenType;
if (StringUtils.isNotBlank(device.getApnId())) {
pushTokenType = DeviceLastSeenState.PushTokenType.APNS;
} else if (StringUtils.isNotBlank(device.getGcmId())) {
@@ -69,7 +64,6 @@ abstract class IdleDevicePushNotificationExperiment implements PushNotificationE
} else {
pushTokenType = null;
}
return new DeviceLastSeenState(true, device.getCreated(), hasPushToken(device), device.getLastSeen(), pushTokenType);
} else {
return DeviceLastSeenState.MISSING_DEVICE_STATE;
@@ -0,0 +1,88 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.filters;
import com.google.common.net.HttpHeaders;
import com.vdurmont.semver4j.Semver;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.core.SecurityContext;
import java.io.IOException;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
import org.whispersystems.textsecuregcm.util.ua.UserAgent;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
public class RestDeprecationFilter implements ContainerRequestFilter {
private static final String EXPERIMENT_NAME = "restDeprecation";
private static final String DEPRECATED_REST_COUNTER_NAME = MetricsUtil.name(RestDeprecationFilter.class, "blockedRestRequest");
private static final Logger log = LoggerFactory.getLogger(RestDeprecationFilter.class);
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
final ExperimentEnrollmentManager experimentEnrollmentManager;
public RestDeprecationFilter(
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final ExperimentEnrollmentManager experimentEnrollmentManager) {
this.dynamicConfigurationManager = dynamicConfigurationManager;
this.experimentEnrollmentManager = experimentEnrollmentManager;
}
@Override
public void filter(final ContainerRequestContext requestContext) throws IOException {
final SecurityContext securityContext = requestContext.getSecurityContext();
if (securityContext == null || securityContext.getUserPrincipal() == null) {
// We can't check if an unauthenticated request is in the experiment
return;
}
if (securityContext.getUserPrincipal() instanceof AuthenticatedDevice ad) {
if (!experimentEnrollmentManager.isEnrolled(ad.getAccount().getUuid(), EXPERIMENT_NAME)) {
return;
}
} else {
log.error("Security context was not null but user principal was of type {}", securityContext.getUserPrincipal().getClass().getName());
return;
}
final Map<ClientPlatform, Semver> minimumRestFreeVersion = dynamicConfigurationManager.getConfiguration().minimumRestFreeVersion();
final String userAgentString = requestContext.getHeaderString(HttpHeaders.USER_AGENT);
try {
final UserAgent userAgent = UserAgentUtil.parseUserAgentString(userAgentString);
final ClientPlatform platform = userAgent.getPlatform();
final Semver version = userAgent.getVersion();
if (!minimumRestFreeVersion.containsKey(platform)) {
return;
}
if (version.isGreaterThanOrEqualTo(minimumRestFreeVersion.get(platform))) {
Metrics.counter(
DEPRECATED_REST_COUNTER_NAME, Tags.of("platform", platform.name().toLowerCase(), "version", version.toString()))
.increment();
throw new WebApplicationException("use websockets", 498);
}
} catch (final UnrecognizedUserAgentException e) {
return; // at present we're only interested in experimenting on known clients
}
}
}
@@ -1,39 +0,0 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import org.signal.chat.calling.GetTurnCredentialsRequest;
import org.signal.chat.calling.GetTurnCredentialsResponse;
import org.signal.chat.calling.ReactorCallingGrpc;
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import reactor.core.publisher.Mono;
public class CallingGrpcService extends ReactorCallingGrpc.CallingImplBase {
private final TurnTokenGenerator turnTokenGenerator;
private final RateLimiters rateLimiters;
public CallingGrpcService(final TurnTokenGenerator turnTokenGenerator, final RateLimiters rateLimiters) {
this.turnTokenGenerator = turnTokenGenerator;
this.rateLimiters = rateLimiters;
}
@Override
public Mono<GetTurnCredentialsResponse> getTurnCredentials(final GetTurnCredentialsRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
return rateLimiters.getTurnLimiter().validateReactive(authenticatedDevice.accountIdentifier())
.then(Mono.fromSupplier(() -> turnTokenGenerator.generate(authenticatedDevice.accountIdentifier())))
.map(turnToken -> GetTurnCredentialsResponse.newBuilder()
.setUsername(turnToken.username())
.setPassword(turnToken.password())
.addAllUrls(turnToken.urls())
.build());
}
}
@@ -1,36 +1,8 @@
package org.whispersystems.textsecuregcm.limits;
import com.google.common.annotations.VisibleForTesting;
import io.lettuce.core.ScriptOutputType;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.time.Duration;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
public class MessageDeliveryLoopMonitor {
private final ClusterLuaScript getDeliveryAttemptsScript;
private static final Duration DELIVERY_ATTEMPTS_COUNTER_TTL = Duration.ofHours(1);
private static final int DELIVERY_LOOP_THRESHOLD = 5;
private static final Logger logger = LoggerFactory.getLogger(MessageDeliveryLoopMonitor.class);
public MessageDeliveryLoopMonitor(final FaultTolerantRedisClusterClient rateLimitCluster) {
try {
getDeliveryAttemptsScript =
ClusterLuaScript.fromResource(rateLimitCluster, "lua/get_delivery_attempt_count.lua", ScriptOutputType.INTEGER);
} catch (final IOException e) {
throw new UncheckedIOException("Failed to load 'get delivery attempt count' script", e);
}
}
public interface MessageDeliveryLoopMonitor {
/**
* Records an attempt to deliver a message with the given GUID to the given account/device pair and returns the number
* of consecutive attempts to deliver the same message and logs a warning if the message appears to be in a delivery
@@ -44,29 +16,5 @@ public class MessageDeliveryLoopMonitor {
* @param userAgent the User-Agent header supplied by the caller
* @param context a human-readable string identifying the mechanism of message delivery (e.g. "rest" or "websocket")
*/
public void recordDeliveryAttempt(final UUID accountIdentifier,
final byte deviceId,
final UUID messageGuid,
final String userAgent,
final String context) {
incrementDeliveryAttemptCount(accountIdentifier, deviceId, messageGuid)
.thenAccept(deliveryAttemptCount -> {
if (deliveryAttemptCount == DELIVERY_LOOP_THRESHOLD) {
logger.warn("Detected loop delivering message {} via {} to {}:{} ({})",
messageGuid, context, accountIdentifier, deviceId, userAgent);
}
});
}
@VisibleForTesting
CompletableFuture<Long> incrementDeliveryAttemptCount(final UUID accountIdentifier, final byte deviceId, final UUID messageGuid) {
final String firstMessageGuidKey = "firstMessageGuid::{" + accountIdentifier + ":" + deviceId + "}";
final String deliveryAttemptsKey = "firstMessageDeliveryAttempts::{" + accountIdentifier + ":" + deviceId + "}";
return getDeliveryAttemptsScript.executeAsync(
List.of(firstMessageGuidKey, deliveryAttemptsKey),
List.of(messageGuid.toString(), String.valueOf(DELIVERY_ATTEMPTS_COUNTER_TTL.toSeconds())))
.thenApply(result -> (long) result);
}
void recordDeliveryAttempt(UUID accountIdentifier, byte deviceId, UUID messageGuid, String userAgent, String context);
}
@@ -0,0 +1,13 @@
package org.whispersystems.textsecuregcm.limits;
import java.util.UUID;
public class NoopMessageDeliveryLoopMonitor implements MessageDeliveryLoopMonitor {
public NoopMessageDeliveryLoopMonitor() {
}
public void recordDeliveryAttempt(final UUID accountIdentifier, final byte deviceId, final UUID messageGuid, final String userAgent, final String context) {
}
}
@@ -0,0 +1,73 @@
package org.whispersystems.textsecuregcm.limits;
import com.google.common.annotations.VisibleForTesting;
import io.lettuce.core.ScriptOutputType;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.time.Duration;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
public class RedisMessageDeliveryLoopMonitor implements MessageDeliveryLoopMonitor {
private final ClusterLuaScript getDeliveryAttemptsScript;
private static final Duration DELIVERY_ATTEMPTS_COUNTER_TTL = Duration.ofHours(1);
private static final int DELIVERY_LOOP_THRESHOLD = 5;
private static final Logger logger = LoggerFactory.getLogger(MessageDeliveryLoopMonitor.class);
public RedisMessageDeliveryLoopMonitor(final FaultTolerantRedisClusterClient rateLimitCluster) {
try {
getDeliveryAttemptsScript =
ClusterLuaScript.fromResource(rateLimitCluster, "lua/get_delivery_attempt_count.lua", ScriptOutputType.INTEGER);
} catch (final IOException e) {
throw new UncheckedIOException("Failed to load 'get delivery attempt count' script", e);
}
}
/**
* Records an attempt to deliver a message with the given GUID to the given account/device pair and returns the number
* of consecutive attempts to deliver the same message and logs a warning if the message appears to be in a delivery
* loop. This method is intended to detect cases where a message remains at the head of a device's queue after
* repeated attempts to deliver the message, and so the given message GUID should be the first message of a "page"
* sent to clients.
*
* @param accountIdentifier the identifier of the destination account
* @param deviceId the destination device's ID within the given account
* @param messageGuid the GUID of the message
* @param userAgent the User-Agent header supplied by the caller
* @param context a human-readable string identifying the mechanism of message delivery (e.g. "rest" or "websocket")
*/
public void recordDeliveryAttempt(final UUID accountIdentifier,
final byte deviceId,
final UUID messageGuid,
final String userAgent,
final String context) {
incrementDeliveryAttemptCount(accountIdentifier, deviceId, messageGuid)
.thenAccept(deliveryAttemptCount -> {
if (deliveryAttemptCount == DELIVERY_LOOP_THRESHOLD) {
logger.warn("Detected loop delivering message {} via {} to {}:{} ({})",
messageGuid, context, accountIdentifier, deviceId, userAgent);
}
});
}
@VisibleForTesting
CompletableFuture<Long> incrementDeliveryAttemptCount(final UUID accountIdentifier, final byte deviceId, final UUID messageGuid) {
final String firstMessageGuidKey = "firstMessageGuid::{" + accountIdentifier + ":" + deviceId + "}";
final String deliveryAttemptsKey = "firstMessageDeliveryAttempts::{" + accountIdentifier + ":" + deviceId + "}";
return getDeliveryAttemptsScript.executeAsync(
List.of(firstMessageGuidKey, deliveryAttemptsKey),
List.of(messageGuid.toString(), String.valueOf(DELIVERY_ATTEMPTS_COUNTER_TTL.toSeconds())))
.thenApply(result -> (long) result);
}
}
@@ -81,7 +81,7 @@ public class MetricsRequestEventListener implements RequestEventListener {
userAgent = userAgentValues != null && !userAgentValues.isEmpty() ? userAgentValues.get(0) : null;
}
tags.add(UserAgentTagUtil.getPlatformTag(userAgent));
tags.addAll(UserAgentTagUtil.getLibsignalAndPlatformTags(userAgent));
meterRegistry.counter(REQUEST_COUNTER_NAME, tags).increment();
@@ -1,19 +1,23 @@
package org.whispersystems.textsecuregcm.metrics;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.Timer;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.whispersystems.textsecuregcm.util.EnumMapUtil;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
import org.whispersystems.websocket.session.WebSocketSessionContext;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
public class OpenWebSocketCounter {
private static final String WEBSOCKET_CLOSED_COUNTER_NAME = name(OpenWebSocketCounter.class, "websocketClosed");
private final Map<ClientPlatform, AtomicInteger> openWebsocketsByClientPlatform;
private final AtomicInteger openWebsocketsFromUnknownPlatforms;
@@ -81,6 +85,9 @@ public class OpenWebSocketCounter {
context.addWebsocketClosedListener((context1, statusCode, reason) -> {
sample.stop(durationTimer);
openWebSocketCounter.decrementAndGet();
Metrics.counter(WEBSOCKET_CLOSED_COUNTER_NAME, "status", String.valueOf(statusCode))
.increment();
});
}
}
@@ -5,14 +5,10 @@
package org.whispersystems.textsecuregcm.metrics;
import com.vdurmont.semver4j.Semver;
import io.micrometer.core.instrument.Tag;
import java.util.Collections;
import java.util.Map;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
import org.whispersystems.textsecuregcm.util.ua.UserAgent;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
@@ -24,6 +20,7 @@ public class UserAgentTagUtil {
public static final String PLATFORM_TAG = "platform";
public static final String VERSION_TAG = "clientVersion";
public static final String LIBSIGNAL_TAG = "libsignal";
private UserAgentTagUtil() {
}
@@ -52,4 +49,23 @@ public class UserAgentTagUtil {
return Optional.empty();
}
public static List<Tag> getLibsignalAndPlatformTags(final String userAgentString) {
String platform;
boolean libsignal;
try {
final UserAgent userAgent = UserAgentUtil.parseUserAgentString(userAgentString);
platform = userAgent.getPlatform().name().toLowerCase();
libsignal = userAgent.getAdditionalSpecifiers()
.map(additionalSpecifiers -> additionalSpecifiers.contains("libsignal"))
.orElse(false);
} catch (final UnrecognizedUserAgentException e) {
platform = "unrecognized";
libsignal = false;
}
return List.of(Tag.of(PLATFORM_TAG, platform), Tag.of(LIBSIGNAL_TAG, String.valueOf(libsignal)));
}
}
@@ -55,11 +55,7 @@ public class MultiRecipientMessageProvider implements MessageBodyReader<SealedSe
try {
final SealedSenderMultiRecipientMessage message = SealedSenderMultiRecipientMessage.parse(fullMessage);
RECIPIENT_COUNT_DISTRIBUTION.record(message.getRecipients().keySet().size());
if (message.getRecipients().values().stream().anyMatch(r -> message.messageSizeForRecipient(r) > MAX_MESSAGE_SIZE)) {
throw new BadRequestException("message payload too large");
}
RECIPIENT_COUNT_DISTRIBUTION.record(message.getRecipients().size());
return message;
} catch (InvalidMessageException | InvalidVersionException e) {
throw new BadRequestException(e);
@@ -98,24 +98,30 @@ public class FcmSender implements PushNotificationSender {
return GoogleApiUtil.toCompletableFuture(firebaseMessagingClient.sendAsync(builder.build()), executor)
.whenComplete((ignored, throwable) -> sample.stop(SEND_NOTIFICATION_TIMER))
.thenApply(ignored -> new SendPushNotificationResult(true, Optional.empty(), false, Optional.empty()))
.exceptionally(throwable -> {
if (ExceptionUtils.unwrap(throwable) instanceof final FirebaseMessagingException firebaseMessagingException) {
final String errorCode;
.exceptionally(ExceptionUtils.exceptionallyHandler(FirebaseMessagingException.class,
firebaseMessagingException -> {
final String errorCode;
if (firebaseMessagingException.getMessagingErrorCode() != null) {
errorCode = firebaseMessagingException.getMessagingErrorCode().name();
} else {
logger.warn("Received an FCM exception with no error code", firebaseMessagingException);
errorCode = "unknown";
}
if (firebaseMessagingException.getMessagingErrorCode() != null) {
errorCode = firebaseMessagingException.getMessagingErrorCode().name();
if (firebaseMessagingException.getMessagingErrorCode() == MessagingErrorCode.QUOTA_EXCEEDED
&& firebaseMessagingException.getHttpResponse() != null) {
logger.info("FCM request failed with quota exceeded; retry-after: {}, response body: {}",
firebaseMessagingException.getHttpResponse().getHeaders().get("retry-after"),
firebaseMessagingException.getHttpResponse().getContent());
}
} else if (firebaseMessagingException.getHttpResponse() != null) {
errorCode = "http" + firebaseMessagingException.getHttpResponse().getStatusCode();
} else {
logger.warn("Received an FCM exception with no error code", firebaseMessagingException);
errorCode = "unknown";
}
final boolean unregistered =
firebaseMessagingException.getMessagingErrorCode() == MessagingErrorCode.UNREGISTERED;
final boolean unregistered =
firebaseMessagingException.getMessagingErrorCode() == MessagingErrorCode.UNREGISTERED;
return new SendPushNotificationResult(false, Optional.of(errorCode), unregistered, Optional.empty());
} else {
throw ExceptionUtils.wrap(throwable);
}
});
return new SendPushNotificationResult(false, Optional.of(errorCode), unregistered, Optional.empty());
}));
}
}
@@ -9,9 +9,14 @@ import static org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Metrics;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import org.whispersystems.textsecuregcm.util.Util;
/**
* A MessageSender sends Signal messages to destination devices. Messages may be "normal" user-to-user messages,
@@ -42,26 +47,82 @@ public class MessageSender {
this.pushNotificationManager = pushNotificationManager;
}
public void sendMessage(final Account account, final Device device, final Envelope message, final boolean online) {
final boolean destinationPresent = messagesManager.insert(account.getUuid(),
device.getId(),
online ? message.toBuilder().setEphemeral(true).build() : message);
/**
* Sends messages to devices associated with the given destination account. If a destination device has a valid push
* notification token and does not have an active connection to a Signal server, then this method will also send a
* push notification to that device to announce the availability of new messages.
*
* @param account the account to which to send messages
* @param messagesByDeviceId a map of device IDs to message payloads
*/
public void sendMessages(final Account account, final Map<Byte, Envelope> messagesByDeviceId) {
messagesManager.insert(account.getIdentifier(IdentityType.ACI), messagesByDeviceId)
.forEach((deviceId, destinationPresent) -> {
final Envelope message = messagesByDeviceId.get(deviceId);
if (!destinationPresent && !online) {
try {
pushNotificationManager.sendNewMessageNotification(account, device.getId(), message.getUrgent());
} catch (final NotPushRegisteredException ignored) {
}
}
if (!destinationPresent && !message.getEphemeral()) {
try {
pushNotificationManager.sendNewMessageNotification(account, deviceId, message.getUrgent());
} catch (final NotPushRegisteredException ignored) {
}
}
Metrics.counter(SEND_COUNTER_NAME,
CHANNEL_TAG_NAME, getDeliveryChannelName(device),
EPHEMERAL_TAG_NAME, String.valueOf(online),
CLIENT_ONLINE_TAG_NAME, String.valueOf(destinationPresent),
URGENT_TAG_NAME, String.valueOf(message.getUrgent()),
STORY_TAG_NAME, String.valueOf(message.getStory()),
SEALED_SENDER_TAG_NAME, String.valueOf(!message.hasSourceServiceId()))
.increment();
Metrics.counter(SEND_COUNTER_NAME,
CHANNEL_TAG_NAME, account.getDevice(deviceId).map(MessageSender::getDeliveryChannelName).orElse("unknown"),
EPHEMERAL_TAG_NAME, String.valueOf(message.getEphemeral()),
CLIENT_ONLINE_TAG_NAME, String.valueOf(destinationPresent),
URGENT_TAG_NAME, String.valueOf(message.getUrgent()),
STORY_TAG_NAME, String.valueOf(message.getStory()),
SEALED_SENDER_TAG_NAME, String.valueOf(!message.hasSourceServiceId()))
.increment();
});
}
/**
* Sends messages to a group of recipients. If a destination device has a valid push notification token and does not
* have an active connection to a Signal server, then this method will also send a push notification to that device to
* announce the availability of new messages.
*
* @param multiRecipientMessage the multi-recipient message to send to the given recipients
* @param resolvedRecipients a map of recipients to resolved Signal accounts
* @param clientTimestamp the time at which the sender reports the message was sent
* @param isStory {@code true} if the message is a story or {@code false otherwise}
* @param isEphemeral {@code true} if the message should only be delivered to devices with active connections or
* {@code false otherwise}
* @param isUrgent {@code true} if the message is urgent or {@code false otherwise}
*
* @return a future that completes when all messages have been inserted into delivery queues
*/
public CompletableFuture<Void> sendMultiRecipientMessage(final SealedSenderMultiRecipientMessage multiRecipientMessage,
final Map<SealedSenderMultiRecipientMessage.Recipient, Account> resolvedRecipients,
final long clientTimestamp,
final boolean isStory,
final boolean isEphemeral,
final boolean isUrgent) {
return messagesManager.insertMultiRecipientMessage(multiRecipientMessage, resolvedRecipients, clientTimestamp,
isStory, isEphemeral, isUrgent)
.thenAccept(clientPresenceByAccountAndDevice ->
clientPresenceByAccountAndDevice.forEach((account, clientPresenceByDeviceId) ->
clientPresenceByDeviceId.forEach((deviceId, clientPresent) -> {
if (!clientPresent && !isEphemeral) {
try {
pushNotificationManager.sendNewMessageNotification(account, deviceId, isUrgent);
} catch (final NotPushRegisteredException ignored) {
}
}
Metrics.counter(SEND_COUNTER_NAME,
CHANNEL_TAG_NAME,
account.getDevice(deviceId).map(MessageSender::getDeliveryChannelName).orElse("unknown"),
EPHEMERAL_TAG_NAME, String.valueOf(isEphemeral),
CLIENT_ONLINE_TAG_NAME, String.valueOf(clientPresent),
URGENT_TAG_NAME, String.valueOf(isUrgent),
STORY_TAG_NAME, String.valueOf(isStory),
SEALED_SENDER_TAG_NAME, String.valueOf(true))
.increment();
})))
.thenRun(Util.NOOP);
}
@VisibleForTesting
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.push;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.binder.jvm.ExecutorServiceMetrics;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
@@ -43,21 +44,21 @@ public class ReceiptSender {
try {
accountManager.getByAccountIdentifier(destinationIdentifier.uuid()).ifPresentOrElse(
destinationAccount -> {
final Envelope.Builder message = Envelope.newBuilder()
final Envelope message = Envelope.newBuilder()
.setServerTimestamp(System.currentTimeMillis())
.setSourceServiceId(sourceIdentifier.toServiceIdentifierString())
.setSourceDevice(sourceDeviceId)
.setDestinationServiceId(destinationIdentifier.toServiceIdentifierString())
.setClientTimestamp(messageId)
.setType(Envelope.Type.SERVER_DELIVERY_RECEIPT)
.setUrgent(false);
.setUrgent(false)
.build();
for (final Device destinationDevice : destinationAccount.getDevices()) {
try {
messageSender.sendMessage(destinationAccount, destinationDevice, message.build(), false);
} catch (final Exception e) {
logger.warn("Could not send delivery receipt", e);
}
try {
messageSender.sendMessages(destinationAccount, destinationAccount.getDevices().stream()
.collect(Collectors.toMap(Device::getId, ignored -> message)));
} catch (final Exception e) {
logger.warn("Could not send delivery receipt", e);
}
},
() -> logger.info("No longer registered: {}", destinationIdentifier)
@@ -14,12 +14,17 @@ import io.grpc.TlsChannelCredentials;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.util.Base64;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.signal.registration.rpc.CheckVerificationCodeRequest;
@@ -35,9 +40,12 @@ import org.whispersystems.textsecuregcm.util.CompletableFutureUtil;
public class RegistrationServiceClient implements Managed {
private static final Base64.Encoder BASE64_UNPADDED_ENCODER = Base64.getEncoder().withoutPadding();
private final ManagedChannel channel;
private final RegistrationServiceGrpc.RegistrationServiceFutureStub stub;
private final Executor callbackExecutor;
private final byte[] collationKeySalt;
/**
* @param from an e164 in a {@code long} representation e.g. {@code 18005550123}
@@ -60,6 +68,7 @@ public class RegistrationServiceClient implements Managed {
final int port,
final CallCredentials callCredentials,
final String caCertificatePem,
final byte[] collationKeySalt,
final Executor callbackExecutor) throws IOException {
try (final ByteArrayInputStream certificateInputStream = new ByteArrayInputStream(caCertificatePem.getBytes(StandardCharsets.UTF_8))) {
@@ -73,19 +82,29 @@ public class RegistrationServiceClient implements Managed {
}
this.stub = RegistrationServiceGrpc.newFutureStub(channel).withCallCredentials(callCredentials);
this.collationKeySalt = collationKeySalt;
this.callbackExecutor = callbackExecutor;
// Fail fast: reject bad keys
try {
getInitializedMac(collationKeySalt);
} catch (final InvalidKeyException e) {
throw new IllegalArgumentException(e);
}
}
public CompletableFuture<RegistrationServiceSession> createRegistrationSession(
final Phonenumber.PhoneNumber phoneNumber, final boolean accountExistsWithPhoneNumber, final Duration timeout) {
final Phonenumber.PhoneNumber phoneNumber, final String sourceHost, final boolean accountExistsWithPhoneNumber, final Duration timeout) {
final long e164 = Long.parseLong(
PhoneNumberUtil.getInstance().format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164).substring(1));
final String rateLimitCollationKey = hmac(sourceHost);
return CompletableFutureUtil.toCompletableFuture(stub.withDeadline(toDeadline(timeout))
.createSession(CreateRegistrationSessionRequest.newBuilder()
.setE164(e164)
.setAccountExistsWithE164(accountExistsWithPhoneNumber)
.setRateLimitCollationKey(rateLimitCollationKey)
.build()), callbackExecutor)
.thenApply(response -> switch (response.getResponseCase()) {
case SESSION_METADATA -> buildSessionResponseFromMetadata(response.getSessionMetadata());
@@ -259,4 +278,30 @@ public class RegistrationServiceClient implements Managed {
channel.shutdown();
}
}
private String hmac(String sourceHost) {
final Mac hmacSha256 = getInitializedMac();
hmacSha256.update(sourceHost.getBytes(StandardCharsets.UTF_8));
return BASE64_UNPADDED_ENCODER.encodeToString(hmacSha256.doFinal());
}
private Mac getInitializedMac() {
try {
return getInitializedMac(collationKeySalt);
} catch (final InvalidKeyException e) {
throw new AssertionError(e);
}
}
private static Mac getInitializedMac(byte[] key) throws InvalidKeyException {
try {
final Mac hmacSha256 = Mac.getInstance("HmacSHA256");
hmacSha256.init(new SecretKeySpec(key, "HmacSHA256"));
return hmacSha256;
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
}
@@ -4,8 +4,8 @@
*/
package org.whispersystems.textsecuregcm.storage;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.ByteString;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -13,10 +13,10 @@ import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.signal.libsignal.protocol.IdentityKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.controllers.MessageController;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.controllers.StaleDevicesException;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
@@ -115,40 +115,39 @@ public class ChangeNumberManager {
private void sendDeviceMessages(final Account account, final List<IncomingMessage> deviceMessages) {
try {
deviceMessages.forEach(message ->
sendMessageToSelf(account, account.getDevice(message.destinationDeviceId()), message));
} catch (RuntimeException e) {
final long serverTimestamp = System.currentTimeMillis();
messageSender.sendMessages(account, deviceMessages.stream()
.filter(message -> getMessageContent(message).isPresent())
.collect(Collectors.toMap(IncomingMessage::destinationDeviceId, message -> Envelope.newBuilder()
.setType(Envelope.Type.forNumber(message.type()))
.setClientTimestamp(serverTimestamp)
.setServerTimestamp(serverTimestamp)
.setDestinationServiceId(new AciServiceIdentifier(account.getUuid()).toServiceIdentifierString())
.setContent(ByteString.copyFrom(getMessageContent(message).orElseThrow()))
.setSourceServiceId(new AciServiceIdentifier(account.getUuid()).toServiceIdentifierString())
.setSourceDevice(Device.PRIMARY_ID)
.setUpdatedPni(account.getPhoneNumberIdentifier().toString())
.setUrgent(true)
.setEphemeral(false)
.build())));
} catch (final RuntimeException e) {
logger.warn("Changed number but could not send all device messages on {}", account.getUuid(), e);
throw e;
}
}
@VisibleForTesting
void sendMessageToSelf(
Account sourceAndDestinationAccount, Optional<Device> destinationDevice, IncomingMessage message) {
Optional<byte[]> contents = MessageController.getMessageContent(message);
if (contents.isEmpty()) {
logger.debug("empty message contents sending to self, ignoring");
return;
} else if (destinationDevice.isEmpty()) {
logger.debug("destination device not present");
return;
private static Optional<byte[]> getMessageContent(final IncomingMessage message) {
if (StringUtils.isEmpty(message.content())) {
logger.warn("Message has no content");
return Optional.empty();
}
final long serverTimestamp = System.currentTimeMillis();
final Envelope envelope = Envelope.newBuilder()
.setType(Envelope.Type.forNumber(message.type()))
.setClientTimestamp(serverTimestamp)
.setServerTimestamp(serverTimestamp)
.setDestinationServiceId(
new AciServiceIdentifier(sourceAndDestinationAccount.getUuid()).toServiceIdentifierString())
.setContent(ByteString.copyFrom(contents.get()))
.setSourceServiceId(new AciServiceIdentifier(sourceAndDestinationAccount.getUuid()).toServiceIdentifierString())
.setSourceDevice(Device.PRIMARY_ID)
.setUpdatedPni(sourceAndDestinationAccount.getPhoneNumberIdentifier().toString())
.setUrgent(true)
.build();
messageSender.sendMessage(sourceAndDestinationAccount, destinationDevice.get(), envelope, false);
try {
return Optional.of(Base64.getDecoder().decode(message.content()));
} catch (final IllegalArgumentException e) {
logger.warn("Failed to parse message content", e);
return Optional.empty();
}
}
}
@@ -203,22 +203,28 @@ public class MessagesCache {
this.unlockQueueScript = unlockQueueScript;
}
public boolean insert(final UUID messageGuid,
public CompletableFuture<Boolean> insert(final UUID messageGuid,
final UUID destinationAccountIdentifier,
final byte destinationDeviceId,
final MessageProtos.Envelope message) {
final MessageProtos.Envelope messageWithGuid = message.toBuilder().setServerGuid(messageGuid.toString()).build();
return insertTimer.record(() -> insertScript.execute(destinationAccountIdentifier, destinationDeviceId, messageWithGuid));
final Timer.Sample sample = Timer.start();
return insertScript.executeAsync(destinationAccountIdentifier, destinationDeviceId, messageWithGuid)
.whenComplete((ignored, throwable) -> sample.stop(insertTimer));
}
public byte[] insertSharedMultiRecipientMessagePayload(
public CompletableFuture<byte[]> insertSharedMultiRecipientMessagePayload(
final SealedSenderMultiRecipientMessage sealedSenderMultiRecipientMessage) {
return insertSharedMrmPayloadTimer.record(() -> {
final byte[] sharedMrmKey = getSharedMrmKey(UUID.randomUUID());
insertMrmScript.execute(sharedMrmKey, sealedSenderMultiRecipientMessage);
return sharedMrmKey;
});
final Timer.Sample sample = Timer.start();
final byte[] sharedMrmKey = getSharedMrmKey(UUID.randomUUID());
return insertMrmScript.executeAsync(sharedMrmKey, sealedSenderMultiRecipientMessage)
.thenApply(ignored -> sharedMrmKey)
.whenComplete((ignored, throwable) -> sample.stop(insertSharedMrmPayloadTimer));
}
public CompletableFuture<Optional<RemovedMessage>> remove(final UUID destinationUuid, final byte destinationDevice,
@@ -12,6 +12,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.push.ClientEvent;
import org.whispersystems.textsecuregcm.push.NewMessageAvailableEvent;
@@ -44,7 +45,7 @@ class MessagesCacheInsertScript {
* @return {@code true} if the destination device had a registered "presence"/event subscriber or {@code false}
* otherwise
*/
boolean execute(final UUID destinationUuid, final byte destinationDevice, final MessageProtos.Envelope envelope) {
CompletableFuture<Boolean> executeAsync(final UUID destinationUuid, final byte destinationDevice, final MessageProtos.Envelope envelope) {
assert envelope.hasServerGuid();
assert envelope.hasServerTimestamp();
@@ -62,6 +63,7 @@ class MessagesCacheInsertScript {
NEW_MESSAGE_EVENT_BYTES // eventPayload
));
return (boolean) insertScript.executeBinary(keys, args);
return insertScript.executeBinaryAsync(keys, args)
.thenApply(result -> (boolean) result);
}
}
@@ -9,9 +9,11 @@ import io.lettuce.core.ScriptOutputType;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.util.Util;
/**
* Inserts the shared multi-recipient message payload into the cache. The list of recipients and views will be set as
@@ -31,7 +33,7 @@ class MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript {
ScriptOutputType.INTEGER);
}
void execute(final byte[] sharedMrmKey, final SealedSenderMultiRecipientMessage message) {
CompletableFuture<Void> executeAsync(final byte[] sharedMrmKey, final SealedSenderMultiRecipientMessage message) {
final List<byte[]> keys = List.of(
sharedMrmKey // sharedMrmKey
);
@@ -47,6 +49,7 @@ class MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript {
}
});
script.executeBinary(keys, args);
return script.executeBinaryAsync(keys, args)
.thenRun(Util.NOOP);
}
}
@@ -6,18 +6,23 @@ package org.whispersystems.textsecuregcm.storage;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.protobuf.ByteString;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import java.time.Clock;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javax.annotation.Nullable;
import org.reactivestreams.Publisher;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
@@ -25,6 +30,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.util.Pair;
import reactor.core.observability.micrometer.Micrometer;
@@ -48,41 +55,120 @@ public class MessagesManager {
private final MessagesCache messagesCache;
private final ReportMessageManager reportMessageManager;
private final ExecutorService messageDeletionExecutor;
private final Clock clock;
public MessagesManager(
final MessagesDynamoDb messagesDynamoDb,
final MessagesCache messagesCache,
final ReportMessageManager reportMessageManager,
final ExecutorService messageDeletionExecutor) {
final ExecutorService messageDeletionExecutor,
final Clock clock) {
this.messagesDynamoDb = messagesDynamoDb;
this.messagesCache = messagesCache;
this.reportMessageManager = reportMessageManager;
this.messageDeletionExecutor = messageDeletionExecutor;
this.clock = clock;
}
/**
* Inserts a message into a target device's message queue and notifies registered listeners that a new message is
* available.
* Inserts messages into the message queues for devices associated with the identified account.
*
* @param destinationUuid the account identifier for the destination queue
* @param destinationDeviceId the device ID for the destination queue
* @param message the message to insert into the queue
* @param accountIdentifier the account identifier for the destination queue
* @param messagesByDeviceId a map of device IDs to messages
*
* @return {@code true} if the destination device is "present" (i.e. has an active event listener) or {@code false}
* otherwise
* @return a map of device IDs to a device's presence state (i.e. if the device has an active event listener)
*
* @see org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager
*/
public boolean insert(final UUID destinationUuid, final byte destinationDeviceId, final Envelope message) {
final UUID messageGuid = UUID.randomUUID();
public Map<Byte, Boolean> insert(final UUID accountIdentifier, final Map<Byte, Envelope> messagesByDeviceId) {
return insertAsync(accountIdentifier, messagesByDeviceId).join();
}
final boolean destinationPresent = messagesCache.insert(messageGuid, destinationUuid, destinationDeviceId, message);
private CompletableFuture<Map<Byte, Boolean>> insertAsync(final UUID accountIdentifier, final Map<Byte, Envelope> messagesByDeviceId) {
final Map<Byte, Boolean> devicePresenceById = new ConcurrentHashMap<>();
if (message.hasSourceServiceId() && !destinationUuid.toString().equals(message.getSourceServiceId())) {
reportMessageManager.store(message.getSourceServiceId(), messageGuid);
}
return CompletableFuture.allOf(messagesByDeviceId.entrySet().stream()
.map(deviceIdAndMessage -> {
final byte deviceId = deviceIdAndMessage.getKey();
final Envelope message = deviceIdAndMessage.getValue();
final UUID messageGuid = UUID.randomUUID();
return destinationPresent;
return messagesCache.insert(messageGuid, accountIdentifier, deviceId, message)
.thenAccept(present -> {
if (message.hasSourceServiceId() && !accountIdentifier.toString()
.equals(message.getSourceServiceId())) {
// Note that this is an asynchronous, best-effort, fire-and-forget operation
reportMessageManager.store(message.getSourceServiceId(), messageGuid);
}
devicePresenceById.put(deviceId, present);
});
})
.toArray(CompletableFuture[]::new))
.thenApply(ignored -> devicePresenceById);
}
/**
* Inserts messages into the message queues for devices associated with the identified accounts.
*
* @param multiRecipientMessage the multi-recipient message to insert into destination queues
* @param resolvedRecipients a map of multi-recipient message {@code Recipient} entities to their corresponding
* Signal accounts; messages will not be delivered to unresolved recipients
* @param clientTimestamp the timestamp for the message as reported by the sending party
* @param isStory {@code true} if the given message is a story or {@code false} otherwise
* @param isEphemeral {@code true} if the given message should only be delivered to devices with active
* connections to a Signal server or {@code false} otherwise
* @param isUrgent {@code true} if the given message is urgent or {@code false} otherwise
*
* @return a map of accounts to maps of device IDs to a device's presence state (i.e. if the device has an active
* event listener)
*
* @see org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager
*/
public CompletableFuture<Map<Account, Map<Byte, Boolean>>> insertMultiRecipientMessage(
final SealedSenderMultiRecipientMessage multiRecipientMessage,
final Map<SealedSenderMultiRecipientMessage.Recipient, Account> resolvedRecipients,
final long clientTimestamp,
final boolean isStory,
final boolean isEphemeral,
final boolean isUrgent) {
final long serverTimestamp = clock.millis();
return insertSharedMultiRecipientMessagePayload(multiRecipientMessage)
.thenCompose(sharedMrmKey -> {
final Envelope prototypeMessage = Envelope.newBuilder()
.setType(Envelope.Type.UNIDENTIFIED_SENDER)
.setClientTimestamp(clientTimestamp == 0 ? serverTimestamp : clientTimestamp)
.setServerTimestamp(serverTimestamp)
.setStory(isStory)
.setEphemeral(isEphemeral)
.setUrgent(isUrgent)
.setSharedMrmKey(ByteString.copyFrom(sharedMrmKey))
.build();
final Map<Account, Map<Byte, Boolean>> clientPresenceByAccountAndDevice = new ConcurrentHashMap<>();
return CompletableFuture.allOf(multiRecipientMessage.getRecipients().entrySet().stream()
.filter(serviceIdAndRecipient -> resolvedRecipients.containsKey(serviceIdAndRecipient.getValue()))
.map(serviceIdAndRecipient -> {
final ServiceIdentifier serviceIdentifier = ServiceIdentifier.fromLibsignal(serviceIdAndRecipient.getKey());
final SealedSenderMultiRecipientMessage.Recipient recipient = serviceIdAndRecipient.getValue();
final byte[] devices = recipient.getDevices();
return insertAsync(resolvedRecipients.get(recipient).getIdentifier(IdentityType.ACI),
IntStream.range(0, devices.length).mapToObj(i -> devices[i])
.collect(Collectors.toMap(deviceId -> deviceId, deviceId -> prototypeMessage.toBuilder()
.setDestinationServiceId(serviceIdentifier.toServiceIdentifierString())
.build())))
.thenAccept(clientPresenceByDeviceId ->
clientPresenceByAccountAndDevice.put(resolvedRecipients.get(recipient),
clientPresenceByDeviceId));
})
.toArray(CompletableFuture[]::new))
.thenApply(ignored -> clientPresenceByAccountAndDevice);
});
}
public CompletableFuture<Boolean> mayHavePersistedMessages(final UUID destinationUuid, final Device destinationDevice) {
@@ -217,7 +303,7 @@ public class MessagesManager {
* @return a key where the shared data is stored
* @see MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript
*/
public byte[] insertSharedMultiRecipientMessagePayload(
private CompletableFuture<byte[]> insertSharedMultiRecipientMessagePayload(
final SealedSenderMultiRecipientMessage sealedSenderMultiRecipientMessage) {
return messagesCache.insertSharedMultiRecipientMessagePayload(sealedSenderMultiRecipientMessage);
}
@@ -0,0 +1,104 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import com.google.common.annotations.VisibleForTesting;
import io.lettuce.core.SetArgs;
import io.micrometer.core.instrument.Timer;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.util.Util;
/**
* Timers for operations that may span machines or requests and require a persistently stored timer start itme
*/
public class PersistentTimer {
private static final Logger logger = LoggerFactory.getLogger(PersistentTimer.class);
private static String TIMER_NAMESPACE = "persistent_timer";
@VisibleForTesting
static final Duration TIMER_TTL = Duration.ofHours(1);
private final FaultTolerantRedisClusterClient redisClient;
private final Clock clock;
public PersistentTimer(final FaultTolerantRedisClusterClient redisClient, final Clock clock) {
this.redisClient = redisClient;
this.clock = clock;
}
public class Sample {
private final Instant start;
private final String redisKey;
public Sample(final Instant start, final String redisKey) {
this.start = start;
this.redisKey = redisKey;
}
/**
* Stop the timer, recording the duration between now and the first call to start. This deletes the persistent timer.
*
* @param timer The micrometer timer to record the duration to
* @return A future that completes when the resources associated with the persistent timer have been destroyed
*/
public CompletableFuture<Void> stop(Timer timer) {
Duration duration = Duration.between(start, clock.instant());
timer.record(duration);
return redisClient.withCluster(connection -> connection.async().del(redisKey))
.toCompletableFuture()
.thenRun(Util.NOOP);
}
}
/**
* Start the timer if a timer with the provided namespaced key has not already been started, otherwise return the
* existing sample.
*
* @param namespace A namespace prefix to use for the timer
* @param key The unique key within the namespace that identifies the timer
* @return A future that completes with a {@link Sample} that can later be used to record the final duration.
*/
public CompletableFuture<Sample> start(final String namespace, final String key) {
final Instant now = clock.instant();
final String redisKey = redisKey(namespace, key);
return redisClient.withCluster(connection ->
connection.async().setGet(redisKey, String.valueOf(now.getEpochSecond()), SetArgs.Builder.nx().ex(TIMER_TTL)))
.toCompletableFuture()
.thenApply(serialized -> new Sample(parseStoredTimestamp(serialized).orElse(now), redisKey));
}
@VisibleForTesting
String redisKey(final String namespace, final String key) {
return String.format("%s::%s::%s", TIMER_NAMESPACE, namespace, key);
}
private static Optional<Instant> parseStoredTimestamp(final @Nullable String serialized) {
return Optional
.ofNullable(serialized)
.flatMap(s -> {
try {
return Optional.of(Long.parseLong(s));
} catch (NumberFormatException e) {
logger.warn("Failed to parse stored timestamp {}", s, e);
return Optional.empty();
}
})
.map(Instant::ofEpochSecond);
}
}
@@ -3,6 +3,8 @@ package org.whispersystems.textsecuregcm.storage;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.util.Util;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemResponse;
@@ -11,6 +13,7 @@ import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
@@ -20,6 +23,7 @@ public class ReportMessageDynamoDb {
static final String ATTR_TTL = "E";
private final DynamoDbClient db;
private final DynamoDbAsyncClient dynamoDbAsyncClient;
private final String tableName;
private final Duration ttl;
@@ -30,20 +34,26 @@ public class ReportMessageDynamoDb {
.distributionStatisticExpiry(Duration.ofDays(1))
.register(Metrics.globalRegistry);
public ReportMessageDynamoDb(final DynamoDbClient dynamoDB, final String tableName, final Duration ttl) {
public ReportMessageDynamoDb(final DynamoDbClient dynamoDB,
final DynamoDbAsyncClient dynamoDbAsyncClient,
final String tableName,
final Duration ttl) {
this.db = dynamoDB;
this.dynamoDbAsyncClient = dynamoDbAsyncClient;
this.tableName = tableName;
this.ttl = ttl;
}
public void store(byte[] hash) {
db.putItem(PutItemRequest.builder()
public CompletableFuture<Void> store(byte[] hash) {
return dynamoDbAsyncClient.putItem(PutItemRequest.builder()
.tableName(tableName)
.item(Map.of(
KEY_HASH, AttributeValues.fromByteArray(hash),
ATTR_TTL, AttributeValues.fromLong(Instant.now().plus(ttl).getEpochSecond())
))
.build());
.build())
.thenRun(Util.NOOP);
}
public boolean remove(byte[] hash) {
@@ -54,11 +54,8 @@ public class ReportMessageManager {
}
public void store(String sourceAci, UUID messageGuid) {
try {
Objects.requireNonNull(sourceAci);
reportMessageDynamoDb.store(hash(messageGuid, sourceAci));
reportMessageDynamoDb.store(hash(messageGuid, Objects.requireNonNull(sourceAci)));
} catch (final Exception e) {
logger.warn("Failed to store hash", e);
}
@@ -94,8 +94,9 @@ class BraintreeGraphqlClient {
final CreatePayPalOneTimePaymentMutation.Data data = assertSuccessAndExtractDataFromApolloResponse(apolloResponse);
if (data.createPayPalOneTimePayment == null) {
logger.warn(
"createPayPalOneTimePayment requestId={} did not have any errors but data was null. response={}",
apolloResponse.extensions.getOrDefault("requestId", "<No-Request-Id>"), httpResponse.body());
"createPayPalOneTimePayment requestId={} currency={} amount={} did not have any errors but data was null. response={}",
apolloResponse.extensions.getOrDefault("requestId", "<No-Request-Id>"),
currency, amount, httpResponse.body());
throw new ServiceUnavailableException();
}
return data.createPayPalOneTimePayment;
@@ -22,13 +22,15 @@ public class DestinationDeviceValidator {
/**
* @see #validateRegistrationIds(Account, Stream, boolean)
*/
public static <T> void validateRegistrationIds(final Account account, final Collection<T> messages,
Function<T, Byte> getDeviceId, Function<T, Integer> getRegistrationId, boolean usePhoneNumberIdentity)
throws StaleDevicesException {
public static <T> void validateRegistrationIds(final Account account,
final Collection<T> messages,
Function<T, Byte> getDeviceId,
Function<T, Integer> getRegistrationId,
boolean usePhoneNumberIdentity) throws StaleDevicesException {
validateRegistrationIds(account,
messages.stream().map(m -> new Pair<>(getDeviceId.apply(m), getRegistrationId.apply(m))),
usePhoneNumberIdentity);
}
/**
@@ -8,9 +8,6 @@ package org.whispersystems.textsecuregcm.websocket;
import static org.whispersystems.textsecuregcm.util.HeaderUtils.basicCredentialsFromAuthHeader;
import com.google.common.net.HttpHeaders;
import io.dropwizard.auth.basic.BasicCredentials;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import org.eclipse.jetty.websocket.api.UpgradeRequest;
import org.whispersystems.textsecuregcm.auth.AccountAuthenticator;
@@ -26,7 +23,6 @@ public class WebSocketAccountAuthenticator implements WebSocketAuthenticator<Aut
private static final ReusableAuth<AuthenticatedDevice> CREDENTIALS_NOT_PRESENTED = ReusableAuth.anonymous();
private static final ReusableAuth<AuthenticatedDevice> INVALID_CREDENTIALS_PRESENTED = ReusableAuth.invalid();
private final AccountAuthenticator accountAuthenticator;
private final PrincipalSupplier<AuthenticatedDevice> principalSupplier;
@@ -40,13 +36,7 @@ public class WebSocketAccountAuthenticator implements WebSocketAuthenticator<Aut
public ReusableAuth<AuthenticatedDevice> authenticate(final UpgradeRequest request)
throws AuthenticationException {
try {
// If the `Authorization` header was set for the request it takes priority, and we use the result of the
// header-based auth ignoring the result of the query-based auth.
final String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
if (authHeader != null) {
return authenticatedAccountFromHeaderAuth(authHeader);
}
return authenticatedAccountFromQueryParams(request);
return authenticatedAccountFromHeaderAuth(request.getHeader(HttpHeaders.AUTHORIZATION));
} catch (final Exception e) {
// this will be handled and logged upstream
// the most likely exception is a transient error connecting to account storage
@@ -54,23 +44,7 @@ public class WebSocketAccountAuthenticator implements WebSocketAuthenticator<Aut
}
}
private ReusableAuth<AuthenticatedDevice> authenticatedAccountFromQueryParams(final UpgradeRequest request) {
final Map<String, List<String>> parameters = request.getParameterMap();
final List<String> usernames = parameters.get("login");
final List<String> passwords = parameters.get("password");
if (usernames == null || usernames.size() == 0 ||
passwords == null || passwords.size() == 0) {
return CREDENTIALS_NOT_PRESENTED;
}
final BasicCredentials credentials = new BasicCredentials(usernames.get(0).replace(" ", "+"),
passwords.get(0).replace(" ", "+"));
return accountAuthenticator.authenticate(credentials)
.map(authenticatedAccount -> ReusableAuth.authenticated(authenticatedAccount, this.principalSupplier))
.orElse(INVALID_CREDENTIALS_PRESENTED);
}
private ReusableAuth<AuthenticatedDevice> authenticatedAccountFromHeaderAuth(@Nullable final String authHeader)
throws AuthenticationException {
private ReusableAuth<AuthenticatedDevice> authenticatedAccountFromHeaderAuth(@Nullable final String authHeader) {
if (authHeader == null) {
return CREDENTIALS_NOT_PRESENTED;
}
@@ -217,13 +217,13 @@ record CommandDependencies(
MessagesCache messagesCache = new MessagesCache(messagesCluster,
messageDeliveryScheduler, messageDeletionExecutor, Clock.systemUTC());
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster);
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbClient,
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
configuration.getDynamoDbTables().getReportMessage().getTableName(),
configuration.getReportMessageConfiguration().getReportTtl());
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster,
configuration.getReportMessageConfiguration().getCounterTtl());
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache,
reportMessageManager, messageDeletionExecutor);
reportMessageManager, messageDeletionExecutor, Clock.systemUTC());
AccountLockManager accountLockManager = new AccountLockManager(dynamoDbClient,
configuration.getDynamoDbTables().getDeletedAccountsLock().getTableName());
ClientPublicKeysManager clientPublicKeysManager =
@@ -0,0 +1,96 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.workers;
import com.google.common.annotations.VisibleForTesting;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.CompletableFuture;
import org.apache.commons.lang3.StringUtils;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import reactor.core.publisher.Mono;
/**
* Checks if a device may benefit from receiving a push notification
*/
public class IdleWakeupEligibilityChecker {
@VisibleForTesting
static final Duration MIN_SHORT_IDLE_DURATION = Duration.ofDays(3);
@VisibleForTesting
static final Duration MAX_SHORT_IDLE_DURATION = Duration.ofDays(30);
@VisibleForTesting
static final Duration MIN_LONG_IDLE_DURATION = Duration.ofDays(60);
@VisibleForTesting
static final Duration MAX_LONG_IDLE_DURATION = Duration.ofDays(75);
private final MessagesManager messagesManager;
private final Clock clock;
public IdleWakeupEligibilityChecker(final Clock clock, final MessagesManager messagesManager) {
this.messagesManager = messagesManager;
this.clock = clock;
}
/**
* Determine whether the device may benefit from a push notification.
*
* @param account The account to check
* @param device The device to check
* @return true if the device may benefit from a push notification, otherwise false
* @implNote There are two populations that may benefit from a wakeup:
* <ol>
* <li> Devices that have only been idle for a little while, but have messages that they don't seem to be retrieving
* <li> Devices that have been idle for a long time, but don't have any messages
* </ol>
* We think the first group sometimes just needs a little nudge to wake up and get their messages, and the latter
* group generally WOULD get their messages if they had any. We want to notify the first group to prompt them to
* actually get their messages and the latter group to prevent them from getting deleted due to inactivity (since they
* are otherwise healthy installations that just aren't getting much traffic).
*/
public CompletableFuture<Boolean> isDeviceEligible(final Account account, final Device device) {
if (!hasPushToken(device)) {
return CompletableFuture.completedFuture(false);
}
if (isShortIdle(device, clock)) {
return messagesManager.mayHaveUrgentPersistedMessages(account.getIdentifier(IdentityType.ACI), device);
} else if (isLongIdle(device, clock)) {
return messagesManager.mayHavePersistedMessages(account.getIdentifier(IdentityType.ACI), device)
.thenApply(mayHavePersistedMessages -> !mayHavePersistedMessages);
} else {
return CompletableFuture.completedFuture(false);
}
}
@VisibleForTesting
static boolean isShortIdle(final Device device, final Clock clock) {
final Duration idleDuration = Duration.between(Instant.ofEpochMilli(device.getLastSeen()), clock.instant());
return idleDuration.compareTo(MIN_SHORT_IDLE_DURATION) >= 0 && idleDuration.compareTo(MAX_SHORT_IDLE_DURATION) < 0;
}
@VisibleForTesting
static boolean isLongIdle(final Device device, final Clock clock) {
final Duration idleDuration = Duration.between(Instant.ofEpochMilli(device.getLastSeen()), clock.instant());
return idleDuration.compareTo(MIN_LONG_IDLE_DURATION) >= 0 && idleDuration.compareTo(MAX_LONG_IDLE_DURATION) < 0;
}
@VisibleForTesting
static boolean hasPushToken(final Device device) {
return !StringUtils.isAllBlank(device.getApnId(), device.getGcmId());
}
}
@@ -4,7 +4,6 @@ import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import net.sourceforge.argparse4j.inf.Subparser;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.configuration.DynamoDbTables;
@@ -18,8 +17,6 @@ import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuples;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalTime;
public class NotifyIdleDevicesCommand extends AbstractSinglePassCrawlAccountsCommand {
@@ -35,18 +32,6 @@ public class NotifyIdleDevicesCommand extends AbstractSinglePassCrawlAccountsCom
@VisibleForTesting
static final LocalTime PREFERRED_NOTIFICATION_TIME = LocalTime.of(14, 0);
@VisibleForTesting
static final Duration MIN_SHORT_IDLE_DURATION = Duration.ofDays(3);
@VisibleForTesting
static final Duration MAX_SHORT_IDLE_DURATION = Duration.ofDays(30);
@VisibleForTesting
static final Duration MIN_LONG_IDLE_DURATION = Duration.ofDays(60);
@VisibleForTesting
static final Duration MAX_LONG_IDLE_DURATION = Duration.ofDays(75);
private static final Counter DEVICE_INSPECTED_COUNTER =
Metrics.counter(MetricsUtil.name(NotifyIdleDevicesCommand.class, "deviceInspected"));
@@ -87,12 +72,15 @@ public class NotifyIdleDevicesCommand extends AbstractSinglePassCrawlAccountsCom
final MessagesManager messagesManager = getCommandDependencies().messagesManager();
final IdleDeviceNotificationScheduler idleDeviceNotificationScheduler = buildIdleDeviceNotificationScheduler();
final Clock clock = getClock();
final IdleWakeupEligibilityChecker idleWakeupEligibilityChecker = new IdleWakeupEligibilityChecker(clock, messagesManager);
accounts
.flatMap(account -> Flux.fromIterable(account.getDevices()).map(device -> Tuples.of(account, device)))
.doOnNext(ignored -> DEVICE_INSPECTED_COUNTER.increment())
.flatMap(accountAndDevice -> isDeviceEligible(accountAndDevice.getT1(), accountAndDevice.getT2(), messagesManager, clock)
.mapNotNull(eligible -> eligible ? accountAndDevice : null), maxConcurrency)
.flatMap(accountAndDevice -> Mono.fromFuture(() ->
idleWakeupEligibilityChecker.isDeviceEligible(accountAndDevice.getT1(), accountAndDevice.getT2()))
.mapNotNull(eligible -> eligible ? accountAndDevice : null),
maxConcurrency)
.flatMap(accountAndDevice -> {
final Account account = accountAndDevice.getT1();
final Device device = accountAndDevice.getT2();
@@ -136,52 +124,4 @@ public class NotifyIdleDevicesCommand extends AbstractSinglePassCrawlAccountsCom
Clock.systemUTC());
}
@VisibleForTesting
static Mono<Boolean> isDeviceEligible(final Account account,
final Device device,
final MessagesManager messagesManager,
final Clock clock) {
// There are two populations of interest for this crawler:
//
// 1. Devices that have only been idle for a little while, but have messages that they don't seem to be retrieving
// 2. Devices that have been idle for a long time, but don't have any messages
//
// We think the first group sometimes just needs a little nudge to wake up and get their messages, and the latter
// group generally WOULD get their messages if they had any. We want to notify the first group to prompt them to
// actually get their messages and the latter group to prevent them from getting deleted due to inactivity (since
// they are otherwise healthy installations that just aren't getting much traffic).
if (!hasPushToken(device)) {
return Mono.just(false);
}
if (isShortIdle(device, clock)) {
return Mono.fromFuture(messagesManager.mayHaveUrgentPersistedMessages(account.getIdentifier(IdentityType.ACI), device));
} else if (isLongIdle(device, clock)) {
return Mono.fromFuture(messagesManager.mayHavePersistedMessages(account.getIdentifier(IdentityType.ACI), device))
.map(mayHavePersistedMessages -> !mayHavePersistedMessages);
} else {
return Mono.just(false);
}
}
@VisibleForTesting
static boolean isShortIdle(final Device device, final Clock clock) {
final Duration idleDuration = Duration.between(Instant.ofEpochMilli(device.getLastSeen()), clock.instant());
return idleDuration.compareTo(MIN_SHORT_IDLE_DURATION) >= 0 && idleDuration.compareTo(MAX_SHORT_IDLE_DURATION) < 0;
}
@VisibleForTesting
static boolean isLongIdle(final Device device, final Clock clock) {
final Duration idleDuration = Duration.between(Instant.ofEpochMilli(device.getLastSeen()), clock.instant());
return idleDuration.compareTo(MIN_LONG_IDLE_DURATION) >= 0 && idleDuration.compareTo(MAX_LONG_IDLE_DURATION) < 0;
}
@VisibleForTesting
static boolean hasPushToken(final Device device) {
return !StringUtils.isAllBlank(device.getApnId(), device.getGcmId());
}
}
@@ -295,19 +295,19 @@ message MonitorRequest {
message AciMonitorRequest {
bytes aci = 1;
repeated uint64 entries = 2;
uint64 entry_position = 2;
bytes commitment_index = 3;
}
message UsernameHashMonitorRequest {
bytes username_hash = 1;
repeated uint64 entries = 2;
uint64 entry_position = 2;
bytes commitment_index = 3;
}
message E164MonitorRequest {
string e164 = 1;
repeated uint64 entries = 2;
uint64 entry_position = 2;
bytes commitment_index = 3;
}
@@ -39,6 +39,12 @@ message CreateRegistrationSessionRequest {
* session represents a "re-registration" attempt).
*/
bool account_exists_with_e164 = 2;
/**
* The session creation rate limit for the number will be
* collated by this key.
*/
string rate_limit_collation_key = 3;
}
message CreateRegistrationSessionResponse {
@@ -17,11 +17,12 @@ import jakarta.ws.rs.core.Response;
import java.net.URI;
import java.util.List;
import java.util.Map;
import org.eclipse.jetty.util.component.LifeCycle;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.StatusCode;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.whispersystems.textsecuregcm.metrics.NoopAwsSdkMetricPublisher;
@@ -47,27 +48,22 @@ class WhisperServerServiceTest {
Resources.getResource("config/test-secrets-bundle.yml").getPath());
}
private static final WebSocketClient webSocketClient = new WebSocketClient();
private static final DropwizardAppExtension<WhisperServerConfiguration> EXTENSION = new DropwizardAppExtension<>(
WhisperServerService.class, Resources.getResource("config/test.yml").getPath());
private WebSocketClient webSocketClient;
@AfterAll
static void teardown() {
System.clearProperty("secrets.bundle.filename");
}
@BeforeEach
void setUp() throws Exception {
webSocketClient = new WebSocketClient();
@BeforeAll
static void setUp() throws Exception {
webSocketClient.start();
}
@AfterEach
void tearDown() throws Exception {
webSocketClient.stop();
}
@Test
void start() throws Exception {
// make sure the service nominally starts and responds to health checks
@@ -96,6 +92,16 @@ class WhisperServerServiceTest {
final TestWebsocketListener testWebsocketListener = new TestWebsocketListener();
EXTENSION.getTestSupport().getEnvironment().getApplicationContext().getServer()
.addEventListener(new LifeCycle.Listener() {
@Override
public void lifeCycleStopped(final LifeCycle event) {
// closed by org.eclipse.jetty.websocket.common.SessionTracker during the container Lifecycle stopping phase
assertEquals(StatusCode.SHUTDOWN, testWebsocketListener.closeFuture().getNow(-1));
}
});
// Session is Closeable, but we intentionally keep it open so that we can confirm the container Lifecycle behavior
final Session session = webSocketClient.connect(testWebsocketListener,
URI.create(String.format("ws://localhost:%d/v1/websocket/", EXTENSION.getLocalPort())))
.join();
@@ -112,6 +118,8 @@ class WhisperServerServiceTest {
assertEquals(401, whoami.getStatus());
final long whoamiTimestamp = Long.parseLong(whoami.getHeaders().get(HeaderUtils.TIMESTAMP_HEADER.toLowerCase()));
assertTrue(whoamiTimestamp >= start);
}
@Test
@@ -1,137 +0,0 @@
package org.whispersystems.textsecuregcm.auth;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
public class TurnTokenGeneratorTest {
@Test
public void testAlwaysSelectFirst() throws JsonProcessingException {
final String configString = """
captcha:
scoreFloor: 1.0
turn:
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, "bloop".getBytes(StandardCharsets.UTF_8));
final long COUNT = 1000;
final Map<String, Long> urlCounts = Stream
.generate(() -> turnTokenGenerator.generate(UUID.randomUUID()))
.limit(COUNT)
.flatMap(token -> token.urls().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:
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, "bloop".getBytes(StandardCharsets.UTF_8));
final long COUNT = 1000;
final Map<String, Long> urlCounts = Stream
.generate(() -> turnTokenGenerator.generate(UUID.randomUUID()))
.limit(COUNT)
.flatMap(token -> token.urls().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
enrolledAcis:
- 732506d7-d04f-43a4-b1d7-8a3a91ebe8a6
- 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, "bloop".getBytes(StandardCharsets.UTF_8));
TurnToken token = turnTokenGenerator.generate(UUID.fromString("732506d7-d04f-43a4-b1d7-8a3a91ebe8a6"));
assertThat(token.urls().get(0)).isEqualTo("enrolled.org");
token = turnTokenGenerator.generate(UUID.randomUUID());
assertThat(token.urls().get(0)).isEqualTo("unenrolled.org");
}
}
@@ -117,7 +117,7 @@ public class TurnCallRouterTest {
() -> callDnsRecords,
() -> performanceTable,
() -> manualTable,
configTurnRouter,
configTurnRouter,
() -> geoIp,
// set to true so the return values are predictable
true
@@ -127,8 +127,8 @@ public class TurnCallRouterTest {
TurnServerOptions optionsWithUrls(List<String> urls) {
return new TurnServerOptions(
TEST_HOSTNAME,
urls,
EXPECTED_TEST_URLS_WITH_HOSTS
Optional.of(urls),
Optional.of(EXPECTED_TEST_URLS_WITH_HOSTS)
);
}
@@ -144,8 +144,8 @@ public class TurnCallRouterTest {
assertThat(router().getRoutingFor(aci, Optional.of(InetAddress.getByName("0.0.0.1")), 10))
.isEqualTo(new TurnServerOptions(
TEST_HOSTNAME,
null,
targetedUrls
Optional.empty(),
Optional.of(targetedUrls)
));
}
@@ -157,8 +157,23 @@ public class TurnCallRouterTest {
assertThat(router().getRoutingFor(aci, Optional.of(InetAddress.getByName("0.0.0.1")), 10))
.isEqualTo(new TurnServerOptions(
TEST_HOSTNAME,
null,
TEST_URLS_WITH_HOSTS
Optional.empty(),
Optional.of(TEST_URLS_WITH_HOSTS)
));
}
@Test
public void testUrlsOnlyNoInstanceIps() throws UnknownHostException {
when(performanceTable.getDatacentersFor(any(), any(), any(), any()))
.thenReturn(List.of("dc-performance2", "dc-performance1"));
when(configTurnRouter.shouldRandomize())
.thenReturn(false);
assertThat(router().getRoutingFor(aci, Optional.of(InetAddress.getByName("0.0.0.1")), 0))
.isEqualTo(new TurnServerOptions(
TEST_HOSTNAME,
Optional.empty(),
Optional.of(TEST_URLS_WITH_HOSTS)
));
}
@@ -10,7 +10,7 @@ import java.math.BigDecimal;
import java.net.http.HttpClient;
import java.util.Collections;
import java.util.Map;
import org.whispersystems.textsecuregcm.currency.CoinMarketCapClient;
import org.whispersystems.textsecuregcm.currency.CoinGeckoClient;
import org.whispersystems.textsecuregcm.currency.FixerClient;
@JsonTypeName("stub")
@@ -22,8 +22,8 @@ public class StubPaymentsServiceClientsFactory implements PaymentsServiceClients
}
@Override
public CoinMarketCapClient buildCoinMarketCapClient(final HttpClient httpClient) {
return new StubCoinMarketCapClient();
public CoinGeckoClient buildCoinGeckoClient(final HttpClient httpClient) {
return new StubCoinGeckoClient();
}
/**
@@ -44,9 +44,9 @@ public class StubPaymentsServiceClientsFactory implements PaymentsServiceClients
/**
* Always returns {@code 0} for spot price checks
*/
private static class StubCoinMarketCapClient extends CoinMarketCapClient {
private static class StubCoinGeckoClient extends CoinGeckoClient {
public StubCoinMarketCapClient() {
public StubCoinGeckoClient() {
super(null, null, null);
}
@@ -23,6 +23,7 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
import org.whispersystems.textsecuregcm.entities.RegistrationServiceSession;
import org.whispersystems.textsecuregcm.registration.ClientType;
import org.whispersystems.textsecuregcm.registration.MessageTransport;
@@ -35,12 +36,16 @@ public class StubRegistrationServiceClientFactory implements RegistrationService
@NotNull
private String registrationCaCertificate;
@JsonProperty
@NotNull
private SecretBytes collationKeySalt;
@Override
public RegistrationServiceClient build(final Environment environment, final Executor callbackExecutor,
final ScheduledExecutorService identityRefreshExecutor) {
try {
return new StubRegistrationServiceClient(registrationCaCertificate);
return new StubRegistrationServiceClient(registrationCaCertificate, collationKeySalt.value());
} catch (IOException e) {
throw new RuntimeException(e);
}
@@ -50,13 +55,13 @@ public class StubRegistrationServiceClientFactory implements RegistrationService
private final static Map<String, RegistrationServiceSession> SESSIONS = new ConcurrentHashMap<>();
public StubRegistrationServiceClient(final String registrationCaCertificate) throws IOException {
super("example.com", 8080, null, registrationCaCertificate, null);
public StubRegistrationServiceClient(final String registrationCaCertificate, final byte[] collationKeySalt) throws IOException {
super("example.com", 8080, null, registrationCaCertificate, collationKeySalt, null);
}
@Override
public CompletableFuture<RegistrationServiceSession> createRegistrationSession(
final Phonenumber.PhoneNumber phoneNumber, final boolean accountExistsWithPhoneNumber, final Duration timeout) {
final Phonenumber.PhoneNumber phoneNumber, final String sourceHost, final boolean accountExistsWithPhoneNumber, final Duration timeout) {
final String e164 = PhoneNumberUtil.getInstance()
.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164);
@@ -376,6 +376,23 @@ class DynamicConfigurationTest {
assertThat(turnConfiguration.getHostname()).isEqualTo("test.domain.org");
assertThat(turnConfiguration.getRandomizeRate()).isEqualTo(100_000L);
assertThat(turnConfiguration.getDefaultInstanceIpCount()).isEqualTo(0);
}
{
final String config = REQUIRED_CONFIG.concat("""
turn:
uriConfigs:
- uris:
- turn:test0.org
- turn:test1.org
defaultInstanceIpCount: 5
""");
DynamicTurnConfiguration turnConfiguration = DynamicConfigurationManager
.parseConfiguration(config, DynamicConfiguration.class)
.orElseThrow()
.getTurnConfiguration();
assertThat(turnConfiguration.getDefaultInstanceIpCount()).isEqualTo(5);
}
}
@@ -159,7 +159,6 @@ class AccountControllerTest {
.addResource(new AccountController(
accountsManager,
rateLimiters,
turnTokenGenerator,
registrationRecoveryPasswordsManager,
usernameZkProofVerifier
))
@@ -1,185 +0,0 @@
/*
* Copyright 2013 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.controllers;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.when;
import io.dropwizard.auth.AuthValueFactoryProvider;
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
import io.dropwizard.testing.junit5.ResourceExtension;
import jakarta.ws.rs.core.Response;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
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.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.CloudflareTurnCredentialsManager;
import org.whispersystems.textsecuregcm.auth.TurnToken;
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
import org.whispersystems.textsecuregcm.calls.routing.TurnCallRouter;
import org.whispersystems.textsecuregcm.calls.routing.TurnServerOptions;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.TestRemoteAddressFilterProvider;
@ExtendWith(DropwizardExtensionsSupport.class)
class CallRoutingControllerTest {
private static final String GET_CALL_ENDPOINTS_PATH = "v1/calling/relays";
private static final String REMOTE_ADDRESS = "123.123.123.1";
private static final RateLimiters rateLimiters = mock(RateLimiters.class);
private static final RateLimiter getCallEndpointLimiter = mock(RateLimiter.class);
private static final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = mock(
DynamicConfigurationManager.class);
private static final ExperimentEnrollmentManager experimentEnrollmentManager = mock(
ExperimentEnrollmentManager.class);
private static final TurnTokenGenerator turnTokenGenerator = new TurnTokenGenerator(dynamicConfigurationManager,
"bloop".getBytes(StandardCharsets.UTF_8));
private static final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager = mock(
CloudflareTurnCredentialsManager.class);
private static final TurnCallRouter turnCallRouter = mock(TurnCallRouter.class);
private static final ResourceExtension resources = ResourceExtension.builder()
.addProvider(AuthHelper.getAuthFilter())
.addProvider(new AuthValueFactoryProvider.Binder<>(AuthenticatedDevice.class))
.addProvider(new RateLimitExceededExceptionMapper())
.addProvider(new TestRemoteAddressFilterProvider(REMOTE_ADDRESS))
.setMapper(SystemMapper.jsonMapper())
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
.addResource(new CallRoutingController(rateLimiters, turnCallRouter, turnTokenGenerator,
experimentEnrollmentManager, cloudflareTurnCredentialsManager))
.build();
@BeforeEach
void setup() {
when(rateLimiters.getCallEndpointLimiter()).thenReturn(getCallEndpointLimiter);
}
@AfterEach
void tearDown() {
reset(experimentEnrollmentManager, dynamicConfigurationManager, rateLimiters, getCallEndpointLimiter,
turnCallRouter);
}
@Test
void testGetTurnEndpointsSuccess() throws UnknownHostException {
TurnServerOptions options = new TurnServerOptions(
"example.domain.org",
List.of("stun:12.34.56.78"),
List.of("stun:example.domain.org")
);
when(turnCallRouter.getRoutingFor(
eq(AuthHelper.VALID_UUID),
eq(Optional.of(InetAddress.getByName(REMOTE_ADDRESS))),
anyInt())
).thenReturn(options);
try (Response response = resources.getJerseyTest()
.target(GET_CALL_ENDPOINTS_PATH)
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get()) {
assertThat(response.getStatus()).isEqualTo(200);
TurnToken token = response.readEntity(TurnToken.class);
assertThat(token.username()).isNotEmpty();
assertThat(token.password()).isNotEmpty();
assertThat(token.hostname()).isEqualTo(options.hostname());
assertThat(token.urlsWithIps()).isEqualTo(options.urlsWithIps());
assertThat(token.urls()).isEqualTo(options.urlsWithHostname());
}
}
@Test
void testGetTurnEndpointsCloudflare() throws IOException {
when(experimentEnrollmentManager.isEnrolled(AuthHelper.VALID_NUMBER, AuthHelper.VALID_UUID, "cloudflareTurn"))
.thenReturn(true);
when(cloudflareTurnCredentialsManager.retrieveFromCloudflare()).thenReturn(new TurnToken("ABC", "XYZ",
List.of("turn:cloudflare.example.com:3478?transport=udp"), null,
"cf.example.com"));
try (Response response = resources.getJerseyTest()
.target(GET_CALL_ENDPOINTS_PATH)
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get()) {
assertThat(response.getStatus()).isEqualTo(200);
TurnToken token = response.readEntity(TurnToken.class);
assertThat(token.username()).isEqualTo("ABC");
assertThat(token.password()).isEqualTo("XYZ");
assertThat(token.hostname()).isEqualTo("cf.example.com");
assertThat(token.urlsWithIps()).isNull();
assertThat(token.urls()).isEqualTo(List.of("turn:cloudflare.example.com:3478?transport=udp"));
}
}
@Test
void testGetTurnEndpointsInvalidIpSuccess() throws UnknownHostException {
TurnServerOptions options = new TurnServerOptions(
"example.domain.org",
List.of(),
List.of("stun:example.domain.org")
);
when(turnCallRouter.getRoutingFor(
eq(AuthHelper.VALID_UUID),
eq(Optional.of(InetAddress.getByName(REMOTE_ADDRESS))),
anyInt())
).thenReturn(options);
try (Response response = resources.getJerseyTest()
.target(GET_CALL_ENDPOINTS_PATH)
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get()) {
assertThat(response.getStatus()).isEqualTo(200);
TurnToken token = response.readEntity(TurnToken.class);
assertThat(token.username()).isNotEmpty();
assertThat(token.password()).isNotEmpty();
assertThat(token.hostname()).isEqualTo(options.hostname());
assertThat(token.urlsWithIps()).isEqualTo(options.urlsWithIps());
assertThat(token.urls()).isEqualTo(options.urlsWithHostname());
}
}
@Test
void testGetTurnEndpointRateLimited() throws RateLimitExceededException {
doThrow(new RateLimitExceededException(null))
.when(getCallEndpointLimiter).validate(AuthHelper.VALID_UUID);
try (final Response response = resources.getJerseyTest()
.target(GET_CALL_ENDPOINTS_PATH)
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get()) {
assertThat(response.getStatus()).isEqualTo(429);
}
}
}
@@ -34,12 +34,10 @@ import org.whispersystems.textsecuregcm.auth.TurnToken;
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
import org.whispersystems.textsecuregcm.calls.routing.TurnCallRouter;
import org.whispersystems.textsecuregcm.calls.routing.TurnServerOptions;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.TestRemoteAddressFilterProvider;
@@ -51,8 +49,8 @@ class CallRoutingControllerV2Test {
private static final String REMOTE_ADDRESS = "123.123.123.1";
private static final TurnServerOptions TURN_SERVER_OPTIONS = new TurnServerOptions(
"example.domain.org",
List.of("stun:12.34.56.78"),
List.of("stun:example.domain.org")
Optional.of(List.of("stun:12.34.56.78")),
Optional.of(List.of("stun:example.domain.org"))
);
private static final TurnToken CLOUDFLARE_TURN_TOKEN = new TurnToken(
"ABC",
@@ -63,12 +61,9 @@ class CallRoutingControllerV2Test {
private static final RateLimiters rateLimiters = mock(RateLimiters.class);
private static final RateLimiter getCallEndpointLimiter = mock(RateLimiter.class);
private static final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = mock(
DynamicConfigurationManager.class);
private static final ExperimentEnrollmentManager experimentEnrollmentManager = mock(
ExperimentEnrollmentManager.class);
private static final TurnTokenGenerator turnTokenGenerator = new TurnTokenGenerator(dynamicConfigurationManager,
"bloop".getBytes(StandardCharsets.UTF_8));
private static final TurnTokenGenerator turnTokenGenerator = new TurnTokenGenerator("bloop".getBytes(StandardCharsets.UTF_8));
private static final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager = mock(
CloudflareTurnCredentialsManager.class);
private static final TurnCallRouter turnCallRouter = mock(TurnCallRouter.class);
@@ -91,8 +86,7 @@ class CallRoutingControllerV2Test {
@AfterEach
void tearDown() {
reset(experimentEnrollmentManager, dynamicConfigurationManager, rateLimiters, getCallEndpointLimiter,
turnCallRouter);
reset(experimentEnrollmentManager, rateLimiters, getCallEndpointLimiter, turnCallRouter);
}
void initializeMocksWith(Optional<TurnServerOptions> signalTurn, Optional<TurnToken> cloudflare) {
@@ -100,8 +94,7 @@ class CallRoutingControllerV2Test {
try {
when(turnCallRouter.getRoutingFor(
eq(AuthHelper.VALID_UUID),
eq(Optional.of(InetAddress.getByName(REMOTE_ADDRESS))),
anyInt())
eq(Optional.of(InetAddress.getByName(REMOTE_ADDRESS))))
).thenReturn(options);
} catch (UnknownHostException ignored) {
}
@@ -136,8 +129,8 @@ class CallRoutingControllerV2Test {
assertThat(relays.getFirst().username()).isNotEmpty();
assertThat(relays.getFirst().password()).isNotEmpty();
assertThat(relays.getFirst().hostname()).isEqualTo(options.hostname());
assertThat(relays.getFirst().urlsWithIps()).isEqualTo(options.urlsWithIps());
assertThat(relays.getFirst().urls()).isEqualTo(options.urlsWithHostname());
assertThat(relays.getFirst().urlsWithIps()).isEqualTo(options.urlsWithIps().get());
assertThat(relays.getFirst().urls()).isEqualTo(options.urlsWithHostname().get());
}
}
@@ -166,8 +159,8 @@ class CallRoutingControllerV2Test {
assertThat(token.username()).isNotEmpty();
assertThat(token.password()).isNotEmpty();
assertThat(token.hostname()).isEqualTo(options.hostname());
assertThat(token.urlsWithIps()).isEqualTo(options.urlsWithIps());
assertThat(token.urls()).isEqualTo(options.urlsWithHostname());
assertThat(token.urlsWithIps()).isEqualTo(options.urlsWithIps().get());
assertThat(token.urls()).isEqualTo(options.urlsWithHostname().get());
}
}
@@ -175,14 +168,13 @@ class CallRoutingControllerV2Test {
void testGetRelaysInvalidIpSuccess() throws UnknownHostException {
TurnServerOptions options = new TurnServerOptions(
"example.domain.org",
List.of(),
List.of("stun:example.domain.org")
Optional.of(List.of()),
Optional.of(List.of("stun:example.domain.org"))
);
when(turnCallRouter.getRoutingFor(
eq(AuthHelper.VALID_UUID),
eq(Optional.of(InetAddress.getByName(REMOTE_ADDRESS))),
anyInt())
eq(Optional.of(InetAddress.getByName(REMOTE_ADDRESS))))
).thenReturn(options);
try (Response rawResponse = resources.getJerseyTest()
.target(GET_CALL_RELAYS_PATH)
@@ -200,8 +192,8 @@ class CallRoutingControllerV2Test {
assertThat(token.username()).isNotEmpty();
assertThat(token.password()).isNotEmpty();
assertThat(token.hostname()).isEqualTo(options.hostname());
assertThat(token.urlsWithIps()).isEqualTo(options.urlsWithIps());
assertThat(token.urls()).isEqualTo(options.urlsWithHostname());
assertThat(token.urlsWithIps()).isEqualTo(options.urlsWithIps().get());
assertThat(token.urls()).isEqualTo(options.urlsWithHostname().get());
}
}
@@ -12,7 +12,6 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyByte;
import static org.mockito.Mockito.anyString;
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;
@@ -43,6 +42,7 @@ import java.util.concurrent.CompletableFuture;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.glassfish.jersey.server.ServerProperties;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.junit.jupiter.api.AfterEach;
@@ -52,6 +52,7 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.NullSource;
import org.junit.jupiter.params.provider.ValueSource;
@@ -90,6 +91,7 @@ import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.DeviceSpec;
import org.whispersystems.textsecuregcm.storage.LinkDeviceTokenAlreadyUsedException;
import org.whispersystems.textsecuregcm.storage.PersistentTimer;
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
@@ -104,6 +106,7 @@ class DeviceControllerTest {
private static final AccountsManager accountsManager = mock(AccountsManager.class);
private static final ClientPublicKeysManager clientPublicKeysManager = mock(ClientPublicKeysManager.class);
private static final PersistentTimer persistentTimer = mock(PersistentTimer.class);
private static final RateLimiters rateLimiters = mock(RateLimiters.class);
private static final RateLimiter rateLimiter = mock(RateLimiter.class);
@SuppressWarnings("unchecked")
@@ -123,6 +126,7 @@ class DeviceControllerTest {
accountsManager,
clientPublicKeysManager,
rateLimiters,
persistentTimer,
deviceConfiguration);
@RegisterExtension
@@ -161,6 +165,9 @@ class DeviceControllerTest {
when(clientPublicKeysManager.setPublicKey(any(), anyByte(), any()))
.thenReturn(CompletableFuture.completedFuture(null));
when(persistentTimer.start(anyString(), anyString()))
.thenReturn(CompletableFuture.completedFuture(mock(PersistentTimer.Sample.class)));
AccountsHelper.setupMockUpdate(accountsManager);
}
@@ -955,6 +962,8 @@ class DeviceControllerTest {
.waitForNewLinkedDevice(eq(AuthHelper.VALID_UUID), eq(AuthHelper.VALID_DEVICE), eq(tokenIdentifier), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.of(deviceInfo)));
when(rateLimiter.validateAsync(AuthHelper.VALID_UUID)).thenReturn(CompletableFuture.completedFuture(null));
try (final Response response = resources.getJerseyTest()
.target("/v1/devices/wait_for_linked_device/" + tokenIdentifier)
.request()
@@ -979,6 +988,8 @@ class DeviceControllerTest {
.waitForNewLinkedDevice(eq(AuthHelper.VALID_UUID), eq(AuthHelper.VALID_DEVICE), eq(tokenIdentifier), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.empty()));
when(rateLimiter.validateAsync(AuthHelper.VALID_UUID)).thenReturn(CompletableFuture.completedFuture(null));
try (final Response response = resources.getJerseyTest()
.target("/v1/devices/wait_for_linked_device/" + tokenIdentifier)
.request()
@@ -997,6 +1008,8 @@ class DeviceControllerTest {
.waitForNewLinkedDevice(eq(AuthHelper.VALID_UUID), eq(AuthHelper.VALID_DEVICE), eq(tokenIdentifier), any()))
.thenReturn(CompletableFuture.failedFuture(new IllegalArgumentException()));
when(rateLimiter.validateAsync(AuthHelper.VALID_UUID)).thenReturn(CompletableFuture.completedFuture(null));
try (final Response response = resources.getJerseyTest()
.target("/v1/devices/wait_for_linked_device/" + tokenIdentifier)
.request()
@@ -1042,10 +1055,11 @@ class DeviceControllerTest {
}
@Test
void waitForLinkedDeviceRateLimited() throws RateLimitExceededException {
void waitForLinkedDeviceRateLimited() {
final String tokenIdentifier = Base64.getUrlEncoder().withoutPadding().encodeToString(new byte[32]);
doThrow(new RateLimitExceededException(null)).when(rateLimiter).validate(AuthHelper.VALID_UUID);
when(rateLimiter.validateAsync(AuthHelper.VALID_UUID))
.thenReturn(CompletableFuture.failedFuture(new RateLimitExceededException(null)));
try (final Response response = resources.getJerseyTest()
.target("/v1/devices/wait_for_linked_device/" + tokenIdentifier)
@@ -1255,7 +1269,7 @@ class DeviceControllerTest {
void recordRestoreAccountRequest() {
final String token = RandomStringUtils.secure().nextAlphanumeric(16);
final RestoreAccountRequest restoreAccountRequest =
new RestoreAccountRequest(RestoreAccountRequest.Method.LOCAL_BACKUP);
new RestoreAccountRequest(RestoreAccountRequest.Method.LOCAL_BACKUP, null);
when(accountsManager.recordRestoreAccountRequest(token, restoreAccountRequest))
.thenReturn(CompletableFuture.completedFuture(null));
@@ -1273,7 +1287,7 @@ class DeviceControllerTest {
void recordRestoreAccountRequestBadToken() {
final String token = RandomStringUtils.secure().nextAlphanumeric(128);
final RestoreAccountRequest restoreAccountRequest =
new RestoreAccountRequest(RestoreAccountRequest.Method.LOCAL_BACKUP);
new RestoreAccountRequest(RestoreAccountRequest.Method.LOCAL_BACKUP, null);
try (final Response response = resources.getJerseyTest()
.target("/v1/devices/restore_account/" + token)
@@ -1287,7 +1301,7 @@ class DeviceControllerTest {
@Test
void recordRestoreAccountRequestInvalidRequest() {
final String token = RandomStringUtils.secure().nextAlphanumeric(16);
final RestoreAccountRequest restoreAccountRequest = new RestoreAccountRequest(null);
final RestoreAccountRequest restoreAccountRequest = new RestoreAccountRequest(null, null);
try (final Response response = resources.getJerseyTest()
.target("/v1/devices/restore_account/" + token)
@@ -1298,11 +1312,34 @@ class DeviceControllerTest {
}
}
@ParameterizedTest
@CsvSource({
"0, true",
"4096, true",
"4097, false"
})
void recordRestoreAccountRequestBootstrapLengthLimit(int bootstrapLength, boolean valid) {
final String token = RandomStringUtils.secure().nextAlphanumeric(16);
final byte[] bootstrap = TestRandomUtil.nextBytes(bootstrapLength);
final RestoreAccountRequest restoreAccountRequest = new RestoreAccountRequest(
RestoreAccountRequest.Method.DEVICE_TRANSFER, bootstrap);
try (final Response response = resources.getJerseyTest()
.target("/v1/devices/restore_account/" + token)
.request()
.put(Entity.json(restoreAccountRequest))) {
assertEquals(valid ? 204 : 422, response.getStatus());
}
}
@Test
void waitForDeviceTransferRequest() {
final String token = RandomStringUtils.secure().nextAlphanumeric(16);
final RestoreAccountRequest restoreAccountRequest =
new RestoreAccountRequest(RestoreAccountRequest.Method.LOCAL_BACKUP);
new RestoreAccountRequest(RestoreAccountRequest.Method.LOCAL_BACKUP, null);
when(accountsManager.waitForRestoreAccountRequest(eq(token), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.of(restoreAccountRequest)));
@@ -305,7 +305,7 @@ public class KeyTransparencyControllerTest {
try (Response response = request.post(Entity.json(
createRequestJson(
new KeyTransparencyMonitorRequest(
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(3L), COMMITMENT_INDEX),
new KeyTransparencyMonitorRequest.AciMonitor(ACI,3, COMMITMENT_INDEX),
Optional.empty(), Optional.empty(), 3L, 4L))))) {
assertEquals(200, response.getStatus());
@@ -327,7 +327,7 @@ public class KeyTransparencyControllerTest {
try (Response response = request.post(
Entity.json(createRequestJson(
new KeyTransparencyMonitorRequest(
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(3L), COMMITMENT_INDEX),
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 3, COMMITMENT_INDEX),
Optional.empty(), Optional.empty(), 3L, 4L))))) {
assertEquals(400, response.getStatus());
verifyNoInteractions(keyTransparencyServiceClient);
@@ -346,7 +346,7 @@ public class KeyTransparencyControllerTest {
try (Response response = request.post(
Entity.json(createRequestJson(
new KeyTransparencyMonitorRequest(
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(3L), COMMITMENT_INDEX),
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 3, COMMITMENT_INDEX),
Optional.empty(), Optional.empty(), 3L, 4L))))) {
assertEquals(httpStatus, response.getStatus());
verify(keyTransparencyServiceClient, times(1)).monitor(any(), any(), any(), anyLong(), anyLong(), any());
@@ -381,115 +381,101 @@ public class KeyTransparencyControllerTest {
new KeyTransparencyMonitorRequest(null, Optional.empty(), Optional.empty(), 3L, 4L))),
// aci monitor fields can't be null
Arguments.of(createRequestJson(
new KeyTransparencyMonitorRequest(new KeyTransparencyMonitorRequest.AciMonitor(null, null, null),
new KeyTransparencyMonitorRequest(new KeyTransparencyMonitorRequest.AciMonitor(null, 4, null),
Optional.empty(), Optional.empty(), 3L, 4L))),
Arguments.of(createRequestJson(
new KeyTransparencyMonitorRequest(
new KeyTransparencyMonitorRequest.AciMonitor(null, List.of(4L), COMMITMENT_INDEX),
new KeyTransparencyMonitorRequest.AciMonitor(null, 4, COMMITMENT_INDEX),
Optional.empty(), Optional.empty(), 3L, 4L))),
Arguments.of(createRequestJson(
new KeyTransparencyMonitorRequest(new KeyTransparencyMonitorRequest.AciMonitor(ACI, null, COMMITMENT_INDEX),
new KeyTransparencyMonitorRequest(new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, null),
Optional.empty(), Optional.empty(), 3L, 4L))),
Arguments.of(createRequestJson(
new KeyTransparencyMonitorRequest(new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), null),
Optional.empty(), Optional.empty(), 3L, 4L))),
// aciPositions list can't be empty
// aciPosition must be positive
Arguments.of(createRequestJson(new KeyTransparencyMonitorRequest(
new KeyTransparencyMonitorRequest.AciMonitor(ACI, Collections.emptyList(), COMMITMENT_INDEX),
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 0, COMMITMENT_INDEX),
Optional.empty(), Optional.empty(), 3L, 4L))),
// aci commitment index must be the correct size
Arguments.of(createRequestJson(new KeyTransparencyMonitorRequest(
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), new byte[0]),
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, new byte[0]),
Optional.empty(), Optional.empty(), 3L, 4L))),
Arguments.of(createRequestJson(new KeyTransparencyMonitorRequest(
new KeyTransparencyMonitorRequest.AciMonitor(ACI, Collections.emptyList(), new byte[33]),
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 0, new byte[33]),
Optional.empty(), Optional.empty(), 3L, 4L))),
// username monitor fields cannot be null
Arguments.of(createRequestJson(
new KeyTransparencyMonitorRequest(
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), COMMITMENT_INDEX), Optional.empty(),
Optional.of(new KeyTransparencyMonitorRequest.UsernameHashMonitor(null, null, null)),
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX), Optional.empty(),
Optional.of(new KeyTransparencyMonitorRequest.UsernameHashMonitor(null, 5, null)),
3L, 4L))),
Arguments.of(createRequestJson(
new KeyTransparencyMonitorRequest(
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), COMMITMENT_INDEX), Optional.empty(),
Optional.of(new KeyTransparencyMonitorRequest.UsernameHashMonitor(null, List.of(5L), COMMITMENT_INDEX)),
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX), Optional.empty(),
Optional.of(new KeyTransparencyMonitorRequest.UsernameHashMonitor(null, 5, COMMITMENT_INDEX)),
3L, 4L))),
Arguments.of(createRequestJson(
new KeyTransparencyMonitorRequest(
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), COMMITMENT_INDEX), Optional.empty(),
Optional.of(
new KeyTransparencyMonitorRequest.UsernameHashMonitor(USERNAME_HASH, null, COMMITMENT_INDEX)),
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX), Optional.empty(),
Optional.of(new KeyTransparencyMonitorRequest.UsernameHashMonitor(USERNAME_HASH, 5, null)),
3L, 4L))),
// usernameHashPosition must be positive
Arguments.of(createRequestJson(
new KeyTransparencyMonitorRequest(
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), COMMITMENT_INDEX), Optional.empty(),
Optional.of(new KeyTransparencyMonitorRequest.UsernameHashMonitor(USERNAME_HASH, List.of(5L), null)),
3L, 4L))),
// usernameHashPositions list cannot be empty
Arguments.of(createRequestJson(
new KeyTransparencyMonitorRequest(
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), COMMITMENT_INDEX),
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX),
Optional.empty(),
Optional.of(new KeyTransparencyMonitorRequest.UsernameHashMonitor(USERNAME_HASH,
Collections.emptyList(), COMMITMENT_INDEX)), 3L, 4L))),
0, COMMITMENT_INDEX)), 3L, 4L))),
// username commitment index must be the correct size
Arguments.of(createRequestJson(
new KeyTransparencyMonitorRequest(
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), new byte[0]),
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, new byte[0]),
Optional.empty(),
Optional.of(new KeyTransparencyMonitorRequest.UsernameHashMonitor(USERNAME_HASH,
List.of(5L), new byte[0])), 3L, 4L))),
5, new byte[0])), 3L, 4L))),
Arguments.of(createRequestJson(
new KeyTransparencyMonitorRequest(new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), null),
new KeyTransparencyMonitorRequest(new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, null),
Optional.empty(),
Optional.of(new KeyTransparencyMonitorRequest.UsernameHashMonitor(USERNAME_HASH,
List.of(5L), new byte[33])), 3L, 4L))),
5, new byte[33])), 3L, 4L))),
// e164 fields cannot be null
Arguments.of(
createRequestJson(new KeyTransparencyMonitorRequest(
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), COMMITMENT_INDEX),
Optional.of(new KeyTransparencyMonitorRequest.E164Monitor(null, null, null)),
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX),
Optional.of(new KeyTransparencyMonitorRequest.E164Monitor(null, 5, null)),
Optional.empty(), 3L, 4L))),
Arguments.of(
createRequestJson(new KeyTransparencyMonitorRequest(
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), COMMITMENT_INDEX),
Optional.of(new KeyTransparencyMonitorRequest.E164Monitor(null, List.of(5L), COMMITMENT_INDEX)),
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX),
Optional.of(new KeyTransparencyMonitorRequest.E164Monitor(null, 5, COMMITMENT_INDEX)),
Optional.empty(), 3L, 4L))),
Arguments.of(
createRequestJson(new KeyTransparencyMonitorRequest(
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), COMMITMENT_INDEX),
Optional.of(new KeyTransparencyMonitorRequest.E164Monitor(NUMBER, null, COMMITMENT_INDEX)),
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX),
Optional.of(new KeyTransparencyMonitorRequest.E164Monitor(NUMBER, 5, null)),
Optional.empty(), 3L, 4L))),
Arguments.of(
createRequestJson(new KeyTransparencyMonitorRequest(
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), COMMITMENT_INDEX),
Optional.of(new KeyTransparencyMonitorRequest.E164Monitor(NUMBER, List.of(5L), null)),
Optional.empty(), 3L, 4L))),
// e164Positions list cannot empty
// e164Position must be positive
Arguments.of(createRequestJson(new KeyTransparencyMonitorRequest(
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), COMMITMENT_INDEX),
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX),
Optional.of(
new KeyTransparencyMonitorRequest.E164Monitor(NUMBER, Collections.emptyList(), COMMITMENT_INDEX)),
new KeyTransparencyMonitorRequest.E164Monitor(NUMBER, 0, COMMITMENT_INDEX)),
Optional.empty(), 3L, 4L))),
// e164 commitment index must be the correct size
Arguments.of(createRequestJson(new KeyTransparencyMonitorRequest(
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), COMMITMENT_INDEX),
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX),
Optional.of(
new KeyTransparencyMonitorRequest.E164Monitor(NUMBER, List.of(5L), new byte[0])),
new KeyTransparencyMonitorRequest.E164Monitor(NUMBER, 5, new byte[0])),
Optional.empty(), 3L, 4L))),
Arguments.of(createRequestJson(new KeyTransparencyMonitorRequest(
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), COMMITMENT_INDEX),
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX),
Optional.of(
new KeyTransparencyMonitorRequest.E164Monitor(NUMBER, List.of(5L), new byte[33])),
new KeyTransparencyMonitorRequest.E164Monitor(NUMBER, 5, new byte[33])),
Optional.empty(), 3L, 4L))),
// lastNonDistinguishedTreeHeadSize must be positive
Arguments.of(createRequestJson(new KeyTransparencyMonitorRequest(
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), COMMITMENT_INDEX), Optional.empty(),
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX), Optional.empty(),
Optional.empty(), 0L, 4L))),
// lastDistinguishedTreeHeadSize must be positive
Arguments.of(createRequestJson(new KeyTransparencyMonitorRequest(
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), COMMITMENT_INDEX), Optional.empty(),
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX), Optional.empty(),
Optional.empty(), 3L, 0L)))
);
}
@@ -503,7 +489,7 @@ public class KeyTransparencyControllerTest {
.request();
try (Response response = request.post(
Entity.json(createRequestJson(
new KeyTransparencyMonitorRequest(new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(3L), null),
new KeyTransparencyMonitorRequest(new KeyTransparencyMonitorRequest.AciMonitor(ACI, 3, null),
Optional.empty(), Optional.empty(),
3L, 4L))))) {
assertEquals(429, response.getStatus());
@@ -84,6 +84,7 @@ import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.TestRemoteAddressFilterProvider;
@ExtendWith(DropwizardExtensionsSupport.class)
class VerificationControllerTest {
@@ -120,6 +121,7 @@ class VerificationControllerTest {
.addProvider(new NonNormalizedPhoneNumberExceptionMapper())
.addProvider(new ObsoletePhoneNumberFormatExceptionMapper())
.addProvider(new RegistrationServiceSenderExceptionMapper())
.addProvider(new TestRemoteAddressFilterProvider("127.0.0.1"))
.setMapper(SystemMapper.jsonMapper())
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
.addResource(
@@ -190,7 +192,7 @@ class VerificationControllerTest {
@Test
void createSessionRateLimited() {
when(registrationServiceClient.createRegistrationSession(any(), anyBoolean(), any()))
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any()))
.thenReturn(CompletableFuture.failedFuture(new RateLimitExceededException(null)));
final Invocation.Builder request = resources.getJerseyTest()
@@ -204,7 +206,7 @@ class VerificationControllerTest {
@Test
void createSessionRegistrationServiceError() {
when(registrationServiceClient.createRegistrationSession(any(), anyBoolean(), any()))
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any()))
.thenReturn(CompletableFuture.failedFuture(new RuntimeException("expected service error")));
final Invocation.Builder request = resources.getJerseyTest()
@@ -219,7 +221,7 @@ class VerificationControllerTest {
@ParameterizedTest
@MethodSource
void createBeninSessionSuccess(final String requestedNumber, final String expectedNumber) {
when(registrationServiceClient.createRegistrationSession(any(), anyBoolean(), any()))
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any()))
.thenReturn(
CompletableFuture.completedFuture(
new RegistrationServiceSession(SESSION_ID, requestedNumber, false, null, null, null,
@@ -236,7 +238,7 @@ class VerificationControllerTest {
final ArgumentCaptor<Phonenumber.PhoneNumber> phoneNumberArgumentCaptor = ArgumentCaptor.forClass(
Phonenumber.PhoneNumber.class);
verify(registrationServiceClient).createRegistrationSession(phoneNumberArgumentCaptor.capture(), anyBoolean(), any());
verify(registrationServiceClient).createRegistrationSession(phoneNumberArgumentCaptor.capture(), anyString(), anyBoolean(), any());
final Phonenumber.PhoneNumber phoneNumber = phoneNumberArgumentCaptor.getValue();
assertEquals(expectedNumber, PhoneNumberUtil.getInstance().format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164));
@@ -260,7 +262,7 @@ class VerificationControllerTest {
.format(PhoneNumberUtil.getInstance().getExampleNumber("BJ"), PhoneNumberUtil.PhoneNumberFormat.E164);
final String oldFormatBeninE164 = newFormatBeninE164.replaceFirst("01", "");
when(registrationServiceClient.createRegistrationSession(any(), anyBoolean(), any()))
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any()))
.thenReturn(
CompletableFuture.completedFuture(
new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null,
@@ -281,7 +283,7 @@ class VerificationControllerTest {
@MethodSource
void createSessionSuccess(final String pushToken, final String pushTokenType,
final List<VerificationSession.Information> expectedRequestedInformation) {
when(registrationServiceClient.createRegistrationSession(any(), anyBoolean(), any()))
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any()))
.thenReturn(
CompletableFuture.completedFuture(
new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null,
@@ -315,7 +317,7 @@ class VerificationControllerTest {
@ParameterizedTest
@ValueSource(booleans = {true, false})
void createSessionReregistration(final boolean isReregistration) throws NumberParseException {
when(registrationServiceClient.createRegistrationSession(any(), anyBoolean(), any()))
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any()))
.thenReturn(
CompletableFuture.completedFuture(
new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null,
@@ -337,6 +339,7 @@ class VerificationControllerTest {
verify(registrationServiceClient).createRegistrationSession(
eq(PhoneNumberUtil.getInstance().parse(NUMBER, null)),
anyString(),
eq(isReregistration),
any()
);
@@ -0,0 +1,40 @@
package org.whispersystems.textsecuregcm.currency;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Map;
import org.junit.jupiter.api.Test;
class CoinGeckoClientTest {
private static final String RESPONSE_JSON = """
{
"mobilecoin": {
"usd": 0.226212
}
}
""";
@Test
void parseResponse() throws JsonProcessingException {
final Map<String, Map<String, BigDecimal>> parsedResponse = CoinGeckoClient.parseResponse(RESPONSE_JSON);
assertTrue(parsedResponse.containsKey("mobilecoin"));
assertEquals(1, parsedResponse.get("mobilecoin").size());
assertEquals(new BigDecimal("0.226212"), parsedResponse.get("mobilecoin").get("usd"));
}
@Test
void extractConversionRate() throws IOException {
final Map<String, Map<String, BigDecimal>> parsedResponse = CoinGeckoClient.parseResponse(RESPONSE_JSON);
assertEquals(new BigDecimal("0.226212"), CoinGeckoClient.extractConversionRate(parsedResponse.get("mobilecoin"), "usd"));
assertThrows(IOException.class, () -> CoinGeckoClient.extractConversionRate(parsedResponse.get("mobilecoin"), "CAD"));
}
}
@@ -1,61 +0,0 @@
package org.whispersystems.textsecuregcm.currency;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Map;
import org.junit.jupiter.api.Test;
class CoinMarketCapClientTest {
private static final String RESPONSE_JSON = """
{
"status": {
"timestamp": "2022-11-09T17:15:06.356Z",
"error_code": 0,
"error_message": null,
"elapsed": 41,
"credit_count": 1,
"notice": null
},
"data": {
"id": 7878,
"symbol": "MOB",
"name": "MobileCoin",
"amount": 1,
"last_updated": "2022-11-09T17:14:00.000Z",
"quote": {
"USD": {
"price": 0.6625319895827952,
"last_updated": "2022-11-09T17:14:00.000Z"
}
}
}
}
""";
@Test
void parseResponse() throws JsonProcessingException {
final CoinMarketCapClient.CoinMarketCapResponse parsedResponse = CoinMarketCapClient.parseResponse(RESPONSE_JSON);
assertEquals(7878, parsedResponse.priceConversionResponse().id());
assertEquals("MOB", parsedResponse.priceConversionResponse().symbol());
final Map<String, CoinMarketCapClient.PriceConversionQuote> quote =
parsedResponse.priceConversionResponse().quote();
assertEquals(1, quote.size());
assertEquals(new BigDecimal("0.6625319895827952"), quote.get("USD").price());
}
@Test
void extractConversionRate() throws IOException {
final CoinMarketCapClient.CoinMarketCapResponse parsedResponse = CoinMarketCapClient.parseResponse(RESPONSE_JSON);
assertEquals(new BigDecimal("0.6625319895827952"), CoinMarketCapClient.extractConversionRate(parsedResponse, "USD"));
assertThrows(IOException.class, () -> CoinMarketCapClient.extractConversionRate(parsedResponse, "CAD"));
}
}
@@ -38,16 +38,16 @@ class CurrencyConversionManagerTest {
@Test
void testCurrencyCalculations() throws IOException {
FixerClient fixerClient = mock(FixerClient.class);
CoinMarketCapClient coinMarketCapClient = mock(CoinMarketCapClient.class);
CoinGeckoClient coinGeckoClient = mock(CoinGeckoClient.class);
when(coinMarketCapClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("2.35"));
when(coinGeckoClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("2.35"));
when(fixerClient.getConversionsForBase(eq("USD"))).thenReturn(Map.of(
"EUR", new BigDecimal("0.822876"),
"FJD", new BigDecimal("2.0577"),
"FKP", new BigDecimal("0.743446")
));
CurrencyConversionManager manager = new CurrencyConversionManager(fixerClient, coinMarketCapClient, REDIS_CLUSTER_EXTENSION.getRedisCluster(),
CurrencyConversionManager manager = new CurrencyConversionManager(fixerClient, coinGeckoClient, REDIS_CLUSTER_EXTENSION.getRedisCluster(),
List.of("FOO"), EXECUTOR, Clock.systemUTC());
manager.updateCacheIfNecessary();
@@ -66,9 +66,9 @@ class CurrencyConversionManagerTest {
@Test
void testCurrencyCalculations_noTrailingZeros() throws IOException {
FixerClient fixerClient = mock(FixerClient.class);
CoinMarketCapClient coinMarketCapClient = mock(CoinMarketCapClient.class);
CoinGeckoClient CoinGeckoClient = mock(CoinGeckoClient.class);
when(coinMarketCapClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("1.00000"));
when(CoinGeckoClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("1.00000"));
when(fixerClient.getConversionsForBase(eq("USD"))).thenReturn(Map.of(
"EUR", new BigDecimal("0.200000"),
"FJD", new BigDecimal("3.00000"),
@@ -76,7 +76,7 @@ class CurrencyConversionManagerTest {
"CAD", new BigDecimal("700.000")
));
CurrencyConversionManager manager = new CurrencyConversionManager(fixerClient, coinMarketCapClient, REDIS_CLUSTER_EXTENSION.getRedisCluster(),
CurrencyConversionManager manager = new CurrencyConversionManager(fixerClient, CoinGeckoClient, REDIS_CLUSTER_EXTENSION.getRedisCluster(),
List.of("FOO"), EXECUTOR, Clock.systemUTC());
manager.updateCacheIfNecessary();
@@ -96,16 +96,16 @@ class CurrencyConversionManagerTest {
@Test
void testCurrencyCalculations_accuracy() throws IOException {
FixerClient fixerClient = mock(FixerClient.class);
CoinMarketCapClient coinMarketCapClient = mock(CoinMarketCapClient.class);
CoinGeckoClient CoinGeckoClient = mock(CoinGeckoClient.class);
when(coinMarketCapClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("0.999999"));
when(CoinGeckoClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("0.999999"));
when(fixerClient.getConversionsForBase(eq("USD"))).thenReturn(Map.of(
"EUR", new BigDecimal("1.000001"),
"FJD", new BigDecimal("0.000001"),
"FKP", new BigDecimal("1")
));
CurrencyConversionManager manager = new CurrencyConversionManager(fixerClient, coinMarketCapClient, REDIS_CLUSTER_EXTENSION.getRedisCluster(),
CurrencyConversionManager manager = new CurrencyConversionManager(fixerClient, CoinGeckoClient, REDIS_CLUSTER_EXTENSION.getRedisCluster(),
List.of("FOO"), EXECUTOR, Clock.systemUTC());
manager.updateCacheIfNecessary();
@@ -125,21 +125,21 @@ class CurrencyConversionManagerTest {
@Test
void testCurrencyCalculationsTimeoutNoRun() throws IOException {
FixerClient fixerClient = mock(FixerClient.class);
CoinMarketCapClient coinMarketCapClient = mock(CoinMarketCapClient.class);
CoinGeckoClient CoinGeckoClient = mock(CoinGeckoClient.class);
when(coinMarketCapClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("2.35"));
when(CoinGeckoClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("2.35"));
when(fixerClient.getConversionsForBase(eq("USD"))).thenReturn(Map.of(
"EUR", new BigDecimal("0.822876"),
"FJD", new BigDecimal("2.0577"),
"FKP", new BigDecimal("0.743446")
));
CurrencyConversionManager manager = new CurrencyConversionManager(fixerClient, coinMarketCapClient, REDIS_CLUSTER_EXTENSION.getRedisCluster(),
CurrencyConversionManager manager = new CurrencyConversionManager(fixerClient, CoinGeckoClient, REDIS_CLUSTER_EXTENSION.getRedisCluster(),
List.of("FOO"), EXECUTOR, Clock.systemUTC());
manager.updateCacheIfNecessary();
when(coinMarketCapClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("3.50"));
when(CoinGeckoClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("3.50"));
manager.updateCacheIfNecessary();
@@ -155,26 +155,26 @@ class CurrencyConversionManagerTest {
}
@Test
void testCurrencyCalculationsCoinMarketCapTimeoutWithRun() throws IOException {
void testCurrencyCalculationsCoinGeckoTimeoutWithRun() throws IOException {
FixerClient fixerClient = mock(FixerClient.class);
CoinMarketCapClient coinMarketCapClient = mock(CoinMarketCapClient.class);
CoinGeckoClient CoinGeckoClient = mock(CoinGeckoClient.class);
when(coinMarketCapClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("2.35"));
when(CoinGeckoClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("2.35"));
when(fixerClient.getConversionsForBase(eq("USD"))).thenReturn(Map.of(
"EUR", new BigDecimal("0.822876"),
"FJD", new BigDecimal("2.0577"),
"FKP", new BigDecimal("0.743446")
));
CurrencyConversionManager manager = new CurrencyConversionManager(fixerClient, coinMarketCapClient, REDIS_CLUSTER_EXTENSION.getRedisCluster(),
CurrencyConversionManager manager = new CurrencyConversionManager(fixerClient, CoinGeckoClient, REDIS_CLUSTER_EXTENSION.getRedisCluster(),
List.of("FOO"), EXECUTOR, Clock.systemUTC());
manager.updateCacheIfNecessary();
REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(connection ->
connection.sync().del(CurrencyConversionManager.COIN_MARKET_CAP_SHARED_CACHE_CURRENT_KEY));
connection.sync().del(CurrencyConversionManager.COIN_GECKO_CAP_SHARED_CACHE_CURRENT_KEY));
when(coinMarketCapClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("3.50"));
when(CoinGeckoClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("3.50"));
manager.updateCacheIfNecessary();
CurrencyConversionEntityList conversions = manager.getCurrencyConversions().orElseThrow();
@@ -192,9 +192,9 @@ class CurrencyConversionManagerTest {
@Test
void testCurrencyCalculationsFixerTimeoutWithRun() throws IOException {
FixerClient fixerClient = mock(FixerClient.class);
CoinMarketCapClient coinMarketCapClient = mock(CoinMarketCapClient.class);
CoinGeckoClient CoinGeckoClient = mock(CoinGeckoClient.class);
when(coinMarketCapClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("2.35"));
when(CoinGeckoClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("2.35"));
when(fixerClient.getConversionsForBase(eq("USD"))).thenReturn(Map.of(
"EUR", new BigDecimal("0.822876"),
"FJD", new BigDecimal("2.0577"),
@@ -207,12 +207,12 @@ class CurrencyConversionManagerTest {
when(clock.instant()).thenReturn(currentTime);
when(clock.millis()).thenReturn(currentTime.toEpochMilli());
CurrencyConversionManager manager = new CurrencyConversionManager(fixerClient, coinMarketCapClient, REDIS_CLUSTER_EXTENSION.getRedisCluster(),
CurrencyConversionManager manager = new CurrencyConversionManager(fixerClient, CoinGeckoClient, REDIS_CLUSTER_EXTENSION.getRedisCluster(),
List.of("FOO"), EXECUTOR, clock);
manager.updateCacheIfNecessary();
when(coinMarketCapClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("3.50"));
when(CoinGeckoClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("3.50"));
when(fixerClient.getConversionsForBase(eq("USD"))).thenReturn(Map.of(
"EUR", new BigDecimal("0.922876"),
"FJD", new BigDecimal("2.0577"),
@@ -239,7 +239,7 @@ class CurrencyConversionManagerTest {
@Test
void convertToUsd() {
final CurrencyConversionManager currencyConversionManager = new CurrencyConversionManager(mock(FixerClient.class),
mock(CoinMarketCapClient.class),
mock(CoinGeckoClient.class),
mock(FaultTolerantRedisClusterClient.class),
Collections.emptyList(),
EXECUTOR,
@@ -64,8 +64,6 @@ class OutgoingMessageEntityTest {
@Test
void entityPreservesEnvelope() {
final Random random = new Random();
final byte[] reportSpamToken = TestRandomUtil.nextBytes(8);
final Account account = new Account();
@@ -79,11 +77,14 @@ class OutgoingMessageEntityTest {
(byte) 123,
System.currentTimeMillis(),
false,
false,
true,
reportSpamToken);
MessageProtos.Envelope envelope = baseEnvelope.toBuilder().setServerGuid(UUID.randomUUID().toString()).build();
assertEquals(envelope, OutgoingMessageEntity.fromEnvelope(envelope).toEnvelope());
// Note that outgoing message entities don't have an "ephemeral"/"online" flag
assertEquals(envelope.toBuilder().clearEphemeral().build(),
OutgoingMessageEntity.fromEnvelope(envelope).toEnvelope());
}
}
@@ -0,0 +1,111 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.filters;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.common.net.HttpHeaders;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.SecurityContext;
import java.net.URI;
import java.util.UUID;
import org.glassfish.jersey.server.ContainerRequest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.tests.util.FakeDynamicConfigurationManager;
import org.whispersystems.textsecuregcm.util.SystemMapper;
class RestDeprecationFilterTest {
@Test
void testNoConfig() throws Exception {
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
new FakeDynamicConfigurationManager<>(new DynamicConfiguration());
final ExperimentEnrollmentManager experimentEnrollmentManager = new ExperimentEnrollmentManager(dynamicConfigurationManager);
final RestDeprecationFilter filter = new RestDeprecationFilter(dynamicConfigurationManager, experimentEnrollmentManager);
final Account account = new Account();
account.setUuid(UUID.randomUUID());
final SecurityContext securityContext = mock(SecurityContext.class);
when(securityContext.getUserPrincipal()).thenReturn(new AuthenticatedDevice(account, new Device()));
final ContainerRequest req = new ContainerRequest(null, new URI("/some/uri"), "GET", securityContext, null, null);
req.getHeaders().add(HttpHeaders.USER_AGENT, "Signal-Android/100.0.0");
filter.filter(req);
}
@Test
void testOldClient() throws Exception {
final DynamicConfiguration config = SystemMapper.yamlMapper().readValue(
"""
minimumRestFreeVersion:
ANDROID: 200.0.0
experiments:
restDeprecation:
uuidEnrollmentPercentage: 100
""",
DynamicConfiguration.class);
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = new FakeDynamicConfigurationManager<>(config);
final ExperimentEnrollmentManager experimentEnrollmentManager = new ExperimentEnrollmentManager(dynamicConfigurationManager);
final RestDeprecationFilter filter = new RestDeprecationFilter(dynamicConfigurationManager, experimentEnrollmentManager);
final Account account = new Account();
account.setUuid(UUID.randomUUID());
final SecurityContext securityContext = mock(SecurityContext.class);
when(securityContext.getUserPrincipal()).thenReturn(new AuthenticatedDevice(account, new Device()));
final ContainerRequest req = new ContainerRequest(null, new URI("/some/uri"), "GET", securityContext, null, null);
req.getHeaders().add(HttpHeaders.USER_AGENT, "Signal-Android/100.0.0");
filter.filter(req);
}
@Test
void testBlocking() throws Exception {
final DynamicConfiguration config = SystemMapper.yamlMapper().readValue(
"""
minimumRestFreeVersion:
ANDROID: 10.10.10
experiments:
restDeprecation:
enrollmentPercentage: 100
""",
DynamicConfiguration.class);
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = new FakeDynamicConfigurationManager<>(config);
final ExperimentEnrollmentManager experimentEnrollmentManager = new ExperimentEnrollmentManager(dynamicConfigurationManager);
final RestDeprecationFilter filter = new RestDeprecationFilter(dynamicConfigurationManager, experimentEnrollmentManager);
final Account account = new Account();
account.setUuid(UUID.randomUUID());
final SecurityContext securityContext = mock(SecurityContext.class);
when(securityContext.getUserPrincipal()).thenReturn(new AuthenticatedDevice(account, new Device()));
final ContainerRequest req = new ContainerRequest(null, new URI("/some/path"), "GET", securityContext, null, null);
req.getHeaders().putSingle(HttpHeaders.USER_AGENT, "Signal-Android/10.9.15");
filter.filter(req);
req.getHeaders().putSingle(HttpHeaders.USER_AGENT, "Signal-Android/10.10.9");
filter.filter(req);
req.getHeaders().putSingle(HttpHeaders.USER_AGENT, "Signal-Android/10.10.10");
assertThrows(WebApplicationException.class, () -> filter.filter(req));
req.getHeaders().putSingle(HttpHeaders.USER_AGENT, "Signal-Android/100.0.0");
assertThrows(WebApplicationException.class, () -> filter.filter(req));
}
}
@@ -1,75 +0,0 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.whispersystems.textsecuregcm.grpc.GrpcTestUtils.assertRateLimitExceeded;
import java.time.Duration;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.signal.chat.calling.CallingGrpc;
import org.signal.chat.calling.GetTurnCredentialsRequest;
import org.signal.chat.calling.GetTurnCredentialsResponse;
import org.whispersystems.textsecuregcm.auth.TurnToken;
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.util.MockUtils;
class CallingGrpcServiceTest extends SimpleBaseGrpcTest<CallingGrpcService, CallingGrpc.CallingBlockingStub> {
@Mock
private TurnTokenGenerator turnTokenGenerator;
@Mock
private RateLimiter turnCredentialRateLimiter;
@Override
protected CallingGrpcService createServiceBeforeEachTest() {
final RateLimiters rateLimiters = mock(RateLimiters.class);
when(rateLimiters.getTurnLimiter()).thenReturn(turnCredentialRateLimiter);
return new CallingGrpcService(turnTokenGenerator, rateLimiters);
}
@Test
void getTurnCredentials() {
final String username = "test-username";
final String password = "test-password";
final List<String> urls = List.of("first", "second");
final String hostname = "hostname";
MockUtils.updateRateLimiterResponseToAllow(turnCredentialRateLimiter, AUTHENTICATED_ACI);
when(turnTokenGenerator.generate(any())).thenReturn(new TurnToken(username, password, urls, null, hostname));
final GetTurnCredentialsResponse response = authenticatedServiceStub().getTurnCredentials(GetTurnCredentialsRequest.newBuilder().build());
final GetTurnCredentialsResponse expectedResponse = GetTurnCredentialsResponse.newBuilder()
.setUsername(username)
.setPassword(password)
.addAllUrls(urls)
.build();
assertEquals(expectedResponse, response);
}
@Test
void getTurnCredentialsRateLimited() {
final Duration retryAfter = MockUtils.updateRateLimiterResponseToFail(
turnCredentialRateLimiter, AUTHENTICATED_ACI, Duration.ofMinutes(19));
assertRateLimitExceeded(retryAfter, () -> authenticatedServiceStub().getTurnCredentials(GetTurnCredentialsRequest.newBuilder().build()));
verify(turnTokenGenerator, never()).generate(any());
verifyNoInteractions(turnTokenGenerator);
}
}
@@ -11,14 +11,14 @@ import org.whispersystems.textsecuregcm.storage.Device;
class MessageDeliveryLoopMonitorTest {
private MessageDeliveryLoopMonitor messageDeliveryLoopMonitor;
private RedisMessageDeliveryLoopMonitor messageDeliveryLoopMonitor;
@RegisterExtension
static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
@BeforeEach
void setUp() {
messageDeliveryLoopMonitor = new MessageDeliveryLoopMonitor(REDIS_CLUSTER_EXTENSION.getRedisCluster());
messageDeliveryLoopMonitor = new RedisMessageDeliveryLoopMonitor(REDIS_CLUSTER_EXTENSION.getRedisCluster());
}
@Test
@@ -90,7 +90,7 @@ class MetricsRequestEventListenerTest {
final ContainerRequest request = mock(ContainerRequest.class);
when(request.getMethod()).thenReturn(method);
when(request.getRequestHeader(HttpHeaders.USER_AGENT)).thenReturn(
Collections.singletonList("Signal-Android/4.53.7 (Android 8.1)"));
Collections.singletonList("Signal-Android/7.6.2 Android/34 libsignal/0.46.0"));
final ContainerResponse response = mock(ContainerResponse.class);
when(response.getStatus()).thenReturn(statusCode);
@@ -116,12 +116,13 @@ class MetricsRequestEventListenerTest {
tags.add(tag);
}
assertEquals(5, tags.size());
assertEquals(6, tags.size());
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.PATH_TAG, path)));
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.METHOD_TAG, method)));
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.STATUS_CODE_TAG, String.valueOf(statusCode))));
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.TRAFFIC_SOURCE_TAG, TRAFFIC_SOURCE.name().toLowerCase())));
assertTrue(tags.contains(Tag.of(UserAgentTagUtil.PLATFORM_TAG, "android")));
assertTrue(tags.contains(Tag.of(UserAgentTagUtil.LIBSIGNAL_TAG, "true")));
}
@Test
@@ -178,12 +179,13 @@ class MetricsRequestEventListenerTest {
tags.add(tag);
}
assertEquals(5, tags.size());
assertEquals(6, tags.size());
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.PATH_TAG, "/v1/test/hello")));
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.METHOD_TAG, "GET")));
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.STATUS_CODE_TAG, String.valueOf(200))));
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.TRAFFIC_SOURCE_TAG, TRAFFIC_SOURCE.name().toLowerCase())));
assertTrue(tags.contains(Tag.of(UserAgentTagUtil.PLATFORM_TAG, "android")));
assertTrue(tags.contains(Tag.of(UserAgentTagUtil.LIBSIGNAL_TAG, "false")));
}
@Test
@@ -238,12 +240,13 @@ class MetricsRequestEventListenerTest {
tags.add(tag);
}
assertEquals(5, tags.size());
assertEquals(6, tags.size());
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.PATH_TAG, "/v1/test/hello")));
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.METHOD_TAG, "GET")));
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.STATUS_CODE_TAG, String.valueOf(200))));
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.TRAFFIC_SOURCE_TAG, TRAFFIC_SOURCE.name().toLowerCase())));
assertTrue(tags.contains(Tag.of(UserAgentTagUtil.PLATFORM_TAG, "unrecognized")));
assertTrue(tags.contains(Tag.of(UserAgentTagUtil.LIBSIGNAL_TAG, "false")));
}
private static SubProtocol.WebSocketResponseMessage getResponse(ArgumentCaptor<ByteBuffer> responseCaptor)
@@ -10,23 +10,25 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyByte;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import com.google.protobuf.ByteString;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.commons.lang3.RandomStringUtils;
import java.util.concurrent.CompletableFuture;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junitpioneer.jupiter.cartesian.CartesianTest;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
@@ -49,17 +51,21 @@ class MessageSenderTest {
@CartesianTest
void sendMessage(@CartesianTest.Values(booleans = {true, false}) final boolean clientPresent,
@CartesianTest.Values(booleans = {true, false}) final boolean onlineMessage,
@CartesianTest.Values(booleans = {true, false}) final boolean ephemeral,
@CartesianTest.Values(booleans = {true, false}) final boolean urgent,
@CartesianTest.Values(booleans = {true, false}) final boolean hasPushToken) throws NotPushRegisteredException {
final boolean expectPushNotificationAttempt = !clientPresent && !onlineMessage;
final boolean expectPushNotificationAttempt = !clientPresent && !ephemeral;
final UUID accountIdentifier = UUID.randomUUID();
final byte deviceId = Device.PRIMARY_ID;
final Account account = mock(Account.class);
final Device device = mock(Device.class);
final MessageProtos.Envelope message = generateRandomMessage();
final MessageProtos.Envelope message = MessageProtos.Envelope.newBuilder()
.setEphemeral(ephemeral)
.setUrgent(urgent)
.build();
when(account.getUuid()).thenReturn(accountIdentifier);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
@@ -72,18 +78,61 @@ class MessageSenderTest {
.when(pushNotificationManager).sendNewMessageNotification(any(), anyByte(), anyBoolean());
}
when(messagesManager.insert(eq(accountIdentifier), eq(deviceId), any())).thenReturn(clientPresent);
when(messagesManager.insert(any(), any())).thenReturn(Map.of(deviceId, clientPresent));
assertDoesNotThrow(() -> messageSender.sendMessage(account, device, message, onlineMessage));
assertDoesNotThrow(() -> messageSender.sendMessages(account, Map.of(device.getId(), message)));
final MessageProtos.Envelope expectedMessage = onlineMessage
final MessageProtos.Envelope expectedMessage = ephemeral
? message.toBuilder().setEphemeral(true).build()
: message.toBuilder().build();
verify(messagesManager).insert(accountIdentifier, deviceId, expectedMessage);
verify(messagesManager).insert(accountIdentifier, Map.of(deviceId, expectedMessage));
if (expectPushNotificationAttempt) {
verify(pushNotificationManager).sendNewMessageNotification(account, deviceId, expectedMessage.getUrgent());
verify(pushNotificationManager).sendNewMessageNotification(account, deviceId, urgent);
} else {
verifyNoInteractions(pushNotificationManager);
}
}
@CartesianTest
void sendMultiRecipientMessage(@CartesianTest.Values(booleans = {true, false}) final boolean clientPresent,
@CartesianTest.Values(booleans = {true, false}) final boolean ephemeral,
@CartesianTest.Values(booleans = {true, false}) final boolean urgent,
@CartesianTest.Values(booleans = {true, false}) final boolean hasPushToken) throws NotPushRegisteredException {
final boolean expectPushNotificationAttempt = !clientPresent && !ephemeral;
final UUID accountIdentifier = UUID.randomUUID();
final byte deviceId = Device.PRIMARY_ID;
final Account account = mock(Account.class);
final Device device = mock(Device.class);
when(account.getUuid()).thenReturn(accountIdentifier);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
when(device.getId()).thenReturn(deviceId);
if (hasPushToken) {
when(device.getApnId()).thenReturn("apns-token");
} else {
doThrow(NotPushRegisteredException.class)
.when(pushNotificationManager).sendNewMessageNotification(any(), anyByte(), anyBoolean());
}
when(messagesManager.insertMultiRecipientMessage(any(), any(), anyLong(), anyBoolean(), anyBoolean(), anyBoolean()))
.thenReturn(CompletableFuture.completedFuture(Map.of(account, Map.of(deviceId, clientPresent))));
assertDoesNotThrow(() -> messageSender.sendMultiRecipientMessage(mock(SealedSenderMultiRecipientMessage.class),
Collections.emptyMap(),
System.currentTimeMillis(),
false,
ephemeral,
urgent)
.join());
if (expectPushNotificationAttempt) {
verify(pushNotificationManager).sendNewMessageNotification(account, deviceId, urgent);
} else {
verifyNoInteractions(pushNotificationManager);
}
@@ -123,14 +172,4 @@ class MessageSenderTest {
return arguments;
}
private MessageProtos.Envelope generateRandomMessage() {
return MessageProtos.Envelope.newBuilder()
.setClientTimestamp(System.currentTimeMillis())
.setServerTimestamp(System.currentTimeMillis())
.setContent(ByteString.copyFromUtf8(RandomStringUtils.secure().nextAlphanumeric(256)))
.setType(MessageProtos.Envelope.Type.CIPHERTEXT)
.setServerGuid(UUID.randomUUID().toString())
.build();
}
}
@@ -21,6 +21,7 @@ import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.redis.RedisServerExtension;
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
@@ -33,7 +34,9 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -178,8 +181,9 @@ public class AccountsManagerDeviceTransferIntegrationTest {
@Test
void waitForRestoreAccountRequest() {
final String token = RandomStringUtils.secure().nextAlphanumeric(16);
final byte[] deviceTransferBootstrap = TestRandomUtil.nextBytes(100);
final RestoreAccountRequest restoreAccountRequest =
new RestoreAccountRequest(RestoreAccountRequest.Method.DEVICE_TRANSFER);
new RestoreAccountRequest(RestoreAccountRequest.Method.DEVICE_TRANSFER, deviceTransferBootstrap);
final CompletableFuture<Optional<RestoreAccountRequest>> displacedFuture =
accountsManager.waitForRestoreAccountRequest(token, Duration.ofSeconds(5));
@@ -191,14 +195,17 @@ public class AccountsManagerDeviceTransferIntegrationTest {
accountsManager.recordRestoreAccountRequest(token, restoreAccountRequest).join();
assertEquals(Optional.of(restoreAccountRequest), activeFuture.join());
final Optional<RestoreAccountRequest> result = activeFuture.join();
assertTrue(result.isPresent());
assertEquals(restoreAccountRequest.method(), result.get().method());
assertArrayEquals(restoreAccountRequest.deviceTransferBootstrap(), result.get().deviceTransferBootstrap());
}
@Test
void waitForRestoreAccountRequestAlreadyRequested() {
final String token = RandomStringUtils.secure().nextAlphanumeric(16);
final RestoreAccountRequest restoreAccountRequest =
new RestoreAccountRequest(RestoreAccountRequest.Method.DEVICE_TRANSFER);
new RestoreAccountRequest(RestoreAccountRequest.Method.DEVICE_TRANSFER, null);
accountsManager.recordRestoreAccountRequest(token, restoreAccountRequest).join();
@@ -22,6 +22,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -104,7 +105,7 @@ public class ChangeNumberManagerTest {
changeNumberManager.changeNumber(account, "+18025551234", null, null, null, null, null);
verify(accountsManager).changeNumber(account, "+18025551234", null, null, null, null);
verify(accountsManager, never()).updateDevice(any(), anyByte(), any());
verify(messageSender, never()).sendMessage(eq(account), any(), any(), eq(false));
verify(messageSender, never()).sendMessages(eq(account), any());
}
@Test
@@ -118,7 +119,7 @@ public class ChangeNumberManagerTest {
changeNumberManager.changeNumber(account, "+18025551234", pniIdentityKey, prekeys, null, Collections.emptyList(), Collections.emptyMap());
verify(accountsManager).changeNumber(account, "+18025551234", pniIdentityKey, prekeys, null, Collections.emptyMap());
verify(messageSender, never()).sendMessage(eq(account), any(), any(), eq(false));
verify(messageSender, never()).sendMessages(eq(account), any());
}
@Test
@@ -155,10 +156,15 @@ public class ChangeNumberManagerTest {
verify(accountsManager).changeNumber(account, changedE164, pniIdentityKey, prekeys, null, registrationIds);
final ArgumentCaptor<MessageProtos.Envelope> envelopeCaptor = ArgumentCaptor.forClass(MessageProtos.Envelope.class);
verify(messageSender).sendMessage(any(), eq(d2), envelopeCaptor.capture(), eq(false));
@SuppressWarnings("unchecked") final ArgumentCaptor<Map<Byte, MessageProtos.Envelope>> envelopeCaptor =
ArgumentCaptor.forClass(Map.class);
final MessageProtos.Envelope envelope = envelopeCaptor.getValue();
verify(messageSender).sendMessages(any(), envelopeCaptor.capture());
assertEquals(1, envelopeCaptor.getValue().size());
assertEquals(Set.of(deviceId2), envelopeCaptor.getValue().keySet());
final MessageProtos.Envelope envelope = envelopeCaptor.getValue().get(deviceId2);
assertEquals(aci, UUID.fromString(envelope.getDestinationServiceId()));
assertEquals(aci, UUID.fromString(envelope.getSourceServiceId()));
@@ -203,10 +209,15 @@ public class ChangeNumberManagerTest {
verify(accountsManager).changeNumber(account, changedE164, pniIdentityKey, prekeys, pqPrekeys, registrationIds);
final ArgumentCaptor<MessageProtos.Envelope> envelopeCaptor = ArgumentCaptor.forClass(MessageProtos.Envelope.class);
verify(messageSender).sendMessage(any(), eq(d2), envelopeCaptor.capture(), eq(false));
@SuppressWarnings("unchecked") final ArgumentCaptor<Map<Byte, MessageProtos.Envelope>> envelopeCaptor =
ArgumentCaptor.forClass(Map.class);
final MessageProtos.Envelope envelope = envelopeCaptor.getValue();
verify(messageSender).sendMessages(any(), envelopeCaptor.capture());
assertEquals(1, envelopeCaptor.getValue().size());
assertEquals(Set.of(deviceId2), envelopeCaptor.getValue().keySet());
final MessageProtos.Envelope envelope = envelopeCaptor.getValue().get(deviceId2);
assertEquals(aci, UUID.fromString(envelope.getDestinationServiceId()));
assertEquals(aci, UUID.fromString(envelope.getSourceServiceId()));
@@ -249,10 +260,15 @@ public class ChangeNumberManagerTest {
verify(accountsManager).updatePniKeys(account, pniIdentityKey, prekeys, pqPrekeys, registrationIds);
final ArgumentCaptor<MessageProtos.Envelope> envelopeCaptor = ArgumentCaptor.forClass(MessageProtos.Envelope.class);
verify(messageSender).sendMessage(any(), eq(d2), envelopeCaptor.capture(), eq(false));
@SuppressWarnings("unchecked") final ArgumentCaptor<Map<Byte, MessageProtos.Envelope>> envelopeCaptor =
ArgumentCaptor.forClass(Map.class);
final MessageProtos.Envelope envelope = envelopeCaptor.getValue();
verify(messageSender).sendMessages(any(), envelopeCaptor.capture());
assertEquals(1, envelopeCaptor.getValue().size());
assertEquals(Set.of(deviceId2), envelopeCaptor.getValue().keySet());
final MessageProtos.Envelope envelope = envelopeCaptor.getValue().get(deviceId2);
assertEquals(aci, UUID.fromString(envelope.getDestinationServiceId()));
assertEquals(aci, UUID.fromString(envelope.getSourceServiceId()));
@@ -291,10 +307,15 @@ public class ChangeNumberManagerTest {
verify(accountsManager).updatePniKeys(account, pniIdentityKey, prekeys, null, registrationIds);
final ArgumentCaptor<MessageProtos.Envelope> envelopeCaptor = ArgumentCaptor.forClass(MessageProtos.Envelope.class);
verify(messageSender).sendMessage(any(), eq(d2), envelopeCaptor.capture(), eq(false));
@SuppressWarnings("unchecked") final ArgumentCaptor<Map<Byte, MessageProtos.Envelope>> envelopeCaptor =
ArgumentCaptor.forClass(Map.class);
final MessageProtos.Envelope envelope = envelopeCaptor.getValue();
verify(messageSender).sendMessages(any(), envelopeCaptor.capture());
assertEquals(1, envelopeCaptor.getValue().size());
assertEquals(Set.of(deviceId2), envelopeCaptor.getValue().keySet());
final MessageProtos.Envelope envelope = envelopeCaptor.getValue().get(deviceId2);
assertEquals(aci, UUID.fromString(envelope.getDestinationServiceId()));
assertEquals(aci, UUID.fromString(envelope.getSourceServiceId()));
@@ -335,10 +356,15 @@ public class ChangeNumberManagerTest {
verify(accountsManager).updatePniKeys(account, pniIdentityKey, prekeys, pqPrekeys, registrationIds);
final ArgumentCaptor<MessageProtos.Envelope> envelopeCaptor = ArgumentCaptor.forClass(MessageProtos.Envelope.class);
verify(messageSender).sendMessage(any(), eq(d2), envelopeCaptor.capture(), eq(false));
@SuppressWarnings("unchecked") final ArgumentCaptor<Map<Byte, MessageProtos.Envelope>> envelopeCaptor =
ArgumentCaptor.forClass(Map.class);
final MessageProtos.Envelope envelope = envelopeCaptor.getValue();
verify(messageSender).sendMessages(any(), envelopeCaptor.capture());
assertEquals(1, envelopeCaptor.getValue().size());
assertEquals(Set.of(deviceId2), envelopeCaptor.getValue().keySet());
final MessageProtos.Envelope envelope = envelopeCaptor.getValue().get(deviceId2);
assertEquals(aci, UUID.fromString(envelope.getDestinationServiceId()));
assertEquals(aci, UUID.fromString(envelope.getSourceServiceId()));
@@ -84,7 +84,7 @@ class MessagePersisterIntegrationTest {
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
messageDeliveryScheduler, messageDeletionExecutorService, Clock.systemUTC());
messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, mock(ReportMessageManager.class),
messageDeletionExecutorService);
messageDeletionExecutorService, Clock.systemUTC());
websocketConnectionEventExecutor = Executors.newVirtualThreadPerTaskExecutor();
asyncOperationQueueingExecutor = Executors.newSingleThreadExecutor();
@@ -143,7 +143,7 @@ class MessagePersisterIntegrationTest {
final MessageProtos.Envelope message = generateRandomMessage(messageGuid, timestamp);
messagesCache.insert(messageGuid, account.getUuid(), Device.PRIMARY_ID, message);
messagesCache.insert(messageGuid, account.getUuid(), Device.PRIMARY_ID, message).join();
expectedMessages.add(message);
}
@@ -358,7 +358,7 @@ class MessagePersisterTest {
.setServerGuid(messageGuid.toString())
.build();
messagesCache.insert(messageGuid, accountUuid, deviceId, envelope);
messagesCache.insert(messageGuid, accountUuid, deviceId, envelope).join();
}
}
@@ -40,7 +40,7 @@ class MessagesCacheGetItemsScriptTest {
.setServerGuid(serverGuid)
.build();
insertScript.execute(destinationUuid, deviceId, envelope1);
insertScript.executeAsync(destinationUuid, deviceId, envelope1);
final MessagesCacheGetItemsScript getItemsScript = new MessagesCacheGetItemsScript(
REDIS_CLUSTER_EXTENSION.getRedisCluster());
@@ -41,7 +41,7 @@ class MessagesCacheInsertScriptTest {
.setServerGuid(UUID.randomUUID().toString())
.build();
insertScript.execute(destinationUuid, deviceId, envelope1);
insertScript.executeAsync(destinationUuid, deviceId, envelope1);
assertEquals(List.of(envelope1), getStoredMessages(destinationUuid, deviceId));
@@ -50,11 +50,11 @@ class MessagesCacheInsertScriptTest {
.setServerGuid(UUID.randomUUID().toString())
.build();
insertScript.execute(destinationUuid, deviceId, envelope2);
insertScript.executeAsync(destinationUuid, deviceId, envelope2);
assertEquals(List.of(envelope1, envelope2), getStoredMessages(destinationUuid, deviceId));
insertScript.execute(destinationUuid, deviceId, envelope1);
insertScript.executeAsync(destinationUuid, deviceId, envelope1);
assertEquals(List.of(envelope1, envelope2), getStoredMessages(destinationUuid, deviceId),
"Messages with same GUID should be deduplicated");
@@ -89,10 +89,10 @@ class MessagesCacheInsertScriptTest {
final MessagesCacheInsertScript insertScript =
new MessagesCacheInsertScript(REDIS_CLUSTER_EXTENSION.getRedisCluster());
assertFalse(insertScript.execute(destinationUuid, deviceId, MessageProtos.Envelope.newBuilder()
assertFalse(insertScript.executeAsync(destinationUuid, deviceId, MessageProtos.Envelope.newBuilder()
.setServerTimestamp(Instant.now().getEpochSecond())
.setServerGuid(UUID.randomUUID().toString())
.build()));
.build()).join());
final FaultTolerantPubSubClusterConnection<byte[], byte[]> pubSubClusterConnection =
REDIS_CLUSTER_EXTENSION.getRedisCluster().createBinaryPubSubConnection();
@@ -100,9 +100,9 @@ class MessagesCacheInsertScriptTest {
pubSubClusterConnection.usePubSubConnection(connection ->
connection.sync().ssubscribe(WebSocketConnectionEventManager.getClientEventChannel(destinationUuid, deviceId)));
assertTrue(insertScript.execute(destinationUuid, deviceId, MessageProtos.Envelope.newBuilder()
assertTrue(insertScript.executeAsync(destinationUuid, deviceId, MessageProtos.Envelope.newBuilder()
.setServerTimestamp(Instant.now().getEpochSecond())
.setServerGuid(UUID.randomUUID().toString())
.build()));
.build()).join());
}
}
@@ -6,7 +6,9 @@
package org.whispersystems.textsecuregcm.storage;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import io.lettuce.core.RedisCommandExecutionException;
import java.util.ArrayList;
@@ -14,8 +16,10 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletionException;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import io.lettuce.core.RedisException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
@@ -39,8 +43,8 @@ class MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScriptTest {
REDIS_CLUSTER_EXTENSION.getRedisCluster());
final byte[] sharedMrmKey = MessagesCache.getSharedMrmKey(UUID.randomUUID());
insertMrmScript.execute(sharedMrmKey,
MessagesCacheTest.generateRandomMrmMessage(destinations));
insertMrmScript.executeAsync(sharedMrmKey,
MessagesCacheTest.generateRandomMrmMessage(destinations)).join();
final int totalDevices = destinations.values().stream().mapToInt(List::size).sum();
final long hashFieldCount = REDIS_CLUSTER_EXTENSION.getRedisCluster()
@@ -82,15 +86,17 @@ class MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScriptTest {
REDIS_CLUSTER_EXTENSION.getRedisCluster());
final byte[] sharedMrmKey = MessagesCache.getSharedMrmKey(UUID.randomUUID());
insertMrmScript.execute(sharedMrmKey,
MessagesCacheTest.generateRandomMrmMessage(new AciServiceIdentifier(UUID.randomUUID()), Device.PRIMARY_ID));
insertMrmScript.executeAsync(sharedMrmKey,
MessagesCacheTest.generateRandomMrmMessage(new AciServiceIdentifier(UUID.randomUUID()), Device.PRIMARY_ID)).join();
final RedisCommandExecutionException e = assertThrows(RedisCommandExecutionException.class,
() -> insertMrmScript.execute(sharedMrmKey,
final CompletionException completionException = assertThrows(CompletionException.class,
() -> insertMrmScript.executeAsync(sharedMrmKey,
MessagesCacheTest.generateRandomMrmMessage(new AciServiceIdentifier(UUID.randomUUID()),
Device.PRIMARY_ID)));
Device.PRIMARY_ID)).join());
assertEquals(MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript.ERROR_KEY_EXISTS, e.getMessage());
assertInstanceOf(RedisException.class, completionException.getCause());
assertTrue(completionException.getCause().getMessage()
.contains(MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript.ERROR_KEY_EXISTS));
}
}
@@ -34,7 +34,7 @@ class MessagesCacheRemoveByGuidScriptTest {
.setServerGuid(serverGuid.toString())
.build();
insertScript.execute(destinationUuid, deviceId, envelope1);
insertScript.executeAsync(destinationUuid, deviceId, envelope1);
final MessagesCacheRemoveByGuidScript removeByGuidScript = new MessagesCacheRemoveByGuidScript(
REDIS_CLUSTER_EXTENSION.getRedisCluster());
@@ -35,7 +35,7 @@ class MessagesCacheRemoveQueueScriptTest {
.setServerGuid(UUID.randomUUID().toString())
.build();
insertScript.execute(destinationUuid, deviceId, envelope1);
insertScript.executeAsync(destinationUuid, deviceId, envelope1);
final MessagesCacheRemoveQueueScript removeScript = new MessagesCacheRemoveQueueScript(
REDIS_CLUSTER_EXTENSION.getRedisCluster());
@@ -41,8 +41,7 @@ class MessagesCacheRemoveRecipientViewFromMrmDataScriptTest {
REDIS_CLUSTER_EXTENSION.getRedisCluster());
final byte[] sharedMrmKey = MessagesCache.getSharedMrmKey(UUID.randomUUID());
insertMrmScript.execute(sharedMrmKey,
MessagesCacheTest.generateRandomMrmMessage(destinations));
insertMrmScript.executeAsync(sharedMrmKey, MessagesCacheTest.generateRandomMrmMessage(destinations)).join();
final MessagesCacheRemoveRecipientViewFromMrmDataScript removeRecipientViewFromMrmDataScript = new MessagesCacheRemoveRecipientViewFromMrmDataScript(
REDIS_CLUSTER_EXTENSION.getRedisCluster());
@@ -103,8 +102,8 @@ class MessagesCacheRemoveRecipientViewFromMrmDataScriptTest {
REDIS_CLUSTER_EXTENSION.getRedisCluster());
final byte[] sharedMrmKey = MessagesCache.getSharedMrmKey(UUID.randomUUID());
insertMrmScript.execute(sharedMrmKey,
MessagesCacheTest.generateRandomMrmMessage(serviceIdentifier, deviceId));
insertMrmScript.executeAsync(sharedMrmKey,
MessagesCacheTest.generateRandomMrmMessage(serviceIdentifier, deviceId)).join();
sharedMrmKeys.add(sharedMrmKey);
}
@@ -122,7 +122,7 @@ class MessagesCacheTest {
void testInsert(final boolean sealedSender) {
final UUID messageGuid = UUID.randomUUID();
assertDoesNotThrow(() -> messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID,
generateRandomMessage(messageGuid, sealedSender)));
generateRandomMessage(messageGuid, sealedSender))).join();
}
@Test
@@ -130,8 +130,8 @@ class MessagesCacheTest {
final UUID duplicateGuid = UUID.randomUUID();
final MessageProtos.Envelope duplicateMessage = generateRandomMessage(duplicateGuid, false);
messagesCache.insert(duplicateGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, duplicateMessage);
messagesCache.insert(duplicateGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, duplicateMessage);
messagesCache.insert(duplicateGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, duplicateMessage).join();
messagesCache.insert(duplicateGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, duplicateMessage).join();
assertEquals(1, messagesCache.getAllMessages(DESTINATION_UUID, DESTINATION_DEVICE_ID, 0, 10)
.count()
@@ -149,7 +149,7 @@ class MessagesCacheTest {
final MessageProtos.Envelope message = generateRandomMessage(messageGuid, sealedSender);
messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message);
messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message).join();
final Optional<RemovedMessage> maybeRemovedMessage = messagesCache.remove(DESTINATION_UUID,
DESTINATION_DEVICE_ID, messageGuid).get(5, TimeUnit.SECONDS);
@@ -175,12 +175,12 @@ class MessagesCacheTest {
for (final MessageProtos.Envelope message : messagesToRemove) {
messagesCache.insert(UUID.fromString(message.getServerGuid()), DESTINATION_UUID, DESTINATION_DEVICE_ID,
message);
message).join();
}
for (final MessageProtos.Envelope message : messagesToPreserve) {
messagesCache.insert(UUID.fromString(message.getServerGuid()), DESTINATION_UUID, DESTINATION_DEVICE_ID,
message);
message).join();
}
final List<RemovedMessage> removedMessages = messagesCache.remove(DESTINATION_UUID, DESTINATION_DEVICE_ID,
@@ -197,7 +197,7 @@ class MessagesCacheTest {
final UUID messageGuid = UUID.randomUUID();
final MessageProtos.Envelope message = generateRandomMessage(messageGuid, true);
messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message);
messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message).join();
assertTrue(messagesCache.hasMessages(DESTINATION_UUID, DESTINATION_DEVICE_ID));
}
@@ -208,7 +208,7 @@ class MessagesCacheTest {
final UUID messageGuid = UUID.randomUUID();
final MessageProtos.Envelope message = generateRandomMessage(messageGuid, true);
messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message);
messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message).join();
assertTrue(messagesCache.hasMessagesAsync(DESTINATION_UUID, DESTINATION_DEVICE_ID).join());
}
@@ -223,7 +223,7 @@ class MessagesCacheTest {
for (int i = 0; i < messageCount; i++) {
final UUID messageGuid = UUID.randomUUID();
final MessageProtos.Envelope message = generateRandomMessage(messageGuid, i % 2 == 0);
messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message);
messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message).join();
assertEquals(expectedOldestTimestamp,
messagesCache.getEarliestUndeliveredTimestamp(DESTINATION_UUID, DESTINATION_DEVICE_ID).block());
expectedMessages.add(message);
@@ -248,7 +248,7 @@ class MessagesCacheTest {
for (int i = 0; i < messageCount; i++) {
final UUID messageGuid = UUID.randomUUID();
final MessageProtos.Envelope message = generateRandomMessage(messageGuid, sealedSender);
messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message);
messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message).join();
expectedMessages.add(message);
}
@@ -262,7 +262,7 @@ class MessagesCacheTest {
final UUID message1Guid = UUID.randomUUID();
final MessageProtos.Envelope message1 = generateRandomMessage(message1Guid, sealedSender);
messagesCache.insert(message1Guid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message1);
messagesCache.insert(message1Guid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message1).join();
final List<MessageProtos.Envelope> get1 = get(DESTINATION_UUID, DESTINATION_DEVICE_ID,
1);
assertEquals(List.of(message1), get1);
@@ -272,7 +272,7 @@ class MessagesCacheTest {
final UUID message2Guid = UUID.randomUUID();
final MessageProtos.Envelope message2 = generateRandomMessage(message2Guid, sealedSender);
messagesCache.insert(message2Guid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message2);
messagesCache.insert(message2Guid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message2).join();
assertEquals(List.of(message2), get(DESTINATION_UUID, DESTINATION_DEVICE_ID, 1));
}
@@ -287,7 +287,7 @@ class MessagesCacheTest {
for (int i = 0; i < messageCount; i++) {
final UUID messageGuid = UUID.randomUUID();
final MessageProtos.Envelope message = generateRandomMessage(messageGuid, true);
messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message);
messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message).join();
expectedMessages.add(message);
}
@@ -295,7 +295,7 @@ class MessagesCacheTest {
final UUID ephemeralMessageGuid = UUID.randomUUID();
final MessageProtos.Envelope ephemeralMessage = generateRandomMessage(ephemeralMessageGuid, true)
.toBuilder().setEphemeral(true).build();
messagesCache.insert(ephemeralMessageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, ephemeralMessage);
messagesCache.insert(ephemeralMessageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, ephemeralMessage).join();
final Clock cacheClock;
if (expectStale) {
@@ -352,7 +352,7 @@ class MessagesCacheTest {
final UUID messageGuid = UUID.randomUUID();
final MessageProtos.Envelope message = generateRandomMessage(messageGuid, sealedSender);
messagesCache.insert(messageGuid, DESTINATION_UUID, deviceId, message);
messagesCache.insert(messageGuid, DESTINATION_UUID, deviceId, message).join();
}
}
@@ -372,7 +372,7 @@ class MessagesCacheTest {
final UUID messageGuid = UUID.randomUUID();
final MessageProtos.Envelope message = generateRandomMessage(messageGuid, sealedSender);
messagesCache.insert(messageGuid, DESTINATION_UUID, deviceId, message);
messagesCache.insert(messageGuid, DESTINATION_UUID, deviceId, message).join();
}
}
@@ -404,7 +404,7 @@ class MessagesCacheTest {
final UUID messageGuid = UUID.randomUUID();
messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID,
generateRandomMessage(messageGuid, sealedSender));
generateRandomMessage(messageGuid, sealedSender)).join();
final int slot = SlotHash.getSlot(DESTINATION_UUID + "::" + DESTINATION_DEVICE_ID);
assertTrue(messagesCache.getQueuesToPersist(slot + 1, Instant.now().plusSeconds(60), 100).isEmpty());
@@ -427,7 +427,7 @@ class MessagesCacheTest {
final byte[] sharedMrmDataKey;
if (sharedMrmKeyPresent) {
sharedMrmDataKey = messagesCache.insertSharedMultiRecipientMessagePayload(mrm);
sharedMrmDataKey = messagesCache.insertSharedMultiRecipientMessagePayload(mrm).join();
} else {
sharedMrmDataKey = "{1}".getBytes(StandardCharsets.UTF_8);
}
@@ -440,7 +440,7 @@ class MessagesCacheTest {
.setSharedMrmKey(ByteString.copyFrom(sharedMrmDataKey))
.clearContent()
.build();
messagesCache.insert(guid, destinationServiceId.uuid(), deviceId, message);
messagesCache.insert(guid, destinationServiceId.uuid(), deviceId, message).join();
assertEquals(sharedMrmKeyPresent ? 1 : 0, (long) REDIS_CLUSTER_EXTENSION.getRedisCluster()
.withBinaryCluster(conn -> conn.sync().exists(sharedMrmDataKey)));
@@ -487,13 +487,13 @@ class MessagesCacheTest {
final MessageProtos.Envelope message = generateRandomMessage(messageGuid,
new AciServiceIdentifier(destinationUuid), true);
messagesCache.insert(messageGuid, destinationUuid, deviceId, message);
messagesCache.insert(messageGuid, destinationUuid, deviceId, message).join();
final SealedSenderMultiRecipientMessage mrm = generateRandomMrmMessage(destinationServiceId, deviceId);
final byte[] sharedMrmDataKey;
if (sharedMrmKeyPresent) {
sharedMrmDataKey = messagesCache.insertSharedMultiRecipientMessagePayload(mrm);
sharedMrmDataKey = messagesCache.insertSharedMultiRecipientMessagePayload(mrm).join();
} else {
sharedMrmDataKey = new byte[]{1};
}
@@ -505,7 +505,7 @@ class MessagesCacheTest {
.clearContent()
.setSharedMrmKey(ByteString.copyFrom(sharedMrmDataKey))
.build();
messagesCache.insert(mrmMessageGuid, destinationUuid, deviceId, mrmMessage);
messagesCache.insert(mrmMessageGuid, destinationUuid, deviceId, mrmMessage).join();
final List<MessageProtos.Envelope> messages = messagesCache.getMessagesToPersist(destinationUuid, deviceId, 100);
@@ -7,22 +7,42 @@ package org.whispersystems.textsecuregcm.storage;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyByte;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import com.google.protobuf.ByteString;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.signal.libsignal.protocol.InvalidMessageException;
import org.signal.libsignal.protocol.InvalidVersionException;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.tests.util.MultiRecipientMessageHelper;
import org.whispersystems.textsecuregcm.tests.util.TestRecipient;
import org.whispersystems.textsecuregcm.util.TestClock;
import reactor.core.publisher.Mono;
class MessagesManagerTest {
@@ -31,8 +51,15 @@ class MessagesManagerTest {
private final MessagesCache messagesCache = mock(MessagesCache.class);
private final ReportMessageManager reportMessageManager = mock(ReportMessageManager.class);
private static final TestClock CLOCK = TestClock.pinned(Instant.now());
private final MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache,
reportMessageManager, Executors.newSingleThreadExecutor());
reportMessageManager, Executors.newSingleThreadExecutor(), CLOCK);
@BeforeEach
void setUp() {
when(messagesCache.insert(any(), any(), anyByte(), any())).thenReturn(CompletableFuture.completedFuture(true));
}
@Test
void insert() {
@@ -43,7 +70,7 @@ class MessagesManagerTest {
final UUID destinationUuid = UUID.randomUUID();
messagesManager.insert(destinationUuid, Device.PRIMARY_ID, message);
messagesManager.insert(destinationUuid, Map.of(Device.PRIMARY_ID, message));
verify(reportMessageManager).store(eq(sourceAci.toString()), any(UUID.class));
@@ -51,11 +78,113 @@ class MessagesManagerTest {
.setSourceServiceId(destinationUuid.toString())
.build();
messagesManager.insert(destinationUuid, Device.PRIMARY_ID, syncMessage);
messagesManager.insert(destinationUuid, Map.of(Device.PRIMARY_ID, syncMessage));
verifyNoMoreInteractions(reportMessageManager);
}
@Test
void insertMultiRecipientMessage() throws InvalidMessageException, InvalidVersionException {
final ServiceIdentifier singleDeviceAccountAciServiceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
final ServiceIdentifier singleDeviceAccountPniServiceIdentifier = new PniServiceIdentifier(UUID.randomUUID());
final ServiceIdentifier multiDeviceAccountAciServiceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
final ServiceIdentifier unresolvedAccountAciServiceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
final Account singleDeviceAccount = mock(Account.class);
final Account multiDeviceAccount = mock(Account.class);
when(singleDeviceAccount.getIdentifier(IdentityType.ACI))
.thenReturn(singleDeviceAccountAciServiceIdentifier.uuid());
when(multiDeviceAccount.getIdentifier(IdentityType.ACI))
.thenReturn(multiDeviceAccountAciServiceIdentifier.uuid());
final byte[] multiRecipientMessageBytes = MultiRecipientMessageHelper.generateMultiRecipientMessage(List.of(
new TestRecipient(singleDeviceAccountAciServiceIdentifier, Device.PRIMARY_ID, 1, new byte[48]),
new TestRecipient(multiDeviceAccountAciServiceIdentifier, Device.PRIMARY_ID, 2, new byte[48]),
new TestRecipient(multiDeviceAccountAciServiceIdentifier, (byte) (Device.PRIMARY_ID + 1), 3, new byte[48]),
new TestRecipient(unresolvedAccountAciServiceIdentifier, Device.PRIMARY_ID, 4, new byte[48]),
new TestRecipient(singleDeviceAccountPniServiceIdentifier, Device.PRIMARY_ID, 5, new byte[48])
));
final SealedSenderMultiRecipientMessage multiRecipientMessage =
SealedSenderMultiRecipientMessage.parse(multiRecipientMessageBytes);
final Map<SealedSenderMultiRecipientMessage.Recipient, Account> resolvedRecipients = new HashMap<>();
multiRecipientMessage.getRecipients().forEach(((serviceId, recipient) -> {
if (serviceId.getRawUUID().equals(singleDeviceAccountAciServiceIdentifier.uuid()) ||
serviceId.getRawUUID().equals(singleDeviceAccountPniServiceIdentifier.uuid())) {
resolvedRecipients.put(recipient, singleDeviceAccount);
} else if (serviceId.getRawUUID().equals(multiDeviceAccountAciServiceIdentifier.uuid())) {
resolvedRecipients.put(recipient, multiDeviceAccount);
}
}));
final Map<Account, Map<Byte, Boolean>> expectedPresenceByAccountAndDeviceId = Map.of(
singleDeviceAccount, Map.of(Device.PRIMARY_ID, true),
multiDeviceAccount, Map.of(Device.PRIMARY_ID, false, (byte) (Device.PRIMARY_ID + 1), true)
);
final Map<UUID, Map<Byte, Boolean>> presenceByAccountIdentifierAndDeviceId = Map.of(
singleDeviceAccountAciServiceIdentifier.uuid(), Map.of(Device.PRIMARY_ID, true),
multiDeviceAccountAciServiceIdentifier.uuid(), Map.of(Device.PRIMARY_ID, false, (byte) (Device.PRIMARY_ID + 1), true)
);
final byte[] sharedMrmKey = "shared-mrm-key".getBytes(StandardCharsets.UTF_8);
when(messagesCache.insertSharedMultiRecipientMessagePayload(multiRecipientMessage))
.thenReturn(CompletableFuture.completedFuture(sharedMrmKey));
when(messagesCache.insert(any(), any(), anyByte(), any()))
.thenAnswer(invocation -> {
final UUID accountIdentifier = invocation.getArgument(1);
final byte deviceId = invocation.getArgument(2);
return CompletableFuture.completedFuture(
presenceByAccountIdentifierAndDeviceId.getOrDefault(accountIdentifier, Collections.emptyMap())
.getOrDefault(deviceId, false));
});
final long clientTimestamp = System.currentTimeMillis();
final boolean isStory = ThreadLocalRandom.current().nextBoolean();
final boolean isEphemeral = ThreadLocalRandom.current().nextBoolean();
final boolean isUrgent = ThreadLocalRandom.current().nextBoolean();
final Envelope prototypeExpectedMessage = Envelope.newBuilder()
.setType(Envelope.Type.UNIDENTIFIED_SENDER)
.setClientTimestamp(clientTimestamp)
.setServerTimestamp(CLOCK.millis())
.setStory(isStory)
.setEphemeral(isEphemeral)
.setUrgent(isUrgent)
.setSharedMrmKey(ByteString.copyFrom(sharedMrmKey))
.build();
assertEquals(expectedPresenceByAccountAndDeviceId,
messagesManager.insertMultiRecipientMessage(multiRecipientMessage, resolvedRecipients, clientTimestamp, isStory, isEphemeral, isUrgent).join());
verify(messagesCache).insert(any(),
eq(singleDeviceAccountAciServiceIdentifier.uuid()),
eq(Device.PRIMARY_ID),
eq(prototypeExpectedMessage.toBuilder().setDestinationServiceId(singleDeviceAccountAciServiceIdentifier.toServiceIdentifierString()).build()));
verify(messagesCache).insert(any(),
eq(singleDeviceAccountAciServiceIdentifier.uuid()),
eq(Device.PRIMARY_ID),
eq(prototypeExpectedMessage.toBuilder().setDestinationServiceId(singleDeviceAccountPniServiceIdentifier.toServiceIdentifierString()).build()));
verify(messagesCache).insert(any(),
eq(multiDeviceAccountAciServiceIdentifier.uuid()),
eq((byte) (Device.PRIMARY_ID + 1)),
eq(prototypeExpectedMessage.toBuilder().setDestinationServiceId(multiDeviceAccountAciServiceIdentifier.toServiceIdentifierString()).build()));
verify(messagesCache, never()).insert(any(),
eq(unresolvedAccountAciServiceIdentifier.uuid()),
anyByte(),
any());
}
@ParameterizedTest
@CsvSource({
"false, false, false",
Loaded 100 of 113 files, more files were not shown because too many files have changed in this diff. Show more