Compare commits

...
Author SHA1 Message Date
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
Ravi Khadiwala a88560e557 Add gRPC backup services 2025-01-08 16:13:51 -06:00
Ravi Khadiwala 3ca9a66323 Stripe HTTP2 clients in CloudflareTurnCredentialsManager 2025-01-08 16:02:22 -06:00
Chris Eager 3a4a55c245 Reject old-format Benin numbers, which are now undeliverable 2025-01-07 12:16:44 -06:00
104 changed files with 4071 additions and 2290 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 }}
+2 -2
View File
@@ -11,9 +11,9 @@ jobs:
container: ubuntu:22.04
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
+5 -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
@@ -484,6 +485,7 @@ turn:
- turns:%s:443?transport=tcp
ttl: 86400
hostname: turn.cloudflare.example.com
numHttpClients: 1
linkDevice:
secret: secret://linkDevice.secret
+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>
@@ -133,7 +133,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;
@@ -154,6 +154,7 @@ import org.whispersystems.textsecuregcm.grpc.PaymentsGrpcService;
import org.whispersystems.textsecuregcm.grpc.ProfileAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.ProfileGrpcService;
import org.whispersystems.textsecuregcm.grpc.RequestAttributesInterceptor;
import org.whispersystems.textsecuregcm.grpc.ValidatingInterceptor;
import org.whispersystems.textsecuregcm.grpc.net.GrpcClientConnectionManager;
import org.whispersystems.textsecuregcm.grpc.net.ManagedDefaultEventLoopGroup;
import org.whispersystems.textsecuregcm.grpc.net.ManagedLocalGrpcServer;
@@ -175,6 +176,7 @@ import org.whispersystems.textsecuregcm.mappers.ImpossiblePhoneNumberExceptionMa
import org.whispersystems.textsecuregcm.mappers.InvalidWebsocketAddressExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.JsonMappingExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.NonNormalizedPhoneNumberExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.ObsoletePhoneNumberFormatExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.ServerRejectedExceptionMapper;
@@ -225,6 +227,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;
@@ -329,6 +332,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()));
@@ -427,7 +431,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(
@@ -614,7 +618,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 =
@@ -667,8 +671,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(),
@@ -676,6 +679,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getTurnConfiguration().cloudflare().urls(),
config.getTurnConfiguration().cloudflare().urlsWithIps(),
config.getTurnConfiguration().cloudflare().hostname(),
config.getTurnConfiguration().cloudflare().numHttpClients(),
config.getTurnConfiguration().cloudflare().circuitBreaker(),
cloudflareTurnHttpExecutor,
config.getTurnConfiguration().cloudflare().retry(),
@@ -696,9 +700,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,
@@ -860,6 +864,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final RequestAttributesInterceptor requestAttributesInterceptor =
new RequestAttributesInterceptor(grpcClientConnectionManager);
final ValidatingInterceptor validatingInterceptor = new ValidatingInterceptor();
final LocalAddress anonymousGrpcServerAddress = new LocalAddress("grpc-anonymous");
final LocalAddress authenticatedGrpcServerAddress = new LocalAddress("grpc-authenticated");
@@ -873,6 +879,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
.intercept(
new ExternalRequestFilter(config.getExternalRequestFilterConfiguration().permittedInternalRanges(),
config.getExternalRequestFilterConfiguration().grpcMethods()))
.intercept(validatingInterceptor)
// TODO: specialize metrics with user-agent platform
.intercept(metricCollectingServerInterceptor)
.intercept(errorMappingInterceptor)
@@ -895,6 +902,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
// http://grpc.github.io/grpc-java/javadoc/io/grpc/ServerBuilder.html#intercept-io.grpc.ServerInterceptor-
serverBuilder
// TODO: specialize metrics with user-agent platform
.intercept(validatingInterceptor)
.intercept(metricCollectingServerInterceptor)
.intercept(errorMappingInterceptor)
.intercept(remoteDeprecationFilter)
@@ -1090,11 +1098,12 @@ 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),
@@ -1108,7 +1117,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
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()),
@@ -1119,7 +1128,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),
@@ -1212,6 +1221,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new ServerRejectedExceptionMapper(),
new ImpossiblePhoneNumberExceptionMapper(),
new NonNormalizedPhoneNumberExceptionMapper(),
new ObsoletePhoneNumberFormatExceptionMapper(),
new RegistrationServiceSenderExceptionMapper(),
new SubscriptionExceptionMapper(),
new JsonMappingExceptionMapper()
@@ -6,6 +6,8 @@
package org.whispersystems.textsecuregcm.auth;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;
import io.netty.resolver.dns.DnsNameResolver;
import jakarta.ws.rs.core.Response;
import java.io.IOException;
@@ -14,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;
@@ -22,6 +25,7 @@ import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.SystemMapper;
@@ -29,6 +33,9 @@ public class CloudflareTurnCredentialsManager {
private static final Logger logger = LoggerFactory.getLogger(CloudflareTurnCredentialsManager.class);
private static final String CREDENTIAL_FETCH_TIMER_NAME = MetricsUtil.name(CloudflareTurnCredentialsManager.class,
"credentialFetchLatency");
private final List<String> cloudflareTurnUrls;
private final List<String> cloudflareTurnUrlsWithIps;
private final String cloudflareTurnHostname;
@@ -51,8 +58,9 @@ public class CloudflareTurnCredentialsManager {
public CloudflareTurnCredentialsManager(final String cloudflareTurnApiToken,
final String cloudflareTurnEndpoint, final long cloudflareTurnTtl, final List<String> cloudflareTurnUrls,
final List<String> cloudflareTurnUrlsWithIps, final String cloudflareTurnHostname,
final CircuitBreakerConfiguration circuitBreaker, final ExecutorService executor, final RetryConfiguration retry,
final ScheduledExecutorService retryExecutor, final DnsNameResolver dnsNameResolver) {
final int cloudflareTurnNumHttpClients, final CircuitBreakerConfiguration circuitBreaker,
final ExecutorService executor, final RetryConfiguration retry, final ScheduledExecutorService retryExecutor,
final DnsNameResolver dnsNameResolver) {
this.cloudflareTurnClient = FaultTolerantHttpClient.newBuilder()
.withName("cloudflare-turn")
@@ -60,6 +68,7 @@ public class CloudflareTurnCredentialsManager {
.withExecutor(executor)
.withRetry(retry)
.withRetryExecutor(retryExecutor)
.withNumClients(cloudflareTurnNumHttpClients)
.build();
this.cloudflareTurnUrls = cloudflareTurnUrls;
this.cloudflareTurnUrlsWithIps = cloudflareTurnUrlsWithIps;
@@ -93,11 +102,20 @@ public class CloudflareTurnCredentialsManager {
throw new IOException(e);
}
final Timer.Sample sample = Timer.start();
final HttpResponse<String> response;
try {
response = cloudflareTurnClient.sendAsync(request, HttpResponse.BodyHandlers.ofString()).join();
sample.stop(Timer.builder(CREDENTIAL_FETCH_TIMER_NAME)
.publishPercentileHistogram(true)
.tags("outcome", "success")
.register(Metrics.globalRegistry));
} catch (CompletionException e) {
logger.warn("failed to make http request to Cloudflare Turn: {}", e.getMessage());
sample.stop(Timer.builder(CREDENTIAL_FETCH_TIMER_NAME)
.publishPercentileHistogram(true)
.tags("outcome", "failure")
.register(Metrics.globalRegistry));
throw new IOException(ExceptionUtils.unwrap(e));
}
@@ -109,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
);
}
}
@@ -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
) {
}
@@ -9,6 +9,7 @@ import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.util.List;
import jakarta.validation.constraints.Positive;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
public record CloudflareTurnConfiguration(@NotNull SecretString apiToken,
@@ -18,7 +19,8 @@ public record CloudflareTurnConfiguration(@NotNull SecretString apiToken,
@NotBlank List<String> urlsWithIps,
@NotNull @Valid CircuitBreakerConfiguration circuitBreaker,
@NotNull @Valid RetryConfiguration retry,
@NotBlank String hostname) {
@NotBlank String hostname,
@Positive int numHttpClients) {
public CloudflareTurnConfiguration {
if (circuitBreaker == null) {
@@ -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);
@@ -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)
@@ -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(CallRoutingController.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,32 @@ 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.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 +432,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 +463,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 +519,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 +564,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 +615,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 +676,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 +726,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 +901,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 +950,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();
}
}
}
@@ -95,6 +95,7 @@ import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.ObsoletePhoneNumberFormatException;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.Util;
@@ -172,8 +173,9 @@ 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)
throws RateLimitExceededException {
public VerificationSessionResponse createSession(@NotNull @Valid final CreateVerificationSessionRequest request,
@Context final ContainerRequestContext requestContext)
throws RateLimitExceededException, ObsoletePhoneNumberFormatException {
final Pair<String, PushNotification.TokenType> pushTokenAndType = validateAndExtractPushToken(
request.getUpdateVerificationSessionRequest());
@@ -187,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<>();
@@ -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)
@@ -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,226 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import io.grpc.Status;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import org.signal.chat.backup.CopyMediaRequest;
import org.signal.chat.backup.CopyMediaResponse;
import org.signal.chat.backup.DeleteAllRequest;
import org.signal.chat.backup.DeleteAllResponse;
import org.signal.chat.backup.DeleteMediaRequest;
import org.signal.chat.backup.DeleteMediaResponse;
import org.signal.chat.backup.GetBackupInfoRequest;
import org.signal.chat.backup.GetBackupInfoResponse;
import org.signal.chat.backup.GetCdnCredentialsRequest;
import org.signal.chat.backup.GetCdnCredentialsResponse;
import org.signal.chat.backup.GetUploadFormRequest;
import org.signal.chat.backup.GetUploadFormResponse;
import org.signal.chat.backup.ListMediaRequest;
import org.signal.chat.backup.ListMediaResponse;
import org.signal.chat.backup.ReactorBackupsAnonymousGrpc;
import org.signal.chat.backup.RefreshRequest;
import org.signal.chat.backup.RefreshResponse;
import org.signal.chat.backup.SetPublicKeyRequest;
import org.signal.chat.backup.SetPublicKeyResponse;
import org.signal.chat.backup.SignedPresentation;
import org.signal.libsignal.protocol.InvalidKeyException;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialPresentation;
import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
import org.whispersystems.textsecuregcm.backup.BackupManager;
import org.whispersystems.textsecuregcm.backup.CopyParameters;
import org.whispersystems.textsecuregcm.backup.MediaEncryptionParameters;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public class BackupsAnonymousGrpcService extends ReactorBackupsAnonymousGrpc.BackupsAnonymousImplBase {
private final BackupManager backupManager;
public BackupsAnonymousGrpcService(final BackupManager backupManager) {
this.backupManager = backupManager;
}
@Override
public Mono<GetCdnCredentialsResponse> getCdnCredentials(final GetCdnCredentialsRequest request) {
return authenticateBackupUserMono(request.getSignedPresentation())
.map(user -> backupManager.generateReadAuth(user, request.getCdn()))
.map(credentials -> GetCdnCredentialsResponse.newBuilder().putAllHeaders(credentials).build());
}
@Override
public Mono<GetBackupInfoResponse> getBackupInfo(final GetBackupInfoRequest request) {
return Mono.fromFuture(() ->
authenticateBackupUser(request.getSignedPresentation()).thenCompose(backupManager::backupInfo))
.map(info -> GetBackupInfoResponse.newBuilder()
.setBackupName(info.messageBackupKey())
.setCdn(info.cdn())
.setBackupDir(info.backupSubdir())
.setMediaDir(info.mediaSubdir())
.setUsedSpace(info.mediaUsedSpace().orElse(0L))
.build());
}
@Override
public Mono<RefreshResponse> refresh(final RefreshRequest request) {
return Mono.fromFuture(() -> authenticateBackupUser(request.getSignedPresentation())
.thenCompose(backupManager::ttlRefresh))
.thenReturn(RefreshResponse.getDefaultInstance());
}
@Override
public Mono<SetPublicKeyResponse> setPublicKey(final SetPublicKeyRequest request) {
final ECPublicKey publicKey = deserialize(ECPublicKey::new, request.getPublicKey().toByteArray());
final BackupAuthCredentialPresentation presentation = deserialize(
BackupAuthCredentialPresentation::new,
request.getSignedPresentation().getPresentation().toByteArray());
final byte[] signature = request.getSignedPresentation().getPresentationSignature().toByteArray();
return Mono.fromFuture(() -> backupManager.setPublicKey(presentation, signature, publicKey))
.thenReturn(SetPublicKeyResponse.getDefaultInstance());
}
@Override
public Mono<GetUploadFormResponse> getUploadForm(final GetUploadFormRequest request) {
return authenticateBackupUserMono(request.getSignedPresentation())
.flatMap(backupUser -> switch (request.getUploadTypeCase()) {
case MESSAGES -> Mono.fromFuture(backupManager.createMessageBackupUploadDescriptor(backupUser));
case MEDIA -> Mono.fromCompletionStage(backupManager.createTemporaryAttachmentUploadDescriptor(backupUser));
case UPLOADTYPE_NOT_SET -> Mono.error(Status.INVALID_ARGUMENT
.withDescription("Must set upload_type")
.asRuntimeException());
})
.map(uploadDescriptor -> GetUploadFormResponse.newBuilder()
.setCdn(uploadDescriptor.cdn())
.setKey(uploadDescriptor.key())
.setSignedUploadLocation(uploadDescriptor.signedUploadLocation())
.putAllHeaders(uploadDescriptor.headers())
.build());
}
@Override
public Flux<CopyMediaResponse> copyMedia(final CopyMediaRequest request) {
return authenticateBackupUserMono(request.getSignedPresentation())
.flatMapMany(backupUser -> backupManager.copyToBackup(backupUser,
request.getItemsList().stream().map(item -> new CopyParameters(
item.getSourceAttachmentCdn(), item.getSourceKey(),
// uint32 in proto, make sure it fits in a signed int
fromUnsignedExact(item.getObjectLength()),
new MediaEncryptionParameters(item.getEncryptionKey().toByteArray(), item.getHmacKey().toByteArray()),
item.getMediaId().toByteArray())).toList()))
.map(copyResult -> {
CopyMediaResponse.Builder builder = CopyMediaResponse
.newBuilder()
.setMediaId(ByteString.copyFrom(copyResult.mediaId()));
builder = switch (copyResult.outcome()) {
case SUCCESS -> builder
.setSuccess(CopyMediaResponse.CopySuccess.newBuilder().setCdn(copyResult.cdn()).build());
case OUT_OF_QUOTA -> builder
.setOutOfSpace(CopyMediaResponse.OutOfSpace.getDefaultInstance());
case SOURCE_WRONG_LENGTH -> builder
.setWrongSourceLength(CopyMediaResponse.WrongSourceLength.getDefaultInstance());
case SOURCE_NOT_FOUND -> builder
.setSourceNotFound(CopyMediaResponse.SourceNotFound.getDefaultInstance());
};
return builder.build();
});
}
@Override
public Mono<ListMediaResponse> listMedia(final ListMediaRequest request) {
return authenticateBackupUserMono(request.getSignedPresentation()).zipWhen(
backupUser -> Mono.fromFuture(backupManager.list(
backupUser,
request.hasCursor() ? Optional.of(request.getCursor()) : Optional.empty(),
request.getLimit()).toCompletableFuture()),
(backupUser, listResult) -> {
final ListMediaResponse.Builder builder = ListMediaResponse.newBuilder();
for (BackupManager.StorageDescriptorWithLength sd : listResult.media()) {
builder.addPage(ListMediaResponse.ListEntry.newBuilder()
.setMediaId(ByteString.copyFrom(sd.key()))
.setCdn(sd.cdn())
.setLength(sd.length())
.build());
}
builder
.setBackupDir(backupUser.backupDir())
.setMediaDir(backupUser.mediaDir());
listResult.cursor().ifPresent(builder::setCursor);
return builder.build();
});
}
@Override
public Mono<DeleteAllResponse> deleteAll(final DeleteAllRequest request) {
return Mono.fromFuture(() -> authenticateBackupUser(request.getSignedPresentation())
.thenCompose(backupManager::deleteEntireBackup))
.thenReturn(DeleteAllResponse.getDefaultInstance());
}
@Override
public Flux<DeleteMediaResponse> deleteMedia(final DeleteMediaRequest request) {
return Mono
.fromFuture(() -> authenticateBackupUser(request.getSignedPresentation()))
.flatMapMany(backupUser -> backupManager.deleteMedia(backupUser, request
.getItemsList()
.stream()
.map(item -> new BackupManager.StorageDescriptor(item.getCdn(), item.getMediaId().toByteArray()))
.toList()))
.map(storageDescriptor -> DeleteMediaResponse.newBuilder()
.setMediaId(ByteString.copyFrom(storageDescriptor.key()))
.setCdn(storageDescriptor.cdn()).build());
}
private Mono<AuthenticatedBackupUser> authenticateBackupUserMono(final SignedPresentation signedPresentation) {
return Mono.fromFuture(() -> authenticateBackupUser(signedPresentation));
}
private CompletableFuture<AuthenticatedBackupUser> authenticateBackupUser(
final SignedPresentation signedPresentation) {
if (signedPresentation == null) {
throw Status.UNAUTHENTICATED.asRuntimeException();
}
try {
return backupManager.authenticateBackupUser(
new BackupAuthCredentialPresentation(signedPresentation.getPresentation().toByteArray()),
signedPresentation.getPresentationSignature().toByteArray());
} catch (InvalidInputException e) {
throw Status.UNAUTHENTICATED.withDescription("Could not deserialize presentation").asRuntimeException();
}
}
/**
* Convert an int from a proto uint32 to a signed positive integer, throwing if the value exceeds
* {@link Integer#MAX_VALUE}. To convert to a long, see {@link Integer#toUnsignedLong(int)}
*/
private static int fromUnsignedExact(final int i) {
if (i < 0) {
throw Status.INVALID_ARGUMENT.withDescription("Invalid size").asRuntimeException();
}
return i;
}
private interface Deserializer<T> {
T deserialize(byte[] bytes) throws InvalidInputException, InvalidKeyException;
}
private static <T> T deserialize(Deserializer<T> deserializer, byte[] bytes) {
try {
return deserializer.deserialize(bytes);
} catch (InvalidInputException | InvalidKeyException e) {
throw Status.INVALID_ARGUMENT.withDescription("Invalid serialization").asRuntimeException();
}
}
}
@@ -0,0 +1,122 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import io.grpc.Status;
import java.time.Instant;
import java.util.List;
import java.util.stream.Collectors;
import org.signal.chat.backup.GetBackupAuthCredentialsRequest;
import org.signal.chat.backup.GetBackupAuthCredentialsResponse;
import org.signal.chat.backup.ReactorBackupsGrpc;
import org.signal.chat.backup.RedeemReceiptRequest;
import org.signal.chat.backup.RedeemReceiptResponse;
import org.signal.chat.backup.SetBackupIdRequest;
import org.signal.chat.backup.SetBackupIdResponse;
import org.signal.chat.common.ZkCredential;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialRequest;
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import reactor.core.publisher.Mono;
public class BackupsGrpcService extends ReactorBackupsGrpc.BackupsImplBase {
private final AccountsManager accountManager;
private final BackupAuthManager backupAuthManager;
public BackupsGrpcService(final AccountsManager accountManager, final BackupAuthManager backupAuthManager) {
this.accountManager = accountManager;
this.backupAuthManager = backupAuthManager;
}
@Override
public Mono<SetBackupIdResponse> setBackupId(SetBackupIdRequest request) {
final BackupAuthCredentialRequest messagesCredentialRequest = deserialize(
BackupAuthCredentialRequest::new,
request.getMessagesBackupAuthCredentialRequest().toByteArray());
final BackupAuthCredentialRequest mediaCredentialRequest = deserialize(
BackupAuthCredentialRequest::new,
request.getMediaBackupAuthCredentialRequest().toByteArray());
return authenticatedAccount()
.flatMap(account -> Mono.fromFuture(
backupAuthManager.commitBackupId(account, messagesCredentialRequest, mediaCredentialRequest)))
.thenReturn(SetBackupIdResponse.getDefaultInstance());
}
public Mono<RedeemReceiptResponse> redeemReceipt(RedeemReceiptRequest request) {
final ReceiptCredentialPresentation receiptCredentialPresentation = deserialize(
ReceiptCredentialPresentation::new,
request.getPresentation().toByteArray());
return authenticatedAccount()
.flatMap(account -> Mono.fromFuture(backupAuthManager.redeemReceipt(account, receiptCredentialPresentation)))
.thenReturn(RedeemReceiptResponse.getDefaultInstance());
}
@Override
public Mono<GetBackupAuthCredentialsResponse> getBackupAuthCredentials(GetBackupAuthCredentialsRequest request) {
return authenticatedAccount().flatMap(account -> {
final Mono<List<BackupAuthManager.Credential>> messageCredentials = Mono.fromCompletionStage(() ->
backupAuthManager.getBackupAuthCredentials(
account,
BackupCredentialType.MESSAGES,
Instant.ofEpochSecond(request.getRedemptionStart()),
Instant.ofEpochSecond(request.getRedemptionStop())));
final Mono<List<BackupAuthManager.Credential>> mediaCredentials = Mono.fromCompletionStage(() ->
backupAuthManager.getBackupAuthCredentials(
account,
BackupCredentialType.MEDIA,
Instant.ofEpochSecond(request.getRedemptionStart()),
Instant.ofEpochSecond(request.getRedemptionStop())));
return messageCredentials.zipWith(mediaCredentials, (messageCreds, mediaCreds) ->
GetBackupAuthCredentialsResponse.newBuilder()
.putAllMessageCredentials(messageCreds.stream().collect(Collectors.toMap(
c -> c.redemptionTime().getEpochSecond(),
c -> ZkCredential.newBuilder()
.setCredential(ByteString.copyFrom(c.credential().serialize()))
.setRedemptionTime(c.redemptionTime().getEpochSecond())
.build())))
.putAllMediaCredentials(mediaCreds.stream().collect(Collectors.toMap(
c -> c.redemptionTime().getEpochSecond(),
c -> ZkCredential.newBuilder()
.setCredential(ByteString.copyFrom(c.credential().serialize()))
.setRedemptionTime(c.redemptionTime().getEpochSecond())
.build())))
.build());
});
}
private Mono<Account> authenticatedAccount() {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
return Mono
.fromFuture(() -> accountManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException));
}
private interface Deserializer<T> {
T deserialize(byte[] bytes) throws InvalidInputException;
}
private <T> T deserialize(Deserializer<T> deserializer, byte[] bytes) {
try {
return deserializer.deserialize(bytes);
} catch (InvalidInputException e) {
throw Status.INVALID_ARGUMENT.withDescription("Invalid serialization").asRuntimeException();
}
}
}
@@ -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());
}
}
@@ -0,0 +1,18 @@
package org.whispersystems.textsecuregcm.mappers;
import io.micrometer.core.instrument.Metrics;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.util.ObsoletePhoneNumberFormatException;
public class ObsoletePhoneNumberFormatExceptionMapper implements ExceptionMapper<ObsoletePhoneNumberFormatException> {
private static final String COUNTER_NAME = MetricsUtil.name(ObsoletePhoneNumberFormatExceptionMapper.class, "errors");
@Override
public Response toResponse(final ObsoletePhoneNumberFormatException exception) {
Metrics.counter(COUNTER_NAME, "regionCode", exception.getRegionCode()).increment();
return Response.status(499).build();
}
}
@@ -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);
@@ -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);
}
/**
@@ -0,0 +1,15 @@
package org.whispersystems.textsecuregcm.util;
public class ObsoletePhoneNumberFormatException extends Exception {
private final String regionCode;
public ObsoletePhoneNumberFormatException(final String regionCode) {
super("The provided format is obsolete in %s".formatted(regionCode));
this.regionCode = regionCode;
}
public String getRegionCode() {
return regionCode;
}
}
@@ -27,7 +27,6 @@ import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.random.RandomGenerator;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
public class Util {
@@ -125,7 +124,7 @@ public class Util {
try {
final PhoneNumber phoneNumber = PHONE_NUMBER_UTIL.parse(number, null);
// Benin is changing phone number formats from +229 XXXXXXXX to +229 01XXXXXXXX starting on November 30, 2024
// Benin changed phone number formats from +229 XXXXXXXX to +229 01XXXXXXXX on November 30, 2024
if ("BJ".equals(PHONE_NUMBER_UTIL.getRegionCodeForNumber(phoneNumber))) {
final String nationalSignificantNumber = PHONE_NUMBER_UTIL.getNationalSignificantNumber(phoneNumber);
final String alternateE164;
@@ -176,7 +175,7 @@ public class Util {
throw new IllegalArgumentException("Numbers from different countries cannot be equivalent alternate forms");
}
if (regions.contains("BJ")) {
// Benin is changing phone number formats from +229 XXXXXXXX to +229 01XXXXXXXX starting on November 30, 2024
// Benin changed phone number formats from +229 XXXXXXXX to +229 01XXXXXXXX on November 30, 2024
// We prefer the longest form for long-term stability
return e164s.stream().sorted(Comparator.comparingInt(String::length).reversed()).findFirst();
}
@@ -217,7 +216,7 @@ public class Util {
}
/**
* Benin is changing phone number formats from +229 XXXXXXXX to +229 01XXXXXXXX starting on November 30, 2024.
* Benin changed phone number formats from +229 XXXXXXXX to +229 01XXXXXXXX on November 30, 2024
*
* @param phoneNumber the phone number to check.
* @return whether the provided phone number is an old-format Benin phone number
@@ -235,11 +234,9 @@ public class Util {
* @return the canonical phone number if applicable, otherwise the original phone number.
*/
public static Phonenumber.PhoneNumber canonicalizePhoneNumber(final Phonenumber.PhoneNumber phoneNumber)
throws NumberParseException {
throws NumberParseException, ObsoletePhoneNumberFormatException {
if (isOldFormatBeninPhoneNumber(phoneNumber)) {
// Benin changed phone number formats from +229 XXXXXXXX to +229 01XXXXXXXX starting on November 30, 2024.
final String newFormatNumber = "+22901" + PHONE_NUMBER_UTIL.getNationalSignificantNumber(phoneNumber);
return PhoneNumberUtil.getInstance().parse(newFormatNumber, null);
throw new ObsoletePhoneNumberFormatException("bj");
}
return phoneNumber;
}
@@ -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 {
@@ -0,0 +1,544 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
syntax = "proto3";
option java_multiple_files = true;
package org.signal.chat.backup;
import "google/protobuf/empty.proto";
import "org/signal/chat/common.proto";
import "org/signal/chat/require.proto";
/**
* Service for backup operations that require account authentication.
*
* Most actual backup operations operate on the backup-id and cannot be linked
* to the caller's account, but setting up anonymous credentials and changing
* backup tier requires account authentication.
*
* All rpcs on this service may return these errors. rpc specific errors
* documented on the individual rpc.
*
* errors:
* UNAUTHENTICATED Authentication failed or the account does not exist
* INVALID_ARGUMENT The request did not meet a documented requirement
* RESOURCE_EXHAUSTED Rate limit exceeded. A retry-after header containing an
* ISO8601 duration string will be present in the response
* trailers.
*/
service Backups {
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
/**
* Set a (blinded) backup-id for the account.
*
* Each account may have a single active backup-id that can be used
* to store and retrieve backups. Once the backup-id is set,
* BackupAuthCredentials can be generated using GetBackupAuthCredentials.
*
* The blinded backup-id and the key-pair used to blind it must be derived
* from a recoverable secret.
*
* errors:
* PERMISSION_DENIED: This account is not currently eligible for backups
*/
rpc SetBackupId(SetBackupIdRequest) returns (SetBackupIdResponse) {}
/**
* Redeem a receipt acquired from /v1/subscription/{subscriberId}/receipt_credentials
* to mark the account as eligible for the paid backup tier.
*
* After successful redemption, subsequent requests to
* GetBackupAuthCredentials will return credentials with the level on the
* provided receipt until the expiration time on the receipt.
*/
rpc RedeemReceipt(RedeemReceiptRequest) returns (RedeemReceiptResponse) {}
/**
* After setting a blinded backup-id with PUT /v1/archives/, this fetches
* credentials that can be used to perform operations against that backup-id.
* Clients may (and should) request up to 7 days of credentials at a time.
*
* The redemption_start and redemption_end seconds must be UTC day aligned, and
* must not span more than 7 days.
*
* Each credential contains a receipt level which indicates the backup level
* the credential is good for. If the account has paid backup access that
* expires at some point in the provided redemption window, credentials with
* redemption times after the expiration may be on a lower backup level.
*
* Clients must validate the receipt level on the credential matches a known
* receipt level before using it.
*
* errors:
* NOT_FOUND: Could not find an existing blinded backup id associated with the
* account.
*/
rpc GetBackupAuthCredentials(GetBackupAuthCredentialsRequest) returns (GetBackupAuthCredentialsResponse) {}
}
message SetBackupIdRequest {
/**
* A BackupAuthCredentialRequest containing a blinded encrypted backup-id,
* encoded in standard padded base64. This backup-id should be used for
* message backups only, and must have the message backup type set on the
* credential.
*/
bytes messages_backup_auth_credential_request = 1;
/**
* A BackupAuthCredentialRequest containing a blinded encrypted backup-id,
* encoded in standard padded base64. This backup-id should be used for
* media only, and must have the media type set on the credential.
*/
bytes media_backup_auth_credential_request = 2;
}
message SetBackupIdResponse {}
message RedeemReceiptRequest {
/**
* Presentation for a previously acquired receipt, serialized with libsignal
*/
bytes presentation = 1;
}
message RedeemReceiptResponse {}
message GetBackupAuthCredentialsRequest {
/**
* The redemption time for the first credential. This must be a day-aligned
* seconds since epoch in UTC.
*/
int64 redemption_start = 1 [(require.range).min = 1];
/**
* The redemption time for the last credential. This must be a day-aligned
* seconds since epoch in UTC. The span between redemptionStart and
* redemptionEnd must not exceed 7 days.
*/
int64 redemption_stop = 2 [(require.range).min = 1];
}
message GetBackupAuthCredentialsResponse {
/**
* The requested message backup ZkCredentials indexed by the start of their
* validity period. The smallest key should be for the requested
* redemption_start, the largest for the requested the requested
* redemption_end.
*/
map<int64, common.ZkCredential> message_credentials = 1;
/**
* The requested media backup ZkCredentials indexed by the start of their
* validity period. The smallest key should be for the requested
* redemption_start, the largest for the requested the requested
* redemption_end.
*/
map<int64, common.ZkCredential> media_credentials = 2;
}
/**
* Service for backup operations with anonymous credentials
*
* This service never requires account authentication. It instead requires a
* backup-id authenticated with an anonymous credential that cannot be linked
* to the account.
*
* To register an anonymous credential:
* 1. Set a backup-id on the authenticated channel via Backups::SetBackupId
* 2. Retrieve BackupAuthCredentials via Backups::GetBackupAuthCredentials
* 3. Generate a key pair and set the public key via
* BackupsAnonymous::SetPublicKey
*
* Unless otherwise noted, requests for this service require a
* SignedPresentation, which includes:
* - a presentation generated from a BackupAuthCredential issued by
* GetBackupAuthCredentials
* - a signature of that presentation using the private key of a key pair
* previously set with SetPublicKey.
*
* All RPCs on this service may return these errors. RPC specific errors
* documented on the individual RPC.
*
* errors:
* UNAUTHENTICATED Either the presentation was missing, the credential was
* expired, presentation verification failed, the signature
* was incorrect, there was no committed public key for the
* corresponding backup id, or the request was made on a
* non-anonymous channel.
* PERMISSION_DENIED The credential does not have permission to perform the
* requested action.
* RESOURCE_EXHAUSTED Rate limit exceeded. A retry-after header containing an
* ISO8601 duration string will be present in the response
* trailers.
* INVALID_ARGUMENT The request did not meet a documented requirement
*/
service BackupsAnonymous {
option (require.auth) = AUTH_ONLY_ANONYMOUS;
/**
* Retrieve credentials used to read objects stored on the backup cdn
*/
rpc GetCdnCredentials(GetCdnCredentialsRequest) returns (GetCdnCredentialsResponse) {}
/**
* Retrieve information about the currently stored backup
*/
rpc GetBackupInfo(GetBackupInfoRequest) returns (GetBackupInfoResponse) {}
/**
* Permanently set the public key of an ED25519 key-pair for the backup-id.
* All requests (including this one!) must sign their BackupAuthCredential
* presentations with the private key corresponding to the provided public key.
*
* Trying to set a public key when a different one is already set will return
* an UNAUTHENTICATED error.
*/
rpc SetPublicKey(SetPublicKeyRequest) returns (SetPublicKeyResponse) {}
/**
* Refresh the backup, indicating that the backup is still active. Clients
* must periodically upload new backups or perform a refresh. If a backup has
* not been active for 30 days, it may deleted
*/
rpc Refresh(RefreshRequest) returns (RefreshResponse) {}
/**
* Retrieve an upload form that can be used to perform a resumable upload
*/
rpc GetUploadForm(GetUploadFormRequest) returns (GetUploadFormResponse) {}
/**
* Copy and re-encrypt media from the attachments cdn into the backup cdn.
* The original, already encrypted, attachments will be encrypted with the
* provided key material before being copied.
*
* The copy operation is not atomic and responses will be returned as copy
* operations complete with detailed information about the outcome. If an
* error is encountered, not all requests may be reflected in the responses.
*
* On retries, a particular destination media id must not be reused with a
* different source media id or different encryption parameters.
*/
rpc CopyMedia(CopyMediaRequest) returns (stream CopyMediaResponse) {}
/**
* Retrieve a page of media objects stored for this backup-id. A client may
* have previously stored media objects that are no longer referenced in their
* current backup. To reclaim storage space used by these orphaned objects,
* perform a list operation and remove any unreferenced media objects
* via DeleteMedia.
*/
rpc ListMedia(ListMediaRequest) returns (ListMediaResponse) {}
/**
* Delete media objects stored with this backup-id. Streams the locations of
* media items back when the item has successfully been removed.
*/
rpc DeleteMedia(DeleteMediaRequest) returns (stream DeleteMediaResponse) {}
/**
* Delete all backup metadata, objects, and stored public key. To use
* backups again, a public key must be resupplied.
*/
rpc DeleteAll(DeleteAllRequest) returns (DeleteAllResponse) {}
}
message SignedPresentation {
/**
* Presentation of a BackupAuthCredential previously retrieved from
* GetBackupAuthCredentials on the authenticated channel
*/
bytes presentation = 1;
/**
* The presentation signed with the private key corresponding to the public
* key set with SetPublicKey
*/
bytes presentation_signature = 2;
}
message SetPublicKeyRequest {
SignedPresentation signed_presentation = 1;
/**
* The public key, serialized in libsignal's elliptic-curve public key format.
*/
bytes public_key = 2;
}
message SetPublicKeyResponse {}
message GetCdnCredentialsRequest {
SignedPresentation signed_presentation = 1;
int32 cdn = 2;
}
message GetCdnCredentialsResponse {
/**
* Headers to include with requests to the read from the backup CDN. Includes
* time limited read-only credentials.
*/
map<string, string> headers = 1;
}
message GetBackupInfoRequest {
SignedPresentation signed_presentation = 1;
}
message GetBackupInfoResponse {
/**
* The base directory of your backup data on the cdn. The message backup can
* be found in the returned cdn at /backup_dir/backup_name and stored media can
* be found at /backup_dir/media_dir/media_id
*/
string backup_dir = 1;
/**
* The prefix path component for media objects on a cdn. Stored media for a
* media_id can be found at /backup_dir/media_dir/media_id, where the media_id
* is encoded in unpadded url-safe base64.
*/
string media_dir = 2;
/**
* The CDN type where the message backup is stored. Media may be stored
* elsewhere. If absent, no message backup currently exists.
*/
optional int32 cdn = 3;
/**
* The name of the most recent message backup on the cdn. The backup is at
* /backup_dir/backup_name. If absent, no message backup currently exists.
*/
optional string backup_name = 4;
/**
* The amount of space used to store media
*/
uint64 used_space = 5;
}
message RefreshRequest {
SignedPresentation signed_presentation = 1;
}
message RefreshResponse {
SignedPresentation signed_presentation = 1;
}
message GetUploadFormRequest {
SignedPresentation signed_presentation = 1;
message MessagesUploadType {}
message MediaUploadType {}
oneof upload_type {
/**
* Retrieve an upload form that can be used to perform a resumable upload of
* a message backup. The finished upload will be available on the backup cdn.
*/
MessagesUploadType messages = 2;
/**
* Retrieve an upload form for a temporary location that can be used to
* perform a resumable upload of an attachment. After uploading, the
* attachment can be copied into the backup via CopyMedia.
*
* Behaves identically to the account authenticated version at /attachments.
*/
MediaUploadType media = 3;
}
}
message GetUploadFormResponse {
/**
* Indicates the CDN type. 3 indicates resumable uploads using TUS
*/
int32 cdn = 1;
/**
* The location within the specified cdn where the finished upload can be found
*/
string key = 2;
/**
* A map of headers to include with all upload requests. Potentially contains
* time-limited upload credentials
*/
map<string, string> headers = 3;
/**
* The URL to upload to with the appropriate protocol
*/
string signed_upload_location = 4;
}
message CopyMediaItem {
/**
* The attachment cdn of the object to copy into the backup
*/
int32 source_attachment_cdn = 1 [(require.present) = true];
/**
* The attachment key of the object to copy into the backup
*/
string source_key = 2 [(require.nonEmpty) = true];
/**
* The length of the source attachment before the encryption applied by the
* copy operation
*/
uint32 object_length = 3;
/**
* media_id to copy on to the backup CDN
*/
bytes media_id = 4 [(require.exactlySize) = 15];
/**
* A 32-byte key for the MAC
*/
bytes hmac_key = 5 [(require.exactlySize) = 32];
/**
* A 32-byte encryption key for AES
*/
bytes encryption_key = 6 [(require.exactlySize) = 32];
}
message CopyMediaRequest {
SignedPresentation signed_presentation = 1;
/**
* Items to copy
*/
repeated CopyMediaItem items = 2;
}
message CopyMediaResponse {
message SourceNotFound {}
message WrongSourceLength {}
message OutOfSpace {}
message CopySuccess {
/**
* The backup cdn where this media object is stored
*/
int32 cdn = 1;
}
/**
* The 15-byte media_id from the corresponding CopyMediaItem in the request
*/
bytes media_id = 1;
oneof outcome {
/**
* The media item was successfully copied into the backup
*/
CopySuccess success = 2;
/**
* The source object was not found
*/
SourceNotFound source_not_found = 3;
/**
* The provided object length was incorrect
*/
WrongSourceLength wrong_source_length = 4;
/**
* All media capacity has been consumed. Free some space to continue.
*/
OutOfSpace out_of_space = 5;
}
}
message ListMediaRequest {
SignedPresentation signed_presentation = 1;
/**
* A cursor returned by a previous call to ListMedia, absent on the first call
*/
optional string cursor = 2;
/**
* If provided, the maximum number of entries to return in a page
*/
uint32 limit = 3 [(require.range) = {min: 0, max: 10000}];
}
message ListMediaResponse {
message ListEntry {
/**
* The backup cdn where this media object is stored
*/
int32 cdn = 1;
/**
* The media_id of the object
*/
bytes media_id = 2;
/**
* The length of the object in bytes
*/
uint64 length = 3;
}
/**
* A page of media objects stored for this backup ID
*/
repeated ListEntry page = 1;
/**
* The base directory of the backup data on the cdn. The stored media can be
* found at /backup_dir/media_dir/media_id, where the media_id is encoded with
* unpadded url-safe base64.
*/
string backup_dir = 2;
/**
* The prefix path component for the media objects. The stored media for
* media_id can be found at /backup_dir/media_dir/media_id, where the media_id
* is encoded with unpadded url-safe base64.
*/
string media_dir = 3;
/**
* If set, the cursor value to pass to the next list request to continue
* listing. If absent, all objects have been listed
*/
optional string cursor = 4;
}
message DeleteAllRequest {
SignedPresentation signed_presentation = 1;
}
message DeleteAllResponse {}
message DeleteMediaItem {
/**
* The backup cdn where this media object is stored
*/
int32 cdn = 1;
/**
* The media_id of the object to delete
*/
bytes media_id = 2;
}
message DeleteMediaRequest {
SignedPresentation signed_presentation = 1;
repeated DeleteMediaItem items = 2;
}
message DeleteMediaResponse {
/**
* The backup cdn where the media object was stored
*/
int32 cdn = 1;
/**
* The media_id of the object that was successfully deleted
*/
bytes media_id = 3;
}
@@ -101,3 +101,15 @@ enum DeviceCapability {
DEVICE_CAPABILITY_VERSIONED_EXPIRATION_TIMER = 4;
DEVICE_CAPABILITY_STORAGE_SERVICE_RECORD_KEY_ROTATION = 5;
}
message ZkCredential {
/*
* Day on which this credential can be redeemed, in UTC seconds since epoch
*/
int64 redemption_time = 1;
/*
* The ZK credential, using libsignal's serialization
*/
bytes credential = 2;
}
@@ -61,6 +61,7 @@ public class CloudflareTurnCredentialsManagerTest {
List.of("turn:cf.example.com"),
List.of("turn:%s", "turn:%s:80?transport=tcp", "turns:%s:443?transport=tcp"),
TURN_HOSTNAME,
2,
new CircuitBreakerConfiguration(),
httpExecutor,
new RetryConfiguration(),
@@ -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
))
@@ -21,6 +21,7 @@ import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
@@ -34,12 +35,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;
@@ -52,12 +51,10 @@ class CallRoutingControllerTest {
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);
@@ -81,16 +78,15 @@ class CallRoutingControllerTest {
@AfterEach
void tearDown() {
reset(experimentEnrollmentManager, dynamicConfigurationManager, rateLimiters, getCallEndpointLimiter,
turnCallRouter);
reset(experimentEnrollmentManager, 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")
Optional.of(List.of("stun:12.34.56.78")),
Optional.of(List.of("stun:example.domain.org"))
);
when(turnCallRouter.getRoutingFor(
@@ -109,8 +105,8 @@ class CallRoutingControllerTest {
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());
}
}
@@ -120,7 +116,7 @@ class CallRoutingControllerTest {
.thenReturn(true);
when(cloudflareTurnCredentialsManager.retrieveFromCloudflare()).thenReturn(new TurnToken("ABC", "XYZ",
List.of("turn:cloudflare.example.com:3478?transport=udp"), null,
List.of("turn:cloudflare.example.com:3478?transport=udp"), Collections.emptyList(),
"cf.example.com"));
try (Response response = resources.getJerseyTest()
@@ -134,7 +130,7 @@ class CallRoutingControllerTest {
assertThat(token.username()).isEqualTo("ABC");
assertThat(token.password()).isEqualTo("XYZ");
assertThat(token.hostname()).isEqualTo("cf.example.com");
assertThat(token.urlsWithIps()).isNull();
assertThat(token.urlsWithIps()).isEmpty();
assertThat(token.urls()).isEqualTo(List.of("turn:cloudflare.example.com:3478?transport=udp"));
}
}
@@ -143,8 +139,8 @@ class CallRoutingControllerTest {
void testGetTurnEndpointsInvalidIpSuccess() 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(
@@ -163,8 +159,8 @@ class CallRoutingControllerTest {
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());
}
}
@@ -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;
@@ -90,6 +89,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 +104,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 +124,7 @@ class DeviceControllerTest {
accountsManager,
clientPublicKeysManager,
rateLimiters,
persistentTimer,
deviceConfiguration);
@RegisterExtension
@@ -161,6 +163,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 +960,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 +986,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 +1006,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 +1053,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)
@@ -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());
@@ -66,6 +66,7 @@ import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.mappers.ImpossiblePhoneNumberExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.NonNormalizedPhoneNumberExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.ObsoletePhoneNumberFormatExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExceptionMapper;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
@@ -83,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 {
@@ -117,7 +119,9 @@ class VerificationControllerTest {
.addProvider(new RateLimitExceededExceptionMapper())
.addProvider(new ImpossiblePhoneNumberExceptionMapper())
.addProvider(new NonNormalizedPhoneNumberExceptionMapper())
.addProvider(new ObsoletePhoneNumberFormatExceptionMapper())
.addProvider(new RegistrationServiceSenderExceptionMapper())
.addProvider(new TestRemoteAddressFilterProvider("127.0.0.1"))
.setMapper(SystemMapper.jsonMapper())
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
.addResource(
@@ -188,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()
@@ -202,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()
@@ -217,10 +221,10 @@ 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, NUMBER, false, null, null, null,
new RegistrationServiceSession(SESSION_ID, requestedNumber, false, null, null, null,
SESSION_EXPIRATION_SECONDS)));
when(verificationSessionManager.insert(any(), any()))
.thenReturn(CompletableFuture.completedFuture(null));
@@ -234,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));
@@ -245,19 +249,41 @@ class VerificationControllerTest {
// libphonenumber 8.13.50 and on generate new-format numbers for Benin
final String newFormatBeninE164 = PhoneNumberUtil.getInstance()
.format(PhoneNumberUtil.getInstance().getExampleNumber("BJ"), PhoneNumberUtil.PhoneNumberFormat.E164);
final String oldFormatBeninE164 = newFormatBeninE164.replaceFirst("01", "");
return Stream.of(
Arguments.of(oldFormatBeninE164, newFormatBeninE164),
Arguments.of(newFormatBeninE164, newFormatBeninE164),
Arguments.of(NUMBER, NUMBER)
);
}
@Test
void createBeninSessionFailure() {
// libphonenumber 8.13.50 and on generate new-format numbers for Benin
final String newFormatBeninE164 = PhoneNumberUtil.getInstance()
.format(PhoneNumberUtil.getInstance().getExampleNumber("BJ"), PhoneNumberUtil.PhoneNumberFormat.E164);
final String oldFormatBeninE164 = newFormatBeninE164.replaceFirst("01", "");
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any()))
.thenReturn(
CompletableFuture.completedFuture(
new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null,
SESSION_EXPIRATION_SECONDS)));
when(verificationSessionManager.insert(any(), any()))
.thenReturn(CompletableFuture.completedFuture(null));
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/verification/session")
.request()
.header(HttpHeaders.X_FORWARDED_FOR, "127.0.0.1");
try (Response response = request.post(Entity.json(createSessionJson(oldFormatBeninE164, "token", "fcm")))) {
assertEquals(499, response.getStatus());
}
}
@ParameterizedTest
@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,
@@ -291,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,
@@ -313,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,
@@ -0,0 +1,328 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
import com.google.protobuf.ByteString;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import java.time.Clock;
import java.util.Arrays;
import java.util.Iterator;
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.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junitpioneer.jupiter.cartesian.CartesianTest;
import org.mockito.Mock;
import org.signal.chat.backup.BackupsAnonymousGrpc;
import org.signal.chat.backup.CopyMediaItem;
import org.signal.chat.backup.CopyMediaRequest;
import org.signal.chat.backup.CopyMediaResponse;
import org.signal.chat.backup.DeleteMediaItem;
import org.signal.chat.backup.DeleteMediaRequest;
import org.signal.chat.backup.GetBackupInfoRequest;
import org.signal.chat.backup.GetBackupInfoResponse;
import org.signal.chat.backup.GetCdnCredentialsRequest;
import org.signal.chat.backup.GetCdnCredentialsResponse;
import org.signal.chat.backup.GetUploadFormRequest;
import org.signal.chat.backup.GetUploadFormResponse;
import org.signal.chat.backup.ListMediaRequest;
import org.signal.chat.backup.ListMediaResponse;
import org.signal.chat.backup.SetPublicKeyRequest;
import org.signal.chat.backup.SignedPresentation;
import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialPresentation;
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
import org.signal.libsignal.zkgroup.backups.BackupLevel;
import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
import org.whispersystems.textsecuregcm.backup.BackupAuthTestUtil;
import org.whispersystems.textsecuregcm.backup.BackupManager;
import org.whispersystems.textsecuregcm.backup.BackupUploadDescriptor;
import org.whispersystems.textsecuregcm.backup.CopyResult;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import reactor.core.publisher.Flux;
class BackupsAnonymousGrpcServiceTest extends
SimpleBaseGrpcTest<BackupsAnonymousGrpcService, BackupsAnonymousGrpc.BackupsAnonymousBlockingStub> {
private final UUID aci = UUID.randomUUID();
private final byte[] messagesBackupKey = TestRandomUtil.nextBytes(32);
private final BackupAuthTestUtil backupAuthTestUtil = new BackupAuthTestUtil(Clock.systemUTC());
private final BackupAuthCredentialPresentation presentation =
presentation(backupAuthTestUtil, messagesBackupKey, aci);
@Mock
private BackupManager backupManager;
@Override
protected BackupsAnonymousGrpcService createServiceBeforeEachTest() {
return new BackupsAnonymousGrpcService(backupManager);
}
@BeforeEach
void setup() {
when(backupManager.authenticateBackupUser(any(), any()))
.thenReturn(CompletableFuture.completedFuture(
backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID)));
}
@Test
void setPublicKey() {
when(backupManager.setPublicKey(any(), any(), any())).thenReturn(CompletableFuture.completedFuture(null));
assertThatNoException().isThrownBy(() -> unauthenticatedServiceStub().setPublicKey(SetPublicKeyRequest.newBuilder()
.setPublicKey(ByteString.copyFrom(Curve.generateKeyPair().getPublicKey().serialize()))
.setSignedPresentation(signedPresentation(presentation))
.build()));
}
@Test
void setBadPublicKey() {
when(backupManager.setPublicKey(any(), any(), any())).thenReturn(CompletableFuture.completedFuture(null));
assertThatExceptionOfType(StatusRuntimeException.class).isThrownBy(() ->
unauthenticatedServiceStub().setPublicKey(SetPublicKeyRequest.newBuilder()
.setPublicKey(ByteString.copyFromUtf8("aaaaa")) // Invalid public key
.setSignedPresentation(signedPresentation(presentation))
.build()))
.extracting(ex -> ex.getStatus().getCode())
.isEqualTo(Status.Code.INVALID_ARGUMENT);
}
@Test
void setMissingPublicKey() {
assertThatExceptionOfType(StatusRuntimeException.class).isThrownBy(() ->
unauthenticatedServiceStub().setPublicKey(SetPublicKeyRequest.newBuilder()
// Missing public key
.setSignedPresentation(signedPresentation(presentation))
.build()))
.extracting(ex -> ex.getStatus().getCode())
.isEqualTo(Status.Code.INVALID_ARGUMENT);
}
@Test
void putMediaBatchSuccess() {
final byte[][] mediaIds = {TestRandomUtil.nextBytes(15), TestRandomUtil.nextBytes(15)};
when(backupManager.copyToBackup(any(), any()))
.thenReturn(Flux.just(
new CopyResult(CopyResult.Outcome.SUCCESS, mediaIds[0], 1),
new CopyResult(CopyResult.Outcome.SUCCESS, mediaIds[1], 1)));
final CopyMediaRequest request = CopyMediaRequest.newBuilder()
.setSignedPresentation(signedPresentation(presentation))
.addItems(CopyMediaItem.newBuilder()
.setSourceAttachmentCdn(3)
.setSourceKey("abc")
.setObjectLength(100)
.setMediaId(ByteString.copyFrom(mediaIds[0]))
.setHmacKey(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
.setEncryptionKey(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
.build())
.addItems(CopyMediaItem.newBuilder()
.setSourceAttachmentCdn(3)
.setSourceKey("def")
.setObjectLength(200)
.setMediaId(ByteString.copyFrom(mediaIds[1]))
.setHmacKey(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
.setEncryptionKey(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
.build())
.build();
final Iterator<CopyMediaResponse> it = unauthenticatedServiceStub().copyMedia(request);
for (int i = 0; i < 2; i++) {
final CopyMediaResponse response = it.next();
assertThat(response.getSuccess().getCdn()).isEqualTo(1);
assertThat(response.getMediaId().toByteArray()).isEqualTo(mediaIds[i]);
}
assertThat(it.hasNext()).isFalse();
}
@Test
void putMediaBatchPartialFailure() {
// Copy four different mediaIds, with a variety of success/failure outcomes
final byte[][] mediaIds = IntStream.range(0, 4).mapToObj(i -> TestRandomUtil.nextBytes(15)).toArray(byte[][]::new);
final CopyResult.Outcome[] outcomes = new CopyResult.Outcome[]{
CopyResult.Outcome.SUCCESS,
CopyResult.Outcome.SOURCE_NOT_FOUND,
CopyResult.Outcome.SOURCE_WRONG_LENGTH,
CopyResult.Outcome.OUT_OF_QUOTA
};
when(backupManager.copyToBackup(any(), any()))
.thenReturn(Flux.fromStream(IntStream.range(0, 4)
.mapToObj(i -> new CopyResult(
outcomes[i],
mediaIds[i],
outcomes[i] == CopyResult.Outcome.SUCCESS ? 1 : null))));
final CopyMediaRequest request = CopyMediaRequest.newBuilder()
.setSignedPresentation(signedPresentation(presentation))
.addAllItems(Arrays.stream(mediaIds)
.map(mediaId -> CopyMediaItem.newBuilder()
.setSourceAttachmentCdn(3)
.setSourceKey("abc")
.setObjectLength(100)
.setMediaId(ByteString.copyFrom(mediaId))
.setHmacKey(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
.setEncryptionKey(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
.build())
.collect(Collectors.toList()))
.build();
final Iterator<CopyMediaResponse> responses = unauthenticatedServiceStub().copyMedia(request);
// Verify that we get the expected response for each mediaId
for (int i = 0; i < mediaIds.length; i++) {
final CopyMediaResponse response = responses.next();
switch (outcomes[i]) {
case SUCCESS -> assertThat(response.getSuccess().getCdn()).isEqualTo(1);
case SOURCE_WRONG_LENGTH -> assertThat(response.getWrongSourceLength()).isNotNull();
case OUT_OF_QUOTA -> assertThat(response.getOutOfSpace()).isNotNull();
case SOURCE_NOT_FOUND -> assertThat(response.getSourceNotFound()).isNotNull();
}
assertThat(response.getMediaId().toByteArray()).isEqualTo(mediaIds[i]);
}
}
@Test
void getBackupInfo() {
when(backupManager.backupInfo(any())).thenReturn(CompletableFuture.completedFuture(new BackupManager.BackupInfo(
1, "myBackupDir", "myMediaDir", "filename", Optional.empty())));
final GetBackupInfoResponse response = unauthenticatedServiceStub().getBackupInfo(GetBackupInfoRequest.newBuilder()
.setSignedPresentation(signedPresentation(presentation))
.build());
assertThat(response.getBackupDir()).isEqualTo("myBackupDir");
assertThat(response.getBackupName()).isEqualTo("filename");
assertThat(response.getCdn()).isEqualTo(1);
assertThat(response.getUsedSpace()).isEqualTo(0L);
}
@CartesianTest
void list(
@CartesianTest.Values(booleans = {true, false}) final boolean cursorProvided,
@CartesianTest.Values(booleans = {true, false}) final boolean cursorReturned)
throws VerificationFailedException {
final byte[] mediaId = TestRandomUtil.nextBytes(15);
final Optional<String> expectedCursor = cursorProvided ? Optional.of("myCursor") : Optional.empty();
final Optional<String> returnedCursor = cursorReturned ? Optional.of("newCursor") : Optional.empty();
final int limit = 17;
when(backupManager.list(any(), eq(expectedCursor), eq(limit)))
.thenReturn(CompletableFuture.completedFuture(new BackupManager.ListMediaResult(
List.of(new BackupManager.StorageDescriptorWithLength(1, mediaId, 100)),
returnedCursor)));
final ListMediaRequest.Builder request = ListMediaRequest.newBuilder()
.setSignedPresentation(signedPresentation(presentation))
.setLimit(limit);
if (cursorProvided) {
request.setCursor("myCursor");
}
final ListMediaResponse response = unauthenticatedServiceStub().listMedia(request.build());
assertThat(response.getPageCount()).isEqualTo(1);
assertThat(response.getPage(0).getLength()).isEqualTo(100);
assertThat(response.getPage(0).getMediaId().toByteArray()).isEqualTo(mediaId);
assertThat(response.hasCursor() ? response.getCursor() : null).isEqualTo(returnedCursor.orElse(null));
}
@Test
void delete() {
final DeleteMediaRequest request = DeleteMediaRequest.newBuilder()
.setSignedPresentation(signedPresentation(presentation))
.addAllItems(IntStream.range(0, 100).mapToObj(i ->
DeleteMediaItem.newBuilder()
.setCdn(3)
.setMediaId(ByteString.copyFrom(TestRandomUtil.nextBytes(15)))
.build())
.toList()).build();
when(backupManager.deleteMedia(any(), any()))
.thenReturn(Flux.fromStream(request.getItemsList().stream()
.map(m -> new BackupManager.StorageDescriptor(m.getCdn(), m.getMediaId().toByteArray()))));
final AtomicInteger count = new AtomicInteger(0);
unauthenticatedServiceStub().deleteMedia(request).forEachRemaining(i -> count.getAndIncrement());
assertThat(count.get()).isEqualTo(100);
}
@Test
void mediaUploadForm() {
when(backupManager.createTemporaryAttachmentUploadDescriptor(any()))
.thenReturn(CompletableFuture.completedFuture(
new BackupUploadDescriptor(3, "abc", Map.of("k", "v"), "example.org")));
final GetUploadFormRequest request = GetUploadFormRequest.newBuilder()
.setMedia(GetUploadFormRequest.MediaUploadType.getDefaultInstance())
.setSignedPresentation(signedPresentation(presentation))
.build();
final GetUploadFormResponse uploadForm = unauthenticatedServiceStub().getUploadForm(request);
assertThat(uploadForm.getCdn()).isEqualTo(3);
assertThat(uploadForm.getKey()).isEqualTo("abc");
assertThat(uploadForm.getHeadersMap()).containsExactlyEntriesOf(Map.of("k", "v"));
assertThat(uploadForm.getSignedUploadLocation()).isEqualTo("example.org");
// rate limit
when(backupManager.createTemporaryAttachmentUploadDescriptor(any()))
.thenReturn(CompletableFuture.failedFuture(new RateLimitExceededException(null)));
assertThatExceptionOfType(StatusRuntimeException.class)
.isThrownBy(() -> unauthenticatedServiceStub().getUploadForm(request))
.extracting(StatusRuntimeException::getStatus)
.isEqualTo(Status.RESOURCE_EXHAUSTED);
}
@Test
void readAuth() {
when(backupManager.generateReadAuth(any(), eq(3))).thenReturn(Map.of("key", "value"));
final GetCdnCredentialsResponse response = unauthenticatedServiceStub().getCdnCredentials(
GetCdnCredentialsRequest.newBuilder()
.setCdn(3)
.setSignedPresentation(signedPresentation(presentation))
.build());
assertThat(response.getHeadersMap()).containsExactlyEntriesOf(Map.of("key", "value"));
}
private static AuthenticatedBackupUser backupUser(final byte[] backupId, final BackupCredentialType credentialType,
final BackupLevel backupLevel) {
return new AuthenticatedBackupUser(backupId, credentialType, backupLevel, "myBackupDir", "myMediaDir");
}
private static BackupAuthCredentialPresentation presentation(BackupAuthTestUtil backupAuthTestUtil,
byte[] messagesBackupKey, UUID aci) {
try {
return backupAuthTestUtil.getPresentation(BackupLevel.PAID, messagesBackupKey, aci);
} catch (VerificationFailedException e) {
throw new RuntimeException(e);
}
}
private static SignedPresentation signedPresentation(BackupAuthCredentialPresentation presentation) {
return SignedPresentation.newBuilder()
.setPresentation(ByteString.copyFrom(presentation.serialize()))
.setPresentationSignature(ByteString.copyFromUtf8("aaa")).build();
}
}
@@ -0,0 +1,243 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.protobuf.ByteString;
import io.grpc.Status;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junitpioneer.jupiter.cartesian.CartesianTest;
import org.mockito.Mock;
import org.signal.chat.backup.BackupsGrpc;
import org.signal.chat.backup.GetBackupAuthCredentialsRequest;
import org.signal.chat.backup.GetBackupAuthCredentialsResponse;
import org.signal.chat.backup.RedeemReceiptRequest;
import org.signal.chat.backup.SetBackupIdRequest;
import org.signal.chat.common.ZkCredential;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialRequest;
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
import org.signal.libsignal.zkgroup.backups.BackupLevel;
import org.signal.libsignal.zkgroup.receipts.ClientZkReceiptOperations;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredential;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequestContext;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
import org.whispersystems.textsecuregcm.backup.BackupAuthTestUtil;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.util.EnumMapUtil;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
class BackupsGrpcServiceTest extends SimpleBaseGrpcTest<BackupsGrpcService, BackupsGrpc.BackupsBlockingStub> {
private final byte[] messagesBackupKey = TestRandomUtil.nextBytes(32);
private final byte[] mediaBackupKey = TestRandomUtil.nextBytes(32);
private final BackupAuthTestUtil backupAuthTestUtil = new BackupAuthTestUtil(Clock.systemUTC());
final BackupAuthCredentialRequest mediaAuthCredRequest =
backupAuthTestUtil.getRequest(mediaBackupKey, AUTHENTICATED_ACI);
final BackupAuthCredentialRequest messagesAuthCredRequest =
backupAuthTestUtil.getRequest(messagesBackupKey, AUTHENTICATED_ACI);
private final Account account = mock(Account.class);
@Mock
private BackupAuthManager backupAuthManager;
@Mock
private AccountsManager accountsManager;
@Override
protected BackupsGrpcService createServiceBeforeEachTest() {
return new BackupsGrpcService(accountsManager, backupAuthManager);
}
@BeforeEach
void setup() {
when(accountsManager.getByAccountIdentifierAsync(AUTHENTICATED_ACI))
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
}
@Test
void setBackupId() {
when(backupAuthManager.commitBackupId(any(), any(), any())).thenReturn(CompletableFuture.completedFuture(null));
authenticatedServiceStub().setBackupId(
SetBackupIdRequest.newBuilder()
.setMediaBackupAuthCredentialRequest(ByteString.copyFrom(mediaAuthCredRequest.serialize()))
.setMessagesBackupAuthCredentialRequest(ByteString.copyFrom(messagesAuthCredRequest.serialize()))
.build());
verify(backupAuthManager).commitBackupId(account, messagesAuthCredRequest, mediaAuthCredRequest);
}
@Test
void setBackupIdInvalid() {
// missing media credential
GrpcTestUtils.assertStatusException(
Status.INVALID_ARGUMENT, () -> authenticatedServiceStub().setBackupId(SetBackupIdRequest.newBuilder()
.setMessagesBackupAuthCredentialRequest(ByteString.copyFrom(messagesAuthCredRequest.serialize()))
.build())
);
// missing message credential
GrpcTestUtils.assertStatusException(
Status.INVALID_ARGUMENT, () -> authenticatedServiceStub().setBackupId(SetBackupIdRequest.newBuilder()
.setMediaBackupAuthCredentialRequest(ByteString.copyFrom(mediaAuthCredRequest.serialize()))
.build())
);
// missing all credentials
GrpcTestUtils.assertStatusException(
Status.INVALID_ARGUMENT, () -> authenticatedServiceStub().setBackupId(SetBackupIdRequest.newBuilder().build())
);
// invalid serialization
GrpcTestUtils.assertStatusException(
Status.INVALID_ARGUMENT, () -> authenticatedServiceStub().setBackupId(
SetBackupIdRequest.newBuilder()
.setMessagesBackupAuthCredentialRequest(ByteString.fromHex("FF"))
.setMediaBackupAuthCredentialRequest(ByteString.fromHex("FF"))
.build())
);
}
public static Stream<Arguments> setBackupIdException() {
return Stream.of(
Arguments.of(new RateLimitExceededException(null), false, Status.RESOURCE_EXHAUSTED),
Arguments.of(Status.INVALID_ARGUMENT.withDescription("async").asRuntimeException(), false,
Status.INVALID_ARGUMENT),
Arguments.of(Status.INVALID_ARGUMENT.withDescription("sync").asRuntimeException(), true,
Status.INVALID_ARGUMENT)
);
}
@ParameterizedTest
@MethodSource
void setBackupIdException(final Exception ex, final boolean sync, final Status expected) {
if (sync) {
when(backupAuthManager.commitBackupId(any(), any(), any())).thenThrow(ex);
} else {
when(backupAuthManager.commitBackupId(any(), any(), any())).thenReturn(CompletableFuture.failedFuture(ex));
}
GrpcTestUtils.assertStatusException(
expected, () -> authenticatedServiceStub().setBackupId(SetBackupIdRequest.newBuilder()
.setMediaBackupAuthCredentialRequest(ByteString.copyFrom(mediaAuthCredRequest.serialize()))
.setMessagesBackupAuthCredentialRequest(ByteString.copyFrom(messagesAuthCredRequest.serialize()))
.build())
);
}
@Test
void redeemReceipt() throws InvalidInputException, VerificationFailedException {
final ServerSecretParams params = ServerSecretParams.generate();
final ServerZkReceiptOperations serverOps = new ServerZkReceiptOperations(params);
final ClientZkReceiptOperations clientOps = new ClientZkReceiptOperations(params.getPublicParams());
final ReceiptCredentialRequestContext rcrc = clientOps
.createReceiptCredentialRequestContext(new ReceiptSerial(TestRandomUtil.nextBytes(ReceiptSerial.SIZE)));
final ReceiptCredentialResponse rcr = serverOps.issueReceiptCredential(rcrc.getRequest(), 0L, 3L);
final ReceiptCredential receiptCredential = clientOps.receiveReceiptCredential(rcrc, rcr);
final ReceiptCredentialPresentation presentation = clientOps.createReceiptCredentialPresentation(receiptCredential);
when(backupAuthManager.redeemReceipt(any(), any())).thenReturn(CompletableFuture.completedFuture(null));
authenticatedServiceStub().redeemReceipt(RedeemReceiptRequest.newBuilder()
.setPresentation(ByteString.copyFrom(presentation.serialize()))
.build());
verify(backupAuthManager).redeemReceipt(account, presentation);
}
@Test
void getCredentials() {
final Instant start = Instant.now().truncatedTo(ChronoUnit.DAYS);
final Instant end = start.plus(Duration.ofDays(1));
final Map<BackupCredentialType, List<BackupAuthManager.Credential>> expectedCredentialsByType =
EnumMapUtil.toEnumMap(BackupCredentialType.class, credentialType -> backupAuthTestUtil.getCredentials(
BackupLevel.PAID, backupAuthTestUtil.getRequest(messagesBackupKey, AUTHENTICATED_ACI), credentialType,
start, end));
expectedCredentialsByType.forEach((credentialType, expectedCredentials) ->
when(backupAuthManager.getBackupAuthCredentials(any(), eq(credentialType), eq(start), eq(end)))
.thenReturn(CompletableFuture.completedFuture(expectedCredentials)));
final GetBackupAuthCredentialsResponse credentialResponse = authenticatedServiceStub().getBackupAuthCredentials(
GetBackupAuthCredentialsRequest.newBuilder()
.setRedemptionStart(start.getEpochSecond()).setRedemptionStop(end.getEpochSecond())
.build());
expectedCredentialsByType.forEach((credentialType, expectedCredentials) -> {
final Map<Long, ZkCredential> creds = switch (credentialType) {
case MESSAGES -> credentialResponse.getMessageCredentialsMap();
case MEDIA -> credentialResponse.getMediaCredentialsMap();
};
assertThat(creds).hasSize(expectedCredentials.size()).containsKey(start.getEpochSecond());
for (BackupAuthManager.Credential expectedCred : expectedCredentials) {
assertThat(creds)
.extractingByKey(expectedCred.redemptionTime().getEpochSecond())
.isNotNull()
.extracting(ZkCredential::getCredential)
.extracting(ByteString::toByteArray)
.isEqualTo(expectedCred.credential().serialize());
}
});
}
@ParameterizedTest
@CsvSource({
"true, false",
"false, true",
"true, true"
})
void getCredentialsBadInput(final boolean missingStart, final boolean missingEnd) {
final Instant start = Instant.now().truncatedTo(ChronoUnit.DAYS);
final Instant end = start.plus(Duration.ofDays(1));
final GetBackupAuthCredentialsRequest.Builder builder = GetBackupAuthCredentialsRequest.newBuilder();
if (!missingStart) {
builder.setRedemptionStart(start.getEpochSecond());
}
if (!missingEnd) {
builder.setRedemptionStop(end.getEpochSecond());
}
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT,
() -> authenticatedServiceStub().getBackupAuthCredentials(builder.build()));
}
}
@@ -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);
}
}
@@ -35,7 +35,7 @@ public final class GrpcTestUtils {
final BindableService service) {
mockAuthenticationInterceptor.setAuthenticatedDevice(authenticatedAci, authenticatedDeviceId);
extension.getServiceRegistry()
.addService(ServerInterceptors.intercept(service, mockRequestAttributesInterceptor, mockAuthenticationInterceptor, new ErrorMappingInterceptor()));
.addService(ServerInterceptors.intercept(service, new ValidatingInterceptor(), mockRequestAttributesInterceptor, mockAuthenticationInterceptor, new ErrorMappingInterceptor()));
}
public static void setupUnauthenticatedExtension(
@@ -43,7 +43,7 @@ public final class GrpcTestUtils {
final MockRequestAttributesInterceptor mockRequestAttributesInterceptor,
final BindableService service) {
extension.getServiceRegistry()
.addService(ServerInterceptors.intercept(service, mockRequestAttributesInterceptor, new ErrorMappingInterceptor()));
.addService(ServerInterceptors.intercept(service, new ValidatingInterceptor(), mockRequestAttributesInterceptor, new ErrorMappingInterceptor()));
}
public static void assertStatusException(final Status expected, final Executable serviceCall) {
@@ -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();
}
}
@@ -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",
@@ -0,0 +1,100 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import io.micrometer.core.instrument.Timer;
import java.time.Duration;
import java.time.Instant;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
import org.whispersystems.textsecuregcm.util.TestClock;
class PersistentTimerTest {
private static final String NAMESPACE = "namespace";
private static final String KEY = "key";
@RegisterExtension
private static final RedisClusterExtension CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
private TestClock clock;
private PersistentTimer timer;
@BeforeEach
public void setup() {
clock = TestClock.pinned(Instant.ofEpochSecond(10));
timer = new PersistentTimer(CLUSTER_EXTENSION.getRedisCluster(), clock);
}
@Test
public void testStop() {
PersistentTimer.Sample sample = timer.start(NAMESPACE, KEY).join();
final String redisKey = timer.redisKey(NAMESPACE, KEY);
final String actualStartString = CLUSTER_EXTENSION.getRedisCluster()
.withCluster(conn -> conn.sync().get(redisKey));
final Instant actualStart = Instant.ofEpochSecond(Long.parseLong(actualStartString));
assertThat(actualStart).isEqualTo(clock.instant());
final long ttl = CLUSTER_EXTENSION.getRedisCluster()
.withCluster(conn -> conn.sync().ttl(redisKey));
assertThat(ttl).isBetween(0L, PersistentTimer.TIMER_TTL.getSeconds());
Timer mockTimer = mock(Timer.class);
clock.pin(clock.instant().plus(Duration.ofSeconds(5)));
sample.stop(mockTimer).join();
verify(mockTimer).record(Duration.ofSeconds(5));
final String afterDeletion = CLUSTER_EXTENSION.getRedisCluster()
.withCluster(conn -> conn.sync().get(redisKey));
assertThat(afterDeletion).isNull();
}
@Test
public void testNamespace() {
Timer mockTimer = mock(Timer.class);
clock.pin(Instant.ofEpochSecond(10));
PersistentTimer.Sample timer1 = timer.start("n1", KEY).join();
clock.pin(Instant.ofEpochSecond(20));
PersistentTimer.Sample timer2 = timer.start("n2", KEY).join();
clock.pin(Instant.ofEpochSecond(30));
timer2.stop(mockTimer).join();
verify(mockTimer).record(Duration.ofSeconds(10));
timer1.stop(mockTimer).join();
verify(mockTimer).record(Duration.ofSeconds(20));
}
@Test
public void testMultipleStart() {
Timer mockTimer = mock(Timer.class);
clock.pin(Instant.ofEpochSecond(10));
PersistentTimer.Sample timer1 = timer.start(NAMESPACE, KEY).join();
clock.pin(Instant.ofEpochSecond(11));
PersistentTimer.Sample timer2 = timer.start(NAMESPACE, KEY).join();
clock.pin(Instant.ofEpochSecond(12));
PersistentTimer.Sample timer3 = timer.start(NAMESPACE, KEY).join();
clock.pin(Instant.ofEpochSecond(20));
timer2.stop(mockTimer).join();
verify(mockTimer).record(Duration.ofSeconds(10));
assertThatNoException().isThrownBy(() -> timer1.stop(mockTimer).join());
assertThatNoException().isThrownBy(() -> timer3.stop(mockTimer).join());
}
}
@@ -29,6 +29,7 @@ class ReportMessageDynamoDbTest {
void setUp() {
this.reportMessageDynamoDb = new ReportMessageDynamoDb(
DYNAMO_DB_EXTENSION.getDynamoDbClient(),
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
Tables.REPORT_MESSAGES.tableName(),
Duration.ofDays(1));
}
@@ -44,8 +45,8 @@ class ReportMessageDynamoDbTest {
() -> assertFalse(reportMessageDynamoDb.remove(hash2))
);
reportMessageDynamoDb.store(hash1);
reportMessageDynamoDb.store(hash2);
reportMessageDynamoDb.store(hash1).join();
reportMessageDynamoDb.store(hash2).join();
assertAll("both hashes should be found",
() -> assertTrue(reportMessageDynamoDb.remove(hash1)),
@@ -18,6 +18,7 @@ import static org.mockito.Mockito.when;
import java.time.Duration;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
@@ -68,8 +69,8 @@ class ReportMessageManagerTest {
verify(reportMessageDynamoDb).store(any());
doThrow(RuntimeException.class)
.when(reportMessageDynamoDb).store(any());
when(reportMessageDynamoDb.store(any()))
.thenReturn(CompletableFuture.failedFuture(new RuntimeException()));
assertDoesNotThrow(() -> reportMessageManager.store(sourceAci.toString(), messageGuid));
}
@@ -0,0 +1,92 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.tests.util;
import java.nio.ByteBuffer;
import java.util.List;
public class MultiRecipientMessageHelper {
private MultiRecipientMessageHelper() {
}
public static byte[] generateMultiRecipientMessage(final List<TestRecipient> recipients) {
return generateMultiRecipientMessage(recipients, 32);
}
public static byte[] generateMultiRecipientMessage(final List<TestRecipient> recipients, final int sharedPayloadSize) {
if (sharedPayloadSize < 32) {
throw new IllegalArgumentException("Shared payload size must be at least 32 bytes");
}
final ByteBuffer buffer = ByteBuffer.allocate(payloadSize(recipients, sharedPayloadSize));
// first write the header
buffer.put((byte) 0x23); // version byte
// count varint
writeVarint(buffer, recipients.size());
recipients.forEach(recipient -> {
buffer.put(recipient.uuid().toFixedWidthByteArray());
assert recipient.deviceIds().length == recipient.registrationIds().length;
for (int i = 0; i < recipient.deviceIds().length; i++) {
final int hasMore = i == recipient.deviceIds().length - 1 ? 0 : 0x8000;
buffer.put(recipient.deviceIds()[i]); // device id (1 byte)
buffer.putShort((short) (recipient.registrationIds()[i] | hasMore)); // registration id (2 bytes)
}
buffer.put(recipient.perRecipientKeyMaterial()); // key material (48 bytes)
});
// now write the actual message body (empty for now)
writeVarint(buffer, sharedPayloadSize);
buffer.put(new byte[sharedPayloadSize]);
return buffer.array();
}
private static void writeVarint(final ByteBuffer buffer, long n) {
if (n < 0) {
throw new IllegalArgumentException();
}
while (n >= 0x80) {
buffer.put ((byte) (n & 0x7F | 0x80));
n >>= 7;
}
buffer.put((byte) (n & 0x7F));
}
private static int payloadSize(final List<TestRecipient> recipients, final int sharedPayloadSize) {
final int fixedBytesPerRecipient = 17 // Service identifier length
+ 48; // Per-recipient key material
final int bytesForDevices = 3 * recipients.stream()
.mapToInt(recipient -> recipient.deviceIds().length)
.sum();
return 1 // Version byte
+ varintLength(recipients.size())
+ (recipients.size() * fixedBytesPerRecipient)
+ bytesForDevices
+ varintLength(sharedPayloadSize)
+ sharedPayloadSize;
}
private static int varintLength(long n) {
int length = 0;
while (n >= 0x80) {
length += 1;
n >>= 7;
}
return length + 1;
}
}
@@ -0,0 +1,22 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.tests.util;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
public record TestRecipient(ServiceIdentifier uuid,
byte[] deviceIds,
int[] registrationIds,
byte[] perRecipientKeyMaterial) {
public TestRecipient(ServiceIdentifier uuid,
byte deviceId,
int registrationId,
byte[] perRecipientKeyMaterial) {
this(uuid, new byte[]{deviceId}, new int[]{registrationId}, perRecipientKeyMaterial);
}
}
@@ -7,15 +7,17 @@ package org.whispersystems.textsecuregcm.util;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import java.util.stream.Stream;
import com.google.i18n.phonenumbers.Phonenumber;
import javax.annotation.Nullable;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.CsvSource;
@@ -93,9 +95,13 @@ class UtilTest {
@ParameterizedTest
@MethodSource
void normalizeBeninPhoneNumber(final Phonenumber.PhoneNumber beninNumber, final Phonenumber.PhoneNumber expectedBeninNumber)
throws NumberParseException {
assertTrue(expectedBeninNumber.exactlySameAs(Util.canonicalizePhoneNumber(beninNumber)));
void normalizeBeninPhoneNumber(final Phonenumber.PhoneNumber beninNumber, final Phonenumber.PhoneNumber expectedBeninNumber, @Nullable Class<? extends Throwable> exception)
throws Exception {
if (exception == null) {
assertTrue(expectedBeninNumber.exactlySameAs(Util.canonicalizePhoneNumber(beninNumber)));
} else {
assertThrows(exception, () -> Util.canonicalizePhoneNumber(beninNumber));
}
}
private static Stream<Arguments> normalizeBeninPhoneNumber() throws NumberParseException {
@@ -103,9 +109,9 @@ class UtilTest {
final Phonenumber.PhoneNumber newFormatBeninPhoneNumber = PhoneNumberUtil.getInstance().parse(NEW_FORMAT_BENIN_E164_STRING, null);
final Phonenumber.PhoneNumber usPhoneNumber = PhoneNumberUtil.getInstance().getExampleNumber("US");
return Stream.of(
Arguments.of(newFormatBeninPhoneNumber, newFormatBeninPhoneNumber),
Arguments.of(oldFormatBeninPhoneNumber, newFormatBeninPhoneNumber),
Arguments.of(usPhoneNumber, usPhoneNumber)
Arguments.of(newFormatBeninPhoneNumber, newFormatBeninPhoneNumber, null),
Arguments.of(oldFormatBeninPhoneNumber, null, ObsoletePhoneNumberFormatException.class),
Arguments.of(usPhoneNumber, usPhoneNumber, null)
);
}
}
@@ -13,8 +13,6 @@ import static org.mockito.Mockito.when;
import com.google.common.net.HttpHeaders;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import io.dropwizard.auth.basic.BasicCredentials;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;
import javax.annotation.Nullable;
@@ -64,11 +62,9 @@ class WebSocketAccountAuthenticatorTest {
@MethodSource
void testAuthenticate(
@Nullable final String authorizationHeaderValue,
final Map<String, List<String>> upgradeRequestParameters,
final boolean expectAccount,
final boolean expectInvalid) throws Exception {
when(upgradeRequest.getParameterMap()).thenReturn(upgradeRequestParameters);
if (authorizationHeaderValue != null) {
when(upgradeRequest.getHeader(eq(HttpHeaders.AUTHORIZATION))).thenReturn(authorizationHeaderValue);
}
@@ -84,29 +80,16 @@ class WebSocketAccountAuthenticatorTest {
}
private static Stream<Arguments> testAuthenticate() {
final Map<String, List<String>> paramsMapWithValidAuth =
Map.of("login", List.of(VALID_USER), "password", List.of(VALID_PASSWORD));
final Map<String, List<String>> paramsMapWithInvalidAuth =
Map.of("login", List.of(INVALID_USER), "password", List.of(INVALID_PASSWORD));
final String headerWithValidAuth =
HeaderUtils.basicAuthHeader(VALID_USER, VALID_PASSWORD);
final String headerWithInvalidAuth =
HeaderUtils.basicAuthHeader(INVALID_USER, INVALID_PASSWORD);
return Stream.of(
// if `Authorization` header is present, outcome should not depend on the value of query parameters
Arguments.of(headerWithValidAuth, Map.of(), true, false),
Arguments.of(headerWithInvalidAuth, Map.of(), false, true),
Arguments.of("invalid header value", Map.of(), false, true),
Arguments.of(headerWithValidAuth, paramsMapWithValidAuth, true, false),
Arguments.of(headerWithInvalidAuth, paramsMapWithValidAuth, false, true),
Arguments.of("invalid header value", paramsMapWithValidAuth, false, true),
Arguments.of(headerWithValidAuth, paramsMapWithInvalidAuth, true, false),
Arguments.of(headerWithInvalidAuth, paramsMapWithInvalidAuth, false, true),
Arguments.of("invalid header value", paramsMapWithInvalidAuth, false, true),
// if `Authorization` header is not set, outcome should match the query params based auth
Arguments.of(null, paramsMapWithValidAuth, true, false),
Arguments.of(null, paramsMapWithInvalidAuth, false, true),
Arguments.of(null, Map.of(), false, false)
Arguments.of(headerWithValidAuth, true, false),
Arguments.of(headerWithInvalidAuth, false, true),
Arguments.of("invalid header value", false, true),
// if `Authorization` header is not set, we expect no account and anonymous credentials
Arguments.of(null, false, false)
);
}
}
@@ -132,7 +132,7 @@ class WebSocketConnectionIntegrationTest {
void testProcessStoredMessages(final int persistedMessageCount, final int cachedMessageCount) {
final WebSocketConnection webSocketConnection = new WebSocketConnection(
mock(ReceiptSender.class),
new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager, sharedExecutorService),
new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager, sharedExecutorService, Clock.systemUTC()),
new MessageMetrics(),
mock(PushNotificationManager.class),
mock(PushNotificationScheduler.class),
@@ -164,7 +164,7 @@ class WebSocketConnectionIntegrationTest {
final UUID messageGuid = UUID.randomUUID();
final MessageProtos.Envelope envelope = generateRandomMessage(messageGuid);
messagesCache.insert(messageGuid, account.getUuid(), device.getId(), envelope);
messagesCache.insert(messageGuid, account.getUuid(), device.getId(), envelope).join();
expectedMessages.add(envelope);
}
@@ -220,7 +220,7 @@ class WebSocketConnectionIntegrationTest {
void testProcessStoredMessagesClientClosed() {
final WebSocketConnection webSocketConnection = new WebSocketConnection(
mock(ReceiptSender.class),
new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager, sharedExecutorService),
new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager, sharedExecutorService, Clock.systemUTC()),
new MessageMetrics(),
mock(PushNotificationManager.class),
mock(PushNotificationScheduler.class),
@@ -253,7 +253,7 @@ class WebSocketConnectionIntegrationTest {
for (int i = 0; i < cachedMessageCount; i++) {
final UUID messageGuid = UUID.randomUUID();
final MessageProtos.Envelope envelope = generateRandomMessage(messageGuid);
messagesCache.insert(messageGuid, account.getUuid(), device.getId(), envelope);
messagesCache.insert(messageGuid, account.getUuid(), device.getId(), envelope).join();
expectedMessages.add(envelope);
}
@@ -289,7 +289,7 @@ class WebSocketConnectionIntegrationTest {
void testProcessStoredMessagesSendFutureTimeout() {
final WebSocketConnection webSocketConnection = new WebSocketConnection(
mock(ReceiptSender.class),
new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager, sharedExecutorService),
new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager, sharedExecutorService, Clock.systemUTC()),
new MessageMetrics(),
mock(PushNotificationManager.class),
mock(PushNotificationScheduler.class),
@@ -323,7 +323,7 @@ class WebSocketConnectionIntegrationTest {
for (int i = 0; i < cachedMessageCount; i++) {
final UUID messageGuid = UUID.randomUUID();
final MessageProtos.Envelope envelope = generateRandomMessage(messageGuid);
messagesCache.insert(messageGuid, account.getUuid(), device.getId(), envelope);
messagesCache.insert(messageGuid, account.getUuid(), device.getId(), envelope).join();
expectedMessages.add(envelope);
}
@@ -0,0 +1,272 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.workers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
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.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
public class IdleWakeupEligibilityCheckerTest {
private static final Instant CURRENT_TIME = Instant.now();
private final Clock clock = Clock.fixed(CURRENT_TIME, ZoneId.systemDefault());
private MessagesManager messagesManager;
private IdleWakeupEligibilityChecker idleChecker;
@BeforeEach
void setup() {
messagesManager = mock(MessagesManager.class);
idleChecker = new IdleWakeupEligibilityChecker(clock, messagesManager);
}
@ParameterizedTest
@MethodSource
void isDeviceEligible(final Account account,
final Device device,
final boolean mayHaveMessages,
final boolean mayHaveUrgentMessages,
final boolean expectEligible) {
when(messagesManager.mayHavePersistedMessages(account.getIdentifier(IdentityType.ACI), device))
.thenReturn(CompletableFuture.completedFuture(mayHaveMessages));
when(messagesManager.mayHaveUrgentPersistedMessages(account.getIdentifier(IdentityType.ACI), device))
.thenReturn(CompletableFuture.completedFuture(mayHaveUrgentMessages));
assertEquals(expectEligible, idleChecker.isDeviceEligible(account, device).join());
}
private static List<Arguments> isDeviceEligible() {
final List<Arguments> arguments = new ArrayList<>();
final Account account = mock(Account.class);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(UUID.randomUUID());
when(account.getNumber()).thenReturn(PhoneNumberUtil.getInstance().format(
PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164));
{
// Long-idle device with push token and messages
final Device device = mock(Device.class);
when(device.getApnId()).thenReturn("apns-token");
when(device.getLastSeen()).thenReturn(
CURRENT_TIME.minus(IdleWakeupEligibilityChecker.MIN_LONG_IDLE_DURATION).toEpochMilli());
arguments.add(Arguments.of(account, device, true, true, false));
}
{
// Long-idle device missing push token, but with messages
final Device device = mock(Device.class);
when(device.getLastSeen()).thenReturn(
CURRENT_TIME.minus(IdleWakeupEligibilityChecker.MIN_LONG_IDLE_DURATION).toEpochMilli());
arguments.add(Arguments.of(account, device, true, true, false));
}
{
// Long-idle device missing push token and messages
final Device device = mock(Device.class);
when(device.getLastSeen()).thenReturn(
CURRENT_TIME.minus(IdleWakeupEligibilityChecker.MIN_LONG_IDLE_DURATION).toEpochMilli());
arguments.add(Arguments.of(account, device, false, false, false));
}
{
// Long-idle device with push token, but no messages
final Device device = mock(Device.class);
when(device.getLastSeen()).thenReturn(
CURRENT_TIME.minus(IdleWakeupEligibilityChecker.MIN_LONG_IDLE_DURATION).toEpochMilli());
when(device.getApnId()).thenReturn("apns-token");
arguments.add(Arguments.of(account, device, false, false, true));
}
{
// Short-idle device with push token and urgent messages
final Device device = mock(Device.class);
when(device.getApnId()).thenReturn("apns-token");
when(device.getLastSeen()).thenReturn(
CURRENT_TIME.minus(IdleWakeupEligibilityChecker.MIN_SHORT_IDLE_DURATION).toEpochMilli());
arguments.add(Arguments.of(account, device, true, true, true));
}
{
// Short-idle device with push token and only non-urgent messages
final Device device = mock(Device.class);
when(device.getApnId()).thenReturn("apns-token");
when(device.getLastSeen()).thenReturn(
CURRENT_TIME.minus(IdleWakeupEligibilityChecker.MIN_SHORT_IDLE_DURATION).toEpochMilli());
arguments.add(Arguments.of(account, device, true, false, false));
}
{
// Short-idle device missing push token, but with urgent messages
final Device device = mock(Device.class);
when(device.getLastSeen()).thenReturn(
CURRENT_TIME.minus(IdleWakeupEligibilityChecker.MIN_SHORT_IDLE_DURATION).toEpochMilli());
arguments.add(Arguments.of(account, device, true, true, false));
}
{
// Short-idle device missing push token and messages
final Device device = mock(Device.class);
when(device.getLastSeen()).thenReturn(
CURRENT_TIME.minus(IdleWakeupEligibilityChecker.MIN_SHORT_IDLE_DURATION).toEpochMilli());
arguments.add(Arguments.of(account, device, false, false, false));
}
{
// Short-idle device with push token, but no messages
final Device device = mock(Device.class);
when(device.getLastSeen()).thenReturn(
CURRENT_TIME.minus(IdleWakeupEligibilityChecker.MIN_SHORT_IDLE_DURATION).toEpochMilli());
when(device.getApnId()).thenReturn("apns-token");
arguments.add(Arguments.of(account, device, false, false, false));
}
{
// Active device with push token and urgent messages
final Device device = mock(Device.class);
when(device.getLastSeen()).thenReturn(CURRENT_TIME.toEpochMilli());
when(device.getApnId()).thenReturn("apns-token");
arguments.add(Arguments.of(account, device, true, true, false));
}
{
// Active device missing push token, but with urgent messages
final Device device = mock(Device.class);
when(device.getLastSeen()).thenReturn(CURRENT_TIME.toEpochMilli());
arguments.add(Arguments.of(account, device, true, true, false));
}
{
// Active device missing push token and messages
final Device device = mock(Device.class);
when(device.getLastSeen()).thenReturn(CURRENT_TIME.toEpochMilli());
arguments.add(Arguments.of(account, device, false, false, false));
}
{
// Active device with push token, but no messages
final Device device = mock(Device.class);
when(device.getLastSeen()).thenReturn(CURRENT_TIME.toEpochMilli());
when(device.getApnId()).thenReturn("apns-token");
arguments.add(Arguments.of(account, device, false, false, false));
}
return arguments;
}
@ParameterizedTest
@MethodSource
void isShortIdle(final Duration idleDuration, final boolean expectIdle) {
final Instant currentTime = Instant.now();
final Clock clock = Clock.fixed(currentTime, ZoneId.systemDefault());
final Device device = mock(Device.class);
when(device.getLastSeen()).thenReturn(currentTime.minus(idleDuration).toEpochMilli());
assertEquals(expectIdle, IdleWakeupEligibilityChecker.isShortIdle(device, clock));
}
private static List<Arguments> isShortIdle() {
return List.of(
Arguments.of(IdleWakeupEligibilityChecker.MIN_SHORT_IDLE_DURATION, true),
Arguments.of(IdleWakeupEligibilityChecker.MIN_SHORT_IDLE_DURATION.plusMillis(1), true),
Arguments.of(IdleWakeupEligibilityChecker.MIN_SHORT_IDLE_DURATION.minusMillis(1), false),
Arguments.of(IdleWakeupEligibilityChecker.MAX_SHORT_IDLE_DURATION, false),
Arguments.of(IdleWakeupEligibilityChecker.MAX_SHORT_IDLE_DURATION.plusMillis(1), false),
Arguments.of(IdleWakeupEligibilityChecker.MAX_SHORT_IDLE_DURATION.minusMillis(1), true)
);
}
@ParameterizedTest
@MethodSource
void isLongIdle(final Duration idleDuration, final boolean expectIdle) {
final Instant currentTime = Instant.now();
final Clock clock = Clock.fixed(currentTime, ZoneId.systemDefault());
final Device device = mock(Device.class);
when(device.getLastSeen()).thenReturn(currentTime.minus(idleDuration).toEpochMilli());
assertEquals(expectIdle, IdleWakeupEligibilityChecker.isLongIdle(device, clock));
}
private static List<Arguments> isLongIdle() {
return List.of(
Arguments.of(IdleWakeupEligibilityChecker.MIN_LONG_IDLE_DURATION, true),
Arguments.of(IdleWakeupEligibilityChecker.MIN_LONG_IDLE_DURATION.plusMillis(1), true),
Arguments.of(IdleWakeupEligibilityChecker.MIN_LONG_IDLE_DURATION.minusMillis(1), false),
Arguments.of(IdleWakeupEligibilityChecker.MAX_LONG_IDLE_DURATION, false),
Arguments.of(IdleWakeupEligibilityChecker.MAX_LONG_IDLE_DURATION.plusMillis(1), false),
Arguments.of(IdleWakeupEligibilityChecker.MAX_LONG_IDLE_DURATION.minusMillis(1), true)
);
}
@ParameterizedTest
@MethodSource
void hasPushToken(final Device device, final boolean expectHasPushToken) {
assertEquals(expectHasPushToken, IdleWakeupEligibilityChecker.hasPushToken(device));
}
private static List<Arguments> hasPushToken() {
final List<Arguments> arguments = new ArrayList<>();
{
// No token at all
final Device device = mock(Device.class);
arguments.add(Arguments.of(device, false));
}
{
// FCM token
final Device device = mock(Device.class);
when(device.getGcmId()).thenReturn("fcm-token");
arguments.add(Arguments.of(device, true));
}
{
// APNs token
final Device device = mock(Device.class);
when(device.getApnId()).thenReturn("apns-token");
arguments.add(Arguments.of(device, true));
}
return arguments;
}
}
Loaded 100 of 104 files, more files were not shown because too many files have changed in this diff. Show more