Compare commits

...
Author SHA1 Message Date
Chris Eager 6e42b2898c Make BraintreeConfiguration.publicKey a SecretString 2025-10-01 13:06:56 -05:00
ravi-signal 9384813752 Forgive some clock skew when requesting ZK credentials 2025-10-01 13:03:27 -05:00
Chris Eager 70ac4ad139 Update response documentation for PUT /v1/challenge 2025-10-01 12:59:48 -05:00
Chris Eager 4ab58e950b Add authenticated tag to MetricsRequestEventListener 2025-09-29 15:37:24 -07:00
Jonathan Klabunde Tomer 7f301cbf95 filter datadog metrics with dynamic allow list 2025-09-29 15:37:11 -07:00
Ameya Lokare 5a7660d3ae Update to the latest version of the spam filter 2025-09-29 11:13:50 -07:00
Chris Eager 850172f6a3 Register system resource metrics in MetricsUtil#configureRegistries 2025-09-29 11:11:17 -07:00
Ravi Khadiwala 4e73162055 Fix default maxQuotaStaleness 2025-09-29 13:07:21 -05:00
Jonathan Klabunde Tomer 4127cf90ab also set the OTLP logging resource from config 2025-09-22 14:10:11 -07:00
Jonathan Klabunde Tomer 08cc7bc462 use standard OTLP endpoint environment variable for logging 2025-09-22 12:50:55 -07:00
ravi-signal 2cf2391f38 Avoid NPE validating invalid RegistrationRequest 2025-09-22 11:23:59 -07:00
Jonathan Klabunde Tomer 007dde8d45 add OTLP logging appender factory 2025-09-22 11:09:40 -07:00
Katherine Yen f80e30f9f2 Update to the latest version of the spam filter 2025-09-18 14:57:52 -04:00
Katherine ff5201a58e Q4 2025 dependency updates 2025-09-18 14:56:27 -04:00
Chris Eager 8954708d77 Update OptionalAccess check with PNI service IDs
This was mis-aligned with other parts of the service and client implementations
2025-09-18 13:54:11 -05:00
Katherine Yen 3cf194e476 Catch IllegalStateException when closing RecordingStream 2025-09-18 13:53:31 -05:00
Jordan Rose bad2602491 test.yml: Use libsignal's test sealed sender certificate 2025-09-18 13:52:37 -05:00
Ravi Khadiwala a647c1bfdf Update backup media metrics on all TTL refreshes 2025-09-18 13:52:13 -05:00
Ravi Khadiwala 1bba30a81e Make per-message deflate extension for websockets configurable 2025-09-18 13:51:36 -05:00
Chris Eager 827d8388d0 Fix comment typos in test.yml 2025-09-17 10:58:34 -05:00
Jordan Rose 70efb19a86 test.yml: Move sealed sender certificate from secrets bundle 2025-09-17 10:45:50 -05:00
Ravi Khadiwala 35ffb208e3 Make max total backup media configurable 2025-09-15 13:03:42 -05:00
Chris Eager e50dcd185d Update stripe-java to 28.4.0 2025-09-15 13:01:17 -05:00
Ravi Khadiwala 1cd446ee31 Add paid tag to BackupMetricsCommand counter 2025-09-12 16:41:46 -05:00
Chris Eager 1847c6d4ca Update to the latest version of the spam filter 2025-09-12 16:39:51 -05:00
ravi-signalandKatherine 1770558d5e Add an endpoint to check if your backup-id can be rotated
Co-authored-by: Katherine <katherine@signal.org>
2025-09-12 16:39:01 -05:00
Chris Eager e0d39212ec Update to the latest version of the spam filter 2025-09-11 16:24:59 -05:00
Ravi Khadiwala 31ebe9071a Don't count backup metrics on TTL refresh 2025-09-11 16:20:51 -05:00
Chris Eager 8f65486fab Update BaseRateLimiters#defaultScript 2025-09-11 13:40:35 -05:00
Ravi Khadiwala 7e3540bda0 Workaround for sdk issue iterating large DynamoDB pages 2025-09-10 11:05:29 -05:00
ravi-signalandKatherine c544628dfe Add a command to clear IAP issued receipt count
Co-authored-by: Katherine <katherine@signal.org>
2025-09-10 11:00:02 -05:00
Ravi Khadiwala 61b162d0a1 clean up warnings in BackupManagerTest 2025-09-10 10:59:47 -05:00
Ravi Khadiwala 8c2d738924 Make backup batch operation concurrency configurable 2025-09-10 10:59:47 -05:00
Ravi Khadiwala efde8a31f9 Missing Money.nanos should be treated as 0 2025-09-08 15:21:43 -05:00
Katherine b2dd315177 Set TCP timeout on Redis clients 2025-09-08 12:37:03 -04:00
Jordan Rose dc3920a99c Avoid setting the isStory field in an Envelope when possible 2025-09-05 15:33:38 -05:00
Ameya Lokare b8e8fd3313 Implement MRM insert in FoundationDB message store 2025-09-04 11:59:28 -07:00
ravi-signal a5423b6e21 Simplify SubscriptionExceptions 2025-09-04 13:50:51 -05:00
Jordan Rose 89b37015c6 Reserve a second sealed sender ServerCertificate ID 2025-09-04 13:49:15 -05:00
Ravi Khadiwala 2af3088571 Preserve backup vouchers accross re-registration 2025-09-04 13:48:45 -05:00
ravi-signal 774cc52b61 Make SubscriptionController synchronous 2025-09-02 15:11:05 -05:00
Ameya Lokare f52a262741 Update to the latest version of the spam filter 2025-08-28 13:43:53 -07:00
Jon Chambers cd957e0347 Standardize circuit breaker/retry names 2025-08-28 13:38:25 -04:00
Jon Chambers 8060d74899 Automatically register metrics/instrument breaker/retry instances on creation 2025-08-28 13:38:25 -04:00
Jon Chambers 0e1e248564 Remove resilience4j-micrometer 2025-08-28 13:38:25 -04:00
Jon Chambers d33761f107 Revert "reduce cost of resilience4j metrics"
This reverts commit 8e429e267f.
2025-08-28 13:38:25 -04:00
Jon Chambers 89c7521be0 Don't request more messages if we already have an active message source 2025-08-28 13:26:33 -04:00
Jonathan Klabunde Tomer 8e429e267f reduce cost of resilience4j metrics 2025-08-27 18:02:48 -07:00
Jon Chambers 8fe87b77e4 Wait for message acknowledgement before fetching new messags from Redis/DynamoDB 2025-08-27 15:20:05 -04:00
Jon Chambers 194e43926a Reapply "Move error/entry handling to subscribe handlers"
This reverts commit 4d521cea42.
2025-08-27 15:20:05 -04:00
Jon Chambers 4c0281f540 Reapply "Add a (failing!) test for dropped errors during WebSocketConnectionTest"
This reverts commit 0f2a4d02e0.
2025-08-27 15:20:05 -04:00
Jon Chambers 75391785f8 Reapply "Use MessageStream in WebSocketConnection"
This reverts commit a94ce72894.
2025-08-27 15:20:05 -04:00
Jon Chambers ebdc5a30f8 Restore "may have messages" methods 2025-08-27 15:20:05 -04:00
Jon Chambers f57093a94a Prefix breaker/retry names where appropriate 2025-08-27 14:45:29 -04:00
Jon Chambers 53f9c7b31f Remove unnecessary "-breaker" and "-retry" suffixes from names 2025-08-27 14:45:29 -04:00
Jon Chambers bc20aee7c9 Rename CircuitBreakerUtil to ResilienceUtil 2025-08-27 14:45:29 -04:00
Jon Chambers 807e03ca2b Remove legacy circuit breaker/retry metrics 2025-08-27 14:45:29 -04:00
Jon Chambers a747afb487 Publish metrics from circuit breaker/retry registries 2025-08-27 14:45:29 -04:00
Jon Chambers eb42d22155 Update to the latest version of the spam filter 2025-08-27 12:05:30 -04:00
Jon Chambers 8825396fc1 Restore Redis retries for select operations 2025-08-27 11:52:16 -04:00
Jon Chambers f616612104 Use central registries for Retry and CircuitBreaker instances 2025-08-27 11:33:42 -04:00
Jon Chambers a8c6fa93e0 Remove default/integral retries from Redis clients 2025-08-27 11:20:11 -04:00
Jon Chambers 32cf12e9af Remove an unused method from RetryConfiguration 2025-08-27 11:20:11 -04:00
Jon Chambers 1cc933b6bc Pause if we hit an exception while processing scheduled notifications 2025-08-27 11:05:17 -04:00
Ravi Khadiwala dbbd913445 Allow downgrade on SQPR capability 2025-08-22 11:50:55 -05:00
Jon Chambers 50e7301dd8 Remove cluster-specific configuration from Redis singleton clients 2025-08-22 12:46:32 -04:00
Jonathan Klabunde Tomer 552edbc1eb update to the latest revision of the spam filter 2025-08-21 15:25:40 -07:00
Jon Chambers 7f5ea6608c Add plumbing to roll out binary service IDs/UUIDs on envelopes to internal users 2025-08-21 14:53:41 -07:00
Jonathan Klabunde Tomer 78a7112675 Use native exponential histograms 2025-08-21 14:53:21 -07:00
Ravi Khadiwala be8b44d645 Add noise tunnel connection metrics 2025-08-21 10:32:11 -05:00
Ravi Khadiwala 7ca3604601 Augment gRPC metrics with UA 2025-08-21 10:32:11 -05:00
Ravi Khadiwala c5af8f3a9e Adjust default backup level configuration 2025-08-19 12:43:51 -05:00
Ravi Khadiwala d67847e5b1 Make s3 endpoints configurable 2025-08-19 12:29:42 -05:00
Jon Chambers 3a5704a5cc Fix a flaky MessageCacheInsertScript test by calling .join() on async operations 2025-08-19 13:14:20 -04:00
Katherine Yen 50a54136e8 Update to the latest version of the spam filter 2025-08-18 14:59:07 -04:00
ameya-signal a1d9c4c062 Check presence before updating last message versionstamp 2025-08-18 10:16:00 -07:00
Katherine 4acb3b5ac7 Use the target device's registration ID in the GET /v1/keys/identifier/deviceId ratelimit 2025-08-18 10:15:45 -07:00
ravi-signal b76eaa1098 Add a bounded virtual executor service 2025-08-15 15:49:50 -05:00
Ravi Khadiwala c883cd8148 Encourage PQ prekey upload to new store 2025-08-15 15:48:57 -05:00
Ravi Khadiwala 1e77d0471e Remove paged prekey experiment configuration 2025-08-15 15:48:57 -05:00
Jon Chambers a94ce72894 Revert "Use MessageStream in WebSocketConnection"
This reverts commit 470e17963a.
2025-08-13 16:13:50 -04:00
Jon Chambers 0f2a4d02e0 Revert "Add a (failing!) test for dropped errors during WebSocketConnectionTest"
This reverts commit fc8d180f7c.
2025-08-13 16:13:50 -04:00
Jon Chambers 4d521cea42 Revert "Move error/entry handling to subscribe handlers"
This reverts commit 7d10209198.
2025-08-13 16:13:50 -04:00
Jon Chambers 7d10209198 Move error/entry handling to subscribe handlers 2025-08-13 14:38:53 -04:00
Jon Chambers fc8d180f7c Add a (failing!) test for dropped errors during WebSocketConnectionTest 2025-08-13 14:38:53 -04:00
Jon Chambers 470e17963a Use MessageStream in WebSocketConnection 2025-08-13 10:22:55 -04:00
Chris Eager 4c5dc118aa Use nanoTime for queue drain metric 2025-08-11 18:26:40 -04:00
Chris Eager ad84cd848a Fix potential NullPointerException in StripeManager#createPaymentIntent 2025-08-11 18:26:21 -04:00
Katherine 127bd56f73 Don't require ALWAYS_CAPABLE capabilities when linking a device 2025-08-11 18:25:55 -04:00
Jon Chambers ad3721acf1 Count "send sync message" attempts with incorrect registration IDs 2025-08-11 18:24:38 -04:00
Jon Chambers 085127326b Improve thread synchronization in RedisDynamoDbMessagePublisherTest 2025-08-11 18:24:10 -04:00
Jon Chambers 2e32ab3282 Extend the Redis command timeout in FaultTolerantRedisClusterClientTest 2025-08-11 18:23:51 -04:00
ameya-signal 8bb125597b Add initial version of FoundationDB message store 2025-08-11 18:23:27 -04:00
Jonathan Klabunde Tomer 8ca7f85bf0 fix NPE in MetricsUtil#configureHistogramFilters 2025-08-11 14:11:17 -07:00
Jonathan Klabunde Tomer 9d4d36939c Update to the latest revision of the spam filter 2025-08-11 12:30:40 -07:00
Jonathan Klabunde Tomer dabe1c157b remove unnecessary MessageMetrics default constructor 2025-08-11 12:28:28 -07:00
Jonathan Klabunde TomerandJon Chambers 36d0c4422e Configure Micrometer distribution buckets for OpenTelemetry
Co-authored-by: Jon Chambers <63609320+jon-signal@users.noreply.github.com>
2025-08-11 11:45:33 -07:00
Jon Chambers 1429efd573 Retire duplicative "message delivery time" metrics 2025-08-08 13:52:20 -04:00
Katherine 93c03c5676 Hardcode ssre2 and deleteSync capabilities to true from GET /v1/profile/{identifier} 2025-08-08 09:28:13 -04:00
Katherine Yen bd1bd007c0 Count successful timezone parsing to get a ratio of success to failures 2025-08-08 09:27:46 -04:00
Katherine Yen f485406c4d Stop using device creation timestamp as a fallback in getting a recommended notification time 2025-08-08 09:27:46 -04:00
Jon Chambers d96c360016 Introduce MessageStream and RedisDynamoDbMessagePublisher 2025-08-08 09:27:05 -04:00
Jon Chambers 6d71f43b6c Update to the latest version of the spam filter 2025-08-08 09:26:21 -04:00
Katherine d6824fcaf6 Remove EncryptDeviceCreationTimestampCommand 2025-08-04 12:51:07 -04:00
Katherine 61f388f5f4 Rename registrationId field on TransferArchiveUploadedRequest 2025-08-04 12:50:56 -04:00
Jon Chambers 6955e1ee20 Retire RedisClusterHealthCheck 2025-08-04 09:59:28 -04:00
Jon Chambers 7bb4a4bc90 Remove an unused hasMessages method 2025-08-04 09:59:17 -04:00
Jon Chambers 6fa01a5d48 Remove unused Lua scripts 2025-08-04 09:59:17 -04:00
Jon Chambers 5a65a46fc1 Remove an unused constant 2025-08-04 09:59:17 -04:00
Jon Chambers c255355e5c Make internal Redis connection management methods private 2025-08-04 09:59:17 -04:00
Jon Chambers 8d3781db90 Remove the "send message" timeout 2025-08-04 09:58:56 -04:00
ravi-signal f6a87b2ec0 Always elide devices missing required PreKeys 2025-08-01 12:01:35 -05:00
ravi-signal e8a1854c5e Move /v1/svrb/auth to /v1/archives/auth/svrb 2025-08-01 12:00:44 -05:00
Katherine f8d27d8fab "encrypt timestamps" crawler optimizations 2025-08-01 12:31:09 -04:00
Jon Chambers 94dd2712b1 Extent timeout in WebSocketConnectionTest 2025-07-31 17:09:02 -04:00
Jon Chambers a4804f6501 Don't retry "connection closed" errors 2025-07-31 16:37:19 -04:00
Jon Chambers 5cb3a053fb Add a timer for sendMessage calls 2025-07-31 16:37:19 -04:00
Jon Chambers 4923b6da68 Measure only errors that terminate a message stream 2025-07-31 16:37:19 -04:00
Jon Chambers b7e64e09a3 Add an already-passing, disabled-by-default test for client WebSocket timeouts 2025-07-31 16:37:19 -04:00
Jon Chambers 76e65a47a2 Represent timeouts as Durations rather than bare millis 2025-07-31 16:37:19 -04:00
Jon Chambers ef644ce319 Drop WhisperServerServiceTest#testOtlpConfig 2025-07-31 16:27:29 -04:00
Jon Chambers 08c4179a7a Disable OpenTelemetry in tests 2025-07-31 16:27:29 -04:00
Jon Chambers 5c3be9c3d6 Use error-specific retry mechanisms in WebSocketConnection and associated classes 2025-07-31 10:53:11 -04:00
Jonathan Klabunde Tomer 8fc0b49994 tweak OpenTelemetry configuration 2025-07-30 14:42:20 -07:00
Katherine db4c71368c Use registration ID or creation timestamp in the transfer archive flow 2025-07-30 15:32:49 -04:00
Jon Chambers 30774bbc40 Remove special-case handling for an extremely narrow message delivery edge case 2025-07-29 16:52:19 -04:00
Ravi Khadiwala 3b48c82c72 Update to the latest version of the spam filter 2025-07-29 15:51:22 -05:00
255 changed files with 8868 additions and 5674 deletions

No files matched your search

+2 -2
View File
@@ -11,8 +11,8 @@ jobs:
contents: write
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- uses: actions/setup-java@3a4f6e1af504cf6a31855fa899c6aa5355ba6c12 # v4.7.0
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
- uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
with:
distribution: 'temurin'
java-version-file: .java-version
+3 -3
View File
@@ -18,13 +18,13 @@ jobs:
id-token: write
contents: read
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
- uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
with:
distribution: 'temurin'
java-version-file: .java-version
cache: 'maven'
- uses: aws-actions/configure-aws-credentials@b47578312673ae6fa5b5096b330d9fbac3d116df # v4.2.1
- uses: aws-actions/configure-aws-credentials@b47578312673ae6fa5b5096b330d9fbac3d116df # v5.0.0
name: Configure AWS credentials from Test account
with:
role-to-assume: ${{ vars.AWS_ROLE }}
+14 -7
View File
@@ -13,16 +13,21 @@ jobs:
timeout-minutes: 20
services:
foundationdb:
foundationdb0:
# Note: this should generally match the version of the FoundationDB SERVER deployed in production; it's okay if
# it's a little behind the CLIENT version.
image: foundationdb/foundationdb:7.3.62
options: --name foundationdb
options: --name foundationdb0
foundationdb1:
# Note: this should generally match the version of the FoundationDB SERVER deployed in production; it's okay if
# it's a little behind the CLIENT version.
image: foundationdb/foundationdb:7.3.62
options: --name foundationdb1
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
- name: Set up JDK
uses: actions/setup-java@3a4f6e1af504cf6a31855fa899c6aa5355ba6c12 # v4.7.0
uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
with:
distribution: 'temurin'
java-version-file: .java-version
@@ -49,12 +54,14 @@ jobs:
# ca-certificates: required for AWS CRT client
apt update && apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin ca-certificates
- name: Configure FoundationDB database
run: docker exec foundationdb /usr/bin/fdbcli --exec 'configure new single memory'
- name: Configure FoundationDB0 database
run: docker exec foundationdb0 /usr/bin/fdbcli --exec 'configure new single memory'
- name: Configure FoundationDB1 database
run: docker exec foundationdb1 /usr/bin/fdbcli --exec 'configure new single memory'
- name: Download and install FoundationDB client
run: |
./mvnw -e -B -Pexclude-spam-filter clean prepare-package -DskipTests=true
cp service/target/jib-extra/usr/lib/libfdb_c.x86_64.so /usr/lib/libfdb_c.x86_64.so
ldconfig
- name: Build with Maven
run: ./mvnw -e -B clean verify -DfoundationDb.serviceContainerName=foundationdb
run: ./mvnw -e -B clean verify -DfoundationDb.serviceContainerNamePrefix=foundationdb
BIN
View File
Binary file not shown.
+4 -4
View File
@@ -14,7 +14,7 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.2/maven-wrapper-3.3.2.jar
distributionSha256Sum=4ec3f26fb1a692473aea0235c300bd20f0f9fe741947c82c1234cefd76ac3a3c
wrapperSha256Sum=3d8f20ce6103913be8b52aef6d994e0c54705fb527324ceb9b835b338739c7a8
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.11/apache-maven-3.9.11-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.4/maven-wrapper-3.3.4.jar
distributionSha256Sum=0d7125e8c91097b36edb990ea5934e6c68b4440eef4ea96510a0f6815e7eeadb
wrapperSha256Sum=4e2fbf6554bc8a4702cdfdd3bef464f423393d784ddbb037216320ce55d5e4e1
@@ -41,7 +41,6 @@ import org.signal.libsignal.protocol.kem.KEMKeyType;
import org.signal.libsignal.protocol.kem.KEMPublicKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
import org.whispersystems.textsecuregcm.entities.DeviceActivationRequest;
@@ -306,11 +305,7 @@ public final class Operations {
private static FaultTolerantHttpClient buildClient() {
try {
return FaultTolerantHttpClient.newBuilder()
.withName("integration-test")
.withExecutor(Executors.newFixedThreadPool(16))
.withRetryExecutor(Executors.newSingleThreadScheduledExecutor())
.withCircuitBreaker(new CircuitBreakerConfiguration())
return FaultTolerantHttpClient.newBuilder("integration-test", Executors.newFixedThreadPool(16))
.withTrustedServerCertificates(CONFIG.rootCert())
.build();
} catch (final CertificateException e) {
+40 -26
View File
@@ -37,11 +37,11 @@
</modules>
<properties>
<aws.sdk2.version>2.31.70</aws.sdk2.version>
<braintree.version>3.42.0</braintree.version>
<commons-csv.version>1.14.0</commons-csv.version>
<commons-io.version>2.19.0</commons-io.version>
<dropwizard.version>4.0.12</dropwizard.version>
<aws.sdk2.version>2.33.8</aws.sdk2.version>
<braintree.version>3.44.0</braintree.version>
<commons-csv.version>1.14.1</commons-csv.version>
<commons-io.version>2.20.0</commons-io.version>
<dropwizard.version>4.0.16</dropwizard.version>
<dropwizard-metrics-datadog.version>1.1.14</dropwizard-metrics-datadog.version>
<!-- Note: when updating FoundationDB, also include a copy of `libfdb_c.so` from the FoundationDB release at
src/main/jib/usr/lib/libfdb_c.so. We use x86_64 builds without AVX instructions enabled (i.e. FoundationDB versions
@@ -50,39 +50,39 @@
<foundationdb.version>7.3.62</foundationdb.version>
<foundationdb.api-version>730</foundationdb.api-version>
<foundationdb.client-library-sha256>bfed237b787fae3cde1222676e6bfbb0d218fc27bf9e903397a7a7aa96fb2d33</foundationdb.client-library-sha256>
<google-cloud-libraries.version>26.62.0</google-cloud-libraries.version>
<google-cloud-libraries.version>26.67.0</google-cloud-libraries.version>
<grpc.version>1.73.0</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
<gson.version>2.13.1</gson.version>
<gson.version>2.13.2</gson.version>
<!-- several libraries (AWS, Google Cloud) use Apache http components transitively, and we need to align them -->
<httpcore.version>4.4.16</httpcore.version>
<httpclient.version>4.5.14</httpclient.version>
<jackson.version>2.19.1</jackson.version>
<jackson.version>2.20.0</jackson.version>
<junit-pioneer.version>2.3.0</junit-pioneer.version>
<jsr305.version>3.0.2</jsr305.version>
<kotlin.version>2.2.0</kotlin.version>
<kotlin.version>2.2.20</kotlin.version>
<!-- Logback 1.5.14+ has a null pointer bug: https://github.com/qos-ch/logback/issues/929. -->
<logback.version>1.5.13</logback.version>
<logback-access-common.version>2.0.5</logback-access-common.version>
<lettuce.version>6.7.1.RELEASE</lettuce.version>
<libphonenumber.version>9.0.8</libphonenumber.version>
<logback-access-common.version>2.0.6</logback-access-common.version>
<lettuce.version>6.8.1.RELEASE</lettuce.version>
<libphonenumber.version>9.0.13</libphonenumber.version>
<logstash.logback.version>8.1</logstash.logback.version>
<log4j-bom.version>2.25.0</log4j-bom.version>
<log4j-bom.version>2.25.1</log4j-bom.version>
<luajava.version>3.5.0</luajava.version>
<micrometer.version>1.15.1</micrometer.version>
<netty.version>4.1.122.Final</netty.version>
<micrometer.version>1.15.4</micrometer.version>
<netty.version>4.1.127.Final</netty.version>
<!-- Must be less than or equal to the value from Google libraries-bom which controls the protobuf runtime version.
See https://protobuf.dev/support/cross-version-runtime-guarantee/. -->
<protoc.version>4.29.4</protoc.version>
<pushy.version>0.15.4</pushy.version>
<reactive.grpc.version>1.2.4</reactive.grpc.version>
<reactor-bom.version>2024.0.7</reactor-bom.version> <!-- 3.7.4, see https://github.com/reactor/reactor#bom-versioning-scheme -->
<reactor-bom.version>2024.0.10</reactor-bom.version> <!-- 3.7.11, see https://github.com/reactor/reactor#bom-versioning-scheme -->
<resilience4j.version>2.3.0</resilience4j.version>
<semver4j.version>3.1.0</semver4j.version>
<simple-grpc.version>0.1.0</simple-grpc.version>
<slf4j.version>2.0.17</slf4j.version>
<stripe.version>23.10.0</stripe.version>
<swagger.version>2.2.31</swagger.version>
<testcontainers.version>1.21.2</testcontainers.version>
<stripe.version>28.4.0</stripe.version>
<swagger.version>2.2.36</swagger.version>
<testcontainers.version>1.21.3</testcontainers.version>
<!-- images to use in tests via testcontainers -->
<dynamodb.image>amazon/dynamodb-local:3.0.0@sha256:2fed5e3a965a4ba5aa6ac82baec57058b5a3848e959d705518f3fd579a77e76b</dynamodb.image>
@@ -90,8 +90,8 @@
<redis.image>redis:7.4-alpine@sha256:af1d0fc3f63b02b13ff7906c9baf7c5b390b8881ca08119cd570677fe2f60b55</redis.image>
<redis-cluster.image>docker.io/bitnami/redis-cluster:7.4@sha256:a53d023fdfaf8a8d7ddc58da040d3494e4cb45772644618ffa44c42dcd32b9af</redis-cluster.image>
<!-- eclipse-temurin:24.0.1_9-jre-noble (note: always use the multi-arch manifest *LIST* here) -->
<docker.image.sha256>a42f2330212db8bc1459a2550def18f6ec04a8c31494ffc20dea13dfa82a211e</docker.image.sha256>
<!-- eclipse-temurin:24.0.2_12-jre-noble (note: always use the multi-arch manifest *LIST* here) -->
<docker.image.sha256>85ecfc9bbb42af046d2bacbf1219d2005be4840cbfa16c2e6fd910d9ccfec95b</docker.image.sha256>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
@@ -163,6 +163,20 @@
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-bom</artifactId>
<version>1.54.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>io.opentelemetry.instrumentation</groupId>
<artifactId>opentelemetry-instrumentation-bom</artifactId>
<version>2.20.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-bom</artifactId>
@@ -246,7 +260,7 @@
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>9.7.1 </version>
<version>9.8</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -272,13 +286,13 @@
<dependency>
<groupId>com.redis</groupId>
<artifactId>testcontainers-redis</artifactId>
<version>2.2.2</version>
<version>2.2.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.signal</groupId>
<artifactId>libsignal-server</artifactId>
<version>0.76.5</version>
<version>0.80.3</version>
</dependency>
<dependency>
<groupId>org.signal</groupId>
@@ -352,7 +366,7 @@
<dependency>
<groupId>org.wiremock</groupId>
<artifactId>wiremock</artifactId>
<version>3.12.1</version>
<version>3.13.1</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -551,7 +565,7 @@
<rules>
<dependencyConvergence/>
<requireMavenVersion>
<version>3.9.9</version>
<version>3.9.11</version>
</requireMavenVersion>
</rules>
</configuration>
+1
View File
@@ -3,6 +3,7 @@ datadog.apiKey: unset
stripe.apiKey: unset
stripe.idempotencyKeyGenerator: abcdefg12345678= # base64 for creating request idempotency hash
braintree.publicKey: unset
braintree.privateKey: unset
googlePlayBilling.credentialsJson: |
+1 -1
View File
@@ -57,7 +57,7 @@ stripe:
braintree:
merchantId: unset
publicKey: unset
publicKey: secret://braintree.publicKey
privateKey: secret://braintree.privateKey
environment: unset
graphqlUrl: unset
+67 -18
View File
@@ -11,11 +11,11 @@
<artifactId>service</artifactId>
<properties>
<firebase-admin.version>9.4.3</firebase-admin.version>
<firebase-admin.version>9.6.0</firebase-admin.version>
<java-uuid-generator.version>5.1.0</java-uuid-generator.version>
<google-androidpublisher.version>v3-rev20250318-2.0.0</google-androidpublisher.version>
<storekit.version>3.4.0</storekit.version>
<webauthn4j.version>0.28.6.RELEASE</webauthn4j.version>
<google-androidpublisher.version>v3-rev20250904-2.0.0</google-androidpublisher.version>
<storekit.version>3.6.0</storekit.version>
<webauthn4j.version>0.29.6.RELEASE</webauthn4j.version>
<java-jwt.version>4.5.0</java-jwt.version>
</properties>
@@ -35,7 +35,7 @@
<artifactId>app-store-server-library</artifactId>
<version>${storekit.version}</version>
<exclusions>
<!-- conflicts with okio-jvm from apollo-api-jvm -->
<!-- conflicts with other users; resolved manually with explicit import -->
<exclusion>
<groupId>com.squareup.okio</groupId>
<artifactId>okio-jvm</artifactId>
@@ -198,6 +198,28 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-sdk</artifactId>
</dependency>
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-exporter-otlp</artifactId>
</dependency>
<dependency>
<groupId>io.opentelemetry.instrumentation</groupId>
<artifactId>opentelemetry-logback-appender-1.0</artifactId>
<!-- *all* opentelemetry-logback-appender versions are "alpha" despite the advanced version number -->
<version>2.19.0-alpha</version>
<exclusions>
<!-- incubator packages aren't included in the opentelemetry BOM, and we don't use them -->
<exclusion>
<groupId>io.opentelemetry.instrumentation</groupId>
<artifactId>opentelemetry-instrumentation-api-incubator</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>party.iroiro.luajava</groupId>
<artifactId>luajava</artifactId>
@@ -243,38 +265,47 @@
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.27.1</version>
<version>1.28.0</version>
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-pubsub</artifactId>
<exclusions>
<!-- our direct import of guava brings in a more recent version of failureaccess, so excluding it here -->
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>failureaccess</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- resolve opentelemetry-semconv conflicts from lower in firebase-admin and firestore dependency trees -->
<dependency>
<groupId>com.google.firebase</groupId>
<artifactId>firebase-admin</artifactId>
<version>${firebase-admin.version}</version>
<exclusions>
<!-- our direct import of guava brings in a more recent version of failureaccess, so excluding it here -->
<exclusion>
<groupId>io.opentelemetry.semconv</groupId>
<artifactId>opentelemetry-semconv</artifactId>
<groupId>com.google.guava</groupId>
<artifactId>failureaccess</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.opentelemetry.semconv</groupId>
<artifactId>opentelemetry-semconv</artifactId>
<version>1.30.0</version>
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-firestore</artifactId>
<exclusions>
<!-- incubator packages aren't included in the opentelemetry BOM, and we don't use them -->
<exclusion>
<groupId>io.opentelemetry.semconv</groupId>
<artifactId>opentelemetry-semconv</artifactId>
<groupId>io.opentelemetry.instrumentation</groupId>
<artifactId>opentelemetry-instrumentation-api-incubator</artifactId>
</exclusion>
<!-- our direct import of guava brings in a more recent version of failureaccess, so excluding it here -->
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>failureaccess</artifactId>
</exclusion>
</exclusions>
</dependency>
@@ -390,7 +421,7 @@
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>dynamodb-lock-client</artifactId>
<version>1.3.0</version>
<version>1.4.0</version>
</dependency>
<dependency>
@@ -432,7 +463,7 @@
<dependency>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>geocoder</artifactId>
<version>3.2</version>
<version>3.14</version>
</dependency>
<dependency>
@@ -445,6 +476,12 @@
<artifactId>netty-codec-haproxy</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-transport-native-epoll</artifactId>
<classifier>linux-x86_64</classifier>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.test-framework</groupId>
<artifactId>jersey-test-framework-core</artifactId>
@@ -538,9 +575,21 @@
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
</exclusion>
<!-- conflicts with other users; resolved manually with explicit import -->
<exclusion>
<groupId>com.squareup.okio</groupId>
<artifactId>okio-jvm</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- to resolve conflicting imports from other dependencies -->
<dependency>
<groupId>com.squareup.okio</groupId>
<artifactId>okio-jvm</artifactId>
<version>3.15.0</version>
</dependency>
</dependencies>
<profiles>
@@ -9,6 +9,7 @@ import io.dropwizard.core.Configuration;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
@@ -22,6 +23,7 @@ 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.CircuitBreakerConfiguration;
import org.whispersystems.textsecuregcm.configuration.ClientReleaseConfiguration;
import org.whispersystems.textsecuregcm.configuration.DatadogConfiguration;
import org.whispersystems.textsecuregcm.configuration.DefaultAwsCredentialsFactory;
@@ -51,6 +53,7 @@ import org.whispersystems.textsecuregcm.configuration.PaymentsServiceConfigurati
import org.whispersystems.textsecuregcm.configuration.RegistrationServiceClientFactory;
import org.whispersystems.textsecuregcm.configuration.RemoteConfigConfiguration;
import org.whispersystems.textsecuregcm.configuration.ReportMessageConfiguration;
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
import org.whispersystems.textsecuregcm.configuration.S3ObjectMonitorFactory;
import org.whispersystems.textsecuregcm.configuration.SecureStorageServiceConfiguration;
import org.whispersystems.textsecuregcm.configuration.SecureValueRecoveryConfiguration;
@@ -63,7 +66,6 @@ import org.whispersystems.textsecuregcm.configuration.TurnConfiguration;
import org.whispersystems.textsecuregcm.configuration.UnidentifiedDeliveryConfiguration;
import org.whispersystems.textsecuregcm.configuration.VirtualThreadConfiguration;
import org.whispersystems.textsecuregcm.configuration.ZkConfig;
import org.whispersystems.textsecuregcm.limits.RateLimiterConfig;
import org.whispersystems.websocket.configuration.WebSocketConfiguration;
/** @noinspection MismatchedQueryAndUpdateOfCollection, WeakerAccess */
@@ -189,11 +191,6 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private List<MaxDeviceConfiguration> maxDevices = new LinkedList<>();
@Valid
@NotNull
@JsonProperty
private Map<String, RateLimiterConfig> limits = new HashMap<>();
@Valid
@NotNull
@JsonProperty
@@ -316,7 +313,7 @@ public class WhisperServerConfiguration extends Configuration {
@Valid
@NotNull
@JsonProperty
private VirtualThreadConfiguration virtualThread = new VirtualThreadConfiguration(Duration.ofMillis(1));
private VirtualThreadConfiguration virtualThread = new VirtualThreadConfiguration();
@Valid
@NotNull
@@ -340,6 +337,17 @@ public class WhisperServerConfiguration extends Configuration {
private IdlePrimaryDeviceReminderConfiguration idlePrimaryDeviceReminder =
new IdlePrimaryDeviceReminderConfiguration(Duration.ofDays(30));
@JsonProperty
private Map<String, @Valid CircuitBreakerConfiguration> circuitBreakers = Collections.emptyMap();
@JsonProperty
private Map<String, @Valid RetryConfiguration> retries = Collections.emptyMap();
@JsonProperty
@Valid
@NotNull
private RetryConfiguration generalRedisRetry = new RetryConfiguration();
public TlsKeyStoreConfiguration getTlsKeyStoreConfiguration() {
return tlsKeyStore;
}
@@ -562,4 +570,16 @@ public class WhisperServerConfiguration extends Configuration {
public IdlePrimaryDeviceReminderConfiguration idlePrimaryDeviceReminderConfiguration() {
return idlePrimaryDeviceReminder;
}
public Map<String, CircuitBreakerConfiguration> getCircuitBreakerConfigurations() {
return circuitBreakers;
}
public Map<String, RetryConfiguration> getRetryConfigurations() {
return retries;
}
public RetryConfiguration getGeneralRedisRetryConfiguration() {
return generalRedisRetry;
}
}
@@ -27,7 +27,6 @@ import io.lettuce.core.metrics.MicrometerCommandLatencyRecorder;
import io.lettuce.core.metrics.MicrometerOptions;
import io.lettuce.core.resource.ClientResources;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.binder.grpc.MetricCollectingServerInterceptor;
import io.micrometer.core.instrument.binder.jvm.ExecutorServiceMetrics;
import io.netty.channel.local.LocalAddress;
import io.netty.channel.socket.nio.NioDatagramChannel;
@@ -64,6 +63,8 @@ import java.util.concurrent.ThreadPoolExecutor;
import java.util.function.Function;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.eclipse.jetty.websocket.core.WebSocketComponents;
import org.eclipse.jetty.websocket.core.server.WebSocketServerComponents;
import org.eclipse.jetty.websocket.server.config.JettyWebSocketServletContainerInitializer;
import org.glassfish.jersey.server.ServerProperties;
import org.signal.i18n.HeaderControlledResourceBundleLookup;
@@ -93,6 +94,7 @@ import org.whispersystems.textsecuregcm.backup.BackupManager;
import org.whispersystems.textsecuregcm.backup.BackupsDb;
import org.whispersystems.textsecuregcm.backup.Cdn3BackupCredentialGenerator;
import org.whispersystems.textsecuregcm.backup.Cdn3RemoteStorageManager;
import org.whispersystems.textsecuregcm.backup.SecureValueRecoveryBCredentialsGeneratorFactory;
import org.whispersystems.textsecuregcm.badges.ConfiguredProfileBadgeConverter;
import org.whispersystems.textsecuregcm.captcha.CaptchaChecker;
import org.whispersystems.textsecuregcm.captcha.CaptchaClient;
@@ -126,7 +128,6 @@ import org.whispersystems.textsecuregcm.controllers.RemoteConfigController;
import org.whispersystems.textsecuregcm.controllers.RemoteConfigControllerV1;
import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery2Controller;
import org.whispersystems.textsecuregcm.controllers.SecureValueRecoveryBController;
import org.whispersystems.textsecuregcm.controllers.StickerController;
import org.whispersystems.textsecuregcm.controllers.SubscriptionController;
import org.whispersystems.textsecuregcm.controllers.VerificationController;
@@ -147,6 +148,7 @@ import org.whispersystems.textsecuregcm.grpc.ExternalServiceCredentialsAnonymous
import org.whispersystems.textsecuregcm.grpc.ExternalServiceCredentialsGrpcService;
import org.whispersystems.textsecuregcm.grpc.KeysAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.KeysGrpcService;
import org.whispersystems.textsecuregcm.grpc.MetricServerInterceptor;
import org.whispersystems.textsecuregcm.grpc.PaymentsGrpcService;
import org.whispersystems.textsecuregcm.grpc.ProfileAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.ProfileGrpcService;
@@ -191,7 +193,6 @@ import org.whispersystems.textsecuregcm.metrics.ReportedMessageMetricsListener;
import org.whispersystems.textsecuregcm.metrics.TlsCertificateExpirationUtil;
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.FcmSender;
import org.whispersystems.textsecuregcm.push.MessageSender;
@@ -258,7 +259,9 @@ import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
import org.whispersystems.textsecuregcm.util.BufferingInterceptor;
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
import org.whispersystems.textsecuregcm.util.ManagedAwsCrt;
import org.whispersystems.textsecuregcm.util.ManagedExecutors;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
import org.whispersystems.textsecuregcm.util.VirtualExecutorServiceProvider;
@@ -272,8 +275,8 @@ import org.whispersystems.textsecuregcm.workers.BackupMetricsCommand;
import org.whispersystems.textsecuregcm.workers.BackupUsageRecalculationCommand;
import org.whispersystems.textsecuregcm.workers.CertificateCommand;
import org.whispersystems.textsecuregcm.workers.CheckDynamicConfigurationCommand;
import org.whispersystems.textsecuregcm.workers.ClearIssuedReceiptRedemptionsCommand;
import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
import org.whispersystems.textsecuregcm.workers.EncryptDeviceCreationTimestampCommand;
import org.whispersystems.textsecuregcm.workers.IdleDeviceNotificationSchedulerFactory;
import org.whispersystems.textsecuregcm.workers.MessagePersisterServiceCommand;
import org.whispersystems.textsecuregcm.workers.NotifyIdleDevicesCommand;
@@ -342,13 +345,13 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
bootstrap.addCommand(new BackupUsageRecalculationCommand());
bootstrap.addCommand(new RemoveExpiredLinkedDevicesCommand());
bootstrap.addCommand(new NotifyIdleDevicesCommand());
bootstrap.addCommand(new ClearIssuedReceiptRedemptionsCommand());
bootstrap.addCommand(new ProcessScheduledJobsServiceCommand("process-idle-device-notification-jobs",
"Processes scheduled jobs to send notifications to idle devices",
new IdleDeviceNotificationSchedulerFactory()));
bootstrap.addCommand(new RegenerateSecondaryDynamoDbTableDataCommand());
bootstrap.addCommand(new EncryptDeviceCreationTimestampCommand());
}
@Override
@@ -365,6 +368,14 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
UncaughtExceptionHandler.register();
config.getCircuitBreakerConfigurations().forEach((name, configuration) ->
ResilienceUtil.getCircuitBreakerRegistry().addConfiguration(name, configuration.toCircuitBreakerConfig()));
config.getRetryConfigurations().forEach((name, configuration) ->
ResilienceUtil.getRetryRegistry().addConfiguration(name, configuration.toRetryConfigBuilder().build()));
ResilienceUtil.setGeneralRedisRetryConfiguration(config.getGeneralRedisRetryConfiguration());
ScheduledExecutorService dynamicConfigurationExecutor = ScheduledExecutorServiceBuilder.of(environment, "dynamicConfiguration")
.threads(1).build();
@@ -374,6 +385,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
dynamicConfigurationManager.start();
MetricsUtil.configureRegistries(config, environment, dynamicConfigurationManager);
MetricsUtil.configureLogging(config, environment);
ExperimentEnrollmentManager experimentEnrollmentManager = new ExperimentEnrollmentManager(dynamicConfigurationManager);
@@ -398,8 +410,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
environment.lifecycle().manage(new ManagedAwsCrt());
final ExecutorService awsSdkMetricsExecutor = environment.lifecycle()
.virtualExecutorService(name(getClass(), "awsSdkMetrics-%d"));
final ExecutorService awsSdkMetricsExecutor = ManagedExecutors.newVirtualThreadPerTaskExecutor(
"awsSdkMetrics",
config.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor(),
environment);
final DynamoDbAsyncClient dynamoDbAsyncClient = config.getDynamoDbClientConfiguration()
.buildAsyncClient(awsCredentialsProvider, new MicrometerAwsSdkMetricPublisher(awsSdkMetricsExecutor, "dynamoDbAsync"));
@@ -411,6 +425,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final S3AsyncClient asyncCdnS3Client = S3AsyncClient.builder()
.credentialsProvider(cdnCredentialsProvider)
.region(Region.of(config.getCdnConfiguration().region()))
.endpointOverride(config.getCdnConfiguration().endpointOverride())
.build();
BlockingQueue<Runnable> messageDeletionQueue = new LinkedBlockingQueue<>();
@@ -442,6 +457,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
S3AsyncClient asyncKeysS3Client = S3AsyncClient.builder()
.credentialsProvider(awsCredentialsProvider)
.region(Region.of(config.getPagedSingleUseKEMPreKeyStore().region()))
.endpointOverride(config.getPagedSingleUseKEMPreKeyStore().endpointOverride())
.build();
KeysManager keysManager = new KeysManager(
new SingleUseECPreKeyStore(dynamoDbAsyncClient, config.getDynamoDbTables().getEcKeys().getTableName()),
@@ -452,12 +468,11 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getDynamoDbTables().getPagedKemKeys().getTableName(),
config.getPagedSingleUseKEMPreKeyStore().bucket()),
new RepeatedUseECSignedPreKeyStore(dynamoDbAsyncClient, config.getDynamoDbTables().getEcSignedPreKeys().getTableName()),
new RepeatedUseKEMSignedPreKeyStore(dynamoDbAsyncClient, config.getDynamoDbTables().getKemLastResortKeys().getTableName()),
experimentEnrollmentManager);
new RepeatedUseKEMSignedPreKeyStore(dynamoDbAsyncClient, config.getDynamoDbTables().getKemLastResortKeys().getTableName()));
MessagesDynamoDb messagesDynamoDb = new MessagesDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
config.getDynamoDbTables().getMessages().getTableName(),
config.getDynamoDbTables().getMessages().getExpiration(),
messageDeletionAsyncExecutor);
messageDeletionAsyncExecutor, experimentEnrollmentManager);
RemoteConfigs remoteConfigs = new RemoteConfigs(dynamoDbClient,
config.getDynamoDbTables().getRemoteConfig().getTableName());
PushChallengeDynamoDb pushChallengeDynamoDb = new PushChallengeDynamoDb(dynamoDbClient,
@@ -504,7 +519,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
messageDeliveryQueue);
ScheduledExecutorService recurringJobExecutor = ScheduledExecutorServiceBuilder.of(environment, "recurringJob").threads(6).build();
ScheduledExecutorService websocketScheduledExecutor = ScheduledExecutorServiceBuilder.of(environment, "websocket").threads(8).build();
ExecutorService apnSenderExecutor = ExecutorServiceBuilder.of(environment, "apnSender")
.maxThreads(1).minThreads(1).build();
ExecutorService fcmSenderExecutor = ExecutorServiceBuilder.of(environment, "fcmSender")
@@ -517,13 +531,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
.minThreads(1).maxThreads(1).build();
ExecutorService asyncOperationQueueingExecutor = ExecutorServiceBuilder.of(environment, "asyncOperationQueueing")
.minThreads(1).maxThreads(1).build();
ScheduledExecutorService secureValueRecoveryServiceRetryExecutor =
ScheduledExecutorServiceBuilder.of(environment, "secureValueRecoveryServiceRetry").threads(1).build();
ScheduledExecutorService storageServiceRetryExecutor =
ScheduledExecutorServiceBuilder.of(environment, "storageServiceRetry").threads(1).build();
ScheduledExecutorService remoteStorageRetryExecutor =
ScheduledExecutorServiceBuilder.of(environment, "remoteStorageRetry").threads(1).build();
ScheduledExecutorService registrationIdentityTokenRefreshExecutor =
final ScheduledExecutorService retryExecutor = ScheduledExecutorServiceBuilder.of(environment, "retry")
.threads(16).build();
final ScheduledExecutorService registrationIdentityTokenRefreshExecutor =
ScheduledExecutorServiceBuilder.of(environment, "registrationIdentityTokenRefresh").threads(1).build();
Scheduler messageDeliveryScheduler = Schedulers.fromExecutorService(
@@ -536,11 +547,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
// TODO: generally speaking this is a DynamoDB I/O executor for the accounts table; we should eventually have a general executor for speaking to the accounts table, but most of the server is still synchronous so this isn't widely useful yet
ExecutorService batchIdentityCheckExecutor = ExecutorServiceBuilder.of(environment, "batchIdentityCheck").minThreads(32).maxThreads(32).build();
ExecutorService subscriptionProcessorExecutor = ExecutorServiceBuilder.of(environment, "subscriptionProcessor")
.maxThreads(availableProcessors) // mostly this is IO bound so tying to number of processors is tenuous at best
.minThreads(availableProcessors) // mostly this is IO bound so tying to number of processors is tenuous at best
.allowCoreThreadTimeOut(true).
build();
ExecutorService receiptSenderExecutor = ExecutorServiceBuilder.of(environment, "receiptSender")
.maxThreads(2)
.minThreads(2)
@@ -566,17 +573,20 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
.maxThreads(2)
.minThreads(2)
.build();
ExecutorService googlePlayBillingExecutor = environment.lifecycle()
.virtualExecutorService(name(getClass(), "googlePlayBilling-%d"));
ExecutorService appleAppStoreExecutor = environment.lifecycle()
.virtualExecutorService(name(getClass(), "appleAppStore-%d"));
ExecutorService clientEventExecutor = environment.lifecycle()
.virtualExecutorService(name(getClass(), "clientEvent-%d"));
ExecutorService disconnectionRequestListenerExecutor = environment.lifecycle()
.virtualExecutorService(name(getClass(), "disconnectionRequest-%d"));
ScheduledExecutorService appleAppStoreRetryExecutor = ScheduledExecutorServiceBuilder.of(environment, "appleAppStoreRetry").threads(1).build();
ScheduledExecutorService subscriptionProcessorRetryExecutor = ScheduledExecutorServiceBuilder.of(environment, "subscriptionProcessorRetry").threads(1).build();
ExecutorService subscriptionProcessorExecutor = ManagedExecutors.newVirtualThreadPerTaskExecutor(
"subscriptionProcessor",
config.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor(),
environment);
ExecutorService clientEventExecutor = ManagedExecutors.newVirtualThreadPerTaskExecutor(
"clientEvent",
config.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor(),
environment);
ExecutorService disconnectionRequestListenerExecutor = ManagedExecutors.newVirtualThreadPerTaskExecutor(
"disconnectionRequest",
config.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor(),
environment);
ScheduledExecutorService cloudflareTurnRetryExecutor = ScheduledExecutorServiceBuilder.of(environment, "cloudflareTurnRetry").threads(1).build();
ScheduledExecutorService messagePollExecutor = ScheduledExecutorServiceBuilder.of(environment, "messagePollExecutor").threads(1).build();
ScheduledExecutorService provisioningWebsocketTimeoutExecutor = ScheduledExecutorServiceBuilder.of(environment, "provisioningWebsocketTimeout").threads(1).build();
@@ -596,9 +606,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
ExternalServiceCredentialsGenerator paymentsCredentialsGenerator = PaymentsController.credentialsGenerator(
config.getPaymentsServiceConfiguration());
ExternalServiceCredentialsGenerator svr2CredentialsGenerator = SecureValueRecovery2Controller.credentialsGenerator(
config.getSvr2Configuration());
ExternalServiceCredentialsGenerator svrbCredentialsGenerator = SecureValueRecoveryBController.credentialsGenerator(
config.getSvrbConfiguration());
config.getSvr2Configuration());
ExternalServiceCredentialsGenerator svrbCredentialsGenerator =
SecureValueRecoveryBCredentialsGeneratorFactory.svrbCredentialsGenerator(config.getSvrbConfiguration());
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager =
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords);
@@ -615,49 +625,51 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
SecureValueRecoveryClient secureValueRecovery2Client = new SecureValueRecoveryClient(
svr2CredentialsGenerator,
secureValueRecoveryServiceExecutor,
secureValueRecoveryServiceRetryExecutor,
retryExecutor,
config.getSvr2Configuration(),
() -> dynamicConfigurationManager.getConfiguration().getSvr2StatusCodesToIgnoreForAccountDeletion());
SecureValueRecoveryClient secureValueRecoveryBClient = new SecureValueRecoveryClient(
svrbCredentialsGenerator,
secureValueRecoveryServiceExecutor,
secureValueRecoveryServiceRetryExecutor,
retryExecutor,
config.getSvrbConfiguration(),
() -> dynamicConfigurationManager.getConfiguration().getSvrbStatusCodesToIgnoreForAccountDeletion());
SecureStorageClient secureStorageClient = new SecureStorageClient(storageCredentialsGenerator,
storageServiceExecutor, storageServiceRetryExecutor, config.getSecureStorageServiceConfiguration());
storageServiceExecutor, retryExecutor, config.getSecureStorageServiceConfiguration());
final GrpcClientConnectionManager grpcClientConnectionManager = new GrpcClientConnectionManager();
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient, grpcClientConnectionManager, disconnectionRequestListenerExecutor);
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster, asyncCdnS3Client, config.getCdnConfiguration().bucket());
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient,
grpcClientConnectionManager, disconnectionRequestListenerExecutor, retryExecutor);
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster, retryExecutor, asyncCdnS3Client,
config.getCdnConfiguration().bucket());
MessagesCache messagesCache = new MessagesCache(messagesCluster, messageDeliveryScheduler,
messageDeletionAsyncExecutor, clock);
messageDeletionAsyncExecutor, retryExecutor, clock, experimentEnrollmentManager);
ClientReleaseManager clientReleaseManager = new ClientReleaseManager(clientReleases,
recurringJobExecutor,
config.getClientReleaseConfiguration().refreshInterval(),
Clock.systemUTC());
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster,
config.getReportMessageConfiguration().getCounterTtl());
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager,
messageDeletionAsyncExecutor, Clock.systemUTC());
RedisMessageAvailabilityManager redisMessageAvailabilityManager =
new RedisMessageAvailabilityManager(messagesCluster, clientEventExecutor, asyncOperationQueueingExecutor);
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
reportMessageManager, messageDeletionAsyncExecutor, Clock.systemUTC());
AccountLockManager accountLockManager = new AccountLockManager(dynamoDbClient,
config.getDynamoDbTables().getDeletedAccountsLock().getTableName());
ClientPublicKeysManager clientPublicKeysManager =
new ClientPublicKeysManager(clientPublicKeys, accountLockManager, accountLockExecutor);
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
pubsubClient, accountLockManager, keysManager, messagesManager, profilesManager,
secureStorageClient, secureValueRecovery2Client, secureValueRecoveryBClient, disconnectionRequestManager,
secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
registrationRecoveryPasswordsManager, clientPublicKeysManager, accountLockExecutor, messagePollExecutor,
clock, config.getLinkDeviceSecretConfiguration().secret().value(), dynamicConfigurationManager);
retryExecutor, 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());
PushNotificationScheduler pushNotificationScheduler = new PushNotificationScheduler(pushSchedulerCluster,
apnSender, fcmSender, accountsManager, 0, 0);
apnSender, fcmSender, accountsManager, 0, 0, retryExecutor);
PushNotificationManager pushNotificationManager =
new PushNotificationManager(accountsManager, apnSender, fcmSender, pushNotificationScheduler);
RedisMessageAvailabilityManager redisMessageAvailabilityManager =
new RedisMessageAvailabilityManager(accountsManager, pushNotificationManager, messagesCluster, clientEventExecutor, asyncOperationQueueingExecutor);
RateLimiters rateLimiters = RateLimiters.create(dynamicConfigurationManager, rateLimitersCluster);
RateLimiters rateLimiters = RateLimiters.create(dynamicConfigurationManager, rateLimitersCluster, retryExecutor);
ProvisioningManager provisioningManager = new ProvisioningManager(pubsubClient);
IssuedReceiptsManager issuedReceiptsManager = new IssuedReceiptsManager(
config.getDynamoDbTables().getIssuedReceipts().getTableName(),
@@ -697,9 +709,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getTurnConfiguration().cloudflare().urlsWithIps(),
config.getTurnConfiguration().cloudflare().hostname(),
config.getTurnConfiguration().cloudflare().numHttpClients(),
config.getTurnConfiguration().cloudflare().circuitBreaker(),
config.getTurnConfiguration().cloudflare().circuitBreakerConfigurationName(),
cloudflareTurnHttpExecutor,
config.getTurnConfiguration().cloudflare().retry(),
config.getTurnConfiguration().cloudflare().retryConfigurationName(),
cloudflareTurnRetryExecutor,
cloudflareDnsResolver
);
@@ -728,25 +740,23 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
StripeManager stripeManager = new StripeManager(config.getStripe().apiKey().value(), subscriptionProcessorExecutor,
config.getStripe().idempotencyKeyGenerator().value(), config.getStripe().boostDescription(), config.getStripe().supportedCurrenciesByPaymentMethod());
BraintreeManager braintreeManager = new BraintreeManager(config.getBraintree().merchantId(),
config.getBraintree().publicKey(), config.getBraintree().privateKey().value(),
config.getBraintree().publicKey().value(), config.getBraintree().privateKey().value(),
config.getBraintree().environment(),
config.getBraintree().supportedCurrenciesByPaymentMethod(), config.getBraintree().merchantAccounts(),
config.getBraintree().graphqlUrl(), currencyManager, config.getBraintree().pubSubPublisher().build(),
config.getBraintree().circuitBreaker(), subscriptionProcessorExecutor,
subscriptionProcessorRetryExecutor);
config.getBraintree().circuitBreakerConfigurationName(), subscriptionProcessorExecutor);
GooglePlayBillingManager googlePlayBillingManager = new GooglePlayBillingManager(
new ByteArrayInputStream(config.getGooglePlayBilling().credentialsJson().value().getBytes(StandardCharsets.UTF_8)),
config.getGooglePlayBilling().packageName(),
config.getGooglePlayBilling().applicationName(),
config.getGooglePlayBilling().productIdToLevel(),
googlePlayBillingExecutor);
config.getGooglePlayBilling().productIdToLevel());
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);
config.getAppleAppStore().retryConfigurationName());
environment.lifecycle().manage(apnSender);
environment.lifecycle().manage(pushNotificationScheduler);
@@ -790,7 +800,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
clock);
final Cdn3RemoteStorageManager cdn3RemoteStorageManager = new Cdn3RemoteStorageManager(
remoteStorageHttpExecutor,
remoteStorageRetryExecutor,
retryExecutor,
config.getCdn3StorageManagerConfiguration());
BackupManager backupManager = new BackupManager(
backupsDb,
@@ -799,7 +809,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
tusAttachmentGenerator,
cdn3BackupCredentialGenerator,
cdn3RemoteStorageManager,
clock);
svrbCredentialsGenerator,
secureValueRecoveryBClient,
clock,
dynamicConfigurationManager);
final AppleDeviceChecks appleDeviceChecks = new AppleDeviceChecks(
dynamoDbClient,
@@ -818,8 +831,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final ManagedDefaultEventLoopGroup localEventLoopGroup = new ManagedDefaultEventLoopGroup();
final RemoteDeprecationFilter remoteDeprecationFilter = new RemoteDeprecationFilter(dynamicConfigurationManager);
final MetricCollectingServerInterceptor metricCollectingServerInterceptor =
new MetricCollectingServerInterceptor(Metrics.globalRegistry);
final MetricServerInterceptor metricServerInterceptor = new MetricServerInterceptor(Metrics.globalRegistry, clientReleaseManager);
final ErrorMappingInterceptor errorMappingInterceptor = new ErrorMappingInterceptor();
final RequestAttributesInterceptor requestAttributesInterceptor =
@@ -841,8 +853,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new ExternalRequestFilter(config.getExternalRequestFilterConfiguration().permittedInternalRanges(),
config.getExternalRequestFilterConfiguration().grpcMethods()))
.intercept(validatingInterceptor)
// TODO: specialize metrics with user-agent platform
.intercept(metricCollectingServerInterceptor)
.intercept(metricServerInterceptor)
.intercept(errorMappingInterceptor)
.intercept(remoteDeprecationFilter)
.intercept(requestAttributesInterceptor)
@@ -862,9 +873,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
// depends on the user-agent context so it has to come first here!
// http://grpc.github.io/grpc-java/javadoc/io/grpc/ServerBuilder.html#intercept-io.grpc.ServerInterceptor-
serverBuilder
// TODO: specialize metrics with user-agent platform
.intercept(validatingInterceptor)
.intercept(metricCollectingServerInterceptor)
.intercept(metricServerInterceptor)
.intercept(errorMappingInterceptor)
.intercept(remoteDeprecationFilter)
.intercept(requestAttributesInterceptor)
@@ -979,7 +989,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
environment.jersey().register(new BufferingInterceptor());
environment.jersey().register(new RestDeprecationFilter(dynamicConfigurationManager, experimentEnrollmentManager));
environment.jersey().register(new VirtualExecutorServiceProvider("managed-async-virtual-thread-"));
environment.jersey().register(new VirtualExecutorServiceProvider(
"managed-async-virtual-thread",
config.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor()));
environment.jersey().register(new RateLimitByIpFilter(rateLimiters));
environment.jersey().register(new RequestStatisticsFilter(TrafficSource.HTTP));
environment.jersey().register(MultiRecipientMessageProvider.class);
@@ -990,14 +1002,17 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
///
WebSocketEnvironment<AuthenticatedDevice> webSocketEnvironment = new WebSocketEnvironment<>(environment,
config.getWebSocketConfiguration(), Duration.ofMillis(90000));
webSocketEnvironment.jersey().register(new VirtualExecutorServiceProvider("managed-async-websocket-virtual-thread-"));
webSocketEnvironment.jersey().register(new VirtualExecutorServiceProvider(
"managed-async-websocket-virtual-thread",
config.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor()));
webSocketEnvironment.setAuthenticator(new WebSocketAccountAuthenticator(accountAuthenticator));
webSocketEnvironment.setAuthenticatedWebSocketUpgradeFilter(new IdlePrimaryDeviceAuthenticatedWebSocketUpgradeFilter(
config.idlePrimaryDeviceReminderConfiguration().minIdleDuration(), Clock.systemUTC()));
webSocketEnvironment.setConnectListener(
new AuthenticatedConnectListener(accountsManager, receiptSender, messagesManager, messageMetrics, pushNotificationManager,
pushNotificationScheduler, redisMessageAvailabilityManager, disconnectionRequestManager, websocketScheduledExecutor,
messageDeliveryScheduler, clientReleaseManager, messageDeliveryLoopMonitor, experimentEnrollmentManager));
pushNotificationScheduler, disconnectionRequestManager,
messageDeliveryScheduler, clientReleaseManager, messageDeliveryLoopMonitor, experimentEnrollmentManager
));
webSocketEnvironment.jersey().register(new RateLimitByIpFilter(rateLimiters));
webSocketEnvironment.jersey().register(new RequestStatisticsFilter(TrafficSource.WEBSOCKET));
webSocketEnvironment.jersey().register(MultiRecipientMessageProvider.class);
@@ -1116,7 +1131,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new RemoteConfigController(remoteConfigsManager, config.getRemoteConfigConfiguration().globalConfig(), clock),
new SecureStorageController(storageCredentialsGenerator),
new SecureValueRecovery2Controller(svr2CredentialsGenerator, accountsManager),
new SecureValueRecoveryBController(svrbCredentialsGenerator),
new StickerController(rateLimiters, config.getCdnConfiguration().credentials().accessKeyId().value(),
config.getCdnConfiguration().credentials().secretAccessKey().value(), config.getCdnConfiguration().region(),
config.getCdnConfiguration().bucket()),
@@ -1131,7 +1145,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
zkReceiptOperations, issuedReceiptsManager);
commonControllers.add(new SubscriptionController(clock, config.getSubscription(), config.getOneTimeDonations(),
subscriptionManager, stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager,
profileBadgeConverter, bankMandateTranslator));
profileBadgeConverter, bankMandateTranslator, dynamicConfigurationManager));
commonControllers.add(new OneTimeDonationController(clock, config.getOneTimeDonations(), stripeManager, braintreeManager,
zkReceiptOperations, issuedReceiptsManager, oneTimeDonationsManager));
}
@@ -1154,7 +1168,13 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
webSocketEnvironment.jersey().property(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE);
provisioningEnvironment.jersey().property(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE);
JettyWebSocketServletContainerInitializer.configure(environment.getApplicationContext(), null);
JettyWebSocketServletContainerInitializer.configure(environment.getApplicationContext(), (context, container) -> {
if (config.getWebSocketConfiguration().isDisablePerMessageDeflate()) {
WebSocketComponents components =
WebSocketServerComponents.getWebSocketComponents(environment.getApplicationContext().getServletContext());
components.getExtensionRegistry().unregister("permessage-deflate");
}
});
WebSocketResourceProviderFactory<AuthenticatedDevice> webSocketServlet = new WebSocketResourceProviderFactory<>(
webSocketEnvironment, AuthenticatedDevice.class, config.getWebSocketConfiguration(),
@@ -1173,11 +1193,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
provisioning.setAsyncSupported(true);
environment.admin().addTask(new SetRequestLoggingEnabledTask());
// healthcheck, admin port
environment.healthChecks().register("cacheCluster", new RedisClusterHealthCheck(cacheCluster));
MetricsUtil.registerSystemResourceMetrics(environment);
}
private void registerExceptionMappers(Environment environment,
@@ -6,8 +6,6 @@
package org.whispersystems.textsecuregcm.auth;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;
import io.netty.resolver.dns.DnsNameResolver;
import jakarta.ws.rs.core.Response;
import java.io.IOException;
@@ -21,12 +19,10 @@ import java.util.List;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.SystemMapper;
@@ -34,9 +30,6 @@ public class CloudflareTurnCredentialsManager {
private static final Logger logger = LoggerFactory.getLogger(CloudflareTurnCredentialsManager.class);
private static final String CREDENTIAL_FETCH_TIMER_NAME = MetricsUtil.name(CloudflareTurnCredentialsManager.class,
"credentialFetchLatency");
private final List<String> cloudflareTurnUrls;
private final List<String> cloudflareTurnUrlsWithIps;
private final String cloudflareTurnHostname;
@@ -66,18 +59,15 @@ public class CloudflareTurnCredentialsManager {
final List<String> cloudflareTurnUrlsWithIps,
final String cloudflareTurnHostname,
final int cloudflareTurnNumHttpClients,
final CircuitBreakerConfiguration circuitBreaker,
@Nullable final String circuitBreakerConfigurationName,
final ExecutorService executor,
final RetryConfiguration retry,
@Nullable final String retryConfigurationName,
final ScheduledExecutorService retryExecutor,
final DnsNameResolver dnsNameResolver) {
this.cloudflareTurnClient = FaultTolerantHttpClient.newBuilder()
.withName("cloudflare-turn")
.withCircuitBreaker(circuitBreaker)
.withExecutor(executor)
.withRetry(retry)
.withRetryExecutor(retryExecutor)
this.cloudflareTurnClient = FaultTolerantHttpClient.newBuilder("cloudflare-turn", executor)
.withCircuitBreaker(circuitBreakerConfigurationName)
.withRetry(retryConfigurationName, retryExecutor)
.withNumClients(cloudflareTurnNumHttpClients)
.build();
this.cloudflareTurnUrls = cloudflareTurnUrls;
@@ -119,20 +109,11 @@ public class CloudflareTurnCredentialsManager {
throw new IOException(e);
}
final Timer.Sample sample = Timer.start();
final HttpResponse<String> response;
try {
response = cloudflareTurnClient.sendAsync(getCredentialsRequest, HttpResponse.BodyHandlers.ofString()).join();
sample.stop(Timer.builder(CREDENTIAL_FETCH_TIMER_NAME)
.publishPercentileHistogram(true)
.tags("outcome", "success")
.register(Metrics.globalRegistry));
} catch (CompletionException e) {
logger.warn("failed to make http request to Cloudflare Turn: {}", e.getMessage());
sample.stop(Timer.builder(CREDENTIAL_FETCH_TIMER_NAME)
.publishPercentileHistogram(true)
.tags("outcome", "failure")
.register(Metrics.globalRegistry));
throw new IOException(ExceptionUtils.unwrap(e));
}
@@ -8,10 +8,12 @@ package org.whispersystems.textsecuregcm.auth;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.InvalidProtocolBufferException;
import io.dropwizard.lifecycle.Managed;
import io.lettuce.core.RedisCommandTimeoutException;
import io.lettuce.core.pubsub.RedisPubSubAdapter;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -21,6 +23,7 @@ import java.util.UUID;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -32,6 +35,7 @@ import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubConnection;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
/**
@@ -45,6 +49,11 @@ public class DisconnectionRequestManager extends RedisPubSubAdapter<byte[], byte
private final FaultTolerantRedisClient pubSubClient;
private final GrpcClientConnectionManager grpcClientConnectionManager;
private final Executor listenerEventExecutor;
private final ScheduledExecutorService retryExecutor;
private static final String RETRY_NAME = ResilienceUtil.name(DisconnectionRequestManager.class);
private static final Duration SUBSCRIBE_RETRY_DELAY = Duration.ofSeconds(5);
private final Map<AccountIdentifierAndDeviceId, List<DisconnectionRequestListener>> listeners =
new ConcurrentHashMap<>();
@@ -66,11 +75,13 @@ public class DisconnectionRequestManager extends RedisPubSubAdapter<byte[], byte
public DisconnectionRequestManager(final FaultTolerantRedisClient pubSubClient,
final GrpcClientConnectionManager grpcClientConnectionManager,
final Executor listenerEventExecutor) {
final Executor listenerEventExecutor,
final ScheduledExecutorService retryExecutor) {
this.pubSubClient = pubSubClient;
this.grpcClientConnectionManager = grpcClientConnectionManager;
this.listenerEventExecutor = listenerEventExecutor;
this.retryExecutor = retryExecutor;
}
@Override
@@ -78,7 +89,25 @@ public class DisconnectionRequestManager extends RedisPubSubAdapter<byte[], byte
this.pubSubConnection = pubSubClient.createBinaryPubSubConnection();
this.pubSubConnection.usePubSubConnection(connection -> {
connection.addListener(this);
connection.sync().subscribe(DISCONNECTION_REQUEST_CHANNEL);
boolean subscribed = false;
// Loop indefinitely until we establish a subscription. We don't want to fail immediately if there's a temporary
// Redis connectivity issue, since that would derail the whole startup process and likely lead to unnecessary pod
// churn, which might make things worse. If we never establish a connection, readiness probes will eventually fail
// and terminate the pods.
do {
try {
connection.sync().subscribe(DISCONNECTION_REQUEST_CHANNEL);
subscribed = true;
} catch (final RedisCommandTimeoutException e) {
try {
Thread.sleep(SUBSCRIBE_RETRY_DELAY);
} catch (final InterruptedException ex) {
throw new RuntimeException(ex);
}
}
} while (!subscribed);
});
}
@@ -159,9 +188,10 @@ public class DisconnectionRequestManager extends RedisPubSubAdapter<byte[], byte
.addAllDeviceIds(deviceIds.stream().mapToInt(Byte::intValue).boxed().toList())
.build();
return pubSubClient.withBinaryConnection(connection ->
connection.async().publish(DISCONNECTION_REQUEST_CHANNEL, disconnectionRequest.toByteArray()))
.toCompletableFuture()
return ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
.executeCompletionStage(retryExecutor, () -> pubSubClient.withBinaryConnection(connection ->
connection.async().publish(DISCONNECTION_REQUEST_CHANNEL, disconnectionRequest.toByteArray()))
.toCompletableFuture())
.thenRun(DISCONNECTION_REQUESTS_SENT_COUNTER::increment);
}
@@ -72,6 +72,11 @@ public class OptionalAccess {
throw new NotAuthorizedException(Response.Status.UNAUTHORIZED);
}
// Unidentified access is only for ACI identities
if (IdentityType.PNI.equals(targetIdentifier.identityType())) {
throw new NotAuthorizedException(Response.Status.UNAUTHORIZED);
}
// Unrestricted unidentified access does what it says on the tin: we don't check if the key the
// caller provided is right or not.
if (targetAccount.get().isUnrestrictedUnidentifiedAccess()) {
@@ -82,11 +87,6 @@ public class OptionalAccess {
throw new IllegalArgumentException("Target account is not identified by the given identifier");
}
// Unidentified access is only for ACI identities
if (IdentityType.PNI.equals(targetIdentifier.identityType())) {
throw new NotAuthorizedException(Response.Status.UNAUTHORIZED);
}
// At this point, any successful authentication requires a real access key on the target account
if (targetAccount.get().getUnidentifiedAccessKey().isEmpty()) {
throw new NotAuthorizedException(Response.Status.UNAUTHORIZED);
@@ -0,0 +1,103 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.auth;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.Iterator;
import java.util.Objects;
import java.util.stream.Stream;
import org.jetbrains.annotations.NotNull;
/// A validated range of days for which a credential may be issued.
public class RedemptionRange implements Iterable<Instant> {
public static final Duration MAX_REDEMPTION_DURATION = Duration.ofDays(7);
/// The first day for which a credential should be issued
private final LocalDate from;
/// The last day for which a credential should be issued
private final LocalDate end;
private RedemptionRange(final LocalDate from, final LocalDate end) {
this.from = from;
this.end = end;
}
/// Construct a {@link RedemptionRange} if the provided day bounds are valid.
///
/// The redemption bounds must satisfy:
/// - `redemptionEnd` >= `redemptionStart`
/// - `redemptionStart` and `redemptionEnd` are day-aligned
/// - `redemptionStart` is yesterday or later
/// - `redemptionEnd` is tomorrow + `MAX_REDEMPTION_DURATION` or earlier
/// - The number of days requested is less than `MAX_REDEMPTION_DURATION`
///
/// @param clock Clock to use to get current day
/// @param redemptionStart The first day included in the range
/// @param redemptionEnd The last day included in the range
/// @return A {@link RedemptionRange} that can be used to iterate each day between `redemptionStart` and
/// `redemptionEnd`
/// @throws IllegalArgumentException if the redemption bounds were not valid
public static RedemptionRange inclusive(Clock clock, Instant redemptionStart, Instant redemptionEnd)
throws IllegalArgumentException {
final Instant today = clock.instant().truncatedTo(ChronoUnit.DAYS);
final Instant yesterday = today.minus(Duration.ofDays(1));
if (redemptionStart.isAfter(redemptionEnd)) {
throw new IllegalArgumentException("end of range must be after start of range");
}
if (!redemptionStart.truncatedTo(ChronoUnit.DAYS).equals(redemptionStart)
|| !redemptionEnd.truncatedTo(ChronoUnit.DAYS).equals(redemptionEnd)) {
throw new IllegalArgumentException("timestamps must be day aligned");
}
if (redemptionStart.isBefore(yesterday)) {
throw new IllegalArgumentException("start of range too far in the past");
}
if (redemptionEnd.isAfter(today.plus(MAX_REDEMPTION_DURATION).plus(Duration.ofDays(1)))) {
throw new IllegalArgumentException("end of range too far in the future");
}
if (redemptionEnd.isAfter(redemptionStart.plus(MAX_REDEMPTION_DURATION))) {
throw new IllegalArgumentException("redemption window too large");
}
return new RedemptionRange(
LocalDate.ofInstant(redemptionStart, ZoneOffset.UTC),
LocalDate.ofInstant(redemptionEnd, ZoneOffset.UTC));
}
@Override
public @NotNull Iterator<Instant> iterator() {
final Instant fromInstant = from.atStartOfDay(ZoneOffset.UTC).toInstant();
final Instant endInstant = end.atStartOfDay(ZoneOffset.UTC).toInstant();
return Stream
.iterate(fromInstant, redemptionTime -> redemptionTime.plus(Duration.ofDays(1)))
.takeWhile(redemptionTime -> !redemptionTime.isAfter(endInstant))
.iterator();
}
@Override
public boolean equals(final Object o) {
if (o == null || getClass() != o.getClass()) {
return false;
}
RedemptionRange that = (RedemptionRange) o;
return Objects.equals(from, that.from) && Objects.equals(end, that.end);
}
@Override
public int hashCode() {
return Objects.hash(from, end);
}
}
@@ -11,11 +11,14 @@ import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import javax.annotation.Nullable;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
import org.signal.libsignal.zkgroup.InvalidInputException;
@@ -29,8 +32,10 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.RedemptionRange;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
@@ -54,7 +59,6 @@ public class BackupAuthManager {
final static Duration MAX_REDEMPTION_DURATION = Duration.ofDays(7);
final static String BACKUP_EXPERIMENT_NAME = "backup";
final static String BACKUP_MEDIA_EXPERIMENT_NAME = "backupMedia";
private final ExperimentEnrollmentManager experimentEnrollmentManager;
@@ -99,9 +103,6 @@ public class BackupAuthManager {
final Device device,
final BackupAuthCredentialRequest messagesBackupCredentialRequest,
final BackupAuthCredentialRequest mediaBackupCredentialRequest) {
if (configuredBackupLevel(account).isEmpty()) {
throw Status.PERMISSION_DENIED.withDescription("Backups not allowed on account").asRuntimeException();
}
if (!device.isPrimary()) {
throw Status.PERMISSION_DENIED.withDescription("Only primary device can set backup-id").asRuntimeException();
}
@@ -138,6 +139,32 @@ public class BackupAuthManager {
.toCompletableFuture();
}
public record BackupIdRotationLimit(boolean hasPermitsRemaining, Duration nextPermitAvailable) {}
public CompletionStage<BackupIdRotationLimit> checkBackupIdRotationLimit(final Account account) {
final RateLimiter messagesLimiter = rateLimiters.forDescriptor(RateLimiters.For.SET_BACKUP_ID);
final RateLimiter mediaLimiter = rateLimiters.forDescriptor(RateLimiters.For.SET_PAID_MEDIA_BACKUP_ID);
final boolean isPaid = hasActiveVoucher(account);
final CompletionStage<Boolean> hasSetMessagesPermits =
messagesLimiter.hasAvailablePermitsAsync(account.getUuid(), 1);
final CompletionStage<Boolean> hasSetMediaPermits = isPaid
? mediaLimiter.hasAvailablePermitsAsync(account.getUuid(), 1)
: CompletableFuture.completedFuture(true);
return hasSetMessagesPermits.thenCombine(hasSetMediaPermits, (hasMessage, hasMedia) -> {
if (hasMedia && hasMessage) {
return new BackupIdRotationLimit(true, Duration.ZERO);
} else {
final Duration timeToNextPermit = Collections.max(Arrays.asList(
messagesLimiter.config().permitRegenerationDuration(),
isPaid ? mediaLimiter.config().permitRegenerationDuration() : Duration.ZERO));
return new BackupIdRotationLimit(false, timeToNextPermit);
}
});
}
public record Credential(BackupAuthCredentialResponse credential, Instant redemptionTime) {}
/**
@@ -152,15 +179,13 @@ public class BackupAuthManager {
*
* @param account The account to create the credentials for
* @param credentialType The type of backup credentials to create
* @param redemptionStart The day (must be truncated to a day boundary) the first credential should be valid
* @param redemptionEnd The day (must be truncated to a day boundary) the last credential should be valid
* @param redemptionRange The time range to return credentials for
* @return Credentials and the day on which they may be redeemed
*/
public CompletableFuture<List<Credential>> getBackupAuthCredentials(
final Account account,
final BackupCredentialType credentialType,
final Instant redemptionStart,
final Instant redemptionEnd) {
final RedemptionRange redemptionRange) {
// If the account has an expired payment, clear it before continuing
if (hasExpiredVoucher(account)) {
@@ -169,21 +194,7 @@ public class BackupAuthManager {
if (hasExpiredVoucher(a)) {
a.setBackupVoucher(null);
}
}).thenCompose(updated -> getBackupAuthCredentials(updated, credentialType, redemptionStart, redemptionEnd));
}
// If this account isn't allowed some level of backup access via configuration, don't continue
final BackupLevel configuredBackupLevel = configuredBackupLevel(account).orElseThrow(() ->
Status.PERMISSION_DENIED.withDescription("Backups not allowed on account").asRuntimeException());
final Instant startOfDay = clock.instant().truncatedTo(ChronoUnit.DAYS);
if (redemptionStart.isAfter(redemptionEnd) ||
redemptionStart.isBefore(startOfDay) ||
redemptionEnd.isAfter(startOfDay.plus(MAX_REDEMPTION_DURATION)) ||
!redemptionStart.equals(redemptionStart.truncatedTo(ChronoUnit.DAYS)) ||
!redemptionEnd.equals(redemptionEnd.truncatedTo(ChronoUnit.DAYS))) {
throw Status.INVALID_ARGUMENT.withDescription("invalid redemption window").asRuntimeException();
}).thenCompose(updated -> getBackupAuthCredentials(updated, credentialType, redemptionRange));
}
// fetch the blinded backup-id the account should have previously committed to
@@ -191,14 +202,15 @@ public class BackupAuthManager {
.orElseThrow(() -> Status.NOT_FOUND.withDescription("No blinded backup-id has been added to the account").asRuntimeException());
try {
final BackupLevel defaultBackupLevel = configuredBackupLevel(account);
// create a credential for every day in the requested period
final BackupAuthCredentialRequest credentialReq = new BackupAuthCredentialRequest(committedBytes);
return CompletableFuture.completedFuture(Stream
.iterate(redemptionStart, redemptionTime -> !redemptionTime.isAfter(redemptionEnd), curr -> curr.plus(Duration.ofDays(1)))
return CompletableFuture.completedFuture(StreamSupport.stream(redemptionRange.spliterator(), false)
.map(redemptionTime -> {
// Check if the account has a voucher that's good for a certain receiptLevel at redemption time, otherwise
// use the default receipt level
final BackupLevel backupLevel = storedBackupLevel(account, redemptionTime).orElse(configuredBackupLevel);
final BackupLevel backupLevel = storedBackupLevel(account, redemptionTime).orElse(defaultBackupLevel);
return new Credential(
credentialReq.issueCredential(redemptionTime, backupLevel, credentialType, serverSecretParams),
redemptionTime);
@@ -328,20 +340,12 @@ public class BackupAuthManager {
* Get the backup receipt level that should be used by default for this account determined via configuration.
*
* @param account the account to check
* @return If present, the default receipt level that should be used for the account if the account does not have a
* BackupVoucher. Empty if the account should never have backup access
* @return The default receipt level that should be used for the account if the account does not have a
* BackupVoucher.
*/
private Optional<BackupLevel> configuredBackupLevel(final Account account) {
if (inExperiment(BACKUP_MEDIA_EXPERIMENT_NAME, account)) {
return Optional.of(BackupLevel.PAID);
}
if (inExperiment(BACKUP_EXPERIMENT_NAME, account)) {
return Optional.of(BackupLevel.FREE);
}
return Optional.empty();
}
private boolean inExperiment(final String experimentName, final Account account) {
return this.experimentEnrollmentManager.isEnrolled(account.getUuid(), experimentName);
private BackupLevel configuredBackupLevel(final Account account) {
return this.experimentEnrollmentManager.isEnrolled(account.getUuid(), BACKUP_MEDIA_EXPERIMENT_NAME)
? BackupLevel.PAID
: BackupLevel.FREE;
}
}
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.backup;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.util.DataSize;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
@@ -19,6 +18,7 @@ import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -38,9 +38,15 @@ import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicBackupConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.util.AsyncTimerUtil;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.Pair;
@@ -54,24 +60,9 @@ import reactor.core.scheduler.Scheduler;
public class BackupManager {
static final String MESSAGE_BACKUP_NAME = "messageBackup";
public static final long MAX_TOTAL_BACKUP_MEDIA_BYTES = DataSize.gibibytes(100).toBytes();
public static final long MAX_MESSAGE_BACKUP_OBJECT_SIZE = DataSize.mebibytes(101).toBytes();
public static final long MAX_MEDIA_OBJECT_SIZE = DataSize.mebibytes(101).toBytes();
// If the last media usage recalculation is over MAX_QUOTA_STALENESS, force a recalculation before quota enforcement.
static final Duration MAX_QUOTA_STALENESS = Duration.ofDays(1);
// How many cdn object deletion requests can be outstanding at a time per backup deletion operation
private static final int DELETION_CONCURRENCY = 10;
// How many cdn object copy requests can be outstanding at a time per batch copy-to-backup operation
private static final int COPY_CONCURRENCY = 10;
// How often we should persist the current usage
@VisibleForTesting
static int USAGE_CHECKPOINT_COUNT = 10;
private static final String ZK_AUTHN_COUNTER_NAME = MetricsUtil.name(BackupManager.class, "authentication");
private static final String ZK_AUTHZ_FAILURE_COUNTER_NAME = MetricsUtil.name(BackupManager.class,
"authorizationFailure");
@@ -82,6 +73,9 @@ public class BackupManager {
private static final Timer SYNCHRONOUS_DELETE_TIMER =
Metrics.timer(MetricsUtil.name(BackupManager.class, "synchronousDelete"));
private static final String NUM_OBJECTS_SUMMARY_NAME = MetricsUtil.name(BackupsDb.class, "numObjects");
private static final String BYTES_USED_SUMMARY_NAME = MetricsUtil.name(BackupsDb.class, "bytesUsed");
private static final String SUCCESS_TAG_NAME = "success";
private static final String FAILURE_REASON_TAG_NAME = "reason";
@@ -94,8 +88,10 @@ public class BackupManager {
private final Cdn3BackupCredentialGenerator cdn3BackupCredentialGenerator;
private final RemoteStorageManager remoteStorageManager;
private final SecureRandom secureRandom = new SecureRandom();
private final ExternalServiceCredentialsGenerator secureValueRecoveryBCredentialsGenerator;
private final SecureValueRecoveryClient secureValueRecoveryBClient;
private final Clock clock;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
public BackupManager(
final BackupsDb backupsDb,
@@ -104,14 +100,20 @@ public class BackupManager {
final TusAttachmentGenerator tusAttachmentGenerator,
final Cdn3BackupCredentialGenerator cdn3BackupCredentialGenerator,
final RemoteStorageManager remoteStorageManager,
final Clock clock) {
final ExternalServiceCredentialsGenerator secureValueRecoveryBCredentialsGenerator,
final SecureValueRecoveryClient secureValueRecoveryBClient,
final Clock clock,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
this.backupsDb = backupsDb;
this.serverSecretParams = serverSecretParams;
this.rateLimiters = rateLimiters;
this.tusAttachmentGenerator = tusAttachmentGenerator;
this.cdn3BackupCredentialGenerator = cdn3BackupCredentialGenerator;
this.remoteStorageManager = remoteStorageManager;
this.secureValueRecoveryBClient = secureValueRecoveryBClient;
this.clock = clock;
this.secureValueRecoveryBCredentialsGenerator = secureValueRecoveryBCredentialsGenerator;
this.dynamicConfigurationManager = dynamicConfigurationManager;
}
@@ -148,7 +150,6 @@ public class BackupManager {
}));
}
/**
* Create a form that may be used to upload a backup file for the backupId encoded in the presentation.
* <p>
@@ -165,7 +166,8 @@ public class BackupManager {
// this could race with concurrent updates, but the only effect would be last-writer-wins on the timestamp
return backupsDb
.addMessageBackup(backupUser)
.thenApply(result -> cdn3BackupCredentialGenerator.generateUpload(cdnMessageBackupName(backupUser)));
.thenApply(_ ->
cdn3BackupCredentialGenerator.generateUpload(cdnMessageBackupName(backupUser)));
}
public CompletableFuture<BackupUploadDescriptor> createTemporaryAttachmentUploadDescriptor(
@@ -191,7 +193,33 @@ public class BackupManager {
public CompletableFuture<Void> ttlRefresh(final AuthenticatedBackupUser backupUser) {
checkBackupLevel(backupUser, BackupLevel.FREE);
// update message backup TTL
return backupsDb.ttlRefresh(backupUser);
return backupsDb.ttlRefresh(backupUser).thenAccept(storedBackupAttributes -> {
if (backupUser.credentialType() == BackupCredentialType.MEDIA) {
final long maxTotalMediaSize =
dynamicConfigurationManager.getConfiguration().getBackupConfiguration().maxTotalMediaSize();
// Report that the backup is out of quota if it cannot store a max size media object
final boolean quotaExhausted = storedBackupAttributes.bytesUsed() >=
(maxTotalMediaSize - BackupManager.MAX_MEDIA_OBJECT_SIZE);
final Tags tags = Tags.of(
UserAgentTagUtil.getPlatformTag(backupUser.userAgent()),
Tag.of("type", backupUser.credentialType().name()),
Tag.of("tier", backupUser.backupLevel().name()),
Tag.of("quotaExhausted", String.valueOf(quotaExhausted)));
DistributionSummary.builder(NUM_OBJECTS_SUMMARY_NAME)
.tags(tags)
.publishPercentileHistogram()
.register(Metrics.globalRegistry)
.record(storedBackupAttributes.numObjects());
DistributionSummary.builder(BYTES_USED_SUMMARY_NAME)
.tags(tags)
.publishPercentileHistogram()
.register(Metrics.globalRegistry)
.record(storedBackupAttributes.bytesUsed());
}
});
}
public record BackupInfo(int cdn, String backupSubdir, String mediaSubdir, String messageBackupKey,
@@ -230,6 +258,9 @@ public class BackupManager {
checkBackupLevel(backupUser, BackupLevel.PAID);
checkBackupCredentialType(backupUser, BackupCredentialType.MEDIA);
final DynamicBackupConfiguration backupConfiguration =
dynamicConfigurationManager.getConfiguration().getBackupConfiguration();
return Mono.fromFuture(() -> allowedCopies(backupUser, toCopy))
.flatMapMany(quotaResult -> Flux.concat(
@@ -239,7 +270,7 @@ public class BackupManager {
Flux.fromIterable(quotaResult.requestsToCopy())
// Update the usage in reasonable chunk sizes to bound how out of sync our claimed and actual usage gets
.buffer(USAGE_CHECKPOINT_COUNT)
.buffer(backupConfiguration.usageCheckpointCount())
.concatMap(copyParameters -> {
final long quotaToConsume = copyParameters.stream()
.mapToLong(CopyParameters::destinationObjectSize)
@@ -257,7 +288,7 @@ public class BackupManager {
.fromFuture(this.backupsDb.trackMedia(backupUser, -1, -copyParams.destinationObjectSize()))
.thenReturn(copyResult);
}),
COPY_CONCURRENCY, 1),
backupConfiguration.copyConcurrency(), 1),
// There wasn't enough quota remaining to perform these copies
Flux.fromIterable(quotaResult.requestsToReject())
@@ -309,11 +340,16 @@ public class BackupManager {
})
.sum();
final DynamicBackupConfiguration backupConfiguration =
dynamicConfigurationManager.getConfiguration().getBackupConfiguration();
final Duration maxQuotaStaleness = backupConfiguration.maxQuotaStaleness();
final long maxTotalMediaSize = backupConfiguration.maxTotalMediaSize();
return backupsDb.getMediaUsage(backupUser)
.thenComposeAsync(info -> {
long remainingQuota = MAX_TOTAL_BACKUP_MEDIA_BYTES - info.usageInfo().bytesUsed();
long remainingQuota = maxTotalMediaSize - info.usageInfo().bytesUsed();
final boolean canStore = remainingQuota >= totalBytesAdded;
if (canStore || info.lastRecalculationTime().isAfter(clock.instant().minus(MAX_QUOTA_STALENESS))) {
if (canStore || info.lastRecalculationTime().isAfter(clock.instant().minus(maxQuotaStaleness))) {
return CompletableFuture.completedFuture(remainingQuota);
}
@@ -330,7 +366,7 @@ public class BackupManager {
Tag.of("usageChanged", String.valueOf(usageChanged))))
.increment();
})
.thenApply(newUsage -> MAX_TOTAL_BACKUP_MEDIA_BYTES - newUsage.bytesUsed());
.thenApply(newUsage -> maxTotalMediaSize - newUsage.bytesUsed());
})
.thenApply(remainingQuota -> {
// Figure out how many of the requested objects fit in the remaining quota
@@ -387,6 +423,26 @@ public class BackupManager {
return cdn3BackupCredentialGenerator.readHeaders(backupUser.backupDir());
}
/**
* Generate credentials that can be used with SVRB
*
* @param backupUser an already ZK authenticated backup user
* @return the credential that may be used with SVRB
*/
public ExternalServiceCredentials generateSvrbAuth(final AuthenticatedBackupUser backupUser) {
checkBackupLevel(backupUser, BackupLevel.FREE);
// Clients may only use SVRB with their messages backup-id
checkBackupCredentialType(backupUser, BackupCredentialType.MESSAGES);
return secureValueRecoveryBCredentialsGenerator.generateFor(svrbIdentifier(backupUser));
}
private static String svrbIdentifier(final AuthenticatedBackupUser backupUser) {
return svrbIdentifier(BackupsDb.hashedBackupId(backupUser.backupId()));
}
private static String svrbIdentifier(final byte[] hashedBackupId) {
return HexFormat.of().formatHex(hashedBackupId);
}
/**
* List of media stored for a particular backup id
@@ -427,13 +483,22 @@ public class BackupManager {
public CompletableFuture<Void> deleteEntireBackup(final AuthenticatedBackupUser backupUser) {
checkBackupLevel(backupUser, BackupLevel.FREE);
return backupsDb
final int deletionConcurrency =
dynamicConfigurationManager.getConfiguration().getBackupConfiguration().deletionConcurrency();
// Clients only include SVRB data with their messages backup-id
final CompletableFuture<Void> svrbRemoval = switch(backupUser.credentialType()) {
case BackupCredentialType.MESSAGES -> secureValueRecoveryBClient.removeData(svrbIdentifier(backupUser));
case BackupCredentialType.MEDIA -> CompletableFuture.completedFuture(null);
};
return svrbRemoval.thenCompose(_ -> backupsDb
// Try to swap out the backupDir for the user
.scheduleBackupDeletion(backupUser)
// If there was already a pending swap, try to delete the cdn objects directly
.exceptionallyCompose(ExceptionUtils.exceptionallyHandler(BackupsDb.PendingDeletionException.class, e ->
AsyncTimerUtil.record(SYNCHRONOUS_DELETE_TIMER, () ->
deletePrefix(backupUser.backupDir(), DELETION_CONCURRENCY))));
deletePrefix(backupUser.backupDir(), deletionConcurrency)))));
}
@@ -448,11 +513,13 @@ public class BackupManager {
.withDescription("unsupported media cdn provided")
.asRuntimeException();
}
final DynamicBackupConfiguration backupConfiguration =
dynamicConfigurationManager.getConfiguration().getBackupConfiguration();
return Flux.usingWhen(
// Gather usage updates into the UsageBatcher so we don't have to update our backup record on every delete
Mono.just(new UsageBatcher()),
Mono.just(new UsageBatcher(backupConfiguration.usageCheckpointCount())),
// Deletes the objects, returning their former location. Tracks bytes removed so the quota can be updated on
// completion
@@ -461,7 +528,7 @@ public class BackupManager {
// Delete the objects, allowing DELETION_CONCURRENCY operations out at a time
.flatMapSequential(
sd -> Mono.fromCompletionStage(remoteStorageManager.delete(cdnMediaPath(backupUser, sd.key()))),
DELETION_CONCURRENCY)
backupConfiguration.deletionConcurrency())
.zipWithIterable(storageDescriptors)
// Track how much the remote storage manager indicated was deleted as part of the operation
@@ -497,9 +564,14 @@ public class BackupManager {
*/
private static class UsageBatcher {
private final int usageCheckpointCount;
private long runningCountDelta = 0;
private long runningBytesDelta = 0;
UsageBatcher(int usageCheckpointCount) {
this.usageCheckpointCount = usageCheckpointCount;
}
record UsageUpdate(long countDelta, long bytesDelta) {}
/**
@@ -512,7 +584,7 @@ public class BackupManager {
boolean update(long bytesDelta) {
this.runningCountDelta += Long.signum(bytesDelta);
this.runningBytesDelta += bytesDelta;
return Math.abs(runningCountDelta) >= USAGE_CHECKPOINT_COUNT;
return Math.abs(runningCountDelta) >= usageCheckpointCount;
}
/**
@@ -588,11 +660,10 @@ public class BackupManager {
* List all backups stored in the backups table
*
* @param segments Number of segments to read in parallel from the underlying backup database
* @param scheduler Scheduler for running downstream operations
* @return Flux of {@link StoredBackupAttributes} for each backup record in the backups table
*/
public Flux<StoredBackupAttributes> listBackupAttributes(final int segments, final Scheduler scheduler) {
return this.backupsDb.listBackupAttributes(segments, scheduler);
public Flux<StoredBackupAttributes> listBackupAttributes(final int segments) {
return this.backupsDb.listBackupAttributes(segments);
}
/**
@@ -617,12 +688,17 @@ public class BackupManager {
* @return A stage that completes when the deletion operation is finished
*/
public CompletableFuture<Void> expireBackup(final ExpiredBackup expiredBackup) {
return backupsDb.startExpiration(expiredBackup)
// Clients only include SVRB data with their messages backup-id
final CompletableFuture<Void> svrbRemoval = switch(expiredBackup.expirationType()) {
case ALL -> secureValueRecoveryBClient.removeData(svrbIdentifier(expiredBackup.hashedBackupId()));
case MEDIA, GARBAGE_COLLECTION -> CompletableFuture.completedFuture(null);
};
return svrbRemoval.thenCompose(_ -> backupsDb.startExpiration(expiredBackup)
// the deletion operation is effectively single threaded -- it's expected that the caller can increase
// concurrency by deleting more backups at once, rather than increasing concurrency deleting an individual
// backup
.thenCompose(ignored -> deletePrefix(expiredBackup.prefixToDelete(), 1))
.thenCompose(ignored -> backupsDb.finishExpiration(expiredBackup));
.thenCompose(ignored -> backupsDb.finishExpiration(expiredBackup)));
}
/**
@@ -87,10 +87,6 @@ public class BackupsDb {
private final SecureRandom secureRandom;
private static final String NUM_OBJECTS_SUMMARY_NAME = MetricsUtil.name(BackupsDb.class, "numObjects");
private static final String BYTES_USED_SUMMARY_NAME = MetricsUtil.name(BackupsDb.class, "bytesUsed");
private static final String BACKUPS_COUNTER_NAME = MetricsUtil.name(BackupsDb.class, "backups");
// The backups table
// B: 16 bytes that identifies the backup
@@ -246,7 +242,7 @@ public class BackupsDb {
*
* @param backupUser an already authorized backup user
*/
CompletableFuture<Void> ttlRefresh(final AuthenticatedBackupUser backupUser) {
CompletableFuture<StoredBackupAttributes> ttlRefresh(final AuthenticatedBackupUser backupUser) {
final Instant today = clock.instant().truncatedTo(ChronoUnit.DAYS);
// update message backup TTL
return dynamoClient.updateItem(UpdateBuilder.forUser(backupTableName, backupUser)
@@ -254,16 +250,17 @@ public class BackupsDb {
.updateItemBuilder()
.returnValues(ReturnValue.ALL_OLD)
.build())
.thenAccept(updateItemResponse ->
updateMetricsAfterRefresh(backupUser, today, updateItemResponse.attributes()));
.thenApply(updateItemResponse -> fromItem(updateItemResponse.attributes()));
}
/**
* Track that a backup will be stored for the user
*
* @param backupUser an already authorized backup user
* @return A future that completes with the attributes of the backup before the update
*/
CompletableFuture<Void> addMessageBackup(final AuthenticatedBackupUser backupUser) {
CompletableFuture<StoredBackupAttributes> addMessageBackup(final AuthenticatedBackupUser backupUser) {
final Instant today = clock.instant().truncatedTo(ChronoUnit.DAYS);
// this could race with concurrent updates, but the only effect would be last-writer-wins on the timestamp
return dynamoClient.updateItem(
@@ -273,40 +270,7 @@ public class BackupsDb {
.updateItemBuilder()
.returnValues(ReturnValue.ALL_OLD)
.build())
.thenAccept(updateItemResponse ->
updateMetricsAfterRefresh(backupUser, today, updateItemResponse.attributes()));
}
private void updateMetricsAfterRefresh(final AuthenticatedBackupUser backupUser, final Instant today, final Map<String, AttributeValue> item) {
final Instant previousRefreshTime = Instant.ofEpochSecond(
AttributeValues.getLong(item, ATTR_LAST_REFRESH, 0L));
// Only publish a metric update once per day
if (previousRefreshTime.isBefore(today)) {
final long mediaCount = AttributeValues.getLong(item, ATTR_MEDIA_COUNT, 0L);
final long bytesUsed = AttributeValues.getLong(item, ATTR_MEDIA_BYTES_USED, 0L);
final Tags tags = Tags.of(
UserAgentTagUtil.getPlatformTag(backupUser.userAgent()),
Tag.of("tier", backupUser.backupLevel().name()));
DistributionSummary.builder(NUM_OBJECTS_SUMMARY_NAME)
.tags(tags)
.publishPercentileHistogram()
.register(Metrics.globalRegistry)
.record(mediaCount);
DistributionSummary.builder(BYTES_USED_SUMMARY_NAME)
.tags(tags)
.publishPercentileHistogram()
.register(Metrics.globalRegistry)
.record(bytesUsed);
// Report that the backup is out of quota if it cannot store a max size media object
final boolean quotaExhausted = bytesUsed >=
(BackupManager.MAX_TOTAL_BACKUP_MEDIA_BYTES - BackupManager.MAX_MEDIA_OBJECT_SIZE);
Metrics.counter(BACKUPS_COUNTER_NAME,
tags.and("quotaExhausted", String.valueOf(quotaExhausted)))
.increment();
}
.thenApply(updateItemResponse -> fromItem(updateItemResponse.attributes()));
}
/**
@@ -497,14 +461,12 @@ public class BackupsDb {
}
}
Flux<StoredBackupAttributes> listBackupAttributes(final int segments, final Scheduler scheduler) {
Flux<StoredBackupAttributes> listBackupAttributes(final int segments) {
if (segments < 1) {
throw new IllegalArgumentException("Total number of segments must be positive");
}
return Flux.range(0, segments)
.parallel()
.runOn(scheduler)
.flatMap(segment -> dynamoClient.scanPaginator(ScanRequest.builder()
.tableName(backupTableName)
.consistentRead(true)
@@ -519,18 +481,22 @@ public class BackupsDb {
"#backupDir", ATTR_BACKUP_DIR,
"#mediaDir", ATTR_MEDIA_DIR))
.projectionExpression("#backupIdHash, #refresh, #mediaRefresh, #bytesUsed, #numObjects, #backupDir, #mediaDir")
.build())
.items())
.sequential()
.build()))
// Don't use the SDK's item publisher, works around https://github.com/aws/aws-sdk-java-v2/issues/6411
.concatMap(page -> Flux.fromIterable(page.items()))
.filter(item -> item.containsKey(KEY_BACKUP_ID_HASH))
.map(item -> new StoredBackupAttributes(
AttributeValues.getByteArray(item, KEY_BACKUP_ID_HASH, null),
AttributeValues.getString(item, ATTR_BACKUP_DIR, null),
AttributeValues.getString(item, ATTR_MEDIA_DIR, null),
Instant.ofEpochSecond(AttributeValues.getLong(item, ATTR_LAST_REFRESH, 0L)),
Instant.ofEpochSecond(AttributeValues.getLong(item, ATTR_LAST_MEDIA_REFRESH, 0L)),
AttributeValues.getLong(item, ATTR_MEDIA_BYTES_USED, 0L),
AttributeValues.getLong(item, ATTR_MEDIA_COUNT, 0L)));
.map(BackupsDb::fromItem);
}
private static StoredBackupAttributes fromItem(Map<String, AttributeValue> item) {
return new StoredBackupAttributes(
AttributeValues.getByteArray(item, KEY_BACKUP_ID_HASH, null),
AttributeValues.getString(item, ATTR_BACKUP_DIR, null),
AttributeValues.getString(item, ATTR_MEDIA_DIR, null),
Instant.ofEpochSecond(AttributeValues.getLong(item, ATTR_LAST_REFRESH, 0L)),
Instant.ofEpochSecond(AttributeValues.getLong(item, ATTR_LAST_MEDIA_REFRESH, 0L)),
AttributeValues.getLong(item, ATTR_MEDIA_BYTES_USED, 0L),
AttributeValues.getLong(item, ATTR_MEDIA_COUNT, 0L));
}
Flux<ExpiredBackup> getExpiredBackups(final int segments, final Scheduler scheduler, final Instant purgeTime) {
@@ -67,12 +67,9 @@ public class Cdn3RemoteStorageManager implements RemoteStorageManager {
this.clientSecret = configuration.clientSecret().value();
// Client used for calls to storage-manager
this.storageManagerHttpClient = FaultTolerantHttpClient.newBuilder()
.withName("cdn3-storage-manager")
.withCircuitBreaker(configuration.circuitBreaker())
.withExecutor(httpExecutor)
.withRetryExecutor(retryExecutor)
.withRetry(configuration.retry())
this.storageManagerHttpClient = FaultTolerantHttpClient.newBuilder("cdn3-storage-manager", httpExecutor)
.withCircuitBreaker(configuration.circuitBreakerConfigurationName())
.withRetry(configuration.retryConfigurationName(), retryExecutor)
.withConnectTimeout(Duration.ofSeconds(10))
.withVersion(HttpClient.Version.HTTP_2)
.withNumClients(configuration.numHttpClients())
@@ -0,0 +1,33 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.backup;
import com.google.common.annotations.VisibleForTesting;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
import org.whispersystems.textsecuregcm.configuration.SecureValueRecoveryConfiguration;
import java.time.Clock;
public class SecureValueRecoveryBCredentialsGeneratorFactory {
private SecureValueRecoveryBCredentialsGeneratorFactory() {}
@VisibleForTesting
static ExternalServiceCredentialsGenerator svrbCredentialsGenerator(
final SecureValueRecoveryConfiguration cfg,
final Clock clock) {
return ExternalServiceCredentialsGenerator
.builder(cfg.userAuthenticationTokenSharedSecret())
.withUserDerivationKey(cfg.userIdTokenSharedSecret().value())
.prependUsername(false)
.withDerivedUsernameTruncateLength(16)
.withClock(clock)
.build();
}
public static ExternalServiceCredentialsGenerator svrbCredentialsGenerator(final SecureValueRecoveryConfiguration cfg) {
return svrbCredentialsGenerator(cfg, Clock.systemUTC());
}
}
@@ -12,6 +12,7 @@ import jakarta.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
import javax.annotation.Nullable;
/**
* @param env The ios environment to use, typically SANDBOX or PRODUCTION
@@ -26,6 +27,8 @@ import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
* subscription levels
* @param appleRootCerts Apple root certificates to verify signed API responses, encoded as base64 strings:
* https://www.apple.com/certificateauthority/
* @param retryConfigurationName The name of the retry configuration to use in the App Store client; if `null`, uses the
* global default configuration.
*/
public record AppleAppStoreConfiguration(
@NotNull Environment env,
@@ -37,11 +40,5 @@ public record AppleAppStoreConfiguration(
@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();
}
}
@Nullable String retryConfigurationName) {
}
@@ -11,6 +11,7 @@ import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
@@ -22,24 +23,16 @@ import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
* @param supportedCurrenciesByPaymentMethod the set of supported currencies
* @param graphqlUrl the Braintree GraphQL URl to use (this must match the environment)
* @param merchantAccounts merchant account within the merchant for processing individual currencies
* @param circuitBreaker configuration for the circuit breaker used by the GraphQL HTTP client
* @param circuitBreakerConfigurationName the name of the circuit breaker configuration for the breaker used by the
* GraphQL HTTP client; if `null`, uses the global default configuration
*/
public record BraintreeConfiguration(@NotBlank String merchantId,
@NotBlank String publicKey,
@NotNull SecretString publicKey,
@NotNull SecretString privateKey,
@NotBlank String environment,
@Valid @NotEmpty Map<PaymentMethod, Set<@NotBlank String>> supportedCurrenciesByPaymentMethod,
@NotBlank String graphqlUrl,
@NotEmpty Map<String, String> merchantAccounts,
@NotNull @Valid CircuitBreakerConfiguration circuitBreaker,
@Nullable String circuitBreakerConfigurationName,
@Valid @NotNull PubSubPublisherFactory pubSubPublisher) {
public BraintreeConfiguration {
if (circuitBreaker == null) {
// It’s a little counter-intuitive, but this compact constructor allows a default value
// to be used when one isn’t specified (e.g. in YAML), allowing the field to still be
// validated as @NotNull
circuitBreaker = new CircuitBreakerConfiguration();
}
}
}
@@ -5,6 +5,7 @@ import jakarta.validation.constraints.NotNull;
import java.util.Collections;
import java.util.Map;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
import javax.annotation.Nullable;
/**
* Configuration for the cdn3 storage manager
@@ -16,8 +17,10 @@ import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
* storage-manager when copying to determine how to read a source object. Current schemes are
* 'gcs' and 'r2'
* @param numHttpClients The number http clients to use with the storage-manager to support request striping
* @param circuitBreaker A circuit breaker configuration for the storage-manager http client
* @param retry A retry configuration for the storage-manager http client
* @param circuitBreakerConfigurationName The name of a circuit breaker configuration for the storage-manager http
* client; if `null`, uses the global default configuration
* @param retryConfigurationName The name of a retry configuration for the storage-manager http client; if
* `null`, uses the global default configuration
*/
public record Cdn3StorageManagerConfiguration(
@NotNull String baseUri,
@@ -25,8 +28,8 @@ public record Cdn3StorageManagerConfiguration(
@NotNull SecretString clientSecret,
@NotNull Map<Integer, String> sourceSchemes,
@NotNull Integer numHttpClients,
@NotNull @Valid CircuitBreakerConfiguration circuitBreaker,
@NotNull @Valid RetryConfiguration retry) {
@Nullable String circuitBreakerConfigurationName,
@Nullable String retryConfigurationName) {
public Cdn3StorageManagerConfiguration {
if (numHttpClients == null) {
@@ -35,11 +38,5 @@ public record Cdn3StorageManagerConfiguration(
if (sourceSchemes == null) {
sourceSchemes = Collections.emptyMap();
}
if (circuitBreaker == null) {
circuitBreaker = new CircuitBreakerConfiguration();
}
if (retry == null) {
retry = new RetryConfiguration();
}
}
}
@@ -8,8 +8,11 @@ package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import javax.annotation.Nullable;
import java.net.URI;
public record CdnConfiguration(@NotNull @Valid StaticAwsCredentialsFactory credentials,
@NotBlank String bucket,
@NotBlank String region) {
@NotBlank String region,
@Nullable URI endpointOverride) {
}
@@ -1,29 +0,0 @@
package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
/**
* Configuration used to interact with a cdn via HTTP
*/
public class ClientCdnConfiguration {
@JsonProperty
@NotNull
@Valid
CircuitBreakerConfiguration circuitBreaker = new CircuitBreakerConfiguration();
@JsonProperty
@NotNull
@Valid
RetryConfiguration retry = new RetryConfiguration();
public CircuitBreakerConfiguration getCircuitBreaker() {
return circuitBreaker;
}
public RetryConfiguration getRetry() {
return retry;
}
}
@@ -15,6 +15,7 @@ import java.time.Duration;
import java.util.List;
import jakarta.validation.constraints.Positive;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
import javax.annotation.Nullable;
/**
* Configuration properties for Cloudflare TURN integration.
@@ -27,8 +28,10 @@ import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
* @param urlsWithIps a collection of {@link String#format(String, Object...)} patterns to be populated with resolved IP
* addresses for {@link #hostname} in responses to clients; each pattern must include a single
* {@code %s} placeholder for the IP address
* @param circuitBreaker a circuit breaker for requests to Cloudflare
* @param retry a retry policy for requests to Cloudflare
* @param circuitBreakerConfigurationName the name of a circuit breaker configuration for requests to Cloudflare; if
* `null`, uses the global default configuration
* @param retryConfigurationName the name of a retry policy for requests to Cloudflare; if `null`, uses the global
* default configuration
* @param hostname the hostname to resolve to IP addresses for use with {@link #urlsWithIps}; also transmitted to
* clients for use as an SNI when connecting to pre-resolved hosts
* @param numHttpClients the number of parallel HTTP clients to use to communicate with Cloudflare
@@ -39,24 +42,11 @@ public record CloudflareTurnConfiguration(@NotNull SecretString apiToken,
@NotNull Duration clientCredentialTtl,
@NotNull @NotEmpty @Valid List<@NotBlank String> urls,
@NotNull @NotEmpty @Valid List<@NotBlank String> urlsWithIps,
@NotNull @Valid CircuitBreakerConfiguration circuitBreaker,
@NotNull @Valid RetryConfiguration retry,
@Nullable String circuitBreakerConfigurationName,
@Nullable String retryConfigurationName,
@NotBlank String hostname,
@Positive int numHttpClients) {
public CloudflareTurnConfiguration {
if (circuitBreaker == null) {
// It’s a little counter-intuitive, but this compact constructor allows a default value
// to be used when one isn’t specified (e.g. in YAML), allowing the field to still be
// validated as @NotNull
circuitBreaker = new CircuitBreakerConfiguration();
}
if (retry == null) {
retry = new RetryConfiguration();
}
}
@AssertTrue
@Schema(hidden = true)
public boolean isClientTtlShorterThanRequestedTtl() {
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.micrometer.registry.otlp.HistogramFlavor;
import io.micrometer.registry.otlp.OtlpConfig;
import java.time.Duration;
import java.util.Map;
@@ -15,6 +16,8 @@ import java.util.Map;
public record OpenTelemetryConfiguration(
@JsonProperty boolean enabled,
@JsonProperty Duration shutdownWaitDuration,
@JsonProperty int maxBucketCount,
@JsonProperty Map<String, Integer> maxBucketsPerMeter,
@JsonAnyGetter @JsonAnySetter Map<String, String> otlpConfig
) implements OtlpConfig {
@@ -23,6 +26,19 @@ public record OpenTelemetryConfiguration(
return otlpConfig.get(key.split("\\.", 2)[1]);
}
@Override
public Map<String, Integer> maxBucketsPerMeter() {
if (maxBucketsPerMeter == null) {
return Map.of();
}
return maxBucketsPerMeter;
}
@Override
public HistogramFlavor histogramFlavor() {
return HistogramFlavor.BASE2_EXPONENTIAL_BUCKET_HISTOGRAM;
}
public Duration shutdownWaitDuration() {
if (shutdownWaitDuration == null) {
return step().plus(step().dividedBy(2));
@@ -5,11 +5,12 @@
package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import javax.annotation.Nullable;
import java.net.URI;
public record PagedSingleUseKEMPreKeyStoreConfiguration(
@NotBlank String bucket,
@NotBlank String region) {
@NotBlank String region,
@Nullable URI endpointOverride) {
}
@@ -9,10 +9,10 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.google.common.annotations.VisibleForTesting;
import io.lettuce.core.resource.ClientResources;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import java.time.Duration;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
@JsonTypeName("default")
@@ -27,14 +27,8 @@ public class RedisClusterConfiguration implements FaultTolerantRedisClusterFacto
private Duration timeout = Duration.ofSeconds(1);
@JsonProperty
@NotNull
@Valid
private CircuitBreakerConfiguration circuitBreaker = new CircuitBreakerConfiguration();
@JsonProperty
@NotNull
@Valid
private RetryConfiguration retry = new RetryConfiguration();
@Nullable
private String circuitBreakerConfigurationName;
@VisibleForTesting
void setConfigurationUri(final String configurationUri) {
@@ -49,12 +43,8 @@ public class RedisClusterConfiguration implements FaultTolerantRedisClusterFacto
return timeout;
}
public CircuitBreakerConfiguration getCircuitBreakerConfiguration() {
return circuitBreaker;
}
public RetryConfiguration getRetryConfiguration() {
return retry;
@Nullable public String getCircuitBreakerConfigurationName() {
return circuitBreakerConfigurationName;
}
@Override
@@ -9,10 +9,10 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.google.common.annotations.VisibleForTesting;
import io.lettuce.core.resource.ClientResources;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import java.time.Duration;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
@JsonTypeName("default")
@@ -27,14 +27,8 @@ public class RedisConfiguration implements FaultTolerantRedisClientFactory {
private Duration timeout = Duration.ofSeconds(1);
@JsonProperty
@NotNull
@Valid
private CircuitBreakerConfiguration circuitBreaker = new CircuitBreakerConfiguration();
@JsonProperty
@NotNull
@Valid
private RetryConfiguration retry = new RetryConfiguration();
@Nullable
private String circuitBreakerConfigurationName;
public String getUri() {
return uri;
@@ -49,12 +43,8 @@ public class RedisConfiguration implements FaultTolerantRedisClientFactory {
return timeout;
}
public @NotNull @Valid CircuitBreakerConfiguration getCircuitBreakerConfiguration() {
return circuitBreaker;
}
public @NotNull @Valid RetryConfiguration getRetryConfiguration() {
return retry;
@Nullable public String getCircuitBreakerConfigurationName() {
return circuitBreakerConfigurationName;
}
@Override
@@ -36,13 +36,9 @@ public class RetryConfiguration {
this.waitDuration = waitDuration;
}
public RetryConfig toRetryConfig() {
return toRetryConfigBuilder().build();
}
public <T> RetryConfig.Builder<T> toRetryConfigBuilder() {
return RetryConfig.<T>custom()
.maxAttempts(getMaxAttempts())
.waitDuration(Duration.ofMillis(getWaitDuration()));
.maxAttempts(getMaxAttempts())
.waitDuration(Duration.ofMillis(getWaitDuration()));
}
}
@@ -5,24 +5,16 @@
package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import java.util.List;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
public record SecureStorageServiceConfiguration(@NotNull SecretBytes userAuthenticationTokenSharedSecret,
@NotBlank String uri,
@NotEmpty List<@NotBlank String> storageCaCertificates,
@Valid CircuitBreakerConfiguration circuitBreaker,
@Valid RetryConfiguration retry) {
public SecureStorageServiceConfiguration {
if (circuitBreaker == null) {
circuitBreaker = new CircuitBreakerConfiguration();
}
if (retry == null) {
retry = new RetryConfiguration();
}
}
@Nullable String circuitBreakerConfigurationName,
@Nullable String retryConfigurationName) {
}
@@ -11,22 +11,13 @@ import jakarta.validation.constraints.NotNull;
import java.util.List;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
import org.whispersystems.textsecuregcm.util.ExactlySize;
import javax.annotation.Nullable;
public record SecureValueRecoveryConfiguration(
@NotBlank String uri,
@ExactlySize(32) SecretBytes userAuthenticationTokenSharedSecret,
@ExactlySize(32) SecretBytes userIdTokenSharedSecret,
@NotEmpty List<@NotBlank String> svrCaCertificates,
@NotNull @Valid CircuitBreakerConfiguration circuitBreaker,
@NotNull @Valid RetryConfiguration retry) {
public SecureValueRecoveryConfiguration {
if (circuitBreaker == null) {
circuitBreaker = new CircuitBreakerConfiguration();
}
if (retry == null) {
retry = new RetryConfiguration();
}
}
@Nullable String circuitBreakerConfigurationName,
@Nullable String retryConfigurationName) {
}
@@ -6,4 +6,20 @@ package org.whispersystems.textsecuregcm.configuration;
import java.time.Duration;
public record VirtualThreadConfiguration(Duration pinEventThreshold) {}
public record VirtualThreadConfiguration(
Duration pinEventThreshold,
Integer maxConcurrentThreadsPerExecutor) {
public VirtualThreadConfiguration() {
this(null, null);
}
public VirtualThreadConfiguration {
if (maxConcurrentThreadsPerExecutor == null) {
maxConcurrentThreadsPerExecutor = 1_000_000;
}
if (pinEventThreshold == null) {
pinEventThreshold = Duration.ofMillis(1);
}
}
}
@@ -0,0 +1,48 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration.dynamic;
import io.dropwizard.util.DataSize;
import jakarta.validation.constraints.NotNull;
import java.time.Duration;
/**
*
* @param deletionConcurrency How many cdn object deletion requests can be outstanding at a time per backup deletion operation
* @param copyConcurrency How many cdn object copy requests can be outstanding at a time per batch copy-to-backup operation
* @param usageCheckpointCount When doing batch operations, how often persist usage deltas
* @param maxQuotaStaleness The maximum age of a quota estimate that can be used to enforce a quota limit
* @param maxTotalMediaSize The number of media bytes a paid-tier user may store
*/
public record DynamicBackupConfiguration(
@NotNull Integer deletionConcurrency,
@NotNull Integer copyConcurrency,
@NotNull Integer usageCheckpointCount,
@NotNull Duration maxQuotaStaleness,
@NotNull Long maxTotalMediaSize) {
public DynamicBackupConfiguration {
if (deletionConcurrency == null) {
deletionConcurrency = 10;
}
if (copyConcurrency == null) {
copyConcurrency = 10;
}
if (usageCheckpointCount == null) {
usageCheckpointCount = 10;
}
if (maxQuotaStaleness == null) {
maxQuotaStaleness = Duration.ofDays(1);
}
if (maxTotalMediaSize == null) {
maxTotalMediaSize = DataSize.gibibytes(100).toBytes();
}
}
public DynamicBackupConfiguration() {
this(null, null, null, null, null);
}
}
@@ -50,7 +50,7 @@ public class DynamicConfiguration {
@JsonProperty
@Valid
DynamicMetricsConfiguration metricsConfiguration = new DynamicMetricsConfiguration(false, false);
DynamicMetricsConfiguration metricsConfiguration = new DynamicMetricsConfiguration(false, false, null);
@JsonProperty
@Valid
@@ -64,6 +64,10 @@ public class DynamicConfiguration {
@Valid
DynamicRestDeprecationConfiguration restDeprecation = new DynamicRestDeprecationConfiguration(Map.of());
@JsonProperty
@Valid
private DynamicBackupConfiguration backup = new DynamicBackupConfiguration();
public Optional<DynamicExperimentEnrollmentConfiguration> getExperimentEnrollmentConfiguration(
final String experimentName) {
return Optional.ofNullable(experiments.get(experimentName));
@@ -114,4 +118,7 @@ public class DynamicConfiguration {
return restDeprecation;
}
public DynamicBackupConfiguration getBackupConfiguration() {
return backup;
}
}
@@ -5,11 +5,15 @@
package org.whispersystems.textsecuregcm.configuration.dynamic;
import java.util.Set;
import javax.annotation.Nullable;
/**
* @param enableLettuceRemoteTag whether the `remote` tag should be added. Note: although this is dynamic, meters are
* cached after creation, so changes will only affect servers launched after the change.
* @param enableAwsSdkMetrics whether to record AWS SDK metrics. Note: although this is dynamic, meters are cached after
* creation, so changes will only affect servers launched after the change.
* @param datadogAllowList if present, a list of metrics to send to datadog; others will be filtered out. If null, this filtering is not performed.
*/
public record DynamicMetricsConfiguration(boolean enableLettuceRemoteTag, boolean enableAwsSdkMetrics) {
public record DynamicMetricsConfiguration(boolean enableLettuceRemoteTag, boolean enableAwsSdkMetrics, @Nullable Set<String> datadogAllowList) {
}
@@ -45,6 +45,7 @@ import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.time.Clock;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64;
@@ -64,6 +65,8 @@ import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialRequest;
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
import org.whispersystems.textsecuregcm.auth.RedemptionRange;
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
import org.whispersystems.textsecuregcm.backup.BackupManager;
import org.whispersystems.textsecuregcm.backup.CopyParameters;
@@ -162,6 +165,34 @@ public class ArchiveController {
});
}
public record BackupIdLimitResponse(
@Schema(description = "If true, a call to PUT /v1/archive/backupid may succeed without waiting")
boolean hasPermitsRemaining,
@Schema(description = "How long to wait before a permit becomes available, in seconds")
long retryAfterSeconds) {}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/backupid/limits")
@Operation(
summary = "Retrieve limits",
description = """
Determine whether the backup-id can currently be rotated
""")
@ApiResponse(responseCode = "200", description = "Successfully retrieved backup-id rotation limits", useReturnTypeSchema = true)
@ApiResponse(responseCode = "403", description = "Invalid account authentication")
public CompletionStage<BackupIdLimitResponse> checkLimits(@Auth final AuthenticatedDevice authenticatedDevice) {
return accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier())
.thenCompose(maybeAccount -> {
final Account account = maybeAccount
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
return backupAuthManager.checkBackupIdRotationLimit(account).thenApply(limit ->
new BackupIdLimitResponse(limit.hasPermitsRemaining(), limit.nextPermitAvailable().getSeconds()));
});
}
public record RedeemBackupReceiptRequest(
@Schema(description = "Presentation of a ZK receipt encoded in standard padded base64", implementation = String.class)
@JsonDeserialize(using = Deserializer.class)
@@ -280,6 +311,13 @@ public class ArchiveController {
final Map<BackupCredentialType, List<BackupAuthCredentialsResponse.BackupAuthCredential>> credentialsByType =
new ConcurrentHashMap<>();
final RedemptionRange redemptionRange;
try {
redemptionRange = RedemptionRange.inclusive(Clock.systemUTC(), Instant.ofEpochSecond(startSeconds), Instant.ofEpochSecond(endSeconds));
} catch (IllegalArgumentException e) {
throw new BadRequestException(e.getMessage());
}
return accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier())
.thenCompose(maybeAccount -> {
final Account account = maybeAccount
@@ -289,7 +327,7 @@ public class ArchiveController {
.map(credentialType -> this.backupAuthManager.getBackupAuthCredentials(
account,
credentialType,
Instant.ofEpochSecond(startSeconds), Instant.ofEpochSecond(endSeconds))
redemptionRange)
.thenAccept(credentials -> {
backupMetrics.updateGetCredentialCounter(
UserAgentTagUtil.getPlatformTag(userAgent),
@@ -389,6 +427,35 @@ public class ArchiveController {
.thenApply(ReadAuthResponse::new);
}
@GET
@Path("/auth/svrb")
@Produces(MediaType.APPLICATION_JSON)
@Operation(
summary = "Generate credentials for SVRB",
description = """
Generate SVRB service credentials. Generated credentials have an expiration time of 1 day (subject to change)
""")
@ApiResponse(responseCode = "200", description = "`JSON` with generated credentials.", useReturnTypeSchema = true)
@ApiResponseZkAuth
public CompletionStage<ExternalServiceCredentials> svrbAuth(
@Auth final Optional<AuthenticatedDevice> account,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@Parameter(description = BackupAuthCredentialPresentationHeader.DESCRIPTION, schema = @Schema(implementation = String.class))
@NotNull
@HeaderParam(X_SIGNAL_ZK_AUTH) final ArchiveController.BackupAuthCredentialPresentationHeader presentation,
@Parameter(description = BackupAuthCredentialPresentationSignature.DESCRIPTION, schema = @Schema(implementation = String.class))
@NotNull
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature) {
if (account.isPresent()) {
throw new BadRequestException("must not use authenticated connection for anonymous operations");
}
return backupManager
.authenticateBackupUser(presentation.presentation, signature.signature, userAgent)
.thenApply(backupManager::generateSvrbAuth);
}
public record BackupInfoResponse(
@Schema(description = "The CDN type where the message backup is stored. Media may be stored elsewhere.")
int cdn,
@@ -24,7 +24,6 @@ import java.security.InvalidKeyException;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@@ -36,6 +35,7 @@ import org.signal.libsignal.zkgroup.auth.ServerZkAuthOperations;
import org.signal.libsignal.zkgroup.calllinks.CallLinkAuthCredentialResponse;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
import org.whispersystems.textsecuregcm.auth.RedemptionRange;
import org.whispersystems.textsecuregcm.entities.DeliveryCertificate;
import org.whispersystems.textsecuregcm.entities.GroupCredentials;
import org.whispersystems.textsecuregcm.identity.IdentityType;
@@ -97,17 +97,13 @@ public class CertificateController {
@QueryParam("redemptionStartSeconds") long startSeconds,
@QueryParam("redemptionEndSeconds") long endSeconds) {
final Instant startOfDay = clock.instant().truncatedTo(ChronoUnit.DAYS);
final Instant redemptionStart = Instant.ofEpochSecond(startSeconds);
final Instant redemptionEnd = Instant.ofEpochSecond(endSeconds);
if (redemptionStart.isAfter(redemptionEnd) ||
redemptionStart.isBefore(startOfDay) ||
redemptionEnd.isAfter(startOfDay.plus(MAX_REDEMPTION_DURATION)) ||
!redemptionStart.equals(redemptionStart.truncatedTo(ChronoUnit.DAYS)) ||
!redemptionEnd.equals(redemptionEnd.truncatedTo(ChronoUnit.DAYS))) {
throw new BadRequestException();
final RedemptionRange redemptionRange;
try {
final Instant redemptionStart = Instant.ofEpochSecond(startSeconds);
final Instant redemptionEnd = Instant.ofEpochSecond(endSeconds);
redemptionRange = RedemptionRange.inclusive(clock, redemptionStart, redemptionEnd);
} catch (IllegalArgumentException e) {
throw new BadRequestException(e.getCause());
}
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
@@ -116,12 +112,10 @@ public class CertificateController {
final List<GroupCredentials.GroupCredential> credentials = new ArrayList<>();
final List<GroupCredentials.CallLinkAuthCredential> callLinkAuthCredentials = new ArrayList<>();
Instant redemption = redemptionStart;
final ServiceId.Aci aci = new ServiceId.Aci(account.getIdentifier(IdentityType.ACI));
final ServiceId.Pni pni = new ServiceId.Pni(account.getIdentifier(IdentityType.PNI));
while (!redemption.isAfter(redemptionEnd)) {
for (Instant redemption : redemptionRange) {
AuthCredentialWithPniResponse authCredentialWithPni = serverZkAuthOperations.issueAuthCredentialWithPniZkc(aci, pni, redemption);
credentials.add(new GroupCredentials.GroupCredential(
authCredentialWithPni.serialize(),
@@ -130,8 +124,6 @@ public class CertificateController {
callLinkAuthCredentials.add(new GroupCredentials.CallLinkAuthCredential(
CallLinkAuthCredentialResponse.issueCredential(aci, redemption, genericServerSecretParams).serialize(),
redemption.getEpochSecond()));
redemption = redemption.plus(Duration.ofDays(1));
}
return new GroupCredentials(credentials, callLinkAuthCredentials, pni.getRawUUID());
@@ -78,7 +78,8 @@ public class ChallengeController {
AnswerCaptchaChallengeRequest.class}))})
)
@ApiResponse(responseCode = "200", description = "Indicates the challenge proof was accepted")
@ApiResponse(responseCode = "428", description = "Submitted captcha token is invalid")
@ApiResponse(responseCode = "400", description = "The request was invalid")
@ApiResponse(responseCode = "428", description = "Submitted captcha token was not accepted")
@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"))
@@ -115,6 +115,8 @@ public class DeviceController {
private static final String WAIT_FOR_TRANSFER_ARCHIVE_TIMER_NAME =
MetricsUtil.name(DeviceController.class, "waitForTransferArchiveDuration");
private static final String RECORD_TRANSFER_ARCHIVE_UPLOADED_COUNTER_NAME = MetricsUtil.name(DeviceController.class, "recordTransferArchiveUploaded");
private static final String HAS_REGISTRATION_ID_TAG_NAME = "hasRegistrationId";
@VisibleForTesting
static final int MIN_TOKEN_IDENTIFIER_LENGTH = 32;
@@ -446,6 +448,8 @@ public class DeviceController {
private static boolean isCapabilityDowngrade(final Account account, final Set<DeviceCapability> capabilities) {
final Set<DeviceCapability> requiredCapabilities = Arrays.stream(DeviceCapability.values())
// `ALWAYS_CAPABLE` capabilities are always assumed to be present, so we don't require callers to specify them
.filter(capability -> capability.getAccountCapabilityMode() != DeviceCapability.AccountCapabilityMode.ALWAYS_CAPABLE)
.filter(DeviceCapability::preventDowngrade)
.filter(account::hasCapability)
.collect(Collectors.toSet());
@@ -533,8 +537,14 @@ public class DeviceController {
@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(@Auth final AuthenticatedDevice authenticatedDevice,
@NotNull @Valid final TransferArchiveUploadedRequest transferArchiveUploadedRequest) {
@NotNull @Valid final TransferArchiveUploadedRequest transferArchiveUploadedRequest,
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable String userAgent) {
Metrics.counter(RECORD_TRANSFER_ARCHIVE_UPLOADED_COUNTER_NAME, Tags.of(
UserAgentTagUtil.getPlatformTag(userAgent),
io.micrometer.core.instrument.Tag.of(
HAS_REGISTRATION_ID_TAG_NAME,
String.valueOf(transferArchiveUploadedRequest.destinationDeviceRegistrationId().isPresent()))
)).increment();
return rateLimiters.getUploadTransferArchiveLimiter()
.validateAsync(authenticatedDevice.accountIdentifier())
.thenCompose(ignored -> accounts.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
@@ -544,7 +554,8 @@ public class DeviceController {
return accounts.recordTransferArchiveUpload(account,
transferArchiveUploadedRequest.destinationDeviceId(),
Instant.ofEpochMilli(transferArchiveUploadedRequest.destinationDeviceCreated()),
transferArchiveUploadedRequest.destinationDeviceCreated().map(Instant::ofEpochMilli),
transferArchiveUploadedRequest.destinationDeviceRegistrationId(),
transferArchiveUploadedRequest.transferArchive());
});
}
@@ -26,6 +26,7 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.Function;
import javax.annotation.Nonnull;
import org.glassfish.jersey.server.ManagedAsync;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
@@ -86,64 +87,59 @@ public class DonationController {
specific error message suitable for logging will be included as text/plain body
""")
@ApiResponse(responseCode = "429", description = "Rate limited.")
public CompletionStage<Response> redeemReceipt(
@ManagedAsync
public Response redeemReceipt(
@Auth final AuthenticatedDevice auth,
@NotNull @Valid final RedeemReceiptRequest request) {
return CompletableFuture.supplyAsync(() -> {
ReceiptCredentialPresentation receiptCredentialPresentation;
try {
receiptCredentialPresentation = receiptCredentialPresentationFactory
.build(request.getReceiptCredentialPresentation());
} catch (InvalidInputException e) {
return CompletableFuture.completedFuture(Response.status(Status.BAD_REQUEST)
.entity("invalid receipt credential presentation")
.type(MediaType.TEXT_PLAIN_TYPE)
.build());
ReceiptCredentialPresentation receiptCredentialPresentation;
try {
receiptCredentialPresentation = receiptCredentialPresentationFactory
.build(request.getReceiptCredentialPresentation());
} catch (InvalidInputException e) {
return Response.status(Status.BAD_REQUEST)
.entity("invalid receipt credential presentation")
.type(MediaType.TEXT_PLAIN_TYPE)
.build();
}
try {
serverZkReceiptOperations.verifyReceiptCredentialPresentation(receiptCredentialPresentation);
} catch (VerificationFailedException e) {
return Response.status(Status.BAD_REQUEST)
.entity("receipt credential presentation verification failed")
.type(MediaType.TEXT_PLAIN_TYPE)
.build();
}
final ReceiptSerial receiptSerial = receiptCredentialPresentation.getReceiptSerial();
final Instant receiptExpiration = Instant.ofEpochSecond(receiptCredentialPresentation.getReceiptExpirationTime());
final long receiptLevel = receiptCredentialPresentation.getReceiptLevel();
final String badgeId = badgesConfiguration.getReceiptLevels().get(receiptLevel);
if (badgeId == null) {
return Response.serverError()
.entity("server does not recognize the requested receipt level")
.type(MediaType.TEXT_PLAIN_TYPE)
.build();
}
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
final boolean receiptMatched = redeemedReceiptsManager.put(
receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, auth.accountIdentifier()).join();
if (!receiptMatched) {
return Response.status(Status.BAD_REQUEST)
.entity("receipt serial is already redeemed")
.type(MediaType.TEXT_PLAIN_TYPE)
.build();
}
accountsManager.update(account, a -> {
a.addBadge(clock, new AccountBadge(badgeId, receiptExpiration, request.isVisible()));
if (request.isPrimary()) {
a.makeBadgePrimaryIfExists(clock, badgeId);
}
try {
serverZkReceiptOperations.verifyReceiptCredentialPresentation(receiptCredentialPresentation);
} catch (VerificationFailedException e) {
return CompletableFuture.completedFuture(Response.status(Status.BAD_REQUEST)
.entity("receipt credential presentation verification failed")
.type(MediaType.TEXT_PLAIN_TYPE)
.build());
}
final ReceiptSerial receiptSerial = receiptCredentialPresentation.getReceiptSerial();
final Instant receiptExpiration = Instant.ofEpochSecond(receiptCredentialPresentation.getReceiptExpirationTime());
final long receiptLevel = receiptCredentialPresentation.getReceiptLevel();
final String badgeId = badgesConfiguration.getReceiptLevels().get(receiptLevel);
if (badgeId == null) {
return CompletableFuture.completedFuture(Response.serverError()
.entity("server does not recognize the requested receipt level")
.type(MediaType.TEXT_PLAIN_TYPE)
.build());
}
return accountsManager.getByAccountIdentifierAsync(auth.accountIdentifier())
.thenCompose(maybeAccount -> {
final Account account = maybeAccount.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
return redeemedReceiptsManager.put(
receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, auth.accountIdentifier())
.thenCompose(receiptMatched -> {
if (!receiptMatched) {
return CompletableFuture.completedFuture(Response.status(Status.BAD_REQUEST)
.entity("receipt serial is already redeemed")
.type(MediaType.TEXT_PLAIN_TYPE)
.build());
}
return accountsManager.updateAsync(account, a -> {
a.addBadge(clock, new AccountBadge(badgeId, receiptExpiration, request.isVisible()));
if (request.isPrimary()) {
a.makeBadgePrimaryIfExists(clock, badgeId);
}
})
.thenApply(ignored -> Response.ok().build());
});
});
}).thenCompose(Function.identity());
});
return Response.ok().build();
}
}
@@ -6,7 +6,6 @@ package org.whispersystems.textsecuregcm.controllers;
import com.google.common.net.HttpHeaders;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
@@ -34,7 +33,6 @@ import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@@ -57,7 +55,6 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.GroupSendTokenHeader;
import org.whispersystems.textsecuregcm.auth.OptionalAccess;
import org.whispersystems.textsecuregcm.entities.CheckKeysRequest;
import org.whispersystems.textsecuregcm.entities.ECPreKey;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.entities.PreKeyCount;
@@ -92,10 +89,7 @@ public class KeysController {
private final ServerSecretParams serverSecretParams;
private final Clock clock;
private static final String GET_KEYS_COUNTER_NAME = MetricsUtil.name(KeysController.class, "getKeys");
private static final String STORE_KEYS_COUNTER_NAME = MetricsUtil.name(KeysController.class, "storeKeys");
private static final String STORE_KEY_BUNDLE_SIZE_DISTRIBUTION_NAME =
MetricsUtil.name(KeysController.class, "storeKeyBundleSize");
private static final String PRIMARY_DEVICE_TAG_NAME = "isPrimary";
private static final String IDENTITY_TYPE_TAG_NAME = "identityType";
private static final String KEY_TYPE_TAG_NAME = "keyType";
@@ -176,12 +170,6 @@ public class KeysController {
Metrics.counter(STORE_KEYS_COUNTER_NAME, tags).increment();
DistributionSummary.builder(STORE_KEY_BUNDLE_SIZE_DISTRIBUTION_NAME)
.tags(tags)
.publishPercentileHistogram()
.register(Metrics.globalRegistry)
.record(setKeysRequest.preKeys().size());
storeFutures.add(keysManager.storeEcOneTimePreKeys(identifier, device.getId(), setKeysRequest.preKeys()));
}
@@ -197,12 +185,6 @@ public class KeysController {
final Tags tags = Tags.of(platformTag, primaryDeviceTag, identityTypeTag, Tag.of(KEY_TYPE_TAG_NAME, "kyber"));
Metrics.counter(STORE_KEYS_COUNTER_NAME, tags).increment();
DistributionSummary.builder(STORE_KEY_BUNDLE_SIZE_DISTRIBUTION_NAME)
.tags(tags)
.publishPercentileHistogram()
.register(Metrics.globalRegistry)
.record(setKeysRequest.pqPreKeys().size());
storeFutures.add(keysManager.storeKemOneTimePreKeys(identifier, device.getId(), setKeysRequest.pqPreKeys()));
}
@@ -388,58 +370,20 @@ public class KeysController {
final Account target = maybeTarget.orElseThrow(NotFoundException::new);
if (account.isPresent()) {
rateLimiters.getPreKeysLimiter().validate(
account.get().getUuid() + "." + maybeAuthenticatedDevice.get().deviceId() + "__" + targetIdentifier.uuid()
+ "." + deviceId);
rateLimiters.getPreKeysLimiter().validate(getPreKeysLimiterKey(account.get(), maybeAuthenticatedDevice.get(),
targetIdentifier, target, deviceId));
}
final List<Device> devices = parseDeviceId(deviceId, target);
final List<PreKeyResponseItem> responseItems = Flux.fromIterable(devices)
.flatMap(device -> Mono.zip(
Mono.just(device),
Mono.fromFuture(keysManager.takeEC(targetIdentifier.uuid(), device.getId())),
Mono.fromFuture(keysManager.getEcSignedPreKey(targetIdentifier.uuid(), device.getId())),
Mono.fromFuture(keysManager.takePQ(targetIdentifier.uuid(), device.getId()))))
.flatMap(deviceAndPreKeys -> {
final Device device = deviceAndPreKeys.getT1();
final KEMSignedPreKey pqPreKey = deviceAndPreKeys.getT4().orElse(null);
final ECPreKey unsignedEcPreKey = deviceAndPreKeys.getT2().orElse(null);
final ECSignedPreKey signedEcPreKey = deviceAndPreKeys.getT3().orElse(null);
final int registrationId = device.getRegistrationId(targetIdentifier.identityType());
Metrics.counter(GET_KEYS_COUNTER_NAME, Tags.of(
UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(IDENTITY_TYPE_TAG_NAME, targetIdentifier.identityType().name()),
Tag.of("oneTimeEcKeyAvailable", String.valueOf(unsignedEcPreKey != null)),
Tag.of("signedEcKeyAvailable", String.valueOf(signedEcPreKey != null)),
Tag.of("pqKeyAvailable", String.valueOf(pqPreKey != null))))
.increment();
if (pqPreKey == null) {
// The PQ prekey should never be null. This should only happen if the account or device has been
// removed.
return Mono.fromCompletionStage(() -> accounts.getByServiceIdentifierAsync(targetIdentifier))
.flatMap(maybeAccount -> maybeAccount
.flatMap(rereadAccount -> rereadAccount.getDevice(device.getId()))
.filter(rereadDevice ->
registrationId == rereadDevice.getRegistrationId(targetIdentifier.identityType()))
.map(rereadDevice -> {
// The account and device still exist, and the device we originally read matches the current
// registrationId, so the lastResort key should have existed
log.error(
"Target {}, Account {}, DeviceId {}, RegistrationId {} was missing a last resort prekey",
targetIdentifier,
target.getIdentifier(IdentityType.ACI),
rereadDevice.getId(),
rereadDevice.getRegistrationId(targetIdentifier.identityType()));
return Mono.<PreKeyResponseItem>error(new IOException("Device missing last resort prekey"));
})
.orElse(Mono.empty()));
}
return Mono.just(new PreKeyResponseItem(
device.getId(), registrationId, signedEcPreKey, unsignedEcPreKey, pqPreKey));
})
final List<PreKeyResponseItem> responseItems = Flux.fromIterable(devices).flatMap(device -> Mono
.fromCompletionStage(keysManager.takeDevicePreKeys(device.getId(), targetIdentifier, userAgent))
.flatMap(Mono::justOrEmpty)
.map(devicePreKeys -> new PreKeyResponseItem(
device.getId(), device.getRegistrationId(targetIdentifier.identityType()),
devicePreKeys.ecSignedPreKey(),
devicePreKeys.ecPreKey().orElse(null),
devicePreKeys.kemSignedPreKey())))
.collectList()
.block();
@@ -463,4 +407,24 @@ public class KeysController {
throw new WebApplicationException(Response.status(422).build());
}
}
private String getPreKeysLimiterKey(
final Account account,
final AuthenticatedDevice authenticatedDevice,
final ServiceIdentifier targetIdentifier,
final Account targetAccount,
final String targetDeviceId) {
final String targetRegistrationId = targetDeviceId.equals("*")
? "*"
: String.valueOf(
parseDeviceId(targetDeviceId, targetAccount).getFirst().getRegistrationId(targetIdentifier.identityType()));
return String.format("%s.%s__%s.%s.%s",
account.getUuid(),
authenticatedDevice.deviceId(),
targetIdentifier.uuid(),
targetDeviceId,
targetRegistrationId
);
}
}
@@ -110,7 +110,6 @@ import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.Util;
import org.whispersystems.textsecuregcm.websocket.WebSocketConnection;
import org.whispersystems.websocket.WebsocketHeaders;
import reactor.core.scheduler.Scheduler;
@@ -161,6 +160,9 @@ public class MessageController {
.register(Metrics.globalRegistry);
}
private static final String INCORRECT_SYNC_MESSAGE_REGISTRATION_IDS_COUNTER_NAME =
MetricsUtil.name(MessageController.class, "incorrectSyncMessageRegistrationIds");
// The Signal desktop client (really, JavaScript in general) can handle message timestamps at most 100,000,000 days
// past the epoch; please see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date
// for additional details.
@@ -452,6 +454,12 @@ public class MessageController {
userAgent);
} catch (final MismatchedDevicesException e) {
if (!e.getMismatchedDevices().staleDeviceIds().isEmpty()) {
if (messageType == MessageType.SYNC) {
Metrics.counter(INCORRECT_SYNC_MESSAGE_REGISTRATION_IDS_COUNTER_NAME,
Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)))
.increment();
}
throw new WebApplicationException(Response.status(410)
.type(MediaType.APPLICATION_JSON)
.entity(new StaleDevicesResponse(e.getMismatchedDevices().staleDeviceIds()))
@@ -841,15 +849,8 @@ public class MessageController {
final Device device = account.getDevice(auth.deviceId())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
return messagesManager.delete(
auth.accountIdentifier(),
device,
uuid,
null)
return messagesManager.delete(auth.accountIdentifier(), device, uuid, null)
.thenAccept(maybeRemovedMessage -> maybeRemovedMessage.ifPresent(removedMessage -> {
WebSocketConnection.recordMessageDeliveryDuration(removedMessage.serverTimestamp(), device);
if (removedMessage.sourceServiceId().isPresent()
&& removedMessage.envelopeType() != Type.SERVER_DELIVERY_RECEIPT) {
if (removedMessage.sourceServiceId().get() instanceof AciServiceIdentifier aciServiceIdentifier) {
@@ -1,63 +0,0 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.controllers;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.auth.Auth;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import java.time.Clock;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
import org.whispersystems.textsecuregcm.configuration.SecureValueRecoveryConfiguration;
@Path("/v1/svrb")
@Tag(name = "Secure Value Recovery B")
public class SecureValueRecoveryBController {
public static ExternalServiceCredentialsGenerator credentialsGenerator(final SecureValueRecoveryConfiguration cfg) {
return credentialsGenerator(cfg, Clock.systemUTC());
}
@VisibleForTesting
public static ExternalServiceCredentialsGenerator credentialsGenerator(final SecureValueRecoveryConfiguration cfg,
final Clock clock) {
return ExternalServiceCredentialsGenerator
.builder(cfg.userAuthenticationTokenSharedSecret())
.withUserDerivationKey(cfg.userIdTokenSharedSecret().value())
.prependUsername(false)
.withDerivedUsernameTruncateLength(16)
.withClock(clock)
.build();
}
private final ExternalServiceCredentialsGenerator svrbCredentialGenerator;
public SecureValueRecoveryBController(final ExternalServiceCredentialsGenerator svrbCredentialGenerator) {
this.svrbCredentialGenerator = svrbCredentialGenerator;
}
@GET
@Path("/auth")
@Produces(MediaType.APPLICATION_JSON)
@Operation(
summary = "Generate credentials for SVRB",
description = """
Generate SVRB service credentials. Generated credentials have an expiration time of 1 day (subject to change)
"""
)
@ApiResponse(responseCode = "200", description = "`JSON` with generated credentials.", useReturnTypeSchema = true)
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
public ExternalServiceCredentials getAuth(@Auth final AuthenticatedDevice auth) {
return svrbCredentialGenerator.generateFor(auth.accountIdentifier().toString());
}
}
@@ -52,11 +52,11 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.glassfish.jersey.server.ManagedAsync;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.backup.BackupManager;
@@ -65,15 +65,18 @@ import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfigurati
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationCurrencyConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionLevelConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.entities.Badge;
import org.whispersystems.textsecuregcm.entities.PurchasableBadge;
import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.PaymentTime;
import org.whispersystems.textsecuregcm.storage.SubscriberCredentials;
import org.whispersystems.textsecuregcm.storage.SubscriptionException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionException;
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
import org.whispersystems.textsecuregcm.storage.Subscriptions;
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator;
import org.whispersystems.textsecuregcm.subscriptions.BankTransferType;
@@ -85,7 +88,10 @@ import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidLevelException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiresActionException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
@@ -105,6 +111,7 @@ public class SubscriptionController {
private final AppleAppStoreManager appleAppStoreManager;
private final BadgeTranslator badgeTranslator;
private final BankMandateTranslator bankMandateTranslator;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
static final String RECEIPT_ISSUED_COUNTER_NAME = MetricsUtil.name(SubscriptionController.class, "receiptIssued");
static final String PROCESSOR_TAG_NAME = "processor";
static final String TYPE_TAG_NAME = "type";
@@ -120,7 +127,8 @@ public class SubscriptionController {
@Nonnull GooglePlayBillingManager googlePlayBillingManager,
@Nonnull AppleAppStoreManager appleAppStoreManager,
@Nonnull BadgeTranslator badgeTranslator,
@Nonnull BankMandateTranslator bankMandateTranslator) {
@Nonnull BankMandateTranslator bankMandateTranslator,
@NotNull DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
this.subscriptionManager = subscriptionManager;
this.clock = Objects.requireNonNull(clock);
this.subscriptionConfiguration = Objects.requireNonNull(subscriptionConfiguration);
@@ -131,6 +139,7 @@ public class SubscriptionController {
this.appleAppStoreManager = appleAppStoreManager;
this.badgeTranslator = Objects.requireNonNull(badgeTranslator);
this.bankMandateTranslator = Objects.requireNonNull(bankMandateTranslator);
this.dynamicConfigurationManager = dynamicConfigurationManager;
}
private Map<String, CurrencyConfiguration> buildCurrencyConfiguration() {
@@ -203,12 +212,14 @@ public class SubscriptionController {
giftBadge,
oneTimeDonationConfiguration.gift().expiration())));
final long maxTotalBackupMediaBytes =
dynamicConfigurationManager.getConfiguration().getBackupConfiguration().maxTotalMediaSize();
final Map<String, BackupLevelConfiguration> backupLevels = subscriptionConfiguration.getBackupLevels()
.entrySet().stream()
.collect(Collectors.toMap(
e -> String.valueOf(e.getKey()),
e -> new BackupLevelConfiguration(
BackupManager.MAX_TOTAL_BACKUP_MEDIA_BYTES,
maxTotalBackupMediaBytes,
e.getValue().playProductId(),
e.getValue().mediaTtl().toDays())));
@@ -233,12 +244,14 @@ public class SubscriptionController {
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
name = "Retry-After",
description = "If present, a positive integer indicating the number of seconds before a subsequent attempt could succeed"))
public CompletableFuture<Response> deleteSubscriber(
@ManagedAsync
public Response deleteSubscriber(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@PathParam("subscriberId") String subscriberId) throws SubscriptionException {
@PathParam("subscriberId") String subscriberId) throws SubscriptionException, RateLimitExceededException {
SubscriberCredentials subscriberCredentials =
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
return subscriptionManager.deleteSubscriber(subscriberCredentials).thenApply(unused -> Response.ok().build());
subscriptionManager.deleteSubscriber(subscriberCredentials);
return Response.ok().build();
}
@PUT
@@ -255,15 +268,17 @@ public class SubscriptionController {
@ApiResponse(responseCode = "200", description = "The subscriber was successfully created or refreshed")
@ApiResponse(responseCode = "403", description = "subscriberId authentication failure OR account authentication is present")
@ApiResponse(responseCode = "404", description = "subscriberId is malformed")
public CompletableFuture<Response> updateSubscriber(
@ManagedAsync
public Response updateSubscriber(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@PathParam("subscriberId") String subscriberId) throws SubscriptionException {
SubscriberCredentials subscriberCredentials =
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
return subscriptionManager.updateSubscriber(subscriberCredentials).thenApply(record -> Response.ok().build());
subscriptionManager.updateSubscriber(subscriberCredentials);
return Response.ok().build();
}
record CreatePaymentMethodResponse(String clientSecret, PaymentProvider processor) {
public record CreatePaymentMethodResponse(String clientSecret, PaymentProvider processor) {
}
@@ -271,7 +286,8 @@ public class SubscriptionController {
@Path("/{subscriberId}/create_payment_method")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public CompletableFuture<Response> createPaymentMethod(
@ManagedAsync
public CreatePaymentMethodResponse createPaymentMethod(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@PathParam("subscriberId") String subscriberId,
@QueryParam("type") @DefaultValue("CARD") PaymentMethod paymentMethodType,
@@ -290,13 +306,13 @@ public class SubscriptionController {
case UNKNOWN -> throw new BadRequestException("Invalid payment method");
};
return subscriptionManager.addPaymentMethodToCustomer(
subscriberCredentials,
customerAwareSubscriptionPaymentProcessor,
getClientPlatform(userAgentString),
CustomerAwareSubscriptionPaymentProcessor::createPaymentMethodSetupToken)
.thenApply(token ->
Response.ok(new CreatePaymentMethodResponse(token, customerAwareSubscriptionPaymentProcessor.getProvider())).build());
final String token = subscriptionManager.addPaymentMethodToCustomer(
subscriberCredentials,
customerAwareSubscriptionPaymentProcessor,
getClientPlatform(userAgentString),
CustomerAwareSubscriptionPaymentProcessor::createPaymentMethodSetupToken);
return new CreatePaymentMethodResponse(token, customerAwareSubscriptionPaymentProcessor.getProvider());
}
public record CreatePayPalBillingAgreementRequest(@NotBlank String returnUrl, @NotBlank String cancelUrl) {}
@@ -307,7 +323,8 @@ public class SubscriptionController {
@Path("/{subscriberId}/create_payment_method/paypal")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public CompletableFuture<Response> createPayPalPaymentMethod(
@ManagedAsync
public CreatePayPalBillingAgreementResponse createPayPalPaymentMethod(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@PathParam("subscriberId") String subscriberId,
@NotNull @Valid CreatePayPalBillingAgreementRequest request,
@@ -321,17 +338,16 @@ public class SubscriptionController {
.findFirst()
.orElse(Locale.US);
return subscriptionManager.addPaymentMethodToCustomer(
final BraintreeManager.PayPalBillingAgreementApprovalDetails billingAgreementApprovalDetails = subscriptionManager.addPaymentMethodToCustomer(
subscriberCredentials,
braintreeManager,
getClientPlatform(userAgentString),
(mgr, customerId) ->
mgr.createPayPalBillingAgreement(request.returnUrl, request.cancelUrl, locale.toLanguageTag()))
.thenApply(billingAgreementApprovalDetails -> Response.ok(
new CreatePayPalBillingAgreementResponse(
billingAgreementApprovalDetails.approvalUrl(),
billingAgreementApprovalDetails.billingAgreementToken()))
.build());
.join();
return new CreatePayPalBillingAgreementResponse(
billingAgreementApprovalDetails.approvalUrl(),
billingAgreementApprovalDetails.billingAgreementToken());
}
private CustomerAwareSubscriptionPaymentProcessor getCustomerAwareProcessor(PaymentProvider processor) {
@@ -346,7 +362,8 @@ public class SubscriptionController {
@Path("/{subscriberId}/default_payment_method/{processor}/{paymentMethodToken}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public CompletableFuture<Response> setDefaultPaymentMethodWithProcessor(
@ManagedAsync
public Response setDefaultPaymentMethodWithProcessor(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@PathParam("subscriberId") String subscriberId,
@PathParam("processor") PaymentProvider processor,
@@ -356,7 +373,8 @@ public class SubscriptionController {
final CustomerAwareSubscriptionPaymentProcessor manager = getCustomerAwareProcessor(processor);
return setDefaultPaymentMethod(manager, paymentMethodToken, subscriberCredentials);
setDefaultPaymentMethod(manager, paymentMethodToken, subscriberCredentials);
return Response.ok().build();
}
public record SetSubscriptionLevelSuccessResponse(long level) {
@@ -383,7 +401,8 @@ public class SubscriptionController {
@Path("/{subscriberId}/level/{level}/{currency}/{idempotencyKey}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public CompletableFuture<Response> setSubscriptionLevel(
@ManagedAsync
public SetSubscriptionLevelSuccessResponse setSubscriptionLevel(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@PathParam("subscriberId") String subscriberId,
@PathParam("level") long level,
@@ -391,42 +410,40 @@ public class SubscriptionController {
@PathParam("idempotencyKey") String idempotencyKey) throws SubscriptionException {
SubscriberCredentials subscriberCredentials =
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
return subscriptionManager.getSubscriber(subscriberCredentials)
.thenCompose(record -> {
final ProcessorCustomer processorCustomer = record.getProcessorCustomer()
.orElseThrow(() ->
// a missing customer ID indicates the client made requests out of order,
// and needs to call create_payment_method to create a customer for the given payment method
new ClientErrorException(Status.CONFLICT));
try {
final Subscriptions.Record record = subscriptionManager.getSubscriber(subscriberCredentials);
final ProcessorCustomer processorCustomer = record.getProcessorCustomer()
.orElseThrow(() ->
// a missing customer ID indicates the client made requests out of order,
// and needs to call create_payment_method to create a customer for the given payment method
new ClientErrorException(Status.CONFLICT));
final String subscriptionTemplateId = getSubscriptionTemplateId(level, currency,
processorCustomer.processor());
final String subscriptionTemplateId = getSubscriptionTemplateId(level, currency,
processorCustomer.processor());
final CustomerAwareSubscriptionPaymentProcessor manager = getCustomerAwareProcessor(processorCustomer.processor());
return subscriptionManager.updateSubscriptionLevelForCustomer(subscriberCredentials, record, manager, level,
currency, idempotencyKey, subscriptionTemplateId, this::subscriptionsAreSameType);
})
.exceptionally(ExceptionUtils.exceptionallyHandler(SubscriptionException.InvalidLevel.class, e -> {
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
.entity(new SubscriptionController.SetSubscriptionLevelErrorResponse(List.of(
new SubscriptionController.SetSubscriptionLevelErrorResponse.Error(
SubscriptionController.SetSubscriptionLevelErrorResponse.Error.Type.UNSUPPORTED_LEVEL,
null))))
.build());
}))
.exceptionally(ExceptionUtils.exceptionallyHandler(SubscriptionException.PaymentRequiresAction.class, e -> {
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
.entity(new SetSubscriptionLevelErrorResponse(List.of(new SetSubscriptionLevelErrorResponse.Error(
SetSubscriptionLevelErrorResponse.Error.Type.PAYMENT_REQUIRES_ACTION, null))))
.build());
}))
.exceptionally(ExceptionUtils.exceptionallyHandler(SubscriptionException.InvalidArguments.class, e -> {
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
.entity(new SetSubscriptionLevelErrorResponse(List.of(new SetSubscriptionLevelErrorResponse.Error(
SetSubscriptionLevelErrorResponse.Error.Type.INVALID_ARGUMENTS, e.getMessage()))))
.build());
}))
.thenApply(unused -> Response.ok(new SetSubscriptionLevelSuccessResponse(level)).build());
final CustomerAwareSubscriptionPaymentProcessor manager = getCustomerAwareProcessor(
processorCustomer.processor());
subscriptionManager.updateSubscriptionLevelForCustomer(subscriberCredentials, record, manager, level,
currency, idempotencyKey, subscriptionTemplateId, this::subscriptionsAreSameType);
return new SetSubscriptionLevelSuccessResponse(level);
} catch (SubscriptionInvalidLevelException e) {
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
.entity(new SubscriptionController.SetSubscriptionLevelErrorResponse(List.of(
new SubscriptionController.SetSubscriptionLevelErrorResponse.Error(
SubscriptionController.SetSubscriptionLevelErrorResponse.Error.Type.UNSUPPORTED_LEVEL,
null))))
.build());
} catch (SubscriptionPaymentRequiresActionException e) {
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
.entity(new SetSubscriptionLevelErrorResponse(List.of(new SetSubscriptionLevelErrorResponse.Error(
SetSubscriptionLevelErrorResponse.Error.Type.PAYMENT_REQUIRES_ACTION, null))))
.build());
} catch (SubscriptionInvalidArgumentsException e) {
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
.entity(new SetSubscriptionLevelErrorResponse(List.of(new SetSubscriptionLevelErrorResponse.Error(
SetSubscriptionLevelErrorResponse.Error.Type.INVALID_ARGUMENTS, e.getMessage()))))
.build());
}
}
public boolean subscriptionsAreSameType(long level1, long level2) {
@@ -449,7 +466,7 @@ public class SubscriptionController {
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 = "200", description = "The originalTransactionId was successfully validated", useReturnTypeSchema = true)
@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")
@@ -457,16 +474,16 @@ public class SubscriptionController {
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
name = "Retry-After",
description = "If present, a positive integer indicating the number of seconds before a subsequent attempt could succeed"))
public CompletableFuture<SetSubscriptionLevelSuccessResponse> setAppStoreSubscription(
@ManagedAsync
public SetSubscriptionLevelSuccessResponse setAppStoreSubscription(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@PathParam("subscriberId") String subscriberId,
@PathParam("originalTransactionId") String originalTransactionId) throws SubscriptionException {
@PathParam("originalTransactionId") String originalTransactionId) throws SubscriptionException, RateLimitExceededException {
final SubscriberCredentials subscriberCredentials =
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
return subscriptionManager
.updateAppStoreTransactionId(subscriberCredentials, appleAppStoreManager, originalTransactionId)
.thenApply(SetSubscriptionLevelSuccessResponse::new);
return new SetSubscriptionLevelSuccessResponse(subscriptionManager
.updateAppStoreTransactionId(subscriberCredentials, appleAppStoreManager, originalTransactionId));
}
@@ -493,7 +510,7 @@ public class SubscriptionController {
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 = "200", description = "The purchaseToken was validated and acknowledged", useReturnTypeSchema = true)
@ApiResponse(responseCode = "402", description = "The purchaseToken payment 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 purchaseToken does not exist")
@@ -501,16 +518,16 @@ public class SubscriptionController {
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
name = "Retry-After",
description = "If present, a positive integer indicating the number of seconds before a subsequent attempt could succeed"))
public CompletableFuture<SetSubscriptionLevelSuccessResponse> setPlayStoreSubscription(
@ManagedAsync
public SetSubscriptionLevelSuccessResponse setPlayStoreSubscription(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@PathParam("subscriberId") String subscriberId,
@PathParam("purchaseToken") String purchaseToken) throws SubscriptionException {
@PathParam("purchaseToken") String purchaseToken) throws SubscriptionException, RateLimitExceededException {
final SubscriberCredentials subscriberCredentials =
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
return subscriptionManager
.updatePlayBillingPurchaseToken(subscriberCredentials, googlePlayBillingManager, purchaseToken)
.thenApply(SetSubscriptionLevelSuccessResponse::new);
return new SetSubscriptionLevelSuccessResponse(subscriptionManager
.updatePlayBillingPurchaseToken(subscriberCredentials, googlePlayBillingManager, purchaseToken));
}
@Schema(description = """
@@ -572,24 +589,21 @@ public class SubscriptionController {
description = """
Returns all configuration for badges, donation subscriptions, backup subscriptions, and one-time donation (
"boost" and "gift") minimum and suggested amounts.""")
@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = GetSubscriptionConfigurationResponse.class)))
public CompletableFuture<Response> getConfiguration(@Context ContainerRequestContext containerRequestContext) {
return CompletableFuture.supplyAsync(() -> {
List<Locale> acceptableLanguages = HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext);
return Response.ok(buildGetSubscriptionConfigurationResponse(acceptableLanguages)).build();
});
@ApiResponse(responseCode = "200", useReturnTypeSchema = true)
@ManagedAsync
public GetSubscriptionConfigurationResponse getConfiguration(@Context ContainerRequestContext containerRequestContext) {
List<Locale> acceptableLanguages = HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext);
return buildGetSubscriptionConfigurationResponse(acceptableLanguages);
}
@GET
@Path("/bank_mandate/{bankTransferType}")
@Produces(MediaType.APPLICATION_JSON)
public CompletableFuture<Response> getBankMandate(final @Context ContainerRequestContext containerRequestContext,
@ManagedAsync
public GetBankMandateResponse getBankMandate(final @Context ContainerRequestContext containerRequestContext,
final @PathParam("bankTransferType") BankTransferType bankTransferType) {
return CompletableFuture.supplyAsync(() -> {
List<Locale> acceptableLanguages = HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext);
return Response.ok(new GetBankMandateResponse(
bankMandateTranslator.translate(acceptableLanguages, bankTransferType))).build();
});
List<Locale> acceptableLanguages = HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext);
return new GetBankMandateResponse(bankMandateTranslator.translate(acceptableLanguages, bankTransferType));
}
public record GetBankMandateResponse(String mandate) {}
@@ -652,19 +666,20 @@ public class SubscriptionController {
to Stripe's. Since we don’t support trials or unpaid subscriptions, the associated statuses will never be returned
by the API.
""")
@ApiResponse(responseCode = "200", description = "The subscriberId exists", content = @Content(schema = @Schema(implementation = GetSubscriptionInformationResponse.class)))
@ApiResponse(responseCode = "200", description = "The subscriberId exists", useReturnTypeSchema = true)
@ApiResponse(responseCode = "403", description = "subscriberId authentication failure OR account authentication is present")
@ApiResponse(responseCode = "404", description = "No such subscriberId exists or subscriberId is malformed")
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
name = "Retry-After",
description = "If present, a positive integer indicating the number of seconds before a subsequent attempt could succeed"))
public CompletableFuture<Response> getSubscriptionInformation(
@ManagedAsync
public GetSubscriptionInformationResponse getSubscriptionInformation(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@PathParam("subscriberId") String subscriberId) throws SubscriptionException {
@PathParam("subscriberId") String subscriberId) throws SubscriptionException, RateLimitExceededException {
SubscriberCredentials subscriberCredentials =
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
return subscriptionManager.getSubscriptionInformation(subscriberCredentials).thenApply(maybeInfo -> maybeInfo
.map(subscriptionInformation -> Response.ok(
return subscriptionManager.getSubscriptionInformation( subscriberCredentials)
.map(subscriptionInformation ->
new GetSubscriptionInformationResponse(
new GetSubscriptionInformationResponse.Subscription(
subscriptionInformation.level(),
@@ -679,8 +694,8 @@ public class SubscriptionController {
subscriptionInformation.paymentMethod(),
subscriptionInformation.paymentProcessing()),
subscriptionInformation.chargeFailure()
)).build())
.orElseGet(() -> Response.ok(new GetSubscriptionInformationResponse(null, null)).build()));
))
.orElseGet(() -> new GetSubscriptionInformationResponse(null, null));
}
public record GetReceiptCredentialsRequest(
@@ -717,7 +732,7 @@ public class SubscriptionController {
Clients MUST validate that the generated receipt credential's level and expiration matches their expectations.
""")
@ApiResponse(responseCode = "200", description = "Successfully created receipt", content = @Content(schema = @Schema(implementation = GetReceiptCredentialsResponse.class)))
@ApiResponse(responseCode = "200", description = "Successfully created receipt", useReturnTypeSchema = true)
@ApiResponse(responseCode = "204", description = "No invoice has been issued for this subscription OR invoice is in 'open' state")
@ApiResponse(responseCode = "400", description = "Bad ReceiptCredentialRequest")
@ApiResponse(responseCode = "402", description = "Invoice is in any state other than 'open' or 'paid'. May include chargeFailure details in body.",
@@ -741,63 +756,68 @@ public class SubscriptionController {
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
name = "Retry-After",
description = "If present, a positive integer indicating the number of seconds before a subsequent attempt could succeed"))
public CompletableFuture<Response> createSubscriptionReceiptCredentials(
@ManagedAsync
public Response createSubscriptionReceiptCredentials(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@PathParam("subscriberId") String subscriberId,
@NotNull @Valid GetReceiptCredentialsRequest request) throws SubscriptionException {
@NotNull @Valid GetReceiptCredentialsRequest request) throws SubscriptionException, RateLimitExceededException {
SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
return subscriptionManager.createReceiptCredentials(subscriberCredentials, request, this::receiptExpirationWithGracePeriod)
.thenApply(receiptCredential -> {
final ReceiptCredentialResponse receiptCredentialResponse = receiptCredential.receiptCredentialResponse();
final CustomerAwareSubscriptionPaymentProcessor.ReceiptItem receipt = receiptCredential.receiptItem();
Metrics.counter(RECEIPT_ISSUED_COUNTER_NAME,
Tags.of(
Tag.of(PROCESSOR_TAG_NAME, receiptCredential.paymentProvider().toString()),
Tag.of(TYPE_TAG_NAME, "subscription"),
Tag.of(SUBSCRIPTION_TYPE_TAG_NAME,
subscriptionConfiguration.getSubscriptionLevel(receipt.level()).type().name()
.toLowerCase(Locale.ROOT)),
UserAgentTagUtil.getPlatformTag(userAgent)))
.increment();
return Response.ok(new GetReceiptCredentialsResponse(receiptCredentialResponse.serialize())).build();
})
.exceptionally(ExceptionUtils.exceptionallyHandler(
SubscriptionException.ReceiptRequestedForOpenPayment.class,
e -> Response.noContent().build()));
try {
final SubscriptionManager.ReceiptResult receiptCredential = subscriptionManager.createReceiptCredentials(
subscriberCredentials, request, this::receiptExpirationWithGracePeriod);
final ReceiptCredentialResponse receiptCredentialResponse = receiptCredential.receiptCredentialResponse();
final CustomerAwareSubscriptionPaymentProcessor.ReceiptItem receipt = receiptCredential.receiptItem();
Metrics.counter(RECEIPT_ISSUED_COUNTER_NAME,
Tags.of(
Tag.of(PROCESSOR_TAG_NAME, receiptCredential.paymentProvider().toString()),
Tag.of(TYPE_TAG_NAME, "subscription"),
Tag.of(SUBSCRIPTION_TYPE_TAG_NAME,
subscriptionConfiguration.getSubscriptionLevel(receipt.level()).type().name()
.toLowerCase(Locale.ROOT)),
UserAgentTagUtil.getPlatformTag(userAgent)))
.increment();
return Response.ok(new GetReceiptCredentialsResponse(receiptCredentialResponse.serialize())).build();
} catch (SubscriptionReceiptRequestedForOpenPaymentException e) {
return Response.noContent().build();
}
}
@POST
@Path("/{subscriberId}/default_payment_method_for_ideal/{setupIntentId}")
@Produces(MediaType.APPLICATION_JSON)
public CompletableFuture<Response> setDefaultPaymentMethodForIdeal(
@ManagedAsync
public Response setDefaultPaymentMethodForIdeal(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@PathParam("subscriberId") String subscriberId,
@PathParam("setupIntentId") @NotEmpty String setupIntentId) throws SubscriptionException {
SubscriberCredentials subscriberCredentials =
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
return stripeManager.getGeneratedSepaIdFromSetupIntent(setupIntentId)
.thenCompose(generatedSepaId -> setDefaultPaymentMethod(stripeManager, generatedSepaId, subscriberCredentials));
final String generatedSepaId = stripeManager.getGeneratedSepaIdFromSetupIntent(setupIntentId).join();
setDefaultPaymentMethod(stripeManager, generatedSepaId, subscriberCredentials);
return Response.ok().build();
}
private CompletableFuture<Response> setDefaultPaymentMethod(final CustomerAwareSubscriptionPaymentProcessor manager,
private void setDefaultPaymentMethod(final CustomerAwareSubscriptionPaymentProcessor manager,
final String paymentMethodId,
final SubscriberCredentials requestData) {
return subscriptionManager.getSubscriber(requestData)
.thenCompose(record -> record.getProcessorCustomer()
.map(processorCustomer -> manager.setDefaultPaymentMethodForCustomer(processorCustomer.customerId(),
paymentMethodId, record.subscriptionId))
.orElseThrow(() ->
// a missing customer ID indicates the client made requests out of order,
// and needs to call create_payment_method to create a customer for the given payment method
new ClientErrorException(Status.CONFLICT)))
.exceptionally(ExceptionUtils.exceptionallyHandler(SubscriptionException.InvalidArguments.class, e -> {
// Here, invalid arguments must mean that the client has made requests out of order, and needs to finish
// setting up the paymentMethod first
throw new ClientErrorException(Status.CONFLICT);
}))
.thenApply(customer -> Response.ok().build());
final SubscriberCredentials requestData) throws SubscriptionException {
try {
final Subscriptions.Record record = subscriptionManager.getSubscriber(requestData);
final ProcessorCustomer processorCustomer = record.getProcessorCustomer()
// a missing customer ID indicates the client made requests out of order,
// and needs to call create_payment_method to create a customer for the given payment method
.orElseThrow(() ->new ClientErrorException(Status.CONFLICT));
manager
.setDefaultPaymentMethodForCustomer(processorCustomer.customerId(), paymentMethodId, record.subscriptionId);
} catch (SubscriptionInvalidArgumentsException e) {
// Here, invalid arguments must mean that the client has made requests out of order, and needs to finish
// setting up the paymentMethod first
throw new ClientErrorException(Status.CONFLICT);
}
}
private Instant receiptExpirationWithGracePeriod(CustomerAwareSubscriptionPaymentProcessor.ReceiptItem receiptItem) {
@@ -51,10 +51,14 @@ public record IncomingMessage(int type,
.setClientTimestamp(timestamp)
.setServerTimestamp(clock.millis())
.setDestinationServiceId(destinationIdentifier.toServiceIdentifierString())
.setStory(story)
.setEphemeral(ephemeral)
.setUrgent(urgent);
if (story) {
// Avoid sending this field if it's false.
envelopeBuilder.setStory(true);
}
if (sourceServiceIdentifier != null && sourceDeviceId != null) {
envelopeBuilder
.setSourceServiceId(sourceServiceIdentifier.toServiceIdentifierString())
@@ -46,9 +46,13 @@ public record OutgoingMessageEntity(UUID guid,
.setServerTimestamp(serverTimestamp())
.setDestinationServiceId(destinationUuid().toServiceIdentifierString())
.setServerGuid(guid().toString())
.setStory(story)
.setUrgent(urgent);
if (story) {
// Avoid sending this field if it's false.
builder.setStory(true);
}
if (sourceUuid() != null) {
builder.setSourceServiceId(sourceUuid().toServiceIdentifierString());
builder.setSourceDevice(sourceDevice());
@@ -19,7 +19,7 @@ public class PreKeyResponseItem {
private int registrationId;
@JsonProperty
@Schema(description="the signed elliptic-curve prekey for the device, if one has been set")
@Schema(description="the signed elliptic-curve prekey for the device")
private ECSignedPreKey signedPreKey;
@JsonProperty
@@ -28,7 +28,7 @@ public class PreKeyResponseItem {
@JsonProperty
@Schema(description="a signed post-quantum prekey for the device " +
"(a one-time prekey if any remain, otherwise the last-resort prekey if one has been set)")
"(a one-time prekey if any remain, otherwise the last-resort prekey)")
private KEMSignedPreKey pqPreKey;
public PreKeyResponseItem() {}
@@ -89,6 +89,9 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT
@AssertTrue
@Schema(hidden = true)
boolean hasExactlyOneMessageDeliveryChannel() {
if (deviceActivationRequest == null || accountAttributes == null) {
return false;
}
if (accountAttributes.getFetchesMessages()) {
return deviceActivationRequest().apnToken().isEmpty() && deviceActivationRequest().gcmToken().isEmpty();
} else {
@@ -7,21 +7,30 @@ package org.whispersystems.textsecuregcm.entities;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import org.whispersystems.textsecuregcm.storage.Device;
import java.util.Optional;
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 timestamp, in milliseconds since the epoch, at which the destination device was created.
Deprecated in favor of `destinationDeviceRegistrationId`.
""", deprecated = true)
@Deprecated
Optional<@Positive Long> destinationDeviceCreated,
@Schema(description = "The registration ID of the destination device")
Optional<@Min(0) @Max(Device.MAX_REGISTRATION_ID) Integer> destinationDeviceRegistrationId,
@NotNull
@Valid
@@ -29,4 +38,10 @@ public record TransferArchiveUploadedRequest(
The location of the transfer archive if the archive was successfully uploaded, otherwise a error indicating that
the upload has failed and the destination device should stop waiting
""", oneOf = {RemoteAttachment.class, RemoteAttachmentError.class})
TransferArchiveResult transferArchive) {}
TransferArchiveResult transferArchive) {
@AssertTrue
@Schema(hidden = true)
public boolean isExactlyOneDisambiguatorProvided() {
return destinationDeviceCreated.isPresent() ^ destinationDeviceRegistrationId.isPresent();
}
}
@@ -21,6 +21,8 @@ import org.signal.chat.backup.GetBackupInfoRequest;
import org.signal.chat.backup.GetBackupInfoResponse;
import org.signal.chat.backup.GetCdnCredentialsRequest;
import org.signal.chat.backup.GetCdnCredentialsResponse;
import org.signal.chat.backup.GetSvrBCredentialsRequest;
import org.signal.chat.backup.GetSvrBCredentialsResponse;
import org.signal.chat.backup.GetUploadFormRequest;
import org.signal.chat.backup.GetUploadFormResponse;
import org.signal.chat.backup.ListMediaRequest;
@@ -64,6 +66,16 @@ public class BackupsAnonymousGrpcService extends ReactorBackupsAnonymousGrpc.Bac
.map(credentials -> GetCdnCredentialsResponse.newBuilder().putAllHeaders(credentials).build());
}
@Override
public Mono<GetSvrBCredentialsResponse> getSvrBCredentials(final GetSvrBCredentialsRequest request) {
return authenticateBackupUserMono(request.getSignedPresentation())
.map(backupManager::generateSvrbAuth)
.map(credentials -> GetSvrBCredentialsResponse.newBuilder()
.setUsername(credentials.username())
.setPassword(credentials.password())
.build());
}
@Override
public Mono<GetBackupInfoResponse> getBackupInfo(final GetBackupInfoRequest request) {
return Mono.fromFuture(() ->
@@ -6,12 +6,11 @@ package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import io.grpc.Status;
import io.micrometer.core.instrument.Tag;
import java.time.Clock;
import java.time.Instant;
import java.util.List;
import java.util.stream.Collectors;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import org.signal.chat.backup.GetBackupAuthCredentialsRequest;
import org.signal.chat.backup.GetBackupAuthCredentialsResponse;
import org.signal.chat.backup.ReactorBackupsGrpc;
@@ -24,10 +23,10 @@ import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialRequest;
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
import org.whispersystems.textsecuregcm.auth.RedemptionRange;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
import org.whispersystems.textsecuregcm.controllers.ArchiveController;
import org.whispersystems.textsecuregcm.metrics.BackupMetrics;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.Account;
@@ -35,8 +34,6 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import reactor.core.publisher.Mono;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
public class BackupsGrpcService extends ReactorBackupsGrpc.BackupsImplBase {
private final AccountsManager accountManager;
@@ -85,14 +82,20 @@ public class BackupsGrpcService extends ReactorBackupsGrpc.BackupsImplBase {
@Override
public Mono<GetBackupAuthCredentialsResponse> getBackupAuthCredentials(GetBackupAuthCredentialsRequest request) {
final Tag platformTag = UserAgentTagUtil.getPlatformTag(RequestAttributesUtil.getUserAgent().orElse(null));
final RedemptionRange redemptionRange;
try {
redemptionRange = RedemptionRange.inclusive(Clock.systemUTC(),
Instant.ofEpochSecond(request.getRedemptionStart()),
Instant.ofEpochSecond(request.getRedemptionStop()));
} catch (IllegalArgumentException e) {
throw Status.INVALID_ARGUMENT.withDescription(e.getMessage()).asRuntimeException();
}
return authenticatedAccount().flatMap(account -> {
final Mono<List<BackupAuthManager.Credential>> messageCredentials = Mono.fromCompletionStage(() ->
backupAuthManager.getBackupAuthCredentials(
account,
BackupCredentialType.MESSAGES,
Instant.ofEpochSecond(request.getRedemptionStart()),
Instant.ofEpochSecond(request.getRedemptionStop())))
redemptionRange))
.doOnSuccess(credentials ->
backupMetrics.updateGetCredentialCounter(platformTag, BackupCredentialType.MESSAGES, credentials.size()));
@@ -100,8 +103,7 @@ public class BackupsGrpcService extends ReactorBackupsGrpc.BackupsImplBase {
backupAuthManager.getBackupAuthCredentials(
account,
BackupCredentialType.MEDIA,
Instant.ofEpochSecond(request.getRedemptionStart()),
Instant.ofEpochSecond(request.getRedemptionStop())))
redemptionRange))
.doOnSuccess(credentials ->
backupMetrics.updateGetCredentialCounter(platformTag, BackupCredentialType.MEDIA, credentials.size()));
@@ -47,16 +47,6 @@ enum ExternalServiceDefinitions {
.withClock(clock)
.build();
}),
SVRB(ExternalServiceType.EXTERNAL_SERVICE_TYPE_SVRB, (chatConfig, clock) -> {
final SecureValueRecoveryConfiguration cfg = chatConfig.getSvrbConfiguration();
return ExternalServiceCredentialsGenerator
.builder(cfg.userAuthenticationTokenSharedSecret())
.withUserDerivationKey(cfg.userIdTokenSharedSecret().value())
.prependUsername(false)
.withDerivedUsernameTruncateLength(16)
.withClock(clock)
.build();
}),
STORAGE(ExternalServiceType.EXTERNAL_SERVICE_TYPE_STORAGE, (chatConfig, clock) -> {
final PaymentsServiceConfiguration cfg = chatConfig.getPaymentsServiceConfiguration();
return ExternalServiceCredentialsGenerator
@@ -56,7 +56,7 @@ public class KeysAnonymousGrpcService extends ReactorKeysAnonymousGrpc.KeysAnony
groupSendTokenUtil.checkGroupSendToken(request.getGroupSendToken(), serviceIdentifier);
yield lookUpAccount(serviceIdentifier, Status.NOT_FOUND)
.flatMap(targetAccount -> KeysGrpcHelper.getPreKeys(targetAccount, serviceIdentifier.identityType(), deviceId, keysManager));
.flatMap(targetAccount -> KeysGrpcHelper.getPreKeys(targetAccount, serviceIdentifier, deviceId, keysManager));
} catch (final StatusException e) {
yield Mono.error(e);
}
@@ -66,7 +66,7 @@ public class KeysAnonymousGrpcService extends ReactorKeysAnonymousGrpc.KeysAnony
lookUpAccount(serviceIdentifier, Status.UNAUTHENTICATED)
.flatMap(targetAccount ->
UnidentifiedAccessUtil.checkUnidentifiedAccess(targetAccount, request.getUnidentifiedAccessKey().toByteArray())
? KeysGrpcHelper.getPreKeys(targetAccount, serviceIdentifier.identityType(), deviceId, keysManager)
? KeysGrpcHelper.getPreKeys(targetAccount, serviceIdentifier, deviceId, keysManager)
: Mono.error(Status.UNAUTHENTICATED.asException()));
default -> Mono.error(Status.INVALID_ARGUMENT.asException());
@@ -11,10 +11,7 @@ import org.signal.chat.common.EcPreKey;
import org.signal.chat.common.EcSignedPreKey;
import org.signal.chat.common.KemSignedPreKey;
import org.signal.chat.keys.GetPreKeysResponse;
import org.whispersystems.textsecuregcm.entities.ECPreKey;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.KeysManager;
@@ -28,7 +25,7 @@ class KeysGrpcHelper {
static final byte ALL_DEVICES = 0;
static Mono<GetPreKeysResponse> getPreKeys(final Account targetAccount,
final IdentityType identityType,
final ServiceIdentifier targetServiceIdentifier,
final byte targetDeviceId,
final KeysManager keysManager) {
@@ -36,42 +33,37 @@ class KeysGrpcHelper {
? Flux.fromIterable(targetAccount.getDevices())
: Flux.from(Mono.justOrEmpty(targetAccount.getDevice(targetDeviceId)));
final String userAgent = RequestAttributesUtil.getUserAgent().orElse(null);
return devices
.switchIfEmpty(Mono.error(Status.NOT_FOUND.asException()))
.flatMap(device -> Flux.merge(
Mono.fromFuture(() -> keysManager.takeEC(targetAccount.getIdentifier(identityType), device.getId())),
Mono.fromFuture(() -> keysManager.getEcSignedPreKey(targetAccount.getIdentifier(identityType), device.getId())),
Mono.fromFuture(() -> keysManager.takePQ(targetAccount.getIdentifier(identityType), device.getId())))
.flatMap(device -> Mono
.fromFuture(keysManager.takeDevicePreKeys(device.getId(), targetServiceIdentifier, userAgent))
.flatMap(Mono::justOrEmpty)
.reduce(GetPreKeysResponse.PreKeyBundle.newBuilder(), (builder, preKey) -> {
if (preKey instanceof ECPreKey ecPreKey) {
builder.setEcOneTimePreKey(EcPreKey.newBuilder()
.map(devicePreKeys -> {
final GetPreKeysResponse.PreKeyBundle.Builder builder = GetPreKeysResponse.PreKeyBundle.newBuilder()
.setEcSignedPreKey(EcSignedPreKey.newBuilder()
.setKeyId(devicePreKeys.ecSignedPreKey().keyId())
.setPublicKey(ByteString.copyFrom(devicePreKeys.ecSignedPreKey().serializedPublicKey()))
.setSignature(ByteString.copyFrom(devicePreKeys.ecSignedPreKey().signature()))
.build())
.setKemOneTimePreKey(KemSignedPreKey.newBuilder()
.setKeyId(devicePreKeys.kemSignedPreKey().keyId())
.setPublicKey(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().serializedPublicKey()))
.setSignature(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().signature()))
.build());
devicePreKeys.ecPreKey().ifPresent(ecPreKey -> builder.setEcOneTimePreKey(EcPreKey.newBuilder()
.setKeyId(ecPreKey.keyId())
.setPublicKey(ByteString.copyFrom(ecPreKey.serializedPublicKey()))
.build());
} else if (preKey instanceof ECSignedPreKey ecSignedPreKey) {
builder.setEcSignedPreKey(EcSignedPreKey.newBuilder()
.setKeyId(ecSignedPreKey.keyId())
.setPublicKey(ByteString.copyFrom(ecSignedPreKey.serializedPublicKey()))
.setSignature(ByteString.copyFrom(ecSignedPreKey.signature()))
.build());
} else if (preKey instanceof KEMSignedPreKey kemSignedPreKey) {
builder.setKemOneTimePreKey(KemSignedPreKey.newBuilder()
.setKeyId(kemSignedPreKey.keyId())
.setPublicKey(ByteString.copyFrom(kemSignedPreKey.serializedPublicKey()))
.setSignature(ByteString.copyFrom(kemSignedPreKey.signature()))
.build());
} else {
throw new AssertionError("Unexpected pre-key type: " + preKey.getClass());
}
return builder;
})
// Cast device IDs to `int` to match data types in the response object’s protobuf definition
.map(builder -> Tuples.of((int) device.getId(), builder.build())))
.build()));
// Cast device IDs to `int` to match data types in the response object’s protobuf definition
return Tuples.of((int) device.getId(), builder.build());
}))
// If there were no devices with valid prekey bundles in the account, the account is gone
.switchIfEmpty(Mono.error(Status.NOT_FOUND.asException()))
.collectMap(Tuple2::getT1, Tuple2::getT2)
.map(preKeyBundles -> GetPreKeysResponse.newBuilder()
.setIdentityKey(ByteString.copyFrom(targetAccount.getIdentityKey(identityType).serialize()))
.setIdentityKey(ByteString
.copyFrom(targetAccount.getIdentityKey(targetServiceIdentifier.identityType())
.serialize()))
.putAllPreKeys(preKeyBundles)
.build());
}
@@ -136,7 +136,7 @@ public class KeysGrpcService extends ReactorKeysGrpc.KeysImplBase {
.flatMap(Mono::justOrEmpty))
.switchIfEmpty(Mono.error(Status.NOT_FOUND.asException()))
.flatMap(targetAccount ->
KeysGrpcHelper.getPreKeys(targetAccount, targetIdentifier.identityType(), deviceId, keysManager));
KeysGrpcHelper.getPreKeys(targetAccount, targetIdentifier, deviceId, keysManager));
}
@Override
@@ -168,9 +168,13 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
.setDestinationServiceId(destinationServiceIdentifier.toServiceIdentifierString())
.setEphemeral(ephemeral)
.setUrgent(urgent)
.setStory(story)
.setContent(entry.getValue().getPayload());
if (story) {
// Avoid sending this field if it's false.
envelopeBuilder.setStory(true);
}
spamCheckResult.token().ifPresent(reportSpamToken ->
envelopeBuilder.setReportSpamToken(ByteString.copyFrom(reportSpamToken)));
@@ -0,0 +1,134 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import com.google.common.annotations.VisibleForTesting;
import io.grpc.*;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.Timer;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
public class MetricServerInterceptor implements ServerInterceptor {
private static final String TAG_SERVICE_NAME = "grpcService";
private static final String TAG_METHOD_NAME = "method";
private static final String TAG_METHOD_TYPE = "methodType";
private static final String TAG_STATUS_CODE = "statusCode";
@VisibleForTesting
static final String REQUEST_MESSAGE_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "requestMessage");
@VisibleForTesting
static final String RESPONSE_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "responseMessage");
@VisibleForTesting
static final String RPC_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "rpc");
@VisibleForTesting
static final String DURATION_TIMER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "processingDuration");
private final MeterRegistry meterRegistry;
private final ClientReleaseManager clientReleaseManager;
public MetricServerInterceptor(final MeterRegistry meterRegistry, final ClientReleaseManager clientReleaseManager) {
this.meterRegistry = meterRegistry;
this.clientReleaseManager = clientReleaseManager;
}
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
final ServerCall<ReqT, RespT> call,
final Metadata headers,
final ServerCallHandler<ReqT, RespT> next) {
final Optional<String> userAgentString = RequestAttributesUtil.getUserAgent();
final List<Tag> tagList = new ArrayList<>(6);
tagList.add(Tag.of(TAG_SERVICE_NAME, call.getMethodDescriptor().getServiceName()));
tagList.add(Tag.of(TAG_METHOD_NAME, call.getMethodDescriptor().getBareMethodName()));
tagList.add(Tag.of(TAG_METHOD_TYPE, call.getMethodDescriptor().getType().name()));
RequestAttributesUtil.getUserAgent()
.map(UserAgentTagUtil::getLibsignalAndPlatformTags)
.ifPresent(tagList::addAll);
userAgentString
.flatMap(ua -> UserAgentTagUtil.getClientVersionTag(ua, clientReleaseManager))
.ifPresent(tagList::add);
final Tags tags = Tags.of(tagList);
final MetricServerCall<ReqT, RespT> monitoringServerCall = new MetricServerCall<>(call, tags);
return new MetricServerCallListener<>(next.startCall(monitoringServerCall, headers), tags);
}
/**
* A ServerCall delegator that updates metrics on response messages and the final RPC status
*/
private class MetricServerCall<ReqT, RespT> extends ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT> {
private final Counter responseMessageCounter;
private final Tags tags;
MetricServerCall(final ServerCall<ReqT, RespT> delegate, final Tags tags) {
super(delegate);
this.responseMessageCounter = meterRegistry.counter(RESPONSE_COUNTER_NAME, tags);
this.tags = tags;
}
@Override
public void close(final Status status, final Metadata responseHeaders) {
meterRegistry.counter(RPC_COUNTER_NAME, tags.and(TAG_STATUS_CODE, status.getCode().name())).increment();
super.close(status, responseHeaders);
}
@Override
public void sendMessage(final RespT responseMessage) {
this.responseMessageCounter.increment();
super.sendMessage(responseMessage);
}
}
/**
* A ServerCallListener delegator that updates metrics on requests and measures the RPC time on completion
*/
private class MetricServerCallListener<ReqT> extends ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT> {
private final Counter requestCounter;
private final Timer responseTimer;
private final Timer.Sample sample;
MetricServerCallListener(final ServerCall.Listener<ReqT> delegate, final Tags tags) {
super(delegate);
this.requestCounter = meterRegistry.counter(REQUEST_MESSAGE_COUNTER_NAME, tags);
this.responseTimer = meterRegistry.timer(DURATION_TIMER_NAME, tags);
this.sample = Timer.start(meterRegistry);
}
@Override
public void onMessage(final ReqT requestMessage) {
this.requestCounter.increment();
super.onMessage(requestMessage);
}
@Override
public void onComplete() {
this.sample.stop(responseTimer);
super.onComplete();
}
@Override
public void onCancel() {
this.sample.stop(responseTimer);
super.onCancel();
}
}
}
@@ -1,5 +1,8 @@
package org.whispersystems.textsecuregcm.grpc.net;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
@@ -15,6 +18,8 @@ import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
/**
* An "establish local connection" handler waits for a Noise handshake to complete upstream in the pipeline, buffering
@@ -22,24 +27,28 @@ import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
* server.
*/
public class EstablishLocalGrpcConnectionHandler extends ChannelInboundHandlerAdapter {
private static final Logger log = LoggerFactory.getLogger(EstablishLocalGrpcConnectionHandler.class);
private final GrpcClientConnectionManager grpcClientConnectionManager;
private final LocalAddress authenticatedGrpcServerAddress;
private final LocalAddress anonymousGrpcServerAddress;
private final FramingType framingType;
private final List<Object> pendingReads = new ArrayList<>();
private static final Logger log = LoggerFactory.getLogger(EstablishLocalGrpcConnectionHandler.class);
private static final String CONNECTION_ESTABLISHED_COUNTER_NAME = MetricsUtil.name(EstablishLocalGrpcConnectionHandler.class, "established");
public EstablishLocalGrpcConnectionHandler(final GrpcClientConnectionManager grpcClientConnectionManager,
final LocalAddress authenticatedGrpcServerAddress,
final LocalAddress anonymousGrpcServerAddress) {
final LocalAddress anonymousGrpcServerAddress,
final FramingType framingType) {
this.grpcClientConnectionManager = grpcClientConnectionManager;
this.authenticatedGrpcServerAddress = authenticatedGrpcServerAddress;
this.anonymousGrpcServerAddress = anonymousGrpcServerAddress;
this.framingType = framingType;
}
@Override
@@ -63,6 +72,12 @@ public class EstablishLocalGrpcConnectionHandler extends ChannelInboundHandlerAd
GrpcClientConnectionManager.handleHandshakeInitiated(
remoteChannelContext.channel(), remoteAddress, userAgent, acceptLanguage);
final List<Tag> tags = UserAgentTagUtil.getLibsignalAndPlatformTags(userAgent);
Metrics.counter(CONNECTION_ESTABLISHED_COUNTER_NAME, Tags.of(tags)
.and("authenticated", Boolean.toString(authenticatedDevice.isPresent()))
.and("framingType", framingType.name()))
.increment();
new Bootstrap()
.remoteAddress(grpcServerAddress)
.channel(LocalChannel.class)
@@ -0,0 +1,6 @@
package org.whispersystems.textsecuregcm.grpc.net;
public enum FramingType {
NOISE_DIRECT,
WEBSOCKET
}
@@ -18,4 +18,5 @@ public record NoiseIdentityDeterminedEvent(
Optional<AuthenticatedDevice> authenticatedDevice,
InetAddress remoteAddress,
String userAgent,
String acceptLanguage) {}
String acceptLanguage) {
}
@@ -16,7 +16,7 @@ import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
* Watches for inbound close frames and closes the connection in response
*/
public class NoiseDirectInboundCloseHandler extends ChannelInboundHandlerAdapter {
private static String CLIENT_CLOSE_COUNTER_NAME = MetricsUtil.name(ChannelInboundHandlerAdapter.class, "clientClose");
private static String CLIENT_CLOSE_COUNTER_NAME = MetricsUtil.name(NoiseDirectInboundCloseHandler.class, "clientClose");
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
if (msg instanceof NoiseDirectFrame ndf && ndf.frameType() == NoiseDirectFrame.FrameType.CLOSE) {
@@ -1,5 +1,6 @@
package org.whispersystems.textsecuregcm.grpc.net.noisedirect;
import io.micrometer.core.instrument.Metrics;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufOutputStream;
import io.netty.channel.ChannelFutureListener;
@@ -7,12 +8,14 @@ import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import org.whispersystems.textsecuregcm.grpc.net.OutboundCloseErrorMessage;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
/**
* Translates {@link OutboundCloseErrorMessage}s into {@link NoiseDirectFrame} error frames. After error frames are
* written, the channel is closed
*/
class NoiseDirectOutboundErrorHandler extends ChannelOutboundHandlerAdapter {
private static String SERVER_CLOSE_COUNTER_NAME = MetricsUtil.name(NoiseDirectInboundCloseHandler.class, "serverClose");
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
@@ -23,6 +26,8 @@ class NoiseDirectOutboundErrorHandler extends ChannelOutboundHandlerAdapter {
case NOISE_HANDSHAKE_ERROR -> NoiseDirectProtos.CloseReason.Code.HANDSHAKE_ERROR;
case INTERNAL_SERVER_ERROR -> NoiseDirectProtos.CloseReason.Code.INTERNAL_ERROR;
};
Metrics.counter(SERVER_CLOSE_COUNTER_NAME, "reason", code.name()).increment();
final NoiseDirectProtos.CloseReason proto = NoiseDirectProtos.CloseReason.newBuilder()
.setCode(code)
.setMessage(err.message())
@@ -17,6 +17,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.grpc.net.ErrorHandler;
import org.whispersystems.textsecuregcm.grpc.net.EstablishLocalGrpcConnectionHandler;
import org.whispersystems.textsecuregcm.grpc.net.FramingType;
import org.whispersystems.textsecuregcm.grpc.net.GrpcClientConnectionManager;
import org.whispersystems.textsecuregcm.grpc.net.HAProxyMessageHandler;
import org.whispersystems.textsecuregcm.grpc.net.NoiseHandshakeHandler;
@@ -68,7 +69,9 @@ public class NoiseDirectTunnelServer implements Managed {
// This handler will open a local connection to the appropriate gRPC server and install a ProxyHandler
// once the Noise handshake has completed
.addLast(new EstablishLocalGrpcConnectionHandler(
grpcClientConnectionManager, authenticatedGrpcServerAddress, anonymousGrpcServerAddress))
grpcClientConnectionManager,
authenticatedGrpcServerAddress, anonymousGrpcServerAddress,
FramingType.NOISE_DIRECT))
.addLast(new ErrorHandler());
}
});
@@ -104,6 +104,8 @@ public class NoiseWebSocketTunnelServer implements Managed {
// request and passed it down the pipeline
.addLast(new WebSocketOpeningHandshakeHandler(AUTHENTICATED_SERVICE_PATH, ANONYMOUS_SERVICE_PATH, HEALTH_CHECK_PATH))
.addLast(new WebSocketServerProtocolHandler("/", true))
// Metrics on inbound/outbound Close frames
.addLast(new WebSocketCloseMetricHandler())
// Turn generic OutboundCloseErrorMessages into websocket close frames
.addLast(new WebSocketOutboundErrorHandler())
.addLast(new RejectUnsupportedMessagesHandler())
@@ -116,7 +118,10 @@ public class NoiseWebSocketTunnelServer implements Managed {
.addLast(new NoiseHandshakeHandler(clientPublicKeysManager, ecKeyPair))
// This handler will open a local connection to the appropriate gRPC server and install a ProxyHandler
// once the Noise handshake has completed
.addLast(new EstablishLocalGrpcConnectionHandler(grpcClientConnectionManager, authenticatedGrpcServerAddress, anonymousGrpcServerAddress))
.addLast(new EstablishLocalGrpcConnectionHandler(
grpcClientConnectionManager,
authenticatedGrpcServerAddress, anonymousGrpcServerAddress,
FramingType.WEBSOCKET))
.addLast(new ErrorHandler());
}
});
@@ -0,0 +1,50 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc.net.websocket;
import io.micrometer.core.instrument.Metrics;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
public class WebSocketCloseMetricHandler extends ChannelDuplexHandler {
private static String CLIENT_CLOSE_COUNTER_NAME = MetricsUtil.name(WebSocketCloseMetricHandler.class, "clientClose");
private static String SERVER_CLOSE_COUNTER_NAME = MetricsUtil.name(WebSocketCloseMetricHandler.class, "serverClose");
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
if (msg instanceof CloseWebSocketFrame closeFrame) {
Metrics.counter(CLIENT_CLOSE_COUNTER_NAME, "closeCode", validatedCloseCode(closeFrame.statusCode())).increment();
}
ctx.fireChannelRead(msg);
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (msg instanceof CloseWebSocketFrame closeFrame) {
Metrics.counter(SERVER_CLOSE_COUNTER_NAME, "closeCode", Integer.toString(closeFrame.statusCode())).increment();
}
ctx.write(msg, promise);
}
private static String validatedCloseCode(int closeCode) {
if (closeCode >= 1000 && closeCode <= 1015) {
// RFC-6455 pre-defined status codes
return Integer.toString(closeCode);
} else if (closeCode >= 4000 && closeCode <= 4100) {
// Application status codes
return Integer.toString(closeCode);
} else {
return "unknown";
}
}
}
@@ -10,11 +10,13 @@ import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.grpc.net.OutboundCloseErrorMessage;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
/**
* Converts {@link OutboundCloseErrorMessage}s written to the pipeline into WebSocket close frames
*/
class WebSocketOutboundErrorHandler extends ChannelDuplexHandler {
private static String SERVER_CLOSE_COUNTER_NAME = MetricsUtil.name(WebSocketOutboundErrorHandler.class, "serverClose");
private boolean websocketHandshakeComplete = false;
@@ -16,6 +16,8 @@ import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.time.Duration;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.Executor;
@@ -24,55 +26,39 @@ import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.IntStream;
import io.micrometer.core.instrument.Tags;
import javax.annotation.Nullable;
import org.glassfish.jersey.SslConfigurator;
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
import org.whispersystems.textsecuregcm.util.CertificateUtil;
import org.whispersystems.textsecuregcm.util.CircuitBreakerUtil;
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
public class FaultTolerantHttpClient {
private final List<HttpClient> httpClients;
private final Duration defaultRequestTimeout;
private final ScheduledExecutorService retryExecutor;
private final Retry retry;
@Nullable private final ScheduledExecutorService retryExecutor;
@Nullable private final Retry retry;
private final CircuitBreaker breaker;
public static final String SECURITY_PROTOCOL_TLS_1_2 = "TLSv1.2";
public static final String SECURITY_PROTOCOL_TLS_1_3 = "TLSv1.3";
public static Builder newBuilder() {
return new Builder();
public static Builder newBuilder(final String name, final Executor executor) {
return new Builder(name, executor);
}
@VisibleForTesting
FaultTolerantHttpClient(String name, List<HttpClient> httpClients, ScheduledExecutorService retryExecutor,
Duration defaultRequestTimeout, RetryConfiguration retryConfiguration,
final Predicate<Throwable> retryOnException, CircuitBreakerConfiguration circuitBreakerConfiguration) {
FaultTolerantHttpClient(final List<HttpClient> httpClients,
final Duration defaultRequestTimeout,
@Nullable final ScheduledExecutorService retryExecutor,
@Nullable final Retry retry,
final CircuitBreaker circuitBreaker) {
this.httpClients = httpClients;
this.retryExecutor = retryExecutor;
this.defaultRequestTimeout = defaultRequestTimeout;
this.breaker = CircuitBreaker.of(name + "-breaker", circuitBreakerConfiguration.toCircuitBreakerConfig());
CircuitBreakerUtil.registerMetrics(breaker, FaultTolerantHttpClient.class, Tags.empty());
if (retryConfiguration != null) {
if (this.retryExecutor == null) {
throw new IllegalArgumentException("retryExecutor must be specified with retryConfiguration");
}
final RetryConfig.Builder<HttpResponse> retryConfig = retryConfiguration.<HttpResponse>toRetryConfigBuilder()
.retryOnResult(o -> o.statusCode() >= 500);
if (retryOnException != null) {
retryConfig.retryOnException(retryOnException);
}
this.retry = Retry.of(name + "-retry", retryConfig.build());
CircuitBreakerUtil.registerMetrics(retry, FaultTolerantHttpClient.class);
} else {
this.retry = null;
}
this.retryExecutor = retryExecutor;
this.retry = retry;
this.breaker = circuitBreaker;
}
private HttpClient httpClient() {
@@ -80,28 +66,30 @@ public class FaultTolerantHttpClient {
}
public <T> CompletableFuture<HttpResponse<T>> sendAsync(HttpRequest request,
HttpResponse.BodyHandler<T> bodyHandler) {
final HttpResponse.BodyHandler<T> bodyHandler) {
if (request.timeout().isEmpty()) {
request = HttpRequest.newBuilder(request, (n, v) -> true)
request = HttpRequest.newBuilder(request, (_, _) -> true)
.timeout(defaultRequestTimeout)
.build();
}
Supplier<CompletionStage<HttpResponse<T>>> asyncRequest = sendAsync(httpClient(), request, bodyHandler);
final Supplier<CompletionStage<HttpResponse<T>>> asyncRequestSupplier =
sendAsync(httpClient(), request, bodyHandler);
if (retry != null) {
return breaker.executeCompletionStage(retryableCompletionStage(asyncRequest)).toCompletableFuture();
} else {
return breaker.executeCompletionStage(asyncRequest).toCompletableFuture();
}
}
assert retryExecutor != null;
private <T> Supplier<CompletionStage<T>> retryableCompletionStage(Supplier<CompletionStage<T>> supplier) {
return () -> retry.executeCompletionStage(retryExecutor, supplier);
return breaker.executeCompletionStage(retry.decorateCompletionStage(retryExecutor, asyncRequestSupplier))
.toCompletableFuture();
} else {
return breaker.executeCompletionStage(asyncRequestSupplier).toCompletableFuture();
}
}
private <T> Supplier<CompletionStage<HttpResponse<T>>> sendAsync(HttpClient client, HttpRequest request,
HttpResponse.BodyHandler<T> bodyHandler) {
return () -> client.sendAsync(request, bodyHandler);
}
@@ -113,21 +101,18 @@ public class FaultTolerantHttpClient {
private Duration requestTimeout = Duration.ofSeconds(60);
private int numClients = 1;
private String name;
private final String name;
private Executor executor;
private ScheduledExecutorService retryExecutor;
private KeyStore trustStore;
private String securityProtocol = SECURITY_PROTOCOL_TLS_1_2;
private RetryConfiguration retryConfiguration;
private String retryConfigurationName;
private ScheduledExecutorService retryExecutor;
private Predicate<Throwable> retryOnException;
private CircuitBreakerConfiguration circuitBreakerConfiguration;
@Nullable private String circuitBreakerConfigurationName;
private Builder() {
}
public Builder withName(String name) {
this.name = name;
return this;
private Builder(final String name, final Executor executor) {
this.name = getClass().getSimpleName() + "/" + Objects.requireNonNull(name);
this.executor = Objects.requireNonNull(executor);
}
public Builder withVersion(HttpClient.Version version) {
@@ -140,11 +125,6 @@ public class FaultTolerantHttpClient {
return this;
}
public Builder withExecutor(Executor executor) {
this.executor = executor;
return this;
}
public Builder withConnectTimeout(Duration connectTimeout) {
this.connectTimeout = connectTimeout;
return this;
@@ -155,18 +135,15 @@ public class FaultTolerantHttpClient {
return this;
}
public Builder withRetry(RetryConfiguration retryConfiguration) {
this.retryConfiguration = retryConfiguration;
return this;
}
public Builder withRetryExecutor(ScheduledExecutorService retryExecutor) {
public Builder withRetry(@Nullable final String retryConfigurationName, final ScheduledExecutorService retryExecutor) {
this.retryConfigurationName = retryConfigurationName;
this.retryExecutor = retryExecutor;
return this;
}
public Builder withCircuitBreaker(CircuitBreakerConfiguration circuitBreakerConfiguration) {
this.circuitBreakerConfiguration = circuitBreakerConfiguration;
public Builder withCircuitBreaker(@Nullable final String circuitBreakerConfigurationName) {
this.circuitBreakerConfigurationName = circuitBreakerConfigurationName;
return this;
}
@@ -206,10 +183,6 @@ public class FaultTolerantHttpClient {
}
public FaultTolerantHttpClient build() {
if (this.circuitBreakerConfiguration == null || this.name == null || this.executor == null) {
throw new IllegalArgumentException("Must specify circuit breaker config, name, and executor");
}
if (numClients > 1 && version != HttpClient.Version.HTTP_2) {
throw new IllegalArgumentException("Should not use additional HTTP clients unless using HTTP/2");
}
@@ -232,8 +205,33 @@ public class FaultTolerantHttpClient {
return builder.build();
}).toList();
return new FaultTolerantHttpClient(name, httpClients, retryExecutor, requestTimeout, retryConfiguration,
retryOnException, circuitBreakerConfiguration);
@Nullable final Retry retry;
if (retryExecutor != null) {
final RetryConfig.Builder<HttpResponse<?>> retryConfigBuilder =
RetryConfig.from(Optional.ofNullable(retryConfigurationName)
.flatMap(name -> ResilienceUtil.getRetryRegistry().getConfiguration(name))
.orElseGet(() -> ResilienceUtil.getRetryRegistry().getDefaultConfig()));
retryConfigBuilder.retryOnResult(response -> response.statusCode() >= 500);
if (retryOnException != null) {
retryConfigBuilder.retryOnException(retryOnException);
}
retry = ResilienceUtil.getRetryRegistry()
.retry(ResilienceUtil.name(FaultTolerantHttpClient.class, name), retryConfigBuilder.build());
} else {
retry = null;
}
final String circuitBreakerName = ResilienceUtil.name(FaultTolerantHttpClient.class, name);
final CircuitBreaker circuitBreaker = circuitBreakerConfigurationName != null
? ResilienceUtil.getCircuitBreakerRegistry().circuitBreaker(circuitBreakerName, circuitBreakerConfigurationName)
: ResilienceUtil.getCircuitBreakerRegistry().circuitBreaker(circuitBreakerName);
return new FaultTolerantHttpClient(httpClients, requestTimeout, retryExecutor, retry, circuitBreaker);
}
}
@@ -13,6 +13,7 @@ import java.io.UncheckedIOException;
import java.time.Clock;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.apache.commons.lang3.tuple.Pair;
@@ -30,11 +31,12 @@ public abstract class BaseRateLimiters<T extends RateLimiterDescriptor> {
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final ClusterLuaScript validateScript,
final FaultTolerantRedisClusterClient cacheCluster,
final ScheduledExecutorService retryExecutor,
final Clock clock) {
this.rateLimiterByDescriptor = Arrays.stream(values)
.map(descriptor -> Pair.of(
descriptor,
createForDescriptor(descriptor, dynamicConfigurationManager, validateScript, cacheCluster, clock)))
createForDescriptor(descriptor, dynamicConfigurationManager, validateScript, cacheCluster, retryExecutor, clock)))
.collect(Collectors.toUnmodifiableMap(Pair::getKey, Pair::getValue));
}
@@ -42,7 +44,7 @@ public abstract class BaseRateLimiters<T extends RateLimiterDescriptor> {
return requireNonNull(rateLimiterByDescriptor.get(handle));
}
protected static ClusterLuaScript defaultScript(final FaultTolerantRedisClusterClient cacheCluster) {
public static ClusterLuaScript defaultScript(final FaultTolerantRedisClusterClient cacheCluster) {
try {
return ClusterLuaScript.fromResource(
cacheCluster, "lua/validate_rate_limit.lua", ScriptOutputType.INTEGER);
@@ -56,9 +58,10 @@ public abstract class BaseRateLimiters<T extends RateLimiterDescriptor> {
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final ClusterLuaScript validateScript,
final FaultTolerantRedisClusterClient cacheCluster,
final ScheduledExecutorService retryExecutor,
final Clock clock) {
final Supplier<RateLimiterConfig> configResolver =
() -> dynamicConfigurationManager.getConfiguration().getLimits().getOrDefault(descriptor.id(), descriptor.defaultConfig());
return new DynamicRateLimiter(descriptor.id(), configResolver, validateScript, cacheCluster, clock);
return new DynamicRateLimiter(descriptor.id(), configResolver, validateScript, cacheCluster, retryExecutor, clock);
}
}
@@ -14,11 +14,13 @@ import java.time.Duration;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Supplier;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.Util;
@@ -30,22 +32,26 @@ public class DynamicRateLimiter implements RateLimiter {
private final ClusterLuaScript validateScript;
private final FaultTolerantRedisClusterClient cluster;
private final ScheduledExecutorService retryExecutor;
private final Counter limitExceededCounter;
private final Clock clock;
private static final String RETRY_NAME = ResilienceUtil.name(DynamicRateLimiter.class);
public DynamicRateLimiter(
final String name,
final Supplier<RateLimiterConfig> configResolver,
final ClusterLuaScript validateScript,
final FaultTolerantRedisClusterClient cluster,
final ScheduledExecutorService retryExecutor,
final Clock clock) {
this.name = requireNonNull(name);
this.configResolver = requireNonNull(configResolver);
this.validateScript = requireNonNull(validateScript);
this.cluster = requireNonNull(cluster);
this.retryExecutor = requireNonNull(retryExecutor);
this.clock = requireNonNull(clock);
this.limitExceededCounter = Metrics.counter(MetricsUtil.name(getClass(), "exceeded"), "rateLimiterName", name);
}
@@ -129,13 +135,15 @@ public class DynamicRateLimiter implements RateLimiter {
@Override
public void clear(final String key) {
cluster.useCluster(connection -> connection.sync().del(bucketName(name, key)));
ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
.executeRunnable(() -> cluster.useCluster(connection -> connection.sync().del(bucketName(name, key))));
}
@Override
public CompletionStage<Void> clearAsync(final String key) {
return cluster.withCluster(connection -> connection.async().del(bucketName(name, key)))
.thenRun(Util.NOOP);
return ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
.executeCompletionStage(retryExecutor, () -> cluster.withCluster(connection -> connection.async().del(bucketName(name, key)))
.thenRun(Util.NOOP));
}
@Override
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.limits;
import com.google.common.annotations.VisibleForTesting;
import java.time.Clock;
import java.time.Duration;
import java.util.concurrent.ScheduledExecutorService;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
@@ -77,9 +78,10 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
public static RateLimiters create(
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final FaultTolerantRedisClusterClient cacheCluster) {
final FaultTolerantRedisClusterClient cacheCluster,
final ScheduledExecutorService retryExecutor) {
return new RateLimiters(
dynamicConfigurationManager, defaultScript(cacheCluster), cacheCluster, Clock.systemUTC());
dynamicConfigurationManager, defaultScript(cacheCluster), cacheCluster, retryExecutor, Clock.systemUTC());
}
@VisibleForTesting
@@ -87,8 +89,9 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final ClusterLuaScript validateScript,
final FaultTolerantRedisClusterClient cacheCluster,
final ScheduledExecutorService retryExecutor,
final Clock clock) {
super(For.values(), dynamicConfigurationManager, validateScript, cacheCluster, clock);
super(For.values(), dynamicConfigurationManager, validateScript, cacheCluster, retryExecutor, clock);
}
public RateLimiter getAllocateDeviceLimiter() {
@@ -12,8 +12,16 @@ import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
import java.util.Map;
import org.whispersystems.textsecuregcm.storage.SubscriptionException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionChargeFailurePaymentRequiredException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionException;
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionForbiddenException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidAmountException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorConflictException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
public class SubscriptionExceptionMapper implements ExceptionMapper<SubscriptionException> {
@VisibleForTesting
@@ -25,20 +33,20 @@ public class SubscriptionExceptionMapper implements ExceptionMapper<Subscription
public Response toResponse(final SubscriptionException exception) {
// Some exceptions have specific error body formats
if (exception instanceof SubscriptionException.InvalidAmount e) {
if (exception instanceof SubscriptionInvalidAmountException e) {
return Response
.status(Response.Status.BAD_REQUEST)
.entity(Map.of("error", e.getErrorCode()))
.type(MediaType.APPLICATION_JSON_TYPE)
.build();
}
if (exception instanceof SubscriptionException.ProcessorException e) {
if (exception instanceof SubscriptionProcessorException e) {
return Response.status(PROCESSOR_ERROR_STATUS_CODE)
.entity(new ChargeFailureResponse(e.getProcessor().name(), e.getChargeFailure()))
.type(MediaType.APPLICATION_JSON_TYPE)
.build();
}
if (exception instanceof SubscriptionException.ChargeFailurePaymentRequired e) {
if (exception instanceof SubscriptionChargeFailurePaymentRequiredException e) {
return Response
.status(Response.Status.PAYMENT_REQUIRED)
.entity(new ChargeFailureResponse(e.getProcessor().name(), e.getChargeFailure()))
@@ -48,11 +56,11 @@ public class SubscriptionExceptionMapper implements ExceptionMapper<Subscription
// 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;
case SubscriptionException.InvalidArguments e -> Response.Status.BAD_REQUEST;
case SubscriptionException.ProcessorConflict e -> Response.Status.CONFLICT;
case SubscriptionException.PaymentRequired e -> Response.Status.PAYMENT_REQUIRED;
case SubscriptionNotFoundException e -> Response.Status.NOT_FOUND;
case SubscriptionForbiddenException e -> Response.Status.FORBIDDEN;
case SubscriptionInvalidArgumentsException e -> Response.Status.BAD_REQUEST;
case SubscriptionProcessorConflictException e -> Response.Status.CONFLICT;
case SubscriptionPaymentRequiredException e -> Response.Status.PAYMENT_REQUIRED;
default -> Response.Status.INTERNAL_SERVER_ERROR;
});
@@ -12,6 +12,10 @@ import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nullable;
import org.glassfish.jersey.server.ContainerResponse;
import org.glassfish.jersey.server.monitoring.RequestEvent;
import org.glassfish.jersey.server.monitoring.RequestEventListener;
@@ -21,11 +25,6 @@ import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import org.whispersystems.textsecuregcm.util.logging.UriInfoUtil;
import org.whispersystems.websocket.WebSocketResourceProvider;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* Gathers and reports request-level metrics for WebSocket traffic only.
* For HTTP traffic, use {@link MetricsHttpChannelListener}.
@@ -53,6 +52,9 @@ public class MetricsRequestEventListener implements RequestEventListener {
@VisibleForTesting
static final String TRAFFIC_SOURCE_TAG = "trafficSource";
@VisibleForTesting
static final String AUTHENTICATED_TAG = "authenticated";
private final TrafficSource trafficSource;
private final MeterRegistry meterRegistry;
@@ -86,6 +88,12 @@ public class MetricsRequestEventListener implements RequestEventListener {
.map(ContainerResponse::getStatus)
.orElse(499))));
tags.add(Tag.of(TRAFFIC_SOURCE_TAG, trafficSource.name().toLowerCase()));
tags.add(Tag.of(AUTHENTICATED_TAG, Optional.ofNullable(event.getContainerRequest().getProperty(WebSocketResourceProvider.REUSABLE_AUTH_PROPERTY))
.filter(Optional.class::isInstance)
.map(Optional.class::cast)
.map(Optional::isPresent)
.orElse(false)
.toString()));
@Nullable final String userAgent;
{
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.metrics;
import com.codahale.metrics.SharedMetricRegistries;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.core.setup.Environment;
import io.dropwizard.lifecycle.Managed;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Metrics;
@@ -21,9 +22,18 @@ import io.micrometer.core.instrument.config.MeterFilter;
import io.micrometer.core.instrument.distribution.DistributionStatisticConfig;
import io.micrometer.registry.otlp.OtlpMeterRegistry;
import io.micrometer.statsd.StatsdMeterRegistry;
import io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporter;
import io.opentelemetry.instrumentation.logback.appender.v1_0.OpenTelemetryAppender;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.logs.SdkLoggerProvider;
import io.opentelemetry.sdk.logs.export.BatchLogRecordProcessor;
import io.opentelemetry.sdk.resources.Resource;
import io.opentelemetry.sdk.resources.ResourceBuilder;
import io.opentelemetry.semconv.ServiceAttributes;
import java.time.Duration;
import java.util.Map;
import java.util.Optional;
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
import org.whispersystems.textsecuregcm.WhisperServerVersion;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
@@ -65,7 +75,7 @@ public class MetricsUtil {
Duration shutdownWaitDuration = Duration.ZERO;
if (config.getDatadogConfiguration() != null && config.getDatadogConfiguration().enabled()) {
if (config.getDatadogConfiguration().enabled()) {
final StatsdMeterRegistry dogstatsdMeterRegistry = new StatsdMeterRegistry(
config.getDatadogConfiguration(), io.micrometer.core.instrument.Clock.SYSTEM);
@@ -76,12 +86,13 @@ public class MetricsUtil {
"env", config.getDatadogConfiguration().getEnvironment()));
configureMeterFilters(dogstatsdMeterRegistry.config(), dynamicConfigurationManager);
configureDatadogAllowList(dogstatsdMeterRegistry.config(), dynamicConfigurationManager);
Metrics.addRegistry(dogstatsdMeterRegistry);
shutdownWaitDuration = config.getDatadogConfiguration().getShutdownWaitDuration();
}
if (config.getOpenTelemetryConfiguration() != null && config.getOpenTelemetryConfiguration().enabled()) {
if (config.getOpenTelemetryConfiguration().enabled()) {
final OtlpMeterRegistry otlpMeterRegistry = new OtlpMeterRegistry(
config.getOpenTelemetryConfiguration(), io.micrometer.core.instrument.Clock.SYSTEM);
@@ -99,12 +110,53 @@ public class MetricsUtil {
environment.lifecycle().addEventListener(new ApplicationShutdownMonitor(Metrics.globalRegistry));
environment.lifecycle().addEventListener(
new MicrometerRegistryManager(Metrics.globalRegistry, shutdownWaitDuration));
registerSystemResourceMetrics();
}
public static void configureLogging(final WhisperServerConfiguration config, final Environment environment) {
if (!config.getOpenTelemetryConfiguration().enabled()) {
return;
}
final Map<String, String> env = System.getenv();
final String endpoint =
Optional.ofNullable(env.get("OTEL_EXPORTER_OTLP_LOGS_ENDPOINT"))
.or(() -> Optional.ofNullable(env.get("OTEL_EXPORTER_OTLP_ENDPOINT")))
.map(u -> u.endsWith("/v1/logs") ? u : u + "/v1/logs")
.orElse("http://localhost:4318/v1/logs");
final ResourceBuilder resource = Resource.builder();
config.getOpenTelemetryConfiguration().resourceAttributes().forEach((k, v) -> resource.put(k, v));
final OpenTelemetrySdk openTelemetry =
OpenTelemetrySdk.builder()
.setLoggerProvider(
SdkLoggerProvider.builder()
.setResource(resource.build())
.addLogRecordProcessor(
BatchLogRecordProcessor.builder(
OtlpHttpLogRecordExporter.builder()
.setEndpoint(endpoint)
.build()).build())
.build())
.build();
OpenTelemetryAppender.install(openTelemetry);
environment.lifecycle().manage(new Managed() {
@Override
public void stop() {
openTelemetry.shutdown();
}
});
}
@VisibleForTesting
static void configureMeterFilters(MeterRegistry.Config config,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
final DistributionStatisticConfig defaultDistributionStatisticConfig = DistributionStatisticConfig.builder()
.percentilesHistogram(true)
.percentiles(.75, .95, .99, .999)
.build();
@@ -137,7 +189,15 @@ public class MetricsUtil {
&& id.getName().startsWith(awsSdkMetricNamePrefix)));
}
public static void registerSystemResourceMetrics(final Environment environment) {
@VisibleForTesting
static void configureDatadogAllowList(
final MeterRegistry.Config config, final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
config.meterFilter(MeterFilter.denyUnless(id ->
dynamicConfigurationManager.getConfiguration().getMetricsConfiguration().datadogAllowList() == null ||
dynamicConfigurationManager.getConfiguration().getMetricsConfiguration().datadogAllowList().contains(id.getName())));
}
static void registerSystemResourceMetrics() {
new ProcessorMetrics().bindTo(Metrics.globalRegistry);
new FileDescriptorMetrics().bindTo(Metrics.globalRegistry);
@@ -0,0 +1,49 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.metrics;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import io.dropwizard.logging.common.AbstractAppenderFactory;
import io.dropwizard.logging.common.async.AsyncAppenderFactory;
import io.dropwizard.logging.common.filter.LevelFilterFactory;
import io.dropwizard.logging.common.layout.LayoutFactory;
import io.opentelemetry.instrumentation.logback.appender.v1_0.OpenTelemetryAppender;
@JsonTypeName("otlp")
public class OpenTelemetryAppenderFactory extends AbstractAppenderFactory<ILoggingEvent> {
@JsonProperty
private String destination;
@Override
public Appender<ILoggingEvent> build(
final LoggerContext context,
final String applicationName,
final LayoutFactory<ILoggingEvent> layoutFactory,
final LevelFilterFactory<ILoggingEvent> levelFilterFactory,
final AsyncAppenderFactory<ILoggingEvent> asyncAppenderFactory) {
final OpenTelemetryAppender appender = new OpenTelemetryAppender();
appender.setCaptureCodeAttributes(true);
appender.setCaptureLoggerContext(true);
// The installation of an OpenTelemetry configuration happens in
// WhisperServerService (or CommandDependencies), in order to let us tie
// into Dropwizard's lifecycle management; this allows us to buffer any
// logs emitted between now and that happening.
appender.setNumLogsCapturedBeforeOtelInstall(1000);
appender.addFilter(levelFilterFactory.build(threshold));
getFilterFactories().forEach(f -> appender.addFilter(f.build()));
appender.start();
return wrapAsync(appender, asyncAppenderFactory);
}
}
@@ -83,7 +83,7 @@ public class OpenWebSocketCounter {
Metrics.counter(newConnectionCounterName, tagsWithClientPlatform).increment();
context.addWebsocketClosedListener((context1, statusCode, reason) -> {
context.addWebsocketClosedListener((_, statusCode, _) -> {
sample.stop(Timer.builder(durationTimerName)
.publishPercentileHistogram(true)
.tags(tagsWithClientPlatform)
@@ -1,24 +0,0 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.providers;
import com.codahale.metrics.health.HealthCheck;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
public class RedisClusterHealthCheck extends HealthCheck {
private final FaultTolerantRedisClusterClient redisCluster;
public RedisClusterHealthCheck(final FaultTolerantRedisClusterClient redisCluster) {
this.redisCluster = redisCluster;
}
@Override
protected Result check() {
redisCluster.withCluster(connection -> connection.sync().upstream().commands().ping());
return Result.healthy();
}
}
@@ -29,5 +29,5 @@ public interface MessageAvailabilityListener {
* Indicates a newer instance of this client has started reading messages and the listener should close this client's
* underlying network connection.
*/
void handleConflictingMessageReader();
void handleConflictingMessageConsumer();
}
@@ -23,6 +23,7 @@ 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.ResilienceUtil;
public class ProvisioningManager extends RedisPubSubAdapter<byte[], byte[]> implements Managed {
@@ -40,6 +41,8 @@ public class ProvisioningManager extends RedisPubSubAdapter<byte[], byte[]> impl
private static final String RECEIVE_PROVISIONING_MESSAGE_COUNTER_NAME =
name(ProvisioningManager.class, "receiveProvisioningMessage");
private static final String RETRY_NAME = ResilienceUtil.name(ProvisioningManager.class);
private static final Logger logger = LoggerFactory.getLogger(ProvisioningManager.class);
public ProvisioningManager(final FaultTolerantRedisClient pubSubClient) {
@@ -77,8 +80,9 @@ public class ProvisioningManager extends RedisPubSubAdapter<byte[], byte[]> impl
.setContent(ByteString.copyFrom(body))
.build();
final boolean receiverPresent = pubSubClient.withBinaryConnection(connection ->
connection.sync().publish(address.getBytes(StandardCharsets.UTF_8), pubSubMessage.toByteArray()) > 0);
final boolean receiverPresent = ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
.executeSupplier(() -> 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();
@@ -23,6 +23,7 @@ import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiFunction;
@@ -34,6 +35,7 @@ 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.ResilienceUtil;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.RedisClusterUtil;
import org.whispersystems.textsecuregcm.util.Util;
@@ -51,6 +53,8 @@ public class PushNotificationScheduler implements Managed {
@VisibleForTesting
static final String NEXT_SLOT_TO_PROCESS_KEY = "pending_notification_next_slot";
private static final Duration EXCEPTION_PAUSE = Duration.ofSeconds(3);
private static final String BACKGROUND_NOTIFICATION_SCHEDULED_COUNTER_NAME = name(PushNotificationScheduler.class, "backgroundNotification", "scheduled");
private static final String BACKGROUND_NOTIFICATION_SENT_COUNTER_NAME = name(PushNotificationScheduler.class, "backgroundNotification", "sent");
@@ -63,6 +67,7 @@ public class PushNotificationScheduler implements Managed {
private final FcmSender fcmSender;
private final AccountsManager accountsManager;
private final FaultTolerantRedisClusterClient pushSchedulingCluster;
private final ScheduledExecutorService retryExecutor;
private final Clock clock;
private final ClusterLuaScript scheduleBackgroundNotificationScript;
@@ -74,12 +79,12 @@ public class PushNotificationScheduler implements Managed {
private final AtomicBoolean running = new AtomicBoolean(false);
private static final String RETRY_NAME = ResilienceUtil.name(PushNotificationScheduler.class);
class NotificationWorker implements Runnable {
private final int maxConcurrency;
private static final int PAGE_SIZE = 128;
NotificationWorker(final int maxConcurrency) {
this.maxConcurrency = maxConcurrency;
}
@@ -94,7 +99,12 @@ public class PushNotificationScheduler implements Managed {
Util.sleep(1000);
}
} catch (Exception e) {
logger.warn("Exception while operating", e);
logger.warn("Exception while processing scheduled notifications", e);
try {
Thread.sleep(EXCEPTION_PAUSE);
} catch (final InterruptedException _) {
}
}
} while (running.get());
}
@@ -149,7 +159,8 @@ public class PushNotificationScheduler implements Managed {
final FcmSender fcmSender,
final AccountsManager accountsManager,
final int dedicatedProcessWorkerThreadCount,
final int workerMaxConcurrency) throws IOException {
final int workerMaxConcurrency,
final ScheduledExecutorService retryExecutor) throws IOException {
this(pushSchedulingCluster,
apnSender,
@@ -157,17 +168,19 @@ public class PushNotificationScheduler implements Managed {
accountsManager,
Clock.systemUTC(),
dedicatedProcessWorkerThreadCount,
workerMaxConcurrency);
workerMaxConcurrency,
retryExecutor);
}
@VisibleForTesting
PushNotificationScheduler(final FaultTolerantRedisClusterClient pushSchedulingCluster,
final APNSender apnSender,
final FcmSender fcmSender,
final AccountsManager accountsManager,
final Clock clock,
final int dedicatedProcessThreadCount,
final int workerMaxConcurrency) throws IOException {
final APNSender apnSender,
final FcmSender fcmSender,
final AccountsManager accountsManager,
final Clock clock,
final int dedicatedProcessThreadCount,
final int workerMaxConcurrency,
final ScheduledExecutorService retryExecutor) throws IOException {
this.apnSender = apnSender;
this.fcmSender = fcmSender;
@@ -179,6 +192,7 @@ public class PushNotificationScheduler implements Managed {
"lua/apn/schedule_background_notification.lua", ScriptOutputType.VALUE);
this.workerThreads = new Thread[dedicatedProcessThreadCount];
this.retryExecutor = retryExecutor;
for (int i = 0; i < this.workerThreads.length; i++) {
this.workerThreads[i] = new Thread(new NotificationWorker(workerMaxConcurrency), "PushNotificationScheduler-" + i);
@@ -220,13 +234,16 @@ public class PushNotificationScheduler implements Managed {
* @return a future that completes once the notification has been scheduled
*/
public CompletableFuture<Void> scheduleDelayedNotification(final Account account, final Device device, final Duration minDelay) {
return pushSchedulingCluster.withCluster(connection ->
connection.async().zadd(getDelayedNotificationQueueKey(account, device),
clock.instant().plus(minDelay).toEpochMilli(),
encodeAciAndDeviceId(account, device)))
.thenRun(() -> Metrics.counter(DELAYED_NOTIFICATION_SCHEDULED_COUNTER_NAME,
TOKEN_TYPE_TAG, getTokenType(device))
.increment())
final long deliveryTime = clock.instant().plus(minDelay).toEpochMilli();
return ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
.executeCompletionStage(retryExecutor, () -> pushSchedulingCluster.withCluster(connection ->
connection.async().zadd(getDelayedNotificationQueueKey(account, device),
deliveryTime,
encodeAciAndDeviceId(account, device)))
.thenRun(() -> Metrics.counter(DELAYED_NOTIFICATION_SCHEDULED_COUNTER_NAME,
TOKEN_TYPE_TAG, getTokenType(device))
.increment()))
.toCompletableFuture();
}
@@ -33,7 +33,6 @@ import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubClusterConnection;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.util.RedisClusterUtil;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import org.whispersystems.textsecuregcm.util.Util;
@@ -56,8 +55,6 @@ import org.whispersystems.textsecuregcm.util.Util;
*/
public class RedisMessageAvailabilityManager extends RedisClusterPubSubAdapter<byte[], byte[]> implements Managed {
private final AccountsManager accountsManager;
private final PushNotificationManager pushNotificationManager;
private final FaultTolerantRedisClusterClient clusterClient;
private final Executor listenerEventExecutor;
@@ -100,14 +97,9 @@ public class RedisMessageAvailabilityManager extends RedisClusterPubSubAdapter<b
record AccountAndDeviceIdentifier(UUID accountIdentifier, byte deviceId) {
}
public RedisMessageAvailabilityManager(final AccountsManager accountsManager,
final PushNotificationManager pushNotificationManager,
final FaultTolerantRedisClusterClient clusterClient,
final Executor listenerEventExecutor,
final Executor asyncOperationQueueingExecutor) {
this.accountsManager = accountsManager;
this.pushNotificationManager = pushNotificationManager;
public RedisMessageAvailabilityManager(final FaultTolerantRedisClusterClient clusterClient,
final Executor listenerEventExecutor,
final Executor asyncOperationQueueingExecutor) {
this.clusterClient = clusterClient;
this.listenerEventExecutor = listenerEventExecutor;
@@ -140,7 +132,7 @@ public class RedisMessageAvailabilityManager extends RedisClusterPubSubAdapter<b
/**
* Marks the given device as "present" for message delivery and registers a listener for new messages and conflicting
* connections. If the given device already has a presence registered with this manager, that presence is displaced
* immediately and the listener's {@link MessageAvailabilityListener#handleConflictingMessageReader()} method is called.
* immediately and the listener's {@link MessageAvailabilityListener#handleConflictingMessageConsumer()} method is called.
*
* @param accountIdentifier the account identifier for the newly-connected device
* @param deviceId the ID of the newly-connected device within the given account
@@ -184,7 +176,7 @@ public class RedisMessageAvailabilityManager extends RedisClusterPubSubAdapter<b
});
if (displacedListener.get() != null) {
listenerEventExecutor.execute(() -> displacedListener.get().handleConflictingMessageReader());
listenerEventExecutor.execute(() -> displacedListener.get().handleConflictingMessageConsumer());
}
return subscribeFuture.get()
@@ -326,7 +318,7 @@ public class RedisMessageAvailabilityManager extends RedisClusterPubSubAdapter<b
// Only act on new connections to other event manager instances; we'll learn about displacements in THIS
// instance when we update the listener map in `handleClientConnected`
if (!this.serverId.equals(UUIDUtil.fromByteString(clientEvent.getClientConnected().getServerId()))) {
listenerEventExecutor.execute(listener::handleConflictingMessageReader);
listenerEventExecutor.execute(listener::handleConflictingMessageConsumer);
}
}
@@ -341,22 +333,6 @@ public class RedisMessageAvailabilityManager extends RedisClusterPubSubAdapter<b
if (clientEvent.getEventCase() == ClientEvent.EventCase.NEW_MESSAGE_AVAILABLE) {
MESSAGE_AVAILABLE_WITHOUT_LISTENER_COUNTER.increment();
// If we have an active subscription but no registered listener, it's likely that the publisher of this event
// believes that the receiving client was present when it really wasn't. Send a push notification as a
// just-in-case measure.
accountsManager.getByAccountIdentifierAsync(accountAndDeviceIdentifier.accountIdentifier())
.thenAccept(maybeAccount -> maybeAccount.ifPresent(account -> {
try {
pushNotificationManager.sendNewMessageNotification(account, accountAndDeviceIdentifier.deviceId(), true);
} catch (final NotPushRegisteredException ignored) {
}
}))
.whenComplete((ignored, throwable) -> {
if (throwable != null) {
logger.warn("Failed to send follow-up notification to {}:{}", accountAndDeviceIdentifier.accountIdentifier(), accountAndDeviceIdentifier.deviceId());
}
});
}
}
}
@@ -21,7 +21,6 @@ import java.util.concurrent.CompletableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public class ClusterLuaScript {
@@ -133,13 +132,7 @@ public class ClusterLuaScript {
final T[] keys, final T[] args) {
return connection.reactive().evalsha(sha, scriptOutputType, keys, args)
.onErrorResume(e -> {
if (e instanceof RedisNoScriptException) {
return connection.reactive().eval(script, scriptOutputType, keys, args);
}
log.warn("Failed to execute script", e);
return Mono.error(e);
});
.onErrorResume(RedisNoScriptException.class, _ -> connection.reactive().eval(script, scriptOutputType, keys, args))
.doOnError(throwable -> log.warn("Failed to execute script", throwable));
}
}
@@ -1,29 +1,23 @@
package org.whispersystems.textsecuregcm.redis;
import com.google.common.annotations.VisibleForTesting;
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;
import org.whispersystems.textsecuregcm.configuration.RedisConfiguration;
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
public class FaultTolerantRedisClient {
@@ -37,7 +31,6 @@ public class FaultTolerantRedisClient {
private final List<StatefulRedisPubSubConnection<?, ?>> pubSubConnections = new ArrayList<>();
private final CircuitBreaker circuitBreaker;
private final Retry retry;
public FaultTolerantRedisClient(final String name,
final RedisConfiguration redisConfiguration,
@@ -46,16 +39,21 @@ public class FaultTolerantRedisClient {
this(name, clientResourcesBuilder,
RedisUriUtil.createRedisUriWithTimeout(redisConfiguration.getUri(), redisConfiguration.getTimeout()),
redisConfiguration.getTimeout(),
redisConfiguration.getCircuitBreakerConfiguration(),
redisConfiguration.getRetryConfiguration());
redisConfiguration.getCircuitBreakerConfigurationName() != null
? ResilienceUtil.getCircuitBreakerRegistry().circuitBreaker(getCircuitBreakerName(name), redisConfiguration.getCircuitBreakerConfigurationName())
: ResilienceUtil.getCircuitBreakerRegistry().circuitBreaker(getCircuitBreakerName(name)));
}
private static String getCircuitBreakerName(final String name) {
return ResilienceUtil.name(FaultTolerantRedisClient.class, name);
}
@VisibleForTesting
FaultTolerantRedisClient(String name,
final ClientResources.Builder clientResourcesBuilder,
final RedisURI redisUri,
final Duration commandTimeout,
final CircuitBreakerConfiguration circuitBreakerConfiguration,
final RetryConfiguration retryConfiguration) {
final CircuitBreaker circuitBreaker) {
this.name = name;
@@ -70,32 +68,23 @@ public class FaultTolerantRedisClient {
redisUri.setLibraryName(null);
redisUri.setLibraryVersion(null);
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()
final ClientOptions.Builder clientOptionsBuilder = ClientOptions.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());
.publishOnScheduler(true);
lettuceShardCircuitBreaker.setEventBus(redisClient.getResources().eventBus());
NettyUtil.setSocketTimeoutsIfApplicable(clientOptionsBuilder);
this.redisClient.setOptions(clientOptionsBuilder.build());
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);
this.circuitBreaker = circuitBreaker;
}
public void shutdown() {
@@ -128,10 +117,10 @@ public class FaultTolerantRedisClient {
return withConnection(binaryConnection, function);
}
public <K, V> void useConnection(final StatefulRedisConnection<K, V> connection,
private <K, V> void useConnection(final StatefulRedisConnection<K, V> connection,
final Consumer<StatefulRedisConnection<K, V>> consumer) {
try {
circuitBreaker.executeRunnable(() -> retry.executeRunnable(() -> consumer.accept(connection)));
circuitBreaker.executeRunnable(() -> consumer.accept(connection));
} catch (final Throwable t) {
if (t instanceof RedisException) {
throw (RedisException) t;
@@ -141,10 +130,10 @@ public class FaultTolerantRedisClient {
}
}
public <T, K, V> T withConnection(final StatefulRedisConnection<K, V> connection,
private <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)));
return circuitBreaker.executeCallable(() -> function.apply(connection));
} catch (final Throwable t) {
if (t instanceof RedisException) {
throw (RedisException) t;
@@ -6,11 +6,9 @@
package org.whispersystems.textsecuregcm.redis;
import io.github.resilience4j.core.IntervalFunction;
import io.github.resilience4j.reactor.retry.RetryOperator;
import io.github.resilience4j.retry.Retry;
import io.github.resilience4j.retry.RetryConfig;
import io.lettuce.core.ClientOptions;
import io.lettuce.core.RedisCommandTimeoutException;
import io.lettuce.core.RedisException;
import io.lettuce.core.RedisURI;
import io.lettuce.core.TimeoutOptions;
@@ -28,13 +26,8 @@ import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import org.reactivestreams.Publisher;
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
import javax.annotation.Nullable;
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;
/**
@@ -53,25 +46,26 @@ public class FaultTolerantRedisClusterClient {
private final List<StatefulRedisClusterPubSubConnection<?, ?>> pubSubConnections = new ArrayList<>();
private final Retry retry;
private final Retry topologyChangedEventRetry;
public FaultTolerantRedisClusterClient(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(),
clusterConfiguration.getTimeout())),
clusterConfiguration.getTimeout(),
clusterConfiguration.getCircuitBreakerConfiguration(),
clusterConfiguration.getRetryConfiguration());
clusterConfiguration.getCircuitBreakerConfigurationName());
}
FaultTolerantRedisClusterClient(String name, final ClientResources.Builder clientResourcesBuilder,
Iterable<RedisURI> redisUris, Duration commandTimeout, CircuitBreakerConfiguration circuitBreakerConfig,
RetryConfiguration retryConfiguration) {
FaultTolerantRedisClusterClient(final String name,
final ClientResources.Builder clientResourcesBuilder,
final Iterable<RedisURI> redisUris,
final Duration commandTimeout,
@Nullable final String circuitBreakerConfigurationName) {
this.name = name;
@@ -88,13 +82,15 @@ public class FaultTolerantRedisClusterClient {
redisUri.setLibraryVersion(null);
});
final LettuceShardCircuitBreaker lettuceShardCircuitBreaker = new LettuceShardCircuitBreaker(name,
circuitBreakerConfig.toCircuitBreakerConfig(), Schedulers.newSingle("topology-changed-" + name, true));
final LettuceShardCircuitBreaker lettuceShardCircuitBreaker =
new LettuceShardCircuitBreaker(name, circuitBreakerConfigurationName);
this.clusterClient = RedisClusterClient.create(
clientResourcesBuilder.nettyCustomizer(lettuceShardCircuitBreaker).
build(),
redisUris);
this.clusterClient.setOptions(ClusterClientOptions.builder()
final ClusterClientOptions.Builder clusterClientOptionsBuilder = ClusterClientOptions.builder()
.disconnectedBehavior(ClientOptions.DisconnectedBehavior.REJECT_COMMANDS)
.validateClusterNodeMembership(false)
.topologyRefreshOptions(ClusterTopologyRefreshOptions.builder()
@@ -104,10 +100,11 @@ public class FaultTolerantRedisClusterClient {
.timeoutOptions(TimeoutOptions.builder()
.fixedTimeout(commandTimeout)
.build())
.publishOnScheduler(true)
.build());
.publishOnScheduler(true);
lettuceShardCircuitBreaker.setEventBus(clusterClient.getResources().eventBus());
NettyUtil.setSocketTimeoutsIfApplicable(clusterClientOptionsBuilder);
this.clusterClient.setOptions(clusterClientOptionsBuilder.build());
this.stringConnection = clusterClient.connect();
this.binaryConnection = clusterClient.connect(ByteArrayCodec.INSTANCE);
@@ -116,8 +113,6 @@ public class FaultTolerantRedisClusterClient {
clusterClient.getResources().eventBus().publish(
new ClusterTopologyChangedEvent(Collections.emptyList(), clusterClient.getPartitions().getPartitions()));
this.retry = Retry.of(name + "-retry", retryConfiguration.toRetryConfigBuilder()
.retryOnException(exception -> exception instanceof RedisCommandTimeoutException).build());
final RetryConfig topologyChangedEventRetryConfig = RetryConfig.custom()
.maxAttempts(Integer.MAX_VALUE)
.intervalFunction(
@@ -125,8 +120,6 @@ public class FaultTolerantRedisClusterClient {
.build();
this.topologyChangedEventRetry = Retry.of(name + "-topologyChangedRetry", topologyChangedEventRetryConfig);
CircuitBreakerUtil.registerMetrics(retry, FaultTolerantRedisClusterClient.class);
}
public void shutdown() {
@@ -160,15 +153,10 @@ public class FaultTolerantRedisClusterClient {
return withConnection(binaryConnection, function);
}
public <T> Publisher<T> withBinaryClusterReactive(
final Function<StatefulRedisClusterConnection<byte[], byte[]>, Publisher<T>> function) {
return withConnectionReactive(binaryConnection, function);
}
public <K, V> void useConnection(final StatefulRedisClusterConnection<K, V> connection,
private <K, V> void useConnection(final StatefulRedisClusterConnection<K, V> connection,
final Consumer<StatefulRedisClusterConnection<K, V>> consumer) {
try {
retry.executeRunnable(() -> consumer.accept(connection));
consumer.accept(connection);
} catch (final Throwable t) {
if (t instanceof RedisException) {
throw (RedisException) t;
@@ -178,10 +166,10 @@ public class FaultTolerantRedisClusterClient {
}
}
public <T, K, V> T withConnection(final StatefulRedisClusterConnection<K, V> connection,
private <T, K, V> T withConnection(final StatefulRedisClusterConnection<K, V> connection,
final Function<StatefulRedisClusterConnection<K, V>, T> function) {
try {
return retry.executeCallable(() -> function.apply(connection));
return function.apply(connection);
} catch (final Throwable t) {
if (t instanceof RedisException) {
throw (RedisException) t;
@@ -191,22 +179,6 @@ public class FaultTolerantRedisClusterClient {
}
}
public <T, K, V> Publisher<T> withConnectionReactive(
final StatefulRedisClusterConnection<K, V> connection,
final Function<StatefulRedisClusterConnection<K, V>, Publisher<T>> function) {
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 FaultTolerantPubSubClusterConnection<String, String> createPubSubConnection() {
final StatefulRedisClusterPubSubConnection<String, String> pubSubConnection = clusterClient.connectPubSub();
pubSubConnections.add(pubSubConnection);
@@ -8,16 +8,12 @@ package org.whispersystems.textsecuregcm.redis;
import com.google.common.annotations.VisibleForTesting;
import io.github.resilience4j.circuitbreaker.CallNotPermittedException;
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
import io.lettuce.core.RedisNoScriptException;
import io.lettuce.core.cluster.event.ClusterTopologyChangedEvent;
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
import io.lettuce.core.event.EventBus;
import io.lettuce.core.protocol.CommandHandler;
import io.lettuce.core.protocol.CompleteableCommand;
import io.lettuce.core.protocol.RedisCommand;
import io.lettuce.core.resource.NettyCustomizer;
import io.micrometer.core.instrument.Tags;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
@@ -25,17 +21,13 @@ import io.netty.channel.ChannelPromise;
import java.net.SocketAddress;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.util.CircuitBreakerUtil;
import reactor.core.scheduler.Scheduler;
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
/**
* Adds a circuit breaker to every Netty {@link Channel} that gets created, so that a single unhealthy shard does not
@@ -54,63 +46,18 @@ public class LettuceShardCircuitBreaker implements NettyCustomizer {
private static final Logger logger = LoggerFactory.getLogger(LettuceShardCircuitBreaker.class);
private final String clusterName;
private final CircuitBreakerConfig circuitBreakerConfig;
private final Scheduler scheduler;
// this set will be shared with all child channel breakers
private final Set<String> upstreamAddresses = ConcurrentHashMap.newKeySet();
// The EventBus is not available at construction time, because it is one of the client
// resources, which cannot be built without this NettyCustomizer
private EventBus eventBus;
@Nullable
private final String circuitBreakerConfigurationName;
public LettuceShardCircuitBreaker(final String clusterName, final CircuitBreakerConfig circuitBreakerConfig,
final Scheduler scheduler) {
public LettuceShardCircuitBreaker(final String clusterName, @Nullable final String circuitBreakerConfigurationName) {
this.clusterName = clusterName;
this.circuitBreakerConfig = circuitBreakerConfig;
this.scheduler = scheduler;
}
private static String toShardAddress(final RedisClusterNode redisClusterNode) {
return "%s:%s".formatted(redisClusterNode.getUri().getHost(), redisClusterNode.getUri().getPort());
}
void setEventBus(final EventBus eventBus) {
this.eventBus = eventBus;
eventBus.get()
.filter(e -> e instanceof ClusterTopologyChangedEvent)
.map(e -> (ClusterTopologyChangedEvent) e)
.subscribeOn(scheduler)
.subscribe(event -> {
final Set<String> currentUpstreams = event.after().stream()
.filter(node -> node.getRole().isUpstream())
.map(LettuceShardCircuitBreaker::toShardAddress)
.collect(Collectors.toSet());
final Set<String> previousUpstreams = event.before().stream()
.filter(node -> node.getRole().isUpstream())
.map(LettuceShardCircuitBreaker::toShardAddress)
.collect(Collectors.toSet());
if (previousUpstreams.removeAll(currentUpstreams)) {
logger.info("No longer upstream in cluster {}: {}", clusterName, StringUtils.join(previousUpstreams, ", "));
}
// Channels may be created at any time, not just immediately after the cluster client connect()s or when topology
// changes, so we maintain a set that can be queried by channel handlers during their connect() method.
upstreamAddresses.addAll(currentUpstreams);
upstreamAddresses.removeAll(previousUpstreams);
});
this.circuitBreakerConfigurationName = circuitBreakerConfigurationName;
}
@Override
public void afterChannelInitialized(final Channel channel) {
if (eventBus == null) {
throw new IllegalStateException("Event bus must be set before channel customization can occur");
}
final ChannelCircuitBreakerHandler channelCircuitBreakerHandler = new ChannelCircuitBreakerHandler(clusterName,
circuitBreakerConfig, upstreamAddresses, eventBus, scheduler);
final ChannelCircuitBreakerHandler channelCircuitBreakerHandler =
new ChannelCircuitBreakerHandler(clusterName, circuitBreakerConfigurationName);
final String commandHandlerName = StreamSupport.stream(channel.pipeline().spliterator(), false)
.filter(entry -> entry.getValue() instanceof CommandHandler)
@@ -125,51 +72,19 @@ public class LettuceShardCircuitBreaker implements NettyCustomizer {
private static final Logger logger = LoggerFactory.getLogger(ChannelCircuitBreakerHandler.class);
private static final String CLUSTER_TAG_NAME = "cluster";
private static final String SHARD_ADDRESS_TAG_NAME = "shard";
private final String clusterName;
private final CircuitBreakerConfig circuitBreakerConfig;
private final AtomicBoolean registeredMetrics = new AtomicBoolean(false);
private final Set<String> upstreamAddresses;
@Nullable private final String circuitBreakerConfigurationName;
private String shardAddress;
@VisibleForTesting
CircuitBreaker breaker;
public ChannelCircuitBreakerHandler(final String name, final CircuitBreakerConfig circuitBreakerConfig,
final Set<String> upstreamAddresses,
final EventBus eventBus, final Scheduler scheduler) {
public ChannelCircuitBreakerHandler(final String name, @Nullable final String circuitBreakerConfigurationName) {
this.clusterName = name;
this.circuitBreakerConfig = circuitBreakerConfig;
this.upstreamAddresses = upstreamAddresses;
eventBus.get()
.filter(e -> e instanceof ClusterTopologyChangedEvent)
.map(e -> (ClusterTopologyChangedEvent) e)
.subscribeOn(scheduler)
.subscribe(event -> {
if (shardAddress == null) {
logger.warn("Received a topology changed event without a shard address");
return;
}
final Set<String> newUpstreams = event.after().stream().filter(node -> node.getRole().isUpstream())
.map(LettuceShardCircuitBreaker::toShardAddress)
.collect(Collectors.toSet());
if (newUpstreams.contains(shardAddress)) {
registerMetrics();
}
});
}
void registerMetrics() {
// Registering metrics is not idempotent--some counters are added as event listeners,
// and there would be duplicated calls to increment()
if (registeredMetrics.compareAndSet(false, true)) {
logger.info("Registered metrics for: {}/{}", clusterName, shardAddress);
CircuitBreakerUtil.registerMetrics(breaker, getClass(), Tags.of(CLUSTER_TAG_NAME, clusterName));
}
this.circuitBreakerConfigurationName = circuitBreakerConfigurationName;
}
@Override
@@ -183,11 +98,17 @@ public class LettuceShardCircuitBreaker implements NettyCustomizer {
// In some cases, like the default connection, the remote address includes the DNS hostname, which we want to exclude.
shardAddress = StringUtils.substringAfter(remoteAddress.toString(), "/");
breaker = CircuitBreaker.of("%s/%s-breaker".formatted(clusterName, shardAddress), circuitBreakerConfig);
if (upstreamAddresses.contains(shardAddress)) {
registerMetrics();
}
final String circuitBreakerName =
ResilienceUtil.name(LettuceShardCircuitBreaker.class, "%s/%s".formatted(clusterName, shardAddress));
final Map<String, String> tags = Map.of(
CLUSTER_TAG_NAME, clusterName,
SHARD_ADDRESS_TAG_NAME, shardAddress);
breaker = circuitBreakerConfigurationName != null
? ResilienceUtil.getCircuitBreakerRegistry().circuitBreaker(circuitBreakerName, circuitBreakerConfigurationName, tags)
: ResilienceUtil.getCircuitBreakerRegistry().circuitBreaker(circuitBreakerName, tags);
}
@Override
@@ -0,0 +1,34 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.redis;
import io.lettuce.core.ClientOptions;
import io.lettuce.core.SocketOptions;
import io.lettuce.core.resource.EpollProvider;
import java.time.Duration;
public class NettyUtil {
static final Duration TCP_KEEPALIVE_IDLE = Duration.ofSeconds(30);
static final Duration TCP_KEEPALIVE_INTERVAL = Duration.ofSeconds(30);
static final Duration TCP_USER_TIMEOUT = Duration.ofSeconds(30);
static void setSocketTimeoutsIfApplicable(final ClientOptions.Builder clientOptionsBuilder) {
if (EpollProvider.isAvailable()) {
// These socket options are only available with epoll native transport.
clientOptionsBuilder.socketOptions(SocketOptions.builder()
.keepAlive(SocketOptions.KeepAliveOptions.builder()
.interval(TCP_KEEPALIVE_INTERVAL)
.idle(TCP_KEEPALIVE_IDLE)
.enable()
.build())
.tcpUserTimeout(SocketOptions.TcpUserTimeoutOptions.builder()
.enable()
.tcpUserTimeout(TCP_USER_TIMEOUT)
.build())
.build());
}
}
}
@@ -9,7 +9,6 @@ import java.time.Clock;
import java.time.Instant;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.zone.ZoneRules;
import java.util.Comparator;
@@ -19,19 +18,21 @@ import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import io.micrometer.core.instrument.Metrics;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.storage.Account;
public class SchedulingUtil {
private static final String PARSED_TIMEZONE_COUNTER_NAME = MetricsUtil.name(SchedulingUtil.class, "parsedTimezone");
private static final String HAS_TIMEZONE_TAG_NAME = "hasTimezone";
/**
* Gets a present or future time at which to send a notification to a device associated with the given account. This
* is mainly intended to facilitate scheduling notifications such that they arrive during a recipient's waking hours.
* <p/>
* This method will attempt to use a timezone derived from the account's phone number to choose an appropriate time
* to send a notification. If a timezone cannot be derived from the account's phone number, then this method will use
* the account's creation time as a hint. As an example, if the account was created at 07:17 in the server's local
* time, we can assume that the account holder was awake at that time of day, and it's likely a safe time to send a
* notification in the absence of other hints.
* to send a notification. If a timezone cannot be derived from the account's phone number, then this method will
* default to the preferred time in the server's timezone.
*
* @param account the account that will receive the notification
* @param preferredTime the preferred local time (e.g. "noon") at which to deliver the notification
@@ -44,14 +45,13 @@ public class SchedulingUtil {
final Clock clock) {
final ZonedDateTime candidateNotificationTime = getZoneId(account, clock)
.map(zoneId -> ZonedDateTime.now(clock.withZone(zoneId)).with(preferredTime))
.map(zoneId -> {
Metrics.counter(PARSED_TIMEZONE_COUNTER_NAME, HAS_TIMEZONE_TAG_NAME, String.valueOf(true)).increment();
return ZonedDateTime.now(clock.withZone(zoneId)).with(preferredTime);
})
.orElseGet(() -> {
// We couldn't find a reasonable timezone for the account for some reason, so make an educated guess at a
// reasonable time to send a notification based on the account's creation time.
final Instant accountCreation = Instant.ofEpochMilli(account.getPrimaryDevice().getCreated());
final LocalTime accountCreationLocalTime = LocalTime.ofInstant(accountCreation, ZoneId.systemDefault());
return ZonedDateTime.now(ZoneId.systemDefault()).with(accountCreationLocalTime);
Metrics.counter(PARSED_TIMEZONE_COUNTER_NAME, HAS_TIMEZONE_TAG_NAME, String.valueOf(false)).increment();
return ZonedDateTime.now(ZoneId.systemDefault()).with(preferredTime);
});
if (candidateNotificationTime.toInstant().isBefore(clock.instant())) {
@@ -43,15 +43,12 @@ public class SecureStorageClient {
throws CertificateException {
this.storageServiceCredentialsGenerator = storageServiceCredentialsGenerator;
this.deleteUri = URI.create(configuration.uri()).resolve(DELETE_PATH);
this.httpClient = FaultTolerantHttpClient.newBuilder()
.withCircuitBreaker(configuration.circuitBreaker())
.withRetry(configuration.retry())
.withRetryExecutor(retryExecutor)
this.httpClient = FaultTolerantHttpClient.newBuilder("secure-storage", executor)
.withCircuitBreaker(configuration.circuitBreakerConfigurationName())
.withRetry(configuration.retryConfigurationName(), retryExecutor)
.withVersion(HttpClient.Version.HTTP_1_1)
.withConnectTimeout(Duration.ofSeconds(10))
.withRedirect(HttpClient.Redirect.NEVER)
.withExecutor(executor)
.withName("secure-storage")
.withSecurityProtocol(FaultTolerantHttpClient.SECURITY_PROTOCOL_TLS_1_3)
.withTrustedServerCertificates(configuration.storageCaCertificates().toArray(new String[0]))
.build();
@@ -30,9 +30,10 @@ import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
import org.whispersystems.textsecuregcm.util.HttpUtils;
/**
* A client for sending requests to Signal's secure value recovery v2 service on behalf of authenticated users.
* A client for sending requests to Signal's secure value recovery service on behalf of authenticated users.
*/
public class SecureValueRecoveryClient {
private static final Logger logger = LoggerFactory.getLogger(SecureValueRecoveryClient.class);
private final ExternalServiceCredentialsGenerator secureValueRecoveryCredentialsGenerator;
@@ -52,23 +53,24 @@ public class SecureValueRecoveryClient {
this.secureValueRecoveryCredentialsGenerator = secureValueRecoveryCredentialsGenerator;
this.deleteUri = URI.create(configuration.uri()).resolve(DELETE_PATH);
this.allowedDeletionErrorStatusCodes = allowedDeletionErrorStatusCodes;
this.httpClient = FaultTolerantHttpClient.newBuilder()
.withCircuitBreaker(configuration.circuitBreaker())
.withRetry(configuration.retry())
.withRetryExecutor(retryExecutor)
this.httpClient = FaultTolerantHttpClient.newBuilder("secure-value-recovery", executor)
.withCircuitBreaker(configuration.circuitBreakerConfigurationName())
.withRetry(configuration.retryConfigurationName(), retryExecutor)
.withVersion(HttpClient.Version.HTTP_1_1)
.withConnectTimeout(Duration.ofSeconds(10))
.withRedirect(HttpClient.Redirect.NEVER)
.withExecutor(executor)
.withName("secure-value-recovery")
.withSecurityProtocol(FaultTolerantHttpClient.SECURITY_PROTOCOL_TLS_1_2)
.withTrustedServerCertificates(configuration.svrCaCertificates().toArray(new String[0]))
.build();
}
public CompletableFuture<Void> removeData(final UUID accountUuid) {
return removeData(accountUuid.toString());
}
final ExternalServiceCredentials credentials = secureValueRecoveryCredentialsGenerator.generateForUuid(accountUuid);
public CompletableFuture<Void> removeData(final String userIdentifier) {
final ExternalServiceCredentials credentials = secureValueRecoveryCredentialsGenerator.generateFor(userIdentifier);
final HttpRequest request = HttpRequest.newBuilder()
.uri(deleteUri)
@@ -83,11 +85,11 @@ public class SecureValueRecoveryClient {
final List<Integer> allowedErrors = allowedDeletionErrorStatusCodes.get();
if (allowedErrors.contains(response.statusCode())) {
logger.warn("Ignoring failure to delete svr entry for account {} with status {}",
accountUuid, response.statusCode());
logger.warn("Ignoring failure to delete svr entry for identifier {} with status {}",
userIdentifier, response.statusCode());
return null;
}
logger.warn("Failed to delete svr entry for account {} with status {}", accountUuid, response.statusCode());
logger.warn("Failed to delete svr entry for identifier {} with status {}", userIdentifier, response.statusCode());
throw new SecureValueRecoveryException("Failed to delete backup", String.valueOf(response.statusCode()));
});
}
@@ -271,6 +271,7 @@ public class Account {
case PRIMARY_DEVICE -> getPrimaryDevice().hasCapability(capability);
case ANY_DEVICE -> devices.stream().anyMatch(device -> device.hasCapability(capability));
case ALL_DEVICES -> devices.stream().allMatch(device -> device.hasCapability(capability));
case ALWAYS_CAPABLE -> true;
};
}
@@ -322,6 +322,9 @@ public class Accounts {
existingAccount.getBackupCredentialRequest(BackupCredentialType.MESSAGES).orElse(null),
existingAccount.getBackupCredentialRequest(BackupCredentialType.MEDIA).orElse(null));
// Carry over the existing backup voucher to the new account
accountToCreate.setBackupVoucher(existingAccount.getBackupVoucher());
final List<TransactWriteItem> writeItems = new ArrayList<>();
// If we're reclaiming an account that already has a username, we'd like to give the re-registering client
@@ -13,6 +13,7 @@ import com.fasterxml.jackson.databind.ObjectWriter;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import io.dropwizard.lifecycle.Managed;
import io.lettuce.core.RedisCommandTimeoutException;
import io.lettuce.core.RedisException;
import io.lettuce.core.SetArgs;
import io.lettuce.core.cluster.api.sync.RedisAdvancedClusterCommands;
@@ -50,6 +51,7 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
@@ -85,6 +87,8 @@ import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.RegistrationIdValidator;
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Flux;
@@ -111,6 +115,12 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
private static final String DELETE_COUNTER_NAME = name(AccountsManager.class, "deleteCounter");
private static final String COUNTRY_CODE_TAG_NAME = "country";
private static final String DELETION_REASON_TAG_NAME = "reason";
private static final String TIMESTAMP_BASED_TRANSFER_ARCHIVE_KEY_COUNTER_NAME = name(AccountsManager.class, "timestampRedisKeyCounter");
private static final String REGISTRATION_ID_BASED_TRANSFER_ARCHIVE_KEY_COUNTER_NAME = name(AccountsManager.class,"registrationIdRedisKeyCounter");
private static final String RETRY_NAME = ResilienceUtil.name(AccountsManager.class);
private static final Duration SUBSCRIBE_RETRY_DELAY = Duration.ofSeconds(5);
private static final Logger logger = LoggerFactory.getLogger(AccountsManager.class);
@@ -124,12 +134,12 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
private final ProfilesManager profilesManager;
private final SecureStorageClient secureStorageClient;
private final SecureValueRecoveryClient secureValueRecovery2Client;
private final SecureValueRecoveryClient secureValueRecoveryBClient;
private final DisconnectionRequestManager disconnectionRequestManager;
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
private final ClientPublicKeysManager clientPublicKeysManager;
private final Executor accountLockExecutor;
private final ScheduledExecutorService messagesPollExecutor;
private final ScheduledExecutorService retryExecutor;
private final Clock clock;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
@@ -140,7 +150,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
private final Map<String, CompletableFuture<Optional<DeviceInfo>>> waitForDeviceFuturesByTokenIdentifier =
new ConcurrentHashMap<>();
private final Map<TimestampedDeviceIdentifier, CompletableFuture<Optional<TransferArchiveResult>>> waitForTransferArchiveFuturesByDeviceIdentifier =
private final Map<DeviceIdentifier, CompletableFuture<Optional<TransferArchiveResult>>> waitForTransferArchiveFuturesByDeviceIdentifier =
new ConcurrentHashMap<>();
private final Map<String, CompletableFuture<Optional<RestoreAccountRequest>>> waitForRestoreAccountRequestFuturesByToken =
@@ -155,6 +165,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
private static final Duration RECENTLY_ADDED_TRANSFER_ARCHIVE_TTL = Duration.ofHours(1);
private static final String TRANSFER_ARCHIVE_PREFIX = "transfer_archive::";
private static final String TRANSFER_ARCHIVE_KEYSPACE_PATTERN = "__keyspace@0__:" + TRANSFER_ARCHIVE_PREFIX + "*";
private static final String TRANSFER_ARCHIVE_REGISTRATION_ID_PATTERN = "registrationId";
private static final Duration RESTORE_ACCOUNT_REQUEST_TTL = Duration.ofHours(1);
private static final String RESTORE_ACCOUNT_REQUEST_PREFIX = "restore_account::";
@@ -194,7 +205,14 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
}
private record TimestampedDeviceIdentifier(UUID accountIdentifier, byte deviceId, Instant deviceCreationTimestamp) {
private interface DeviceIdentifier {}
private record TimestampDeviceIdentifier(UUID accountIdentifier, byte deviceId, Instant deviceCreationTimestamp)
implements DeviceIdentifier {
}
private record RegistrationIdDeviceIdentifier(UUID accountIdentifier, byte deviceId,
int registrationId) implements DeviceIdentifier {
}
public AccountsManager(final Accounts accounts,
@@ -207,12 +225,11 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final ProfilesManager profilesManager,
final SecureStorageClient secureStorageClient,
final SecureValueRecoveryClient secureValueRecovery2Client,
final SecureValueRecoveryClient secureValueRecoveryBClient,
final DisconnectionRequestManager disconnectionRequestManager,
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
final ClientPublicKeysManager clientPublicKeysManager,
final Executor accountLockExecutor,
final ScheduledExecutorService messagesPollExecutor,
final ScheduledExecutorService messagesPollExecutor, final ScheduledExecutorService retryExecutor,
final Clock clock,
final byte[] linkDeviceSecret,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
@@ -226,12 +243,12 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
this.profilesManager = profilesManager;
this.secureStorageClient = secureStorageClient;
this.secureValueRecovery2Client = secureValueRecovery2Client;
this.secureValueRecoveryBClient = secureValueRecoveryBClient;
this.disconnectionRequestManager = disconnectionRequestManager;
this.registrationRecoveryPasswordsManager = requireNonNull(registrationRecoveryPasswordsManager);
this.clientPublicKeysManager = clientPublicKeysManager;
this.accountLockExecutor = accountLockExecutor;
this.messagesPollExecutor = messagesPollExecutor;
this.retryExecutor = retryExecutor;
this.clock = requireNonNull(clock);
this.dynamicConfigurationManager = dynamicConfigurationManager;
@@ -251,8 +268,27 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
public void start() {
pubSubConnection.usePubSubConnection(connection -> {
connection.addListener(this);
connection.sync().psubscribe(LINKED_DEVICE_KEYSPACE_PATTERN, TRANSFER_ARCHIVE_KEYSPACE_PATTERN,
RESTORE_ACCOUNT_REQUEST_KEYSPACE_PATTERN);
boolean subscribed = false;
// Loop indefinitely until we establish a subscription. We don't want to fail immediately if there's a temporary
// Redis connectivity issue, since that would derail the whole startup process and likely lead to unnecessary pod
// churn, which might make things worse. If we never establish a connection, readiness probes will eventually fail
// and terminate the pods.
do {
try {
connection.sync().psubscribe(LINKED_DEVICE_KEYSPACE_PATTERN, TRANSFER_ARCHIVE_KEYSPACE_PATTERN,
RESTORE_ACCOUNT_REQUEST_KEYSPACE_PATTERN);
subscribed = true;
} catch (final RedisCommandTimeoutException e) {
try {
Thread.sleep(SUBSCRIBE_RETRY_DELAY);
} catch (final InterruptedException ex) {
throw new RuntimeException(ex);
}
}
} while (!subscribed);
});
}
@@ -475,7 +511,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
return CompletableFuture.failedFuture(throwable);
})
.whenComplete((updatedAccountAndDevice, throwable) -> {
.whenComplete((updatedAccountAndDevice, _) -> {
if (updatedAccountAndDevice != null) {
final String key = getLinkedDeviceKey(getLinkDeviceTokenIdentifier(linkDeviceToken));
final String deviceInfoJson;
@@ -486,9 +522,10 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
throw new UncheckedIOException(e);
}
pubSubRedisClient.withConnection(connection ->
connection.async().set(key, deviceInfoJson, SetArgs.Builder.ex(RECENTLY_ADDED_DEVICE_TTL)))
.whenComplete((ignored, pubSubThrowable) -> {
ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
.executeCompletionStage(retryExecutor, () -> pubSubRedisClient.withConnection(connection ->
connection.async().set(key, deviceInfoJson, SetArgs.Builder.ex(RECENTLY_ADDED_DEVICE_TTL))))
.whenComplete((_, pubSubThrowable) -> {
if (pubSubThrowable != null) {
logger.warn("Failed to record recently-created device", pubSubThrowable);
}
@@ -1220,7 +1257,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
return CompletableFuture.allOf(
secureStorageClient.deleteStoredData(account.getUuid()),
secureValueRecovery2Client.removeData(account.getUuid()),
secureValueRecoveryBClient.removeData(account.getUuid()),
keysManager.deleteSingleUsePreKeys(account.getUuid()),
keysManager.deleteSingleUsePreKeys(account.getPhoneNumberIdentifier()),
messagesManager.clear(account.getUuid()),
@@ -1391,10 +1427,11 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
private void redisDelete(final Account account) {
redisDeleteTimer.record(() ->
cacheCluster.useCluster(connection ->
connection.sync().del(getAccountMapKey(account.getPhoneNumberIdentifier().toString()),
getAccountEntityKey(account.getUuid()))));
ResilienceUtil.getGeneralRedisRetry(RETRY_NAME).executeRunnable(() ->
redisDeleteTimer.record(() ->
cacheCluster.useCluster(connection ->
connection.sync().del(getAccountMapKey(account.getPhoneNumberIdentifier().toString()),
getAccountEntityKey(account.getUuid())))));
}
private CompletableFuture<Void> redisDeleteAsync(final Account account) {
@@ -1405,10 +1442,11 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
getAccountEntityKey(account.getUuid())
};
return cacheCluster.withCluster(connection -> connection.async().del(keysToDelete))
return ResilienceUtil.getGeneralRedisRetry(RETRY_NAME).executeCompletionStage(retryExecutor,
() -> cacheCluster.withCluster(connection -> connection.async().del(keysToDelete))
.thenRun(Util.NOOP))
.toCompletableFuture()
.whenComplete((ignoredResult, ignoredException) -> sample.stop(redisDeleteTimer))
.thenRun(Util.NOOP);
.whenComplete((_, _) -> sample.stop(redisDeleteTimer));
}
public CompletableFuture<Optional<DeviceInfo>> waitForNewLinkedDevice(
@@ -1509,32 +1547,64 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
public CompletableFuture<Optional<TransferArchiveResult>> waitForTransferArchive(final Account account, final Device device, final Duration timeout) {
final TimestampedDeviceIdentifier deviceIdentifier =
new TimestampedDeviceIdentifier(account.getIdentifier(IdentityType.ACI),
device.getId(),
Instant.ofEpochMilli(device.getCreated()));
final DeviceIdentifier timestampDeviceIdentifier = new TimestampDeviceIdentifier(account.getIdentifier(IdentityType.ACI), device.getId(), Instant.ofEpochMilli(device.getCreated()));
final String timestampTransferArchiveKey = getTimestampTransferArchiveKey(account.getIdentifier(IdentityType.ACI), device.getId(), Instant.ofEpochMilli(device.getCreated()));
return waitForPubSubKey(waitForTransferArchiveFuturesByDeviceIdentifier,
deviceIdentifier,
getTransferArchiveKey(account.getIdentifier(IdentityType.ACI), device.getId(), Instant.ofEpochMilli(device.getCreated())),
final DeviceIdentifier registrationIdDeviceIdentifier = new RegistrationIdDeviceIdentifier(account.getIdentifier(IdentityType.ACI), device.getId(), device.getRegistrationId(IdentityType.ACI));
final String registrationIdTransferArchiveKey = getRegistrationIdTransferArchiveKey(account.getIdentifier(IdentityType.ACI), device.getId(), device.getRegistrationId(IdentityType.ACI));
final CompletableFuture<Optional<TransferArchiveResult>> timestampFuture = waitForPubSubKey(waitForTransferArchiveFuturesByDeviceIdentifier,
timestampDeviceIdentifier,
timestampTransferArchiveKey,
timeout,
this::handleTransferArchiveAdded);
final CompletableFuture<Optional<TransferArchiveResult>> registrationIdFuture = waitForPubSubKey(waitForTransferArchiveFuturesByDeviceIdentifier,
registrationIdDeviceIdentifier,
registrationIdTransferArchiveKey,
timeout,
this::handleTransferArchiveAdded);
return firstSuccessfulTransferArchiveFuture(List.of(timestampFuture, registrationIdFuture));
}
@VisibleForTesting
static CompletableFuture<Optional<TransferArchiveResult>> firstSuccessfulTransferArchiveFuture(
final List<CompletableFuture<Optional<TransferArchiveResult>>> futures) {
final CompletableFuture<Optional<TransferArchiveResult>> result = new CompletableFuture<>();
final AtomicInteger remaining = new AtomicInteger(futures.size());
for (CompletableFuture<Optional<TransferArchiveResult>> future : futures) {
future.whenComplete((value, _) -> {
if (value.isPresent()) {
result.complete(value);
} else if (remaining.decrementAndGet() == 0) {
result.complete(Optional.empty());
}
});
}
return result;
}
public CompletableFuture<Void> recordTransferArchiveUpload(final Account account,
final byte destinationDeviceId,
final Instant destinationDeviceCreationTimestamp,
@SuppressWarnings("OptionalUsedAsFieldOrParameterType") final Optional<Instant> destinationDeviceCreationTimestamp,
@SuppressWarnings("OptionalUsedAsFieldOrParameterType") final Optional<Integer> maybeRegistrationId,
final TransferArchiveResult transferArchiveResult) {
final String key = getTransferArchiveKey(account.getIdentifier(IdentityType.ACI),
destinationDeviceId,
destinationDeviceCreationTimestamp);
try {
final String transferArchiveJson = SystemMapper.jsonMapper().writeValueAsString(transferArchiveResult);
return pubSubRedisClient.withConnection(connection ->
connection.async().set(key, transferArchiveJson, SetArgs.Builder.ex(RECENTLY_ADDED_TRANSFER_ARCHIVE_TTL)))
final String key = destinationDeviceCreationTimestamp
.map(timestamp -> getTimestampTransferArchiveKey(account.getIdentifier(IdentityType.ACI), destinationDeviceId, timestamp))
.orElseGet(() -> maybeRegistrationId
.map(registrationId -> getRegistrationIdTransferArchiveKey(account.getIdentifier(IdentityType.ACI), destinationDeviceId, registrationId))
// We validate the request object so this should never happen
.orElseThrow(() -> new AssertionError("No creation timestamp or registration ID provided")));
return ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
.executeCompletionStage(retryExecutor, () -> pubSubRedisClient.withConnection(connection -> connection.async()
.set(key, transferArchiveJson, SetArgs.Builder.ex(RECENTLY_ADDED_TRANSFER_ARCHIVE_TTL)))
.toCompletableFuture())
.thenRun(Util.NOOP)
.toCompletableFuture();
} catch (final JsonProcessingException e) {
@@ -1552,15 +1622,27 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
}
private static String getTransferArchiveKey(final UUID accountIdentifier,
private static String getTimestampTransferArchiveKey(final UUID accountIdentifier,
final byte destinationDeviceId,
final Instant destinationDeviceCreationTimestamp) {
Metrics.counter(TIMESTAMP_BASED_TRANSFER_ARCHIVE_KEY_COUNTER_NAME).increment();
return TRANSFER_ARCHIVE_PREFIX + accountIdentifier.toString() +
":" + destinationDeviceId +
":" + destinationDeviceCreationTimestamp.toEpochMilli();
}
private static String getRegistrationIdTransferArchiveKey(final UUID accountIdentifier,
final byte destinationDeviceId,
final int registrationId) {
Metrics.counter(REGISTRATION_ID_BASED_TRANSFER_ARCHIVE_KEY_COUNTER_NAME).increment();
return TRANSFER_ARCHIVE_PREFIX + accountIdentifier.toString() +
":" + destinationDeviceId +
":" + TRANSFER_ARCHIVE_REGISTRATION_ID_PATTERN +
":" + registrationId;
}
public CompletableFuture<Optional<RestoreAccountRequest>> waitForRestoreAccountRequest(final String token, final Duration timeout) {
return waitForPubSubKey(waitForRestoreAccountRequestFuturesByToken,
token,
@@ -1580,8 +1662,10 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
throw new UncheckedIOException(e);
}
return pubSubRedisClient.withConnection(connection ->
connection.async().set(key, requestJson, SetArgs.Builder.ex(RESTORE_ACCOUNT_REQUEST_TTL)))
return ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
.executeCompletionStage(retryExecutor, () -> pubSubRedisClient.withConnection(connection ->
connection.async().set(key, requestJson, SetArgs.Builder.ex(RESTORE_ACCOUNT_REQUEST_TTL)))
.toCompletableFuture())
.thenRun(Util.NOOP)
.toCompletableFuture();
}
@@ -1648,23 +1732,36 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
} else if (TRANSFER_ARCHIVE_KEYSPACE_PATTERN.equals(pattern) && "set".equalsIgnoreCase(message)) {
// The `- 1` here compensates for the '*' in the pattern
final String[] deviceIdentifierComponents =
channel.substring(TRANSFER_ARCHIVE_KEYSPACE_PATTERN.length() - 1).split(":", 3);
channel.substring(TRANSFER_ARCHIVE_KEYSPACE_PATTERN.length() - 1).split(":", 4);
if (deviceIdentifierComponents.length != 3) {
logger.error("Could not parse timestamped device identifier; unexpected component count");
if (deviceIdentifierComponents.length != 3 && deviceIdentifierComponents.length != 4) {
logger.error("Could not parse device identifier; unexpected component count");
return;
}
final DeviceIdentifier deviceIdentifier;
final String transferArchiveKey;
try {
final TimestampedDeviceIdentifier deviceIdentifier;
final String transferArchiveKey;
{
final UUID accountIdentifier = UUID.fromString(deviceIdentifierComponents[0]);
final byte deviceId = Byte.parseByte(deviceIdentifierComponents[1]);
final UUID accountIdentifier = UUID.fromString(deviceIdentifierComponents[0]);
final byte deviceId = Byte.parseByte(deviceIdentifierComponents[1]);
if (deviceIdentifierComponents.length == 3) {
// Parse the old transfer archive Redis key format
final Instant deviceCreationTimestamp = Instant.ofEpochMilli(Long.parseLong(deviceIdentifierComponents[2]));
deviceIdentifier = new TimestampedDeviceIdentifier(accountIdentifier, deviceId, deviceCreationTimestamp);
transferArchiveKey = getTransferArchiveKey(accountIdentifier, deviceId, deviceCreationTimestamp);
deviceIdentifier = new TimestampDeviceIdentifier(accountIdentifier, deviceId, deviceCreationTimestamp);
transferArchiveKey = getTimestampTransferArchiveKey(accountIdentifier, deviceId, deviceCreationTimestamp);
} else {
final String maybeRegistrationIdPattern = deviceIdentifierComponents[2];
if (!maybeRegistrationIdPattern.equals(TRANSFER_ARCHIVE_REGISTRATION_ID_PATTERN)) {
throw new IllegalArgumentException("Could not parse Redis key with pattern " + maybeRegistrationIdPattern);
}
final int registrationId = Integer.parseInt(deviceIdentifierComponents[3]);
if (!RegistrationIdValidator.validRegistrationId(registrationId)) {
throw new IllegalArgumentException("Invalid registration ID: " + registrationId);
}
deviceIdentifier = new RegistrationIdDeviceIdentifier(accountIdentifier, deviceId, registrationId);
transferArchiveKey = getRegistrationIdTransferArchiveKey(accountIdentifier, deviceId, registrationId);
}
Optional.ofNullable(waitForTransferArchiveFuturesByDeviceIdentifier.remove(deviceIdentifier))
@@ -1677,7 +1774,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
}));
} catch (final IllegalArgumentException e) {
logger.error("Could not parse timestamped device identifier", e);
logger.error("Could not parse device identifier", e);
}
} else if (RESTORE_ACCOUNT_REQUEST_KEYSPACE_PATTERN.equalsIgnoreCase(pattern) && "set".equalsIgnoreCase(message)) {
// The `- 1` here compensates for the '*' in the pattern
@@ -0,0 +1,12 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
/// Indicates that more than one consumer is trying to read a specific message queue at the same time.
public class ConflictingMessageConsumerException extends NoStackTraceException {
}
@@ -10,10 +10,12 @@ import java.util.Optional;
public enum DeviceCapability {
STORAGE("storage", AccountCapabilityMode.ANY_DEVICE, false, false),
TRANSFER("transfer", AccountCapabilityMode.PRIMARY_DEVICE, false, false),
DELETE_SYNC("deleteSync", AccountCapabilityMode.ALL_DEVICES, true, true),
STORAGE_SERVICE_RECORD_KEY_ROTATION("ssre2", AccountCapabilityMode.ALL_DEVICES, true, true),
@Deprecated(forRemoval = true) // Can be removed sometime after 11/10/2025
DELETE_SYNC("deleteSync", AccountCapabilityMode.ALWAYS_CAPABLE, true, true),
@Deprecated(forRemoval = true) // Can be removed sometime after 11/10/2025
STORAGE_SERVICE_RECORD_KEY_ROTATION("ssre2", AccountCapabilityMode.ALWAYS_CAPABLE, true, true),
ATTACHMENT_BACKFILL("attachmentBackfill", AccountCapabilityMode.PRIMARY_DEVICE, false, true),
SPARSE_POST_QUANTUM_RATCHET("spqr", AccountCapabilityMode.ALL_DEVICES, true, true);
SPARSE_POST_QUANTUM_RATCHET("spqr", AccountCapabilityMode.ALL_DEVICES, false, true);
public enum AccountCapabilityMode {
/**
@@ -28,6 +30,11 @@ public enum DeviceCapability {
* The account will have the capability iff all devices on the account have the capability
*/
ALL_DEVICES,
/**
* The account always has this capability, regardless of the constituent devices' capabilities.
* This supports retiring capabilities where older clients still need the field provided.
*/
ALWAYS_CAPABLE,
}
private final String name;
@@ -6,7 +6,9 @@
package org.whispersystems.textsecuregcm.storage;
import java.util.UUID;
import com.google.common.annotations.VisibleForTesting;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.grpc.ServiceIdentifierUtil;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
@@ -19,6 +21,9 @@ import org.whispersystems.textsecuregcm.util.UUIDUtil;
*/
public class EnvelopeUtil {
@VisibleForTesting
static final String INCLUDE_BINARY_SERVICE_ID_EXPERIMENT_NAME = "envelopeIncludeBinaryServiceIdentifier";
/**
* Converts all "compressible" UUID-like fields in the given envelope to more compact binary representations.
*
@@ -68,7 +73,22 @@ public class EnvelopeUtil {
*
* @return an envelope with binary representations of UUID-like fields expanded to string representations
*/
public static MessageProtos.Envelope expand(final MessageProtos.Envelope envelope) {
public static MessageProtos.Envelope expand(final MessageProtos.Envelope envelope,
final ExperimentEnrollmentManager experimentEnrollmentManager) {
final boolean includeBinaryServiceIdentifiers;
if (envelope.hasDestinationServiceIdBinary() || envelope.hasDestinationServiceId()) {
final ServiceIdentifier destinationIdentifier = envelope.hasDestinationServiceIdBinary()
? ServiceIdentifier.fromBytes(envelope.getDestinationServiceIdBinary().toByteArray())
: ServiceIdentifier.valueOf(envelope.getDestinationServiceId());
includeBinaryServiceIdentifiers =
experimentEnrollmentManager.isEnrolled(destinationIdentifier.uuid(), INCLUDE_BINARY_SERVICE_ID_EXPERIMENT_NAME);
} else {
includeBinaryServiceIdentifiers = false;
}
final MessageProtos.Envelope.Builder builder = envelope.toBuilder();
if (builder.hasSourceServiceIdBinary()) {
@@ -76,7 +96,10 @@ public class EnvelopeUtil {
ServiceIdentifierUtil.fromByteString(builder.getSourceServiceIdBinary());
builder.setSourceServiceId(sourceServiceId.toServiceIdentifierString());
builder.clearSourceServiceIdBinary();
if (!includeBinaryServiceIdentifiers) {
builder.clearSourceServiceIdBinary();
}
}
if (builder.hasDestinationServiceIdBinary()) {
@@ -84,14 +107,20 @@ public class EnvelopeUtil {
ServiceIdentifierUtil.fromByteString(builder.getDestinationServiceIdBinary());
builder.setDestinationServiceId(destinationServiceId.toServiceIdentifierString());
builder.clearDestinationServiceIdBinary();
if (!includeBinaryServiceIdentifiers) {
builder.clearDestinationServiceIdBinary();
}
}
if (builder.hasServerGuidBinary()) {
final UUID serverGuid = UUIDUtil.fromByteString(builder.getServerGuidBinary());
builder.setServerGuid(serverGuid.toString());
builder.clearServerGuidBinary();
if (!includeBinaryServiceIdentifiers) {
builder.clearServerGuidBinary();
}
}
if (builder.hasUpdatedPniBinary()) {
@@ -34,6 +34,7 @@ import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
@@ -109,6 +110,24 @@ public class IssuedReceiptsManager {
});
}
/**
* Clear the recorded issuances for a particular item
*
* @param processorItemId The itemId within the processor to clear
* @param processor The processor
* @return a future that yields true if the item was deleted, false if the item already did not exist
*/
public CompletableFuture<Boolean> clearIssuance(String processorItemId, PaymentProvider processor) {
final AttributeValue key = dynamoDbKey(processor, processorItemId);
final DeleteItemRequest deleteItemRequest = DeleteItemRequest.builder()
.tableName(table)
.key(Map.of(KEY_PROCESSOR_ITEM_ID, key))
.returnValues(ReturnValue.ALL_OLD)
.build();
return dynamoDbAsyncClient.deleteItem(deleteItemRequest)
.thenApply(item -> item.hasAttributes() && !item.attributes().isEmpty());
}
@VisibleForTesting
static AttributeValue dynamoDbKey(final PaymentProvider processor, String processorItemId) {
if (processor == PaymentProvider.STRIPE) {
@@ -5,29 +5,36 @@
package org.whispersystems.textsecuregcm.storage;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Metrics;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import org.whispersystems.textsecuregcm.controllers.KeysController;
import org.whispersystems.textsecuregcm.entities.ECPreKey;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.util.Futures;
import org.whispersystems.textsecuregcm.util.Optionals;
import reactor.core.publisher.Flux;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
import javax.annotation.Nullable;
public class KeysManager {
// KeysController for backwards compatibility
private static final String GET_KEYS_COUNTER_NAME = MetricsUtil.name(KeysController.class, "getKeys");
private final SingleUseECPreKeyStore ecPreKeys;
private final SingleUseKEMPreKeyStore pqPreKeys;
private final PagedSingleUseKEMPreKeyStore pagedPqPreKeys;
private final RepeatedUseECSignedPreKeyStore ecSignedPreKeys;
private final RepeatedUseKEMSignedPreKeyStore pqLastResortKeys;
private final ExperimentEnrollmentManager experimentEnrollmentManager;
public static String PAGED_KEYS_EXPERIMENT_NAME = "pagedPreKeys";
private static final String TAKE_PQ_NAME = MetricsUtil.name(KeysManager.class, "takePq");
@@ -36,14 +43,12 @@ public class KeysManager {
final SingleUseKEMPreKeyStore pqPreKeys,
final PagedSingleUseKEMPreKeyStore pagedPqPreKeys,
final RepeatedUseECSignedPreKeyStore ecSignedPreKeys,
final RepeatedUseKEMSignedPreKeyStore pqLastResortKeys,
final ExperimentEnrollmentManager experimentEnrollmentManager) {
final RepeatedUseKEMSignedPreKeyStore pqLastResortKeys) {
this.ecPreKeys = ecPreKeys;
this.pqPreKeys = pqPreKeys;
this.pagedPqPreKeys = pagedPqPreKeys;
this.ecSignedPreKeys = ecSignedPreKeys;
this.pqLastResortKeys = pqLastResortKeys;
this.experimentEnrollmentManager = experimentEnrollmentManager;
}
public TransactWriteItem buildWriteItemForEcSignedPreKey(final UUID identifier,
@@ -105,29 +110,26 @@ public class KeysManager {
public CompletableFuture<Void> storeKemOneTimePreKeys(final UUID identifier, final byte deviceId,
final List<KEMSignedPreKey> preKeys) {
final boolean enrolledInPagedKeys = experimentEnrollmentManager.isEnrolled(identifier, PAGED_KEYS_EXPERIMENT_NAME);
final CompletableFuture<Void> deleteOtherKeys = enrolledInPagedKeys
? pqPreKeys.delete(identifier, deviceId)
: pagedPqPreKeys.delete(identifier, deviceId);
return deleteOtherKeys.thenCompose(ignored -> enrolledInPagedKeys
? pagedPqPreKeys.store(identifier, deviceId, preKeys)
: pqPreKeys.store(identifier, deviceId, preKeys));
// Unconditionally delete keys in old format keystore, then write to the pagedPqPreKeys store
return pqPreKeys.delete(identifier, deviceId)
.thenCompose(_ -> pagedPqPreKeys.store(identifier, deviceId, preKeys));
}
public CompletableFuture<Optional<ECPreKey>> takeEC(final UUID identifier, final byte deviceId) {
@VisibleForTesting
CompletableFuture<Optional<ECPreKey>> takeEC(final UUID identifier, final byte deviceId) {
return ecPreKeys.take(identifier, deviceId);
}
public CompletableFuture<Optional<KEMSignedPreKey>> takePQ(final UUID identifier, final byte deviceId) {
final boolean enrolledInPagedKeys = experimentEnrollmentManager.isEnrolled(identifier, PAGED_KEYS_EXPERIMENT_NAME);
return tagTakePQ(pagedPqPreKeys.take(identifier, deviceId), PQSource.PAGE, enrolledInPagedKeys)
@VisibleForTesting
CompletableFuture<Optional<KEMSignedPreKey>> takePQ(final UUID identifier, final byte deviceId) {
return tagTakePQ(pagedPqPreKeys.take(identifier, deviceId), PQSource.PAGE)
.thenCompose(maybeSingleUsePreKey -> maybeSingleUsePreKey
.map(ignored -> CompletableFuture.completedFuture(maybeSingleUsePreKey))
.orElseGet(() -> tagTakePQ(pqPreKeys.take(identifier, deviceId), PQSource.ROW, enrolledInPagedKeys)))
.orElseGet(() -> tagTakePQ(pqPreKeys.take(identifier, deviceId), PQSource.ROW)))
.thenCompose(maybeSingleUsePreKey -> maybeSingleUsePreKey
.map(singleUsePreKey -> CompletableFuture.completedFuture(maybeSingleUsePreKey))
.orElseGet(() -> tagTakePQ(pqLastResortKeys.find(identifier, deviceId), PQSource.LAST_RESORT, enrolledInPagedKeys)));
.orElseGet(() -> tagTakePQ(pqLastResortKeys.find(identifier, deviceId), PQSource.LAST_RESORT)));
}
private enum PQSource {
@@ -135,7 +137,7 @@ public class KeysManager {
ROW,
LAST_RESORT
}
private CompletableFuture<Optional<KEMSignedPreKey>> tagTakePQ(CompletableFuture<Optional<KEMSignedPreKey>> prekey, final PQSource source, final boolean enrolledInPagedKeys) {
private CompletableFuture<Optional<KEMSignedPreKey>> tagTakePQ(CompletableFuture<Optional<KEMSignedPreKey>> prekey, final PQSource source) {
return prekey.thenApply(maybeSingleUsePreKey -> {
final Optional<String> maybeSourceTag = maybeSingleUsePreKey
// If we found a PK, use this source tag
@@ -143,10 +145,7 @@ public class KeysManager {
// If we didn't and this is our last resort, we didn't find a PK
.or(() -> source == PQSource.LAST_RESORT ? Optional.of("absent") : Optional.empty());
maybeSourceTag.ifPresent(sourceTag -> {
Metrics.counter(TAKE_PQ_NAME,
"source", sourceTag,
"enrolled", Boolean.toString(enrolledInPagedKeys))
.increment();
Metrics.counter(TAKE_PQ_NAME, "source", sourceTag).increment();
});
return maybeSingleUsePreKey;
});
@@ -165,9 +164,9 @@ public class KeysManager {
}
public CompletableFuture<Integer> getPqCount(final UUID identifier, final byte deviceId) {
return pagedPqPreKeys.getCount(identifier, deviceId).thenCompose(count -> count == 0
? pqPreKeys.getCount(identifier, deviceId)
: CompletableFuture.completedFuture(count));
// We only return the paged prekey count to encourage clients to upload more prekeys if they only have prekeys
// stored in the previous key store format
return pagedPqPreKeys.getCount(identifier, deviceId);
}
public CompletableFuture<Void> deleteSingleUsePreKeys(final UUID identifier) {
@@ -209,4 +208,36 @@ public class KeysManager {
public CompletableFuture<Void> pruneDeadPage(final UUID identifier, final byte deviceId, final UUID pageId) {
return pagedPqPreKeys.deleteBundleFromS3(identifier, deviceId, pageId);
}
public record DevicePreKeys(
ECSignedPreKey ecSignedPreKey,
Optional<ECPreKey> ecPreKey,
KEMSignedPreKey kemSignedPreKey) {}
public CompletableFuture<Optional<DevicePreKeys>> takeDevicePreKeys(
final byte deviceId,
final ServiceIdentifier serviceIdentifier,
final @Nullable String userAgent) {
final UUID uuid = serviceIdentifier.uuid();
return Futures.zipWith(
this.takeEC(uuid, deviceId),
this.getEcSignedPreKey(uuid, deviceId),
this.takePQ(uuid, deviceId),
(maybeUnsignedEcPreKey, maybeSignedEcPreKey, maybePqPreKey) -> {
Metrics.counter(GET_KEYS_COUNTER_NAME, Tags.of(
UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of("identityType", serviceIdentifier.identityType().name()),
Tag.of("oneTimeEcKeyAvailable", String.valueOf(maybeUnsignedEcPreKey.isPresent())),
Tag.of("signedEcKeyAvailable", String.valueOf(maybeSignedEcPreKey.isPresent())),
Tag.of("pqKeyAvailable", String.valueOf(maybePqPreKey.isPresent()))))
.increment();
// The pq prekey and signed EC prekey should never be null for an existing account. This should only happen
// if the account or device has been removed and the read was split, so we can return empty in those cases.
return Optionals.zipWith(maybeSignedEcPreKey, maybePqPreKey, (signedEcPreKey, pqPreKey) ->
new DevicePreKeys(signedEcPreKey, maybeUnsignedEcPreKey, pqPreKey));
})
.toCompletableFuture();
}
}
@@ -22,6 +22,7 @@ import java.util.Locale;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.IntStream;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -58,16 +59,15 @@ public class MessagePersister implements Managed {
private static final Counter TRIMMED_MESSAGE_COUNTER = Metrics.counter(name(MessagePersister.class, "trimmedMessage"));
private static final Counter TRIMMED_MESSAGE_BYTES_COUNTER = Metrics.counter(name(MessagePersister.class, "trimmedMessageBytes"));
private static final DistributionSummary QUEUE_COUNT_DISTRIBUTION_SUMMARY = DistributionSummary.builder(
name(MessagePersister.class, "queueCount"))
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry);
private static final String QUEUE_SIZE_DISTRIBUTION_SUMMARY_NAME = name(MessagePersister.class, "queueSize");
static final int QUEUE_BATCH_LIMIT = 100;
static final int MESSAGE_BATCH_LIMIT = 100;
private static final DistributionSummary QUEUE_COUNT_DISTRIBUTION_SUMMARY = DistributionSummary.builder(
name(MessagePersister.class, "queueCount"))
.register(Metrics.globalRegistry);
private static final long EXCEPTION_PAUSE_MILLIS = Duration.ofSeconds(3).toMillis();
private static final int CONSECUTIVE_EMPTY_CACHE_REMOVAL_LIMIT = 3;
Loaded 100 of 255 files, more files were not shown because too many files have changed in this diff. Show more