Compare commits

..
Author SHA1 Message Date
Jon Chambers 9c5877aa31 Resolve warnings/accept suggestions throughout AttachmentControllerV4Test 2024-10-21 14:26:28 -04:00
Jon Chambers bda4788a34 Retire AttachmentControllerV2 2024-10-21 14:26:28 -04:00
Jon Chambers 5abfef50fc Avoid repeated constants, standardize test assertions, and add links to docs for PolicySigner 2024-10-21 14:26:04 -04:00
Jon Chambers e3ee5c1f2e Use multiline strings in PostPolicyGenerator 2024-10-21 14:26:04 -04:00
Jon Chambers e6eb702a88 Remove a couple unused imports/loggers from SubscriptionController 2024-10-21 13:18:00 -05:00
Jon Chambers 1447819198 Remove deprecated aci field from batch identity check elements 2024-10-21 13:17:52 -05:00
Jon Chambers adf5795dff Remove unused members in ProfileController 2024-10-21 13:17:52 -05:00
Chris Eager 584fd06b88 Add metric for closed connection age to KeepAliveController 2024-10-21 13:17:21 -05:00
Chris Eager 1faa1a5abc Remove obsolete identity key null-check from /v1/certificate/delivery 2024-10-21 13:17:05 -05:00
Chris Eager b5db8eba06 Remove unnecessary socket.setReuseAddress() in test extensions 2024-10-21 13:16:57 -05:00
Chris Eager c6843c1eae Update to embedded-redis 0.9.1 2024-10-21 13:16:45 -05:00
Ameya Lokare 93b7fd589e Update to the latest version of the spam filter 2024-10-17 09:57:32 -07:00
Jon Chambers eb80305f87 Retire AttachmentControllerV3 2024-10-17 12:48:01 -04:00
Jon Chambers 865e3c5bde Convert AccountBadge to a record 2024-10-17 12:47:50 -04:00
Chris Eager c2270e57df Reduce log level for existing pending presence 2024-10-17 11:47:18 -05:00
Ameya Lokare d48c031548 Pass in destination service identifier to spam filter 2024-10-17 09:11:35 -07:00
Chris Eager 830a07012b Subscribe to remote presence changes before setting the key 2024-10-15 16:54:52 -05:00
Chris Eager 46227295ff Add test for concurrent connections in ClientPresenceManager 2024-10-15 16:54:52 -05:00
Jon Chambers 73fb1fc2ed Add API endpoints for waiting for transfer archives 2024-10-15 12:13:47 -04:00
Jon Chambers 7ff48155d6 Add plumbing for a "wait for transfer archive" system 2024-10-15 12:13:47 -04:00
Jon Chambers 0adaa331a1 Extract RemoteAttachment to a top-level entity 2024-10-15 12:13:47 -04:00
Jon Chambers 30ec06ca76 Fix an incorrect response schema annotation 2024-10-15 12:13:47 -04:00
Jon Chambers 9b5c6e538b Convert DeviceResponse to a record and rename to LinkDeviceResponse 2024-10-15 12:13:29 -04:00
Jon Chambers 240a406964 Introduce EnumMapUtil 2024-10-10 13:29:20 -07:00
Jon Chambers 38d25f9a9b Resolve warnings and accept suggestions throughout DeviceControllerTest 2024-10-10 13:29:05 -07:00
Chris Eager 7b1b6fa1cf Update KeyTransparencyService.proto with MonitorKey.commitment_index 2024-10-10 10:12:21 -04:00
Chris Eager a3d9af132f Use Mono#transformDeferred when applicable 2024-10-10 10:12:04 -04:00
Chris Eager 5d8b566a27 Remove unnecessary MessagesManager#clear with account’s PNI 2024-10-10 10:12:04 -04:00
Jon Chambers 8c30a359e7 Add API endpoints for waiting for newly-linked devices 2024-10-10 10:11:32 -04:00
Jon Chambers 087c2b61ee Update to the latest version of the spam filter 2024-10-09 09:37:07 -04:00
Jon Chambers a9117010f9 Introduce FaultTolerantRedisClient 2024-10-09 09:22:10 -04:00
Ravi Khadiwala 9d980f36b0 Allow experiments to exclude by ACI 2024-10-08 15:02:58 -05:00
Katherine 93515e5a0f Retire paymentActivation capability 2024-10-08 16:01:09 -04:00
Jonathan Klabunde Tomer d550c69f7f Enforce per-IP rate limits 2024-10-07 16:57:29 -05:00
adel-signal 087e192fac Update CallRoutingController to use e164, add UUID to e164 experiments 2024-10-07 16:56:45 -05:00
Jon Chambers 63e45563ec Discard the Redis-backed "used token" system 2024-10-07 17:06:08 -04:00
Jon Chambers 961d6d0a5c Update to the latest version of the spam filter 2024-10-07 16:31:51 -04:00
Jon Chambers f7aacefc40 Manage device linking tokens transactionally 2024-10-07 16:26:11 -04:00
Ravi Khadiwala 42e920cd5c Add appstore subscriptions endpoint 2024-10-04 16:06:15 -05:00
ravi-signal 02ff3f2ff4 Add AppleAppStoreManager 2024-10-04 15:55:07 -05:00
Katherine ca2845bcb0 Update key transparency gRPC client 2024-10-04 16:43:30 -04:00
Ravi Khadiwala 80cd5d9ccc Increase message cache TTL to 46 days 2024-10-02 14:05:40 -05:00
Ravi Khadiwala 0eb7db8de5 Increase the linked device idle timeout to 45 days 2024-10-02 14:05:40 -05:00
Jon Chambers 100955a7db Migrate WebSocket duration instrumentation to OpenWebSocketCounter 2024-10-02 14:02:03 -05:00
Chris Eager 68814813c3 Add timestamp header to all responses 2024-10-02 14:01:19 -05:00
Jon Chambers 39590f1b28 Update to the latest version of the spam filter 2024-10-01 14:27:06 -04:00
Jon Chambers 92698efd39 Remove machinery for setting/storing APNs VOIP tokens 2024-10-01 14:17:39 -04:00
Jon Chambers b693cb98d0 Remove recurring background VOIP notification machinery 2024-10-01 14:17:39 -04:00
Jon Chambers 3ed142d0a9 Introduce OpenWebSocketCounter 2024-10-01 14:17:17 -04:00
Jon Chambers 581e61a85b Count open provisioning WebSockets 2024-10-01 14:17:17 -04:00
Jon Chambers 764b200289 Clarify open websocket gauge name 2024-10-01 14:17:17 -04:00
Jon Chambers 26503dffdf Use a consistent provisioning address 2024-10-01 13:34:37 -04:00
Jon Chambers b284e95394 Clarify ProvisioningAddress field naming 2024-10-01 12:59:58 -04:00
Jon Chambers b2211de8d8 Retire ProvisioningAddress and WebsocketAddress 2024-10-01 12:59:58 -04:00
Ameya Lokare 1bb0eb0e70 Integer comparison of captcha scores 2024-10-01 08:42:12 -07:00
Jon Chambers 0a1161048f Document ProvisioningController and ProvisioningConnectListener 2024-10-01 11:40:40 -04:00
Ameya Lokare 7a6ce00fed Add senderType tag to sendMessageLatency timer
This will allow us to differentiate between sealed vs unsealed sends
latency
2024-09-27 17:35:20 -04:00
Jon Chambers c0aa9ced8d Temporarily disable AWS SDK instrumentation 2024-09-27 17:34:46 -04:00
Jon Chambers 6b36df3f8f Remove unused imports/loggers 2024-09-27 17:34:46 -04:00
Jon Chambers df3caeb04a Expand the scope of the "notify idle devices" job to cover short-idle devices WITH messages 2024-09-27 16:30:51 -04:00
Jon Chambers 0e267509da Add a method for checking for persisted urgent messages 2024-09-27 16:30:51 -04:00
Jon Chambers bbe41278ed Drop an unused hasCachedMessages method 2024-09-27 16:30:51 -04:00
Jon Chambers d91a6b0c38 Retire the "notify idle devices with messages" experiment 2024-09-27 16:30:51 -04:00
Jon Chambers 694a93db6d Explicitly look for sha256sum inputs via stdin 2024-09-27 09:39:19 -04:00
Ameya Lokare 2f2dec87b1 Update to the latest version of the spam filter 2024-09-26 13:03:05 -07:00
Ameya Lokare 098288c290 Update to the latest version of the spam filter 2024-09-26 12:56:09 -07:00
Chris Eager ab2e6bb9a3 Use Mono.share() for mrmMessageMono 2024-09-26 14:48:06 -05:00
Chris Eager 513f19370a Add Experiment#compareMonoResult 2024-09-26 14:48:06 -05:00
Chris Eager e20a4c1f77 Refactor ProcessScheduledJobsServiceCommand to dispose of processing jobs on shutdown 2024-09-26 14:12:12 -05:00
Jon Chambers 946a486c4b Add metric publishers to DynamoDB clients 2024-09-26 15:00:10 -04:00
Jon Chambers 78b40397f9 Simplify metric publisher lifecycles 2024-09-26 15:00:10 -04:00
Jon Chambers 48e8d1c12f Add comments and constants to clarify the structure of metric collections 2024-09-26 15:00:10 -04:00
Jon Chambers b115e95da4 Add an AWS SDK metric publisher 2024-09-26 15:00:10 -04:00
Chris Eager ab0892cc41 Set executor shutdown time in ProcessScheduledJobsServiceCommand 2024-09-26 13:57:20 -05:00
Chris Eager e25291c74c Move MRM content parsing outside of “withBinaryClusterReactive” 2024-09-26 13:57:02 -05:00
Ravi Khadiwala 0e552bd602 Cancel play subscriptions when replacing them 2024-09-26 13:56:10 -05:00
Ameya Lokare e9b3e15556 Return report spam token from spam check instead of separate call 2024-09-26 11:53:40 -07:00
Ravi Khadiwala 237d0fd4e2 remove HTTP layer exceptions from Stripe/Braintree managers 2024-09-24 17:22:38 -05:00
Ravi Khadiwala 50bd30fb1f Fix cancelAtPeriodEnd calculation 2024-09-24 17:14:08 -05:00
Ravi Khadiwala 9fb4e2d272 set billingCycleAnchor in play billing responses 2024-09-24 17:14:08 -05:00
Jon Chambers 3e51366921 Narrow selection criterial for "notify idle devices with messages" experiment 2024-09-23 16:01:44 -04:00
Jonathan Klabunde Tomer 2d184b1ab6 return user's own username link handle in /whoami response 2024-09-23 12:46:10 -07:00
adel-signal befcdf55fe Balance TURN routing options across datacenters 2024-09-23 12:43:43 -07:00
Ravi Khadiwala ba12d39121 URLEncode shortCode paths 2024-09-23 14:43:15 -05:00
Ravi Khadiwala bf0f553ced Don't return 204s as exceptions
The jersey LoggingExceptionMapper automatically adds an entity to
WebApplicationExceptions. Jersey's HTTP server later strips the body on
204 responses, but our custom WebSocketResourceProvider does not
2024-09-23 14:43:04 -05:00
Chris Eager cd68a674bb Update protobuf-java to 3.25.5 2024-09-23 08:43:55 -05:00
Jon Chambers 315fc00eac Lazily evaluate jobs to give max concurrency meaningful "teeth" 2024-09-23 08:43:44 -05:00
Ameya Lokare 6142dcc7e6 Update to the latest version of the spam filter 2024-09-19 12:56:10 -07:00
Jonathan Klabunde Tomer c47141ffda yield json errors from 500s in sendMultiRecipientMessage 2024-09-19 12:36:52 -07:00
Jon Chambers 6c8566db60 Align "allocate device" and "verify device" default rate limits 2024-09-19 14:59:06 -04:00
Jonathan Klabunde Tomer aa60fae3b1 install RateLimitByIpFilter in soft-enforcement mode 2024-09-18 15:38:21 -07:00
Ravi Khadiwala 8cb9c60a3c Relax configured currency checks 2024-09-17 14:27:11 -05:00
Ameya Lokare dd7a20a774 Log IOException from assessCaptcha 2024-09-17 12:01:13 -07:00
Chris Eager 374fe087bc Use destination service ID from the envelope when removing views from shared MRM data 2024-09-16 13:19:11 -05:00
Chris Eager 11691c3122 Update fields in HCaptchaResponse
This reverts commit 8d129b10ca.
2024-09-16 13:12:36 -05:00
Chris Eager 8d129b10ca Revert "Update field names in HCaptchaResponse"
This reverts commit 42d4574213.
2024-09-13 15:28:42 -05:00
Katherine d6e03f50b9 Fix bug in ignoring svr errors in account deletion flow 2024-09-13 12:28:31 -04:00
Chris Eager f60c9f2a15 Use destination service ID from the envelope when looking up in shared MRM data 2024-09-13 11:21:18 -05:00
Chris Eager 1c617284f3 Add MRM views experiment to MessagesCache.getMessagesToPersist() 2024-09-13 11:21:18 -05:00
Chris Eager 5bc6ff0e77 Add check for existing key to MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript 2024-09-13 11:21:18 -05:00
Jonathan Klabunde Tomer 020c21f4ef remove support for deprecated messages DynamoDB key schema 2024-09-13 09:18:41 -07:00
Katherine bd57c1c7e7 Introduce configurable way to ignore SVR errors in the account deletion flow 2024-09-13 10:57:09 -04:00
Katherine Yen f4b94a7a89 Update to the latest version of the spam filter 2024-09-13 10:55:35 -04:00
ravi-signal b666b66160 Add missing @Valid annotations 2024-09-13 10:54:32 -04:00
ameya-signal 8bafb1a641 Update code style in MessageController.sendMessage() 2024-09-13 10:53:40 -04:00
Chris Eager 42d4574213 Update field names in HCaptchaResponse 2024-09-13 10:53:23 -04:00
Alex Konradi 9ef6f8aec9 Add a metric for requests of ZKC auth credentials 2024-09-13 10:53:04 -04:00
Jon Chambers 556eec649d Add platform and push token presence dimensions to account creation metrics 2024-09-06 12:37:23 -05:00
Ameya Lokare e160025cfc Clean up OpenAPI annotations on PUT /v1/challenge
* Remove 413 response since we no longer send it
* Add missing 428 response for when invalid captcha is submitted
2024-09-06 10:36:02 -07:00
Chris Eager 0602149c52 Skip removeRecipientViewFromMrmData pipeline if there are no keys 2024-09-06 12:35:03 -05:00
234 changed files with 5907 additions and 3501 deletions

No files matched your search

@@ -10,6 +10,7 @@ import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import org.signal.integration.config.Config;
import org.whispersystems.textsecuregcm.metrics.NoopAwsSdkMetricPublisher;
import org.whispersystems.textsecuregcm.registration.VerificationSession;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswords;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
@@ -30,9 +31,11 @@ public class IntegrationTools {
public static IntegrationTools create(final Config config) {
final AwsCredentialsProvider credentialsProvider = DefaultCredentialsProvider.builder().build();
final DynamoDbAsyncClient dynamoDbAsyncClient = config.dynamoDbClient().buildAsyncClient(credentialsProvider);
final DynamoDbAsyncClient dynamoDbAsyncClient =
config.dynamoDbClient().buildAsyncClient(credentialsProvider, new NoopAwsSdkMetricPublisher());
final DynamoDbClient dynamoDbClient = config.dynamoDbClient().buildSyncClient(credentialsProvider);
final DynamoDbClient dynamoDbClient =
config.dynamoDbClient().buildSyncClient(credentialsProvider, new NoopAwsSdkMetricPublisher());
final RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
config.dynamoDbTables().registrationRecovery(), Duration.ofDays(1), dynamoDbClient, dynamoDbAsyncClient);
@@ -126,7 +126,7 @@ public class TestUser {
}
public AccountAttributes accountAttributes() {
return new AccountAttributes(true, registrationId, pniRegistrationId, "".getBytes(StandardCharsets.UTF_8), "", true, new Device.DeviceCapabilities(false, false, false, false, false))
return new AccountAttributes(true, registrationId, pniRegistrationId, "".getBytes(StandardCharsets.UTF_8), "", true, new Device.DeviceCapabilities(false, false, false, false))
.withUnidentifiedAccessKey(unidentifiedAccessKey)
.withRecoveryPassword(registrationPassword);
}
Vendored
+1 -1
View File
@@ -260,7 +260,7 @@ done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties"
if [ -n "$wrapperSha256Sum" ]; then
wrapperSha256Result=false
if command -v sha256sum > /dev/null; then
if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c > /dev/null 2>&1; then
if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c - > /dev/null 2>&1; then
wrapperSha256Result=true
fi
elif command -v shasum > /dev/null; then
+2 -2
View File
@@ -63,7 +63,7 @@
<luajava.version>3.4.0</luajava.version>
<micrometer.version>1.13.2</micrometer.version>
<netty.version>4.1.111.Final</netty.version>
<protobuf.version>3.25.2</protobuf.version> <!-- should be kept in sync with the value from Google libraries-bom -->
<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.8</reactor-bom.version> <!-- 3.6.x, see https://github.com/reactor/reactor#bom-versioning-scheme -->
@@ -266,7 +266,7 @@
<dependency>
<groupId>org.signal</groupId>
<artifactId>embedded-redis</artifactId>
<version>0.9.0</version>
<version>0.9.1</version>
<scope>test</scope>
</dependency>
<dependency>
+2 -3
View File
@@ -8,6 +8,8 @@ braintree.privateKey: unset
googlePlayBilling.credentialsJson: |
{ "json": true }
appleAppStore.encodedKey: unset
directoryV2.client.userAuthenticationTokenSharedSecret: abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG= # base64-encoded secret shared with CDS to generate auth tokens for Signal users
directoryV2.client.userIdTokenSharedSecret: bbcdefghijklmnopqrstuvwxyz0123456789ABCDEFG= # base64-encoded secret shared with CDS to generate auth identity tokens for Signal users
@@ -19,9 +21,6 @@ svr3.userIdTokenSharedSecret: dbcdefghijklmnopqrstuvwxyz0123456789ABCDEFG= # bas
tus.userAuthenticationTokenSharedSecret: abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG=
awsAttachments.accessKey: test
awsAttachments.accessSecret: test
gcpAttachments.rsaSigningKey: |
-----BEGIN PRIVATE KEY-----
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
+15 -10
View File
@@ -81,6 +81,18 @@ googlePlayBilling:
applicationName: test
productIdToLevel: {}
appleAppStore:
env: SANDBOX
bundleId: bundle.name
appAppleId: 12345
issuerId: abcdefg
keyId: abcdefg
encodedKey: secret://appleAppStore.encodedKey
subscriptionGroupId: example_subscriptionGroupId
productIdToLevel: {}
appleRootCerts: []
dynamoDbClient:
region: us-west-2 # AWS Region
@@ -90,6 +102,7 @@ dynamoDbTables:
phoneNumberTableName: Example_Accounts_PhoneNumbers
phoneNumberIdentifierTableName: Example_Accounts_PhoneNumberIdentifiers
usernamesTableName: Example_Accounts_Usernames
usedLinkDeviceTokensTableName: Example_Accounts_UsedLinkDeviceTokens
backups:
tableName: Example_Backups
clientReleases:
@@ -150,9 +163,8 @@ cacheCluster: # Redis server configuration for cache cluster
clientPresenceCluster: # Redis server configuration for client presence cluster
configurationUri: redis://redis.example.com:6379/
provisioning:
pubsub: # Redis server configuration for pubsub cluster
uri: redis://redis.example.com:6379/
pubsub: # Redis server configuration for pubsub cluster
uri: redis://redis.example.com:6379/
pushSchedulerCluster: # Redis server configuration for push scheduler cluster
configurationUri: redis://redis.example.com:6379/
@@ -227,13 +239,6 @@ messageCache: # Redis server configuration for message store cache
cluster:
configurationUri: redis://redis.example.com:6379/
awsAttachments: # AWS S3 configuration
bucket: aws-attachments
credentials:
accessKeyId: secret://awsAttachments.accessKey
secretAccessKey: secret://awsAttachments.accessSecret
region: us-west-2
gcpAttachments: # GCP Storage configuration
domain: example.com
email: user@example.cocm
+14 -2
View File
@@ -15,6 +15,7 @@
<java-uuid-generator.version>5.1.0</java-uuid-generator.version>
<sqlite4java.version>1.0.392</sqlite4java.version>
<google-androidpublisher.version>v3-rev20240820-2.0.0</google-androidpublisher.version>
<storekit.version>3.1.0</storekit.version>
</properties>
<dependencies>
@@ -23,7 +24,18 @@
<artifactId>google-api-services-androidpublisher</artifactId>
<version>${google-androidpublisher.version}</version>
</dependency>
<dependency>
<groupId>com.apple.itunes.storekit</groupId>
<artifactId>app-store-server-library</artifactId>
<version>${storekit.version}</version>
<exclusions>
<!-- conflicts with okio-jvm from apollo-api-jvm -->
<exclusion>
<groupId>com.squareup.okio</groupId>
<artifactId>okio-jvm</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.swagger.core.v3</groupId>
<artifactId>swagger-jaxrs2</artifactId>
@@ -506,7 +518,7 @@
<dependency>
<groupId>com.apollographql.apollo3</groupId>
<artifactId>apollo-api-jvm</artifactId>
<version>3.8.2</version>
<version>3.8.5</version>
<exclusions>
<exclusion>
@@ -15,14 +15,13 @@ import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import org.whispersystems.textsecuregcm.attachments.TusConfiguration;
import org.whispersystems.textsecuregcm.configuration.ApnConfiguration;
import org.whispersystems.textsecuregcm.configuration.AppleAppStoreConfiguration;
import org.whispersystems.textsecuregcm.configuration.ArtServiceConfiguration;
import org.whispersystems.textsecuregcm.configuration.AwsAttachmentsConfiguration;
import org.whispersystems.textsecuregcm.configuration.AwsCredentialsProviderFactory;
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
import org.whispersystems.textsecuregcm.configuration.BraintreeConfiguration;
import org.whispersystems.textsecuregcm.configuration.Cdn3StorageManagerConfiguration;
import org.whispersystems.textsecuregcm.configuration.CdnConfiguration;
import org.whispersystems.textsecuregcm.configuration.ClientCdnConfiguration;
import org.whispersystems.textsecuregcm.configuration.ClientReleaseConfiguration;
import org.whispersystems.textsecuregcm.configuration.DatadogConfiguration;
import org.whispersystems.textsecuregcm.configuration.DefaultAwsCredentialsFactory;
@@ -33,6 +32,7 @@ import org.whispersystems.textsecuregcm.configuration.DynamoDbClientFactory;
import org.whispersystems.textsecuregcm.configuration.DynamoDbTables;
import org.whispersystems.textsecuregcm.configuration.ExternalRequestFilterConfiguration;
import org.whispersystems.textsecuregcm.configuration.FaultTolerantRedisClusterFactory;
import org.whispersystems.textsecuregcm.configuration.FaultTolerantRedisClientFactory;
import org.whispersystems.textsecuregcm.configuration.FcmConfiguration;
import org.whispersystems.textsecuregcm.configuration.GcpAttachmentsConfiguration;
import org.whispersystems.textsecuregcm.configuration.GenericZkConfig;
@@ -46,7 +46,6 @@ import org.whispersystems.textsecuregcm.configuration.MessageCacheConfiguration;
import org.whispersystems.textsecuregcm.configuration.NoiseWebSocketTunnelConfiguration;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
import org.whispersystems.textsecuregcm.configuration.PaymentsServiceConfiguration;
import org.whispersystems.textsecuregcm.configuration.ProvisioningConfiguration;
import org.whispersystems.textsecuregcm.configuration.RegistrationServiceClientFactory;
import org.whispersystems.textsecuregcm.configuration.RemoteConfigConfiguration;
import org.whispersystems.textsecuregcm.configuration.ReportMessageConfiguration;
@@ -94,6 +93,11 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private GooglePlayBillingConfiguration googlePlayBilling;
@NotNull
@Valid
@JsonProperty
private AppleAppStoreConfiguration appleAppStore;
@NotNull
@Valid
@JsonProperty
@@ -104,11 +108,6 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private DynamoDbTables dynamoDbTables;
@NotNull
@Valid
@JsonProperty
private AwsAttachmentsConfiguration awsAttachments;
@NotNull
@Valid
@JsonProperty
@@ -137,7 +136,7 @@ public class WhisperServerConfiguration extends Configuration {
@NotNull
@Valid
@JsonProperty
private ProvisioningConfiguration provisioning;
private FaultTolerantRedisClientFactory pubsub;
@NotNull
@Valid
@@ -368,6 +367,10 @@ public class WhisperServerConfiguration extends Configuration {
return googlePlayBilling;
}
public AppleAppStoreConfiguration getAppleAppStore() {
return appleAppStore;
}
public DynamoDbClientFactory getDynamoDbClientConfiguration() {
return dynamoDbClient;
}
@@ -388,10 +391,6 @@ public class WhisperServerConfiguration extends Configuration {
return webSocket;
}
public AwsAttachmentsConfiguration getAwsAttachmentsConfiguration() {
return awsAttachments;
}
public GcpAttachmentsConfiguration getGcpAttachmentsConfiguration() {
return gcpAttachments;
}
@@ -400,8 +399,8 @@ public class WhisperServerConfiguration extends Configuration {
return cacheCluster;
}
public ProvisioningConfiguration getProvisioningConfiguration() {
return provisioning;
public FaultTolerantRedisClientFactory getRedisPubSubConfiguration() {
return pubsub;
}
public SecureValueRecovery2Configuration getSvr2Configuration() {
@@ -110,10 +110,7 @@ import org.whispersystems.textsecuregcm.controllers.AccountController;
import org.whispersystems.textsecuregcm.controllers.AccountControllerV2;
import org.whispersystems.textsecuregcm.controllers.ArchiveController;
import org.whispersystems.textsecuregcm.controllers.ArtController;
import org.whispersystems.textsecuregcm.controllers.AttachmentControllerV2;
import org.whispersystems.textsecuregcm.controllers.AttachmentControllerV3;
import org.whispersystems.textsecuregcm.controllers.AttachmentControllerV4;
import org.whispersystems.textsecuregcm.controllers.OneTimeDonationController;
import org.whispersystems.textsecuregcm.controllers.CallLinkController;
import org.whispersystems.textsecuregcm.controllers.CallRoutingController;
import org.whispersystems.textsecuregcm.controllers.CertificateController;
@@ -125,6 +122,7 @@ import org.whispersystems.textsecuregcm.controllers.KeepAliveController;
import org.whispersystems.textsecuregcm.controllers.KeyTransparencyController;
import org.whispersystems.textsecuregcm.controllers.KeysController;
import org.whispersystems.textsecuregcm.controllers.MessageController;
import org.whispersystems.textsecuregcm.controllers.OneTimeDonationController;
import org.whispersystems.textsecuregcm.controllers.PaymentsController;
import org.whispersystems.textsecuregcm.controllers.ProfileController;
import org.whispersystems.textsecuregcm.controllers.ProvisioningController;
@@ -167,6 +165,7 @@ import org.whispersystems.textsecuregcm.keytransparency.KeyTransparencyServiceCl
import org.whispersystems.textsecuregcm.limits.CardinalityEstimator;
import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor;
import org.whispersystems.textsecuregcm.limits.PushChallengeManager;
import org.whispersystems.textsecuregcm.limits.RateLimitByIpFilter;
import org.whispersystems.textsecuregcm.limits.RateLimitChallengeManager;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper;
@@ -181,25 +180,26 @@ import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper
import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.ServerRejectedExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.SubscriptionProcessorExceptionMapper;
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
import org.whispersystems.textsecuregcm.metrics.MetricsApplicationEventListener;
import org.whispersystems.textsecuregcm.metrics.MetricsHttpChannelListener;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.MicrometerAwsSdkMetricPublisher;
import org.whispersystems.textsecuregcm.metrics.ReportedMessageMetricsListener;
import org.whispersystems.textsecuregcm.metrics.TrafficSource;
import org.whispersystems.textsecuregcm.providers.MultiRecipientMessageProvider;
import org.whispersystems.textsecuregcm.providers.RedisClusterHealthCheck;
import org.whispersystems.textsecuregcm.push.APNSender;
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
import org.whispersystems.textsecuregcm.push.FcmSender;
import org.whispersystems.textsecuregcm.push.MessageSender;
import org.whispersystems.textsecuregcm.push.ProvisioningManager;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
import org.whispersystems.textsecuregcm.push.ReceiptSender;
import org.whispersystems.textsecuregcm.redis.ConnectionEventLogger;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
import org.whispersystems.textsecuregcm.s3.PolicySigner;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
@@ -208,7 +208,6 @@ import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2
import org.whispersystems.textsecuregcm.spam.ChallengeConstraintChecker;
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
import org.whispersystems.textsecuregcm.spam.RegistrationRecoveryChecker;
import org.whispersystems.textsecuregcm.spam.ReportSpamTokenProvider;
import org.whispersystems.textsecuregcm.spam.SpamChecker;
import org.whispersystems.textsecuregcm.spam.SpamFilter;
import org.whispersystems.textsecuregcm.storage.AccountLockManager;
@@ -242,6 +241,7 @@ import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
import org.whispersystems.textsecuregcm.storage.Subscriptions;
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
import org.whispersystems.textsecuregcm.storage.VerificationSessions;
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator;
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
@@ -261,12 +261,9 @@ import org.whispersystems.textsecuregcm.workers.BackupMetricsCommand;
import org.whispersystems.textsecuregcm.workers.CertificateCommand;
import org.whispersystems.textsecuregcm.workers.CheckDynamicConfigurationCommand;
import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
import org.whispersystems.textsecuregcm.workers.DiscardPushNotificationExperimentSamplesCommand;
import org.whispersystems.textsecuregcm.workers.FinishPushNotificationExperimentCommand;
import org.whispersystems.textsecuregcm.workers.IdleDeviceNotificationSchedulerFactory;
import org.whispersystems.textsecuregcm.workers.MessagePersisterServiceCommand;
import org.whispersystems.textsecuregcm.workers.NotifyIdleDevicesWithMessagesExperimentFactory;
import org.whispersystems.textsecuregcm.workers.NotifyIdleDevicesWithoutMessagesCommand;
import org.whispersystems.textsecuregcm.workers.NotifyIdleDevicesCommand;
import org.whispersystems.textsecuregcm.workers.ProcessScheduledJobsServiceCommand;
import org.whispersystems.textsecuregcm.workers.RemoveExpiredAccountsCommand;
import org.whispersystems.textsecuregcm.workers.RemoveExpiredBackupsCommand;
@@ -276,7 +273,6 @@ import org.whispersystems.textsecuregcm.workers.ScheduledApnPushNotificationSend
import org.whispersystems.textsecuregcm.workers.ServerVersionCommand;
import org.whispersystems.textsecuregcm.workers.SetRequestLoggingEnabledTask;
import org.whispersystems.textsecuregcm.workers.SetUserDiscoverabilityCommand;
import org.whispersystems.textsecuregcm.workers.StartPushNotificationExperimentCommand;
import org.whispersystems.textsecuregcm.workers.UnlinkDeviceCommand;
import org.whispersystems.textsecuregcm.workers.ZkParamsCommand;
import org.whispersystems.websocket.WebSocketResourceProviderFactory;
@@ -330,25 +326,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
bootstrap.addCommand(new RemoveExpiredBackupsCommand(Clock.systemUTC()));
bootstrap.addCommand(new BackupMetricsCommand(Clock.systemUTC()));
bootstrap.addCommand(new RemoveExpiredLinkedDevicesCommand());
bootstrap.addCommand(new NotifyIdleDevicesWithoutMessagesCommand());
bootstrap.addCommand(new NotifyIdleDevicesCommand());
bootstrap.addCommand(new ProcessScheduledJobsServiceCommand("process-idle-device-notification-jobs",
"Processes scheduled jobs to send notifications to idle devices",
new IdleDeviceNotificationSchedulerFactory()));
bootstrap.addCommand(
new StartPushNotificationExperimentCommand<>("start-notify-idle-devices-with-messages-experiment",
"Start an experiment to send push notifications to idle devices with pending messages",
new NotifyIdleDevicesWithMessagesExperimentFactory()));
bootstrap.addCommand(
new FinishPushNotificationExperimentCommand<>("finish-notify-idle-devices-with-messages-experiment",
"Finish an experiment to send push notifications to idle devices with pending messages",
new NotifyIdleDevicesWithMessagesExperimentFactory()));
bootstrap.addCommand(
new DiscardPushNotificationExperimentSamplesCommand("discard-notify-idle-devices-with-messages-samples",
"Discard samples from the \"notify idle devices with messages\" experiment",
new NotifyIdleDevicesWithMessagesExperimentFactory()));
}
@Override
@@ -394,10 +375,15 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
BankMandateTranslator bankMandateTranslator = new BankMandateTranslator(headerControlledResourceBundleLookup);
environment.lifecycle().manage(new ManagedAwsCrt());
DynamoDbAsyncClient dynamoDbAsyncClient = config.getDynamoDbClientConfiguration()
.buildAsyncClient(awsCredentialsProvider);
DynamoDbClient dynamoDbClient = config.getDynamoDbClientConfiguration().buildSyncClient(awsCredentialsProvider);
final ExecutorService awsSdkMetricsExecutor = environment.lifecycle()
.virtualExecutorService(name(getClass(), "awsSdkMetrics-%d"));
final DynamoDbAsyncClient dynamoDbAsyncClient = config.getDynamoDbClientConfiguration()
.buildAsyncClient(awsCredentialsProvider, new MicrometerAwsSdkMetricPublisher(awsSdkMetricsExecutor, "dynamoDbAsync"));
final DynamoDbClient dynamoDbClient = config.getDynamoDbClientConfiguration()
.buildSyncClient(awsCredentialsProvider, new MicrometerAwsSdkMetricPublisher(awsSdkMetricsExecutor, "dynamoDbSync"));
BlockingQueue<Runnable> messageDeletionQueue = new LinkedBlockingQueue<>();
Metrics.gaugeCollectionSize(name(getClass(), "messageDeletionQueueSize"), Collections.emptyList(),
@@ -416,7 +402,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getDynamoDbTables().getAccounts().getPhoneNumberTableName(),
config.getDynamoDbTables().getAccounts().getPhoneNumberIdentifierTableName(),
config.getDynamoDbTables().getAccounts().getUsernamesTableName(),
config.getDynamoDbTables().getDeletedAccounts().getTableName());
config.getDynamoDbTables().getDeletedAccounts().getTableName(),
config.getDynamoDbTables().getAccounts().getUsedLinkDeviceTokensTableName());
ClientReleases clientReleases = new ClientReleases(dynamoDbAsyncClient,
config.getDynamoDbTables().getClientReleases().getTableName());
PhoneNumberIdentifiers phoneNumberIdentifiers = new PhoneNumberIdentifiers(dynamoDbClient,
@@ -459,18 +446,21 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
.build();
ConnectionEventLogger.logConnectionEvents(sharedClientResources);
FaultTolerantRedisCluster cacheCluster = config.getCacheClusterConfiguration()
FaultTolerantRedisClusterClient cacheCluster = config.getCacheClusterConfiguration()
.build("main_cache", sharedClientResources.mutate());
FaultTolerantRedisCluster messagesCluster =
FaultTolerantRedisClusterClient messagesCluster =
config.getMessageCacheConfiguration().getRedisClusterConfiguration()
.build("messages", sharedClientResources.mutate());
FaultTolerantRedisCluster clientPresenceCluster = config.getClientPresenceClusterConfiguration()
FaultTolerantRedisClusterClient clientPresenceCluster = config.getClientPresenceClusterConfiguration()
.build("client_presence", sharedClientResources.mutate());
FaultTolerantRedisCluster pushSchedulerCluster = config.getPushSchedulerCluster().build("push_scheduler",
FaultTolerantRedisClusterClient pushSchedulerCluster = config.getPushSchedulerCluster().build("push_scheduler",
sharedClientResources.mutate());
FaultTolerantRedisCluster rateLimitersCluster = config.getRateLimitersCluster().build("rate_limiters",
FaultTolerantRedisClusterClient rateLimitersCluster = config.getRateLimitersCluster().build("rate_limiters",
sharedClientResources.mutate());
FaultTolerantRedisClient pubsubClient =
config.getRedisPubSubConfiguration().build("pubsub", sharedClientResources);
final BlockingQueue<Runnable> keyspaceNotificationDispatchQueue = new ArrayBlockingQueue<>(100_000);
Metrics.gaugeCollectionSize(name(getClass(), "keyspaceNotificationDispatchQueueSize"), Collections.emptyList(),
keyspaceNotificationDispatchQueue);
@@ -584,7 +574,11 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
.virtualExecutorService(name(getClass(), "keyTransparency-%d"));
ExecutorService googlePlayBillingExecutor = environment.lifecycle()
.virtualExecutorService(name(getClass(), "googlePlayBilling-%d"));
ExecutorService appleAppStoreExecutor = environment.lifecycle()
.virtualExecutorService(name(getClass(), "appleAppStore-%d"));
ScheduledExecutorService appleAppStoreRetryExecutor = environment.lifecycle()
.scheduledExecutorService(name(getClass(), "appleAppStoreRetry-%d")).threads(1).build();
ScheduledExecutorService subscriptionProcessorRetryExecutor = environment.lifecycle()
.scheduledExecutorService(name(getClass(), "subscriptionProcessorRetry-%d")).threads(1).build();
ScheduledExecutorService cloudflareTurnRetryExecutor = environment.lifecycle()
@@ -646,11 +640,11 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
ClientPublicKeysManager clientPublicKeysManager =
new ClientPublicKeysManager(clientPublicKeys, accountLockManager, accountLockExecutor);
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
accountLockManager, keysManager, messagesManager, profilesManager,
pubsubClient, accountLockManager, keysManager, messagesManager, profilesManager,
secureStorageClient, secureValueRecovery2Client,
clientPresenceManager,
registrationRecoveryPasswordsManager, clientPublicKeysManager, accountLockExecutor, clientPresenceExecutor,
clock);
clock, config.getLinkDeviceSecretConfiguration().secret().value(), dynamicConfigurationManager);
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs);
APNSender apnSender = new APNSender(apnSenderExecutor, config.getApnConfiguration());
FcmSender fcmSender = new FcmSender(fcmSenderExecutor, config.getFcmConfiguration().credentials().value());
@@ -660,9 +654,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new PushNotificationManager(accountsManager, apnSender, fcmSender, pushNotificationScheduler);
RateLimiters rateLimiters = RateLimiters.createAndValidate(config.getLimitsConfiguration(),
dynamicConfigurationManager, rateLimitersCluster);
ProvisioningManager provisioningManager = new ProvisioningManager(
config.getProvisioningConfiguration().pubsub().build(sharedClientResources),
config.getProvisioningConfiguration().circuitBreaker());
ProvisioningManager provisioningManager = new ProvisioningManager(pubsubClient);
IssuedReceiptsManager issuedReceiptsManager = new IssuedReceiptsManager(
config.getDynamoDbTables().getIssuedReceipts().getTableName(),
config.getDynamoDbTables().getIssuedReceipts().getExpiration(),
@@ -752,6 +744,13 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getGooglePlayBilling().applicationName(),
config.getGooglePlayBilling().productIdToLevel(),
googlePlayBillingExecutor);
AppleAppStoreManager appleAppStoreManager = new AppleAppStoreManager(
config.getAppleAppStore().env(), config.getAppleAppStore().bundleId(), config.getAppleAppStore().appAppleId(),
config.getAppleAppStore().issuerId(), config.getAppleAppStore().keyId(),
config.getAppleAppStore().encodedKey().value(), config.getAppleAppStore().subscriptionGroupId(),
config.getAppleAppStore().productIdToLevel(),
config.getAppleAppStore().appleRootCerts(),
config.getAppleAppStore().retry(), appleAppStoreExecutor, appleAppStoreRetryExecutor);
environment.lifecycle().manage(apnSender);
environment.lifecycle().manage(pushNotificationScheduler);
@@ -763,6 +762,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
environment.lifecycle().manage(keyTransparencyServiceClient);
environment.lifecycle().manage(clientReleaseManager);
environment.lifecycle().manage(virtualThreadPinEventMonitor);
environment.lifecycle().manage(accountsManager);
final RegistrationCaptchaManager registrationCaptchaManager = new RegistrationCaptchaManager(captchaChecker);
@@ -973,6 +973,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final List<Filter> filters = new ArrayList<>();
filters.add(remoteDeprecationFilter);
filters.add(new RemoteAddressFilter());
filters.add(new TimestampResponseFilter());
for (Filter filter : filters) {
environment.servlets()
@@ -1003,6 +1004,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
environment.jersey().register(new BufferingInterceptor());
environment.jersey().register(new VirtualExecutorServiceProvider("managed-async-virtual-thread-"));
environment.jersey().register(new RateLimitByIpFilter(rateLimiters));
environment.jersey().register(new RequestStatisticsFilter(TrafficSource.HTTP));
environment.jersey().register(MultiRecipientMessageProvider.class);
environment.jersey().register(new AuthDynamicFeature(accountAuthFilter));
@@ -1021,10 +1023,12 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
clientReleaseManager, messageDeliveryLoopMonitor));
webSocketEnvironment.jersey()
.register(new WebsocketRefreshApplicationEventListener(accountsManager, clientPresenceManager));
webSocketEnvironment.jersey().register(new RateLimitByIpFilter(rateLimiters));
webSocketEnvironment.jersey().register(new RequestStatisticsFilter(TrafficSource.WEBSOCKET));
webSocketEnvironment.jersey().register(MultiRecipientMessageProvider.class);
webSocketEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET, clientReleaseManager));
webSocketEnvironment.jersey().register(new KeepAliveController(clientPresenceManager));
webSocketEnvironment.jersey().register(new TimestampResponseFilter());
final List<SpamFilter> spamFilters = ServiceLoader.load(SpamFilter.class)
.stream()
@@ -1046,12 +1050,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
if (spamFilter.isEmpty()) {
log.warn("No spam filters installed");
}
final ReportSpamTokenProvider reportSpamTokenProvider = spamFilter
.map(SpamFilter::getReportSpamTokenProvider)
.orElseGet(() -> {
log.warn("No spam-reporting token providers found; using default (no-op) provider as a default");
return ReportSpamTokenProvider.noop();
});
final SpamChecker spamChecker = spamFilter
.map(SpamFilter::getSpamChecker)
.orElseGet(() -> {
@@ -1097,11 +1095,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new AccountControllerV2(accountsManager, changeNumberManager, phoneVerificationTokenManager,
registrationLockVerificationManager, rateLimiters),
new ArtController(rateLimiters, artCredentialsGenerator),
new AttachmentControllerV2(rateLimiters,
config.getAwsAttachmentsConfiguration().credentials().accessKeyId().value(),
config.getAwsAttachmentsConfiguration().credentials().secretAccessKey().value(),
config.getAwsAttachmentsConfiguration().region(), config.getAwsAttachmentsConfiguration().bucket()),
new AttachmentControllerV3(rateLimiters, gcsAttachmentGenerator),
new AttachmentControllerV4(rateLimiters, gcsAttachmentGenerator, tusAttachmentGenerator,
experimentEnrollmentManager),
new ArchiveController(backupAuthManager, backupManager),
@@ -1111,8 +1104,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getDeliveryCertificate().ecPrivateKey(), config.getDeliveryCertificate().expiresDays()),
zkAuthOperations, callingGenericZkSecretParams, clock),
new ChallengeController(rateLimitChallengeManager, challengeConstraintChecker),
new DeviceController(config.getLinkDeviceSecretConfiguration().secret().value(), accountsManager,
clientPublicKeysManager, rateLimiters, rateLimitersCluster, config.getMaxDevices(), clock),
new DeviceController(accountsManager, clientPublicKeysManager, rateLimiters, config.getMaxDevices()),
new DirectoryV2Controller(directoryV2CredentialsGenerator),
new DonationController(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(),
ReceiptCredentialPresentation::new),
@@ -1120,7 +1112,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new KeyTransparencyController(keyTransparencyServiceClient),
new MessageController(rateLimiters, messageByteLimitCardinalityEstimator, messageSender, receiptSender,
accountsManager, messagesManager, pushNotificationManager, pushNotificationScheduler, reportMessageManager,
multiRecipientMessageExecutor, messageDeliveryScheduler, reportSpamTokenProvider, clientReleaseManager,
multiRecipientMessageExecutor, messageDeliveryScheduler, clientReleaseManager,
dynamicConfigurationManager, zkSecretParams, spamChecker, messageMetrics, messageDeliveryLoopMonitor,
Clock.systemUTC()),
new PaymentsController(currencyManager, paymentsCredentialsGenerator),
@@ -1143,10 +1135,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
);
if (config.getSubscription() != null && config.getOneTimeDonations() != null) {
SubscriptionManager subscriptionManager = new SubscriptionManager(subscriptions,
List.of(stripeManager, braintreeManager, googlePlayBillingManager),
List.of(stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager),
zkReceiptOperations, issuedReceiptsManager);
commonControllers.add(new SubscriptionController(clock, config.getSubscription(), config.getOneTimeDonations(),
subscriptionManager, stripeManager, braintreeManager, googlePlayBillingManager,
subscriptionManager, stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager,
profileBadgeConverter, resourceBundleLevelTranslator, bankMandateTranslator));
commonControllers.add(new OneTimeDonationController(clock, config.getOneTimeDonations(), stripeManager, braintreeManager,
zkReceiptOperations, issuedReceiptsManager, oneTimeDonationsManager));
@@ -1163,6 +1155,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
provisioningEnvironment.setConnectListener(new ProvisioningConnectListener(provisioningManager));
provisioningEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET, clientReleaseManager));
provisioningEnvironment.jersey().register(new KeepAliveController(clientPresenceManager));
provisioningEnvironment.jersey().register(new TimestampResponseFilter());
registerCorsFilter(environment);
registerExceptionMappers(environment, webSocketEnvironment, provisioningEnvironment);
@@ -1213,7 +1206,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new ImpossiblePhoneNumberExceptionMapper(),
new NonNormalizedPhoneNumberExceptionMapper(),
new RegistrationServiceSenderExceptionMapper(),
new SubscriptionProcessorExceptionMapper(),
new SubscriptionExceptionMapper(),
new JsonMappingExceptionMapper()
).forEach(exceptionMapper -> {
@@ -76,22 +76,22 @@ public class ConfiguredProfileBadgeConverter implements ProfileBadgeConverter, B
final ResourceBundle resourceBundle = headerControlledResourceBundleLookup.getResourceBundle(BASE_NAME,
acceptableLanguages);
List<Badge> badges = accountBadges.stream()
.filter(accountBadge -> (isSelf || accountBadge.isVisible())
&& now.isBefore(accountBadge.getExpiration())
&& knownBadges.containsKey(accountBadge.getId()))
.filter(accountBadge -> (isSelf || accountBadge.visible())
&& now.isBefore(accountBadge.expiration())
&& knownBadges.containsKey(accountBadge.id()))
.map(accountBadge -> {
BadgeConfiguration configuration = knownBadges.get(accountBadge.getId());
BadgeConfiguration configuration = knownBadges.get(accountBadge.id());
return newBadge(
isSelf,
accountBadge.getId(),
accountBadge.id(),
configuration.getCategory(),
resourceBundle.getString(accountBadge.getId() + "_name"),
resourceBundle.getString(accountBadge.getId() + "_description"),
resourceBundle.getString(accountBadge.id() + "_name"),
resourceBundle.getString(accountBadge.id() + "_description"),
configuration.getSprites(),
configuration.getSvg(),
configuration.getSvgs(),
accountBadge.getExpiration(),
accountBadge.isVisible());
accountBadge.expiration(),
accountBadge.visible());
})
.collect(Collectors.toCollection(ArrayList::new));
badges.addAll(badgeIdsEnabledForAll.stream().filter(knownBadges::containsKey).map(id -> {
@@ -8,15 +8,16 @@ package org.whispersystems.textsecuregcm.calls.routing;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse;
import org.apache.commons.lang3.tuple.Triple;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.util.Util;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.util.*;
import java.util.function.Supplier;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
@@ -58,6 +59,7 @@ public class TurnCallRouter {
* @param aci aci of client
* @param clientAddress IP address to base routing on
* @param instanceLimit max instances to return options for
* @return Up to two * instanceLimit options, half in ipv4, half in ipv6
*/
public TurnServerOptions getRoutingFor(
@Nonnull final UUID aci,
@@ -121,8 +123,7 @@ public class TurnCallRouter {
List<String> urlsWithIps = getUrlsForInstances(
selectInstances(
datacenters,
instanceLimit,
(clientAddress.get() instanceof Inet6Address)
instanceLimit
));
return new TurnServerOptions(hostname, urlsWithIps, minimalRandomUrls());
}
@@ -134,25 +135,22 @@ public class TurnCallRouter {
.toList();
}
private List<String> selectInstances(List<String> datacenters, int limit, boolean preferV6) {
if(datacenters.isEmpty() || limit == 0) {
// returns balanced number of instances across provided datacenters, prioritizing the datacenters earlier in the list
private List<String> selectInstances(List<String> datacenters, int instanceLimit) {
if(datacenters.isEmpty() || instanceLimit == 0) {
return Collections.emptyList();
}
int numV6 = preferV6 ? (limit - limit / 3) : limit / 3;
int numV4 = limit - numV6;
CallDnsRecords dnsRecords = this.callDnsRecords.get();
List<InetAddress> ipv4Selection = datacenters.stream()
.flatMap(dc -> randomNOf(dnsRecords.aByRegion().get(dc), limit, stableSelect).stream())
List<List<InetAddress>> ipv4Options = datacenters.stream()
.map(dc -> randomNOf(dnsRecords.aByRegion().get(dc), instanceLimit, stableSelect))
.toList();
List<InetAddress> ipv6Selection = datacenters.stream()
.flatMap(dc -> randomNOf(dnsRecords.aaaaByRegion().get(dc), limit, stableSelect).stream())
List<List<InetAddress>> ipv6Options = datacenters.stream()
.map(dc -> randomNOf(dnsRecords.aaaaByRegion().get(dc), instanceLimit, stableSelect))
.toList();
// increase numV4 if not enough v6 options. vice-versa is also true
numV4 = Math.max(numV4, limit - ipv6Selection.size());
ipv4Selection = ipv4Selection.stream().limit(numV4).toList();
ipv6Selection = ipv6Selection.stream().limit(limit - ipv4Selection.size()).toList();
List<InetAddress> ipv4Selection = selectFromOptions(ipv4Options, instanceLimit);
List<InetAddress> ipv6Selection = selectFromOptions(ipv6Options, instanceLimit);
return Stream.concat(
ipv4Selection.stream().map(InetAddress::getHostAddress),
@@ -161,6 +159,19 @@ public class TurnCallRouter {
).toList();
}
private static List<InetAddress> selectFromOptions(List<List<InetAddress>> recordsByDc, int instanceLimit) {
return IntStream.range(0, recordsByDc.size())
.mapToObj(dcIndex -> IntStream.range(0, recordsByDc.get(dcIndex).size())
.mapToObj(addressIndex -> Triple.of(addressIndex, dcIndex, recordsByDc.get(dcIndex).get(addressIndex))))
.flatMap(i -> i)
.sorted(Comparator.comparingInt((Triple<Integer, Integer, InetAddress> t) -> t.getLeft())
.thenComparingInt(Triple::getMiddle))
.limit(instanceLimit)
.sorted(Comparator.comparingInt(Triple::getMiddle))
.map(Triple::getRight)
.toList();
}
private static <E> List<E> randomNOf(List<E> values, int n, boolean stableSelect) {
return stableSelect ? Util.randomNOfStable(values, n) : Util.randomNOfShuffled(values, n);
}
@@ -76,7 +76,13 @@ public class AssessmentResult {
if (!solved) {
return false;
}
return this.actualScore >= scoreThreshold.orElse(this.defaultScoreThreshold);
// Since HCaptcha scores are truncated to 2 decimal places, we can multiply by 100 and round to the nearest int for
// comparison instead of floating point comparisons
return normalizedIntScore(this.actualScore) >= normalizedIntScore(scoreThreshold.orElse(this.defaultScoreThreshold));
}
private static int normalizedIntScore(final float score) {
return Math.round(score * 100);
}
public String getScoreString() {
@@ -6,8 +6,7 @@
package org.whispersystems.textsecuregcm.captcha;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.List;
@@ -21,22 +20,19 @@ public class HCaptchaResponse {
@JsonProperty
boolean success;
@JsonProperty(value = "challenge-ts")
Duration challengeTs;
@JsonProperty(value = "challenge_ts")
Instant challengeTs;
@JsonProperty
String hostname;
@JsonProperty
boolean credit;
@JsonProperty(value = "error-codes")
List<String> errorCodes = Collections.emptyList();
@JsonProperty
float score;
@JsonProperty(value = "score-reasons")
@JsonProperty(value = "score_reason")
List<String> scoreReasons = Collections.emptyList();
public HCaptchaResponse() {
@@ -48,7 +44,6 @@ public class HCaptchaResponse {
"success=" + success +
", challengeTs=" + challengeTs +
", hostname='" + hostname + '\'' +
", credit=" + credit +
", errorCodes=" + errorCodes +
", score=" + score +
", scoreReasons=" + scoreReasons +
@@ -9,9 +9,11 @@ import io.micrometer.core.instrument.Metrics;
import org.apache.http.HttpStatus;
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
@@ -28,7 +30,7 @@ public class ShortCodeExpander {
}
public Optional<String> retrieve(final String shortCode) throws IOException {
final URI uri = shortenerHost.resolve(shortCode);
final URI uri = shortenerHost.resolve(URLEncoder.encode(shortCode, StandardCharsets.UTF_8));
final HttpRequest request = HttpRequest.newBuilder().uri(uri).GET().build();
try {
@@ -10,19 +10,22 @@ public class AccountsTableConfiguration extends Table {
private final String phoneNumberTableName;
private final String phoneNumberIdentifierTableName;
private final String usernamesTableName;
private final String usedLinkDeviceTokensTableName;
@JsonCreator
public AccountsTableConfiguration(
@JsonProperty("tableName") final String tableName,
@JsonProperty("phoneNumberTableName") final String phoneNumberTableName,
@JsonProperty("phoneNumberIdentifierTableName") final String phoneNumberIdentifierTableName,
@JsonProperty("usernamesTableName") final String usernamesTableName) {
@JsonProperty("usernamesTableName") final String usernamesTableName,
@JsonProperty("usedLinkDeviceTokensTableName") final String usedLinkDeviceTokensTableName) {
super(tableName);
this.phoneNumberTableName = phoneNumberTableName;
this.phoneNumberIdentifierTableName = phoneNumberIdentifierTableName;
this.usernamesTableName = usernamesTableName;
this.usedLinkDeviceTokensTableName = usedLinkDeviceTokensTableName;
}
@NotBlank
@@ -39,4 +42,9 @@ public class AccountsTableConfiguration extends Table {
public String getUsernamesTableName() {
return usernamesTableName;
}
@NotBlank
public String getUsedLinkDeviceTokensTableName() {
return usedLinkDeviceTokensTableName;
}
}
@@ -0,0 +1,47 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import com.apple.itunes.storekit.model.Environment;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
/**
* @param env The ios environment to use, typically SANDBOX or PRODUCTION
* @param bundleId The bundleId of the app
* @param appAppleId The integer id of the app
* @param issuerId The issuerId for the keys:
* https://developer.apple.com/documentation/appstoreconnectapi/generating_tokens_for_api_requests
* @param keyId The keyId for encodedKey
* @param encodedKey A private key with the "In-App Purchase" key type
* @param subscriptionGroupId The subscription group for in-app purchases
* @param productIdToLevel A map of productIds offered in the product catalog to their corresponding numeric
* subscription levels
* @param appleRootCerts Apple root certificates to verify signed API responses, encoded as base64 strings:
* https://www.apple.com/certificateauthority/
*/
public record AppleAppStoreConfiguration(
@NotNull Environment env,
@NotBlank String bundleId,
@NotNull Long appAppleId,
@NotBlank String issuerId,
@NotBlank String keyId,
@NotNull SecretString encodedKey,
@NotBlank String subscriptionGroupId,
@NotNull Map<String, Long> productIdToLevel,
@NotNull List<@NotBlank String> appleRootCerts,
@NotNull @Valid RetryConfiguration retry) {
public AppleAppStoreConfiguration {
if (retry == null) {
retry = new RetryConfiguration();
}
}
}
@@ -1,14 +0,0 @@
/*
* Copyright 2013 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
public record AwsAttachmentsConfiguration(@NotNull @Valid StaticAwsCredentialsFactory credentials,
@NotBlank String bucket,
@NotBlank String region) {
}
@@ -2,6 +2,7 @@ package org.whispersystems.textsecuregcm.configuration;
import java.util.Collections;
import java.util.Map;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
@@ -24,8 +25,8 @@ public record Cdn3StorageManagerConfiguration(
@NotNull SecretString clientSecret,
@NotNull Map<Integer, String> sourceSchemes,
@NotNull Integer numHttpClients,
@NotNull CircuitBreakerConfiguration circuitBreaker,
@NotNull RetryConfiguration retry) {
@NotNull @Valid CircuitBreakerConfiguration circuitBreaker,
@NotNull @Valid RetryConfiguration retry) {
public Cdn3StorageManagerConfiguration {
if (numHttpClients == null) {
@@ -1,6 +1,7 @@
package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
@@ -15,10 +16,12 @@ public class ClientCdnConfiguration {
@JsonProperty
@NotNull
@Valid
CircuitBreakerConfiguration circuitBreaker = new CircuitBreakerConfiguration();
@JsonProperty
@NotNull
@Valid
RetryConfiguration retry = new RetryConfiguration();
public CircuitBreakerConfiguration getCircuitBreaker() {
@@ -14,6 +14,7 @@ import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.http.crt.AwsCrtHttpClient;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
import software.amazon.awssdk.metrics.MetricPublisher;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
@@ -39,13 +40,14 @@ public record DynamoDbClientConfiguration(@NotBlank String region,
}
@Override
public DynamoDbClient buildSyncClient(final AwsCredentialsProvider credentialsProvider) {
public DynamoDbClient buildSyncClient(final AwsCredentialsProvider credentialsProvider, final MetricPublisher metricPublisher) {
return DynamoDbClient.builder()
.region(Region.of(region()))
.credentialsProvider(credentialsProvider)
.overrideConfiguration(ClientOverrideConfiguration.builder()
.apiCallTimeout(clientExecutionTimeout())
.apiCallAttemptTimeout(clientRequestTimeout())
.addMetricPublisher(metricPublisher)
.build())
.httpClientBuilder(AwsCrtHttpClient.builder()
.maxConcurrency(maxConnections()))
@@ -53,13 +55,14 @@ public record DynamoDbClientConfiguration(@NotBlank String region,
}
@Override
public DynamoDbAsyncClient buildAsyncClient(final AwsCredentialsProvider credentialsProvider) {
public DynamoDbAsyncClient buildAsyncClient(final AwsCredentialsProvider credentialsProvider, final MetricPublisher metricPublisher) {
return DynamoDbAsyncClient.builder()
.region(Region.of(region()))
.credentialsProvider(credentialsProvider)
.overrideConfiguration(ClientOverrideConfiguration.builder()
.apiCallTimeout(clientExecutionTimeout())
.apiCallAttemptTimeout(clientRequestTimeout())
.addMetricPublisher(metricPublisher)
.build())
.httpClientBuilder(NettyNioAsyncHttpClient.builder()
.maxConcurrency(maxConnections()))
@@ -8,13 +8,14 @@ package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import io.dropwizard.jackson.Discoverable;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.metrics.MetricPublisher;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = DynamoDbClientConfiguration.class)
public interface DynamoDbClientFactory extends Discoverable {
DynamoDbClient buildSyncClient(AwsCredentialsProvider awsCredentialsProvider);
DynamoDbClient buildSyncClient(AwsCredentialsProvider awsCredentialsProvider, MetricPublisher metricPublisher);
DynamoDbAsyncClient buildAsyncClient(AwsCredentialsProvider awsCredentialsProvider);
DynamoDbAsyncClient buildAsyncClient(AwsCredentialsProvider awsCredentialsProvider, MetricPublisher metricPublisher);
}
@@ -7,11 +7,11 @@ package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import io.dropwizard.jackson.Discoverable;
import io.lettuce.core.RedisClient;
import io.lettuce.core.resource.ClientResources;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = RedisConfiguration.class)
public interface SingletonRedisClientFactory extends Discoverable {
public interface FaultTolerantRedisClientFactory extends Discoverable {
RedisClient build(ClientResources clientResources);
FaultTolerantRedisClient build(String name, ClientResources clientResources);
}
@@ -8,10 +8,10 @@ package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import io.dropwizard.jackson.Discoverable;
import io.lettuce.core.resource.ClientResources;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = RedisClusterConfiguration.class)
public interface FaultTolerantRedisClusterFactory extends Discoverable {
FaultTolerantRedisCluster build(String name, ClientResources.Builder clientResourcesBuilder);
FaultTolerantRedisClusterClient build(String name, ClientResources.Builder clientResourcesBuilder);
}
@@ -6,6 +6,7 @@
package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import com.fasterxml.jackson.annotation.JsonTypeName;
import org.whispersystems.textsecuregcm.captcha.HCaptchaClient;
@@ -24,10 +25,12 @@ public class HCaptchaConfiguration implements HCaptchaClientFactory {
@JsonProperty
@NotNull
@Valid
CircuitBreakerConfiguration circuitBreaker = new CircuitBreakerConfiguration();
@JsonProperty
@NotNull
@Valid
RetryConfiguration retry = new RetryConfiguration();
@@ -1,20 +0,0 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
public record ProvisioningConfiguration(@Valid @NotNull SingletonRedisClientFactory pubsub,
@Valid @NotNull CircuitBreakerConfiguration circuitBreaker) {
public ProvisioningConfiguration {
if (circuitBreaker == null) {
circuitBreaker = new CircuitBreakerConfiguration();
}
}
}
@@ -13,7 +13,7 @@ import java.time.Duration;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
@JsonTypeName("default")
public class RedisClusterConfiguration implements FaultTolerantRedisClusterFactory {
@@ -58,7 +58,7 @@ public class RedisClusterConfiguration implements FaultTolerantRedisClusterFacto
}
@Override
public FaultTolerantRedisCluster build(final String name, final ClientResources.Builder clientResourcesBuilder) {
return new FaultTolerantRedisCluster(name, this, clientResourcesBuilder);
public FaultTolerantRedisClusterClient build(final String name, final ClientResources.Builder clientResourcesBuilder) {
return new FaultTolerantRedisClusterClient(name, this, clientResourcesBuilder);
}
}
@@ -7,15 +7,16 @@ package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import io.lettuce.core.RedisClient;
import com.google.common.annotations.VisibleForTesting;
import io.lettuce.core.resource.ClientResources;
import java.time.Duration;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import org.whispersystems.textsecuregcm.redis.RedisUriUtil;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
@JsonTypeName("default")
public class RedisConfiguration implements SingletonRedisClientFactory {
public class RedisConfiguration implements FaultTolerantRedisClientFactory {
@JsonProperty
@NotEmpty
@@ -25,20 +26,39 @@ public class RedisConfiguration implements SingletonRedisClientFactory {
@NotNull
private Duration timeout = Duration.ofSeconds(1);
@JsonProperty
@NotNull
@Valid
private CircuitBreakerConfiguration circuitBreaker = new CircuitBreakerConfiguration();
@JsonProperty
@NotNull
@Valid
private RetryConfiguration retry = new RetryConfiguration();
public String getUri() {
return uri;
}
@VisibleForTesting
public void setUri(String uri) {
this.uri = uri;
}
public Duration getTimeout() {
return timeout;
}
@Override
public RedisClient build(final ClientResources clientResources) {
final RedisClient redisClient = RedisClient.create(clientResources,
RedisUriUtil.createRedisUriWithTimeout(uri, timeout));
redisClient.setDefaultTimeout(timeout);
public @NotNull @Valid CircuitBreakerConfiguration getCircuitBreakerConfiguration() {
return circuitBreaker;
}
return redisClient;
public @NotNull @Valid RetryConfiguration getRetryConfiguration() {
return retry;
}
@Override
public FaultTolerantRedisClient build(final String name, final ClientResources clientResources) {
return new FaultTolerantRedisClient(name, this, clientResources.mutate());
}
}
@@ -104,11 +104,13 @@ public class SubscriptionConfiguration {
@JsonIgnore
@ValidationMethod(message = "has a mismatch between the levels supported currencies")
public boolean isCurrencyListSameAcrossAllLevels() {
final Map<Long, SubscriptionLevelConfiguration> subscriptionLevels = Stream
.concat(donationLevels.entrySet().stream(), backupLevels.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
return isCurrencyListSameAccrossLevelConfigurations(donationLevels)
&& isCurrencyListSameAccrossLevelConfigurations(backupLevels);
}
Optional<SubscriptionLevelConfiguration> any = subscriptionLevels.values().stream().findAny();
private static boolean isCurrencyListSameAccrossLevelConfigurations(
Map<Long, ? extends SubscriptionLevelConfiguration> subscriptionLevels) {
Optional<? extends SubscriptionLevelConfiguration> any = subscriptionLevels.values().stream().findAny();
if (any.isEmpty()) {
return true;
}
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.configuration.dynamic;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.validation.Valid;
@@ -71,6 +72,10 @@ public class DynamicConfiguration {
@Valid
DynamicMessagesConfiguration messagesConfiguration = new DynamicMessagesConfiguration();
@JsonProperty
@Valid
List<String> svrStatusCodesToIgnoreForAccountDeletion = Collections.emptyList();
public Optional<DynamicExperimentEnrollmentConfiguration> getExperimentEnrollmentConfiguration(
final String experimentName) {
return Optional.ofNullable(experiments.get(experimentName));
@@ -129,4 +134,8 @@ public class DynamicConfiguration {
return messagesConfiguration;
}
public List<String> getSvrStatusCodesToIgnoreForAccountDeletion() {
return svrStatusCodesToIgnoreForAccountDeletion;
}
}
@@ -26,8 +26,8 @@ public class DynamicExperimentEnrollmentConfiguration {
/**
* What percentage of enrolled UUIDs should the experiment be enabled for.
* <p>
* Unlike {@link this#enrollmentPercentage}, this is not stable by UUID. The same UUID may be
* enrolled/unenrolled across calls.
* Unlike {@link this#enrollmentPercentage}, this is not stable by UUID. The same UUID may be enrolled/unenrolled
* across calls.
*/
@JsonProperty
@Valid
@@ -49,6 +49,14 @@ public class DynamicExperimentEnrollmentConfiguration {
@NotNull
private final UuidSelector uuidSelector = new UuidSelector();
/**
* UUIDs that the experiment should always be disabled for. This takes precedence over uuidSelector.
*/
@Valid
@NotNull
private final Set<UUID> excludedUuids = Collections.emptySet();
/**
* If the UUID is not enrolled via {@link UuidSelector#uuids}, what is the percentage chance it should be enrolled.
* <p>
@@ -67,4 +75,9 @@ public class DynamicExperimentEnrollmentConfiguration {
public UuidSelector getUuidSelector() {
return uuidSelector;
}
public Set<UUID> getExcludedUuids() {
return excludedUuids;
}
}
@@ -120,7 +120,6 @@ public class AccountController {
accounts.updateDevice(account, device.getId(), d -> {
d.setApnId(null);
d.setVoipApnId(null);
d.setGcmId(registrationId.gcmRegistrationId());
d.setFetchesMessages(false);
});
@@ -153,7 +152,6 @@ public class AccountController {
// unconditionally
accounts.updateDevice(account, device.getId(), d -> {
d.setApnId(registrationId.apnRegistrationId());
d.setVoipApnId(registrationId.voipRegistrationId());
d.setGcmId(null);
d.setFetchesMessages(false);
});
@@ -167,7 +165,6 @@ public class AccountController {
accounts.updateDevice(account, device.getId(), d -> {
d.setApnId(null);
d.setVoipApnId(null);
d.setFetchesMessages(false);
if (d.getId() == 1) {
d.setUserAgent("OWI");
@@ -252,6 +249,7 @@ public class AccountController {
auth.getAccount().getNumber(),
auth.getAccount().getPhoneNumberIdentifier(),
auth.getAccount().getUsernameHash().filter(h -> h.length > 0).orElse(null),
auth.getAccount().getUsernameLinkHandle(),
auth.getAccount().isStorageSupported());
}
@@ -150,6 +150,7 @@ public class AccountControllerV2 {
updatedAccount.getNumber(),
updatedAccount.getPhoneNumberIdentifier(),
updatedAccount.getUsernameHash().orElse(null),
updatedAccount.getUsernameLinkHandle(),
updatedAccount.isStorageSupported());
} catch (MismatchedDevicesException e) {
throw new WebApplicationException(Response.status(409)
@@ -208,6 +209,7 @@ public class AccountControllerV2 {
updatedAccount.getNumber(),
updatedAccount.getPhoneNumberIdentifier(),
updatedAccount.getUsernameHash().orElse(null),
updatedAccount.getUsernameLinkHandle(),
updatedAccount.isStorageSupported());
} catch (MismatchedDevicesException e) {
throw new WebApplicationException(Response.status(409)
@@ -32,7 +32,6 @@ import java.util.stream.Stream;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.PositiveOrZero;
import javax.validation.constraints.Size;
@@ -60,13 +59,13 @@ import org.whispersystems.textsecuregcm.backup.BackupManager;
import org.whispersystems.textsecuregcm.backup.CopyParameters;
import org.whispersystems.textsecuregcm.backup.CopyResult;
import org.whispersystems.textsecuregcm.backup.MediaEncryptionParameters;
import org.whispersystems.textsecuregcm.entities.RemoteAttachment;
import org.whispersystems.textsecuregcm.util.BackupAuthCredentialAdapter;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import org.whispersystems.textsecuregcm.util.ByteArrayBase64UrlAdapter;
import org.whispersystems.textsecuregcm.util.ECPublicKeyAdapter;
import org.whispersystems.textsecuregcm.util.ExactlySize;
import org.whispersystems.textsecuregcm.util.Util;
import org.whispersystems.textsecuregcm.util.ValidBase64URLString;
import org.whispersystems.websocket.auth.Mutable;
import org.whispersystems.websocket.auth.ReadOnly;
import reactor.core.publisher.Mono;
@@ -462,16 +461,6 @@ public class ArchiveController {
result.signedUploadLocation()));
}
public record RemoteAttachment(
@Schema(description = "The attachment cdn")
@NotNull
Integer cdn,
@NotBlank
@ValidBase64URLString
@Schema(description = "The attachment key")
String key) {}
public record CopyMediaRequest(
@Schema(description = "The object on the attachment CDN to copy")
@NotNull
@@ -510,7 +499,7 @@ public class ArchiveController {
CopyParameters toCopyParameters() {
return new CopyParameters(
sourceAttachment.cdn, sourceAttachment.key,
sourceAttachment.cdn(), sourceAttachment.key(),
objectLength,
new MediaEncryptionParameters(encryptionKey, hmacKey, iv),
mediaId);
@@ -1,84 +0,0 @@
/*
* Copyright 2013 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.controllers;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.net.HttpHeaders;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.security.SecureRandom;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.entities.AttachmentDescriptorV2;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.s3.PolicySigner;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.util.Conversions;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.websocket.auth.ReadOnly;
// To be removed when Android 7.12 reaches saturation, likely some time toward the end of October 2024
@Deprecated(forRemoval = true)
@Path("/v2/attachments")
@Tag(name = "Attachments")
public class AttachmentControllerV2 {
private final PostPolicyGenerator policyGenerator;
private final PolicySigner policySigner;
private final RateLimiter rateLimiter;
private static final String CREATE_UPLOAD_COUNTER_NAME = name(AttachmentControllerV2.class, "uploadForm");
public AttachmentControllerV2(RateLimiters rateLimiters, String accessKey, String accessSecret, String region,
String bucket) {
this.rateLimiter = rateLimiters.getAttachmentLimiter();
this.policyGenerator = new PostPolicyGenerator(region, bucket, accessKey);
this.policySigner = new PolicySigner(accessSecret, region);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/form/upload")
public AttachmentDescriptorV2 getAttachmentUploadForm(
@ReadOnly @Auth AuthenticatedDevice auth,
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent)
throws RateLimitExceededException {
rateLimiter.validate(auth.getAccount().getUuid());
ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
long attachmentId = generateAttachmentId();
String objectName = String.valueOf(attachmentId);
Pair<String, String> policy = policyGenerator.createFor(now, objectName, 100 * 1024 * 1024);
String signature = policySigner.getSignature(now, policy.second());
Metrics.counter(CREATE_UPLOAD_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent))).increment();
return new AttachmentDescriptorV2(attachmentId, objectName, policy.first(),
"private", "AWS4-HMAC-SHA256",
now.format(PostPolicyGenerator.AWS_DATE_TIME),
policy.second(), signature);
}
private long generateAttachmentId() {
byte[] attachmentBytes = new byte[8];
new SecureRandom().nextBytes(attachmentBytes);
attachmentBytes[0] = (byte) (attachmentBytes[0] & 0x7F);
return Conversions.byteArrayToLong(attachmentBytes);
}
}
@@ -1,66 +0,0 @@
/*
* Copyright 2013 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.controllers;
import io.dropwizard.auth.Auth;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;
import javax.annotation.Nonnull;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
import org.whispersystems.textsecuregcm.attachments.GcsAttachmentGenerator;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.entities.AttachmentDescriptorV3;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.websocket.auth.ReadOnly;
// To be removed when Desktop 7.17 reaches saturation, likely some time toward the end of October 2024
@Deprecated(forRemoval = true)
@Path("/v3/attachments")
@Tag(name = "Attachments")
public class AttachmentControllerV3 {
@Nonnull
private final RateLimiter rateLimiter;
@Nonnull
private final GcsAttachmentGenerator gcsAttachmentGenerator;
@Nonnull
private final SecureRandom secureRandom;
public AttachmentControllerV3(@Nonnull RateLimiters rateLimiters, @Nonnull GcsAttachmentGenerator gcsAttachmentGenerator)
throws IOException, InvalidKeyException, InvalidKeySpecException {
this.rateLimiter = rateLimiters.getAttachmentLimiter();
this.gcsAttachmentGenerator = gcsAttachmentGenerator;
this.secureRandom = new SecureRandom();
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/form/upload")
public AttachmentDescriptorV3 getAttachmentUploadForm(@ReadOnly @Auth AuthenticatedDevice auth)
throws RateLimitExceededException {
rateLimiter.validate(auth.getAccount().getUuid());
final String key = generateAttachmentKey();
final AttachmentGenerator.Descriptor descriptor = this.gcsAttachmentGenerator.generateAttachment(key);
return new AttachmentDescriptorV3(2, key, descriptor.headers(), descriptor.signedUploadLocation());
}
private String generateAttachmentKey() {
final byte[] bytes = new byte[15];
secureRandom.nextBytes(bytes);
return Base64.getUrlEncoder().encodeToString(bytes);
}
}
@@ -30,7 +30,8 @@ import org.whispersystems.websocket.auth.ReadOnly;
/**
* The V4 API is identical to the {@link AttachmentControllerV3} API, but supports an additional TUS based cdn type (cdn3)
* The attachment controller generates "upload forms" for authenticated users that permit them to upload files
* (message attachments) to a remote storage location. The location may be selected by the server at runtime.
*/
@Path("/v4/attachments")
@Tag(name = "Attachments")
@@ -35,7 +35,7 @@ import org.whispersystems.websocket.auth.ReadOnly;
@io.swagger.v3.oas.annotations.tags.Tag(name = "Calling")
public class CallRoutingController {
private static final int TURN_INSTANCE_LIMIT = 3;
private static final int TURN_INSTANCE_LIMIT = 2;
private static final Counter INVALID_IP_COUNTER = Metrics.counter(name(CallRoutingController.class, "invalidIP"));
private static final Logger log = LoggerFactory.getLogger(CallRoutingController.class);
private final RateLimiters rateLimiters;
@@ -79,7 +79,7 @@ public class CallRoutingController {
UUID aci = auth.getAccount().getUuid();
rateLimiters.getCallEndpointLimiter().validate(aci);
if (experimentEnrollmentManager.isEnrolled(aci, "cloudflareTurn")) {
if (experimentEnrollmentManager.isEnrolled(auth.getAccount().getNumber(), aci, "cloudflareTurn")) {
return cloudflareTurnCredentialsManager.retrieveFromCloudflare();
}
@@ -8,8 +8,10 @@ package org.whispersystems.textsecuregcm.controllers;
import static com.codahale.metrics.MetricRegistry.name;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.net.HttpHeaders;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.security.InvalidKeyException;
import java.time.Clock;
@@ -23,12 +25,11 @@ import javax.annotation.Nonnull;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
import org.signal.libsignal.zkgroup.auth.AuthCredentialWithPniResponse;
@@ -38,7 +39,7 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
import org.whispersystems.textsecuregcm.entities.DeliveryCertificate;
import org.whispersystems.textsecuregcm.entities.GroupCredentials;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.websocket.auth.ReadOnly;
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@@ -55,6 +56,8 @@ public class CertificateController {
public static final Duration MAX_REDEMPTION_DURATION = Duration.ofDays(7);
private static final String GENERATE_DELIVERY_CERTIFICATE_COUNTER_NAME = name(CertificateGenerator.class, "generateCertificate");
private static final String INCLUDE_E164_TAG_NAME = "includeE164";
private static final String GET_GROUP_AUTHENTICATION_CREDENTIALS_COUNTER_NAME = name(CertificateController.class,
"getGroupAuthenticationCredentials");
public CertificateController(
@Nonnull CertificateGenerator certificateGenerator,
@@ -74,10 +77,6 @@ public class CertificateController {
@QueryParam("includeE164") @DefaultValue("true") boolean includeE164)
throws InvalidKeyException {
if (auth.getAccount().getIdentityKey(IdentityType.ACI) == null) {
throw new WebApplicationException(Response.Status.BAD_REQUEST);
}
Metrics.counter(GENERATE_DELIVERY_CERTIFICATE_COUNTER_NAME, INCLUDE_E164_TAG_NAME, String.valueOf(includeE164))
.increment();
@@ -90,6 +89,7 @@ public class CertificateController {
@Path("/auth/group")
public GroupCredentials getGroupAuthenticationCredentials(
@ReadOnly @Auth AuthenticatedDevice auth,
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent,
@QueryParam("redemptionStartSeconds") long startSeconds,
@QueryParam("redemptionEndSeconds") long endSeconds,
@QueryParam("zkcCredential") boolean zkcCredential) {
@@ -107,6 +107,11 @@ public class CertificateController {
throw new BadRequestException();
}
Metrics
.counter(GET_GROUP_AUTHENTICATION_CREDENTIALS_COUNTER_NAME,
Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)).and("zkcCredential", String.valueOf(zkcCredential)))
.increment();
final List<GroupCredentials.GroupCredential> credentials = new ArrayList<>();
final List<GroupCredentials.CallLinkAuthCredential> callLinkAuthCredentials = new ArrayList<>();
@@ -66,16 +66,14 @@ public class ChallengeController {
summary = "Submit proof of a challenge completion",
description = """
Some server endpoints (the "send message" endpoint, for example) may return a 428 response indicating the client must complete a challenge before continuing.
Clients may use this endpoint to provide proof of a completed challenge. If successful, the client may then
Clients may use this endpoint to provide proof of a completed challenge. If successful, the client may then
continue their original operation.
""",
requestBody = @RequestBody(content = {@Content(schema = @Schema(oneOf = {AnswerPushChallengeRequest.class,
AnswerCaptchaChallengeRequest.class}))})
)
@ApiResponse(responseCode = "200", description = "Indicates the challenge proof was accepted")
@ApiResponse(responseCode = "413", description = "Too many attempts", headers = @Header(
name = "Retry-After",
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
@ApiResponse(responseCode = "428", description = "Submitted captcha token is invalid")
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
name = "Retry-After",
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
@@ -7,33 +7,33 @@ 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.SetArgs;
import io.lettuce.core.RedisException;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.Timer;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.headers.Header;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
import java.util.LinkedList;
import java.util.EnumMap;
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.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Nullable;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.ForbiddenException;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
@@ -41,10 +41,12 @@ import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.glassfish.jersey.server.ContainerRequest;
import org.whispersystems.textsecuregcm.auth.LinkedDeviceRefreshRequirementProvider;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
@@ -54,20 +56,30 @@ import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.entities.DeviceActivationRequest;
import org.whispersystems.textsecuregcm.entities.DeviceInfo;
import org.whispersystems.textsecuregcm.entities.DeviceInfoList;
import org.whispersystems.textsecuregcm.entities.DeviceResponse;
import org.whispersystems.textsecuregcm.entities.LinkDeviceResponse;
import org.whispersystems.textsecuregcm.entities.LinkDeviceRequest;
import org.whispersystems.textsecuregcm.entities.PreKeySignatureValidator;
import org.whispersystems.textsecuregcm.entities.ProvisioningMessage;
import org.whispersystems.textsecuregcm.entities.RemoteAttachment;
import org.whispersystems.textsecuregcm.entities.SetPublicKeyRequest;
import org.whispersystems.textsecuregcm.entities.TransferArchiveUploadedRequest;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.ClientPublicKeysManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.Device.DeviceCapabilities;
import org.whispersystems.textsecuregcm.storage.DeviceSpec;
import org.whispersystems.textsecuregcm.util.VerificationCode;
import org.whispersystems.textsecuregcm.storage.LinkDeviceTokenAlreadyUsedException;
import org.whispersystems.textsecuregcm.util.EnumMapUtil;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.LinkDeviceToken;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
import org.whispersystems.websocket.auth.Mutable;
import org.whispersystems.websocket.auth.ReadOnly;
@@ -77,56 +89,54 @@ public class DeviceController {
static final int MAX_DEVICES = 6;
private final Key verificationTokenKey;
private final AccountsManager accounts;
private final ClientPublicKeysManager clientPublicKeysManager;
private final RateLimiters rateLimiters;
private final FaultTolerantRedisCluster usedTokenCluster;
private final Map<String, Integer> maxDeviceConfiguration;
private final Clock clock;
private final EnumMap<ClientPlatform, AtomicInteger> linkedDeviceListenersByPlatform;
private final AtomicInteger linkedDeviceListenersForUnrecognizedPlatforms;
private static final String VERIFICATION_TOKEN_ALGORITHM = "HmacSHA256";
private static final String LINKED_DEVICE_LISTENER_GAUGE_NAME =
MetricsUtil.name(DeviceController.class, "linkedDeviceListeners");
private static final String WAIT_FOR_LINKED_DEVICE_TIMER_NAME =
MetricsUtil.name(DeviceController.class, "waitForLinkedDeviceDuration");
@VisibleForTesting
static final Duration TOKEN_EXPIRATION_DURATION = Duration.ofMinutes(10);
static final int MIN_TOKEN_IDENTIFIER_LENGTH = 32;
@VisibleForTesting
static final int MAX_TOKEN_IDENTIFIER_LENGTH = 64;
public DeviceController(final AccountsManager accounts,
final ClientPublicKeysManager clientPublicKeysManager,
final RateLimiters rateLimiters,
final Map<String, Integer> maxDeviceConfiguration) {
public DeviceController(byte[] linkDeviceSecret,
AccountsManager accounts,
ClientPublicKeysManager clientPublicKeysManager,
RateLimiters rateLimiters,
FaultTolerantRedisCluster usedTokenCluster,
Map<String, Integer> maxDeviceConfiguration, final Clock clock) {
this.verificationTokenKey = new SecretKeySpec(linkDeviceSecret, VERIFICATION_TOKEN_ALGORITHM);
this.accounts = accounts;
this.clientPublicKeysManager = clientPublicKeysManager;
this.rateLimiters = rateLimiters;
this.usedTokenCluster = usedTokenCluster;
this.maxDeviceConfiguration = maxDeviceConfiguration;
this.clock = clock;
// Fail fast: reject bad keys
try {
final Mac mac = Mac.getInstance(VERIFICATION_TOKEN_ALGORITHM);
mac.init(verificationTokenKey);
} catch (final NoSuchAlgorithmException e) {
throw new AssertionError("All Java implementations must support HmacSHA256", e);
} catch (final InvalidKeyException e) {
throw new IllegalArgumentException(e);
}
linkedDeviceListenersByPlatform =
EnumMapUtil.toEnumMap(ClientPlatform.class, clientPlatform -> buildGauge(clientPlatform.name().toLowerCase()));
linkedDeviceListenersForUnrecognizedPlatforms = buildGauge("unknown");
}
private static AtomicInteger buildGauge(final String clientPlatformName) {
return Metrics.gauge(LINKED_DEVICE_LISTENER_GAUGE_NAME,
Tags.of(io.micrometer.core.instrument.Tag.of(UserAgentTagUtil.PLATFORM_TAG, clientPlatformName)),
new AtomicInteger(0));
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public DeviceInfoList getDevices(@ReadOnly @Auth AuthenticatedDevice auth) {
List<DeviceInfo> devices = new LinkedList<>();
for (Device device : auth.getAccount().getDevices()) {
devices.add(new DeviceInfo(device.getId(), device.getName(),
device.getLastSeen(), device.getCreated()));
}
return new DeviceInfoList(devices);
return new DeviceInfoList(auth.getAccount().getDevices().stream()
.map(DeviceInfo::forDevice)
.toList());
}
@DELETE
@@ -146,10 +156,35 @@ public class DeviceController {
accounts.removeDevice(auth.getAccount(), deviceId).join();
}
/**
* Generates a signed device-linking token. Generally, primary devices will include the signed device-linking token in
* a provisioning message to a new device, and then the new device will include the token in its request to
* {@link #linkDevice(BasicAuthorizationHeader, String, LinkDeviceRequest, ContainerRequest)}.
*
* @param auth the authenticated account/device
*
* @return a signed device-linking token
*
* @throws RateLimitExceededException if the caller has made too many calls to this method in a set amount of time
* @throws DeviceLimitExceededException if the authenticated account has already reached the maximum number of linked
* devices
*
* @see ProvisioningController#sendProvisioningMessage(AuthenticatedDevice, String, ProvisioningMessage, String)
*/
@GET
@Path("/provisioning/code")
@Produces(MediaType.APPLICATION_JSON)
public VerificationCode createDeviceToken(@ReadOnly @Auth AuthenticatedDevice auth)
@Operation(
summary = "Generate a signed device-linking token",
description = """
Generate a signed device-linking token for transmission to a pending linked device via a provisioning message.
""")
@ApiResponse(responseCode="200", description="Token was generated successfully", useReturnTypeSchema=true)
@ApiResponse(responseCode = "411", description = "The authenticated account already has the maximum allowed number of linked devices")
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
name = "Retry-After",
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
public LinkDeviceToken createDeviceToken(@ReadOnly @Auth AuthenticatedDevice auth)
throws RateLimitExceededException, DeviceLimitExceededException {
final Account account = auth.getAccount();
@@ -170,7 +205,9 @@ public class DeviceController {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
return new VerificationCode(generateVerificationToken(account.getUuid()));
final String token = accounts.generateLinkDeviceToken(account.getUuid());
return new LinkDeviceToken(token, AccountsManager.getLinkDeviceTokenIdentifier(token));
}
@PUT
@@ -190,13 +227,13 @@ public class DeviceController {
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
name = "Retry-After",
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
public DeviceResponse linkDevice(@HeaderParam(HttpHeaders.AUTHORIZATION) BasicAuthorizationHeader authorizationHeader,
public LinkDeviceResponse linkDevice(@HeaderParam(HttpHeaders.AUTHORIZATION) BasicAuthorizationHeader authorizationHeader,
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable String userAgent,
@NotNull @Valid LinkDeviceRequest linkDeviceRequest,
@Context ContainerRequest containerRequest)
throws RateLimitExceededException, DeviceLimitExceededException {
final Account account = checkVerificationToken(linkDeviceRequest.verificationCode())
final Account account = accounts.checkDeviceLinkingToken(linkDeviceRequest.verificationCode())
.flatMap(accounts::getByAccountIdentifier)
.orElseThrow(ForbiddenException::new);
@@ -248,27 +285,110 @@ public class DeviceController {
signalAgent = "OWD";
}
return accounts.addDevice(account, new DeviceSpec(accountAttributes.getName(),
authorizationHeader.getPassword(),
signalAgent,
capabilities,
accountAttributes.getRegistrationId(),
accountAttributes.getPhoneNumberIdentityRegistrationId(),
accountAttributes.getFetchesMessages(),
deviceActivationRequest.apnToken(),
deviceActivationRequest.gcmToken(),
deviceActivationRequest.aciSignedPreKey(),
deviceActivationRequest.pniSignedPreKey(),
deviceActivationRequest.aciPqLastResortPreKey(),
deviceActivationRequest.pniPqLastResortPreKey()))
.thenCompose(a -> usedTokenCluster.withCluster(connection -> connection.async()
.set(getUsedTokenKey(linkDeviceRequest.verificationCode()), "", new SetArgs().ex(TOKEN_EXPIRATION_DURATION)))
.thenApply(ignored -> a))
.thenApply(accountAndDevice -> new DeviceResponse(
accountAndDevice.first().getIdentifier(IdentityType.ACI),
accountAndDevice.first().getIdentifier(IdentityType.PNI),
accountAndDevice.second().getId()))
.join();
try {
return accounts.addDevice(account, new DeviceSpec(accountAttributes.getName(),
authorizationHeader.getPassword(),
signalAgent,
capabilities,
accountAttributes.getRegistrationId(),
accountAttributes.getPhoneNumberIdentityRegistrationId(),
accountAttributes.getFetchesMessages(),
deviceActivationRequest.apnToken(),
deviceActivationRequest.gcmToken(),
deviceActivationRequest.aciSignedPreKey(),
deviceActivationRequest.pniSignedPreKey(),
deviceActivationRequest.aciPqLastResortPreKey(),
deviceActivationRequest.pniPqLastResortPreKey()),
linkDeviceRequest.verificationCode())
.thenApply(accountAndDevice -> new LinkDeviceResponse(
accountAndDevice.first().getIdentifier(IdentityType.ACI),
accountAndDevice.first().getIdentifier(IdentityType.PNI),
accountAndDevice.second().getId()))
.join();
} catch (final CompletionException e) {
if (e.getCause() instanceof LinkDeviceTokenAlreadyUsedException) {
throw new ForbiddenException();
}
throw e;
}
}
@GET
@Path("/wait_for_linked_device/{tokenIdentifier}")
@Produces(MediaType.APPLICATION_JSON)
@Operation(summary = "Wait for a new device to be linked to an account",
description = """
Waits for a new device to be linked to an account and returns basic information about the new device when
available.
""")
@ApiResponse(responseCode = "200", description = "A device was linked to an account using the token associated with the given token identifier",
content = @Content(schema = @Schema(implementation = DeviceInfo.class)))
@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(
@ReadOnly @Auth final AuthenticatedDevice authenticatedDevice,
@PathParam("tokenIdentifier")
@Schema(description = "A 'link device' token identifier provided by the 'create link device token' endpoint")
@Size(min = MIN_TOKEN_IDENTIFIER_LENGTH, max = MAX_TOKEN_IDENTIFIER_LENGTH)
final String tokenIdentifier,
@QueryParam("timeout")
@DefaultValue("30")
@Min(1)
@Max(3600)
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED,
minimum = "1",
maximum = "3600",
description = """
The amount of time (in seconds) to wait for a response. If the expected device is not linked within the
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));
final AtomicInteger linkedDeviceListenerCounter = getCounterForLinkedDeviceListeners(userAgent);
linkedDeviceListenerCounter.incrementAndGet();
final Timer.Sample sample = Timer.start();
try {
return accounts.waitForNewLinkedDevice(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;
}
}
private AtomicInteger getCounterForLinkedDeviceListeners(final String userAgent) {
try {
return linkedDeviceListenersByPlatform.get(UserAgentUtil.parseUserAgentString(userAgent).getPlatform());
} catch (final UnrecognizedUserAgentException ignored) {
return linkedDeviceListenersForUnrecognizedPlatforms;
}
}
@PUT
@@ -310,87 +430,6 @@ public class DeviceController {
setPublicKeyRequest.publicKey());
}
private Mac getInitializedMac() {
try {
final Mac mac = Mac.getInstance(VERIFICATION_TOKEN_ALGORITHM);
mac.init(verificationTokenKey);
return mac;
} catch (final NoSuchAlgorithmException | InvalidKeyException e) {
// All Java implementations must support HmacSHA256 and we checked the key at construction time, so this can never
// happen
throw new AssertionError(e);
}
}
@VisibleForTesting
String generateVerificationToken(final UUID aci) {
final String claims = aci + "." + clock.instant().toEpochMilli();
final byte[] signature = getInitializedMac().doFinal(claims.getBytes(StandardCharsets.UTF_8));
return claims + ":" + Base64.getUrlEncoder().encodeToString(signature);
}
@VisibleForTesting
Optional<UUID> checkVerificationToken(final String verificationToken) {
final boolean tokenUsed = usedTokenCluster.withCluster(connection ->
connection.sync().get(getUsedTokenKey(verificationToken)) != null);
if (tokenUsed) {
return Optional.empty();
}
final String[] claimsAndSignature = verificationToken.split(":", 2);
if (claimsAndSignature.length != 2) {
return Optional.empty();
}
final byte[] expectedSignature = getInitializedMac().doFinal(
claimsAndSignature[0].getBytes(StandardCharsets.UTF_8));
final byte[] providedSignature;
try {
providedSignature = Base64.getUrlDecoder().decode(claimsAndSignature[1]);
} catch (final IllegalArgumentException e) {
return Optional.empty();
}
if (!MessageDigest.isEqual(expectedSignature, providedSignature)) {
return Optional.empty();
}
final String[] aciAndTimestamp = claimsAndSignature[0].split("\\.", 2);
if (aciAndTimestamp.length != 2) {
return Optional.empty();
}
final UUID aci;
try {
aci = UUID.fromString(aciAndTimestamp[0]);
} catch (final IllegalArgumentException e) {
return Optional.empty();
}
final Instant timestamp;
try {
timestamp = Instant.ofEpochMilli(Long.parseLong(aciAndTimestamp[1]));
} catch (final NumberFormatException e) {
return Optional.empty();
}
final Instant tokenExpiration = timestamp.plus(TOKEN_EXPIRATION_DURATION);
if (tokenExpiration.isBefore(clock.instant())) {
return Optional.empty();
}
return Optional.of(aci);
}
private static boolean isCapabilityDowngrade(Account account, DeviceCapabilities capabilities) {
boolean isDowngrade = false;
isDowngrade |= account.isDeleteSyncSupported() && !capabilities.deleteSync();
@@ -398,7 +437,65 @@ public class DeviceController {
return isDowngrade;
}
private static String getUsedTokenKey(final String token) {
return "usedToken::" + token;
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/transfer_archive")
@Operation(
summary = "Signals that a transfer archive has been uploaded for a specific linked device",
description = """
Signals that a transfer archive has been uploaded for a specific linked device. Devices waiting via the "wait
for transfer archive" endpoint will be notified that the new archive is available.
""")
@ApiResponse(responseCode = "204", description = "Success")
@ApiResponse(responseCode = "422", description = "The request object could not be parsed or was otherwise invalid")
@ApiResponse(responseCode = "429", description = "Rate-limited; try again after the prescribed delay")
public CompletionStage<Void> recordTransferArchiveUploaded(@ReadOnly @Auth final AuthenticatedDevice authenticatedDevice,
@NotNull @Valid final TransferArchiveUploadedRequest transferArchiveUploadedRequest) {
return rateLimiters.getUploadTransferArchiveLimiter().validateAsync(authenticatedDevice.getAccount().getIdentifier(IdentityType.ACI))
.thenCompose(ignored -> accounts.recordTransferArchiveUpload(authenticatedDevice.getAccount(),
transferArchiveUploadedRequest.destinationDeviceId(),
Instant.ofEpochMilli(transferArchiveUploadedRequest.destinationDeviceCreated()),
transferArchiveUploadedRequest.transferArchive()));
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/transfer_archive")
@Operation(summary = "Wait for a new transfer archive to be uploaded",
description = """
Waits for a new transfer archive to be uploaded for the authenticated device and returns the location of the
archive when available.
""")
@ApiResponse(responseCode = "200", description = "A new transfer archive was uploaded for the authenticated device",
content = @Content(schema = @Schema(implementation = RemoteAttachment.class)))
@ApiResponse(responseCode = "204", description = "No transfer archive was uploaded before the call completed; clients may repeat the call to continue waiting")
@ApiResponse(responseCode = "400", description = "The given timeout was invalid")
@ApiResponse(responseCode = "429", description = "Rate-limited; try again after the prescribed delay")
public CompletionStage<Response> waitForTransferArchive(@ReadOnly @Auth final AuthenticatedDevice authenticatedDevice,
@QueryParam("timeout")
@DefaultValue("30")
@Min(1)
@Max(3600)
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED,
minimum = "1",
maximum = "3600",
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 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()));
}
}
@@ -10,7 +10,10 @@ import static com.codahale.metrics.MetricRegistry.name;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.Timer;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
@@ -33,8 +36,9 @@ public class KeepAliveController {
private final ClientPresenceManager clientPresenceManager;
private static final String NO_LOCAL_SUBSCRIPTION_COUNTER_NAME = name(KeepAliveController.class,
"noLocalSubscription");
private static final String CLOSED_CONNECTION_AGE_DISTRIBUTION_NAME = name(KeepAliveController.class,
"closedConnectionAge");
public KeepAliveController(final ClientPresenceManager clientPresenceManager) {
this.clientPresenceManager = clientPresenceManager;
@@ -46,16 +50,20 @@ public class KeepAliveController {
maybeAuth.ifPresent(auth -> {
if (!clientPresenceManager.isLocallyPresent(auth.getAccount().getUuid(), auth.getAuthenticatedDevice().getId())) {
final Duration age = Duration.between(context.getClient().getCreated(), Instant.now());
logger.debug("***** No local subscription found for {}::{}; age = {}ms, User-Agent = {}",
auth.getAccount().getUuid(), auth.getAuthenticatedDevice().getId(),
System.currentTimeMillis() - context.getClient().getCreatedTimestamp(),
auth.getAccount().getUuid(), auth.getAuthenticatedDevice().getId(), age.toMillis(),
context.getClient().getUserAgent());
context.getClient().close(1000, "OK");
Metrics.counter(NO_LOCAL_SUBSCRIPTION_COUNTER_NAME,
Tags.of(UserAgentTagUtil.getPlatformTag(context.getClient().getUserAgent())))
.increment();
Timer.builder(CLOSED_CONNECTION_AGE_DISTRIBUTION_NAME)
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(context.getClient().getUserAgent())))
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry)
.record(age);
}
});
@@ -13,7 +13,7 @@ import io.grpc.StatusRuntimeException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import katie.MonitorKey;
import org.signal.keytransparency.client.MonitorKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
@@ -55,6 +55,7 @@ import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.NotAuthorizedException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.POST;
@@ -115,7 +116,6 @@ import org.whispersystems.textsecuregcm.push.MessageSender;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
import org.whispersystems.textsecuregcm.push.ReceiptSender;
import org.whispersystems.textsecuregcm.spam.ReportSpamTokenProvider;
import org.whispersystems.textsecuregcm.spam.SpamChecker;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
@@ -162,7 +162,6 @@ public class MessageController {
private final ReportMessageManager reportMessageManager;
private final ExecutorService multiRecipientMessageExecutor;
private final Scheduler messageDeliveryScheduler;
private final ReportSpamTokenProvider reportSpamTokenProvider;
private final ClientReleaseManager clientReleaseManager;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private final ServerSecretParams serverSecretParams;
@@ -182,10 +181,7 @@ public class MessageController {
private static final String RATE_LIMITED_MESSAGE_COUNTER_NAME = name(MessageController.class, "rateLimitedMessage");
private static final String REJECT_INVALID_ENVELOPE_TYPE = name(MessageController.class, "rejectInvalidEnvelopeType");
private static final Timer SEND_MESSAGE_LATENCY_TIMER =
Timer.builder(MetricsUtil.name(MessageController.class, "sendMessageLatency"))
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry);
private static final String SEND_MESSAGE_LATENCY_TIMER_NAME = MetricsUtil.name(MessageController.class, "sendMessageLatency");
private static final String EPHEMERAL_TAG_NAME = "ephemeral";
private static final String SENDER_TYPE_TAG_NAME = "senderType";
@@ -225,7 +221,6 @@ public class MessageController {
ReportMessageManager reportMessageManager,
@Nonnull ExecutorService multiRecipientMessageExecutor,
Scheduler messageDeliveryScheduler,
@Nonnull ReportSpamTokenProvider reportSpamTokenProvider,
final ClientReleaseManager clientReleaseManager,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final ServerSecretParams serverSecretParams,
@@ -244,7 +239,6 @@ public class MessageController {
this.reportMessageManager = reportMessageManager;
this.multiRecipientMessageExecutor = Objects.requireNonNull(multiRecipientMessageExecutor);
this.messageDeliveryScheduler = messageDeliveryScheduler;
this.reportSpamTokenProvider = reportSpamTokenProvider;
this.clientReleaseManager = clientReleaseManager;
this.dynamicConfigurationManager = dynamicConfigurationManager;
this.serverSecretParams = serverSecretParams;
@@ -254,7 +248,6 @@ public class MessageController {
this.clock = clock;
}
@Timed
@Path("/{destination}")
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@@ -279,77 +272,67 @@ public class MessageController {
@ApiResponse(
responseCode = "410", description = "Mismatched registration ids supplied for some recipient devices",
content = @Content(schema = @Schema(implementation = AccountStaleDevices[].class)))
public Response sendMessage(@ReadOnly @Auth Optional<AuthenticatedDevice> source,
public Response sendMessage(@ReadOnly @Auth final Optional<AuthenticatedDevice> source,
@Parameter(description="The recipient's unidentified access key")
@HeaderParam(HeaderUtils.UNIDENTIFIED_ACCESS_KEY) Optional<Anonymous> accessKey,
@HeaderParam(HeaderUtils.UNIDENTIFIED_ACCESS_KEY) final Optional<Anonymous> accessKey,
@Parameter(description="A group send endorsement token covering the recipient. Must not be combined with `Unidentified-Access-Key` or set on a story message.")
@HeaderParam(HeaderUtils.GROUP_SEND_TOKEN)
@Nullable GroupSendTokenHeader groupSendToken,
@Nullable final GroupSendTokenHeader groupSendToken,
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@Parameter(description="If true, deliver the message only to recipients that are online when it is sent")
@PathParam("destination") ServiceIdentifier destinationIdentifier,
@PathParam("destination") final ServiceIdentifier destinationIdentifier,
@Parameter(description="If true, the message is a story; access tokens are not checked and sending to nonexistent recipients is permitted")
@QueryParam("story") boolean isStory,
@QueryParam("story") final boolean isStory,
@Parameter(description="The encrypted message payloads for each recipient device")
@NotNull @Valid IncomingMessageList messages,
@NotNull @Valid final IncomingMessageList messages,
@Context ContainerRequestContext context) throws RateLimitExceededException {
@Context final ContainerRequestContext context) throws RateLimitExceededException {
if (source.isEmpty() && accessKey.isEmpty() && groupSendToken == null && !isStory) {
throw new WebApplicationException(Status.UNAUTHORIZED);
}
if (groupSendToken != null) {
if (source.isPresent() || accessKey.isPresent()) {
throw new BadRequestException(
"Group send endorsement tokens should not be combined with other authentication");
} else if (isStory) {
throw new BadRequestException("Group send endorsement tokens should not be sent for story messages");
}
}
final String senderType = source.map(
s -> s.getAccount().isIdentifiedBy(destinationIdentifier) ? SENDER_TYPE_SELF : SENDER_TYPE_IDENTIFIED)
.orElse(SENDER_TYPE_UNIDENTIFIED);
final Sample sample = Timer.start();
try {
if (source.isEmpty() && accessKey.isEmpty() && groupSendToken == null && !isStory) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
if (groupSendToken != null) {
if (!source.isEmpty() || !accessKey.isEmpty()) {
throw new BadRequestException(
"Group send endorsement tokens should not be combined with other authentication");
} else if (isStory) {
throw new BadRequestException("Group send endorsement tokens should not be sent for story messages");
}
}
final String senderType;
if (source.isPresent()) {
if (source.get().getAccount().isIdentifiedBy(destinationIdentifier)) {
senderType = SENDER_TYPE_SELF;
} else {
senderType = SENDER_TYPE_IDENTIFIED;
}
} else {
senderType = SENDER_TYPE_UNIDENTIFIED;
}
boolean isSyncMessage = source.isPresent() && source.get().getAccount().isIdentifiedBy(destinationIdentifier);
final boolean isSyncMessage = senderType.equals(SENDER_TYPE_SELF);
if (isSyncMessage && destinationIdentifier.identityType() == IdentityType.PNI) {
throw new WebApplicationException(Status.FORBIDDEN);
}
Optional<Account> destination;
final Optional<Account> destination;
if (!isSyncMessage) {
destination = accountsManager.getByServiceIdentifier(destinationIdentifier);
} else {
destination = source.map(AuthenticatedDevice::getAccount);
}
final Optional<Response> spamCheck = spamChecker.checkForSpam(
context, source.map(AuthenticatedDevice::getAccount), destination);
if (spamCheck.isPresent()) {
return spamCheck.get();
final SpamChecker.SpamCheckResult spamCheck = spamChecker.checkForSpam(
context, source, destination, Optional.of(destinationIdentifier));
final Optional<byte[]> reportSpamToken;
switch (spamCheck) {
case final SpamChecker.Spam spam: return spam.response();
case final SpamChecker.NotSpam notSpam: reportSpamToken = notSpam.token();
}
final Optional<byte[]> spamReportToken = switch (senderType) {
case SENDER_TYPE_IDENTIFIED -> reportSpamTokenProvider.makeReportSpamToken(context, source.get(), destination);
default -> Optional.empty();
};
int totalContentLength = 0;
for (final IncomingMessage message : messages.messages()) {
@@ -387,7 +370,7 @@ public class MessageController {
destinationIdentifier);
}
boolean needsSync = !isSyncMessage && source.isPresent() && source.get().getAccount().getDevices().size() > 1;
final boolean needsSync = !isSyncMessage && source.isPresent() && source.get().getAccount().getDevices().size() > 1;
// 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
@@ -444,41 +427,43 @@ public class MessageController {
Tag.of(AUTH_TYPE_TAG_NAME, authType),
Tag.of(IDENTITY_TYPE_TAG_NAME, destinationIdentifier.identityType().name()));
for (IncomingMessage incomingMessage : messages.messages()) {
Optional<Device> destinationDevice = destination.get().getDevice(incomingMessage.destinationDeviceId());
if (destinationDevice.isPresent()) {
Metrics.counter(SENT_MESSAGE_COUNTER_NAME, tags).increment();
sendIndividualMessage(
source,
destination.get(),
destinationDevice.get(),
destinationIdentifier,
messages.timestamp(),
messages.online(),
isStory,
messages.urgent(),
incomingMessage,
userAgent,
spamReportToken);
}
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);
});
}
return Response.ok(new SendMessageResponse(needsSync)).build();
} catch (MismatchedDevicesException e) {
} catch (final MismatchedDevicesException e) {
throw new WebApplicationException(Response.status(409)
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new MismatchedDevices(e.getMissingDevices(),
e.getExtraDevices()))
.build());
} catch (StaleDevicesException e) {
} catch (final StaleDevicesException e) {
throw new WebApplicationException(Response.status(410)
.type(MediaType.APPLICATION_JSON)
.entity(new StaleDevices(e.getStaleDevices()))
.build());
}
} finally {
sample.stop(SEND_MESSAGE_LATENCY_TIMER);
sample.stop(Timer.builder(SEND_MESSAGE_LATENCY_TIMER_NAME)
.tags(SENDER_TYPE_TAG_NAME, senderType)
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry));
}
}
@@ -562,9 +547,9 @@ public class MessageController {
@Context ContainerRequestContext context) throws RateLimitExceededException {
final Optional<Response> spamCheck = spamChecker.checkForSpam(context, Optional.empty(), Optional.empty());
if (spamCheck.isPresent()) {
return spamCheck.get();
final SpamChecker.SpamCheckResult spamCheck = spamChecker.checkForSpam(context, Optional.empty(), Optional.empty(), Optional.empty());
if (spamCheck instanceof final SpamChecker.Spam spam) {
return spam.response();
}
if (groupSendToken == null && accessKeys == null && !isStory) {
@@ -705,13 +690,13 @@ public class MessageController {
.get();
} catch (InterruptedException e) {
logger.error("interrupted while delivering multi-recipient messages", e);
return Response.serverError().entity("interrupted during delivery").build();
throw new InternalServerErrorException("interrupted during delivery");
} catch (CancellationException e) {
logger.error("cancelled while delivering multi-recipient messages", e);
return Response.serverError().entity("delivery cancelled").build();
throw new InternalServerErrorException("delivery cancelled");
} catch (ExecutionException e) {
logger.error("partial failure while delivering multi-recipient messages", e.getCause());
return Response.serverError().entity("failure during delivery").build();
throw new InternalServerErrorException("failure during delivery");
}
return Response.ok(new SendMultiRecipientMessageResponse(Collections.emptyList())).build();
}
@@ -54,6 +54,7 @@ import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails;
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
import org.whispersystems.textsecuregcm.subscriptions.PaymentStatus;
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionCurrencyUtil;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
@@ -319,20 +320,21 @@ public class OneTimeDonationController {
case STRIPE -> stripeManager.getPaymentDetails(request.paymentIntentId);
case BRAINTREE -> braintreeManager.getPaymentDetails(request.paymentIntentId);
case GOOGLE_PLAY_BILLING -> throw new BadRequestException("cannot use play billing for one-time donations");
case APPLE_APP_STORE -> throw new BadRequestException("cannot use app store purchases for one-time donations");
};
return paymentDetailsFut.thenCompose(paymentDetails -> {
if (paymentDetails == null) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
switch (paymentDetails.status()) {
case PROCESSING -> throw new WebApplicationException(Response.Status.NO_CONTENT);
case SUCCEEDED -> {
}
default -> throw new WebApplicationException(Response.status(Response.Status.PAYMENT_REQUIRED)
} else if (paymentDetails.status() == PaymentStatus.PROCESSING) {
return CompletableFuture.completedFuture(Response.noContent().build());
} else if (paymentDetails.status() != PaymentStatus.SUCCEEDED) {
throw new WebApplicationException(Response.status(Response.Status.PAYMENT_REQUIRED)
.entity(new CreateBoostReceiptCredentialsErrorResponse(paymentDetails.chargeFailure())).build());
}
// The payment was successful, try to issue the receipt credential
long level = oneTimeDonationConfiguration.boost().level();
if (paymentDetails.customMetadata() != null) {
String levelMetadata = paymentDetails.customMetadata()
@@ -11,7 +11,6 @@ import com.google.common.base.Preconditions;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@@ -23,9 +22,7 @@ import java.util.Collection;
import java.util.Collections;
import java.util.HexFormat;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
@@ -43,7 +40,6 @@ import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.container.ContainerRequestContext;
@@ -61,8 +57,6 @@ import org.signal.libsignal.zkgroup.groupsend.GroupSendDerivedKeyPair;
import org.signal.libsignal.zkgroup.groupsend.GroupSendFullToken;
import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialResponse;
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.Anonymous;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.GroupSendTokenHeader;
@@ -86,7 +80,6 @@ import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.s3.PolicySigner;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.storage.Account;
@@ -108,7 +101,6 @@ import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
@Path("/v1/profile")
@Tag(name = "Profile")
public class ProfileController {
private final Logger logger = LoggerFactory.getLogger(ProfileController.class);
private final Clock clock;
private final RateLimiters rateLimiters;
private final ProfilesManager profilesManager;
@@ -130,7 +122,6 @@ public class ProfileController {
private static final String EXPIRING_PROFILE_KEY_CREDENTIAL_TYPE = "expiringProfileKey";
private static final Counter VERSION_NOT_FOUND_COUNTER = Metrics.counter(name(ProfileController.class, "versionNotFound"));
private static final String INVALID_ACCEPT_LANGUAGE_COUNTER_NAME = name(ProfileController.class, "invalidAcceptLanguage");
public ProfileController(
Clock clock,
@@ -312,14 +303,10 @@ public class ProfileController {
maybeRequester, accessKey.filter(ignored -> identifier.identityType() == IdentityType.ACI), identifier);
}
return switch (identifier.identityType()) {
case ACI -> {
yield buildBaseProfileResponseForAccountIdentity(targetAccount,
maybeRequester.map(requester -> ProfileHelper.isSelfProfileRequest(requester.getUuid(), identifier)).orElse(false),
containerRequestContext);
}
case PNI -> {
yield buildBaseProfileResponseForPhoneNumberIdentity(targetAccount);
}
case ACI -> buildBaseProfileResponseForAccountIdentity(targetAccount,
maybeRequester.map(requester -> ProfileHelper.isSelfProfileRequest(requester.getUuid(), identifier)).orElse(false),
containerRequestContext);
case PNI -> buildBaseProfileResponseForPhoneNumberIdentity(targetAccount);
};
}
@@ -363,7 +350,7 @@ public class ProfileController {
private void checkFingerprintAndAdd(BatchIdentityCheckRequest.Element element,
Collection<BatchIdentityCheckResponse.Element> responseElements, MessageDigest md) {
final ServiceIdentifier identifier = Objects.requireNonNullElse(element.uuid(), element.aci());
final ServiceIdentifier identifier = element.uuid();
final Optional<Account> maybeAccount = accountsManager.getByServiceIdentifier(identifier);
maybeAccount.ifPresent(account -> {
@@ -377,7 +364,7 @@ public class ProfileController {
byte[] fingerprint = Util.truncate(digest, 4);
if (!Arrays.equals(fingerprint, element.fingerprint())) {
responseElements.add(new BatchIdentityCheckResponse.Element(element.uuid(), element.aci(), identityKey));
responseElements.add(new BatchIdentityCheckResponse.Element(element.uuid(), identityKey));
}
});
}
@@ -13,6 +13,9 @@ import io.dropwizard.auth.Auth;
import io.dropwizard.util.DataSize;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.Base64;
import javax.validation.Valid;
@@ -31,9 +34,18 @@ import org.whispersystems.textsecuregcm.entities.ProvisioningMessage;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.ProvisioningManager;
import org.whispersystems.textsecuregcm.websocket.ProvisioningAddress;
import org.whispersystems.websocket.auth.ReadOnly;
/**
* The provisioning controller facilitates transmission of provisioning messages from the primary device associated with
* an existing Signal account to a new device. To send a provisioning message, a primary device generally scans a QR
* code displayed by the new device that contains the device's "provisioning address" and a public key. The primary
* device then encrypts a use-case-specific provisioning message and posts it to
* {@link #sendProvisioningMessage(AuthenticatedDevice, String, ProvisioningMessage, String)}, at which point the server
* delivers the message to the new device via an open provisioning WebSocket.
*
* @see org.whispersystems.textsecuregcm.websocket.ProvisioningConnectListener
*/
@Path("/v1/provisioning")
@Tag(name = "Provisioning")
public class ProvisioningController {
@@ -56,22 +68,37 @@ public class ProvisioningController {
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public void sendProvisioningMessage(@ReadOnly @Auth AuthenticatedDevice auth,
@PathParam("destination") String destinationName,
@NotNull @Valid ProvisioningMessage message,
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent)
@Operation(
summary = "Send a provisioning message to a new device",
description = """
Send a provisioning message from an authenticated device to a device that (presumably) is not yet associated
with a Signal account.
""")
@ApiResponse(responseCode="204", description="The provisioning message was delivered to the given provisioning address")
@ApiResponse(responseCode="400", description="The provisioning message was too large")
@ApiResponse(responseCode="404", description="No device with the given provisioning address was connected at the time of the request")
public void sendProvisioningMessage(@ReadOnly @Auth final AuthenticatedDevice auth,
@Parameter(description = "The temporary provisioning address to which to send a provisioning message")
@PathParam("destination") final String provisioningAddress,
@Parameter(description = "The provisioning message to send to the given provisioning address")
@NotNull @Valid final ProvisioningMessage message,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent)
throws RateLimitExceededException {
if (message.body().length() > MAX_MESSAGE_SIZE) {
Metrics.counter(REJECT_OVERSIZE_MESSAGE_COUNTER, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)))
.increment();
Metrics.counter(REJECT_OVERSIZE_MESSAGE_COUNTER, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent))).increment();
throw new WebApplicationException(Response.Status.BAD_REQUEST);
}
rateLimiters.getMessagesLimiter().validate(auth.getAccount().getUuid());
if (!provisioningManager.sendProvisioningMessage(ProvisioningAddress.create(destinationName),
Base64.getMimeDecoder().decode(message.body()))) {
final boolean subscriberPresent =
provisioningManager.sendProvisioningMessage(provisioningAddress, Base64.getMimeDecoder().decode(message.body()));
if (!subscriberPresent) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
}
@@ -157,7 +157,8 @@ public class RegistrationController {
registrationRequest.deviceActivationRequest().aciSignedPreKey(),
registrationRequest.deviceActivationRequest().pniSignedPreKey(),
registrationRequest.deviceActivationRequest().aciPqLastResortPreKey(),
registrationRequest.deviceActivationRequest().pniPqLastResortPreKey()));
registrationRequest.deviceActivationRequest().pniPqLastResortPreKey()),
userAgent);
Metrics.counter(ACCOUNT_CREATED_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(COUNTRY_CODE_TAG_NAME, Util.getCountryCode(number)),
@@ -169,6 +170,7 @@ public class RegistrationController {
account.getNumber(),
account.getPhoneNumberIdentifier(),
account.getUsernameHash().orElse(null),
account.getUsernameLinkHandle(),
existingAccount.map(Account::isStorageSupported).orElse(false));
}
@@ -57,8 +57,6 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.backup.BackupManager;
import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
@@ -75,6 +73,7 @@ import org.whispersystems.textsecuregcm.storage.PaymentTime;
import org.whispersystems.textsecuregcm.storage.SubscriberCredentials;
import org.whispersystems.textsecuregcm.storage.SubscriptionException;
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator;
import org.whispersystems.textsecuregcm.subscriptions.BankTransferType;
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
@@ -96,8 +95,6 @@ import org.whispersystems.websocket.auth.ReadOnly;
@io.swagger.v3.oas.annotations.tags.Tag(name = "Subscriptions")
public class SubscriptionController {
private static final Logger logger = LoggerFactory.getLogger(SubscriptionController.class);
private final Clock clock;
private final SubscriptionConfiguration subscriptionConfiguration;
private final OneTimeDonationConfiguration oneTimeDonationConfiguration;
@@ -105,6 +102,7 @@ public class SubscriptionController {
private final StripeManager stripeManager;
private final BraintreeManager braintreeManager;
private final GooglePlayBillingManager googlePlayBillingManager;
private final AppleAppStoreManager appleAppStoreManager;
private final BadgeTranslator badgeTranslator;
private final LevelTranslator levelTranslator;
private final BankMandateTranslator bankMandateTranslator;
@@ -121,6 +119,7 @@ public class SubscriptionController {
@Nonnull StripeManager stripeManager,
@Nonnull BraintreeManager braintreeManager,
@Nonnull GooglePlayBillingManager googlePlayBillingManager,
@Nonnull AppleAppStoreManager appleAppStoreManager,
@Nonnull BadgeTranslator badgeTranslator,
@Nonnull LevelTranslator levelTranslator,
@Nonnull BankMandateTranslator bankMandateTranslator) {
@@ -131,6 +130,7 @@ public class SubscriptionController {
this.stripeManager = Objects.requireNonNull(stripeManager);
this.braintreeManager = Objects.requireNonNull(braintreeManager);
this.googlePlayBillingManager = Objects.requireNonNull(googlePlayBillingManager);
this.appleAppStoreManager = appleAppStoreManager;
this.badgeTranslator = Objects.requireNonNull(badgeTranslator);
this.levelTranslator = Objects.requireNonNull(levelTranslator);
this.bankMandateTranslator = Objects.requireNonNull(bankMandateTranslator);
@@ -261,8 +261,8 @@ public class SubscriptionController {
// Today, we always choose stripe to process non-paypal payment types, however we could use braintree to process
// other types (like CARD) in the future.
case CARD, SEPA_DEBIT, IDEAL -> stripeManager;
case GOOGLE_PLAY_BILLING ->
throw new BadRequestException("cannot create payment methods with payment type GOOGLE_PLAY_BILLING");
case GOOGLE_PLAY_BILLING, APPLE_APP_STORE ->
throw new BadRequestException("cannot create payment methods with payment type " + paymentMethodType);
case PAYPAL -> throw new BadRequestException("The PAYPAL payment type must use create_payment_method/paypal");
case UNKNOWN -> throw new BadRequestException("Invalid payment method");
};
@@ -315,7 +315,7 @@ public class SubscriptionController {
return switch (processor) {
case STRIPE -> stripeManager;
case BRAINTREE -> braintreeManager;
case GOOGLE_PLAY_BILLING -> throw new BadRequestException("Operation cannot be performed with the GOOGLE_PLAY_BILLING payment provider");
case GOOGLE_PLAY_BILLING, APPLE_APP_STORE -> throw new BadRequestException("Operation cannot be performed with the " + processor + " payment provider");
};
}
@@ -400,6 +400,39 @@ public class SubscriptionController {
== subscriptionConfiguration.getSubscriptionLevel(level2).type();
}
@POST
@Path("/{subscriberId}/appstore/{originalTransactionId}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(summary = "Set app store subscription", description = """
Set an originalTransactionId that represents an IAP subscription made with the app store.
To set up an app store subscription:
1. Create a subscriber with `PUT subscriptions/{subscriberId}` (you must regularly refresh this subscriber)
2. [Create a subscription](https://developer.apple.com/documentation/storekit/in-app_purchase/) with the App Store
directly via StoreKit and obtain a originalTransactionId.
3. `POST` the purchaseToken here
4. Obtain a receipt at `POST /v1/subscription/{subscriberId}/receipt_credentials` which can then be used to obtain the
entitlement
""")
@ApiResponse(responseCode = "200", description = "The originalTransactionId was successfully validated")
@ApiResponse(responseCode = "402", description = "The subscription transaction is incomplete or invalid")
@ApiResponse(responseCode = "403", description = "subscriberId authentication failure OR account authentication is present")
@ApiResponse(responseCode = "404", description = "No such subscriberId exists or subscriberId is malformed or the specified transaction does not exist")
@ApiResponse(responseCode = "409", description = "subscriberId is already linked to a processor that does not support appstore payments. Delete this subscriberId and use a new one.")
@ApiResponse(responseCode = "429", description = "Rate limit exceeded.")
public CompletableFuture<SetSubscriptionLevelSuccessResponse> setAppStoreSubscription(
@ReadOnly @Auth Optional<AuthenticatedDevice> authenticatedAccount,
@PathParam("subscriberId") String subscriberId,
@PathParam("originalTransactionId") String originalTransactionId) throws SubscriptionException {
final SubscriberCredentials subscriberCredentials =
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
return subscriptionManager
.updateAppStoreTransactionId(subscriberCredentials, appleAppStoreManager, originalTransactionId)
.thenApply(SetSubscriptionLevelSuccessResponse::new);
}
@POST
@Path("/{subscriberId}/playbilling/{purchaseToken}")
@@ -419,6 +452,10 @@ public class SubscriptionController {
After calling this method, the payment is confirmed. Callers must durably store their subscriberId before calling
this method to ensure their payment is tracked.
Once a purchaseToken to is posted to a subscriberId, the same subscriberId must not be used with another payment
method. A different playbilling purchaseToken can be posted to the same subscriberId, in this case the subscription
associated with the old purchaseToken will be cancelled.
""")
@ApiResponse(responseCode = "200", description = "The purchaseToken was validated and acknowledged")
@ApiResponse(responseCode = "402", description = "The purchaseToken payment is incomplete or invalid")
@@ -526,7 +563,7 @@ public class SubscriptionController {
long level,
@Schema(
description = "If present, UNIX Epoch Timestamp in seconds, can be used to calculate next billing date. May be absent for IAP subscriptions",
description = "If present, UNIX Epoch Timestamp in seconds, can be used to calculate next billing date.",
externalDocs = @ExternalDocumentation(description = "Calculate next billing date", url = "https://stripe.com/docs/billing/subscriptions/billing-cycle"))
Instant billingCycleAnchor,
@@ -631,7 +668,10 @@ public class SubscriptionController {
UserAgentTagUtil.getPlatformTag(userAgent)))
.increment();
return Response.ok(new GetReceiptCredentialsResponse(receiptCredentialResponse.serialize())).build();
});
})
.exceptionally(ExceptionUtils.exceptionallyHandler(
SubscriptionException.ReceiptRequestedForOpenPayment.class,
e -> Response.noContent().build()));
}
@POST
@@ -397,8 +397,9 @@ public class VerificationController {
Tag.of(SCORE_TAG_NAME, assessmentResult.getScoreString())))
.increment();
} catch (IOException e) {
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE);
} catch (final IOException e) {
logger.error("error assessing captcha", e);
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE, e);
}
if (assessmentResult.isValid(captchaScoreThreshold)) {
@@ -27,7 +27,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.CurrencyConversionEntity;
import org.whispersystems.textsecuregcm.entities.CurrencyConversionEntityList;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
public class CurrencyConversionManager implements Managed {
@@ -47,7 +47,7 @@ public class CurrencyConversionManager implements Managed {
private final CoinMarketCapClient coinMarketCapClient;
private final FaultTolerantRedisCluster cacheCluster;
private final FaultTolerantRedisClusterClient cacheCluster;
private final Clock clock;
@@ -67,7 +67,7 @@ public class CurrencyConversionManager implements Managed {
public CurrencyConversionManager(
final FixerClient fixerClient,
final CoinMarketCapClient coinMarketCapClient,
final FaultTolerantRedisCluster cacheCluster,
final FaultTolerantRedisClusterClient cacheCluster,
final List<String> currencies,
final ScheduledExecutorService executor,
final Clock clock) {
@@ -114,7 +114,7 @@ public record AccountDataReportResponse(UUID reportId,
boolean visible) {
public BadgeDataReport(AccountBadge badge) {
this(badge.getId(), badge.getExpiration(), badge.isVisible());
this(badge.id(), badge.expiration(), badge.visible());
}
}
@@ -27,6 +27,9 @@ public record AccountIdentityResponse(
@JsonDeserialize(using = ByteArrayBase64UrlAdapter.Deserializing.class)
@Nullable byte[] usernameHash,
@Schema(description="this account's username link handle, if set")
@Nullable UUID usernameLinkHandle,
@Schema(description="whether any of this account's devices support storage")
boolean storageCapable) {
}
@@ -7,6 +7,5 @@ package org.whispersystems.textsecuregcm.entities;
import javax.annotation.Nullable;
import javax.validation.constraints.NotEmpty;
public record ApnRegistrationId(@NotEmpty String apnRegistrationId,
@Nullable String voipRegistrationId) {
public record ApnRegistrationId(@NotEmpty String apnRegistrationId) {
}
@@ -1,23 +0,0 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.annotation.JsonProperty;
public record AttachmentDescriptorV2(long attachmentId,
String key,
String credential,
String acl,
String algorithm,
String date,
String policy,
String signature) {
@JsonProperty
public String attachmentIdString() {
return String.valueOf(attachmentId);
}
}
@@ -12,7 +12,6 @@ import javax.annotation.Nullable;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.util.ExactlySize;
import org.whispersystems.textsecuregcm.util.ServiceIdentifierAdapter;
@@ -24,30 +23,13 @@ public record BatchIdentityCheckRequest(@Valid @NotNull @Size(max = 1000) List<E
* @param fingerprint most significant 4 bytes of SHA-256 of the 33-byte identity key field (32-byte curve25519 public
* key prefixed with 0x05)
*/
public record Element(@Nullable
public record Element(@NotNull
@JsonSerialize(using = ServiceIdentifierAdapter.ServiceIdentifierSerializer.class)
@JsonDeserialize(using = ServiceIdentifierAdapter.ServiceIdentifierDeserializer.class)
ServiceIdentifier uuid,
@Nullable
@Deprecated // remove after 2023-11-01
@JsonSerialize(using = ServiceIdentifierAdapter.ServiceIdentifierSerializer.class)
@JsonDeserialize(using = ServiceIdentifierAdapter.AciServiceIdentifierDeserializer.class)
AciServiceIdentifier aci,
@NotNull
@ExactlySize(4)
byte[] fingerprint) {
public Element {
if (aci == null && uuid == null) {
throw new IllegalArgumentException("aci and uuid cannot both be null");
}
if (aci != null && uuid != null) {
throw new IllegalArgumentException("aci and uuid cannot both be non-null");
}
}
}
}
}
@@ -9,7 +9,6 @@ import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.util.List;
import javax.annotation.Nullable;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import org.signal.libsignal.protocol.IdentityKey;
@@ -22,29 +21,12 @@ public record BatchIdentityCheckResponse(@Valid List<Element> elements) {
public record Element(@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonSerialize(using = ServiceIdentifierAdapter.ServiceIdentifierSerializer.class)
@JsonDeserialize(using = ServiceIdentifierAdapter.ServiceIdentifierDeserializer.class)
@Nullable
@NotNull
ServiceIdentifier uuid,
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonSerialize(using = ServiceIdentifierAdapter.ServiceIdentifierSerializer.class)
@JsonDeserialize(using = ServiceIdentifierAdapter.AciServiceIdentifierDeserializer.class)
@Nullable
@Deprecated // remove after 2023-11-01
ServiceIdentifier aci,
@NotNull
@JsonSerialize(using = IdentityKeyAdapter.Serializer.class)
@JsonDeserialize(using = IdentityKeyAdapter.Deserializer.class)
IdentityKey identityKey) {
public Element {
if (aci == null && uuid == null) {
throw new IllegalArgumentException("aci and uuid cannot both be null");
}
if (aci != null && uuid != null) {
throw new IllegalArgumentException("aci and uuid cannot both be non-null");
}
}
}
}
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.util.ByteArrayBase64WithPaddingAdapter;
public record DeviceInfo(long id,
@@ -17,4 +18,8 @@ public record DeviceInfo(long id,
long lastSeen,
long created) {
public static DeviceInfo forDevice(final Device device) {
return new DeviceInfo(device.getId(), device.getName(), device.getLastSeen(), device.getCreated());
}
}
@@ -1,43 +0,0 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.annotations.VisibleForTesting;
import java.util.UUID;
public class DeviceResponse {
@JsonProperty
private UUID uuid;
@JsonProperty
private UUID pni;
@JsonProperty
private byte deviceId;
@VisibleForTesting
public DeviceResponse() {}
public DeviceResponse(UUID uuid, UUID pni, byte deviceId) {
this.uuid = uuid;
this.pni = pni;
this.deviceId = deviceId;
}
public UUID getUuid() {
return uuid;
}
public UUID getPni() {
return pni;
}
public byte getDeviceId() {
return deviceId;
}
}
@@ -0,0 +1,11 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.entities;
import java.util.UUID;
public record LinkDeviceResponse(UUID uuid, UUID pni, byte deviceId) {
}
@@ -5,7 +5,11 @@
package org.whispersystems.textsecuregcm.entities;
import io.swagger.v3.oas.annotations.media.Schema;
import javax.validation.constraints.NotEmpty;
public record ProvisioningMessage(@NotEmpty String body) {
public record ProvisioningMessage(
@Schema(description = "The MIME base64-encoded body of the provisioning message to send to the destination device")
@NotEmpty
String body) {
}
@@ -0,0 +1,22 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.entities;
import io.swagger.v3.oas.annotations.media.Schema;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import org.whispersystems.textsecuregcm.util.ValidBase64URLString;
public record RemoteAttachment(
@Schema(description = "The attachment cdn")
@NotNull
Integer cdn,
@NotBlank
@ValidBase64URLString
@Schema(description = "The attachment key")
String key) {
}
@@ -0,0 +1,27 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.entities;
import io.swagger.v3.oas.annotations.media.Schema;
import org.whispersystems.textsecuregcm.storage.Device;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Positive;
public record TransferArchiveUploadedRequest(@Min(1)
@Max(Device.MAXIMUM_DEVICE_ID)
@Schema(description = "The ID of the device for which the transfer archive has been prepared")
byte destinationDeviceId,
@Positive
@Schema(description = "The timestamp, in milliseconds since the epoch, at which the destination device was created")
long destinationDeviceCreated,
@Schema(description = "The location of the transfer archive")
@Valid
RemoteAttachment transferArchive) {
}
@@ -8,13 +8,11 @@ package org.whispersystems.textsecuregcm.entities;
import org.whispersystems.textsecuregcm.storage.Account;
public record UserCapabilities(
// TODO: Remove the paymentActivation capability entirely sometime soon after 2024-10-07
boolean paymentActivation,
boolean deleteSync,
boolean versionedExpirationTimer) {
public static UserCapabilities createForAccount(final Account account) {
return new UserCapabilities(true, account.isDeleteSyncSupported(),
return new UserCapabilities(account.isDeleteSyncSupported(),
account.isVersionedExpirationTimerSupported());
}
}
@@ -18,6 +18,7 @@ import java.util.concurrent.Executor;
import java.util.function.Supplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;
/**
* An experiment compares the results of two operations and records metrics to assess how frequently they match.
@@ -70,6 +71,14 @@ public class Experiment {
this.experimentNullMismatchTimer = experimentNullMismatchTimer;
}
public <T> void compareMonoResult(final T expected, final Mono<T> experimentMono) {
final Timer.Sample sample = Timer.start();
experimentMono.subscribe(
actual -> recordResult(expected, actual, sample),
cause -> recordError(cause, sample));
}
public <T> void compareFutureResult(final T expected, final CompletionStage<T> experimentStage) {
final Timer.Sample sample = Timer.start();
@@ -5,11 +5,11 @@
package org.whispersystems.textsecuregcm.experiment;
import com.google.common.annotations.VisibleForTesting;
import java.util.Optional;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import com.google.common.annotations.VisibleForTesting;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicExperimentEnrollmentConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicPreRegistrationExperimentEnrollmentConfiguration;
@@ -40,16 +40,32 @@ public class ExperimentEnrollmentManager {
final Optional<DynamicExperimentEnrollmentConfiguration> maybeConfiguration = dynamicConfigurationManager
.getConfiguration().getExperimentEnrollmentConfiguration(experimentName);
return maybeConfiguration.map(config -> {
return maybeConfiguration
.map(config -> isAccountEnrolled(accountUuid, config)
.orElse(isEnrolled(accountUuid, config.getEnrollmentPercentage(), experimentName))
).orElse(false);
}
if (config.getUuidSelector().getUuids().contains(accountUuid)) {
final int r = random.nextInt(100);
return r < config.getUuidSelector().getUuidEnrollmentPercentage();
}
Optional<Boolean> isAccountEnrolled(final UUID accountUuid, DynamicExperimentEnrollmentConfiguration config) {
if (config.getExcludedUuids().contains(accountUuid)) {
return Optional.of(false);
}
if (config.getUuidSelector().getUuids().contains(accountUuid)) {
final int r = random.nextInt(100);
return Optional.of(r < config.getUuidSelector().getUuidEnrollmentPercentage());
}
return isEnrolled(accountUuid, config.getEnrollmentPercentage(), experimentName);
return Optional.empty();
}
}).orElse(false);
public boolean isEnrolled(final String e164, final UUID accountUuid, final String experimentName) {
final Optional<DynamicExperimentEnrollmentConfiguration> maybeConfiguration = dynamicConfigurationManager
.getConfiguration().getExperimentEnrollmentConfiguration(experimentName);
return maybeConfiguration
.flatMap(config -> isAccountEnrolled(accountUuid, config))
.orElse(isEnrolled(e164, experimentName));
}
public boolean isEnrolled(final String e164, final String experimentName) {
@@ -54,8 +54,7 @@ abstract class IdleDevicePushNotificationExperiment implements PushNotificationE
@VisibleForTesting
boolean hasPushToken(final Device device) {
// Exclude VOIP tokens since they have their own, distinct delivery mechanism
return !StringUtils.isAllBlank(device.getApnId(), device.getGcmId()) && StringUtils.isBlank(device.getVoipApnId());
return !StringUtils.isAllBlank(device.getApnId(), device.getGcmId());
}
@Override
@@ -1,76 +0,0 @@
package org.whispersystems.textsecuregcm.experiment;
import com.google.common.annotations.VisibleForTesting;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.push.IdleDeviceNotificationScheduler;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import java.time.Clock;
import java.time.Duration;
import java.time.LocalTime;
import java.util.concurrent.CompletableFuture;
public class NotifyIdleDevicesWithMessagesExperiment extends IdleDevicePushNotificationExperiment {
private final IdleDeviceNotificationScheduler idleDeviceNotificationScheduler;
private final MessagesManager messagesManager;
@VisibleForTesting
static final Duration MIN_IDLE_DURATION = Duration.ofDays(3);
@VisibleForTesting
static final Duration MAX_IDLE_DURATION = Duration.ofDays(14);
@VisibleForTesting
static final LocalTime PREFERRED_NOTIFICATION_TIME = LocalTime.of(14, 0);
public NotifyIdleDevicesWithMessagesExperiment(final IdleDeviceNotificationScheduler idleDeviceNotificationScheduler,
final MessagesManager messagesManager,
final Clock clock) {
super(clock);
this.idleDeviceNotificationScheduler = idleDeviceNotificationScheduler;
this.messagesManager = messagesManager;
}
@Override
protected Duration getMinIdleDuration() {
return MIN_IDLE_DURATION;
}
@Override
protected Duration getMaxIdleDuration() {
return MAX_IDLE_DURATION;
}
@Override
public String getExperimentName() {
return "notify-idle-devices-with-messages";
}
@Override
public CompletableFuture<Boolean> isDeviceEligible(final Account account, final Device device) {
if (!hasPushToken(device)) {
return CompletableFuture.completedFuture(false);
}
if (!isIdle(device)) {
return CompletableFuture.completedFuture(false);
}
return messagesManager.mayHavePersistedMessages(account.getIdentifier(IdentityType.ACI), device);
}
@Override
public Class<DeviceLastSeenState> getStateClass() {
return DeviceLastSeenState.class;
}
@Override
public CompletableFuture<Void> applyExperimentTreatment(final Account account, final Device device) {
return idleDeviceNotificationScheduler.scheduleNotification(account, device, PREFERRED_NOTIFICATION_TIME);
}
}
@@ -5,18 +5,37 @@
package org.whispersystems.textsecuregcm.filters;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import java.io.IOException;
/**
* Injects a timestamp header into all outbound responses.
*/
public class TimestampResponseFilter implements ContainerResponseFilter {
public class TimestampResponseFilter implements Filter, ContainerResponseFilter {
@Override
public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext) {
responseContext.getHeaders().add(HeaderUtils.TIMESTAMP_HEADER, System.currentTimeMillis());
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
throws ServletException, IOException {
if (response instanceof HttpServletResponse httpServletResponse) {
httpServletResponse.setHeader(HeaderUtils.TIMESTAMP_HEADER, String.valueOf(System.currentTimeMillis()));
}
chain.doFilter(request, response);
}
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
// not using add() - it's ok to overwrite any existing header, and we don't want a multi-value
responseContext.getHeaders().putSingle(HeaderUtils.TIMESTAMP_HEADER, System.currentTimeMillis());
}
}
@@ -110,7 +110,6 @@ public class DevicesGrpcService extends ReactorDevicesGrpc.DevicesImplBase {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
@Nullable final String apnsToken;
@Nullable final String apnsVoipToken;
@Nullable final String fcmToken;
switch (request.getTokenRequestCase()) {
@@ -118,12 +117,11 @@ public class DevicesGrpcService extends ReactorDevicesGrpc.DevicesImplBase {
case APNS_TOKEN_REQUEST -> {
final SetPushTokenRequest.ApnsTokenRequest apnsTokenRequest = request.getApnsTokenRequest();
if (StringUtils.isAllBlank(apnsTokenRequest.getApnsToken(), apnsTokenRequest.getApnsVoipToken())) {
throw Status.INVALID_ARGUMENT.withDescription("APNs tokens may not both be blank").asRuntimeException();
if (StringUtils.isBlank(apnsTokenRequest.getApnsToken())) {
throw Status.INVALID_ARGUMENT.withDescription("APNs token must not be blank").asRuntimeException();
}
apnsToken = StringUtils.stripToNull(apnsTokenRequest.getApnsToken());
apnsVoipToken = StringUtils.stripToNull(apnsTokenRequest.getApnsVoipToken());
fcmToken = null;
}
@@ -135,7 +133,6 @@ public class DevicesGrpcService extends ReactorDevicesGrpc.DevicesImplBase {
}
apnsToken = null;
apnsVoipToken = null;
fcmToken = StringUtils.stripToNull(fcmTokenRequest.getFcmToken());
}
@@ -150,14 +147,12 @@ public class DevicesGrpcService extends ReactorDevicesGrpc.DevicesImplBase {
final boolean tokenUnchanged =
Objects.equals(device.getApnId(), apnsToken) &&
Objects.equals(device.getVoipApnId(), apnsVoipToken) &&
Objects.equals(device.getGcmId(), fcmToken);
return tokenUnchanged
? Mono.empty()
: Mono.fromFuture(() -> accountsManager.updateDeviceAsync(account, authenticatedDevice.deviceId(), d -> {
d.setApnId(apnsToken);
d.setVoipApnId(apnsVoipToken);
d.setGcmId(fcmToken);
d.setFetchesMessages(false);
}));
@@ -172,14 +167,13 @@ public class DevicesGrpcService extends ReactorDevicesGrpc.DevicesImplBase {
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
.flatMap(account -> Mono.fromFuture(() -> accountsManager.updateDeviceAsync(account, authenticatedDevice.deviceId(), device -> {
if (StringUtils.isNotBlank(device.getApnId()) || StringUtils.isNotBlank(device.getVoipApnId())) {
if (StringUtils.isNotBlank(device.getApnId())) {
device.setUserAgent(device.isPrimary() ? "OWI" : "OWP");
} else if (StringUtils.isNotBlank(device.getGcmId())) {
device.setUserAgent("OWA");
}
device.setApnId(null);
device.setVoipApnId(null);
device.setGcmId(null);
device.setFetchesMessages(true);
})))
@@ -197,7 +191,6 @@ public class DevicesGrpcService extends ReactorDevicesGrpc.DevicesImplBase {
d -> d.setCapabilities(new Device.DeviceCapabilities(
request.getStorage(),
request.getTransfer(),
request.getPaymentActivation(),
request.getDeleteSync(),
request.getVersionedExpirationTimer())))))
.thenReturn(SetCapabilitiesResponse.newBuilder().build());
@@ -82,7 +82,6 @@ public class ProfileGrpcHelper {
@VisibleForTesting
static UserCapabilities buildUserCapabilities(final org.whispersystems.textsecuregcm.entities.UserCapabilities capabilities) {
return UserCapabilities.newBuilder()
.setPaymentActivation(capabilities.paymentActivation())
.setDeleteSync(capabilities.deleteSync())
.setVersionedExpirationTimer(capabilities.versionedExpirationTimer())
.build();
@@ -19,13 +19,11 @@ import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import io.grpc.TlsChannelCredentials;
import katie.ConsistencyParameters;
import katie.KatieGrpc;
import katie.MonitorKey;
import katie.MonitorRequest;
import katie.MonitorResponse;
import katie.SearchRequest;
import katie.SearchResponse;
import org.signal.keytransparency.client.ConsistencyParameters;
import org.signal.keytransparency.client.KeyTransparencyQueryServiceGrpc;
import org.signal.keytransparency.client.MonitorKey;
import org.signal.keytransparency.client.MonitorRequest;
import org.signal.keytransparency.client.SearchRequest;
import org.whispersystems.textsecuregcm.util.CompletableFutureUtil;
public class KeyTransparencyServiceClient implements Managed {
@@ -35,7 +33,7 @@ public class KeyTransparencyServiceClient implements Managed {
private final int port;
private final ChannelCredentials tlsChannelCredentials;
private ManagedChannel channel;
private KatieGrpc.KatieFutureStub stub;
private KeyTransparencyQueryServiceGrpc.KeyTransparencyQueryServiceFutureStub stub;
public KeyTransparencyServiceClient(
final String host,
@@ -100,7 +98,7 @@ public class KeyTransparencyServiceClient implements Managed {
channel = Grpc.newChannelBuilderForAddress(host, port, tlsChannelCredentials)
.idleTimeout(1, TimeUnit.MINUTES)
.build();
stub = KatieGrpc.newFutureStub(channel);
stub = KeyTransparencyQueryServiceGrpc.newFutureStub(channel);
}
@Override
@@ -22,7 +22,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
public abstract class BaseRateLimiters<T extends RateLimiterDescriptor> {
@@ -39,7 +39,7 @@ public abstract class BaseRateLimiters<T extends RateLimiterDescriptor> {
final Map<String, RateLimiterConfig> configs,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final ClusterLuaScript validateScript,
final FaultTolerantRedisCluster cacheCluster,
final FaultTolerantRedisClusterClient cacheCluster,
final Clock clock) {
this.configs = configs;
this.rateLimiterByDescriptor = Arrays.stream(values)
@@ -69,7 +69,7 @@ public abstract class BaseRateLimiters<T extends RateLimiterDescriptor> {
}
}
protected static ClusterLuaScript defaultScript(final FaultTolerantRedisCluster cacheCluster) {
protected static ClusterLuaScript defaultScript(final FaultTolerantRedisClusterClient cacheCluster) {
try {
return ClusterLuaScript.fromResource(
cacheCluster, "lua/validate_rate_limit.lua", ScriptOutputType.INTEGER);
@@ -83,7 +83,7 @@ public abstract class BaseRateLimiters<T extends RateLimiterDescriptor> {
final Map<String, RateLimiterConfig> configs,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final ClusterLuaScript validateScript,
final FaultTolerantRedisCluster cacheCluster,
final FaultTolerantRedisClusterClient cacheCluster,
final Clock clock) {
if (descriptor.isDynamic()) {
final Supplier<RateLimiterConfig> configResolver = () -> {
@@ -12,7 +12,7 @@ import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.util.Util;
/**
@@ -21,11 +21,11 @@ import org.whispersystems.textsecuregcm.util.Util;
public class CardinalityEstimator {
private volatile double uniqueElementCount;
private final FaultTolerantRedisCluster redisCluster;
private final FaultTolerantRedisClusterClient redisCluster;
private final String hllName;
private final Duration period;
public CardinalityEstimator(final FaultTolerantRedisCluster redisCluster, final String name, final Duration period) {
public CardinalityEstimator(final FaultTolerantRedisClusterClient redisCluster, final String name, final Duration period) {
this.redisCluster = redisCluster;
this.hllName = "cardinality_estimator::" + name;
this.period = period;
@@ -15,7 +15,7 @@ import org.apache.commons.lang3.tuple.Pair;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
public class DynamicRateLimiter implements RateLimiter {
@@ -26,7 +26,7 @@ public class DynamicRateLimiter implements RateLimiter {
private final ClusterLuaScript validateScript;
private final FaultTolerantRedisCluster cluster;
private final FaultTolerantRedisClusterClient cluster;
private final Clock clock;
@@ -38,7 +38,7 @@ public class DynamicRateLimiter implements RateLimiter {
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final Supplier<RateLimiterConfig> configResolver,
final ClusterLuaScript validateScript,
final FaultTolerantRedisCluster cluster,
final FaultTolerantRedisClusterClient cluster,
final Clock clock) {
this.name = requireNonNull(name);
this.dynamicConfigurationManager = dynamicConfigurationManager;
@@ -11,7 +11,7 @@ import java.util.concurrent.CompletableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
public class MessageDeliveryLoopMonitor {
@@ -22,7 +22,7 @@ public class MessageDeliveryLoopMonitor {
private static final Logger logger = LoggerFactory.getLogger(MessageDeliveryLoopMonitor.class);
public MessageDeliveryLoopMonitor(final FaultTolerantRedisCluster rateLimitCluster) {
public MessageDeliveryLoopMonitor(final FaultTolerantRedisClusterClient rateLimitCluster) {
try {
getDeliveryAttemptsScript =
ClusterLuaScript.fromResource(rateLimitCluster, "lua/get_delivery_attempt_count.lua", ScriptOutputType.INTEGER);
@@ -22,6 +22,11 @@ import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
public class RateLimitByIpFilter implements ContainerRequestFilter {
@@ -33,8 +38,9 @@ public class RateLimitByIpFilter implements ContainerRequestFilter {
private static final ExceptionMapper<RateLimitExceededException> EXCEPTION_MAPPER = new RateLimitExceededExceptionMapper();
private final RateLimiters rateLimiters;
private static final String NO_IP_COUNTER_NAME = MetricsUtil.name(RateLimitByIpFilter.class, "noIpAddress");
private final RateLimiters rateLimiters;
public RateLimitByIpFilter(final RateLimiters rateLimiters) {
this.rateLimiters = requireNonNull(rateLimiters);
@@ -65,6 +71,13 @@ public class RateLimitByIpFilter implements ContainerRequestFilter {
// checking if we failed to extract the most recent IP for any reason
if (remoteAddress.isEmpty()) {
Metrics.counter(
NO_IP_COUNTER_NAME,
Tags.of(
Tag.of("limiter", handle.id()),
Tag.of("fail", String.valueOf(annotation.failOnUnresolvedIp()))))
.increment();
// checking if annotation is configured to fail when the most recent IP is not resolved
if (annotation.failOnUnresolvedIp()) {
logger.error("Remote address was null");
@@ -11,7 +11,7 @@ import java.time.Duration;
import java.util.Map;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
@@ -24,8 +24,8 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
PRE_KEYS("prekeys", false, new RateLimiterConfig(6, Duration.ofMinutes(10))),
MESSAGES("messages", false, new RateLimiterConfig(60, Duration.ofSeconds(1))),
STORIES("stories", false, new RateLimiterConfig(5_000, Duration.ofSeconds(8))),
ALLOCATE_DEVICE("allocateDevice", false, new RateLimiterConfig(2, Duration.ofMinutes(2))),
VERIFY_DEVICE("verifyDevice", false, new RateLimiterConfig(6, Duration.ofMinutes(10))),
ALLOCATE_DEVICE("allocateDevice", false, new RateLimiterConfig(6, Duration.ofMinutes(2))),
VERIFY_DEVICE("verifyDevice", false, new RateLimiterConfig(6, Duration.ofMinutes(2))),
TURN("turnAllocate", false, new RateLimiterConfig(60, Duration.ofSeconds(1))),
PROFILE("profile", false, new RateLimiterConfig(4320, Duration.ofSeconds(20))),
STICKER_PACK("stickerPack", false, new RateLimiterConfig(50, Duration.ofMinutes(72))),
@@ -50,6 +50,9 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
EXTERNAL_SERVICE_CREDENTIALS("externalServiceCredentials", true, new RateLimiterConfig(100, Duration.ofMinutes(15))),
KEY_TRANSPARENCY_SEARCH_PER_IP("keyTransparencySearch", true, new RateLimiterConfig(100, Duration.ofSeconds(15))),
KEY_TRANSPARENCY_MONITOR_PER_IP("keyTransparencyMonitor", true, new RateLimiterConfig(100, Duration.ofSeconds(15))),
WAIT_FOR_LINKED_DEVICE("waitForLinkedDevice", true, new RateLimiterConfig(10, Duration.ofSeconds(30))),
UPLOAD_TRANSFER_ARCHIVE("uploadTransferArchive", true, new RateLimiterConfig(10, Duration.ofMinutes(1))),
WAIT_FOR_TRANSFER_ARCHIVE("waitForTransferArchive", true, new RateLimiterConfig(10, Duration.ofSeconds(30))),
;
private final String id;
@@ -81,7 +84,7 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
public static RateLimiters createAndValidate(
final Map<String, RateLimiterConfig> configs,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final FaultTolerantRedisCluster cacheCluster) {
final FaultTolerantRedisClusterClient cacheCluster) {
final RateLimiters rateLimiters = new RateLimiters(
configs, dynamicConfigurationManager, defaultScript(cacheCluster), cacheCluster, Clock.systemUTC());
rateLimiters.validateValuesAndConfigs();
@@ -93,7 +96,7 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
final Map<String, RateLimiterConfig> configs,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final ClusterLuaScript validateScript,
final FaultTolerantRedisCluster cacheCluster,
final FaultTolerantRedisClusterClient cacheCluster,
final Clock clock) {
super(For.values(), configs, dynamicConfigurationManager, validateScript, cacheCluster, clock);
}
@@ -205,4 +208,16 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
public RateLimiter getStoriesLimiter() {
return forDescriptor(For.STORIES);
}
public RateLimiter getWaitForLinkedDeviceLimiter() {
return forDescriptor(For.WAIT_FOR_LINKED_DEVICE);
}
public RateLimiter getUploadTransferArchiveLimiter() {
return forDescriptor(For.UPLOAD_TRANSFER_ARCHIVE);
}
public RateLimiter getWaitForTransferArchiveLimiter() {
return forDescriptor(For.WAIT_FOR_TRANSFER_ARCHIVE);
}
}
@@ -20,7 +20,7 @@ import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfigurati
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.Util;
@@ -36,7 +36,7 @@ public class StaticRateLimiter implements RateLimiter {
private final ClusterLuaScript validateScript;
private final FaultTolerantRedisCluster cacheCluster;
private final FaultTolerantRedisClusterClient cacheCluster;
private final Clock clock;
@@ -45,7 +45,7 @@ public class StaticRateLimiter implements RateLimiter {
final String name,
final RateLimiterConfig config,
final ClusterLuaScript validateScript,
final FaultTolerantRedisCluster cacheCluster,
final FaultTolerantRedisClusterClient cacheCluster,
final Clock clock,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
this.name = requireNonNull(name);
@@ -5,17 +5,48 @@
package org.whispersystems.textsecuregcm.mappers;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.jersey.errors.ErrorMessage;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import org.whispersystems.textsecuregcm.storage.SubscriptionException;
import java.util.Map;
public class SubscriptionExceptionMapper implements ExceptionMapper<SubscriptionException> {
@VisibleForTesting
public static final int PROCESSOR_ERROR_STATUS_CODE = 440;
@Override
public Response toResponse(final SubscriptionException exception) {
// Some exceptions have specific error body formats
if (exception instanceof SubscriptionException.AmountTooSmall e) {
return Response
.status(Response.Status.BAD_REQUEST)
.entity(Map.of("error", "amount_too_small"))
.type(MediaType.APPLICATION_JSON_TYPE)
.build();
}
if (exception instanceof SubscriptionException.ProcessorException e) {
return Response.status(PROCESSOR_ERROR_STATUS_CODE)
.entity(Map.of(
"processor", e.getProcessor().name(),
"chargeFailure", e.getChargeFailure()
))
.type(MediaType.APPLICATION_JSON_TYPE)
.build();
}
if (exception instanceof SubscriptionException.ChargeFailurePaymentRequired e) {
return Response
.status(Response.Status.PAYMENT_REQUIRED)
.entity(Map.of("chargeFailure", e.getChargeFailure()))
.type(MediaType.APPLICATION_JSON_TYPE)
.build();
}
// Otherwise, we'll return a generic error message WebApplicationException, with a detailed error if one is provided
final Response.Status status = (switch (exception) {
case SubscriptionException.NotFound e -> Response.Status.NOT_FOUND;
case SubscriptionException.Forbidden e -> Response.Status.FORBIDDEN;
@@ -36,5 +67,6 @@ public class SubscriptionExceptionMapper implements ExceptionMapper<Subscription
.fromResponse(wae.getResponse())
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new ErrorMessage(wae.getResponse().getStatus(), wae.getLocalizedMessage())).build();
}
}
@@ -1,26 +0,0 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.mappers;
import java.util.Map;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
public class SubscriptionProcessorExceptionMapper implements ExceptionMapper<SubscriptionProcessorException> {
public static final int EXTERNAL_SERVICE_ERROR_STATUS_CODE = 440;
@Override
public Response toResponse(final SubscriptionProcessorException exception) {
return Response.status(EXTERNAL_SERVICE_ERROR_STATUS_CODE)
.entity(Map.of(
"processor", exception.getProcessor().name(),
"chargeFailure", exception.getChargeFailure()
))
.build();
}
}
@@ -0,0 +1,207 @@
package org.whispersystems.textsecuregcm.metrics;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.Timer;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.metrics.MetricPublisher;
import software.amazon.awssdk.metrics.MetricRecord;
import java.time.Duration;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
/**
* A Micrometer AWS SDK metric publisher consumes {@link MetricCollection} instances provided by the AWS SDK when it
* makes calls to the AWS API and publishes a subset of metrics from each call via the Micrometer metrics facade. A
* single {@code MicrometerAwsSdkMetricPublisher} should be bound to a single AWS service client instance; publishers
* should not be assigned to multiple service clients.
*
* @see <a href="https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/metrics-list.html">Service client metrics</a>
*/
public class MicrometerAwsSdkMetricPublisher implements MetricPublisher {
private final ExecutorService recordMetricsExecutorService;
private final String awsClientName;
private final AtomicInteger mostRecentMaxConcurrency;
// Note that these metric collection type names don't seem to appear anywhere in the AWS SDK documentation. The docs
// also hint at, but don't explicitly call out, the structure of a `MetricCollection` passed to the `#publish(...)`
// method. Empirically, for each AWS SDK operation, the SDK will call `#publish(...)` with a collection structured as
// follows:
//
// MetricCollection { name = "ApiCall" }
// +-- MetricRecord { name = "ApiCallDuration" }
// +-- MetricRecord { name = "ApiCallSuccessful" }
// +-- ...
// +-- MetricCollection { name = "ApiCallAttempt" }
// +-- MetricRecord { name = "AwsExtendedRequestId" }
// +-- MetricRecord { name = "AwsRequestId" }
// +-- ...
// +-- MetricCollection {name = "HttpClient" }
// +-- MetricRecord { name = "AvailableConcurrency" }
// +-- MetricRecord { name = "ConcurrencyAcquireDuration" }
// +-- ...
// +-- MetricCollection { name = "ApiCallAttempt" }
// +-- MetricRecord { name = "AwsExtendedRequestId" }
// +-- MetricRecord { name = "AwsRequestId" }
// +-- ...
// +-- MetricCollection {name = "HttpClient" }
// +-- MetricRecord { name = "AvailableConcurrency" }
// +-- MetricRecord { name = "ConcurrencyAcquireDuration" }
// +-- ...
// +-- ...
//
// Every `MetricCollection` passed to `#publish(...)` should have a name of "ApiCall," and the "ApiCall" collection
// will have a fixed collection of named metrics (which ARE documented!). The "ApiCall" collection should have one or
// more "ApiCallAttempt" `MetricCollection` as children, and each "ApiCallAttempt" collection should have exactly one
// "HttpClient" `MetricCollection` as a child.
private static final String METRIC_COLLECTION_TYPE_API_CALL = "ApiCall";
private static final String METRIC_COLLECTION_TYPE_API_CALL_ATTEMPT = "ApiCallAttempt";
private static final String METRIC_COLLECTION_TYPE_HTTP_METRICS = "HttpClient";
private static final String API_CALL_COUNTER_NAME =
MetricsUtil.name(MicrometerAwsSdkMetricPublisher.class, "apiCall");
private static final String API_CALL_RETRY_COUNT_DISTRIBUTION_NAME =
MetricsUtil.name(MicrometerAwsSdkMetricPublisher.class, "apiCallRetries");
private static final String CHANNEL_ACQUISITION_TIMER_NAME =
MetricsUtil.name(MicrometerAwsSdkMetricPublisher.class, "acquireChannelDuration");
private static final String PENDING_CHANNEL_ACQUISITIONS_DISTRIBUTION_NAME =
MetricsUtil.name(MicrometerAwsSdkMetricPublisher.class, "pendingChannelAcquisitions");
private static final String CONCURRENT_REQUESTS_DISTRIBUTION_NAME =
MetricsUtil.name(MicrometerAwsSdkMetricPublisher.class, "concurrentRequests");
private static final String CLIENT_NAME_TAG = "clientName";
/**
* Constructs a new metric publisher that uses the given executor service to record metrics and tags metrics with the
* given client name.
*
* @param recordMetricsExecutorService the executor service via which to record metrics
* @param awsClientName the name of AWS service client to which this publisher is attached
*/
public MicrometerAwsSdkMetricPublisher(final ExecutorService recordMetricsExecutorService, final String awsClientName) {
this.recordMetricsExecutorService = recordMetricsExecutorService;
this.awsClientName = awsClientName;
mostRecentMaxConcurrency = Metrics.gauge("maxConcurrency",
Tags.of(CLIENT_NAME_TAG, awsClientName),
new AtomicInteger(0));
}
@Override
public void publish(final MetricCollection metricCollection) {
/* if (METRIC_COLLECTION_TYPE_API_CALL.equals(metricCollection.name())) {
try {
recordMetricsExecutorService.submit(() -> recordApiCallMetrics(metricCollection));
} catch (final RejectedExecutionException ignored) {
// This can happen if clients make new calls to an upstream service while the server is shutting down
}
} */
}
private void recordApiCallMetrics(final MetricCollection apiCallMetricCollection) {
if (!apiCallMetricCollection.name().equals(METRIC_COLLECTION_TYPE_API_CALL)) {
throw new IllegalArgumentException("Unexpected API call metric collection name: " + apiCallMetricCollection.name());
}
final Map<String, MetricRecord<?>> metricsByName = toMetricMap(apiCallMetricCollection);
final Optional<String> maybeAwsServiceId = Optional.ofNullable(metricsByName.get("ServiceId"))
.map(metricRecord -> (String) metricRecord.value());
final Optional<String> maybeOperationName = Optional.ofNullable(metricsByName.get("OperationName"))
.map(metricRecord -> (String) metricRecord.value());
// Both the service ID and operation name SHOULD always be present, but since the metric collection is unstructured,
// we don't have any compile-time guarantees and so check that they're both present as a pedantic safety check.
if (maybeAwsServiceId.isPresent() && maybeOperationName.isPresent()) {
final String awsServiceId = maybeAwsServiceId.get();
final String operationName = maybeOperationName.get();
final boolean success = Optional.ofNullable(metricsByName.get("ApiCallSuccessful"))
.map(metricRecord -> (boolean) metricRecord.value())
.orElse(false);
final int retryCount = Optional.ofNullable(metricsByName.get("RetryCount"))
.map(metricRecord -> (int) metricRecord.value())
.orElse(0);
final Tags tags = Tags.of(
CLIENT_NAME_TAG, awsClientName,
"awsServiceId", awsServiceId,
"operationName", operationName,
"callSuccess", String.valueOf(success));
Metrics.counter(API_CALL_COUNTER_NAME, tags).increment();
DistributionSummary.builder(API_CALL_RETRY_COUNT_DISTRIBUTION_NAME)
.tags(tags)
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry)
.record(retryCount);
apiCallMetricCollection.childrenWithName(METRIC_COLLECTION_TYPE_API_CALL_ATTEMPT)
.forEach(callAttemptMetricCollection -> recordAttemptMetrics(callAttemptMetricCollection, tags));
}
}
private void recordAttemptMetrics(final MetricCollection apiCallAttemptMetricCollection, final Tags callTags) {
if (!apiCallAttemptMetricCollection.name().equals(METRIC_COLLECTION_TYPE_API_CALL_ATTEMPT)) {
throw new IllegalArgumentException("Unexpected API call attempt metric collection name: " + apiCallAttemptMetricCollection.name());
}
// A "call attempt" metric collection should always have exactly one HTTP metrics child collection, but we have no
// compiler-level guarantees and so do a pedantic check here just to be safe.
apiCallAttemptMetricCollection.childrenWithName(METRIC_COLLECTION_TYPE_HTTP_METRICS).findFirst().ifPresent(httpMetricCollection -> {
final Map<String, MetricRecord<?>> callAttemptMetricsByName = toMetricMap(apiCallAttemptMetricCollection);
final Map<String, MetricRecord<?>> httpMetricsByName = toMetricMap(httpMetricCollection);
Optional.ofNullable(httpMetricsByName.get("MaxConcurrency"))
.ifPresent(maxConcurrencyMetricRecord -> mostRecentMaxConcurrency.set((int) maxConcurrencyMetricRecord.value()));
final Tags attemptTags = Optional.ofNullable(callAttemptMetricsByName.get("ErrorType"))
.map(errorTypeMetricRecord -> callTags.and("error", errorTypeMetricRecord.value().toString()))
.orElse(callTags);
Optional.ofNullable(httpMetricsByName.get("ConcurrencyAcquireDuration"))
.ifPresent(channelAcquisitionDurationMetricRecord -> Timer.builder(CHANNEL_ACQUISITION_TIMER_NAME)
.tags(attemptTags)
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry)
.record((Duration) channelAcquisitionDurationMetricRecord.value()));
Optional.ofNullable(httpMetricsByName.get("LeasedConcurrency"))
.ifPresent(concurrentRequestsMetricRecord -> DistributionSummary.builder(CONCURRENT_REQUESTS_DISTRIBUTION_NAME)
.tags(attemptTags)
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry)
.record((int) concurrentRequestsMetricRecord.value()));
Optional.ofNullable(httpMetricsByName.get("PendingConcurrencyAcquires"))
.ifPresent(pendingChannelAcquisitionsMetricRecord -> DistributionSummary.builder(PENDING_CHANNEL_ACQUISITIONS_DISTRIBUTION_NAME)
.tags(attemptTags)
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry)
.record((int) pendingChannelAcquisitionsMetricRecord.value()));
});
}
private static Map<String, MetricRecord<?>> toMetricMap(final MetricCollection metricCollection) {
return metricCollection.stream()
.collect(Collectors.toMap(metricRecord -> metricRecord.metric().name(), metricRecord -> metricRecord));
}
@Override
public void close() {
}
}
@@ -0,0 +1,15 @@
package org.whispersystems.textsecuregcm.metrics;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.metrics.MetricPublisher;
public class NoopAwsSdkMetricPublisher implements MetricPublisher {
@Override
public void publish(final MetricCollection metricCollection) {
}
@Override
public void close() {
}
}
@@ -0,0 +1,86 @@
package org.whispersystems.textsecuregcm.metrics;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.Timer;
import org.whispersystems.textsecuregcm.util.EnumMapUtil;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
import org.whispersystems.websocket.session.WebSocketSessionContext;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
public class OpenWebSocketCounter {
private final Map<ClientPlatform, AtomicInteger> openWebsocketsByClientPlatform;
private final AtomicInteger openWebsocketsFromUnknownPlatforms;
private final Map<ClientPlatform, Timer> durationTimersByClientPlatform;
private final Timer durationTimerForUnknownPlatforms;
public OpenWebSocketCounter(final String openWebSocketGaugeName, final String durationTimerName) {
this(openWebSocketGaugeName, durationTimerName, Tags.empty());
}
public OpenWebSocketCounter(final String openWebSocketGaugeName, final String durationTimerName, final Tags tags) {
openWebsocketsByClientPlatform = EnumMapUtil.toEnumMap(ClientPlatform.class,
clientPlatform -> buildGauge(openWebSocketGaugeName, clientPlatform.name().toLowerCase(), tags));
openWebsocketsFromUnknownPlatforms = buildGauge(openWebSocketGaugeName, "unknown", tags);
durationTimersByClientPlatform = EnumMapUtil.toEnumMap(ClientPlatform.class,
clientPlatform -> buildTimer(durationTimerName, clientPlatform.name().toLowerCase(), tags));
durationTimerForUnknownPlatforms = buildTimer(durationTimerName, "unknown", tags);
}
private static AtomicInteger buildGauge(final String gaugeName, final String clientPlatformName, final Tags tags) {
return Metrics.gauge(gaugeName,
tags.and(Tag.of(UserAgentTagUtil.PLATFORM_TAG, clientPlatformName)),
new AtomicInteger(0));
}
private static Timer buildTimer(final String timerName, final String clientPlatformName, final Tags tags) {
return Timer.builder(timerName)
.publishPercentileHistogram(true)
.tags(tags.and(Tag.of(UserAgentTagUtil.PLATFORM_TAG, clientPlatformName)))
.register(Metrics.globalRegistry);
}
public void countOpenWebSocket(final WebSocketSessionContext context) {
final Timer.Sample sample = Timer.start();
// We have to jump through some hoops here to have something "effectively final" for the close listener, but
// assignable from a `catch` block.
final AtomicInteger openWebSocketCounter;
final Timer durationTimer;
{
AtomicInteger calculatedOpenWebSocketCounter;
Timer calculatedDurationTimer;
try {
final ClientPlatform clientPlatform =
UserAgentUtil.parseUserAgentString(context.getClient().getUserAgent()).getPlatform();
calculatedOpenWebSocketCounter = openWebsocketsByClientPlatform.get(clientPlatform);
calculatedDurationTimer = durationTimersByClientPlatform.get(clientPlatform);
} catch (final UnrecognizedUserAgentException e) {
calculatedOpenWebSocketCounter = openWebsocketsFromUnknownPlatforms;
calculatedDurationTimer = durationTimerForUnknownPlatforms;
}
openWebSocketCounter = calculatedOpenWebSocketCounter;
durationTimer = calculatedDurationTimer;
}
openWebSocketCounter.incrementAndGet();
context.addWebsocketClosedListener((context1, statusCode, reason) -> {
sample.stop(durationTimer);
openWebSocketCounter.decrementAndGet();
});
}
}
@@ -6,13 +6,13 @@
package org.whispersystems.textsecuregcm.providers;
import com.codahale.metrics.health.HealthCheck;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
public class RedisClusterHealthCheck extends HealthCheck {
private final FaultTolerantRedisCluster redisCluster;
private final FaultTolerantRedisClusterClient redisCluster;
public RedisClusterHealthCheck(final FaultTolerantRedisCluster redisCluster) {
public RedisClusterHealthCheck(final FaultTolerantRedisClusterClient redisCluster) {
this.redisCluster = redisCluster;
}
@@ -34,12 +34,6 @@ public class APNSender implements Managed, PushNotificationSender {
private final String bundleId;
private final ApnsClient apnsClient;
@VisibleForTesting
static final String APN_VOIP_NOTIFICATION_PAYLOAD = new SimpleApnsPayloadBuilder()
.setSound("default")
.setLocalizedAlertMessage("APN_Message")
.build();
@VisibleForTesting
static final String APN_NSE_NOTIFICATION_PAYLOAD = new SimpleApnsPayloadBuilder()
.setMutableContent(true)
@@ -80,22 +74,8 @@ public class APNSender implements Managed, PushNotificationSender {
@Override
public CompletableFuture<SendPushNotificationResult> sendNotification(final PushNotification notification) {
final String topic = switch (notification.tokenType()) {
case APN -> bundleId;
case APN_VOIP -> bundleId + ".voip";
default -> throw new IllegalArgumentException("Unsupported token type: " + notification.tokenType());
};
final boolean isVoip = notification.tokenType() == PushNotification.TokenType.APN_VOIP;
final String payload = switch (notification.notificationType()) {
case NOTIFICATION -> {
if (isVoip) {
yield APN_VOIP_NOTIFICATION_PAYLOAD;
} else {
yield notification.urgent() ? APN_NSE_NOTIFICATION_PAYLOAD : APN_BACKGROUND_PAYLOAD;
}
}
case NOTIFICATION -> notification.urgent() ? APN_NSE_NOTIFICATION_PAYLOAD : APN_BACKGROUND_PAYLOAD;
case ATTEMPT_LOGIN_NOTIFICATION_HIGH_PRIORITY -> new SimpleApnsPayloadBuilder()
.setMutableContent(true)
@@ -115,13 +95,7 @@ public class APNSender implements Managed, PushNotificationSender {
};
final PushType pushType = switch (notification.notificationType()) {
case NOTIFICATION -> {
if (isVoip) {
yield PushType.VOIP;
} else {
yield notification.urgent() ? PushType.ALERT : PushType.BACKGROUND;
}
}
case NOTIFICATION -> notification.urgent() ? PushType.ALERT : PushType.BACKGROUND;
case ATTEMPT_LOGIN_NOTIFICATION_HIGH_PRIORITY -> PushType.ALERT;
case CHALLENGE, RATE_LIMIT_CHALLENGE -> PushType.BACKGROUND;
};
@@ -131,19 +105,17 @@ public class APNSender implements Managed, PushNotificationSender {
if (pushType == PushType.BACKGROUND) {
deliveryPriority = DeliveryPriority.CONSERVE_POWER;
} else {
deliveryPriority = (notification.urgent() || isVoip)
? DeliveryPriority.IMMEDIATE
: DeliveryPriority.CONSERVE_POWER;
deliveryPriority = notification.urgent() ? DeliveryPriority.IMMEDIATE : DeliveryPriority.CONSERVE_POWER;
}
final String collapseId =
(notification.notificationType() == PushNotification.NotificationType.NOTIFICATION && notification.urgent() && !isVoip)
(notification.notificationType() == PushNotification.NotificationType.NOTIFICATION && notification.urgent())
? "incoming-message" : null;
final Instant start = Instant.now();
return apnsClient.sendNotification(new SimpleApnsPushNotification(notification.deviceToken(),
topic,
bundleId,
payload,
MAX_EXPIRATION,
deliveryPriority,
@@ -13,12 +13,12 @@ import io.lettuce.core.LettuceFutures;
import io.lettuce.core.RedisFuture;
import io.lettuce.core.ScriptOutputType;
import io.lettuce.core.cluster.SlotHash;
import io.lettuce.core.cluster.api.sync.RedisAdvancedClusterCommands;
import io.lettuce.core.cluster.api.async.RedisAdvancedClusterAsyncCommands;
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
import io.lettuce.core.cluster.pubsub.RedisClusterPubSubAdapter;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Timer;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;
import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
@@ -27,6 +27,8 @@ import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
@@ -35,8 +37,8 @@ import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubConnection;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubClusterConnection;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.storage.Device;
/**
@@ -52,8 +54,8 @@ public class ClientPresenceManager extends RedisClusterPubSubAdapter<String, Str
private final String managerId = UUID.randomUUID().toString();
private final String connectedClientSetKey = getConnectedClientSetKey(managerId);
private final FaultTolerantRedisCluster presenceCluster;
private final FaultTolerantPubSubConnection<String, String> pubSubConnection;
private final FaultTolerantRedisClusterClient presenceCluster;
private final FaultTolerantPubSubClusterConnection<String, String> pubSubConnection;
private final ClusterLuaScript clearPresenceScript;
private final ClusterLuaScript renewPresenceScript;
@@ -63,6 +65,7 @@ public class ClientPresenceManager extends RedisClusterPubSubAdapter<String, Str
private ScheduledFuture<?> pruneMissingPeersFuture;
private final Map<String, DisplacedPresenceListener> displacementListenersByPresenceKey = new ConcurrentHashMap<>();
private final Map<String, CompletionStage<?>> pendingPresenceSetsByPresenceKey = new ConcurrentHashMap<>();
private final Timer checkPresenceTimer;
private final Timer setPresenceTimer;
@@ -80,7 +83,7 @@ public class ClientPresenceManager extends RedisClusterPubSubAdapter<String, Str
private static final Logger log = LoggerFactory.getLogger(ClientPresenceManager.class);
public ClientPresenceManager(final FaultTolerantRedisCluster presenceCluster,
public ClientPresenceManager(final FaultTolerantRedisClusterClient presenceCluster,
final ScheduledExecutorService scheduledExecutorService,
final ExecutorService keyspaceNotificationExecutorService) throws IOException {
this.presenceCluster = presenceCluster;
@@ -106,7 +109,7 @@ public class ClientPresenceManager extends RedisClusterPubSubAdapter<String, Str
}
@VisibleForTesting
FaultTolerantPubSubConnection<String, String> getPubSubConnection() {
FaultTolerantPubSubClusterConnection<String, String> getPubSubConnection() {
return pubSubConnection;
}
@@ -167,14 +170,29 @@ public class ClientPresenceManager extends RedisClusterPubSubAdapter<String, Str
displacementListenersByPresenceKey.put(presenceKey, displacementListener);
presenceCluster.useCluster(connection -> {
final RedisAdvancedClusterCommands<String, String> commands = connection.sync();
commands.sadd(connectedClientSetKey, presenceKey);
commands.setex(presenceKey, PRESENCE_EXPIRATION_SECONDS, managerId);
});
final CompletableFuture<Void> presenceFuture = new CompletableFuture<>();
final CompletionStage<?> previousFuture = pendingPresenceSetsByPresenceKey.put(presenceKey, presenceFuture);
if (previousFuture != null) {
log.debug("Another presence is already pending for {}:{}", accountUuid, deviceId);
}
subscribeForRemotePresenceChanges(presenceKey);
presenceCluster.withCluster(connection -> {
final RedisAdvancedClusterAsyncCommands<String, String> commands = connection.async();
commands.sadd(connectedClientSetKey, presenceKey);
return commands.setex(presenceKey, PRESENCE_EXPIRATION_SECONDS, managerId);
}).whenComplete((result, throwable) -> {
if (throwable != null) {
presenceFuture.completeExceptionally(throwable);
} else {
presenceFuture.complete(null);
}
});
presenceFuture.whenComplete(
(ignored, throwable) -> pendingPresenceSetsByPresenceKey.remove(presenceKey, presenceFuture));
});
}
@@ -308,19 +326,38 @@ public class ClientPresenceManager extends RedisClusterPubSubAdapter<String, Str
if (channel.startsWith("__keyspace@0__:presence::{")) {
if ("set".equals(message) || "del".equals(message)) {
// for "set", another process has overwritten this presence key, which means the client has connected to another host.
// "set" might mean the client has connected to another host, although it might just be our own `set`,
// because we subscribe for changes before setting the key.
// for "del", another process has indicated the client should be disconnected
final boolean connectedElsewhere = "set".equals(message);
final boolean maybeConnectedElsewhere = "set".equals(message);
// At this point, we're on a Lettuce IO thread and need to dispatch to a separate thread before making
// synchronous Lettuce calls to avoid deadlocking.
keyspaceNotificationExecutorService.execute(() -> {
try {
displacePresence(channel.substring("__keyspace@0__:".length()), connectedElsewhere);
remoteDisplacementMeter.increment();
} catch (final Exception e) {
log.warn("Error displacing presence", e);
}
final String clientPresenceKey = channel.substring("__keyspace@0__:".length());
final CompletionStage<?> pendingConnection = pendingPresenceSetsByPresenceKey.getOrDefault(clientPresenceKey,
CompletableFuture.completedFuture(null));
pendingConnection.thenCompose(ignored -> {
if (maybeConnectedElsewhere) {
return presenceCluster.withCluster(connection -> connection.async().get(clientPresenceKey))
.thenApply(currentManagerId -> !managerId.equals(currentManagerId));
}
return CompletableFuture.completedFuture(true);
})
.exceptionally(ignored -> true)
.thenAcceptAsync(shouldDisplace -> {
if (shouldDisplace) {
try {
displacePresence(clientPresenceKey, maybeConnectedElsewhere);
remoteDisplacementMeter.increment();
} catch (final Exception e) {
log.warn("Error displacing presence", e);
}
}
}, keyspaceNotificationExecutorService);
});
}
}
@@ -70,7 +70,7 @@ public class MessageSender {
if (clientPresent) {
messagesManager.insert(account.getUuid(), device.getId(), message.toBuilder().setEphemeral(true).build());
} else {
messagesManager.removeRecipientViewFromMrmData(account.getUuid(), device.getId(), message);
messagesManager.removeRecipientViewFromMrmData(device.getId(), message);
}
} else {
messagesManager.insert(account.getUuid(), device.getId(), message);
@@ -10,12 +10,7 @@ import static com.codahale.metrics.MetricRegistry.name;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import io.dropwizard.lifecycle.Managed;
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.lettuce.core.RedisClient;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.codec.ByteArrayCodec;
import io.lettuce.core.pubsub.RedisPubSubAdapter;
import io.lettuce.core.pubsub.StatefulRedisPubSubConnection;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import java.nio.charset.StandardCharsets;
@@ -24,22 +19,17 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubConnection;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
import org.whispersystems.textsecuregcm.redis.RedisOperation;
import org.whispersystems.textsecuregcm.storage.PubSubProtos;
import org.whispersystems.textsecuregcm.util.CircuitBreakerUtil;
import org.whispersystems.textsecuregcm.websocket.InvalidWebsocketAddressException;
import org.whispersystems.textsecuregcm.websocket.ProvisioningAddress;
public class ProvisioningManager extends RedisPubSubAdapter<byte[], byte[]> implements Managed {
private final RedisClient redisClient;
private final StatefulRedisPubSubConnection<byte[], byte[]> subscriptionConnection;
private final StatefulRedisConnection<byte[], byte[]> publicationConnection;
private final FaultTolerantRedisClient pubSubClient;
private final FaultTolerantPubSubConnection<byte[], byte[]> pubSubConnection;
private final CircuitBreaker circuitBreaker;
private final Map<ProvisioningAddress, Consumer<PubSubProtos.PubSubMessage>> listenersByProvisioningAddress =
private final Map<String, Consumer<PubSubProtos.PubSubMessage>> listenersByProvisioningAddress =
new ConcurrentHashMap<>();
private static final String ACTIVE_LISTENERS_GAUGE_NAME = name(ProvisioningManager.class, "activeListeners");
@@ -52,59 +42,43 @@ public class ProvisioningManager extends RedisPubSubAdapter<byte[], byte[]> impl
private static final Logger logger = LoggerFactory.getLogger(ProvisioningManager.class);
public ProvisioningManager(final RedisClient redisClient,
final CircuitBreakerConfiguration circuitBreakerConfiguration) {
this.redisClient = redisClient;
this.subscriptionConnection = redisClient.connectPubSub(new ByteArrayCodec());
this.publicationConnection = redisClient.connect(new ByteArrayCodec());
this.circuitBreaker = CircuitBreaker.of("pubsub-breaker", circuitBreakerConfiguration.toCircuitBreakerConfig());
CircuitBreakerUtil.registerMetrics(circuitBreaker, ProvisioningManager.class, Tags.empty());
public ProvisioningManager(final FaultTolerantRedisClient pubSubClient) {
this.pubSubClient = pubSubClient;
this.pubSubConnection = pubSubClient.createBinaryPubSubConnection();
Metrics.gaugeMapSize(ACTIVE_LISTENERS_GAUGE_NAME, Tags.empty(), listenersByProvisioningAddress);
}
@Override
public void start() throws Exception {
subscriptionConnection.addListener(this);
pubSubConnection.usePubSubConnection(connection -> connection.addListener(this));
}
@Override
public void stop() throws Exception {
subscriptionConnection.removeListener(this);
subscriptionConnection.close();
publicationConnection.close();
redisClient.shutdown();
pubSubConnection.usePubSubConnection(connection -> connection.removeListener(this));
}
public void addListener(final ProvisioningAddress address, final Consumer<PubSubProtos.PubSubMessage> listener) {
public void addListener(final String address, final Consumer<PubSubProtos.PubSubMessage> listener) {
listenersByProvisioningAddress.put(address, listener);
circuitBreaker.executeRunnable(
() -> subscriptionConnection.sync().subscribe(address.serialize().getBytes(StandardCharsets.UTF_8)));
pubSubConnection.usePubSubConnection(connection -> connection.sync().subscribe(address.getBytes(StandardCharsets.UTF_8)));
}
public void removeListener(final ProvisioningAddress address) {
RedisOperation.unchecked(() -> circuitBreaker.executeRunnable(
() -> subscriptionConnection.sync().unsubscribe(address.serialize().getBytes(StandardCharsets.UTF_8))));
public void removeListener(final String address) {
RedisOperation.unchecked(() ->
pubSubConnection.usePubSubConnection(connection -> connection.sync().unsubscribe(address.getBytes(StandardCharsets.UTF_8))));
listenersByProvisioningAddress.remove(address);
}
public boolean sendProvisioningMessage(final ProvisioningAddress address, final byte[] body) {
public boolean sendProvisioningMessage(final String address, final byte[] body) {
final PubSubProtos.PubSubMessage pubSubMessage = PubSubProtos.PubSubMessage.newBuilder()
.setType(PubSubProtos.PubSubMessage.Type.DELIVER)
.setContent(ByteString.copyFrom(body))
.build();
final boolean receiverPresent = circuitBreaker.executeSupplier(
() -> publicationConnection.sync()
.publish(address.serialize().getBytes(StandardCharsets.UTF_8), pubSubMessage.toByteArray()) > 0);
final boolean receiverPresent = pubSubClient.withBinaryConnection(connection ->
connection.sync().publish(address.getBytes(StandardCharsets.UTF_8), pubSubMessage.toByteArray()) > 0);
Metrics.counter(SEND_PROVISIONING_MESSAGE_COUNTER_NAME, "online", String.valueOf(receiverPresent)).increment();
@@ -114,7 +88,7 @@ public class ProvisioningManager extends RedisPubSubAdapter<byte[], byte[]> impl
@Override
public void message(final byte[] channel, final byte[] message) {
try {
final ProvisioningAddress address = new ProvisioningAddress(new String(channel, StandardCharsets.UTF_8));
final String address = new String(channel, StandardCharsets.UTF_8);
final PubSubProtos.PubSubMessage pubSubMessage = PubSubProtos.PubSubMessage.parseFrom(message);
if (pubSubMessage.getType() == PubSubProtos.PubSubMessage.Type.DELIVER) {
@@ -129,8 +103,6 @@ public class ProvisioningManager extends RedisPubSubAdapter<byte[], byte[]> impl
Metrics.counter(RECEIVE_PROVISIONING_MESSAGE_COUNTER_NAME, "listenerPresent", String.valueOf(listenerPresent)).increment();
}
} catch (final InvalidWebsocketAddressException e) {
logger.warn("Failed to parse provisioning address", e);
} catch (final InvalidProtocolBufferException e) {
logger.warn("Failed to parse pub/sub message", e);
}
@@ -138,10 +110,6 @@ public class ProvisioningManager extends RedisPubSubAdapter<byte[], byte[]> impl
@Override
public void unsubscribed(final byte[] channel, final long count) {
try {
listenersByProvisioningAddress.remove(new ProvisioningAddress(new String(channel)));
} catch (final InvalidWebsocketAddressException e) {
logger.warn("Failed to parse provisioning address for `unsubscribe` event", e);
}
listenersByProvisioningAddress.remove(new String(channel, StandardCharsets.UTF_8));
}
}
@@ -26,7 +26,6 @@ public record PushNotification(String deviceToken,
public enum TokenType {
FCM,
APN,
APN_VOIP,
APN
}
}
@@ -90,8 +90,6 @@ public class PushNotificationManager {
if (StringUtils.isNotBlank(device.getGcmId())) {
tokenAndType = new Pair<>(device.getGcmId(), PushNotification.TokenType.FCM);
} else if (StringUtils.isNotBlank(device.getVoipApnId())) {
tokenAndType = new Pair<>(device.getVoipApnId(), PushNotification.TokenType.APN_VOIP);
} else if (StringUtils.isNotBlank(device.getApnId())) {
tokenAndType = new Pair<>(device.getApnId(), PushNotification.TokenType.APN);
} else {
@@ -115,7 +113,7 @@ public class PushNotificationManager {
final PushNotificationSender sender = switch (pushNotification.tokenType()) {
case FCM -> fcmSender;
case APN, APN_VOIP -> apnSender;
case APN -> apnSender;
};
return sender.sendNotification(pushNotification).whenComplete((result, throwable) -> {
@@ -141,18 +139,6 @@ public class PushNotificationManager {
result.errorCode(),
result.unregisteredTimestamp());
}
if (result.accepted() &&
pushNotification.tokenType() == PushNotification.TokenType.APN_VOIP &&
pushNotification.notificationType() == PushNotification.NotificationType.NOTIFICATION &&
pushNotification.destination() != null &&
pushNotification.destinationDevice() != null) {
pushNotificationScheduler.scheduleRecurringApnsVoipNotification(
pushNotification.destination(),
pushNotification.destinationDevice())
.whenComplete(logErrors());
}
} else {
logger.debug("Failed to deliver {} push notification to {} ({})",
pushNotification.notificationType(), pushNotification.deviceToken(), pushNotification.tokenType(),
@@ -183,7 +169,7 @@ public class PushNotificationManager {
tokenInvalidationTimestamp.isAfter(Instant.ofEpochMilli(device.getPushTimestamp()))).orElse(true);
if (tokenExpired) {
if (tokenType == PushNotification.TokenType.APN || tokenType == PushNotification.TokenType.APN_VOIP) {
if (tokenType == PushNotification.TokenType.APN) {
pushNotificationScheduler.cancelScheduledNotifications(account, device).whenComplete(logErrors());
}
@@ -215,7 +201,6 @@ public class PushNotificationManager {
switch (tokenType) {
case FCM -> d.setGcmId(null);
case APN -> d.setApnId(null);
case APN_VOIP -> d.setVoipApnId(null);
}
}
})));
@@ -225,7 +210,6 @@ public class PushNotificationManager {
return switch (tokenType) {
case FCM -> device.getGcmId();
case APN -> device.getApnId();
case APN_VOIP -> device.getVoipApnId();
};
}
}
@@ -19,36 +19,31 @@ import java.io.IOException;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiFunction;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.RedisClusterUtil;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public class PushNotificationScheduler implements Managed {
private static final Logger logger = LoggerFactory.getLogger(PushNotificationScheduler.class);
private static final String PENDING_RECURRING_VOIP_NOTIFICATIONS_KEY_PREFIX = "PENDING_APN";
private static final String PENDING_BACKGROUND_NOTIFICATIONS_KEY_PREFIX = "PENDING_BACKGROUND_APN";
private static final String LAST_BACKGROUND_NOTIFICATION_TIMESTAMP_KEY_PREFIX = "LAST_BACKGROUND_NOTIFICATION";
private static final String PENDING_DELAYED_NOTIFICATIONS_KEY_PREFIX = "DELAYED";
@@ -56,11 +51,6 @@ public class PushNotificationScheduler implements Managed {
@VisibleForTesting
static final String NEXT_SLOT_TO_PROCESS_KEY = "pending_notification_next_slot";
private static final Counter delivered = Metrics.counter("chat.ApnPushNotificationScheduler.voip_delivered");
private static final Counter sent = Metrics.counter("chat.ApnPushNotificationScheduler.voip_sent");
private static final Counter retry = Metrics.counter("chat.ApnPushNotificationScheduler.voip_retry");
private static final Counter evicted = Metrics.counter("chat.ApnPushNotificationScheduler.voip_evicted");
private static final Counter BACKGROUND_NOTIFICATION_SCHEDULED_COUNTER = Metrics.counter(name(PushNotificationScheduler.class, "backgroundNotification", "scheduled"));
private static final String BACKGROUND_NOTIFICATION_SENT_COUNTER_NAME = name(PushNotificationScheduler.class, "backgroundNotification", "sent");
@@ -72,13 +62,9 @@ public class PushNotificationScheduler implements Managed {
private final APNSender apnSender;
private final FcmSender fcmSender;
private final AccountsManager accountsManager;
private final FaultTolerantRedisCluster pushSchedulingCluster;
private final FaultTolerantRedisClusterClient pushSchedulingCluster;
private final Clock clock;
private final ClusterLuaScript getPendingVoipDestinationsScript;
private final ClusterLuaScript insertPendingVoipDestinationScript;
private final ClusterLuaScript removePendingVoipDestinationScript;
private final ClusterLuaScript scheduleBackgroundApnsNotificationScript;
private final Thread[] workerThreads;
@@ -117,37 +103,7 @@ public class PushNotificationScheduler implements Managed {
final int slot = (int) (pushSchedulingCluster.withCluster(connection ->
connection.sync().incr(NEXT_SLOT_TO_PROCESS_KEY)) % SlotHash.SLOT_COUNT);
return processRecurringApnsVoipNotifications(slot) +
processScheduledBackgroundApnsNotifications(slot) +
processScheduledDelayedNotifications(slot);
}
@VisibleForTesting
long processRecurringApnsVoipNotifications(final int slot) {
List<String> pendingDestinations;
long entriesProcessed = 0;
do {
pendingDestinations = getPendingDestinationsForRecurringApnsVoipNotifications(slot, PAGE_SIZE);
entriesProcessed += pendingDestinations.size();
Flux.fromIterable(pendingDestinations)
.flatMap(destination -> Mono.fromFuture(() -> getAccountAndDeviceFromPairString(destination))
.flatMap(maybeAccountAndDevice -> {
if (maybeAccountAndDevice.isPresent()) {
final Pair<Account, Device> accountAndDevice = maybeAccountAndDevice.get();
return Mono.fromFuture(() -> sendRecurringApnsVoipNotification(accountAndDevice.first(), accountAndDevice.second()));
} else {
final Pair<UUID, Byte> aciAndDeviceId = decodeAciAndDeviceId(destination);
return Mono.fromFuture(() -> removeRecurringApnsVoipNotificationEntry(aciAndDeviceId.first(), aciAndDeviceId.second()))
.then();
}
}), maxConcurrency)
.then()
.block();
} while (!pendingDestinations.isEmpty());
return entriesProcessed;
return processScheduledBackgroundApnsNotifications(slot) + processScheduledDelayedNotifications(slot);
}
@VisibleForTesting
@@ -185,7 +141,7 @@ public class PushNotificationScheduler implements Managed {
}
}
public PushNotificationScheduler(final FaultTolerantRedisCluster pushSchedulingCluster,
public PushNotificationScheduler(final FaultTolerantRedisClusterClient pushSchedulingCluster,
final APNSender apnSender,
final FcmSender fcmSender,
final AccountsManager accountsManager,
@@ -202,7 +158,7 @@ public class PushNotificationScheduler implements Managed {
}
@VisibleForTesting
PushNotificationScheduler(final FaultTolerantRedisCluster pushSchedulingCluster,
PushNotificationScheduler(final FaultTolerantRedisClusterClient pushSchedulingCluster,
final APNSender apnSender,
final FcmSender fcmSender,
final AccountsManager accountsManager,
@@ -216,13 +172,6 @@ public class PushNotificationScheduler implements Managed {
this.pushSchedulingCluster = pushSchedulingCluster;
this.clock = clock;
this.getPendingVoipDestinationsScript = ClusterLuaScript.fromResource(pushSchedulingCluster, "lua/apn/get.lua",
ScriptOutputType.MULTI);
this.insertPendingVoipDestinationScript = ClusterLuaScript.fromResource(pushSchedulingCluster, "lua/apn/insert.lua",
ScriptOutputType.VALUE);
this.removePendingVoipDestinationScript = ClusterLuaScript.fromResource(pushSchedulingCluster, "lua/apn/remove.lua",
ScriptOutputType.INTEGER);
this.scheduleBackgroundApnsNotificationScript = ClusterLuaScript.fromResource(pushSchedulingCluster,
"lua/apn/schedule_background_notification.lua", ScriptOutputType.VALUE);
@@ -233,17 +182,6 @@ public class PushNotificationScheduler implements Managed {
}
}
/**
* Schedule a recurring VOIP notification until {@link this#cancelScheduledNotifications} is called or the device is
* removed
*
* @return A CompletionStage that completes when the recurring notification has successfully been scheduled
*/
public CompletionStage<Void> scheduleRecurringApnsVoipNotification(Account account, Device device) {
sent.increment();
return insertRecurringApnsVoipNotificationEntry(account.getIdentifier(IdentityType.ACI), device.getId(), clock.millis() + (15 * 1000), (15 * 1000));
}
/**
* Schedule a background APNs notification to be sent some time in the future.
*
@@ -292,32 +230,16 @@ public class PushNotificationScheduler implements Managed {
}
/**
* Cancel a scheduled recurring VOIP notification
* Cancel scheduled notifications for the given account and device.
*
* @return A CompletionStage that completes when the scheduled task has been cancelled.
* @return A CompletionStage that completes when the scheduled notification has been cancelled.
*/
public CompletionStage<Void> cancelScheduledNotifications(Account account, Device device) {
return CompletableFuture.allOf(
cancelRecurringApnsVoipNotifications(account, device),
cancelBackgroundApnsNotifications(account, device),
cancelDelayedNotifications(account, device));
}
private CompletableFuture<Void> cancelRecurringApnsVoipNotifications(final Account account, final Device device) {
return removeRecurringApnsVoipNotificationEntry(account.getIdentifier(IdentityType.ACI), device.getId())
.thenCompose(removed -> {
if (removed) {
delivered.increment();
}
return pushSchedulingCluster.withCluster(connection ->
connection.async().zrem(
getPendingBackgroundApnsNotificationQueueKey(account, device),
encodeAciAndDeviceId(account, device)));
})
.thenRun(Util.NOOP)
.toCompletableFuture();
}
@VisibleForTesting
CompletableFuture<Void> cancelBackgroundApnsNotifications(final Account account, final Device device) {
return pushSchedulingCluster.withCluster(connection -> connection.async()
@@ -353,21 +275,6 @@ public class PushNotificationScheduler implements Managed {
}
}
private CompletableFuture<Void> sendRecurringApnsVoipNotification(final Account account, final Device device) {
if (StringUtils.isBlank(device.getVoipApnId())) {
return removeRecurringApnsVoipNotificationEntry(account.getIdentifier(IdentityType.ACI), device.getId())
.thenRun(Util.NOOP);
}
if (device.getLastSeen() < clock.millis() - TimeUnit.DAYS.toMillis(7)) {
return removeRecurringApnsVoipNotificationEntry(account.getIdentifier(IdentityType.ACI), device.getId())
.thenRun(evicted::increment);
}
return apnSender.sendNotification(new PushNotification(device.getVoipApnId(), PushNotification.TokenType.APN_VOIP, PushNotification.NotificationType.NOTIFICATION, null, account, device, true))
.thenRun(retry::increment);
}
@VisibleForTesting
CompletableFuture<Void> sendBackgroundApnsNotification(final Account account, final Device device) {
if (StringUtils.isBlank(device.getApnId())) {
@@ -443,48 +350,6 @@ public class PushNotificationScheduler implements Managed {
.flatMap(account -> account.getDevice(aciAndDeviceId.second()).map(device -> new Pair<>(account, device))));
}
private CompletableFuture<Boolean> removeRecurringApnsVoipNotificationEntry(final UUID aci, final byte deviceId) {
final String endpoint = getVoipEndpointKey(aci, deviceId);
return removePendingVoipDestinationScript.executeAsync(
List.of(getPendingRecurringApnsVoipNotificationQueueKey(endpoint), endpoint), Collections.emptyList())
.thenApply(result -> ((long) result) > 0);
}
@SuppressWarnings("unchecked")
@VisibleForTesting
List<String> getPendingDestinationsForRecurringApnsVoipNotifications(final int slot, final int limit) {
return (List<String>) getPendingVoipDestinationsScript.execute(
List.of(getPendingRecurringApnsVoipNotificationQueueKey(slot)),
List.of(String.valueOf(clock.millis()), String.valueOf(limit)));
}
@SuppressWarnings("SameParameterValue")
private CompletionStage<Void> insertRecurringApnsVoipNotificationEntry(final UUID aci, final byte deviceId, final long timestamp, final long interval) {
final String endpoint = getVoipEndpointKey(aci, deviceId);
return insertPendingVoipDestinationScript.executeAsync(
List.of(getPendingRecurringApnsVoipNotificationQueueKey(endpoint), endpoint),
List.of(String.valueOf(timestamp),
String.valueOf(interval),
aci.toString(),
String.valueOf(deviceId)))
.thenRun(Util.NOOP);
}
@VisibleForTesting
static String getVoipEndpointKey(final UUID aci, final byte deviceId) {
return "apn_device::{" + aci + "::" + deviceId + "}";
}
private static String getPendingRecurringApnsVoipNotificationQueueKey(final String endpoint) {
return getPendingRecurringApnsVoipNotificationQueueKey(SlotHash.getSlot(endpoint));
}
private static String getPendingRecurringApnsVoipNotificationQueueKey(final int slot) {
return PENDING_RECURRING_VOIP_NOTIFICATIONS_KEY_PREFIX + "::{" + RedisClusterUtil.getMinimalHashTag(slot) + "}";
}
@VisibleForTesting
static String getPendingBackgroundApnsNotificationQueueKey(final Account account, final Device device) {
return getPendingBackgroundApnsNotificationQueueKey(SlotHash.getSlot(encodeAciAndDeviceId(account, device)));
@@ -0,0 +1,65 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.redis;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import io.github.resilience4j.retry.Retry;
import io.lettuce.core.RedisException;
import io.lettuce.core.pubsub.StatefulRedisPubSubConnection;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;
import java.util.function.Consumer;
import java.util.function.Function;
abstract class AbstractFaultTolerantPubSubConnection<K, V, C extends StatefulRedisPubSubConnection<K, V>> {
private final String name;
private final C pubSubConnection;
private final Retry retry;
private final Timer executeTimer;
protected AbstractFaultTolerantPubSubConnection(final String name,
final C pubSubConnection,
final Retry retry) {
this.name = name;
this.pubSubConnection = pubSubConnection;
this.retry = retry;
this.executeTimer = Metrics.timer(name(getClass(), "execute"), "clusterName", name + "-pubsub");
}
protected String getName() {
return name;
}
public void usePubSubConnection(final Consumer<C> consumer) {
try {
retry.executeRunnable(() -> executeTimer.record(() -> consumer.accept(pubSubConnection)));
} catch (final Throwable t) {
if (t instanceof RedisException) {
throw (RedisException) t;
} else {
throw new RedisException(t);
}
}
}
public <T> T withPubSubConnection(final Function<C, T> function) {
try {
return retry.executeCallable(() -> executeTimer.record(() -> function.apply(pubSubConnection)));
} catch (final Throwable t) {
if (t instanceof RedisException) {
throw (RedisException) t;
} else {
throw new RedisException(t);
}
}
}
}
@@ -25,7 +25,7 @@ import reactor.core.publisher.Mono;
public class ClusterLuaScript {
private final FaultTolerantRedisCluster redisCluster;
private final FaultTolerantRedisClusterClient redisCluster;
private final ScriptOutputType scriptOutputType;
private final String script;
private final String sha;
@@ -35,7 +35,7 @@ public class ClusterLuaScript {
private static final Logger log = LoggerFactory.getLogger(ClusterLuaScript.class);
public static ClusterLuaScript fromResource(final FaultTolerantRedisCluster redisCluster,
public static ClusterLuaScript fromResource(final FaultTolerantRedisClusterClient redisCluster,
final String resource,
final ScriptOutputType scriptOutputType) throws IOException {
@@ -51,7 +51,7 @@ public class ClusterLuaScript {
}
@VisibleForTesting
ClusterLuaScript(final FaultTolerantRedisCluster redisCluster,
ClusterLuaScript(final FaultTolerantRedisClusterClient redisCluster,
final String script,
final ScriptOutputType scriptOutputType) {
@@ -0,0 +1,54 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.redis;
import io.github.resilience4j.retry.Retry;
import io.lettuce.core.cluster.event.ClusterTopologyChangedEvent;
import io.lettuce.core.cluster.pubsub.StatefulRedisClusterPubSubConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.scheduler.Scheduler;
public class FaultTolerantPubSubClusterConnection<K, V> extends AbstractFaultTolerantPubSubConnection<K, V, StatefulRedisClusterPubSubConnection<K, V>> {
private final Logger logger = LoggerFactory.getLogger(FaultTolerantPubSubClusterConnection.class);
private final Retry resubscribeRetry;
private final Scheduler topologyChangedEventScheduler;
protected FaultTolerantPubSubClusterConnection(final String name,
final StatefulRedisClusterPubSubConnection<K, V> pubSubConnection,
final Retry retry,
final Retry resubscribeRetry,
final Scheduler topologyChangedEventScheduler) {
super(name, pubSubConnection, retry);
pubSubConnection.setNodeMessagePropagation(true);
this.resubscribeRetry = resubscribeRetry;
this.topologyChangedEventScheduler = topologyChangedEventScheduler;
}
public void subscribeToClusterTopologyChangedEvents(final Runnable eventHandler) {
usePubSubConnection(connection -> connection.getResources().eventBus().get()
.filter(event -> event instanceof ClusterTopologyChangedEvent)
.subscribeOn(topologyChangedEventScheduler)
.subscribe(event -> {
logger.info("Got topology change event for {}, resubscribing all keyspace notifications", getName());
resubscribeRetry.executeRunnable(() -> {
try {
eventHandler.run();
} catch (final RuntimeException e) {
logger.warn("Resubscribe for {} failed", getName(), e);
throw e;
}
});
}));
}
}
@@ -5,90 +5,15 @@
package org.whispersystems.textsecuregcm.redis;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import io.github.resilience4j.retry.Retry;
import io.lettuce.core.RedisException;
import io.lettuce.core.cluster.event.ClusterTopologyChangedEvent;
import io.lettuce.core.cluster.pubsub.StatefulRedisClusterPubSubConnection;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;
import java.util.function.Consumer;
import java.util.function.Function;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.scheduler.Scheduler;
import io.lettuce.core.pubsub.StatefulRedisPubSubConnection;
public class FaultTolerantPubSubConnection<K, V> {
public class FaultTolerantPubSubConnection<K, V> extends AbstractFaultTolerantPubSubConnection<K, V, StatefulRedisPubSubConnection<K, V>> {
private static final Logger logger = LoggerFactory.getLogger(FaultTolerantPubSubConnection.class);
protected FaultTolerantPubSubConnection(final String name,
final StatefulRedisPubSubConnection<K, V> pubSubConnection,
final Retry retry) {
private final String name;
private final StatefulRedisClusterPubSubConnection<K, V> pubSubConnection;
private final Retry retry;
private final Retry resubscribeRetry;
private final Scheduler topologyChangedEventScheduler;
private final Timer executeTimer;
public FaultTolerantPubSubConnection(final String name,
final StatefulRedisClusterPubSubConnection<K, V> pubSubConnection,
final Retry retry, final Retry resubscribeRetry, final Scheduler topologyChangedEventScheduler) {
this.name = name;
this.pubSubConnection = pubSubConnection;
this.retry = retry;
this.resubscribeRetry = resubscribeRetry;
this.topologyChangedEventScheduler = topologyChangedEventScheduler;
this.pubSubConnection.setNodeMessagePropagation(true);
this.executeTimer = Metrics.timer(name(getClass(), "execute"), "clusterName", name + "-pubsub");
super(name, pubSubConnection, retry);
}
public void usePubSubConnection(final Consumer<StatefulRedisClusterPubSubConnection<K, V>> consumer) {
try {
retry.executeRunnable(() -> executeTimer.record(() -> consumer.accept(pubSubConnection)));
} catch (final Throwable t) {
if (t instanceof RedisException) {
throw (RedisException) t;
} else {
throw new RedisException(t);
}
}
}
public <T> T withPubSubConnection(final Function<StatefulRedisClusterPubSubConnection<K, V>, T> function) {
try {
return retry.executeCallable(() -> executeTimer.record(() -> function.apply(pubSubConnection)));
} catch (final Throwable t) {
if (t instanceof RedisException) {
throw (RedisException) t;
} else {
throw new RedisException(t);
}
}
}
public void subscribeToClusterTopologyChangedEvents(final Runnable eventHandler) {
usePubSubConnection(connection -> connection.getResources().eventBus().get()
.filter(event -> event instanceof ClusterTopologyChangedEvent)
.subscribeOn(topologyChangedEventScheduler)
.subscribe(event -> {
logger.info("Got topology change event for {}, resubscribing all keyspace notifications", name);
resubscribeRetry.executeRunnable(() -> {
try {
eventHandler.run();
} catch (final RuntimeException e) {
logger.warn("Resubscribe for {} failed", name, e);
throw e;
}
});
}));
}
}
@@ -0,0 +1,159 @@
package org.whispersystems.textsecuregcm.redis;
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.github.resilience4j.retry.Retry;
import io.lettuce.core.ClientOptions;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisCommandTimeoutException;
import io.lettuce.core.RedisException;
import io.lettuce.core.RedisURI;
import io.lettuce.core.TimeoutOptions;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.cluster.ClusterClientOptions;
import io.lettuce.core.cluster.ClusterTopologyRefreshOptions;
import io.lettuce.core.codec.ByteArrayCodec;
import io.lettuce.core.pubsub.StatefulRedisPubSubConnection;
import io.lettuce.core.resource.ClientResources;
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
import org.whispersystems.textsecuregcm.configuration.RedisConfiguration;
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
import org.whispersystems.textsecuregcm.util.CircuitBreakerUtil;
import reactor.core.scheduler.Schedulers;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
public class FaultTolerantRedisClient {
private final String name;
private final RedisClient redisClient;
private final StatefulRedisConnection<String, String> stringConnection;
private final StatefulRedisConnection<byte[], byte[]> binaryConnection;
private final List<StatefulRedisPubSubConnection<?, ?>> pubSubConnections = new ArrayList<>();
private final CircuitBreaker circuitBreaker;
private final Retry retry;
public FaultTolerantRedisClient(final String name,
final RedisConfiguration redisConfiguration,
final ClientResources.Builder clientResourcesBuilder) {
this(name, clientResourcesBuilder,
RedisUriUtil.createRedisUriWithTimeout(redisConfiguration.getUri(), redisConfiguration.getTimeout()),
redisConfiguration.getTimeout(),
redisConfiguration.getCircuitBreakerConfiguration(),
redisConfiguration.getRetryConfiguration());
}
FaultTolerantRedisClient(String name,
final ClientResources.Builder clientResourcesBuilder,
final RedisURI redisUri,
final Duration commandTimeout,
final CircuitBreakerConfiguration circuitBreakerConfiguration,
final RetryConfiguration retryConfiguration) {
this.name = name;
final LettuceShardCircuitBreaker lettuceShardCircuitBreaker = new LettuceShardCircuitBreaker(name,
circuitBreakerConfiguration.toCircuitBreakerConfig(), Schedulers.newSingle("topology-changed-" + name, true));
this.redisClient = RedisClient.create(clientResourcesBuilder.build(), redisUri);
this.redisClient.setOptions(ClusterClientOptions.builder()
.disconnectedBehavior(ClientOptions.DisconnectedBehavior.REJECT_COMMANDS)
.validateClusterNodeMembership(false)
.topologyRefreshOptions(ClusterTopologyRefreshOptions.builder()
.enableAllAdaptiveRefreshTriggers()
.build())
// for asynchronous commands
.timeoutOptions(TimeoutOptions.builder()
.fixedTimeout(commandTimeout)
.build())
.publishOnScheduler(true)
.build());
lettuceShardCircuitBreaker.setEventBus(redisClient.getResources().eventBus());
this.stringConnection = redisClient.connect();
this.binaryConnection = redisClient.connect(ByteArrayCodec.INSTANCE);
this.circuitBreaker = CircuitBreaker.of(name + "-breaker", circuitBreakerConfiguration.toCircuitBreakerConfig());
this.retry = Retry.of(name + "-retry", retryConfiguration.toRetryConfigBuilder()
.retryOnException(exception -> exception instanceof RedisCommandTimeoutException).build());
CircuitBreakerUtil.registerMetrics(retry, FaultTolerantRedisClusterClient.class);
}
public void shutdown() {
stringConnection.close();
for (final StatefulRedisPubSubConnection<?, ?> pubSubConnection : pubSubConnections) {
pubSubConnection.close();
}
redisClient.shutdown();
}
public String getName() {
return name;
}
public void useConnection(final Consumer<StatefulRedisConnection<String, String>> consumer) {
useConnection(stringConnection, consumer);
}
public <T> T withConnection(final Function<StatefulRedisConnection<String, String>, T> function) {
return withConnection(stringConnection, function);
}
public void useBinaryConnection(final Consumer<StatefulRedisConnection<byte[], byte[]>> consumer) {
useConnection(binaryConnection, consumer);
}
public <T> T withBinaryConnection(final Function<StatefulRedisConnection<byte[], byte[]>, T> function) {
return withConnection(binaryConnection, function);
}
public <K, V> void useConnection(final StatefulRedisConnection<K, V> connection,
final Consumer<StatefulRedisConnection<K, V>> consumer) {
try {
circuitBreaker.executeRunnable(() -> retry.executeRunnable(() -> consumer.accept(connection)));
} catch (final Throwable t) {
if (t instanceof RedisException) {
throw (RedisException) t;
} else {
throw new RedisException(t);
}
}
}
public <T, K, V> T withConnection(final StatefulRedisConnection<K, V> connection,
final Function<StatefulRedisConnection<K, V>, T> function) {
try {
return circuitBreaker.executeCallable(() -> retry.executeCallable(() -> function.apply(connection)));
} catch (final Throwable t) {
if (t instanceof RedisException) {
throw (RedisException) t;
} else {
throw new RedisException(t);
}
}
}
public FaultTolerantPubSubConnection<String, String> createPubSubConnection() {
final StatefulRedisPubSubConnection<String, String> pubSubConnection = redisClient.connectPubSub();
pubSubConnections.add(pubSubConnection);
return new FaultTolerantPubSubConnection<>(name, pubSubConnection, retry);
}
public FaultTolerantPubSubConnection<byte[], byte[]> createBinaryPubSubConnection() {
final StatefulRedisPubSubConnection<byte[], byte[]> pubSubConnection = redisClient.connectPubSub(ByteArrayCodec.INSTANCE);
pubSubConnections.add(pubSubConnection);
return new FaultTolerantPubSubConnection<>(name, pubSubConnection, retry);
}
}
@@ -34,6 +34,7 @@ import org.whispersystems.textsecuregcm.configuration.RedisClusterConfiguration;
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
import org.whispersystems.textsecuregcm.util.CircuitBreakerUtil;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
/**
@@ -41,7 +42,7 @@ import reactor.core.scheduler.Schedulers;
*
* @see LettuceShardCircuitBreaker
*/
public class FaultTolerantRedisCluster {
public class FaultTolerantRedisClusterClient {
private final String name;
@@ -56,8 +57,8 @@ public class FaultTolerantRedisCluster {
private final Retry topologyChangedEventRetry;
public FaultTolerantRedisCluster(final String name, final RedisClusterConfiguration clusterConfiguration,
final ClientResources.Builder clientResourcesBuilder) {
public FaultTolerantRedisClusterClient(final String name, final RedisClusterConfiguration clusterConfiguration,
final ClientResources.Builder clientResourcesBuilder) {
this(name, clientResourcesBuilder,
Collections.singleton(RedisUriUtil.createRedisUriWithTimeout(clusterConfiguration.getConfigurationUri(),
@@ -68,9 +69,9 @@ public class FaultTolerantRedisCluster {
}
FaultTolerantRedisCluster(String name, final ClientResources.Builder clientResourcesBuilder,
Iterable<RedisURI> redisUris, Duration commandTimeout, CircuitBreakerConfiguration circuitBreakerConfig,
RetryConfiguration retryConfiguration) {
FaultTolerantRedisClusterClient(String name, final ClientResources.Builder clientResourcesBuilder,
Iterable<RedisURI> redisUris, Duration commandTimeout, CircuitBreakerConfiguration circuitBreakerConfig,
RetryConfiguration retryConfiguration) {
this.name = name;
@@ -112,7 +113,7 @@ public class FaultTolerantRedisCluster {
this.topologyChangedEventRetry = Retry.of(name + "-topologyChangedRetry", topologyChangedEventRetryConfig);
CircuitBreakerUtil.registerMetrics(retry, FaultTolerantRedisCluster.class);
CircuitBreakerUtil.registerMetrics(retry, FaultTolerantRedisClusterClient.class);
}
public void shutdown() {
@@ -177,18 +178,27 @@ public class FaultTolerantRedisCluster {
}
}
public <T, K, V> Publisher<T> withConnectionReactive(final StatefulRedisClusterConnection<K, V> connection,
public <T, K, V> Publisher<T> withConnectionReactive(
final StatefulRedisClusterConnection<K, V> connection,
final Function<StatefulRedisClusterConnection<K, V>, Publisher<T>> function) {
return Flux.from(function.apply(connection))
.transformDeferred(RetryOperator.of(retry));
final Publisher<T> publisher = function.apply(connection);
if (publisher instanceof Mono<T> m) {
return m.transformDeferred(RetryOperator.of(retry));
}
if (publisher instanceof Flux<T> f) {
return f.transformDeferred(RetryOperator.of(retry));
}
return Flux.from(publisher).transformDeferred(RetryOperator.of(retry));
}
public FaultTolerantPubSubConnection<String, String> createPubSubConnection() {
public FaultTolerantPubSubClusterConnection<String, String> createPubSubConnection() {
final StatefulRedisClusterPubSubConnection<String, String> pubSubConnection = clusterClient.connectPubSub();
pubSubConnections.add(pubSubConnection);
return new FaultTolerantPubSubConnection<>(name, pubSubConnection, retry, topologyChangedEventRetry,
return new FaultTolerantPubSubClusterConnection<>(name, pubSubConnection, retry, topologyChangedEventRetry,
Schedulers.newSingle(name + "-redisPubSubEvents", true));
}
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.s3;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
@@ -19,33 +20,45 @@ public class PolicySigner {
private final String awsAccessSecret;
private final String region;
public PolicySigner(String awsAccessSecret, String region) {
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyyMMdd");
public PolicySigner(final String awsAccessSecret, final String region) {
this.awsAccessSecret = awsAccessSecret;
this.region = region;
this.region = region;
}
public String getSignature(ZonedDateTime now, String policy) {
// See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-create-signed-request.html
public String getSignature(final ZonedDateTime now, final String policy) {
final Mac mac;
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac = Mac.getInstance("HmacSHA256");
} catch (final NoSuchAlgorithmException e) {
throw new AssertionError("Every implementation of the Java platform is required to support HmacSHA256", e);
}
mac.init(new SecretKeySpec(("AWS4" + awsAccessSecret).getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
byte[] dateKey = mac.doFinal(now.format(DateTimeFormatter.ofPattern("yyyyMMdd")).getBytes(StandardCharsets.UTF_8));
try {
mac.init(toHmacKey(("AWS4" + awsAccessSecret).getBytes(StandardCharsets.UTF_8)));
final byte[] dateKey = mac.doFinal(now.format(DATE_FORMAT).getBytes(StandardCharsets.UTF_8));
mac.init(new SecretKeySpec(dateKey, "HmacSHA256"));
byte[] dateRegionKey = mac.doFinal(region.getBytes(StandardCharsets.UTF_8));
mac.init(toHmacKey(dateKey));
final byte[] dateRegionKey = mac.doFinal(region.getBytes(StandardCharsets.UTF_8));
mac.init(new SecretKeySpec(dateRegionKey, "HmacSHA256"));
byte[] dateRegionServiceKey = mac.doFinal("s3".getBytes(StandardCharsets.UTF_8));
mac.init(toHmacKey(dateRegionKey));
final byte[] dateRegionServiceKey = mac.doFinal("s3".getBytes(StandardCharsets.UTF_8));
mac.init(new SecretKeySpec(dateRegionServiceKey, "HmacSHA256"));
byte[] signingKey = mac.doFinal("aws4_request".getBytes(StandardCharsets.UTF_8));
mac.init(toHmacKey(dateRegionServiceKey));
final byte[] signingKey = mac.doFinal("aws4_request".getBytes(StandardCharsets.UTF_8));
mac.init(new SecretKeySpec(signingKey, "HmacSHA256"));
mac.init(toHmacKey(signingKey));
return HexFormat.of().formatHex(mac.doFinal(policy.getBytes(StandardCharsets.UTF_8)));
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
} catch (final InvalidKeyException e) {
throw new AssertionError(e);
}
}
private static Key toHmacKey(final byte[] bytes) {
return new SecretKeySpec(bytes, "HmacSHA256");
}
}
@@ -13,40 +13,42 @@ import org.whispersystems.textsecuregcm.util.Pair;
public class PostPolicyGenerator {
public static final DateTimeFormatter AWS_DATE_TIME = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX");
private static final DateTimeFormatter CREDENTIAL_DATE = DateTimeFormatter.ofPattern("yyyyMMdd" );
public static final DateTimeFormatter AWS_DATE_TIME = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX");
private static final DateTimeFormatter CREDENTIAL_DATE = DateTimeFormatter.ofPattern("yyyyMMdd");
private final String region;
private final String bucket;
private final String awsAccessId;
public PostPolicyGenerator(String region, String bucket, String awsAccessId) {
this.region = region;
this.bucket = bucket;
public PostPolicyGenerator(final String region, final String bucket, final String awsAccessId) {
this.region = region;
this.bucket = bucket;
this.awsAccessId = awsAccessId;
}
public Pair<String, String> createFor(ZonedDateTime now, String object, int maxSizeInBytes) {
String expiration = now.plusMinutes(30).format(DateTimeFormatter.ISO_INSTANT);
String credentialDate = now.format(CREDENTIAL_DATE);
String requestDate = now.format(AWS_DATE_TIME);
String credential = String.format("%s/%s/%s/s3/aws4_request", awsAccessId, credentialDate, region);
public Pair<String, String> createFor(final ZonedDateTime now, final String object, final int maxSizeInBytes) {
final String expiration = now.plusMinutes(30).format(DateTimeFormatter.ISO_INSTANT);
final String credentialDate = now.format(CREDENTIAL_DATE);
final String requestDate = now.format(AWS_DATE_TIME);
final String credential = String.format("%s/%s/%s/s3/aws4_request", awsAccessId, credentialDate, region);
String policy = String.format("{ \"expiration\": \"%s\",\n" +
" \"conditions\": [\n" +
" {\"bucket\": \"%s\"},\n" +
" {\"key\": \"%s\"},\n" +
" {\"acl\": \"private\"},\n" +
" [\"starts-with\", \"$Content-Type\", \"\"],\n" +
" [\"content-length-range\", 1, " + maxSizeInBytes + "],\n" +
"\n" +
" {\"x-amz-credential\": \"%s\"},\n" +
" {\"x-amz-algorithm\": \"AWS4-HMAC-SHA256\"},\n" +
" {\"x-amz-date\": \"%s\" }\n" +
" ]\n" +
"}", expiration, bucket, object, credential, requestDate);
final String policy = String.format("""
{
"expiration": "%s",
"conditions": [
{"bucket": "%s"},
{"key": "%s"},
{"acl": "private"},
["starts-with", "$Content-Type", ""],
["content-length-range", 1, %d],
{"x-amz-credential": "%s"},
{"x-amz-algorithm": "AWS4-HMAC-SHA256"},
{"x-amz-date": "%s" }
]
}
""", expiration, bucket, object, maxSizeInBytes, credential, requestDate);
return new Pair<>(credential, Base64.getEncoder().encodeToString(policy.getBytes(StandardCharsets.UTF_8)));
}
}
@@ -136,7 +136,7 @@ public abstract class JobScheduler {
*
* @see #processJob(byte[])
*/
public CompletableFuture<Void> processAvailableJobs() {
public Mono<Void> processAvailableJobs() {
return Flux.from(dynamoDbAsyncClient.queryPaginator(QueryRequest.builder()
.tableName(tableName)
.keyConditionExpression("#schedulerName = :schedulerName AND #runAt <= :maxRunAt")
@@ -153,7 +153,7 @@ public abstract class JobScheduler {
? item.get(ATTR_JOB_DATA).b().asByteArray()
: null;
return Mono.fromFuture(processJob(jobData))
return Mono.fromFuture(() -> processJob(jobData))
.doOnNext(outcome -> Metrics.counter(PROCESS_JOB_COUNTER_NAME,
SCHEDULER_NAME_TAG, getSchedulerName(),
OUTCOME_TAG, outcome)
@@ -164,8 +164,7 @@ public abstract class JobScheduler {
return Mono.empty();
});
}, MAX_CONCURRENCY)
.then()
.toFuture();
.then();
}
private CompletableFuture<Void> deleteJob(final AttributeValue schedulerName, final AttributeValue runAt) {
Loaded 100 of 234 files, more files were not shown because too many files have changed in this diff. Show more