Compare commits

...
Author SHA1 Message Date
Ameya Lokare 58ad647d29 Update to the latest version of the spam filter 2025-04-07 11:25:49 -07:00
Jon Chambers 099073356c Make destination service identifiers for spam checks non-optional 2025-04-07 11:12:07 -07:00
Chris Eager 37038c4a63 Keep a strong reference to expiration in Gauge 2025-04-07 13:10:41 -05:00
Jon Chambers ffa98e5b34 Reduce and centralize message-sending metrics 2025-04-07 11:08:53 -04:00
Jon Chambers 6013d00654 Introduce a distinct UA for server-generated messages 2025-04-07 11:01:01 -04:00
Jon Chambers c03d63acb8 Centralize message size validation in actual message-sending methods 2025-04-07 11:01:01 -04:00
Jon Chambers c6689ca07a Internalize destination device list/registration ID checks in MessageSender 2025-04-07 09:15:39 -04:00
Chris Eager 1d0e2d29a7 Update javax.ws Javadoc references to jakarta.wx 2025-04-07 09:11:36 -04:00
Ameya Lokare d83d826236 Use expire NX on cardinality estimator key 2025-04-07 09:11:24 -04:00
Chris Eager 2efe687b4b Add TlsCertificateExpirationUtil 2025-04-07 09:10:48 -04:00
Katherine Yen 7cabc8f328 Update to the latest version of the spam filter 2025-04-03 12:27:43 -04:00
Katherine b57bdcaaea Dependency updates for Q2 2025 2025-04-03 12:05:51 -04:00
Chris Eager 041643783d Add libsignal tag to MetricsHttpChannelListener 2025-04-03 11:05:20 -05:00
Jon Chambers ed75ef917a Update to the latest version of the spam filter 2025-04-02 13:27:49 -04:00
Jon Chambers 7ea0885474 Accommodate gRPC in the SpamChecker interface 2025-04-02 13:16:55 -04:00
Jon Chambers 488e7c4913 Update to the latest version of the spam filter 2025-04-02 09:00:35 -04:00
Jon Chambers 6af4d41322 Enumerate rate limit challenge options 2025-04-02 08:48:43 -04:00
Ravi Khadiwala 2b07a21477 Add some additional backup metrics 2025-04-02 08:48:18 -04:00
Jon Chambers 4a42ff562d Define authenticated and anonymous gRPC services for sending messages 2025-04-02 08:47:34 -04:00
Jon Chambers d4031893cc Make raw User-Agent strings available to gRPC services 2025-04-01 09:11:37 -04:00
Ravi Khadiwala c2e3ab832c enforce provisioning websocket timeouts 2025-03-26 16:28:51 -05:00
Ravi Khadiwala 8c2f3c839f Fix calculation of backup staleness metric 2025-03-26 16:28:38 -05:00
Ravi Khadiwala df188e6f15 Document behavior for deletes of non-existing objects 2025-03-26 16:26:18 -05:00
Jon Chambers 12576daf1f Retire the (long-unused!) KEY_EXCHANGE envelope type 2025-03-26 11:32:23 -04:00
Chris Eager 46aefc0cbe Add retry configuration to RemoveExpiredUsernameHoldsCommand 2025-03-25 11:46:05 -05:00
Chris Eager 9d4f9b4c12 Add retry configuration to RemoveExpiredBackupsCommand 2025-03-25 11:46:05 -05:00
Chris Eager 3591e6bebd Add retry configuration to RemoveExpiredAccountsCommand 2025-03-25 11:46:05 -05:00
Chris Eager e12ba6b15b Reduce page size in MessagesDynamoDb#mayHaveUrgentMessages 2025-03-25 11:45:47 -05:00
Chris Eager 744b05244d Add onErrorResume and retries to eligibility check in NotifyIdleDevicesCommand 2025-03-25 11:45:16 -05:00
Chris Eager c22b8fafa6 Update AWS SDK to 2.31.7 2025-03-25 11:44:54 -05:00
Ameya Lokare 2194cf46e1 Remove jaxb and jaxb-api version pins 2025-03-24 16:37:34 -07:00
Jonathan Klabunde Tomer 1a46ac122a add some tags to ProfileController.versionNotFound 2025-03-24 14:57:29 -07:00
Ameya Lokare 55f85a81c6 Update to the latest version of the spam filter 2025-03-24 13:26:53 -07:00
Chris Eager 5a8cb8a312 Revert "Skip shared multi-recipient message payloads for small messages"
This reverts commit db2cd20dcb.
2025-03-24 14:40:12 -05:00
Jon Chambers d641d1fc39 Update to the latest version of the spam filter 2025-03-24 11:17:49 -04:00
Jon Chambers df56c65b54 Validate device message sizes when distributing PNI keys 2025-03-24 10:58:38 -04:00
Jon Chambers 1346fcb59e Require that incoming messages have content 2025-03-24 10:58:38 -04:00
Jon Chambers 50f681ffe8 Centralize message length validation 2025-03-24 10:58:38 -04:00
Jon Chambers faef614d80 Parse message content as a byte array in request entities 2025-03-24 10:58:38 -04:00
Chris Eager db2cd20dcb Skip shared multi-recipient message payloads for small messages 2025-03-21 16:51:21 -05:00
Chris Eager 9ef6024291 Update to the latest version of the spam filter 2025-03-20 10:44:47 -05:00
Jon Chambers a643a6c0f0 Always record inbound message byte rate limit events 2025-03-20 10:44:10 -05:00
Chris Eager 82e21b0c21 Remove obsolete turn implementations 2025-03-20 10:38:14 -05:00
Chris Eager 50e298a4f4 Add counter for Redis events 2025-03-20 10:37:18 -05:00
Chris Eager a0b9c40f6c Add JettySslHandshakeMetrics 2025-03-20 10:36:52 -05:00
Ravi Khadiwala 359cf02161 Add new attachmentBackfill capability 2025-03-19 16:03:40 -05:00
Chris Eager 6a1f01f876 Remove unused executor service 2025-03-13 14:49:04 -04:00
Jon Chambers 0595acc48f Add a counter for messages removed from the message cache 2025-03-13 14:48:34 -04:00
Jon Chambers 46ff8d51dc Switch to remote aggregation for persister distribution summaries 2025-03-13 14:48:34 -04:00
Jon Chambers dcd80e11f4 Measure persisted message bytes 2025-03-13 14:48:34 -04:00
Jon Chambers e1b1c7db8d Normalize persister metric names; make metrics static final 2025-03-13 14:48:34 -04:00
Jon Chambers 99041bc593 Use a dedicated status code (and message) for "reauthentication required" 2025-03-13 14:48:17 -04:00
Ravi Khadiwala dbd14481ed Add a missing join to testTrimOnFullPrimaryQueue 2025-03-11 17:39:15 -05:00
ravi-signal e3160bc717 Add a dedicated size estimation method to MessagesCache 2025-03-10 16:09:05 -05:00
Chris Eager 6798958650 Update autoPagingIterable() usage to remove null params 2025-03-08 09:08:27 -08:00
Chris Eager 3a90c572b4 Ensure customer ID matches in StripeManager#cancelAllActiveSubscriptions 2025-03-08 08:35:43 -08:00
ravi-signal eab3c36d83 Dont discard ephemeral messages beyond what the persister consumes 2025-03-07 15:27:03 -06:00
Ravi Khadiwala b7fee7b426 Allow cancellation of an expired purchaseToken 2025-03-07 15:26:33 -06:00
ravi-signal 469955aec9 Treat a 410 for an IAP token as not found 2025-03-07 15:24:33 -06:00
Chris Eager d1c9dff2c5 Use WhisperServerService as base name for executor service metrics 2025-03-07 15:23:51 -06:00
Jonathan Klabunde Tomer 9491ebbe90 remove versionedExpirationTimer 2025-03-06 08:20:06 -08:00
Ravi Khadiwala 09b50383d7 Automatically trim primary queue when cache cannot be persisted 2025-03-05 15:56:00 -06:00
Jon Chambers 8517eef3fe Add a "critical" warning tier for primary devices missing PQ keys 2025-03-05 08:51:10 -05:00
Jon Chambers 8955e31a1e Configure an "idle primary device reminder" interceptor 2025-03-04 08:35:01 -05:00
Jon Chambers f7a3971c64 Add an authentication interceptor that adds alert headers for idle primary devices 2025-03-04 08:35:01 -05:00
Jon Chambers 552079d3c2 Add an interceptor interface for WebSocket authentication 2025-03-04 08:35:01 -05:00
Chris Eager 59d984e25d Add pqKeyAvailable tag to GetKeys metric 2025-03-04 08:02:05 -05:00
Jonathan Klabunde Tomer d17b9322b7 remove old AAACertificateServices root too 2025-03-04 08:01:53 -05:00
Jonathan Klabunde Tomer 12bc175776 remove expired GeoTrust certificate from push trust store 2025-03-04 08:01:53 -05:00
Ravi Khadiwala 376458efa8 remove extra FCM QUOTA_EXCEEDED logging 2025-03-04 08:01:38 -05:00
Adel Lahlou 886984861f remove performance based turn routing from CallRoutingControllerV2 2025-03-04 08:01:18 -05:00
Jon Chambers b248b6bc12 Add the new APNs certificate to our trust store 2025-02-24 16:24:17 -05:00
ravi-signal 8d0d0d61f1 Add reregistration flag to account creation response 2025-02-21 14:13:04 -06:00
Ravi Khadiwala 26c348520f Revert "Add a 2-notification ttl=0 push notification experiment"
This reverts commit 4908a0aa9e.
2025-02-21 14:07:07 -06:00
Ravi Khadiwala ec79386306 Only accept backup receipt redemption when account has a backup credential request 2025-02-21 14:06:51 -06:00
Katherine 093ac6fb16 Align UpdateValue proto with the KT service's definition 2025-02-21 12:00:33 -08:00
Ravi Khadiwala 68e2c511b7 Split up backup-id rotation rate limits 2025-02-18 10:52:43 -06:00
Ravi Khadiwala 47c82b42d9 Check push tokens for primary device platform tags 2025-02-18 10:49:49 -06:00
Ravi Khadiwala e1a3b48c6e Only set X-Signal-Agent if present 2025-02-18 10:49:26 -06:00
Jon Chambers b8b17ae473 Add methods for iterating over all account identifiers 2025-02-18 11:46:00 -05:00
Chris Eager b203344ed4 Only log unexpected MRM retrieval errors 2025-02-18 10:45:04 -06:00
Chris Eager 6d30a45017 Discard stale messages from MessagesCache#getMessagesToPersist 2025-02-14 12:06:15 -06:00
Chris Eager 3f9863c441 Discard mrm messages that can never be sent 2025-02-14 12:06:15 -06:00
Chris Eager 47294ef6b8 Update README.md 2025-02-13 17:18:50 -06:00
163 changed files with 4012 additions and 3896 deletions

No files matched your search

+1 -1
View File
@@ -12,7 +12,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- uses: actions/setup-java@7a6d8a8234af8eb26422e24e3006232cccaa061b # v4.6.0
- uses: actions/setup-java@3a4f6e1af504cf6a31855fa899c6aa5355ba6c12 # v4.7.0
with:
distribution: 'temurin'
java-version: '21'
+2 -2
View File
@@ -14,12 +14,12 @@ jobs:
contents: read
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- uses: actions/setup-java@7a6d8a8234af8eb26422e24e3006232cccaa061b # v4.6.0
- uses: actions/setup-java@3a4f6e1af504cf6a31855fa899c6aa5355ba6c12 # v4.7.0
with:
distribution: 'temurin'
java-version: '21'
cache: 'maven'
- uses: aws-actions/configure-aws-credentials@e3dd6a429d7300a6a4c196c26e071d42e0343502 # v4.0.2
- uses: aws-actions/configure-aws-credentials@ececac1a45f3b08a01d2dd070d28d111c5fe6722 # v4.1.0
name: Configure AWS credentials from Test account
with:
role-to-assume: ${{ vars.AWS_ROLE }}
+1 -1
View File
@@ -14,7 +14,7 @@ jobs:
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- name: Set up JDK 21
uses: actions/setup-java@7a6d8a8234af8eb26422e24e3006232cccaa061b # v4.6.0
uses: actions/setup-java@3a4f6e1af504cf6a31855fa899c6aa5355ba6c12 # v4.7.0
with:
distribution: 'temurin'
java-version: 21
+22 -3
View File
@@ -8,9 +8,26 @@ Looking for protocol documentation? Check out the website!
https://signal.org/docs/
Cryptography Notice
How to Build
------------
```shell script
$ ./mvnw clean test
```
Security
--------
Security issues should be sent to <a href=mailto:security@signal.org>security@signal.org</a>.
Help
----
We cannot provide direct technical support. Get help running this software in your own environment in our [unofficial community forum][community forum].
Cryptography Notice
-------------------
This distribution includes cryptographic software. The country in which you currently reside may have restrictions on the import, possession, use, and/or re-export to another country, of encryption software.
BEFORE using any encryption software, please check your country's laws, regulations and policies concerning the import, possession, or use, and re-export of encryption software, to see if this is permitted.
See <https://www.wassenaar.org/> for more information.
@@ -19,8 +36,10 @@ The U.S. Government Department of Commerce, Bureau of Industry and Security (BIS
The form and manner of this distribution makes it eligible for export under the License Exception ENC Technology Software Unrestricted (TSU) exception (see the BIS Export Administration Regulations, Section 740.13) for both object code and source code.
License
---------------------
-------
Copyright 2013-2024 Signal Messenger, LLC
Copyright 2013 Signal Messenger, LLC
Licensed under the GNU AGPLv3: https://www.gnu.org/licenses/agpl-3.0.html
[community forum]: https://community.signalusers.org
@@ -8,7 +8,6 @@ package org.signal.integration;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import org.apache.commons.lang3.tuple.Pair;
import org.junit.jupiter.api.Test;
@@ -27,11 +26,10 @@ public class MessagingTest {
try {
final byte[] expectedContent = "Hello, World!".getBytes(StandardCharsets.UTF_8);
final String contentBase64 = Base64.getEncoder().encodeToString(expectedContent);
final IncomingMessage message = new IncomingMessage(1, Device.PRIMARY_ID, userB.registrationId(), contentBase64);
final IncomingMessage message = new IncomingMessage(1, Device.PRIMARY_ID, userB.registrationId(), expectedContent);
final IncomingMessageList messages = new IncomingMessageList(List.of(message), false, true, System.currentTimeMillis());
final Pair<Integer, SendMessageResponse> sendMessage = Operations
Operations
.apiPut("/v1/messages/%s".formatted(userB.aciUuid().toString()), messages)
.authorized(userA)
.execute(SendMessageResponse.class);
@@ -40,7 +38,7 @@ public class MessagingTest {
.authorized(userB)
.execute(OutgoingMessageEntityList.class);
final byte[] actualContent = receiveMessages.getRight().messages().get(0).content();
final byte[] actualContent = receiveMessages.getRight().messages().getFirst().content();
assertArrayEquals(expectedContent, actualContent);
} finally {
Operations.deleteUser(userA);
+44 -36
View File
@@ -37,44 +37,48 @@
</modules>
<properties>
<aws.sdk2.version>2.29.48</aws.sdk2.version>
<braintree.version>3.37.0</braintree.version>
<commons-csv.version>1.12.0</commons-csv.version>
<aws.sdk2.version>2.31.9</aws.sdk2.version>
<braintree.version>3.40.0</braintree.version>
<commons-csv.version>1.14.0</commons-csv.version>
<commons-io.version>2.18.0</commons-io.version>
<dropwizard.version>4.0.11</dropwizard.version>
<dropwizard-metrics-datadog.version>1.1.13</dropwizard-metrics-datadog.version>
<dropwizard.version>4.0.12</dropwizard.version>
<dropwizard-metrics-datadog.version>1.1.14</dropwizard-metrics-datadog.version>
<!-- can be updated to latest version with Dropwizard 5 (Jetty 12); will then need to disable telemetry -->
<dynamodblocal.version>2.2.1</dynamodblocal.version>
<google-cloud-libraries.version>26.52.0</google-cloud-libraries.version>
<google-cloud-libraries.version>26.57.0</google-cloud-libraries.version>
<grpc.version>1.69.0</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
<gson.version>2.11.0</gson.version>
<gson.version>2.12.1</gson.version>
<!-- several libraries (AWS, Google Cloud) use Apache http components transitively, and we need to align them -->
<httpcore.version>4.4.16</httpcore.version>
<httpclient.version>4.5.14</httpclient.version>
<jackson.version>2.18.2</jackson.version>
<jaxb.version>2.3.1</jaxb.version>
<jackson.version>2.18.3</jackson.version>
<junit-pioneer.version>2.3.0</junit-pioneer.version>
<jsr305.version>3.0.2</jsr305.version>
<kotlin.version>1.9.25</kotlin.version>
<lettuce.version>6.5.1.RELEASE</lettuce.version>
<libphonenumber.version>8.13.52</libphonenumber.version>
<kotlin.version>2.1.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.version>2.0.5</logback-access.version>
<lettuce.version>6.5.5.RELEASE</lettuce.version>
<libphonenumber.version>9.0.2</libphonenumber.version>
<logstash.logback.version>7.3</logstash.logback.version>
<log4j-bom.version>2.24.3</log4j-bom.version>
<luajava.version>3.5.0</luajava.version>
<micrometer.version>1.14.2</micrometer.version>
<netty.version>4.1.116.Final</netty.version>
<protobuf.version>3.25.5</protobuf.version> <!-- must be greater than or equal to the value from Google libraries-bom, see https://protobuf.dev/support/cross-version-runtime-guarantee/ -->
<micrometer.version>1.14.5</micrometer.version>
<netty.version>4.1.119.Final</netty.version>
<!-- Must be greater than or equal to the value from Google libraries-bom
since some of its libraries generate code. See https://protobuf.dev/support/cross-version-runtime-guarantee/. -->
<protobuf.version>3.25.5</protobuf.version>
<pushy.version>0.15.4</pushy.version>
<reactive.grpc.version>1.2.4</reactive.grpc.version>
<reactor-bom.version>2024.0.1</reactor-bom.version> <!-- 3.7.1, see https://github.com/reactor/reactor#bom-versioning-scheme -->
<resilience4j.version>2.2.0</resilience4j.version>
<reactor-bom.version>2024.0.4</reactor-bom.version> <!-- 3.7.4, see https://github.com/reactor/reactor#bom-versioning-scheme -->
<resilience4j.version>2.3.0</resilience4j.version>
<semver4j.version>3.1.0</semver4j.version>
<slf4j.version>2.0.16</slf4j.version>
<slf4j.version>2.0.17</slf4j.version>
<stripe.version>23.10.0</stripe.version>
<swagger.version>2.2.27</swagger.version>
<!-- eclipse-temurin:21.0.5_11-jre-jammy (note: always use the multi-arch manifest *LIST* here) -->
<docker.image.sha256>5f8358c9d5615c18e95728e8b8528bda7ff40a7a5da2ac9a35b7a01f5d9b231a</docker.image.sha256>
<!-- eclipse-temurin:21.0.6_7-jre-jammy (note: always use the multi-arch manifest *LIST* here) -->
<docker.image.sha256>02fc89fa8766a9ba221e69225f8d1c10bb91885ddbd3c112448e23488ba40ab6</docker.image.sha256>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
@@ -122,7 +126,7 @@
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>libraries-bom</artifactId>
<artifactId>libraries-bom-protobuf3</artifactId>
<version>${google-cloud-libraries.version}</version>
<type>pom</type>
<scope>import</scope>
@@ -195,11 +199,6 @@
<artifactId>lettuce-core</artifactId>
<version>${lettuce.version}</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>${jaxb.version}</version>
</dependency>
<dependency>
<groupId>net.logstash.logback</groupId>
<artifactId>logstash-logback-encoder</artifactId>
@@ -215,12 +214,6 @@
<artifactId>dropwizard-metrics-datadog</artifactId>
<version>${dropwizard-metrics-datadog.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>${jaxb.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
@@ -235,12 +228,12 @@
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
<version>1.3.5</version>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>9.5</version>
<version>9.7.1 </version>
<scope>test</scope>
</dependency>
<dependency>
@@ -272,7 +265,7 @@
<dependency>
<groupId>org.signal</groupId>
<artifactId>libsignal-server</artifactId>
<version>0.60.0</version>
<version>0.67.6</version>
</dependency>
<dependency>
<groupId>org.signal.forks</groupId>
@@ -302,6 +295,21 @@
<version>${dynamodblocal.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback.access</groupId>
<artifactId>logback-access-common</artifactId>
<version>${logback-access.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
@@ -319,7 +327,7 @@
<dependency>
<groupId>org.wiremock</groupId>
<artifactId>wiremock</artifactId>
<version>3.9.1</version>
<version>3.12.1</version>
<scope>test</scope>
</dependency>
<dependency>
-1
View File
@@ -94,7 +94,6 @@ currentReportingKey.salt: AAAAAAAAAAA=
registrationService.collationKeySalt: AAAAAAAAAAA=
turn.secret: AAAAAAAAAAA=
turn.cloudflare.apiToken: ABCDEFGHIJKLM
linkDevice.secret: AAAAAAAAAAA=
+3 -25
View File
@@ -473,7 +473,6 @@ keyTransparencyService:
clientPrivateKey: secret://keyTransparencyService.clientPrivateKey
turn:
secret: secret://turn.secret
cloudflare:
apiToken: secret://turn.cloudflare.apiToken
endpoint: https://rtc.live.cloudflare.com/v1/turn/keys/LMNOP/credentials/generate
@@ -490,30 +489,6 @@ turn:
linkDevice:
secret: secret://linkDevice.secret
maxmindCityDatabase:
s3Region: a-region
s3Bucket: a-bucket
objectKey: an-object.tar.gz
maxSize: 32777216
callingTurnDnsRecords:
s3Region: a-region
s3Bucket: a-bucket
objectKey: an-object.tar.gz
maxSize: 32777216
callingTurnPerformanceTable:
s3Region: a-region
s3Bucket: a-bucket
objectKey: an-object.tar.gz
maxSize: 32777216
callingTurnManualTable:
s3Region: a-region
s3Bucket: a-bucket
objectKey: an-object.tar.gz
maxSize: 32777216
noiseTunnel:
port: 8443
tlsKeyStoreFile: /path/to/file.p12
@@ -529,3 +504,6 @@ externalRequestFilter:
- /example
permittedInternalRanges:
- 127.0.0.0/8
idlePrimaryDeviceReminder:
minIdleDuration: P30D
+21 -20
View File
@@ -11,14 +11,20 @@
<artifactId>service</artifactId>
<properties>
<firebase-admin.version>9.4.2</firebase-admin.version>
<firebase-admin.version>9.4.3</firebase-admin.version>
<java-uuid-generator.version>5.1.0</java-uuid-generator.version>
<google-androidpublisher.version>v3-rev20250102-2.0.0</google-androidpublisher.version>
<storekit.version>3.2.0</storekit.version>
<webauthn4j.version>0.28.4.RELEASE</webauthn4j.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>
<java-jwt.version>4.5.0</java-jwt.version>
</properties>
<dependencies>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>${java-jwt.version}</version>
</dependency>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-androidpublisher</artifactId>
@@ -137,8 +143,8 @@
<artifactId>logback-core</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-access</artifactId>
<groupId>ch.qos.logback.access</groupId>
<artifactId>logback-access-common</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
@@ -173,10 +179,6 @@
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
@@ -232,32 +234,31 @@
<version>1.27.1</version>
</dependency>
<dependency>
<groupId>com.maxmind.geoip2</groupId>
<artifactId>geoip2</artifactId>
<version>4.2.1</version>
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-pubsub</artifactId>
</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>
<exclusion>
<groupId>io.opentelemetry.semconv</groupId>
<artifactId>opentelemetry-semconv</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.opentelemetry.semconv</groupId>
<artifactId>opentelemetry-semconv</artifactId>
<version>1.27.0-alpha</version>
<version>1.30.0</version>
</dependency>
<!-- resolve opentelemetry-semconv conflict from lower in firebase-admin dependency tree -->
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-firestore</artifactId>
<version>3.30.2</version>
<exclusions>
<exclusion>
<groupId>io.opentelemetry.semconv</groupId>
@@ -410,7 +411,7 @@
<dependency>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>geocoder</artifactId>
<version>2.246</version>
<version>3.2</version>
</dependency>
<dependency>
@@ -37,6 +37,7 @@ import org.whispersystems.textsecuregcm.configuration.FcmConfiguration;
import org.whispersystems.textsecuregcm.configuration.GcpAttachmentsConfiguration;
import org.whispersystems.textsecuregcm.configuration.GenericZkConfig;
import org.whispersystems.textsecuregcm.configuration.GooglePlayBillingConfiguration;
import org.whispersystems.textsecuregcm.configuration.IdlePrimaryDeviceReminderConfiguration;
import org.whispersystems.textsecuregcm.configuration.KeyTransparencyServiceConfiguration;
import org.whispersystems.textsecuregcm.configuration.LinkDeviceSecretConfiguration;
import org.whispersystems.textsecuregcm.configuration.MaxDeviceConfiguration;
@@ -300,27 +301,6 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private VirtualThreadConfiguration virtualThread = new VirtualThreadConfiguration(Duration.ofMillis(1));
@Valid
@NotNull
@JsonProperty
private S3ObjectMonitorFactory maxmindCityDatabase;
@Valid
@NotNull
@JsonProperty
private S3ObjectMonitorFactory callingTurnDnsRecords;
@Valid
@NotNull
@JsonProperty
private S3ObjectMonitorFactory callingTurnPerformanceTable;
@Valid
@NotNull
@JsonProperty
private S3ObjectMonitorFactory callingTurnManualTable;
@Valid
@NotNull
@JsonProperty
@@ -339,6 +319,10 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private boolean logMessageDeliveryLoops;
@JsonProperty
private IdlePrimaryDeviceReminderConfiguration idlePrimaryDeviceReminder =
new IdlePrimaryDeviceReminderConfiguration(Duration.ofDays(30));
public TlsKeyStoreConfiguration getTlsKeyStoreConfiguration() {
return tlsKeyStore;
}
@@ -534,22 +518,6 @@ public class WhisperServerConfiguration extends Configuration {
return virtualThread;
}
public S3ObjectMonitorFactory getMaxmindCityDatabase() {
return maxmindCityDatabase;
}
public S3ObjectMonitorFactory getCallingTurnDnsRecords() {
return callingTurnDnsRecords;
}
public S3ObjectMonitorFactory getCallingTurnPerformanceTable() {
return callingTurnPerformanceTable;
}
public S3ObjectMonitorFactory getCallingTurnManualTable() {
return callingTurnManualTable;
}
public NoiseWebSocketTunnelConfiguration getNoiseWebSocketTunnelConfiguration() {
return noiseTunnel;
}
@@ -566,4 +534,7 @@ public class WhisperServerConfiguration extends Configuration {
return logMessageDeliveryLoops;
}
public IdlePrimaryDeviceReminderConfiguration idlePrimaryDeviceReminderConfiguration() {
return idlePrimaryDeviceReminder;
}
}
@@ -82,9 +82,9 @@ import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
import org.whispersystems.textsecuregcm.auth.CloudflareTurnCredentialsManager;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
import org.whispersystems.textsecuregcm.auth.IdlePrimaryDeviceAuthenticatedWebSocketUpgradeFilter;
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
import org.whispersystems.textsecuregcm.auth.WebsocketRefreshApplicationEventListener;
import org.whispersystems.textsecuregcm.auth.grpc.ProhibitAuthenticationInterceptor;
import org.whispersystems.textsecuregcm.auth.grpc.RequireAuthenticationInterceptor;
@@ -94,10 +94,6 @@ import org.whispersystems.textsecuregcm.backup.BackupsDb;
import org.whispersystems.textsecuregcm.backup.Cdn3BackupCredentialGenerator;
import org.whispersystems.textsecuregcm.backup.Cdn3RemoteStorageManager;
import org.whispersystems.textsecuregcm.badges.ConfiguredProfileBadgeConverter;
import org.whispersystems.textsecuregcm.calls.routing.CallDnsRecordsManager;
import org.whispersystems.textsecuregcm.calls.routing.CallRoutingTableManager;
import org.whispersystems.textsecuregcm.calls.routing.DynamicConfigTurnRouter;
import org.whispersystems.textsecuregcm.calls.routing.TurnCallRouter;
import org.whispersystems.textsecuregcm.captcha.CaptchaChecker;
import org.whispersystems.textsecuregcm.captcha.CaptchaClient;
import org.whispersystems.textsecuregcm.captcha.RegistrationCaptchaManager;
@@ -142,7 +138,6 @@ import org.whispersystems.textsecuregcm.filters.RemoteDeprecationFilter;
import org.whispersystems.textsecuregcm.filters.RequestStatisticsFilter;
import org.whispersystems.textsecuregcm.filters.RestDeprecationFilter;
import org.whispersystems.textsecuregcm.filters.TimestampResponseFilter;
import org.whispersystems.textsecuregcm.geo.MaxMindDatabaseManager;
import org.whispersystems.textsecuregcm.grpc.AccountsAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.AccountsGrpcService;
import org.whispersystems.textsecuregcm.grpc.ErrorMappingInterceptor;
@@ -183,12 +178,14 @@ import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper
import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.ServerRejectedExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
import org.whispersystems.textsecuregcm.metrics.BackupMetrics;
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
import org.whispersystems.textsecuregcm.metrics.MetricsApplicationEventListener;
import org.whispersystems.textsecuregcm.metrics.MetricsHttpChannelListener;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.MicrometerAwsSdkMetricPublisher;
import org.whispersystems.textsecuregcm.metrics.ReportedMessageMetricsListener;
import org.whispersystems.textsecuregcm.metrics.TlsCertificateExpirationUtil;
import org.whispersystems.textsecuregcm.metrics.TrafficSource;
import org.whispersystems.textsecuregcm.providers.MultiRecipientMessageProvider;
import org.whispersystems.textsecuregcm.providers.RedisClusterHealthCheck;
@@ -268,8 +265,6 @@ import org.whispersystems.textsecuregcm.workers.BackupMetricsCommand;
import org.whispersystems.textsecuregcm.workers.CertificateCommand;
import org.whispersystems.textsecuregcm.workers.CheckDynamicConfigurationCommand;
import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
import org.whispersystems.textsecuregcm.workers.DiscardPushNotificationExperimentSamplesCommand;
import org.whispersystems.textsecuregcm.workers.FinishPushNotificationExperimentCommand;
import org.whispersystems.textsecuregcm.workers.IdleDeviceNotificationSchedulerFactory;
import org.whispersystems.textsecuregcm.workers.MessagePersisterServiceCommand;
import org.whispersystems.textsecuregcm.workers.NotifyIdleDevicesCommand;
@@ -282,10 +277,7 @@ import org.whispersystems.textsecuregcm.workers.ScheduledApnPushNotificationSend
import org.whispersystems.textsecuregcm.workers.ServerVersionCommand;
import org.whispersystems.textsecuregcm.workers.SetRequestLoggingEnabledTask;
import org.whispersystems.textsecuregcm.workers.SetUserDiscoverabilityCommand;
import org.whispersystems.textsecuregcm.workers.StartPushNotificationExperimentCommand;
import org.whispersystems.textsecuregcm.workers.UnlinkDeviceCommand;
import org.whispersystems.textsecuregcm.workers.ZeroTtlExperimentNotificationSchedulerFactory;
import org.whispersystems.textsecuregcm.workers.ZeroTtlPushNotificationExperimentFactory;
import org.whispersystems.textsecuregcm.workers.ZkParamsCommand;
import org.whispersystems.websocket.WebSocketResourceProviderFactory;
import org.whispersystems.websocket.setup.WebSocketEnvironment;
@@ -340,24 +332,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
bootstrap.addCommand(new RemoveExpiredLinkedDevicesCommand());
bootstrap.addCommand(new NotifyIdleDevicesCommand());
bootstrap.addCommand(new StartPushNotificationExperimentCommand<>("start-zero-ttl-push-notification-experiment",
"Start an experiment to send push notifications with ttl=0 to idle android devices",
new ZeroTtlPushNotificationExperimentFactory()));
bootstrap.addCommand(
new FinishPushNotificationExperimentCommand<>("finish-zero-ttl-push-notification-experiment",
"Finish an experiment to send push notifications with ttl=0 to idle android devices",
new ZeroTtlPushNotificationExperimentFactory()));
bootstrap.addCommand(
new DiscardPushNotificationExperimentSamplesCommand("discard-zero-ttl-push-notification-experiment",
"Discard samples from the \"zero TTL push notification\" experiment",
new ZeroTtlPushNotificationExperimentFactory()));
bootstrap.addCommand(new ProcessScheduledJobsServiceCommand("process-zero-ttl-notification-jobs",
"Processes scheduled jobs to send zero-ttl experiment notifications to idle devices",
new ZeroTtlExperimentNotificationSchedulerFactory()));
bootstrap.addCommand(new ProcessScheduledJobsServiceCommand("process-idle-device-notification-jobs",
"Processes scheduled jobs to send notifications to idle devices",
new IdleDeviceNotificationSchedulerFactory()));
@@ -392,6 +366,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
.forEach(connectorFactory -> {
if (connectorFactory instanceof HttpsConnectorFactory h) {
h.setKeyStorePassword(config.getTlsKeyStoreConfiguration().password().value());
TlsCertificateExpirationUtil.configureMetrics(h.getKeyStorePath(), h.getKeyStorePassword(), h.getKeyStoreType(), h.getKeyStoreProvider());
}
});
}
@@ -536,8 +512,6 @@ 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 = environment.lifecycle().executorService(name(getClass(), "batchIdentityCheck-%d")).minThreads(32).maxThreads(32).build();
ExecutorService multiRecipientMessageExecutor = environment.lifecycle()
.executorService(name(getClass(), "multiRecipientMessage-%d")).minThreads(64).maxThreads(64).build();
ExecutorService subscriptionProcessorExecutor = environment.lifecycle()
.executorService(name(getClass(), "subscriptionProcessor-%d"))
.maxThreads(availableProcessors) // mostly this is IO bound so tying to number of processors is tenuous at best
@@ -696,7 +670,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final MessageSender messageSender = new MessageSender(messagesManager, pushNotificationManager);
final ReceiptSender receiptSender = new ReceiptSender(accountsManager, messageSender, receiptSenderExecutor);
final TurnTokenGenerator turnTokenGenerator = new TurnTokenGenerator(config.getTurnConfiguration().secret().value());
final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager = new CloudflareTurnCredentialsManager(
config.getTurnConfiguration().cloudflare().apiToken().value(),
config.getTurnConfiguration().cloudflare().endpoint(),
@@ -836,45 +809,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getAppleDeviceCheck().teamId(),
config.getAppleDeviceCheck().bundleId());
final DynamicConfigTurnRouter configTurnRouter = new DynamicConfigTurnRouter(dynamicConfigurationManager);
MaxMindDatabaseManager geoIpCityDatabaseManager = new MaxMindDatabaseManager(
recurringConfigSyncExecutor,
awsCredentialsProvider,
config.getMaxmindCityDatabase(),
"city"
);
environment.lifecycle().manage(geoIpCityDatabaseManager);
CallDnsRecordsManager callDnsRecordsManager = new CallDnsRecordsManager(
recurringConfigSyncExecutor,
awsCredentialsProvider,
config.getCallingTurnDnsRecords()
);
environment.lifecycle().manage(callDnsRecordsManager);
CallRoutingTableManager callRoutingTableManager = new CallRoutingTableManager(
recurringConfigSyncExecutor,
awsCredentialsProvider,
config.getCallingTurnPerformanceTable(),
"Performance"
);
environment.lifecycle().manage(callRoutingTableManager);
CallRoutingTableManager manualCallRoutingTableManager = new CallRoutingTableManager(
recurringConfigSyncExecutor,
awsCredentialsProvider,
config.getCallingTurnManualTable(),
"Manual"
);
environment.lifecycle().manage(manualCallRoutingTableManager);
TurnCallRouter callRouter = new TurnCallRouter(
callDnsRecordsManager,
callRoutingTableManager,
manualCallRoutingTableManager,
configTurnRouter,
geoIpCityDatabaseManager,
false
);
final GrpcClientConnectionManager grpcClientConnectionManager = new GrpcClientConnectionManager();
disconnectionRequestManager.addListener(grpcClientConnectionManager);
@@ -1025,6 +959,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
Set.of(websocketServletPath, provisioningWebsocketServletPath, "/health-check"));
metricsHttpChannelListener.configure(environment);
final MessageMetrics messageMetrics = new MessageMetrics();
final BackupMetrics backupMetrics = new BackupMetrics();
// BufferingInterceptor is needed on the base environment but not the WebSocketEnvironment,
// because we handle serialization of http responses on the websocket on our own and can
@@ -1047,6 +982,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getWebSocketConfiguration(), Duration.ofMillis(90000));
webSocketEnvironment.jersey().register(new VirtualExecutorServiceProvider("managed-async-websocket-virtual-thread-"));
webSocketEnvironment.setAuthenticator(new WebSocketAccountAuthenticator(accountAuthenticator, new AccountPrincipalSupplier(accountsManager)));
webSocketEnvironment.setAuthenticatedWebSocketUpgradeFilter(new IdlePrimaryDeviceAuthenticatedWebSocketUpgradeFilter(
keysManager, config.idlePrimaryDeviceReminderConfiguration().minIdleDuration(), Clock.systemUTC()));
webSocketEnvironment.setConnectListener(
new AuthenticatedConnectListener(receiptSender, messagesManager, messageMetrics, pushNotificationManager,
pushNotificationScheduler, webSocketConnectionEventManager, websocketScheduledExecutor,
@@ -1139,8 +1076,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
registrationLockVerificationManager, rateLimiters),
new AttachmentControllerV4(rateLimiters, gcsAttachmentGenerator, tusAttachmentGenerator,
experimentEnrollmentManager),
new ArchiveController(backupAuthManager, backupManager),
new CallRoutingControllerV2(rateLimiters, callRouter, turnTokenGenerator, experimentEnrollmentManager, cloudflareTurnCredentialsManager),
new ArchiveController(backupAuthManager, backupManager, backupMetrics),
new CallRoutingControllerV2(rateLimiters, cloudflareTurnCredentialsManager),
new CallLinkController(rateLimiters, callingGenericZkSecretParams),
new CertificateController(new CertificateGenerator(config.getDeliveryCertificate().certificate().value(),
config.getDeliveryCertificate().ecPrivateKey(), config.getDeliveryCertificate().expiresDays()),
@@ -1158,7 +1095,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new MessageController(rateLimiters, messageByteLimitCardinalityEstimator, messageSender, receiptSender,
accountsManager, messagesManager, phoneNumberIdentifiers, pushNotificationManager, pushNotificationScheduler,
reportMessageManager, messageDeliveryScheduler, clientReleaseManager,
dynamicConfigurationManager, zkSecretParams, spamChecker, messageMetrics, messageDeliveryLoopMonitor,
zkSecretParams, spamChecker, messageMetrics, messageDeliveryLoopMonitor,
Clock.systemUTC()),
new PaymentsController(currencyManager, paymentsCredentialsGenerator),
new ProfileController(clock, rateLimiters, accountsManager, profilesManager, dynamicConfigurationManager,
@@ -15,8 +15,8 @@ import java.net.Inet6Address;
import java.net.URI;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
@@ -127,11 +127,11 @@ public class CloudflareTurnCredentialsManager {
final CloudflareTurnResponse cloudflareTurnResponse = SystemMapper.jsonMapper()
.readValue(response.body(), CloudflareTurnResponse.class);
return TurnTokenGenerator.from(
return new TurnToken(
cloudflareTurnResponse.iceServers().username(),
cloudflareTurnResponse.iceServers().credential(),
Optional.ofNullable(cloudflareTurnUrls),
Optional.ofNullable(cloudflareTurnComposedUrls),
cloudflareTurnUrls == null ? Collections.emptyList() : cloudflareTurnUrls,
cloudflareTurnComposedUrls,
cloudflareTurnHostname
);
}
@@ -0,0 +1,85 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.auth;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import org.eclipse.jetty.websocket.server.JettyServerUpgradeRequest;
import org.eclipse.jetty.websocket.server.JettyServerUpgradeResponse;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.KeysManager;
import org.whispersystems.websocket.ReusableAuth;
import org.whispersystems.websocket.auth.AuthenticatedWebSocketUpgradeFilter;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
public class IdlePrimaryDeviceAuthenticatedWebSocketUpgradeFilter implements
AuthenticatedWebSocketUpgradeFilter<AuthenticatedDevice> {
private final KeysManager keysManager;
private final Duration minIdleDuration;
private final Clock clock;
@VisibleForTesting
static final String ALERT_HEADER = "X-Signal-Alert";
@VisibleForTesting
static final String IDLE_PRIMARY_DEVICE_ALERT = "idle-primary-device";
@VisibleForTesting
static final String CRITICAL_IDLE_PRIMARY_DEVICE_ALERT = "critical-idle-primary-device";
@VisibleForTesting
static final Duration PQ_KEY_CHECK_THRESHOLD = Duration.ofDays(120);
private static final Counter IDLE_PRIMARY_WARNING_COUNTER = Metrics.counter(
MetricsUtil.name(IdlePrimaryDeviceAuthenticatedWebSocketUpgradeFilter.class, "idlePrimaryDeviceWarning"),
"critical", "false");
private static final Counter CRITICAL_IDLE_PRIMARY_WARNING_COUNTER = Metrics.counter(
MetricsUtil.name(IdlePrimaryDeviceAuthenticatedWebSocketUpgradeFilter.class, "idlePrimaryDeviceWarning"),
"critical", "true");
public IdlePrimaryDeviceAuthenticatedWebSocketUpgradeFilter(final KeysManager keysManager,
final Duration minIdleDuration,
final Clock clock) {
this.keysManager = keysManager;
this.minIdleDuration = minIdleDuration;
this.clock = clock;
}
@Override
public void handleAuthentication(final ReusableAuth<AuthenticatedDevice> authenticated,
final JettyServerUpgradeRequest request,
final JettyServerUpgradeResponse response) {
// No action needed if the connection is unauthenticated (in which case we don't know when we've last seen the
// primary device) or if the authenticated device IS the primary device
authenticated.ref()
.filter(authenticatedDevice -> !authenticatedDevice.getAuthenticatedDevice().isPrimary())
.ifPresent(authenticatedDevice -> {
final Instant primaryDeviceLastSeen =
Instant.ofEpochMilli(authenticatedDevice.getAccount().getPrimaryDevice().getLastSeen());
if (primaryDeviceLastSeen.isBefore(clock.instant().minus(PQ_KEY_CHECK_THRESHOLD)) &&
keysManager.getLastResort(authenticatedDevice.getAccount().getIdentifier(IdentityType.ACI), Device.PRIMARY_ID)
.join().isEmpty()) {
response.addHeader(ALERT_HEADER, CRITICAL_IDLE_PRIMARY_DEVICE_ALERT);
CRITICAL_IDLE_PRIMARY_WARNING_COUNTER.increment();
} else if (primaryDeviceLastSeen.isBefore(clock.instant().minus(minIdleDuration))) {
response.addHeader(ALERT_HEADER, IDLE_PRIMARY_DEVICE_ALERT);
IDLE_PRIMARY_WARNING_COUNTER.increment();
}
});
}
}
@@ -1,87 +0,0 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.auth;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.whispersystems.textsecuregcm.calls.routing.TurnServerOptions;
import org.whispersystems.textsecuregcm.util.Util;
public class TurnTokenGenerator {
private final byte[] turnSecret;
private static final String ALGORITHM = "HmacSHA1";
private static final String WithUrlsProtocol = "00";
private static final String WithIpsProtocol = "01";
public TurnTokenGenerator(final byte[] turnSecret) {
this.turnSecret = turnSecret;
}
public TurnToken generateWithTurnServerOptions(TurnServerOptions options) {
return generateToken(options.hostname(), options.urlsWithIps(), options.urlsWithHostname());
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
private TurnToken generateToken(
String hostname,
Optional<List<String>> urlsWithIps,
Optional<List<String>> urlsWithHostname
) {
try {
final Mac mac = Mac.getInstance(ALGORITHM);
final long validUntilSeconds = Instant.now().plus(Duration.ofDays(1)).getEpochSecond();
final long user = Util.ensureNonNegativeInt(new SecureRandom().nextInt());
final String userTime = validUntilSeconds + ":" + user;
final String protocol = urlsWithIps.isEmpty() || urlsWithIps.get().isEmpty()
? WithUrlsProtocol
: WithIpsProtocol;
final String protocolUserTime = userTime + "#" + protocol;
mac.init(new SecretKeySpec(turnSecret, ALGORITHM));
final String password = Base64.getEncoder().encodeToString(mac.doFinal(protocolUserTime.getBytes()));
return from(
protocolUserTime,
password,
urlsWithHostname,
urlsWithIps,
hostname
);
} catch (final NoSuchAlgorithmException | InvalidKeyException e) {
throw new AssertionError(e);
}
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public static TurnToken from(
String username,
String password,
Optional<List<String>> urls,
Optional<List<String>> urlsWithIps,
String hostname
) {
return new TurnToken(
username,
password,
urls.orElse(Collections.emptyList()),
urlsWithIps.orElse(Collections.emptyList()),
hostname
);
}
}
@@ -14,6 +14,7 @@ import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
@@ -114,9 +115,17 @@ public class BackupAuthManager {
return CompletableFuture.completedFuture(null);
}
return rateLimiters.forDescriptor(RateLimiters.For.SET_BACKUP_ID)
.validateAsync(account.getUuid())
.thenCompose(ignored -> this.accountsManager
CompletionStage<Void> rateLimitFuture = rateLimiters
.forDescriptor(RateLimiters.For.SET_BACKUP_ID)
.validateAsync(account.getUuid());
if (!mediaCredentialRequestMatches && hasActiveVoucher(account)) {
rateLimitFuture = rateLimitFuture.thenCombine(
rateLimiters.forDescriptor(RateLimiters.For.SET_PAID_MEDIA_BACKUP_ID).validateAsync(account.getUuid()),
(ignore1, ignore2) -> null);
}
return rateLimitFuture.thenCompose(ignored -> this.accountsManager
.updateAsync(account, a -> a.setBackupCredentialRequests(serializedMessageCredentialRequest, serializedMediaCredentialRequest))
.thenRun(Util.NOOP))
.toCompletableFuture();
@@ -227,6 +236,12 @@ public class BackupAuthManager {
.asRuntimeException();
}
if (account.getBackupCredentialRequest(BackupCredentialType.MEDIA).isEmpty()) {
throw Status.ABORTED
.withDescription("account must have a backup-id commitment")
.asRuntimeException();
}
return redeemedReceiptsManager
.put(receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, account.getUuid())
.thenCompose(receiptAllowed -> {
@@ -280,8 +295,12 @@ public class BackupAuthManager {
return next;
}
private boolean hasActiveVoucher(final Account account) {
return account.getBackupVoucher() != null && clock.instant().isBefore(account.getBackupVoucher().expiration());
}
private boolean hasExpiredVoucher(final Account account) {
return account.getBackupVoucher() != null && clock.instant().isAfter(account.getBackupVoucher().expiration());
return account.getBackupVoucher() != null && !hasActiveVoucher(account);
}
/**
@@ -46,7 +46,7 @@ public class BackupManager {
static final String MESSAGE_BACKUP_NAME = "messageBackup";
public static final long MAX_TOTAL_BACKUP_MEDIA_BYTES = DataSize.gibibytes(100).toBytes();
static final long MAX_MEDIA_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);
@@ -1,74 +0,0 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.calls.routing;
import org.whispersystems.textsecuregcm.configuration.TurnUriConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicTurnConfiguration;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.WeightedRandomSelect;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.UUID;
/** Uses DynamicConfig to help route a turn request */
public class DynamicConfigTurnRouter {
private static final Random rng = new Random();
public static final long RANDOMIZE_RATE_BASIS = 100_000;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
public DynamicConfigTurnRouter(final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
this.dynamicConfigurationManager = dynamicConfigurationManager;
}
public List<String> targetedUrls(final UUID aci) {
final DynamicTurnConfiguration turnConfig = dynamicConfigurationManager.getConfiguration().getTurnConfiguration();
final Optional<TurnUriConfiguration> enrolled = turnConfig.getUriConfigs().stream()
.filter(config -> config.getEnrolledAcis().contains(aci))
.findFirst();
return enrolled
.map(turnUriConfiguration -> turnUriConfiguration.getUris().stream().toList())
.orElse(Collections.emptyList());
}
public List<String> randomUrls() {
final DynamicTurnConfiguration turnConfig = dynamicConfigurationManager.getConfiguration().getTurnConfiguration();
// select from turn server sets by weighted choice
return WeightedRandomSelect.select(turnConfig
.getUriConfigs()
.stream()
.map(c -> new Pair<>(c.getUris(), c.getWeight())).toList());
}
public String getHostname() {
final DynamicTurnConfiguration turnConfig = dynamicConfigurationManager.getConfiguration().getTurnConfiguration();
return turnConfig.getHostname();
}
public long getRandomizeRate() {
final DynamicTurnConfiguration turnConfig = dynamicConfigurationManager.getConfiguration().getTurnConfiguration();
return turnConfig.getRandomizeRate();
}
public int getDefaultInstanceIpCount() {
final DynamicTurnConfiguration turnConfig = dynamicConfigurationManager.getConfiguration().getTurnConfiguration();
return turnConfig.getDefaultInstanceIpCount();
}
public boolean shouldRandomize() {
long rate = getRandomizeRate();
return rate >= RANDOMIZE_RATE_BASIS || rng.nextLong(0, DynamicConfigTurnRouter.RANDOMIZE_RATE_BASIS) < rate;
}
}
@@ -1,190 +0,0 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.calls.routing;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse;
import org.apache.commons.lang3.tuple.Triple;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.util.Util;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.net.InetAddress;
import java.util.*;
import java.util.function.Supplier;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
* Returns routes based on performance tables, manually routing tables, and target routing. Falls back to a random Turn
* instance that the server knows about.
*/
public class TurnCallRouter {
private final Logger logger = LoggerFactory.getLogger(TurnCallRouter.class);
private final Supplier<CallDnsRecords> callDnsRecords;
private final Supplier<CallRoutingTable> performanceRouting;
private final Supplier<CallRoutingTable> manualRouting;
private final DynamicConfigTurnRouter configTurnRouter;
private final Supplier<DatabaseReader> geoIp;
// controls whether instance IPs are shuffled. using if & boolean is ~5x faster than a function pointer
private final boolean stableSelect;
public TurnCallRouter(
@Nonnull Supplier<CallDnsRecords> callDnsRecords,
@Nonnull Supplier<CallRoutingTable> performanceRouting,
@Nonnull Supplier<CallRoutingTable> manualRouting,
@Nonnull DynamicConfigTurnRouter configTurnRouter,
@Nonnull Supplier<DatabaseReader> geoIp,
boolean stableSelect
) {
this.performanceRouting = performanceRouting;
this.callDnsRecords = callDnsRecords;
this.manualRouting = manualRouting;
this.configTurnRouter = configTurnRouter;
this.geoIp = geoIp;
this.stableSelect = stableSelect;
}
public TurnServerOptions getRoutingFor(
@Nonnull final UUID aci,
@Nonnull final Optional<InetAddress> clientAddress
) {
return getRoutingFor(aci, clientAddress, this.configTurnRouter.getDefaultInstanceIpCount());
}
/**
* Gets Turn Instance addresses. Returns both the IPv4 and IPv6 addresses. Prefers to match the IP protocol of the
* client address in datacenter selection. Returns 2 instance options of the preferred protocol for every one instance
* of the other.
* @param aci aci of client
* @param clientAddress IP address to base routing on
* @param instanceLimit max instances to return options for
* @return Up to two * instanceLimit options, half in ipv4, half in ipv6
*/
public TurnServerOptions getRoutingFor(
@Nonnull final UUID aci,
@Nonnull final Optional<InetAddress> clientAddress,
final int instanceLimit
) {
try {
return getRoutingForInner(aci, clientAddress, instanceLimit);
} catch(Exception e) {
logger.error("Failed to perform routing", e);
return new TurnServerOptions(this.configTurnRouter.getHostname(), null, Optional.of(this.configTurnRouter.randomUrls()));
}
}
TurnServerOptions getRoutingForInner(
@Nonnull final UUID aci,
@Nonnull final Optional<InetAddress> clientAddress,
final int instanceLimit
) {
String hostname = this.configTurnRouter.getHostname();
List<String> targetedUrls = this.configTurnRouter.targetedUrls(aci);
if(!targetedUrls.isEmpty()) {
return new TurnServerOptions(hostname, Optional.empty(), Optional.ofNullable(targetedUrls));
}
if(clientAddress.isEmpty() || this.configTurnRouter.shouldRandomize() || instanceLimit < 1) {
return new TurnServerOptions(hostname, Optional.empty(), Optional.ofNullable(this.configTurnRouter.randomUrls()));
}
CityResponse geoInfo;
try {
geoInfo = geoIp.get().city(clientAddress.get());
} catch (IOException | GeoIp2Exception e) {
throw new RuntimeException(e);
}
Optional<String> subdivision = !geoInfo.getSubdivisions().isEmpty()
? Optional.of(geoInfo.getSubdivisions().getFirst().getIsoCode())
: Optional.empty();
List<String> datacenters = this.manualRouting.get().getDatacentersFor(
clientAddress.get(),
geoInfo.getContinent().getCode(),
geoInfo.getCountry().getIsoCode(),
subdivision
);
if (datacenters.isEmpty()){
datacenters = this.performanceRouting.get().getDatacentersFor(
clientAddress.get(),
geoInfo.getContinent().getCode(),
geoInfo.getCountry().getIsoCode(),
subdivision
);
}
List<String> urlsWithIps = getUrlsForInstances(
selectInstances(
datacenters,
instanceLimit
));
return new TurnServerOptions(hostname, Optional.of(urlsWithIps), Optional.of(minimalRandomUrls()));
}
// Includes only the udp options in the randomUrls
private List<String> minimalRandomUrls(){
return this.configTurnRouter.randomUrls().stream()
.filter(s -> s.startsWith("turn:") && !s.endsWith("transport=tcp"))
.toList();
}
// returns balanced number of instances across provided datacenters, prioritizing the datacenters earlier in the list
private List<String> selectInstances(List<String> datacenters, int instanceLimit) {
if(datacenters.isEmpty() || instanceLimit == 0) {
return Collections.emptyList();
}
CallDnsRecords dnsRecords = this.callDnsRecords.get();
List<List<InetAddress>> ipv4Options = datacenters.stream()
.map(dc -> randomNOf(dnsRecords.aByRegion().get(dc), instanceLimit, stableSelect))
.toList();
List<List<InetAddress>> ipv6Options = datacenters.stream()
.map(dc -> randomNOf(dnsRecords.aaaaByRegion().get(dc), instanceLimit, stableSelect))
.toList();
List<InetAddress> ipv4Selection = selectFromOptions(ipv4Options, instanceLimit);
List<InetAddress> ipv6Selection = selectFromOptions(ipv6Options, instanceLimit);
return Stream.concat(
ipv4Selection.stream().map(InetAddress::getHostAddress),
// map ipv6 to RFC3986 format i.e. surrounded by brackets
ipv6Selection.stream().map(i -> String.format("[%s]", i.getHostAddress()))
).toList();
}
private static List<InetAddress> selectFromOptions(List<List<InetAddress>> recordsByDc, int instanceLimit) {
return IntStream.range(0, recordsByDc.size())
.mapToObj(dcIndex -> IntStream.range(0, recordsByDc.get(dcIndex).size())
.mapToObj(addressIndex -> Triple.of(addressIndex, dcIndex, recordsByDc.get(dcIndex).get(addressIndex))))
.flatMap(i -> i)
.sorted(Comparator.comparingInt((Triple<Integer, Integer, InetAddress> t) -> t.getLeft())
.thenComparingInt(Triple::getMiddle))
.limit(instanceLimit)
.sorted(Comparator.comparingInt(Triple::getMiddle))
.map(Triple::getRight)
.toList();
}
private static <E> List<E> randomNOf(List<E> values, int n, boolean stableSelect) {
return stableSelect ? Util.randomNOfStable(values, n) : Util.randomNOfShuffled(values, n);
}
private static List<String> getUrlsForInstances(List<String> instanceIps) {
return instanceIps.stream().flatMap(ip -> Stream.of(
String.format("turn:%s", ip),
String.format("turn:%s:80?transport=tcp", ip),
String.format("turns:%s:443?transport=tcp", ip)
)
).toList();
}
}
@@ -116,7 +116,8 @@ public class CircuitBreakerConfiguration {
.permittedNumberOfCallsInHalfOpenState(getPermittedNumberOfCallsInHalfOpenState())
.waitDurationInOpenState(getWaitDurationInOpenState())
.slidingWindow(getSlidingWindowSize(), getSlidingWindowMinimumNumberOfCalls(),
CircuitBreakerConfig.SlidingWindowType.COUNT_BASED)
CircuitBreakerConfig.SlidingWindowType.COUNT_BASED,
CircuitBreakerConfig.SlidingWindowSynchronizationStrategy.SYNCHRONIZED)
.build();
}
}
@@ -7,6 +7,7 @@ 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 jakarta.validation.constraints.Positive;
@@ -15,8 +16,8 @@ import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
public record CloudflareTurnConfiguration(@NotNull SecretString apiToken,
@NotBlank String endpoint,
@NotBlank long ttl,
@NotBlank List<String> urls,
@NotBlank List<String> urlsWithIps,
@NotNull @NotEmpty @Valid List<@NotBlank String> urls,
@NotNull @NotEmpty @Valid List<@NotBlank String> urlsWithIps,
@NotNull @Valid CircuitBreakerConfiguration circuitBreaker,
@NotNull @Valid RetryConfiguration retry,
@NotBlank String hostname,
@@ -0,0 +1,11 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import java.time.Duration;
public record IdlePrimaryDeviceReminderConfiguration(Duration minIdleDuration) {
}
@@ -5,7 +5,5 @@
package org.whispersystems.textsecuregcm.configuration;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
public record TurnConfiguration(SecretBytes secret, CloudflareTurnConfiguration cloudflare) {
public record TurnConfiguration(CloudflareTurnConfiguration cloudflare) {
}
@@ -42,10 +42,6 @@ public class DynamicConfiguration {
@Valid
private DynamicCaptchaConfiguration captcha = new DynamicCaptchaConfiguration();
@JsonProperty
@Valid
private DynamicTurnConfiguration turn = new DynamicTurnConfiguration();
@JsonProperty
@Valid
DynamicMessagePersisterConfiguration messagePersister = new DynamicMessagePersisterConfiguration();
@@ -54,10 +50,6 @@ public class DynamicConfiguration {
@Valid
DynamicRateLimitPolicy rateLimitPolicy = new DynamicRateLimitPolicy(false);
@JsonProperty
@Valid
DynamicInboundMessageByteLimitConfiguration inboundMessageByteLimit = new DynamicInboundMessageByteLimitConfiguration(true);
@JsonProperty
@Valid
DynamicRegistrationConfiguration registrationConfiguration = new DynamicRegistrationConfiguration(false);
@@ -104,10 +96,6 @@ public class DynamicConfiguration {
return captcha;
}
public DynamicTurnConfiguration getTurnConfiguration() {
return turn;
}
public DynamicMessagePersisterConfiguration getMessagePersisterConfiguration() {
return messagePersister;
}
@@ -116,10 +104,6 @@ public class DynamicConfiguration {
return rateLimitPolicy;
}
public DynamicInboundMessageByteLimitConfiguration getInboundMessageByteLimitConfiguration() {
return inboundMessageByteLimit;
}
public DynamicRegistrationConfiguration getRegistrationConfiguration() {
return registrationConfiguration;
}
@@ -1,9 +0,0 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration.dynamic;
public record DynamicInboundMessageByteLimitConfiguration(boolean enforceInboundLimit) {
}
@@ -6,13 +6,33 @@
package org.whispersystems.textsecuregcm.configuration.dynamic;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.annotations.VisibleForTesting;
public class DynamicMessagePersisterConfiguration {
@JsonProperty
private boolean persistenceEnabled = true;
/**
* If we have to trim a client's persisted queue to make room to persist from Redis to DynamoDB, how much extra room should we make
*/
@JsonProperty
private double trimOversizedQueueExtraRoomRatio = 1.5;
public DynamicMessagePersisterConfiguration() {}
@VisibleForTesting
public DynamicMessagePersisterConfiguration(final boolean persistenceEnabled, final double trimOversizedQueueExtraRoomRatio) {
this.persistenceEnabled = persistenceEnabled;
this.trimOversizedQueueExtraRoomRatio = trimOversizedQueueExtraRoomRatio;
}
public boolean isPersistenceEnabled() {
return persistenceEnabled;
}
public double getTrimOversizedQueueExtraRoomRatio() {
return trimOversizedQueueExtraRoomRatio;
}
}
@@ -1,50 +0,0 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration.dynamic;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.Valid;
import java.util.Collections;
import java.util.List;
import org.whispersystems.textsecuregcm.configuration.TurnUriConfiguration;
public class DynamicTurnConfiguration {
@JsonProperty
private String hostname;
/**
* Rate at which to prioritize a random turn URL to exercise all endpoints.
* Based on a 100,000 basis, where 100,000 == 100%.
*/
@JsonProperty
private long randomizeRate = 5_000;
/**
* Number of instance ips to return in TURN routing request
*/
@JsonProperty
private int defaultInstanceIpCount = 0;
@JsonProperty
private List<@Valid TurnUriConfiguration> uriConfigs = Collections.emptyList();
public List<TurnUriConfiguration> getUriConfigs() {
return uriConfigs;
}
public long getRandomizeRate() {
return randomizeRate;
}
public int getDefaultInstanceIpCount() {
return defaultInstanceIpCount;
}
public String getHostname() {
return hostname;
}
}
@@ -34,6 +34,7 @@ import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.signal.libsignal.usernames.BaseUsernameException;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
@@ -232,7 +233,9 @@ public class AccountController {
d.setName(attributes.getName());
d.setLastSeen(Util.todayInMillis());
d.setCapabilities(attributes.getCapabilities());
d.setUserAgent(userAgent);
if (StringUtils.isNotBlank(userAgent)) {
d.setUserAgent(userAgent);
}
});
a.setRegistrationLockFromAttributes(attributes);
@@ -43,14 +43,15 @@ import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager
import org.whispersystems.textsecuregcm.entities.AccountDataReportResponse;
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
import org.whispersystems.textsecuregcm.entities.ChangeNumberRequest;
import org.whispersystems.textsecuregcm.entities.MismatchedDevices;
import org.whispersystems.textsecuregcm.entities.MismatchedDevicesResponse;
import org.whispersystems.textsecuregcm.entities.PhoneNumberDiscoverabilityRequest;
import org.whispersystems.textsecuregcm.entities.PhoneNumberIdentityKeyDistributionRequest;
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
import org.whispersystems.textsecuregcm.entities.StaleDevices;
import org.whispersystems.textsecuregcm.entities.StaleDevicesResponse;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
@@ -92,8 +93,9 @@ public class AccountControllerV2 {
@ApiResponse(responseCode = "200", description = "The phone number associated with the authenticated account was changed successfully", useReturnTypeSchema = true)
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
@ApiResponse(responseCode = "403", description = "Verification failed for the provided Registration Recovery Password")
@ApiResponse(responseCode = "409", description = "Mismatched number of devices or device ids in 'devices to notify' list", content = @Content(schema = @Schema(implementation = MismatchedDevices.class)))
@ApiResponse(responseCode = "410", description = "Mismatched registration ids in 'devices to notify' list", content = @Content(schema = @Schema(implementation = StaleDevices.class)))
@ApiResponse(responseCode = "409", description = "Mismatched number of devices or device ids in 'devices to notify' list", content = @Content(schema = @Schema(implementation = MismatchedDevicesResponse.class)))
@ApiResponse(responseCode = "410", description = "Mismatched registration ids in 'devices to notify' list", content = @Content(schema = @Schema(implementation = StaleDevicesResponse.class)))
@ApiResponse(responseCode = "413", description = "One or more device messages was too large")
@ApiResponse(responseCode = "422", description = "The request did not pass validation")
@ApiResponse(responseCode = "423", content = @Content(schema = @Schema(implementation = RegistrationLockFailure.class)))
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
@@ -143,22 +145,27 @@ public class AccountControllerV2 {
request.devicePniSignedPrekeys(),
request.devicePniPqLastResortPrekeys(),
request.deviceMessages(),
request.pniRegistrationIds());
request.pniRegistrationIds(),
userAgentString);
return AccountIdentityResponseBuilder.fromAccount(updatedAccount);
} catch (MismatchedDevicesException e) {
throw new WebApplicationException(Response.status(409)
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new MismatchedDevices(e.getMissingDevices(),
e.getExtraDevices()))
.build());
} catch (StaleDevicesException e) {
throw new WebApplicationException(Response.status(410)
.type(MediaType.APPLICATION_JSON)
.entity(new StaleDevices(e.getStaleDevices()))
.build());
if (!e.getMismatchedDevices().staleDeviceIds().isEmpty()) {
throw new WebApplicationException(Response.status(410)
.type(MediaType.APPLICATION_JSON)
.entity(new StaleDevicesResponse(e.getMismatchedDevices().staleDeviceIds()))
.build());
} else {
throw new WebApplicationException(Response.status(409)
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new MismatchedDevicesResponse(e.getMismatchedDevices().missingDeviceIds(),
e.getMismatchedDevices().extraDeviceIds()))
.build());
}
} catch (IllegalArgumentException e) {
throw new BadRequestException(e);
} catch (MessageTooLargeException e) {
throw new WebApplicationException(Response.Status.REQUEST_ENTITY_TOO_LARGE);
}
}
@@ -173,9 +180,10 @@ public class AccountControllerV2 {
@ApiResponse(responseCode = "403", description = "This endpoint can only be invoked from the account's primary device.")
@ApiResponse(responseCode = "422", description = "The request body failed validation.")
@ApiResponse(responseCode = "409", description = "The set of devices specified in the request does not match the set of devices active on the account.",
content = @Content(schema = @Schema(implementation = MismatchedDevices.class)))
content = @Content(schema = @Schema(implementation = MismatchedDevicesResponse.class)))
@ApiResponse(responseCode = "410", description = "The registration IDs provided for some devices do not match those stored on the server.",
content = @Content(schema = @Schema(implementation = StaleDevices.class)))
content = @Content(schema = @Schema(implementation = StaleDevicesResponse.class)))
@ApiResponse(responseCode = "413", description = "One or more device messages was too large")
public AccountIdentityResponse distributePhoneNumberIdentityKeys(
@Mutable @Auth final AuthenticatedDevice authenticatedDevice,
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgentString,
@@ -196,22 +204,27 @@ public class AccountControllerV2 {
request.devicePniSignedPrekeys(),
request.devicePniPqLastResortPrekeys(),
request.deviceMessages(),
request.pniRegistrationIds());
request.pniRegistrationIds(),
userAgentString);
return AccountIdentityResponseBuilder.fromAccount(updatedAccount);
} catch (MismatchedDevicesException e) {
throw new WebApplicationException(Response.status(409)
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new MismatchedDevices(e.getMissingDevices(),
e.getExtraDevices()))
.build());
} catch (StaleDevicesException e) {
throw new WebApplicationException(Response.status(410)
.type(MediaType.APPLICATION_JSON)
.entity(new StaleDevices(e.getStaleDevices()))
.build());
if (!e.getMismatchedDevices().staleDeviceIds().isEmpty()) {
throw new WebApplicationException(Response.status(410)
.type(MediaType.APPLICATION_JSON)
.entity(new StaleDevicesResponse(e.getMismatchedDevices().staleDeviceIds()))
.build());
} else {
throw new WebApplicationException(Response.status(409)
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new MismatchedDevicesResponse(e.getMismatchedDevices().missingDeviceIds(),
e.getMismatchedDevices().extraDeviceIds()))
.build());
}
} catch (IllegalArgumentException e) {
throw new BadRequestException(e);
} catch (MessageTooLargeException e) {
throw new WebApplicationException(Response.Status.REQUEST_ENTITY_TOO_LARGE);
}
}
@@ -5,6 +5,8 @@
package org.whispersystems.textsecuregcm.controllers;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import com.fasterxml.jackson.core.JsonParser;
@@ -13,13 +15,16 @@ import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.net.HttpHeaders;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
@@ -69,6 +74,8 @@ import org.whispersystems.textsecuregcm.backup.CopyParameters;
import org.whispersystems.textsecuregcm.backup.CopyResult;
import org.whispersystems.textsecuregcm.backup.MediaEncryptionParameters;
import org.whispersystems.textsecuregcm.entities.RemoteAttachment;
import org.whispersystems.textsecuregcm.metrics.BackupMetrics;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.util.BackupAuthCredentialAdapter;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import org.whispersystems.textsecuregcm.util.ByteArrayBase64UrlAdapter;
@@ -80,7 +87,7 @@ import org.whispersystems.websocket.auth.ReadOnly;
import reactor.core.publisher.Mono;
@Path("/v1/archives")
@Tag(name = "Archive")
@io.swagger.v3.oas.annotations.tags.Tag(name = "Archive")
public class ArchiveController {
public final static String X_SIGNAL_ZK_AUTH = "X-Signal-ZK-Auth";
@@ -88,12 +95,15 @@ public class ArchiveController {
private final BackupAuthManager backupAuthManager;
private final BackupManager backupManager;
private final BackupMetrics backupMetrics;
public ArchiveController(
final BackupAuthManager backupAuthManager,
final BackupManager backupManager) {
final BackupManager backupManager,
final BackupMetrics backupMetrics) {
this.backupAuthManager = backupAuthManager;
this.backupManager = backupManager;
this.backupMetrics = backupMetrics;
}
public record SetBackupIdRequest(
@@ -173,9 +183,13 @@ public class ArchiveController {
After successful redemption, subsequent requests to /v1/archive/auth will return credentials with the level on
the provided receipt until the expiration time on the receipt.
Accounts must have an existing backup credential request in order to redeem a receipt. This request will fail
if the account has not already set a backup credential request via PUT `/v1/archives/backupid`.
""")
@ApiResponse(responseCode = "204", description = "The receipt was redeemed")
@ApiResponse(responseCode = "400", description = "The provided presentation or receipt was invalid")
@ApiResponse(responseCode = "409", description = "The target account does not have a backup-id commitment")
@ApiResponse(responseCode = "429", description = "Rate limited.")
public CompletionStage<Response> redeemReceipt(
@Mutable @Auth final AuthenticatedDevice account,
@@ -243,6 +257,7 @@ public class ArchiveController {
@ApiResponse(responseCode = "429", description = "Rate limited.")
public CompletionStage<BackupAuthCredentialsResponse> getBackupZKCredentials(
@Mutable @Auth AuthenticatedDevice auth,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@NotNull @QueryParam("redemptionStartSeconds") Long startSeconds,
@NotNull @QueryParam("redemptionEndSeconds") Long endSeconds) {
@@ -254,11 +269,17 @@ public class ArchiveController {
auth.getAccount(),
credentialType,
Instant.ofEpochSecond(startSeconds), Instant.ofEpochSecond(endSeconds))
.thenAccept(credentials -> credentialsByType.put(credentialType, credentials.stream()
.map(credential -> new BackupAuthCredentialsResponse.BackupAuthCredential(
credential.credential().serialize(),
credential.redemptionTime().getEpochSecond()))
.toList())))
.thenAccept(credentials -> {
backupMetrics.updateGetCredentialCounter(
UserAgentTagUtil.getPlatformTag(userAgent),
credentialType,
credentials.size());
credentialsByType.put(credentialType, credentials.stream()
.map(credential -> new BackupAuthCredentialsResponse.BackupAuthCredential(
credential.credential().serialize(),
credential.redemptionTime().getEpochSecond()))
.toList());
}))
.toArray(CompletableFuture[]::new))
.thenApply(ignored -> new BackupAuthCredentialsResponse(credentialsByType.entrySet().stream()
.collect(Collectors.toMap(
@@ -582,6 +603,7 @@ public class ArchiveController {
@ApiResponseZkAuth
public CompletionStage<CopyMediaResponse> copyMedia(
@ReadOnly @Auth final Optional<AuthenticatedDevice> account,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@Parameter(description = BackupAuthCredentialPresentationHeader.DESCRIPTION, schema = @Schema(implementation = String.class))
@NotNull
@@ -601,6 +623,7 @@ public class ArchiveController {
.fromFuture(backupManager.authenticateBackupUser(presentation.presentation, signature.signature))
.flatMap(backupUser -> backupManager.copyToBackup(backupUser, List.of(copyMediaRequest.toCopyParameters()))
.next()
.doOnNext(result -> backupMetrics.updateCopyCounter(result, UserAgentTagUtil.getPlatformTag(userAgent)))
.map(copyResult -> switch (copyResult.outcome()) {
case SUCCESS -> new CopyMediaResponse(copyResult.cdn());
case SOURCE_WRONG_LENGTH -> throw new BadRequestException("Invalid length");
@@ -679,6 +702,7 @@ public class ArchiveController {
@ApiResponseZkAuth
public CompletionStage<Response> copyMedia(
@ReadOnly @Auth final Optional<AuthenticatedDevice> account,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@Parameter(description = BackupAuthCredentialPresentationHeader.DESCRIPTION, schema = @Schema(implementation = String.class))
@NotNull
@@ -697,6 +721,7 @@ public class ArchiveController {
final Stream<CopyParameters> copyParams = copyMediaRequest.items().stream().map(CopyMediaRequest::toCopyParameters);
return Mono.fromFuture(backupManager.authenticateBackupUser(presentation.presentation, signature.signature))
.flatMapMany(backupUser -> backupManager.copyToBackup(backupUser, copyParams.toList()))
.doOnNext(result -> backupMetrics.updateCopyCounter(result, UserAgentTagUtil.getPlatformTag(userAgent)))
.map(CopyMediaBatchResponse.Entry::fromCopyResult)
.collectList()
.map(list -> Response.status(207).entity(new CopyMediaBatchResponse(list)).build())
@@ -832,7 +857,7 @@ public class ArchiveController {
@Path("/media/delete")
@Operation(summary = "Delete media objects",
description = "Delete media objects stored with this backup-id")
@ApiResponse(responseCode = "204")
@ApiResponse(responseCode = "204", description = "The provided objects were successfully deleted or they do not exist")
@ApiResponse(responseCode = "429", description = "Rate limited.")
@ApiResponseZkAuth
public CompletionStage<Response> deleteMedia(
@@ -18,20 +18,13 @@ import jakarta.ws.rs.Produces;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.CloudflareTurnCredentialsManager;
import org.whispersystems.textsecuregcm.auth.TurnToken;
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
import org.whispersystems.textsecuregcm.calls.routing.TurnCallRouter;
import org.whispersystems.textsecuregcm.calls.routing.TurnServerOptions;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.websocket.auth.ReadOnly;
@@ -39,25 +32,15 @@ import org.whispersystems.websocket.auth.ReadOnly;
@Path("/v2/calling")
public class CallRoutingControllerV2 {
private static final Counter INVALID_IP_COUNTER = Metrics.counter(name(CallRoutingControllerV2.class, "invalidIP"));
private static final Counter CLOUDFLARE_TURN_ERROR_COUNTER = Metrics.counter(name(CallRoutingControllerV2.class, "cloudflareTurnError"));
private final RateLimiters rateLimiters;
private final TurnCallRouter turnCallRouter;
private final TurnTokenGenerator tokenGenerator;
private final ExperimentEnrollmentManager experimentEnrollmentManager;
private final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager;
public CallRoutingControllerV2(
final RateLimiters rateLimiters,
final TurnCallRouter turnCallRouter,
final TurnTokenGenerator tokenGenerator,
final ExperimentEnrollmentManager experimentEnrollmentManager,
final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager
) {
this.rateLimiters = rateLimiters;
this.turnCallRouter = turnCallRouter;
this.tokenGenerator = tokenGenerator;
this.experimentEnrollmentManager = experimentEnrollmentManager;
this.cloudflareTurnCredentialsManager = cloudflareTurnCredentialsManager;
}
@@ -76,34 +59,19 @@ public class CallRoutingControllerV2 {
@ApiResponse(responseCode = "422", description = "Invalid request format.")
@ApiResponse(responseCode = "429", description = "Rate limited.")
public GetCallingRelaysResponse getCallingRelays(
final @ReadOnly @Auth AuthenticatedDevice auth,
@Context ContainerRequestContext requestContext
) throws RateLimitExceededException {
final @ReadOnly @Auth AuthenticatedDevice auth
) throws RateLimitExceededException, IOException {
UUID aci = auth.getAccount().getUuid();
rateLimiters.getCallEndpointLimiter().validate(aci);
List<TurnToken> tokens = new ArrayList<>();
try {
if (experimentEnrollmentManager.isEnrolled(auth.getAccount().getNumber(), aci, "cloudflareTurn")) {
tokens.add(cloudflareTurnCredentialsManager.retrieveFromCloudflare());
}
tokens.add(cloudflareTurnCredentialsManager.retrieveFromCloudflare());
} catch (Exception e) {
// emit counter, rely on Signal URL fallback
CallRoutingControllerV2.CLOUDFLARE_TURN_ERROR_COUNTER.increment();
throw e;
}
Optional<InetAddress> address = Optional.empty();
try {
final String remoteAddress = (String) requestContext.getProperty(
RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
address = Optional.of(InetAddress.getByName(remoteAddress));
} catch (UnknownHostException e) {
INVALID_IP_COUNTER.increment();
}
TurnServerOptions options = turnCallRouter.getRoutingFor(aci, address);
tokens.add(tokenGenerator.generateWithTurnServerOptions(options));
return new GetCallingRelaysResponse(tokens);
}
@@ -52,6 +52,7 @@ import java.util.concurrent.CompletionStage;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.glassfish.jersey.server.ContainerRequest;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
@@ -599,13 +600,21 @@ public class DeviceController {
}
private static io.micrometer.core.instrument.Tag primaryPlatformTag(final Account account) {
final Optional<ClientPlatform> clientPlatform = Optional.ofNullable(
switch (account.getPrimaryDevice().getUserAgent()) {
final Device primaryDevice = account.getPrimaryDevice();
Optional<ClientPlatform> clientPlatform = Optional.empty();
if (StringUtils.isNotBlank(primaryDevice.getGcmId())) {
clientPlatform = Optional.of(ClientPlatform.ANDROID);
} else if (StringUtils.isNotBlank(primaryDevice.getApnId())) {
clientPlatform = Optional.of(ClientPlatform.IOS);
}
clientPlatform = clientPlatform.or(() -> Optional.ofNullable(
switch (primaryDevice.getUserAgent()) {
case "OWA" -> ClientPlatform.ANDROID;
case "OWI", "OWP" -> ClientPlatform.IOS;
case "OWD" -> ClientPlatform.DESKTOP;
case null, default -> null;
});
}));
return io.micrometer.core.instrument.Tag.of(
"primaryPlatform",
@@ -381,7 +381,8 @@ public class KeysController {
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("oneTimeEcKeyAvailable", String.valueOf(unsignedEcPreKey != null)),
Tag.of("pqKeyAvailable", String.valueOf(pqPreKey != null))))
.increment();
if (signedEcPreKey != null || unsignedEcPreKey != null || pqPreKey != null) {
@@ -7,13 +7,9 @@ package org.whispersystems.textsecuregcm.controllers;
import static com.codahale.metrics.MetricRegistry.name;
import com.codahale.metrics.annotation.Timed;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.net.HttpHeaders;
import io.dropwizard.auth.Auth;
import io.dropwizard.util.DataSize;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.Timer;
import io.micrometer.core.instrument.Timer.Sample;
@@ -47,27 +43,22 @@ import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import java.time.Clock;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.glassfish.jersey.server.ManagedAsync;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.protocol.util.Pair;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.groupsend.GroupSendDerivedKeyPair;
@@ -80,20 +71,19 @@ import org.whispersystems.textsecuregcm.auth.CombinedUnidentifiedSenderAccessKey
import org.whispersystems.textsecuregcm.auth.GroupSendTokenHeader;
import org.whispersystems.textsecuregcm.auth.OptionalAccess;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.entities.AccountMismatchedDevices;
import org.whispersystems.textsecuregcm.entities.AccountStaleDevices;
import org.whispersystems.textsecuregcm.entities.IncomingMessage;
import org.whispersystems.textsecuregcm.entities.IncomingMessageList;
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope.Type;
import org.whispersystems.textsecuregcm.entities.MismatchedDevices;
import org.whispersystems.textsecuregcm.entities.MismatchedDevicesResponse;
import org.whispersystems.textsecuregcm.entities.OutgoingMessageEntity;
import org.whispersystems.textsecuregcm.entities.OutgoingMessageEntityList;
import org.whispersystems.textsecuregcm.entities.SendMessageResponse;
import org.whispersystems.textsecuregcm.entities.SendMultiRecipientMessageResponse;
import org.whispersystems.textsecuregcm.entities.SpamReport;
import org.whispersystems.textsecuregcm.entities.StaleDevices;
import org.whispersystems.textsecuregcm.entities.StaleDevicesResponse;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
@@ -105,19 +95,20 @@ import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.providers.MultiRecipientMessageProvider;
import org.whispersystems.textsecuregcm.push.MessageSender;
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
import org.whispersystems.textsecuregcm.push.ReceiptSender;
import org.whispersystems.textsecuregcm.spam.MessageType;
import org.whispersystems.textsecuregcm.spam.SpamCheckResult;
import org.whispersystems.textsecuregcm.spam.SpamChecker;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
import org.whispersystems.textsecuregcm.util.DestinationDeviceValidator;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.Util;
@@ -149,7 +140,6 @@ public class MessageController {
private final ReportMessageManager reportMessageManager;
private final Scheduler messageDeliveryScheduler;
private final ClientReleaseManager clientReleaseManager;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private final ServerSecretParams serverSecretParams;
private final SpamChecker spamChecker;
private final MessageMetrics messageMetrics;
@@ -160,38 +150,25 @@ public class MessageController {
private static final CompletableFuture<?>[] EMPTY_FUTURE_ARRAY = new CompletableFuture<?>[0];
private static final String REJECT_OVERSIZE_MESSAGE_COUNTER = name(MessageController.class, "rejectOversizeMessage");
private static final String LARGE_BUT_NOT_OVERSIZE_MESSAGE_COUNTER = name(MessageController.class, "largeMessage");
private static final String SENT_MESSAGE_COUNTER_NAME = name(MessageController.class, "sentMessages");
private static final String CONTENT_SIZE_DISTRIBUTION_NAME = MetricsUtil.name(MessageController.class, "messageContentSize");
private static final String OUTGOING_MESSAGE_LIST_SIZE_BYTES_DISTRIBUTION_NAME = name(MessageController.class, "outgoingMessageListSizeBytes");
private static final String RATE_LIMITED_MESSAGE_COUNTER_NAME = name(MessageController.class, "rateLimitedMessage");
private static final String SEND_MESSAGE_LATENCY_TIMER_NAME = MetricsUtil.name(MessageController.class, "sendMessageLatency");
private static final Timer INDIVIDUAL_MESSAGE_LATENCY_TIMER;
private static final Timer MULTI_RECIPIENT_MESSAGE_LATENCY_TIMER;
private static final String EPHEMERAL_TAG_NAME = "ephemeral";
private static final String SENDER_TYPE_TAG_NAME = "senderType";
private static final String AUTH_TYPE_TAG_NAME = "authType";
private static final String SENDER_COUNTRY_TAG_NAME = "senderCountry";
private static final String RATE_LIMIT_REASON_TAG_NAME = "rateLimitReason";
private static final String IDENTITY_TYPE_TAG_NAME = "identityType";
private static final String ENDPOINT_TYPE_TAG_NAME = "endpoint";
static {
final String timerName = MetricsUtil.name(MessageController.class, "sendMessageLatency");
final String multiRecipientTagName = "multiRecipient";
private static final String SENDER_TYPE_IDENTIFIED = "identified";
private static final String SENDER_TYPE_UNIDENTIFIED = "unidentified";
private static final String SENDER_TYPE_SELF = "self";
INDIVIDUAL_MESSAGE_LATENCY_TIMER = Timer.builder(timerName)
.tags(multiRecipientTagName, "false")
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry);
private static final String AUTH_TYPE_IDENTIFIED = "identified";
private static final String AUTH_TYPE_ACCESS_KEY = "accessKey";
private static final String AUTH_TYPE_GROUP_SEND_TOKEN = "groupSendToken";
private static final String AUTH_TYPE_STORY = "story";
private static final String ENDPOINT_TYPE_SINGLE = "single";
private static final String ENDPOINT_TYPE_MULTI = "multi";
@VisibleForTesting
static final int MAX_MESSAGE_SIZE = (int) DataSize.kibibytes(256).toBytes();
private static final long LARGE_MESSAGE_SIZE = DataSize.kibibytes(8).toBytes();
MULTI_RECIPIENT_MESSAGE_LATENCY_TIMER = Timer.builder(timerName)
.tags(multiRecipientTagName, "true")
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry);
}
// 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
@@ -213,7 +190,6 @@ public class MessageController {
ReportMessageManager reportMessageManager,
Scheduler messageDeliveryScheduler,
final ClientReleaseManager clientReleaseManager,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final ServerSecretParams serverSecretParams,
final SpamChecker spamChecker,
final MessageMetrics messageMetrics,
@@ -231,7 +207,6 @@ public class MessageController {
this.reportMessageManager = reportMessageManager;
this.messageDeliveryScheduler = messageDeliveryScheduler;
this.clientReleaseManager = clientReleaseManager;
this.dynamicConfigurationManager = dynamicConfigurationManager;
this.serverSecretParams = serverSecretParams;
this.spamChecker = spamChecker;
this.messageMetrics = messageMetrics;
@@ -259,10 +234,10 @@ public class MessageController {
description="The message is not a story and some the recipient service ID does not correspond to a registered Signal user")
@ApiResponse(
responseCode = "409", description = "Incorrect set of devices supplied for recipient",
content = @Content(schema = @Schema(implementation = MismatchedDevices.class)))
content = @Content(schema = @Schema(implementation = MismatchedDevicesResponse.class)))
@ApiResponse(
responseCode = "410", description = "Mismatched registration ids supplied for some recipient devices",
content = @Content(schema = @Schema(implementation = StaleDevices.class)))
content = @Content(schema = @Schema(implementation = StaleDevicesResponse.class)))
@ApiResponse(
responseCode="428",
description="The sender should complete a challenge before proceeding")
@@ -300,13 +275,11 @@ public class MessageController {
}
}
final String senderType = source.map(
s -> s.getAccount().isIdentifiedBy(destinationIdentifier) ? SENDER_TYPE_SELF : SENDER_TYPE_IDENTIFIED)
.orElse(SENDER_TYPE_UNIDENTIFIED);
final Sample sample = Timer.start();
try {
final boolean isSyncMessage = senderType.equals(SENDER_TYPE_SELF);
final boolean isSyncMessage =
source.map(s -> s.getAccount().isIdentifiedBy(destinationIdentifier)).orElse(false);
if (isSyncMessage && destinationIdentifier.identityType() == IdentityType.PNI) {
throw new WebApplicationException(Status.FORBIDDEN);
@@ -319,31 +292,35 @@ public class MessageController {
maybeDestination = source.map(AuthenticatedDevice::getAccount);
}
final SpamChecker.SpamCheckResult spamCheck = spamChecker.checkForSpam(
context, source, maybeDestination, Optional.of(destinationIdentifier));
final Optional<byte[]> reportSpamToken;
switch (spamCheck) {
case final SpamChecker.Spam spam: return spam.response();
case final SpamChecker.NotSpam notSpam: reportSpamToken = notSpam.token();
final MessageType messageType;
if (isStory) {
messageType = MessageType.INDIVIDUAL_STORY;
} else if (isSyncMessage) {
messageType = MessageType.SYNC;
} else if (source.isPresent()) {
messageType = MessageType.INDIVIDUAL_IDENTIFIED_SENDER;
} else {
messageType = MessageType.INDIVIDUAL_SEALED_SENDER;
}
int totalContentLength = 0;
final SpamCheckResult<Response> spamCheckResult =
spamChecker.checkForIndividualRecipientSpamHttp(messageType, context, source, maybeDestination, destinationIdentifier);
for (final IncomingMessage message : messages.messages()) {
final int contentLength = decodedSize(message.content());
validateContentLength(contentLength, false, isSyncMessage, isStory, userAgent);
totalContentLength += contentLength;
if (spamCheckResult.response().isPresent()) {
return spamCheckResult.response().get();
}
final Optional<byte[]> reportSpamToken = spamCheckResult.token();
try {
final int totalContentLength =
messages.messages().stream().mapToInt(message -> message.content().length).sum();
rateLimiters.getInboundMessageBytes().validate(destinationIdentifier.uuid(), totalContentLength);
} catch (final RateLimitExceededException e) {
if (dynamicConfigurationManager.getConfiguration().getInboundMessageByteLimitConfiguration().enforceInboundLimit()) {
messageByteLimitEstimator.add(destinationIdentifier.uuid().toString());
throw e;
}
messageByteLimitEstimator.add(destinationIdentifier.uuid().toString());
throw e;
}
try {
@@ -373,21 +350,13 @@ public class MessageController {
final Account destination = maybeDestination.orElseThrow();
if (source.isPresent() && !isSyncMessage) {
checkMessageRateLimit(source.get(), destination, userAgent);
rateLimiters.getMessagesLimiter().validate(source.get().getAccount().getUuid(), destination.getUuid());
}
if (isStory) {
rateLimiters.getStoriesLimiter().validate(destination.getUuid());
}
final Set<Byte> excludedDeviceIds;
if (isSyncMessage) {
excludedDeviceIds = Set.of(source.get().getAuthenticatedDevice().getId());
} else {
excludedDeviceIds = Collections.emptySet();
}
final Map<Byte, Envelope> messagesByDeviceId = messages.messages().stream()
.collect(Collectors.toMap(IncomingMessage::destinationDeviceId, message -> {
try {
@@ -406,55 +375,30 @@ public class MessageController {
}
}));
DestinationDeviceValidator.validateCompleteDeviceList(destination,
messagesByDeviceId.keySet(),
excludedDeviceIds);
final Map<Byte, Integer> registrationIdsByDeviceId = messages.messages().stream()
.collect(Collectors.toMap(IncomingMessage::destinationDeviceId, IncomingMessage::destinationRegistrationId));
DestinationDeviceValidator.validateRegistrationIds(destination,
messages.messages(),
IncomingMessage::destinationDeviceId,
IncomingMessage::destinationRegistrationId,
destination.getPhoneNumberIdentifier().equals(destinationIdentifier.uuid()));
final String authType;
if (SENDER_TYPE_IDENTIFIED.equals(senderType)) {
authType = AUTH_TYPE_IDENTIFIED;
} else if (isStory) {
authType = AUTH_TYPE_STORY;
} else if (groupSendToken != null) {
authType = AUTH_TYPE_GROUP_SEND_TOKEN;
} else {
authType = AUTH_TYPE_ACCESS_KEY;
}
messageSender.sendMessages(destination, messagesByDeviceId);
Metrics.counter(SENT_MESSAGE_COUNTER_NAME, List.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(ENDPOINT_TYPE_TAG_NAME, ENDPOINT_TYPE_SINGLE),
Tag.of(EPHEMERAL_TAG_NAME, String.valueOf(messages.online())),
Tag.of(SENDER_TYPE_TAG_NAME, senderType),
Tag.of(AUTH_TYPE_TAG_NAME, authType),
Tag.of(IDENTITY_TYPE_TAG_NAME, destinationIdentifier.identityType().name())))
.increment(messagesByDeviceId.size());
messageSender.sendMessages(destination, destinationIdentifier, messagesByDeviceId, registrationIdsByDeviceId, userAgent);
return Response.ok(new SendMessageResponse(needsSync)).build();
} catch (final MismatchedDevicesException e) {
throw new WebApplicationException(Response.status(409)
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new MismatchedDevices(e.getMissingDevices(),
e.getExtraDevices()))
.build());
} catch (final StaleDevicesException e) {
throw new WebApplicationException(Response.status(410)
.type(MediaType.APPLICATION_JSON)
.entity(new StaleDevices(e.getStaleDevices()))
.build());
if (!e.getMismatchedDevices().staleDeviceIds().isEmpty()) {
throw new WebApplicationException(Response.status(410)
.type(MediaType.APPLICATION_JSON)
.entity(new StaleDevicesResponse(e.getMismatchedDevices().staleDeviceIds()))
.build());
} else {
throw new WebApplicationException(Response.status(409)
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new MismatchedDevicesResponse(e.getMismatchedDevices().missingDeviceIds(),
e.getMismatchedDevices().extraDeviceIds()))
.build());
}
} catch (final MessageTooLargeException e) {
throw new WebApplicationException(Status.REQUEST_ENTITY_TOO_LARGE);
}
} finally {
sample.stop(Timer.builder(SEND_MESSAGE_LATENCY_TIMER_NAME)
.tags(SENDER_TYPE_TAG_NAME, senderType)
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry));
sample.stop(INDIVIDUAL_MESSAGE_LATENCY_TIMER);
}
}
@@ -521,10 +465,6 @@ public class MessageController {
throw new BadRequestException("Recipient list is empty");
}
// Verify that the message isn't too large before performing more expensive validations
multiRecipientMessage.getRecipients().values().forEach(recipient ->
validateContentLength(multiRecipientMessage.messageSizeForRecipient(recipient), true, false, isStory, userAgent));
// Check that the request is well-formed and doesn't contain repeated entries for the same device for the same
// recipient
{
@@ -543,185 +483,144 @@ public class MessageController {
}
}
final SpamChecker.SpamCheckResult spamCheck = spamChecker.checkForSpam(context, Optional.empty(), Optional.empty(), Optional.empty());
if (spamCheck instanceof final SpamChecker.Spam spam) {
return spam.response();
}
if (groupSendToken == null && accessKeys == null && !isStory) {
throw new NotAuthorizedException("A group send endorsement token or unidentified access key is required for non-story messages");
}
if (groupSendToken != null) {
if (accessKeys != null) {
throw new BadRequestException("Only one of group send endorsement token and unidentified access key may be provided");
} else if (isStory) {
throw new BadRequestException("Stories should not provide a group send endorsement token");
}
}
if (groupSendToken != null) {
// Group send endorsements are checked before we even attempt to resolve any accounts, since
// the lists of service IDs in the envelope are all that we need to check against
checkGroupSendToken(multiRecipientMessage.getRecipients().keySet(), groupSendToken);
}
// At this point, the caller has at least superficially provided the information needed to send a multi-recipient
// message. Attempt to resolve the destination service identifiers to Signal accounts.
final Map<SealedSenderMultiRecipientMessage.Recipient, Account> resolvedRecipients =
Flux.fromIterable(multiRecipientMessage.getRecipients().entrySet())
.flatMap(serviceIdAndRecipient -> {
final ServiceIdentifier serviceIdentifier =
ServiceIdentifier.fromLibsignal(serviceIdAndRecipient.getKey());
return Mono.fromFuture(() -> accountsManager.getByServiceIdentifierAsync(serviceIdentifier))
.flatMap(Mono::justOrEmpty)
.switchIfEmpty(isStory || groupSendToken != null ? Mono.empty() : Mono.error(NotFoundException::new))
.map(account -> Tuples.of(serviceIdAndRecipient.getValue(), account));
}, MAX_FETCH_ACCOUNT_CONCURRENCY)
.collectMap(Tuple2::getT1, Tuple2::getT2)
.blockOptional()
.orElse(Collections.emptyMap());
// Access keys are checked against the UAK in the resolved accounts, so we have to check after resolving accounts above.
// Group send endorsements are checked earlier; for stories, we don't check permissions at all because only clients check them
if (groupSendToken == null && !isStory) {
checkAccessKeys(accessKeys, multiRecipientMessage, resolvedRecipients);
}
// We might filter out all the recipients of a story (if none exist).
// In this case there is no error so we should just return 200 now.
if (isStory) {
if (resolvedRecipients.isEmpty()) {
return Response.ok(new SendMultiRecipientMessageResponse(List.of())).build();
}
try {
CompletableFuture.allOf(resolvedRecipients.values()
.stream()
.map(account -> account.getIdentifier(IdentityType.ACI))
.map(accountIdentifier ->
rateLimiters.getStoriesLimiter().validateAsync(accountIdentifier).toCompletableFuture())
.toList()
.toArray(EMPTY_FUTURE_ARRAY))
.join();
} catch (final Exception e) {
if (ExceptionUtils.unwrap(e) instanceof RateLimitExceededException rateLimitExceededException) {
throw rateLimitExceededException;
} else {
throw ExceptionUtils.wrap(e);
}
}
}
final Collection<AccountMismatchedDevices> accountMismatchedDevices = new ArrayList<>();
final Collection<AccountStaleDevices> accountStaleDevices = new ArrayList<>();
multiRecipientMessage.getRecipients().forEach((serviceId, recipient) -> {
if (!resolvedRecipients.containsKey(recipient)) {
// When sending stories, we might not be able to resolve all recipients to existing accounts. That's okay! We
// can just skip them.
return;
}
final Account account = resolvedRecipients.get(recipient);
try {
final Map<Byte, Short> deviceIdsToRegistrationIds = recipient.getDevicesAndRegistrationIds()
.collect(Collectors.toMap(Pair<Byte, Short>::first, Pair<Byte, Short>::second));
DestinationDeviceValidator.validateCompleteDeviceList(account, deviceIdsToRegistrationIds.keySet(),
Collections.emptySet());
DestinationDeviceValidator.validateRegistrationIds(
account,
deviceIdsToRegistrationIds.entrySet(),
Map.Entry<Byte, Short>::getKey,
e -> Integer.valueOf(e.getValue()),
serviceId instanceof ServiceId.Pni);
} catch (final MismatchedDevicesException e) {
accountMismatchedDevices.add(
new AccountMismatchedDevices(
ServiceIdentifier.fromLibsignal(serviceId),
new MismatchedDevices(e.getMissingDevices(), e.getExtraDevices())));
} catch (final StaleDevicesException e) {
accountStaleDevices.add(
new AccountStaleDevices(ServiceIdentifier.fromLibsignal(serviceId), new StaleDevices(e.getStaleDevices())));
}
});
if (!accountMismatchedDevices.isEmpty()) {
return Response
.status(409)
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(accountMismatchedDevices)
.build();
}
if (!accountStaleDevices.isEmpty()) {
return Response
.status(410)
.type(MediaType.APPLICATION_JSON)
.entity(accountStaleDevices)
.build();
}
final String authType;
if (isStory) {
authType = AUTH_TYPE_STORY;
} else if (groupSendToken != null) {
authType = AUTH_TYPE_GROUP_SEND_TOKEN;
} else {
authType = AUTH_TYPE_ACCESS_KEY;
}
final Timer.Sample sample = Timer.start();
try {
if (!resolvedRecipients.isEmpty()) {
messageSender.sendMultiRecipientMessage(multiRecipientMessage, resolvedRecipients, timestamp, isStory, online, isUrgent).get();
final SpamCheckResult<Response> spamCheckResult = spamChecker.checkForMultiRecipientSpamHttp(
isStory ? MessageType.MULTI_RECIPIENT_STORY : MessageType.MULTI_RECIPIENT_SEALED_SENDER,
context);
if (spamCheckResult.response().isPresent()) {
return spamCheckResult.response().get();
}
final List<ServiceIdentifier> unresolvedRecipientServiceIds;
if (AUTH_TYPE_GROUP_SEND_TOKEN.equals(authType)) {
unresolvedRecipientServiceIds = multiRecipientMessage.getRecipients().entrySet().stream()
.filter(entry -> !resolvedRecipients.containsKey(entry.getValue()))
.map(entry -> ServiceIdentifier.fromLibsignal(entry.getKey()))
.toList();
} else {
unresolvedRecipientServiceIds = List.of();
if (groupSendToken == null && accessKeys == null && !isStory) {
throw new NotAuthorizedException("A group send endorsement token or unidentified access key is required for non-story messages");
}
if (groupSendToken != null) {
if (accessKeys != null) {
throw new BadRequestException("Only one of group send endorsement token and unidentified access key may be provided");
} else if (isStory) {
throw new BadRequestException("Stories should not provide a group send endorsement token");
}
}
multiRecipientMessage.getRecipients().forEach((serviceId, recipient) -> {
if (!resolvedRecipients.containsKey(recipient)) {
// We skipped sending to this recipient because we couldn't resolve the recipient to an
// existing account; don't increment the counter for this recipient. If the client was
// using a GSE, track the missing recipients to include in the response.
return;
if (groupSendToken != null) {
// Group send endorsements are checked before we even attempt to resolve any accounts, since
// the lists of service IDs in the envelope are all that we need to check against
checkGroupSendToken(multiRecipientMessage.getRecipients().keySet(), groupSendToken);
}
// At this point, the caller has at least superficially provided the information needed to send a multi-recipient
// message. Attempt to resolve the destination service identifiers to Signal accounts.
final Map<SealedSenderMultiRecipientMessage.Recipient, Account> resolvedRecipients =
Flux.fromIterable(multiRecipientMessage.getRecipients().entrySet())
.flatMap(serviceIdAndRecipient -> {
final ServiceIdentifier serviceIdentifier =
ServiceIdentifier.fromLibsignal(serviceIdAndRecipient.getKey());
return Mono.fromFuture(() -> accountsManager.getByServiceIdentifierAsync(serviceIdentifier))
.flatMap(Mono::justOrEmpty)
.switchIfEmpty(isStory || groupSendToken != null ? Mono.empty() : Mono.error(NotFoundException::new))
.map(account -> Tuples.of(serviceIdAndRecipient.getValue(), account));
}, MAX_FETCH_ACCOUNT_CONCURRENCY)
.collectMap(Tuple2::getT1, Tuple2::getT2)
.blockOptional()
.orElse(Collections.emptyMap());
// Access keys are checked against the UAK in the resolved accounts, so we have to check after resolving accounts above.
// Group send endorsements are checked earlier; for stories, we don't check permissions at all because only clients check them
if (groupSendToken == null && !isStory) {
checkAccessKeys(accessKeys, multiRecipientMessage, resolvedRecipients);
}
// We might filter out all the recipients of a story (if none exist).
// In this case there is no error so we should just return 200 now.
if (isStory) {
if (resolvedRecipients.isEmpty()) {
return Response.ok(new SendMultiRecipientMessageResponse(List.of())).build();
}
final String identityType = switch (serviceId) {
case ServiceId.Aci ignored -> "ACI";
case ServiceId.Pni ignored -> "PNI";
default -> "unknown";
};
try {
CompletableFuture.allOf(resolvedRecipients.values()
.stream()
.map(account -> account.getIdentifier(IdentityType.ACI))
.map(accountIdentifier ->
rateLimiters.getStoriesLimiter().validateAsync(accountIdentifier).toCompletableFuture())
.toList()
.toArray(EMPTY_FUTURE_ARRAY))
.join();
} catch (final Exception e) {
if (ExceptionUtils.unwrap(e) instanceof RateLimitExceededException rateLimitExceededException) {
throw rateLimitExceededException;
} else {
throw ExceptionUtils.wrap(e);
}
}
}
Metrics.counter(SENT_MESSAGE_COUNTER_NAME, Tags.of(
UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(ENDPOINT_TYPE_TAG_NAME, ENDPOINT_TYPE_MULTI),
Tag.of(EPHEMERAL_TAG_NAME, String.valueOf(online)),
Tag.of(SENDER_TYPE_TAG_NAME, SENDER_TYPE_UNIDENTIFIED),
Tag.of(AUTH_TYPE_TAG_NAME, authType),
Tag.of(IDENTITY_TYPE_TAG_NAME, identityType)))
.increment(recipient.getDevices().length);
});
try {
if (!resolvedRecipients.isEmpty()) {
messageSender.sendMultiRecipientMessage(multiRecipientMessage, resolvedRecipients, timestamp, isStory, online, isUrgent, userAgent).get();
}
return Response.ok(new SendMultiRecipientMessageResponse(unresolvedRecipientServiceIds)).build();
} catch (InterruptedException e) {
logger.error("interrupted while delivering multi-recipient messages", e);
throw new InternalServerErrorException("interrupted during delivery");
} catch (CancellationException e) {
logger.error("cancelled while delivering multi-recipient messages", e);
throw new InternalServerErrorException("delivery cancelled");
} catch (ExecutionException e) {
logger.error("partial failure while delivering multi-recipient messages", e.getCause());
throw new InternalServerErrorException("failure during delivery");
final List<ServiceIdentifier> unresolvedRecipientServiceIds;
if (groupSendToken != null) {
unresolvedRecipientServiceIds = multiRecipientMessage.getRecipients().entrySet().stream()
.filter(entry -> !resolvedRecipients.containsKey(entry.getValue()))
.map(entry -> ServiceIdentifier.fromLibsignal(entry.getKey()))
.toList();
} else {
unresolvedRecipientServiceIds = List.of();
}
return Response.ok(new SendMultiRecipientMessageResponse(unresolvedRecipientServiceIds)).build();
} catch (InterruptedException e) {
logger.error("interrupted while delivering multi-recipient messages", e);
throw new InternalServerErrorException("interrupted during delivery");
} catch (CancellationException e) {
logger.error("cancelled while delivering multi-recipient messages", e);
throw new InternalServerErrorException("delivery cancelled");
} catch (ExecutionException e) {
logger.error("partial failure while delivering multi-recipient messages", e.getCause());
throw new InternalServerErrorException("failure during delivery");
} catch (MultiRecipientMismatchedDevicesException e) {
final List<AccountMismatchedDevices> accountMismatchedDevices =
e.getMismatchedDevicesByServiceIdentifier().entrySet().stream()
.filter(entry -> !entry.getValue().missingDeviceIds().isEmpty() || !entry.getValue().extraDeviceIds().isEmpty())
.map(entry -> new AccountMismatchedDevices(entry.getKey(),
new MismatchedDevicesResponse(entry.getValue().missingDeviceIds(), entry.getValue().extraDeviceIds())))
.toList();
if (!accountMismatchedDevices.isEmpty()) {
return Response
.status(409)
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(accountMismatchedDevices)
.build();
}
final List<AccountStaleDevices> accountStaleDevices =
e.getMismatchedDevicesByServiceIdentifier().entrySet().stream()
.filter(entry -> !entry.getValue().staleDeviceIds().isEmpty())
.map(entry -> new AccountStaleDevices(entry.getKey(),
new StaleDevicesResponse(entry.getValue().staleDeviceIds())))
.toList();
if (!accountStaleDevices.isEmpty()) {
return Response
.status(410)
.type(MediaType.APPLICATION_JSON)
.entity(accountStaleDevices)
.build();
}
throw new RuntimeException(e);
} catch (final MessageTooLargeException e) {
throw new WebApplicationException(Status.REQUEST_ENTITY_TOO_LARGE);
}
} finally {
sample.stop(MULTI_RECIPIENT_MESSAGE_LATENCY_TIMER);
}
}
@@ -912,70 +811,4 @@ public class MessageController {
return Response.status(Status.ACCEPTED)
.build();
}
private void checkMessageRateLimit(AuthenticatedDevice source, Account destination, String userAgent)
throws RateLimitExceededException {
final String senderCountryCode = Util.getCountryCode(source.getAccount().getNumber());
try {
rateLimiters.getMessagesLimiter().validate(source.getAccount().getUuid(), destination.getUuid());
} catch (final RateLimitExceededException e) {
Metrics.counter(RATE_LIMITED_MESSAGE_COUNTER_NAME,
Tags.of(
UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(SENDER_COUNTRY_TAG_NAME, senderCountryCode),
Tag.of(RATE_LIMIT_REASON_TAG_NAME, "singleDestinationRate"))).increment();
throw e;
}
}
private void validateContentLength(final int contentLength,
final boolean isMultiRecipientMessage,
final boolean isSyncMessage,
final boolean isStory,
final String userAgent) {
final boolean oversize = contentLength > MAX_MESSAGE_SIZE;
DistributionSummary.builder(CONTENT_SIZE_DISTRIBUTION_NAME)
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of("oversize", String.valueOf(oversize)),
Tag.of("multiRecipientMessage", String.valueOf(isMultiRecipientMessage)),
Tag.of("syncMessage", String.valueOf(isSyncMessage)),
Tag.of("story", String.valueOf(isStory))))
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry)
.record(contentLength);
if (oversize) {
Metrics.counter(REJECT_OVERSIZE_MESSAGE_COUNTER, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of("multiRecipientMessage", String.valueOf(isMultiRecipientMessage)),
Tag.of("syncMessage", String.valueOf(isSyncMessage)),
Tag.of("story", String.valueOf(isStory))))
.increment();
throw new WebApplicationException(Status.REQUEST_ENTITY_TOO_LARGE);
}
if (contentLength > LARGE_MESSAGE_SIZE) {
Metrics.counter(
LARGE_BUT_NOT_OVERSIZE_MESSAGE_COUNTER,
Tags.of(UserAgentTagUtil.getPlatformTag(userAgent), Tag.of("multiRecipientMessage", String.valueOf(isMultiRecipientMessage))))
.increment();
}
}
@VisibleForTesting
static int decodedSize(final String base64) {
final int padding;
if (StringUtils.endsWith(base64, "==")) {
padding = 2;
} else if (StringUtils.endsWith(base64, "=")) {
padding = 1;
} else {
padding = 0;
}
return ((StringUtils.length(base64) - padding) * 3) / 4;
}
}
@@ -0,0 +1,11 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.controllers;
import java.util.Set;
public record MismatchedDevices(Set<Byte> missingDeviceIds, Set<Byte> extraDeviceIds, Set<Byte> staleDeviceIds) {
}
@@ -5,23 +5,15 @@
package org.whispersystems.textsecuregcm.controllers;
import java.util.List;
public class MismatchedDevicesException extends Exception {
private final List<Byte> missingDevices;
private final List<Byte> extraDevices;
private final MismatchedDevices mismatchedDevices;
public MismatchedDevicesException(List<Byte> missingDevices, List<Byte> extraDevices) {
this.missingDevices = missingDevices;
this.extraDevices = extraDevices;
public MismatchedDevicesException(final MismatchedDevices mismatchedDevices) {
this.mismatchedDevices = mismatchedDevices;
}
public List<Byte> getMissingDevices() {
return missingDevices;
}
public List<Byte> getExtraDevices() {
return extraDevices;
public MismatchedDevices getMismatchedDevices() {
return mismatchedDevices;
}
}
@@ -0,0 +1,24 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.controllers;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import java.util.Map;
public class MultiRecipientMismatchedDevicesException extends Exception {
private final Map<ServiceIdentifier, MismatchedDevices> mismatchedDevicesByServiceIdentifier;
public MultiRecipientMismatchedDevicesException(
final Map<ServiceIdentifier, MismatchedDevices> mismatchedDevicesByServiceIdentifier) {
this.mismatchedDevicesByServiceIdentifier = mismatchedDevicesByServiceIdentifier;
}
public Map<ServiceIdentifier, MismatchedDevices> getMismatchedDevicesByServiceIdentifier() {
return mismatchedDevicesByServiceIdentifier;
}
}
@@ -9,8 +9,8 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.base.Preconditions;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
@@ -79,6 +79,7 @@ import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.s3.PolicySigner;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.storage.Account;
@@ -121,7 +122,7 @@ public class ProfileController {
private static final String EXPIRING_PROFILE_KEY_CREDENTIAL_TYPE = "expiringProfileKey";
private static final Counter VERSION_NOT_FOUND_COUNTER = Metrics.counter(name(ProfileController.class, "versionNotFound"));
private static final String VERSION_NOT_FOUND_COUNTER_NAME = name(ProfileController.class, "versionNotFound");
public ProfileController(
Clock clock,
@@ -237,6 +238,7 @@ public class ProfileController {
return buildVersionedProfileResponse(targetAccount,
version,
maybeRequester.map(requester -> ProfileHelper.isSelfProfileRequest(requester.getUuid(), accountIdentifier)).orElse(false),
false,
containerRequestContext);
}
@@ -390,20 +392,27 @@ public class ProfileController {
.orElse(null);
return new ExpiringProfileKeyCredentialProfileResponse(
buildVersionedProfileResponse(account, version, isSelf, containerRequestContext),
buildVersionedProfileResponse(account, version, isSelf, true, containerRequestContext),
expiringProfileKeyCredentialResponse);
}
private VersionedProfileResponse buildVersionedProfileResponse(final Account account,
final String version,
final boolean isSelf,
final boolean hasCredentialRequest,
final ContainerRequestContext containerRequestContext) {
final Optional<VersionedProfile> maybeProfile = profilesManager.get(account.getUuid(), version);
if (maybeProfile.isEmpty()) {
// Hypothesis: this should basically never happen since clients can't delete versions
VERSION_NOT_FOUND_COUNTER.increment();
Metrics.counter(
VERSION_NOT_FOUND_COUNTER_NAME,
Tags.of(
"self", String.valueOf(isSelf),
"credential_request", String.valueOf(hasCredentialRequest),
"platform", UserAgentTagUtil.getPlatformTag(containerRequestContext.getHeaderString("User-Agent")).getValue()))
.increment();
}
final byte[] name = maybeProfile.map(VersionedProfile::name).orElse(null);
@@ -36,6 +36,7 @@ import java.util.Optional;
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
import org.whispersystems.textsecuregcm.entities.AccountCreationResponse;
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
@@ -100,7 +101,7 @@ public class RegistrationController {
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
name = "Retry-After",
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
public AccountIdentityResponse register(
public AccountCreationResponse register(
@HeaderParam(HttpHeaders.AUTHORIZATION) @NotNull final BasicAuthorizationHeader authorizationHeader,
@HeaderParam(HeaderUtils.X_SIGNAL_AGENT) final String signalAgent,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@@ -166,12 +167,14 @@ public class RegistrationController {
Tag.of(VERIFICATION_TYPE_TAG_NAME, verificationType.name())))
.increment();
return new AccountIdentityResponseBuilder(account)
final AccountIdentityResponse identityResponse = new AccountIdentityResponseBuilder(account)
// If there was an existing account, return whether it could have had something in the storage service
.storageCapable(existingAccount
.map(a -> a.hasCapability(DeviceCapability.STORAGE))
.orElse(false))
.build();
return new AccountCreationResponse(identityResponse, existingAccount.isPresent());
}
}
@@ -1,22 +0,0 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.controllers;
import java.util.List;
public class StaleDevicesException extends Exception {
private final List<Byte> staleDevices;
public StaleDevicesException(List<Byte> staleDevices) {
this.staleDevices = staleDevices;
}
public List<Byte> getStaleDevices() {
return staleDevices;
}
}
@@ -0,0 +1,32 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import io.swagger.v3.oas.annotations.media.Schema;
// Note, this class cannot be converted into a record because @JsonUnwrapped does not work with records until 2.19. We are on 2.18 until Dropwizard’s BOM updates.
// https://github.com/FasterXML/jackson-databind/issues/1467
public class AccountCreationResponse {
@JsonUnwrapped
private AccountIdentityResponse identityResponse;
@Schema(description = "If true, there was an existing account registered for this number")
private boolean reregistration;
public AccountCreationResponse() {
}
public AccountCreationResponse(AccountIdentityResponse identityResponse, boolean reregistration) {
this.identityResponse = identityResponse;
this.reregistration = reregistration;
}
public boolean isReregistration() {
return reregistration;
}
}
@@ -14,5 +14,5 @@ public record AccountMismatchedDevices(@JsonSerialize(using = ServiceIdentifierA
@JsonDeserialize(using = ServiceIdentifierAdapter.ServiceIdentifierDeserializer.class)
ServiceIdentifier uuid,
MismatchedDevices devices) {
MismatchedDevicesResponse devices) {
}
@@ -14,5 +14,5 @@ public record AccountStaleDevices(@JsonSerialize(using = ServiceIdentifierAdapte
@JsonDeserialize(using = ServiceIdentifierAdapter.ServiceIdentifierDeserializer.class)
ServiceIdentifier uuid,
StaleDevices devices) {
StaleDevicesResponse devices) {
}
@@ -4,18 +4,31 @@
*/
package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.google.protobuf.ByteString;
import com.webauthn4j.converter.jackson.deserializer.json.ByteArrayBase64Deserializer;
import io.micrometer.core.instrument.Metrics;
import jakarta.validation.constraints.AssertTrue;
import java.util.Base64;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.storage.Account;
import java.util.Arrays;
import java.util.Objects;
public record IncomingMessage(int type, byte destinationDeviceId, int destinationRegistrationId, String content) {
public record IncomingMessage(int type,
byte destinationDeviceId,
int destinationRegistrationId,
@JsonDeserialize(using = ByteArrayBase64Deserializer.class)
@NotNull
// Note that max size is validated elsewhere in the interest of controlling responses and
// reporting additional metrics.
@Size(min = 1)
byte[] content) {
private static final String REJECT_INVALID_ENVELOPE_TYPE_COUNTER_NAME =
MetricsUtil.name(IncomingMessage.class, "rejectInvalidEnvelopeType");
@@ -50,9 +63,7 @@ public record IncomingMessage(int type, byte destinationDeviceId, int destinatio
envelopeBuilder.setReportSpamToken(ByteString.copyFrom(reportSpamToken));
}
if (StringUtils.isNotEmpty(content())) {
envelopeBuilder.setContent(ByteString.copyFrom(Base64.getDecoder().decode(content())));
}
envelopeBuilder.setContent(ByteString.copyFrom(content()));
return envelopeBuilder.build();
}
@@ -69,4 +80,17 @@ public record IncomingMessage(int type, byte destinationDeviceId, int destinatio
return true;
}
@Override
public boolean equals(final Object o) {
if (!(o instanceof IncomingMessage(int otherType, byte otherDeviceId, int otherRegistrationId, byte[] otherContent)))
return false;
return type == otherType && destinationDeviceId == otherDeviceId
&& destinationRegistrationId == otherRegistrationId && Objects.deepEquals(content, otherContent);
}
@Override
public int hashCode() {
return Objects.hash(type, destinationDeviceId, destinationRegistrationId, Arrays.hashCode(content));
}
}
@@ -1,20 +0,0 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.List;
public record MismatchedDevices(@JsonProperty
@Schema(description = "Devices present on the account but absent in the request")
List<Byte> missingDevices,
@JsonProperty
@Schema(description = "Devices absent on the request but present in the account")
List<Byte> extraDevices) {
}
@@ -0,0 +1,20 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.Set;
public record MismatchedDevicesResponse(@JsonProperty
@Schema(description = "Devices present on the account but absent in the request")
Set<Byte> missingDevices,
@JsonProperty
@Schema(description = "Devices absent on the request but present in the account")
Set<Byte> extraDevices) {
}
@@ -8,9 +8,9 @@ package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.List;
import java.util.Set;
public record StaleDevices(@JsonProperty
@Schema(description = "Devices that are no longer active")
List<Byte> staleDevices) {
public record StaleDevicesResponse(@JsonProperty
@Schema(description = "Devices that are no longer active")
Set<Byte> staleDevices) {
}
@@ -1,51 +0,0 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.experiment;
import org.whispersystems.textsecuregcm.push.ZeroTtlNotificationScheduler;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.workers.IdleWakeupEligibilityChecker;
import java.time.LocalTime;
import java.util.concurrent.CompletableFuture;
public class ZeroTtlPushNotificationExperiment extends IdleDevicePushNotificationExperiment {
private static final LocalTime PREFERRED_NOTIFICATION_TIME = LocalTime.of(14, 0);
private final ZeroTtlNotificationScheduler zeroTtlNotificationScheduler;
public ZeroTtlPushNotificationExperiment(
final IdleWakeupEligibilityChecker idleWakeupEligibilityChecker,
final ZeroTtlNotificationScheduler zeroTtlNotificationScheduler) {
super(idleWakeupEligibilityChecker);
this.zeroTtlNotificationScheduler = zeroTtlNotificationScheduler;
}
@Override
boolean isIdleDeviceEligible(final Account account, final Device idleDevice, final DeviceLastSeenState state) {
return state.pushTokenType() == DeviceLastSeenState.PushTokenType.FCM;
}
@Override
public String getExperimentName() {
return "zero-ttl-notification";
}
@Override
public Class<DeviceLastSeenState> getStateClass() {
return DeviceLastSeenState.class;
}
@Override
public CompletableFuture<Void> applyExperimentTreatment(final Account account, final Device device) {
return zeroTtlNotificationScheduler.scheduleNotification(account, device, PREFERRED_NOTIFICATION_TIME, true);
}
@Override
public CompletableFuture<Void> applyControlTreatment(final Account account, final Device device) {
return zeroTtlNotificationScheduler.scheduleNotification(account, device, PREFERRED_NOTIFICATION_TIME, false);
}
}
@@ -18,7 +18,7 @@ import org.whispersystems.textsecuregcm.util.HttpServletRequestUtil;
/**
* Sets a {@link HttpServletRequest} attribute (that will also be available as a
* {@link javax.ws.rs.container.ContainerRequestContext} property) with the remote address of the connection, using
* {@link jakarta.ws.rs.container.ContainerRequestContext} property) with the remote address of the connection, using
* {@link HttpServletRequest#getRemoteAddr()}.
*/
public class RemoteAddressFilter implements Filter {
@@ -1,102 +0,0 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.geo;
import com.maxmind.db.CHMCache;
import com.maxmind.geoip2.DatabaseReader;
import io.dropwizard.lifecycle.Managed;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.configuration.S3ObjectMonitorFactory;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.s3.S3ObjectMonitor;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
public class MaxMindDatabaseManager implements Supplier<DatabaseReader>, Managed {
private final S3ObjectMonitor databaseMonitor;
private final AtomicReference<DatabaseReader> databaseReader = new AtomicReference<>();
private final String databaseTag;
private final Timer refreshTimer;
private static final Logger log = LoggerFactory.getLogger(MaxMindDatabaseManager.class);
public MaxMindDatabaseManager(final ScheduledExecutorService executorService,
final AwsCredentialsProvider awsCredentialsProvider, final S3ObjectMonitorFactory configuration,
final String databaseTag) {
this.databaseMonitor = configuration.build(awsCredentialsProvider, executorService);
this.databaseTag = databaseTag;
this.refreshTimer = Metrics.timer(MetricsUtil.name(MaxMindDatabaseManager.class, "refresh"), "db", databaseTag);
}
private void handleDatabaseChanged(final InputStream inputStream) {
refreshTimer.record(() -> {
boolean foundDatabaseEntry = false;
try (final InputStream bufferedInputStream = new BufferedInputStream(inputStream);
final GzipCompressorInputStream gzipInputStream = new GzipCompressorInputStream(bufferedInputStream);
final TarArchiveInputStream tarInputStream = new TarArchiveInputStream(gzipInputStream)) {
ArchiveEntry nextEntry;
while ((nextEntry = tarInputStream.getNextEntry()) != null) {
if (nextEntry.getName().toLowerCase().endsWith(".mmdb")) {
foundDatabaseEntry = true;
final DatabaseReader oldReader = databaseReader.getAndSet(
new DatabaseReader.Builder(tarInputStream).withCache(new CHMCache()).build()
);
if (oldReader != null) {
oldReader.close();
}
break;
}
}
} catch (final IOException e) {
log.error(String.format("Failed to load MaxMind database, tag %s", databaseTag));
}
if (!foundDatabaseEntry) {
log.warn(String.format("No .mmdb entry loaded from input stream, tag %s", databaseTag));
}
});
}
@Override
public void start() throws Exception {
databaseMonitor.start(this::handleDatabaseChanged);
}
@Override
public void stop() throws Exception {
databaseMonitor.stop();
final DatabaseReader reader = databaseReader.getAndSet(null);
if (reader != null) {
reader.close();
}
}
@Override
public DatabaseReader get() {
return this.databaseReader.get();
}
}
@@ -8,6 +8,9 @@ import com.google.protobuf.ByteString;
import io.grpc.Status;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import org.signal.chat.backup.CopyMediaRequest;
import org.signal.chat.backup.CopyMediaResponse;
import org.signal.chat.backup.DeleteAllRequest;
@@ -36,15 +39,22 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
import org.whispersystems.textsecuregcm.backup.BackupManager;
import org.whispersystems.textsecuregcm.backup.CopyParameters;
import org.whispersystems.textsecuregcm.backup.MediaEncryptionParameters;
import org.whispersystems.textsecuregcm.controllers.ArchiveController;
import org.whispersystems.textsecuregcm.metrics.BackupMetrics;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
public class BackupsAnonymousGrpcService extends ReactorBackupsAnonymousGrpc.BackupsAnonymousImplBase {
private final BackupManager backupManager;
private final BackupMetrics backupMetrics;
public BackupsAnonymousGrpcService(final BackupManager backupManager) {
public BackupsAnonymousGrpcService(final BackupManager backupManager, final BackupMetrics backupMetrics) {
this.backupManager = backupManager;
this.backupMetrics = backupMetrics;
}
@Override
@@ -115,6 +125,9 @@ public class BackupsAnonymousGrpcService extends ReactorBackupsAnonymousGrpc.Bac
fromUnsignedExact(item.getObjectLength()),
new MediaEncryptionParameters(item.getEncryptionKey().toByteArray(), item.getHmacKey().toByteArray()),
item.getMediaId().toByteArray())).toList()))
.doOnNext(result -> backupMetrics.updateCopyCounter(
result,
UserAgentTagUtil.getPlatformTag(RequestAttributesUtil.getUserAgent().orElse(null))))
.map(copyResult -> {
CopyMediaResponse.Builder builder = CopyMediaResponse
.newBuilder()
@@ -9,6 +9,9 @@ import io.grpc.Status;
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,18 +27,25 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
import org.whispersystems.textsecuregcm.controllers.ArchiveController;
import org.whispersystems.textsecuregcm.metrics.BackupMetrics;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import reactor.core.publisher.Mono;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
public class BackupsGrpcService extends ReactorBackupsGrpc.BackupsImplBase {
private final AccountsManager accountManager;
private final BackupAuthManager backupAuthManager;
private final BackupMetrics backupMetrics;
public BackupsGrpcService(final AccountsManager accountManager, final BackupAuthManager backupAuthManager) {
public BackupsGrpcService(final AccountsManager accountManager, final BackupAuthManager backupAuthManager, final BackupMetrics backupMetrics) {
this.accountManager = accountManager;
this.backupAuthManager = backupAuthManager;
this.backupMetrics = backupMetrics;
}
@@ -67,19 +77,26 @@ public class BackupsGrpcService extends ReactorBackupsGrpc.BackupsImplBase {
@Override
public Mono<GetBackupAuthCredentialsResponse> getBackupAuthCredentials(GetBackupAuthCredentialsRequest request) {
final Tag platformTag = UserAgentTagUtil.getPlatformTag(RequestAttributesUtil.getUserAgent().orElse(null));
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())));
Instant.ofEpochSecond(request.getRedemptionStop())))
.doOnSuccess(credentials ->
backupMetrics.updateGetCredentialCounter(platformTag, BackupCredentialType.MESSAGES, credentials.size()));
final Mono<List<BackupAuthManager.Credential>> mediaCredentials = Mono.fromCompletionStage(() ->
backupAuthManager.getBackupAuthCredentials(
account,
BackupCredentialType.MEDIA,
Instant.ofEpochSecond(request.getRedemptionStart()),
Instant.ofEpochSecond(request.getRedemptionStop())));
Instant.ofEpochSecond(request.getRedemptionStop())))
.doOnSuccess(credentials ->
backupMetrics.updateGetCredentialCounter(platformTag, BackupCredentialType.MEDIA, credentials.size()));
return messageCredentials.zipWith(mediaCredentials, (messageCreds, mediaCreds) ->
GetBackupAuthCredentialsResponse.newBuilder()
@@ -18,8 +18,8 @@ public class DeviceCapabilityUtil {
case DEVICE_CAPABILITY_STORAGE -> DeviceCapability.STORAGE;
case DEVICE_CAPABILITY_TRANSFER -> DeviceCapability.TRANSFER;
case DEVICE_CAPABILITY_DELETE_SYNC -> DeviceCapability.DELETE_SYNC;
case DEVICE_CAPABILITY_VERSIONED_EXPIRATION_TIMER -> DeviceCapability.VERSIONED_EXPIRATION_TIMER;
case DEVICE_CAPABILITY_STORAGE_SERVICE_RECORD_KEY_ROTATION -> DeviceCapability.STORAGE_SERVICE_RECORD_KEY_ROTATION;
case DEVICE_CAPABILITY_ATTACHMENT_BACKFILL -> DeviceCapability.ATTACHMENT_BACKFILL;
case DEVICE_CAPABILITY_UNSPECIFIED, UNRECOGNIZED -> throw Status.INVALID_ARGUMENT.withDescription("Unrecognized device capability").asRuntimeException();
};
}
@@ -29,8 +29,8 @@ public class DeviceCapabilityUtil {
case STORAGE -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_STORAGE;
case TRANSFER -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_TRANSFER;
case DELETE_SYNC -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_DELETE_SYNC;
case VERSIONED_EXPIRATION_TIMER -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_VERSIONED_EXPIRATION_TIMER;
case STORAGE_SERVICE_RECORD_KEY_ROTATION -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_STORAGE_SERVICE_RECORD_KEY_ROTATION;
case ATTACHMENT_BACKFILL -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_ATTACHMENT_BACKFILL;
};
}
}
@@ -59,6 +59,15 @@ public class RequestAttributesInterceptor implements ServerInterceptor {
}
}
{
final Optional<String> maybeRawUserAgent =
grpcClientConnectionManager.getRawUserAgent(localAddress);
if (maybeRawUserAgent.isPresent()) {
context = context.withValue(RequestAttributesUtil.RAW_USER_AGENT_CONTEXT_KEY, maybeRawUserAgent.get());
}
}
{
final Optional<UserAgent> maybeUserAgent = grpcClientConnectionManager.getUserAgent(localAddress);
@@ -13,7 +13,8 @@ public class RequestAttributesUtil {
static final Context.Key<List<Locale.LanguageRange>> ACCEPT_LANGUAGE_CONTEXT_KEY = Context.key("accept-language");
static final Context.Key<InetAddress> REMOTE_ADDRESS_CONTEXT_KEY = Context.key("remote-address");
static final Context.Key<UserAgent> USER_AGENT_CONTEXT_KEY = Context.key("user-agent");
static final Context.Key<String> RAW_USER_AGENT_CONTEXT_KEY = Context.key("unparsed-user-agent");
static final Context.Key<UserAgent> USER_AGENT_CONTEXT_KEY = Context.key("parsed-user-agent");
private static final List<Locale> AVAILABLE_LOCALES = Arrays.asList(Locale.getAvailableLocales());
@@ -51,9 +52,18 @@ public class RequestAttributesUtil {
/**
* Returns the parsed user-agent of the remote client in the current gRPC request context.
*
* @return the parsed user-agent of the remote client; may be null if unparseable or not specified
* @return the parsed user-agent of the remote client; may be empty if unparseable or not specified
*/
public static Optional<UserAgent> getUserAgent() {
return Optional.ofNullable(USER_AGENT_CONTEXT_KEY.get());
}
/**
* Returns the unparsed user-agent of the remote client in the current gRPC request context.
*
* @return the unparsed user-agent of the remote client; may be empty if not specified
*/
public static Optional<String> getRawUserAgent() {
return Optional.ofNullable(RAW_USER_AGENT_CONTEXT_KEY.get());
}
}
@@ -106,7 +106,21 @@ public class GrpcClientConnectionManager implements DisconnectionRequestListener
}
/**
* Returns the parsed user agent provided by the client the opened the connection associated with the given local
* Returns the unparsed user agent provided by the client that opened the connection associated with the given local
* address. This method may return an empty value if no active local connection is associated with the given local
* address.
*
* @param localAddress the local address for which to find a User-Agent string
*
* @return the user agent string associated with the given local address
*/
public Optional<String> getRawUserAgent(final LocalAddress localAddress) {
return Optional.ofNullable(remoteChannelsByLocalAddress.get(localAddress))
.map(remoteChannel -> remoteChannel.attr(RAW_USER_AGENT_ATTRIBUTE_KEY).get());
}
/**
* Returns the parsed user agent provided by the client that opened the connection associated with the given local
* address. This method may return an empty value if no active local connection is associated with the given local
* address or if the client's user-agent string was not recognized.
*
@@ -15,12 +15,14 @@ import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.util.Util;
import static io.lettuce.core.ExpireArgs.Builder.nx;
/**
* Estimate the number of unique items seen over a configurable period and update a metric
*/
public class CardinalityEstimator {
private volatile double uniqueElementCount;
private volatile long uniqueElementCount;
private final FaultTolerantRedisClusterClient redisCluster;
private final String hllName;
private final Duration period;
@@ -36,41 +38,29 @@ public class CardinalityEstimator {
obj -> obj.uniqueElementCount);
}
public void add(String element) {
public void add(final String element) {
addAsync(element).toCompletableFuture().join();
}
public CompletionStage<Void> addAsync(String element) {
public CompletionStage<Void> addAsync(final String element) {
return redisCluster.withCluster(connection -> connection.async()
.pfadd(hllName, element)
.thenCompose(modCount -> {
if (modCount == 0) {
return CompletableFuture.completedFuture(false);
// The hll hasn't changed - return our current view of cardinality
return CompletableFuture.completedFuture(uniqueElementCount);
}
// The hll changed - update our local view of the cardinality, and
// initialize the TTL if required
return connection.async()
.pfcount(hllName)
.thenCompose(count -> {
uniqueElementCount = count;
// check if this is a new hll with no TTL set
return connection.async().ttl(hllName).thenApply(ttl -> ttl == -1);
});
return connection.async().pfcount(hllName);
})
.thenCompose(isNewHll -> {
if (!isNewHll) {
return CompletableFuture.completedFuture(null);
}
// If this is a new hll, we need to set the TTL. This could be
// a single atomic op in redis 7.x with EXPIRE NX
return connection.async().expire(hllName, period).thenRun(Util.NOOP);
.thenCompose(newUniqueElementCount -> {
uniqueElementCount = newUniqueElementCount;
return connection.async().expire(hllName, period, nx()).thenRun(Util.NOOP);
}));
}
@VisibleForTesting
long estimate() {
return (long) this.uniqueElementCount;
return this.uniqueElementCount;
}
}
@@ -0,0 +1,21 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.limits;
public enum RateLimitChallengeOption {
CAPTCHA("captcha"),
PUSH_CHALLENGE("pushChallenge");
private final String apiName;
RateLimitChallengeOption(final String apiName) {
this.apiName = apiName;
}
public String getApiName() {
return apiName;
}
}
@@ -13,26 +13,23 @@ public class RateLimitChallengeOptionManager {
private final RateLimiters rateLimiters;
public static final String OPTION_CAPTCHA = "captcha";
public static final String OPTION_PUSH_CHALLENGE = "pushChallenge";
public RateLimitChallengeOptionManager(final RateLimiters rateLimiters) {
this.rateLimiters = rateLimiters;
}
public List<String> getChallengeOptions(final Account account) {
final List<String> options = new ArrayList<>(2);
public List<RateLimitChallengeOption> getChallengeOptions(final Account account) {
final List<RateLimitChallengeOption> options = new ArrayList<>(2);
if (rateLimiters.getCaptchaChallengeAttemptLimiter().hasAvailablePermits(account.getUuid(), 1) &&
rateLimiters.getCaptchaChallengeSuccessLimiter().hasAvailablePermits(account.getUuid(), 1)) {
options.add(OPTION_CAPTCHA);
options.add(RateLimitChallengeOption.CAPTCHA);
}
if (rateLimiters.getPushChallengeAttemptLimiter().hasAvailablePermits(account.getUuid(), 1) &&
rateLimiters.getPushChallengeSuccessLimiter().hasAvailablePermits(account.getUuid(), 1)) {
options.add(OPTION_PUSH_CHALLENGE);
options.add(RateLimitChallengeOption.PUSH_CHALLENGE);
}
return options;
@@ -41,7 +41,8 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
RATE_LIMIT_RESET("rateLimitReset", true, new RateLimiterConfig(2, Duration.ofHours(12))),
CAPTCHA_CHALLENGE_ATTEMPT("captchaChallengeAttempt", true, new RateLimiterConfig(10, Duration.ofMinutes(144))),
CAPTCHA_CHALLENGE_SUCCESS("captchaChallengeSuccess", true, new RateLimiterConfig(2, Duration.ofHours(12))),
SET_BACKUP_ID("setBackupId", true, new RateLimiterConfig(2, Duration.ofDays(7))),
SET_BACKUP_ID("setBackupId", true, new RateLimiterConfig(10, Duration.ofHours(1))),
SET_PAID_MEDIA_BACKUP_ID("setPaidMediaBackupId", true, new RateLimiterConfig(5, Duration.ofDays(7))),
PUSH_CHALLENGE_ATTEMPT("pushChallengeAttempt", true, new RateLimiterConfig(10, Duration.ofMinutes(144))),
PUSH_CHALLENGE_SUCCESS("pushChallengeSuccess", true, new RateLimiterConfig(2, Duration.ofHours(12))),
GET_CALLING_RELAYS("getCallingRelays", false, new RateLimiterConfig(100, Duration.ofMinutes(10))),
@@ -0,0 +1,51 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.metrics;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
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 org.signal.libsignal.zkgroup.backups.BackupCredentialType;
import org.whispersystems.textsecuregcm.backup.CopyResult;
public class BackupMetrics {
private final static String COPY_MEDIA_COUNTER_NAME = name(BackupMetrics.class, "copyMedia");
private final static String GET_BACKUP_CREDENTIALS_NAME = name(BackupMetrics.class, "getBackupCredentials");
private MeterRegistry registry;
public BackupMetrics() {
this(Metrics.globalRegistry);
}
@VisibleForTesting
BackupMetrics(MeterRegistry registry) {
this.registry = registry;
}
public void updateCopyCounter(final CopyResult copyResult, final Tag platformTag) {
registry.counter(COPY_MEDIA_COUNTER_NAME, Tags.of(
platformTag,
Tag.of("outcome", copyResult.outcome().name().toLowerCase())))
.increment();
}
public void updateGetCredentialCounter(final Tag platformTag, BackupCredentialType credentialType,
final int numCredentials) {
Metrics.counter(GET_BACKUP_CREDENTIALS_NAME, Tags.of(
platformTag,
Tag.of("num", Integer.toString(numCredentials)),
Tag.of("type", credentialType.name().toLowerCase())))
.increment();
}
}
@@ -34,7 +34,7 @@ import org.whispersystems.textsecuregcm.util.logging.UriInfoUtil;
/**
* Gathers and reports HTTP request metrics at the Jetty container level, which sits above Jersey. In order to get
* templated Jersey request paths, it implements {@link javax.ws.rs.container.ContainerResponseFilter}, in order to give
* templated Jersey request paths, it implements {@link jakarta.ws.rs.container.ContainerResponseFilter}, in order to give
* itself access to the template. It is limited to {@link TrafficSource#HTTP} requests.
* <p>
* It implements {@link LifeCycle.Listener} without overriding methods, so that it can be an event listener that
@@ -137,15 +137,13 @@ public class MetricsHttpChannelListener implements HttpChannel.Listener, Contain
tags.add(Tag.of(METHOD_TAG, requestInfo.method()));
tags.add(Tag.of(STATUS_CODE_TAG, String.valueOf(requestInfo.statusCode())));
tags.add(Tag.of(TRAFFIC_SOURCE_TAG, TrafficSource.HTTP.name().toLowerCase()));
final Tag platformTag = UserAgentTagUtil.getPlatformTag(requestInfo.userAgent());
tags.add(platformTag);
tags.addAll(UserAgentTagUtil.getLibsignalAndPlatformTags(requestInfo.userAgent()));
meterRegistry.counter(REQUEST_COUNTER_NAME, tags).increment();
UserAgentTagUtil.getClientVersionTag(requestInfo.userAgent(), clientReleaseManager).ifPresent(
clientVersionTag -> meterRegistry.counter(REQUESTS_BY_VERSION_COUNTER_NAME,
Tags.of(clientVersionTag, platformTag)).increment());
Tags.of(clientVersionTag, UserAgentTagUtil.getPlatformTag(requestInfo.userAgent()))).increment());
}
@Override
@@ -12,6 +12,7 @@ import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.binder.jetty.JettySslHandshakeMetrics;
import io.micrometer.core.instrument.binder.jvm.JvmMemoryMetrics;
import io.micrometer.core.instrument.binder.jvm.JvmThreadMetrics;
import io.micrometer.core.instrument.binder.system.FileDescriptorMetrics;
@@ -72,6 +73,9 @@ public class MetricsUtil {
Metrics.addRegistry(dogstatsdMeterRegistry);
}
environment.lifecycle().addServerLifecycleListener(
server -> JettySslHandshakeMetrics.addToAllConnectors(server, Metrics.globalRegistry));
environment.lifecycle().addEventListener(new ApplicationShutdownMonitor(Metrics.globalRegistry));
environment.lifecycle().addEventListener(
new MicrometerRegistryManager(Metrics.globalRegistry,
@@ -79,7 +83,7 @@ public class MetricsUtil {
}
@VisibleForTesting
static MeterRegistry.Config configureMeterFilters(MeterRegistry.Config config,
static void configureMeterFilters(MeterRegistry.Config config,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
final DistributionStatisticConfig defaultDistributionStatisticConfig = DistributionStatisticConfig.builder()
.percentiles(.75, .95, .99, .999)
@@ -87,8 +91,7 @@ public class MetricsUtil {
final String awsSdkMetricNamePrefix = MetricsUtil.name(MicrometerAwsSdkMetricPublisher.class);
return config
.meterFilter(new MeterFilter() {
config.meterFilter(new MeterFilter() {
@Override
public DistributionStatisticConfig configure(final Meter.Id id, final DistributionStatisticConfig config) {
return defaultDistributionStatisticConfig.merge(config);
@@ -0,0 +1,112 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.metrics;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.Metrics;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.cert.Certificate;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Optional;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.util.security.CertificateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TlsCertificateExpirationUtil {
private static final Logger logger = LoggerFactory.getLogger(TlsCertificateExpirationUtil.class);
private static final String CERTIFICATE_EXPIRATION_GAUGE_NAME = name(TlsCertificateExpirationUtil.class,
"secondsUntilExpiration");
public static void configureMetrics(final String keyStorePath, final String keyStorePassword, final String keyStoreType, final String keyStoreProvider) {
final KeyStore keyStore;
try {
keyStore = CertificateUtils.getKeyStore(Resource.newResource(keyStorePath), keyStoreType, keyStoreProvider,
keyStorePassword);
} catch (Exception e) {
throw new RuntimeException("Failed to load keystore " + keyStorePath, e);
}
getIdentifiersAndExpirations(keyStore, keyStorePassword)
.forEach((id, expiration) ->
Gauge.builder(CERTIFICATE_EXPIRATION_GAUGE_NAME, expiration,
then -> Duration.between(Instant.now(), then).toSeconds())
.tags("id", id)
.strongReference(true)
.register(Metrics.globalRegistry)
);
}
@VisibleForTesting
static Map<String, Instant> getIdentifiersAndExpirations(final KeyStore keyStore, final String password) {
final Map<String, Instant> identifiersAndExpirations = new HashMap<>();
try {
for (final Iterator<String> it = keyStore.aliases().asIterator(); it.hasNext(); ) {
final Certificate certificate = keyStore.getCertificate(it.next());
if (certificate instanceof X509Certificate x509Certificate) {
final String name = getName(x509Certificate);
final String algorithm = x509Certificate.getPublicKey().getAlgorithm();
final Instant notAfter = Instant.ofEpochMilli(x509Certificate.getNotAfter().getTime());
final String identifier = name + ":" + algorithm;
identifiersAndExpirations.put(identifier, notAfter);
} else {
logger.warn("Unexpected certificate type: {}", certificate.getClass().getName());
}
}
} catch (final KeyStoreException e) {
// This should never happen - this exception is thrown if the keystore is not initialized, which
// CertificateUtils#getKeyStore does.
throw new RuntimeException("Failed to read keystore", e);
} catch (final CertificateParsingException e) {
throw new IllegalArgumentException("Failed to parse certificate", e);
}
return identifiersAndExpirations;
}
private static String getName(X509Certificate x509Certificate) throws CertificateParsingException {
return Optional.ofNullable(x509Certificate.getSubjectAlternativeNames())
.flatMap(sans -> sans.stream().findFirst())
.map(altNames -> {
// each list should be a tuple of
// alternative name type ID (integer), name
if (altNames.size() != 2) {
logger.warn("Unexpected subject alternative name: {}", altNames);
return null;
}
return switch ((Integer) altNames.getFirst()) {
case 2, 7 -> // dns, ip
altNames.getLast().toString();
default -> null;
};
})
.orElse("unknown");
}
}
@@ -8,10 +8,13 @@ package org.whispersystems.textsecuregcm.metrics;
import io.micrometer.core.instrument.Tag;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import org.whispersystems.textsecuregcm.WhisperServerVersion;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
import org.whispersystems.textsecuregcm.util.ua.UserAgent;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
import javax.annotation.Nullable;
/**
* Utility class for extracting platform/version metrics tags from User-Agent strings.
@@ -22,19 +25,30 @@ public class UserAgentTagUtil {
public static final String VERSION_TAG = "clientVersion";
public static final String LIBSIGNAL_TAG = "libsignal";
public static final String SERVER_UA =
String.format("Signal-Server/%s (%s)", WhisperServerVersion.getServerVersion(), UUID.randomUUID());
private UserAgentTagUtil() {
}
public static Tag getPlatformTag(final String userAgentString) {
String platform;
try {
platform = UserAgentUtil.parseUserAgentString(userAgentString).getPlatform().name().toLowerCase();
} catch (final UnrecognizedUserAgentException e) {
platform = "unrecognized";
if (SERVER_UA.equals(userAgentString)) {
return Tag.of(PLATFORM_TAG, "server");
}
return Tag.of(PLATFORM_TAG, platform);
UserAgent userAgent = null;
try {
userAgent = UserAgentUtil.parseUserAgentString(userAgentString);
} catch (final UnrecognizedUserAgentException ignored) {
}
return getPlatformTag(userAgent);
}
public static Tag getPlatformTag(@Nullable final UserAgent userAgent) {
return Tag.of(PLATFORM_TAG, userAgent != null ? userAgent.getPlatform().name().toLowerCase() : "unrecognized");
}
public static Optional<Tag> getClientVersionTag(final String userAgentString, final ClientReleaseManager clientReleaseManager) {
@@ -14,7 +14,6 @@ import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.ThreadManager;
import com.google.firebase.messaging.AndroidConfig;
import com.google.firebase.messaging.AndroidNotification;
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.FirebaseMessagingException;
import com.google.firebase.messaging.Message;
@@ -25,7 +24,6 @@ import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
@@ -80,24 +78,11 @@ public class FcmSender implements PushNotificationSender {
@Override
public CompletableFuture<SendPushNotificationResult> sendNotification(PushNotification pushNotification) {
final AndroidConfig.Builder androidConfig = AndroidConfig.builder()
.setPriority(pushNotification.urgent() ? AndroidConfig.Priority.HIGH : AndroidConfig.Priority.NORMAL);
// This experiment compares the effect of two standard push notifications to one standard + one with a TTL=0
switch (pushNotification.experimentalNotificationType().orElse(null)) {
case ZERO_TTL -> {
androidConfig.setTtl(0);
androidConfig.setCollapseKey("ttl0");
}
case NON_COLLAPSIBLE ->
// We still want to make sure we don't collapse notifications in the control group
androidConfig.setCollapseKey("ttl0");
case null -> {}
}
Message.Builder builder = Message.builder()
.setToken(pushNotification.deviceToken())
.setAndroidConfig(androidConfig.build());
.setAndroidConfig(AndroidConfig.builder()
.setPriority(pushNotification.urgent() ? AndroidConfig.Priority.HIGH : AndroidConfig.Priority.NORMAL)
.build());
final String key = switch (pushNotification.notificationType()) {
case NOTIFICATION -> "newMessageAlert";
@@ -119,12 +104,6 @@ public class FcmSender implements PushNotificationSender {
if (firebaseMessagingException.getMessagingErrorCode() != null) {
errorCode = firebaseMessagingException.getMessagingErrorCode().name();
if (firebaseMessagingException.getMessagingErrorCode() == MessagingErrorCode.QUOTA_EXCEEDED
&& firebaseMessagingException.getHttpResponse() != null) {
logger.info("FCM request failed with quota exceeded; retry-after: {}, response body: {}",
firebaseMessagingException.getHttpResponse().getHeaders().get("retry-after"),
firebaseMessagingException.getHttpResponse().getContent());
}
} else if (firebaseMessagingException.getHttpResponse() != null) {
errorCode = "http" + firebaseMessagingException.getHttpResponse().getStatusCode();
} else {
@@ -8,15 +8,34 @@ import static com.codahale.metrics.MetricRegistry.name;
import static org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.util.DataSize;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
import org.signal.libsignal.protocol.util.Pair;
import org.whispersystems.textsecuregcm.controllers.MessageController;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevices;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.controllers.MultiRecipientMismatchedDevicesException;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import org.whispersystems.textsecuregcm.util.Util;
import javax.annotation.Nullable;
/**
* A MessageSender sends Signal messages to destination devices. Messages may be "normal" user-to-user messages,
@@ -34,13 +53,23 @@ public class MessageSender {
private final MessagesManager messagesManager;
private final PushNotificationManager pushNotificationManager;
// Note that these names deliberately reference `MessageController` for metric continuity
private static final String REJECT_OVERSIZE_MESSAGE_COUNTER_NAME = name(MessageController.class, "rejectOversizeMessage");
private static final String CONTENT_SIZE_DISTRIBUTION_NAME = MetricsUtil.name(MessageController.class, "messageContentSize");
private static final String SEND_COUNTER_NAME = name(MessageSender.class, "sendMessage");
private static final String CHANNEL_TAG_NAME = "channel";
private static final String EPHEMERAL_TAG_NAME = "ephemeral";
private static final String CLIENT_ONLINE_TAG_NAME = "clientOnline";
private static final String URGENT_TAG_NAME = "urgent";
private static final String STORY_TAG_NAME = "story";
private static final String SEALED_SENDER_TAG_NAME = "sealedSender";
private static final String MULTI_RECIPIENT_TAG_NAME = "multiRecipient";
@VisibleForTesting
public static final int MAX_MESSAGE_SIZE = (int) DataSize.kibibytes(256).toBytes();
@VisibleForTesting
static final byte NO_EXCLUDED_DEVICE_ID = -1;
public MessageSender(final MessagesManager messagesManager, final PushNotificationManager pushNotificationManager) {
this.messagesManager = messagesManager;
@@ -52,29 +81,70 @@ public class MessageSender {
* notification token and does not have an active connection to a Signal server, then this method will also send a
* push notification to that device to announce the availability of new messages.
*
* @param account the account to which to send messages
* @param destination the account to which to send messages
* @param destinationIdentifier the service identifier to which the messages are addressed
* @param messagesByDeviceId a map of device IDs to message payloads
* @param registrationIdsByDeviceId a map of device IDs to device registration IDs
* @param userAgent the User-Agent string for the sender; may be {@code null} if not known
*
* @throws MismatchedDevicesException if the given bundle of messages did not include a message for all required
* devices, contained messages for devices not linked to the destination account, or devices with outdated
* registration IDs
* @throws MessageTooLargeException if the given message payload is too large
*/
public void sendMessages(final Account account, final Map<Byte, Envelope> messagesByDeviceId) {
messagesManager.insert(account.getIdentifier(IdentityType.ACI), messagesByDeviceId)
public void sendMessages(final Account destination,
final ServiceIdentifier destinationIdentifier,
final Map<Byte, Envelope> messagesByDeviceId,
final Map<Byte, Integer> registrationIdsByDeviceId,
@Nullable final String userAgent) throws MismatchedDevicesException, MessageTooLargeException {
if (messagesByDeviceId.isEmpty()) {
return;
}
if (!destination.isIdentifiedBy(destinationIdentifier)) {
throw new IllegalArgumentException("Destination account not identified by destination service identifier");
}
final Envelope firstMessage = messagesByDeviceId.values().iterator().next();
final boolean isSyncMessage = StringUtils.isNotBlank(firstMessage.getSourceServiceId()) &&
destination.isIdentifiedBy(ServiceIdentifier.valueOf(firstMessage.getSourceServiceId()));
final boolean isStory = firstMessage.getStory();
validateIndividualMessageContentLength(messagesByDeviceId.values(), isSyncMessage, isStory, userAgent);
final Optional<MismatchedDevices> maybeMismatchedDevices = getMismatchedDevices(destination,
destinationIdentifier,
registrationIdsByDeviceId,
isSyncMessage ? (byte) firstMessage.getSourceDevice() : NO_EXCLUDED_DEVICE_ID);
if (maybeMismatchedDevices.isPresent()) {
throw new MismatchedDevicesException(maybeMismatchedDevices.get());
}
messagesManager.insert(destination.getIdentifier(IdentityType.ACI), messagesByDeviceId)
.forEach((deviceId, destinationPresent) -> {
final Envelope message = messagesByDeviceId.get(deviceId);
if (!destinationPresent && !message.getEphemeral()) {
try {
pushNotificationManager.sendNewMessageNotification(account, deviceId, message.getUrgent());
pushNotificationManager.sendNewMessageNotification(destination, deviceId, message.getUrgent());
} catch (final NotPushRegisteredException ignored) {
}
}
Metrics.counter(SEND_COUNTER_NAME,
CHANNEL_TAG_NAME, account.getDevice(deviceId).map(MessageSender::getDeliveryChannelName).orElse("unknown"),
final Tags tags = Tags.of(
EPHEMERAL_TAG_NAME, String.valueOf(message.getEphemeral()),
CLIENT_ONLINE_TAG_NAME, String.valueOf(destinationPresent),
URGENT_TAG_NAME, String.valueOf(message.getUrgent()),
STORY_TAG_NAME, String.valueOf(message.getStory()),
SEALED_SENDER_TAG_NAME, String.valueOf(!message.hasSourceServiceId()))
.increment();
SEALED_SENDER_TAG_NAME, String.valueOf(!message.hasSourceServiceId()),
MULTI_RECIPIENT_TAG_NAME, "false")
.and(UserAgentTagUtil.getPlatformTag(userAgent));
Metrics.counter(SEND_COUNTER_NAME, tags).increment();
});
}
@@ -82,6 +152,10 @@ public class MessageSender {
* Sends messages to a group of recipients. If a destination device has a valid push notification token and does not
* have an active connection to a Signal server, then this method will also send a push notification to that device to
* announce the availability of new messages.
* <p>
* This method sends messages to all <em>resolved</em> recipients. In some cases, a caller may not be able to resolve
* all recipients to active accounts, but may still choose to send the message. Callers are responsible for rejecting
* the message if they require full resolution of all recipients, but some recipients could not be resolved.
*
* @param multiRecipientMessage the multi-recipient message to send to the given recipients
* @param resolvedRecipients a map of recipients to resolved Signal accounts
@@ -90,15 +164,48 @@ public class MessageSender {
* @param isEphemeral {@code true} if the message should only be delivered to devices with active connections or
* {@code false otherwise}
* @param isUrgent {@code true} if the message is urgent or {@code false otherwise}
* @param userAgent the User-Agent string for the sender; may be {@code null} if not known
*
* @return a future that completes when all messages have been inserted into delivery queues
*
* @throws MultiRecipientMismatchedDevicesException if the given multi-recipient message had did not have all required
* recipient devices for a recipient account, contained recipients for devices not linked to a destination account, or
* recipient devices with outdated registration IDs
* @throws MessageTooLargeException if the given message payload is too large
*/
public CompletableFuture<Void> sendMultiRecipientMessage(final SealedSenderMultiRecipientMessage multiRecipientMessage,
final Map<SealedSenderMultiRecipientMessage.Recipient, Account> resolvedRecipients,
final long clientTimestamp,
final boolean isStory,
final boolean isEphemeral,
final boolean isUrgent) {
final boolean isUrgent,
@Nullable final String userAgent) throws MultiRecipientMismatchedDevicesException, MessageTooLargeException {
validateMultiRecipientMessageContentLength(multiRecipientMessage, isStory, userAgent);
final Map<ServiceIdentifier, MismatchedDevices> mismatchedDevicesByServiceIdentifier = new HashMap<>();
multiRecipientMessage.getRecipients().forEach((serviceId, recipient) -> {
if (!resolvedRecipients.containsKey(recipient)) {
// Callers are responsible for rejecting messages if they're missing recipients in a problematic way. If we run
// into an unresolved recipient here, just skip it.
return;
}
final Account account = resolvedRecipients.get(recipient);
final ServiceIdentifier serviceIdentifier = ServiceIdentifier.fromLibsignal(serviceId);
final Map<Byte, Integer> registrationIdsByDeviceId = recipient.getDevicesAndRegistrationIds()
.collect(Collectors.toMap(Pair::first, pair -> (int) pair.second()));
getMismatchedDevices(account, serviceIdentifier, registrationIdsByDeviceId, NO_EXCLUDED_DEVICE_ID)
.ifPresent(mismatchedDevices ->
mismatchedDevicesByServiceIdentifier.put(serviceIdentifier, mismatchedDevices));
});
if (!mismatchedDevicesByServiceIdentifier.isEmpty()) {
throw new MultiRecipientMismatchedDevicesException(mismatchedDevicesByServiceIdentifier);
}
return messagesManager.insertMultiRecipientMessage(multiRecipientMessage, resolvedRecipients, clientTimestamp,
isStory, isEphemeral, isUrgent)
@@ -112,29 +219,117 @@ public class MessageSender {
}
}
Metrics.counter(SEND_COUNTER_NAME,
CHANNEL_TAG_NAME,
account.getDevice(deviceId).map(MessageSender::getDeliveryChannelName).orElse("unknown"),
final Tags tags = Tags.of(
EPHEMERAL_TAG_NAME, String.valueOf(isEphemeral),
CLIENT_ONLINE_TAG_NAME, String.valueOf(clientPresent),
URGENT_TAG_NAME, String.valueOf(isUrgent),
STORY_TAG_NAME, String.valueOf(isStory),
SEALED_SENDER_TAG_NAME, String.valueOf(true))
.increment();
SEALED_SENDER_TAG_NAME, "true",
MULTI_RECIPIENT_TAG_NAME, "true")
.and(UserAgentTagUtil.getPlatformTag(userAgent));
Metrics.counter(SEND_COUNTER_NAME, tags).increment();
})))
.thenRun(Util.NOOP);
}
@VisibleForTesting
static String getDeliveryChannelName(final Device device) {
if (device.getGcmId() != null) {
return "gcm";
} else if (device.getApnId() != null) {
return "apn";
} else if (device.getFetchesMessages()) {
return "websocket";
} else {
return "none";
static void validateContentLength(final int contentLength,
final boolean isMultiRecipientMessage,
final boolean isSyncMessage,
final boolean isStory,
final String userAgent) throws MessageTooLargeException {
final boolean oversize = contentLength > MAX_MESSAGE_SIZE;
DistributionSummary.builder(CONTENT_SIZE_DISTRIBUTION_NAME)
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of("oversize", String.valueOf(oversize)),
Tag.of("multiRecipientMessage", String.valueOf(isMultiRecipientMessage)),
Tag.of("syncMessage", String.valueOf(isSyncMessage)),
Tag.of("story", String.valueOf(isStory))))
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry)
.record(contentLength);
if (oversize) {
Metrics.counter(REJECT_OVERSIZE_MESSAGE_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of("multiRecipientMessage", String.valueOf(isMultiRecipientMessage)),
Tag.of("syncMessage", String.valueOf(isSyncMessage)),
Tag.of("story", String.valueOf(isStory))))
.increment();
throw new MessageTooLargeException();
}
}
@VisibleForTesting
static Optional<MismatchedDevices> getMismatchedDevices(final Account account,
final ServiceIdentifier serviceIdentifier,
final Map<Byte, Integer> registrationIdsByDeviceId,
final byte excludedDeviceId) {
final Set<Byte> accountDeviceIds = account.getDevices().stream()
.map(Device::getId)
.filter(deviceId -> deviceId != excludedDeviceId)
.collect(Collectors.toSet());
final Set<Byte> missingDeviceIds = new HashSet<>(accountDeviceIds);
missingDeviceIds.removeAll(registrationIdsByDeviceId.keySet());
final Set<Byte> extraDeviceIds = new HashSet<>(registrationIdsByDeviceId.keySet());
extraDeviceIds.removeAll(accountDeviceIds);
final Set<Byte> staleDeviceIds = registrationIdsByDeviceId.entrySet().stream()
// Filter out device IDs that aren't associated with the given account
.filter(entry -> !extraDeviceIds.contains(entry.getKey()))
.filter(entry -> {
final byte deviceId = entry.getKey();
final int registrationId = entry.getValue();
// We know the device must be present because we've already filtered out device IDs that aren't associated
// with the given account
final Device device = account.getDevice(deviceId).orElseThrow();
final int expectedRegistrationId = switch (serviceIdentifier.identityType()) {
case ACI -> device.getRegistrationId();
case PNI -> device.getPhoneNumberIdentityRegistrationId().orElseGet(device::getRegistrationId);
};
return registrationId != expectedRegistrationId;
})
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
return (!missingDeviceIds.isEmpty() || !extraDeviceIds.isEmpty() || !staleDeviceIds.isEmpty())
? Optional.of(new MismatchedDevices(missingDeviceIds, extraDeviceIds, staleDeviceIds))
: Optional.empty();
}
private static void validateIndividualMessageContentLength(final Iterable<Envelope> messages,
final boolean isSyncMessage,
final boolean isStory,
@Nullable final String userAgent) throws MessageTooLargeException {
for (final Envelope message : messages) {
MessageSender.validateContentLength(message.getContent().size(),
false,
isSyncMessage,
isStory,
userAgent);
}
}
private static void validateMultiRecipientMessageContentLength(final SealedSenderMultiRecipientMessage multiRecipientMessage,
final boolean isStory,
@Nullable final String userAgent) throws MessageTooLargeException {
for (final SealedSenderMultiRecipientMessage.Recipient recipient : multiRecipientMessage.getRecipients().values()) {
MessageSender.validateContentLength(multiRecipientMessage.messageSizeForRecipient(recipient),
true,
false,
isStory,
userAgent);
}
}
}
@@ -0,0 +1,11 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.push;
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
public class MessageTooLargeException extends NoStackTraceException {
}
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.push;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import javax.annotation.Nullable;
import java.util.Optional;
public record PushNotification(String deviceToken,
TokenType tokenType,
@@ -16,8 +15,7 @@ public record PushNotification(String deviceToken,
@Nullable String data,
@Nullable Account destination,
@Nullable Device destinationDevice,
boolean urgent,
Optional<ExperimentalNotificationType> experimentalNotificationType) {
boolean urgent) {
public enum NotificationType {
NOTIFICATION,
@@ -30,9 +28,4 @@ public record PushNotification(String deviceToken,
FCM,
APN
}
public enum ExperimentalNotificationType {
ZERO_TTL,
NON_COLLAPSIBLE
}
}
@@ -51,21 +51,11 @@ public class PushNotificationManager {
final Pair<String, PushNotification.TokenType> tokenAndType = getToken(device);
return sendNotification(new PushNotification(tokenAndType.first(), tokenAndType.second(),
PushNotification.NotificationType.NOTIFICATION, null, destination, device, urgent, Optional.empty()));
}
public CompletableFuture<Optional<SendPushNotificationResult>> sendExperimentMessageNotification(
final Account destination, final byte destinationDeviceId, final boolean urgent, PushNotification.ExperimentalNotificationType experimentalNotificationType) throws NotPushRegisteredException {
final Device device = destination.getDevice(destinationDeviceId).orElseThrow(NotPushRegisteredException::new);
final Pair<String, PushNotification.TokenType> tokenAndType = getToken(device);
return sendNotification(new PushNotification(tokenAndType.first(), tokenAndType.second(),
PushNotification.NotificationType.NOTIFICATION,
null, destination, device, urgent, Optional.of(experimentalNotificationType)));
PushNotification.NotificationType.NOTIFICATION, null, destination, device, urgent));
}
public CompletableFuture<SendPushNotificationResult> sendRegistrationChallengeNotification(final String deviceToken, final PushNotification.TokenType tokenType, final String challengeToken) {
return sendNotification(new PushNotification(deviceToken, tokenType, PushNotification.NotificationType.CHALLENGE, challengeToken, null, null, true, Optional.empty()))
return sendNotification(new PushNotification(deviceToken, tokenType, PushNotification.NotificationType.CHALLENGE, challengeToken, null, null, true))
.thenApply(maybeResponse -> maybeResponse.orElseThrow(() -> new AssertionError("Responses must be present for urgent notifications")));
}
@@ -76,7 +66,7 @@ public class PushNotificationManager {
final Pair<String, PushNotification.TokenType> tokenAndType = getToken(device);
return sendNotification(new PushNotification(tokenAndType.first(), tokenAndType.second(),
PushNotification.NotificationType.RATE_LIMIT_CHALLENGE, challengeToken, destination, device, true, Optional.empty()))
PushNotification.NotificationType.RATE_LIMIT_CHALLENGE, challengeToken, destination, device, true))
.thenApply(maybeResponse -> maybeResponse.orElseThrow(() -> new AssertionError("Responses must be present for urgent notifications")));
}
@@ -86,7 +76,7 @@ public class PushNotificationManager {
return sendNotification(new PushNotification(tokenAndType.first(), tokenAndType.second(),
PushNotification.NotificationType.ATTEMPT_LOGIN_NOTIFICATION_HIGH_PRIORITY,
context, destination, device, true, Optional.empty()))
context, destination, device, true))
.thenApply(maybeResponse -> maybeResponse.orElseThrow(() -> new AssertionError("Responses must be present for urgent notifications")));
}
@@ -286,7 +286,7 @@ public class PushNotificationScheduler implements Managed {
return pushSchedulingCluster.withCluster(connection -> connection.async().set(
getLastBackgroundApnsNotificationTimestampKey(account, device),
String.valueOf(clock.millis()), new SetArgs().ex(BACKGROUND_NOTIFICATION_PERIOD)))
.thenCompose(ignored -> apnSender.sendNotification(new PushNotification(device.getApnId(), PushNotification.TokenType.APN, PushNotification.NotificationType.NOTIFICATION, null, account, device, false, Optional.empty())))
.thenCompose(ignored -> apnSender.sendNotification(new PushNotification(device.getApnId(), PushNotification.TokenType.APN, PushNotification.NotificationType.NOTIFICATION, null, account, device, false)))
.thenAccept(response -> Metrics.counter(BACKGROUND_NOTIFICATION_SENT_COUNTER_NAME,
ACCEPTED_TAG, String.valueOf(response.accepted()))
.increment())
@@ -308,8 +308,7 @@ public class PushNotificationScheduler implements Managed {
null,
account,
device,
true,
Optional.empty());
true);
final PushNotificationSender pushNotificationSender = isApnsDevice ? apnSender : fcmSender;
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.push;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.binder.jvm.ExecutorServiceMetrics;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;
import org.slf4j.Logger;
@@ -15,6 +16,7 @@ import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
@@ -54,9 +56,21 @@ public class ReceiptSender {
.setUrgent(false)
.build();
final Map<Byte, Envelope> messagesByDeviceId = destinationAccount.getDevices().stream()
.collect(Collectors.toMap(Device::getId, ignored -> message));
final Map<Byte, Integer> registrationIdsByDeviceId = destinationAccount.getDevices().stream()
.collect(Collectors.toMap(Device::getId, device -> switch (destinationIdentifier.identityType()) {
case ACI -> device.getRegistrationId();
case PNI -> device.getPhoneNumberIdentityRegistrationId().orElseGet(device::getRegistrationId);
}));
try {
messageSender.sendMessages(destinationAccount, destinationAccount.getDevices().stream()
.collect(Collectors.toMap(Device::getId, ignored -> message)));
messageSender.sendMessages(destinationAccount,
destinationIdentifier,
messagesByDeviceId,
registrationIdsByDeviceId,
UserAgentTagUtil.SERVER_UA);
} catch (final Exception e) {
logger.warn("Could not send delivery receipt", e);
}
@@ -1,103 +0,0 @@
package org.whispersystems.textsecuregcm.push;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.annotations.VisibleForTesting;
import java.io.IOException;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalTime;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.scheduler.JobScheduler;
import org.whispersystems.textsecuregcm.scheduler.SchedulingUtil;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
public class ZeroTtlNotificationScheduler extends JobScheduler {
private final AccountsManager accountsManager;
private final PushNotificationManager pushNotificationManager;
private final Clock clock;
@VisibleForTesting
record JobDescriptor(UUID accountIdentifier, byte deviceId, long lastSeen, boolean zeroTtl) {}
public ZeroTtlNotificationScheduler(
final AccountsManager accountsManager,
final PushNotificationManager pushNotificationManager,
final DynamoDbAsyncClient dynamoDbAsyncClient,
final String tableName,
final Duration jobExpiration,
final Clock clock) {
super(dynamoDbAsyncClient, tableName, jobExpiration, clock);
this.accountsManager = accountsManager;
this.pushNotificationManager = pushNotificationManager;
this.clock = clock;
}
@Override
public String getSchedulerName() {
return "ZeroTtlNotification";
}
@Override
protected CompletableFuture<String> processJob(@Nullable final byte[] jobData) {
final JobDescriptor jobDescriptor;
try {
jobDescriptor = SystemMapper.jsonMapper().readValue(jobData, JobDescriptor.class);
} catch (final IOException e) {
return CompletableFuture.failedFuture(e);
}
return accountsManager.getByAccountIdentifierAsync(jobDescriptor.accountIdentifier())
.thenCompose(maybeAccount -> maybeAccount.map(account ->
account.getDevice(jobDescriptor.deviceId()).map(device -> {
if (jobDescriptor.lastSeen() != device.getLastSeen()) {
return CompletableFuture.completedFuture("deviceSeenRecently");
}
try {
return sendNotification(account, jobDescriptor).thenApply(ignored -> "sent");
} catch (final NotPushRegisteredException e) {
return CompletableFuture.completedFuture("deviceTokenDeleted");
}
})
.orElse(CompletableFuture.completedFuture("deviceDeleted")))
.orElse(CompletableFuture.completedFuture("accountDeleted")));
}
private CompletableFuture<Void> sendNotification(final Account account,
final JobDescriptor jobDescriptor) throws NotPushRegisteredException {
final CompletableFuture<Optional<SendPushNotificationResult>> standardNotification = pushNotificationManager.sendNewMessageNotification(
account, jobDescriptor.deviceId(), true);
final CompletableFuture<Optional<SendPushNotificationResult>> experimentNotification = pushNotificationManager.sendExperimentMessageNotification(
account, jobDescriptor.deviceId(), true, jobDescriptor.zeroTtl()
? PushNotification.ExperimentalNotificationType.ZERO_TTL
: PushNotification.ExperimentalNotificationType.NON_COLLAPSIBLE);
return standardNotification.thenCombine(experimentNotification, (ignored1, ignored2) -> null);
}
public CompletableFuture<Void> scheduleNotification(final Account account, final Device device,
final LocalTime preferredDeliveryTime, boolean zeroTtl) {
final Instant runAt = SchedulingUtil.getNextRecommendedNotificationTime(account, preferredDeliveryTime, clock);
try {
return scheduleJob(runAt, SystemMapper.jsonMapper().writeValueAsBytes(
new JobDescriptor(account.getIdentifier(IdentityType.ACI), device.getId(), device.getLastSeen(), zeroTtl)));
} catch (final JsonProcessingException e) {
// This should never happen when serializing an `AccountAndDeviceIdentifier`
throw new AssertionError(e);
}
}
}
@@ -5,23 +5,31 @@
package org.whispersystems.textsecuregcm.redis;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import io.lettuce.core.cluster.event.ClusterTopologyChangedEvent;
import io.lettuce.core.event.connection.ConnectionEvent;
import io.lettuce.core.resource.ClientResources;
import io.micrometer.core.instrument.Metrics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ConnectionEventLogger {
private static final Logger logger = LoggerFactory.getLogger(ConnectionEventLogger.class);
private static final String EVENT_COUNTER_NAME = name(ConnectionEventLogger.class, "events");
public static void logConnectionEvents(final ClientResources clientResources) {
clientResources.eventBus().get().subscribe(event -> {
if (event instanceof ConnectionEvent) {
logger.debug("Connection event: {}", event);
} else if (event instanceof ClusterTopologyChangedEvent) {
logger.info("Cluster topology changed: {}", event);
}
});
}
private static final Logger logger = LoggerFactory.getLogger(ConnectionEventLogger.class);
public static void logConnectionEvents(final ClientResources clientResources) {
clientResources.eventBus().get().subscribe(event -> {
if (event instanceof ConnectionEvent) {
logger.debug("Connection event: {}", event);
} else if (event instanceof ClusterTopologyChangedEvent) {
logger.info("Cluster topology changed: {}", event);
}
Metrics.counter(EVENT_COUNTER_NAME, "type", event.getClass().getSimpleName()).increment();
});
}
}
@@ -0,0 +1,48 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.spam;
import io.grpc.Status;
import java.util.Optional;
/**
* A combination of a gRPC status and response message to communicate to callers that a message has been flagged as
* potential spam.
*
* @param status The gRPC status for this response. If the status is {@link Status#OK}, then a response object will be
* available via {@link #response}. Otherwise, callers should transmit the status as an error to clients.
* @param response a response object to send to clients; will be present if {@link #status} is not {@link Status#OK}
*
* @param <R> the type of response object
*/
public record GrpcResponse<R>(Status status, Optional<R> response) {
/**
* Constructs a new response object with the given status and no response message.
*
* @param status the status to send to callers
*
* @return a new response object with the given status and no response message
*
* @param <R> the type of response object
*/
public static <R> GrpcResponse<R> withStatus(final Status status) {
return new GrpcResponse<>(status, Optional.empty());
}
/**
* Constructs a new response object with a status of {@link Status#OK} and the given response message.
*
* @param response the response to send to the caller
*
* @return a new response object with a status of {@link Status#OK} and the given response message
*
* @param <R> the type of response object
*/
public static <R> GrpcResponse<R> withResponse(final R response) {
return new GrpcResponse<>(Status.OK, Optional.of(response));
}
}
@@ -0,0 +1,15 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.spam;
public enum MessageType {
INDIVIDUAL_IDENTIFIED_SENDER,
SYNC,
INDIVIDUAL_SEALED_SENDER,
MULTI_RECIPIENT_SEALED_SENDER,
INDIVIDUAL_STORY,
MULTI_RECIPIENT_STORY,
}
@@ -0,0 +1,21 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.spam;
import java.util.Optional;
/**
* The result of a spam check. May contain a response to relay to the caller if a message was identified as potential
* spam or a spam reporting token to include in the delivered message.
*
* @param response a transport-appropriate response to return to the sender if the message was identified as potential
* spam, or empty if processing should continue as normal
* @param token a spam-reporting token to include in the outbound message, or empty if no token applies to the message
*
* @param <T> the type of response for messages identified as potential spam
*/
public record SpamCheckResult<T>(Optional<T> response, Optional<byte[]> token) {
}
@@ -5,49 +5,109 @@
package org.whispersystems.textsecuregcm.spam;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.Response;
import java.util.Optional;
import jakarta.ws.rs.core.Response;
import org.signal.chat.messages.SendMessageResponse;
import org.signal.chat.messages.SendMultiRecipientMessageResponse;
import org.whispersystems.textsecuregcm.auth.AccountAndAuthenticatedDeviceHolder;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.Account;
public interface SpamChecker {
/**
* A result from the spam checker that is one of:
* <ul>
* <li>
* Message is determined to be spam, and a response is returned
* </li>
* <li>
* Message is not spam, and an optional spam token is returned
* </li>
* </ul>
*/
sealed interface SpamCheckResult {}
record Spam(Response response) implements SpamCheckResult {}
record NotSpam(Optional<byte[]> token) implements SpamCheckResult {
public static final NotSpam EMPTY_TOKEN = new NotSpam(Optional.empty());
}
/**
* Determine if a message may be spam
* Determine if a message sent to an individual recipient via HTTP may be spam.
*
* @param requestContext The request context for a message send attempt
* @param maybeSource The sender of the message, could be empty if this as message sent with sealed sender
* @param maybeDestination The destination of the message, could be empty if the destination does not exist or could
* @param messageType the type of message to check
* @param requestContext the request context for a message send attempt
* @param maybeSource the sender of the message, could be empty if this as message sent with sealed sender
* @param maybeDestination the destination of the message, could be empty if the destination does not exist or could
* not be retrieved
* @param destinationIdentifier the service identifier for the destination account
* @return A {@link SpamCheckResult}
*/
SpamCheckResult checkForSpam(
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
SpamCheckResult<Response> checkForIndividualRecipientSpamHttp(
final MessageType messageType,
final ContainerRequestContext requestContext,
final Optional<? extends AccountAndAuthenticatedDeviceHolder> maybeSource,
final Optional<Account> maybeDestination,
final Optional<ServiceIdentifier> maybeDestinationIdentifier);
final ServiceIdentifier destinationIdentifier);
/**
* Determine if a message sent to multiple recipients via HTTP may be spam.
*
* @param messageType the type of message to check
* @param requestContext the request context for a message send attempt
* @return A {@link SpamCheckResult}
*/
SpamCheckResult<Response> checkForMultiRecipientSpamHttp(
final MessageType messageType,
final ContainerRequestContext requestContext);
/**
* Determine if a message sent to an individual recipient via gRPC may be spam.
*
* @param messageType the type of message to check
* @param maybeSource the sender of the message, could be empty if this as message sent with sealed sender
* @param maybeDestination the destination of the message, could be empty if the destination does not exist or could
* not be retrieved
* @param destinationIdentifier the service identifier for the destination account
* @return A {@link SpamCheckResult}
*/
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
SpamCheckResult<GrpcResponse<SendMessageResponse>> checkForIndividualRecipientSpamGrpc(
final MessageType messageType,
final Optional<org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice> maybeSource,
final Optional<Account> maybeDestination,
final ServiceIdentifier destinationIdentifier);
/**
* Determine if a message sent to multiple recipients via gRPC may be spam.
*
* @param messageType the type of message to check
*
* @return A {@link SpamCheckResult}
*/
SpamCheckResult<GrpcResponse<SendMultiRecipientMessageResponse>> checkForMultiRecipientSpamGrpc(final MessageType messageType);
static SpamChecker noop() {
return (ignoredContext, ignoredSource, ignoredDestination, ignoredDestinationIdentifier) -> NotSpam.EMPTY_TOKEN;
return new SpamChecker() {
@Override
public SpamCheckResult<Response> checkForIndividualRecipientSpamHttp(final MessageType messageType,
final ContainerRequestContext requestContext,
final Optional<? extends AccountAndAuthenticatedDeviceHolder> maybeSource,
final Optional<Account> maybeDestination,
final ServiceIdentifier destinationIdentifier) {
return new SpamCheckResult<>(Optional.empty(), Optional.empty());
}
@Override
public SpamCheckResult<Response> checkForMultiRecipientSpamHttp(final MessageType messageType,
final ContainerRequestContext requestContext) {
return new SpamCheckResult<>(Optional.empty(), Optional.empty());
}
@Override
public SpamCheckResult<GrpcResponse<SendMessageResponse>> checkForIndividualRecipientSpamGrpc(final MessageType messageType,
final Optional<AuthenticatedDevice> maybeSource,
final Optional<Account> maybeDestination,
final ServiceIdentifier destinationIdentifier) {
return new SpamCheckResult<>(Optional.empty(), Optional.empty());
}
@Override
public SpamCheckResult<GrpcResponse<SendMultiRecipientMessageResponse>> checkForMultiRecipientSpamGrpc(
final MessageType messageType) {
return new SpamCheckResult<>(Optional.empty(), Optional.empty());
}
};
}
}
@@ -1242,6 +1242,26 @@ public class Accounts {
.sequential();
}
Flux<UUID> getAllAccountIdentifiers(final int segments, final Scheduler scheduler) {
if (segments < 1) {
throw new IllegalArgumentException("Total number of segments must be positive");
}
return Flux.range(0, segments)
.parallel()
.runOn(scheduler)
.flatMap(segment -> dynamoDbAsyncClient.scanPaginator(ScanRequest.builder()
.tableName(accountsTableName)
.consistentRead(false)
.segment(segment)
.totalSegments(segments)
.projectionExpression(KEY_ACCOUNT_UUID)
.build())
.items()
.map(item -> AttributeValues.getUUID(item, KEY_ACCOUNT_UUID, null)))
.sequential();
}
@Nonnull
private Optional<Account> getByIndirectLookup(
final Timer timer,
@@ -37,10 +37,12 @@ import java.util.Arrays;
import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Queue;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
@@ -55,6 +57,7 @@ import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import javax.crypto.Mac;
@@ -67,6 +70,7 @@ import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevices;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.entities.DeviceInfo;
@@ -83,7 +87,6 @@ import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryException;
import org.whispersystems.textsecuregcm.util.DestinationDeviceValidator;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.SystemMapper;
@@ -780,24 +783,33 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
// Check that all including primary ID are in signed pre-keys
DestinationDeviceValidator.validateCompleteDeviceList(
account,
pniSignedPreKeys.keySet(),
Collections.emptySet());
validateCompleteDeviceList(account, pniSignedPreKeys.keySet());
// Check that all including primary ID are in Pq pre-keys
if (pniPqLastResortPreKeys != null) {
DestinationDeviceValidator.validateCompleteDeviceList(
account,
pniPqLastResortPreKeys.keySet(),
Collections.emptySet());
validateCompleteDeviceList(account, pniPqLastResortPreKeys.keySet());
}
// Check that all devices are accounted for in the map of new PNI registration IDs
DestinationDeviceValidator.validateCompleteDeviceList(
account,
pniRegistrationIds.keySet(),
Collections.emptySet());
validateCompleteDeviceList(account, pniRegistrationIds.keySet());
}
@VisibleForTesting
static void validateCompleteDeviceList(final Account account, final Set<Byte> deviceIds) throws MismatchedDevicesException {
final Set<Byte> accountDeviceIds = account.getDevices().stream()
.map(Device::getId)
.collect(Collectors.toSet());
final Set<Byte> missingDeviceIds = new HashSet<>(accountDeviceIds);
missingDeviceIds.removeAll(deviceIds);
final Set<Byte> extraDeviceIds = new HashSet<>(deviceIds);
extraDeviceIds.removeAll(accountDeviceIds);
if (!missingDeviceIds.isEmpty() || !extraDeviceIds.isEmpty()) {
throw new MismatchedDevicesException(
new MismatchedDevices(missingDeviceIds, extraDeviceIds, Collections.emptySet()));
}
}
public record UsernameReservation(Account account, byte[] reservedUsernameHash){}
@@ -1217,6 +1229,10 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
return accounts.getAll(segments, scheduler);
}
public Flux<UUID> streamAccountIdentifiersFromDynamo(final int segments, final Scheduler scheduler) {
return accounts.getAllAccountIdentifiers(segments, scheduler);
}
public CompletableFuture<Void> delete(final Account account, final DeletionReason deletionReason) {
final Timer.Sample sample = Timer.start();
@@ -5,27 +5,23 @@
package org.whispersystems.textsecuregcm.storage;
import com.google.protobuf.ByteString;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.signal.libsignal.protocol.IdentityKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.controllers.StaleDevicesException;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.IncomingMessage;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.push.MessageSender;
import org.whispersystems.textsecuregcm.util.DestinationDeviceValidator;
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
public class ChangeNumberManager {
@@ -45,13 +41,12 @@ public class ChangeNumberManager {
@Nullable final Map<Byte, ECSignedPreKey> deviceSignedPreKeys,
@Nullable final Map<Byte, KEMSignedPreKey> devicePqLastResortPreKeys,
@Nullable final List<IncomingMessage> deviceMessages,
@Nullable final Map<Byte, Integer> pniRegistrationIds)
throws InterruptedException, MismatchedDevicesException, StaleDevicesException {
@Nullable final Map<Byte, Integer> pniRegistrationIds,
@Nullable final String senderUserAgent)
throws InterruptedException, MismatchedDevicesException, MessageTooLargeException {
if (ObjectUtils.allNotNull(pniIdentityKey, deviceSignedPreKeys, deviceMessages, pniRegistrationIds)) {
// AccountsManager validates the device set on deviceSignedPreKeys and pniRegistrationIds
validateDeviceMessages(account, deviceMessages);
} else if (!ObjectUtils.allNull(pniIdentityKey, deviceSignedPreKeys, deviceMessages, pniRegistrationIds)) {
if (!(ObjectUtils.allNotNull(pniIdentityKey, deviceSignedPreKeys, deviceMessages, pniRegistrationIds) ||
ObjectUtils.allNull(pniIdentityKey, deviceSignedPreKeys, deviceMessages, pniRegistrationIds))) {
throw new IllegalArgumentException("PNI identity key, signed pre-keys, device messages, and registration IDs must be all null or all non-null");
}
@@ -66,14 +61,14 @@ public class ChangeNumberManager {
if (pniIdentityKey == null) {
return account;
}
return updatePniKeys(account, pniIdentityKey, deviceSignedPreKeys, devicePqLastResortPreKeys, deviceMessages, pniRegistrationIds);
return updatePniKeys(account, pniIdentityKey, deviceSignedPreKeys, devicePqLastResortPreKeys, deviceMessages, pniRegistrationIds, senderUserAgent);
}
final Account updatedAccount = accountsManager.changeNumber(
account, number, pniIdentityKey, deviceSignedPreKeys, devicePqLastResortPreKeys, pniRegistrationIds);
if (deviceMessages != null) {
sendDeviceMessages(updatedAccount, deviceMessages);
sendDeviceMessages(updatedAccount, deviceMessages, senderUserAgent);
}
return updatedAccount;
@@ -84,70 +79,47 @@ public class ChangeNumberManager {
final Map<Byte, ECSignedPreKey> deviceSignedPreKeys,
@Nullable final Map<Byte, KEMSignedPreKey> devicePqLastResortPreKeys,
final List<IncomingMessage> deviceMessages,
final Map<Byte, Integer> pniRegistrationIds) throws MismatchedDevicesException, StaleDevicesException {
validateDeviceMessages(account, deviceMessages);
final Map<Byte, Integer> pniRegistrationIds,
final String senderUserAgent) throws MismatchedDevicesException, MessageTooLargeException {
// Don't try to be smart about ignoring unnecessary retries. If we make literally no change we will skip the ddb
// write anyway. Linked devices can handle some wasted extra key rotations.
final Account updatedAccount = accountsManager.updatePniKeys(
account, pniIdentityKey, deviceSignedPreKeys, devicePqLastResortPreKeys, pniRegistrationIds);
sendDeviceMessages(updatedAccount, deviceMessages);
sendDeviceMessages(updatedAccount, deviceMessages, senderUserAgent);
return updatedAccount;
}
private void validateDeviceMessages(final Account account,
final List<IncomingMessage> deviceMessages) throws MismatchedDevicesException, StaleDevicesException {
// Check that all except primary ID are in device messages
DestinationDeviceValidator.validateCompleteDeviceList(
account,
deviceMessages.stream().map(IncomingMessage::destinationDeviceId).collect(Collectors.toSet()),
Set.of(Device.PRIMARY_ID));
private void sendDeviceMessages(final Account account,
final List<IncomingMessage> deviceMessages,
final String senderUserAgent) throws MessageTooLargeException, MismatchedDevicesException {
// check that all sync messages are to the current registration ID for the matching device
DestinationDeviceValidator.validateRegistrationIds(
account,
deviceMessages,
IncomingMessage::destinationDeviceId,
IncomingMessage::destinationRegistrationId,
false);
}
private void sendDeviceMessages(final Account account, final List<IncomingMessage> deviceMessages) {
try {
final long serverTimestamp = System.currentTimeMillis();
final ServiceIdentifier serviceIdentifier = new AciServiceIdentifier(account.getUuid());
messageSender.sendMessages(account, deviceMessages.stream()
.filter(message -> getMessageContent(message).isPresent())
final Map<Byte, Envelope> messagesByDeviceId = deviceMessages.stream()
.collect(Collectors.toMap(IncomingMessage::destinationDeviceId, message -> Envelope.newBuilder()
.setType(Envelope.Type.forNumber(message.type()))
.setClientTimestamp(serverTimestamp)
.setServerTimestamp(serverTimestamp)
.setDestinationServiceId(new AciServiceIdentifier(account.getUuid()).toServiceIdentifierString())
.setContent(ByteString.copyFrom(getMessageContent(message).orElseThrow()))
.setSourceServiceId(new AciServiceIdentifier(account.getUuid()).toServiceIdentifierString())
.setDestinationServiceId(serviceIdentifier.toServiceIdentifierString())
.setContent(ByteString.copyFrom(message.content()))
.setSourceServiceId(serviceIdentifier.toServiceIdentifierString())
.setSourceDevice(Device.PRIMARY_ID)
.setUpdatedPni(account.getPhoneNumberIdentifier().toString())
.setUrgent(true)
.setEphemeral(false)
.build())));
.build()));
final Map<Byte, Integer> registrationIdsByDeviceId = account.getDevices().stream()
.collect(Collectors.toMap(Device::getId, Device::getRegistrationId));
messageSender.sendMessages(account, serviceIdentifier, messagesByDeviceId, registrationIdsByDeviceId, senderUserAgent);
} catch (final RuntimeException e) {
logger.warn("Changed number but could not send all device messages on {}", account.getUuid(), e);
throw e;
}
}
private static Optional<byte[]> getMessageContent(final IncomingMessage message) {
if (StringUtils.isEmpty(message.content())) {
logger.warn("Message has no content");
return Optional.empty();
}
try {
return Optional.of(Base64.getDecoder().decode(message.content()));
} catch (final IllegalArgumentException e) {
logger.warn("Failed to parse message content", e);
return Optional.empty();
}
}
}
@@ -11,12 +11,21 @@ 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),
VERSIONED_EXPIRATION_TIMER("versionedExpirationTimer", AccountCapabilityMode.ALL_DEVICES, true, true),
STORAGE_SERVICE_RECORD_KEY_ROTATION("ssre2", AccountCapabilityMode.ALL_DEVICES, true, true);
STORAGE_SERVICE_RECORD_KEY_ROTATION("ssre2", AccountCapabilityMode.ALL_DEVICES, true, true),
ATTACHMENT_BACKFILL("attachmentBackfill", AccountCapabilityMode.PRIMARY_DEVICE, false, true);
public enum AccountCapabilityMode {
/**
* The account will have the capability iff the primary device has the capability
*/
PRIMARY_DEVICE,
/**
* The account will have the capability iff any device on the account has the capability
*/
ANY_DEVICE,
/**
* The account will have the capability iff all devices on the account have the capability
*/
ALL_DEVICES,
}
@@ -25,6 +34,18 @@ public enum DeviceCapability {
private final boolean preventDowngrade;
private final boolean includeInProfile;
/**
* Create a DeviceCapability
*
* @param name The name of the device capability that clients will see
* @param accountCapabilityMode How to combine the constituent device's capabilities in the account to an overall
* account capability
* @param preventDowngrade If true, don't let linked devices join that don't have a device capability if the
* overall account has the capability. Most of the time this should only be used in
* conjunction with AccountCapabilityMode.ALL_DEVICES
* @param includeInProfile Whether to return this capability on the account's profile. If false, the capability
* is only visible to the server
*/
DeviceCapability(final String name,
final AccountCapabilityMode accountCapabilityMode,
final boolean preventDowngrade,
@@ -18,11 +18,17 @@ import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.retry.Retry;
import software.amazon.awssdk.services.dynamodb.model.ItemCollectionSizeLimitExceededException;
public class MessagePersister implements Managed {
@@ -30,26 +36,30 @@ public class MessagePersister implements Managed {
private final MessagesCache messagesCache;
private final MessagesManager messagesManager;
private final AccountsManager accountsManager;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private final Duration persistDelay;
private final Thread[] workerThreads;
private volatile boolean running;
private final Timer getQueuesTimer = Metrics.timer(name(MessagePersister.class, "getQueues"));
private final Timer persistQueueTimer = Metrics.timer(name(MessagePersister.class, "persistQueue"));
private final Counter persistQueueExceptionMeter = Metrics.counter(
name(MessagePersister.class, "persistQueueException"));
private final Counter oversizedQueueCounter = Metrics.counter(name(MessagePersister.class, "persistQueueOversized"));
private final DistributionSummary queueCountDistributionSummery = DistributionSummary.builder(
private static final String OVERSIZED_QUEUE_COUNTER_NAME = name(MessagePersister.class, "persistQueueOversized");
private static final Timer GET_QUEUES_TIMER = Metrics.timer(name(MessagePersister.class, "getQueues"));
private static final Timer PERSIST_QUEUE_TIMER = Metrics.timer(name(MessagePersister.class, "persistQueue"));
private static final Counter PERSIST_QUEUE_EXCEPTION_METER =
Metrics.counter(name(MessagePersister.class, "persistQueueException"));
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"))
.publishPercentiles(0.5, 0.75, 0.95, 0.99, 0.999)
.distributionStatisticExpiry(Duration.ofMinutes(10))
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry);
private final DistributionSummary queueSizeDistributionSummery = DistributionSummary.builder(
private static final DistributionSummary QUEUE_SIZE_DISTRIBUTION_SUMMARY = DistributionSummary.builder(
name(MessagePersister.class, "queueSize"))
.publishPercentiles(0.5, 0.75, 0.95, 0.99, 0.999)
.distributionStatisticExpiry(Duration.ofMinutes(10))
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry);
static final int QUEUE_BATCH_LIMIT = 100;
@@ -66,12 +76,12 @@ public class MessagePersister implements Managed {
final AccountsManager accountsManager,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final Duration persistDelay,
final int dedicatedProcessWorkerThreadCount
) {
final int dedicatedProcessWorkerThreadCount) {
this.messagesCache = messagesCache;
this.messagesManager = messagesManager;
this.accountsManager = accountsManager;
this.dynamicConfigurationManager = dynamicConfigurationManager;
this.persistDelay = persistDelay;
this.workerThreads = new Thread[dedicatedProcessWorkerThreadCount];
@@ -82,7 +92,7 @@ public class MessagePersister implements Managed {
.isPersistenceEnabled()) {
try {
final int queuesPersisted = persistNextQueues(Instant.now());
queueCountDistributionSummery.record(queuesPersisted);
QUEUE_COUNT_DISTRIBUTION_SUMMARY.record(queuesPersisted);
if (queuesPersisted == 0) {
Util.sleep(100);
@@ -134,7 +144,7 @@ public class MessagePersister implements Managed {
int queuesPersisted = 0;
do {
queuesToPersist = getQueuesTimer.record(
queuesToPersist = GET_QUEUES_TIMER.record(
() -> messagesCache.getQueuesToPersist(slot, currentTime.minus(persistDelay), QUEUE_BATCH_LIMIT));
for (final String queue : queuesToPersist) {
@@ -154,12 +164,15 @@ public class MessagePersister implements Managed {
try {
persistQueue(maybeAccount.get(), maybeDevice.get());
} catch (final Exception e) {
persistQueueExceptionMeter.increment();
PERSIST_QUEUE_EXCEPTION_METER.increment();
logger.warn("Failed to persist queue {}::{}; will schedule for retry", accountUuid, deviceId, e);
messagesCache.addQueueToPersist(accountUuid, deviceId);
Util.sleep(EXCEPTION_PAUSE_MILLIS);
if (!(e instanceof MessagePersistenceException)) {
// Pause after unexpected exceptions
Util.sleep(EXCEPTION_PAUSE_MILLIS);
}
}
}
@@ -202,24 +215,81 @@ public class MessagePersister implements Managed {
} while (!messages.isEmpty());
queueSizeDistributionSummery.record(messageCount);
QUEUE_SIZE_DISTRIBUTION_SUMMARY.record(messageCount);
} catch (ItemCollectionSizeLimitExceededException e) {
oversizedQueueCounter.increment();
maybeUnlink(account, deviceId); // may throw, in which case we'll retry later by the usual mechanism
final boolean isPrimary = deviceId == Device.PRIMARY_ID;
Metrics.counter(OVERSIZED_QUEUE_COUNTER_NAME, "primary", String.valueOf(isPrimary)).increment();
// may throw, in which case we'll retry later by the usual mechanism
if (isPrimary) {
logger.warn("Failed to persist queue {}::{} due to overfull queue; will trim oldest messages",
account.getUuid(), deviceId);
trimQueue(account, deviceId);
throw new MessagePersistenceException("Could not persist due to an overfull queue. Trimmed primary queue, a subsequent retry may succeed");
} else {
logger.warn("Failed to persist queue {}::{} due to overfull queue; will unlink device", account.getUuid(),
deviceId);
accountsManager.removeDevice(account, deviceId).join();
}
} finally {
messagesCache.unlockQueueForPersistence(accountUuid, deviceId);
sample.stop(persistQueueTimer);
sample.stop(PERSIST_QUEUE_TIMER);
}
}
@VisibleForTesting
void maybeUnlink(final Account account, byte destinationDeviceId) throws MessagePersistenceException {
if (destinationDeviceId == Device.PRIMARY_ID) {
throw new MessagePersistenceException("primary device has a full queue");
}
private void trimQueue(final Account account, byte deviceId) {
final UUID aci = account.getIdentifier(IdentityType.ACI);
logger.warn("Failed to persist queue {}::{} due to overfull queue; will unlink device", account.getUuid(), destinationDeviceId);
accountsManager.removeDevice(account, destinationDeviceId).join();
final Optional<Device> maybeDevice = account.getDevice(deviceId);
if (maybeDevice.isEmpty()) {
logger.warn("Not deleting messages for overfull queue {}::{}, deviceId {} does not exist",
aci, deviceId, deviceId);
return;
}
final Device device = maybeDevice.get();
// Calculate how many bytes we should trim
final long cachedMessageBytes = messagesCache.estimatePersistedQueueSizeBytes(aci, deviceId).join();
final double extraRoomRatio = this.dynamicConfigurationManager.getConfiguration()
.getMessagePersisterConfiguration()
.getTrimOversizedQueueExtraRoomRatio();
final long targetDeleteBytes = Math.round(cachedMessageBytes * extraRoomRatio);
final AtomicLong oldestMessage = new AtomicLong(0L);
final AtomicLong newestMessage = new AtomicLong(0L);
final AtomicLong bytesDeleted = new AtomicLong(0L);
// Iterate from the oldest message until we've removed targetDeleteBytes
final Pair<Long, Long> outcomes = Flux.from(messagesManager.getMessagesForDeviceReactive(aci, device, false))
.concatMap(envelope -> {
if (bytesDeleted.getAndAdd(envelope.getSerializedSize()) >= targetDeleteBytes) {
return Mono.just(Optional.<MessageProtos.Envelope>empty());
}
oldestMessage.compareAndSet(0L, envelope.getServerTimestamp());
newestMessage.set(envelope.getServerTimestamp());
return Mono.just(Optional.of(envelope));
})
.takeWhile(Optional::isPresent)
.flatMap(maybeEnvelope -> {
final MessageProtos.Envelope envelope = maybeEnvelope.get();
TRIMMED_MESSAGE_COUNTER.increment();
TRIMMED_MESSAGE_BYTES_COUNTER.increment(envelope.getSerializedSize());
return Mono
.fromCompletionStage(() -> messagesManager
.delete(aci, device, UUID.fromString(envelope.getServerGuid()), envelope.getServerTimestamp()))
.retryWhen(Retry.backoff(5, Duration.ofSeconds(1)))
.map(Optional::isPresent);
})
.reduce(Pair.of(0L, 0L), (acc, deleted) -> deleted
? Pair.of(acc.getLeft() + 1, acc.getRight())
: Pair.of(acc.getLeft(), acc.getRight() + 1))
.block();
logger.warn(
"Finished trimming {}:{}. Oldest message = {}, newest message = {}. Attempted to delete {} persisted bytes to make room for {} cached message bytes. Delete outcomes: {} present, {} missing.",
aci, deviceId,
Instant.ofEpochMilli(oldestMessage.get()), Instant.ofEpochMilli(newestMessage.get()),
targetDeleteBytes, cachedMessageBytes,
outcomes.getLeft(), outcomes.getRight());
}
}
@@ -10,10 +10,14 @@ import static com.codahale.metrics.MetricRegistry.name;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import io.lettuce.core.Limit;
import io.lettuce.core.Range;
import io.lettuce.core.ScoredValue;
import io.lettuce.core.ZAddArgs;
import io.lettuce.core.cluster.SlotHash;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Timer;
import java.io.IOException;
import java.nio.ByteBuffer;
@@ -30,6 +34,7 @@ import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.function.Function;
import java.util.function.Predicate;
import org.reactivestreams.Publisher;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
@@ -129,11 +134,14 @@ public class MessagesCache {
private final Timer removeByGuidTimer = Metrics.timer(name(MessagesCache.class, "removeByGuid"));
private final Timer removeRecipientViewTimer = Metrics.timer(name(MessagesCache.class, "removeRecipientView"));
private final Timer clearQueueTimer = Metrics.timer(name(MessagesCache.class, "clear"));
private final Counter removeMessageCounter = Metrics.counter(name(MessagesCache.class, "remove"));
private final Counter staleEphemeralMessagesCounter = Metrics.counter(
name(MessagesCache.class, "staleEphemeralMessages"));
private final Counter staleMrmMessagesCounter = Metrics.counter(name(MessagesCache.class, "staleMrmMessages"));
private final Counter mrmContentRetrievedCounter = Metrics.counter(name(MessagesCache.class, "mrmViewRetrieved"));
private final String MRM_RETRIEVAL_ERROR_COUNTER_NAME = name(MessagesCache.class, "mrmRetrievalError");
private final String EPHEMERAL_TAG_NAME = "ephemeral";
private final String MISSING_MRM_DATA_TAG_NAME = "missingMrmData";
private final Counter skippedStaleEphemeralMrmCounter = Metrics.counter(
name(MessagesCache.class, "skippedStaleEphemeralMrm"));
private final Counter sharedMrmDataKeyRemovedCounter = Metrics.counter(
@@ -142,6 +150,9 @@ public class MessagesCache {
static final String NEXT_SLOT_TO_PERSIST_KEY = "user_queue_persist_slot";
private static final byte[] LOCK_VALUE = "1".getBytes(StandardCharsets.UTF_8);
@VisibleForTesting
static final ByteString STALE_MRM_KEY = ByteString.copyFromUtf8("stale");
@VisibleForTesting
static final Duration MAX_EPHEMERAL_MESSAGE_DELAY = Duration.ofSeconds(10);
@@ -263,7 +274,13 @@ public class MessagesCache {
(serviceId, keysToUpdate) -> removeRecipientViewFromMrmData(keysToUpdate, serviceId, destinationDevice));
return removedMessages;
}, messageDeletionExecutorService).whenComplete((ignored, throwable) -> sample.stop(removeByGuidTimer));
}, messageDeletionExecutorService).whenComplete((removedMessages, throwable) -> {
if (removedMessages != null) {
removeMessageCounter.increment(removedMessages.size());
}
sample.stop(removeByGuidTimer);
});
}
@@ -287,20 +304,26 @@ public class MessagesCache {
final Flux<MessageProtos.Envelope> allMessages = getAllMessages(destinationUuid, destinationDevice,
earliestAllowableEphemeralTimestamp, PAGE_SIZE)
.publish()
// We expect exactly two subscribers to this base flux:
// We expect exactly three subscribers to this base flux:
// 1. the websocket that delivers messages to clients
// 2. an internal process to discard stale ephemeral messages
// The discard subscriber will subscribe immediately, but we don’t want to do any work if the
// 2. an internal processes to discard stale ephemeral messages
// 3. an internal process to discard stale MRM messages
// The discard subscribers will subscribe immediately, but we don’t want to do any work if the
// websocket never subscribes.
.autoConnect(2);
.autoConnect(3);
final Flux<MessageProtos.Envelope> messagesToPublish = allMessages
.filter(Predicate.not(envelope -> isStaleEphemeralMessage(envelope, earliestAllowableEphemeralTimestamp)));
.filter(Predicate.not(envelope ->
isStaleEphemeralMessage(envelope, earliestAllowableEphemeralTimestamp) || isStaleMrmMessage(envelope)));
final Flux<MessageProtos.Envelope> staleEphemeralMessages = allMessages
.filter(envelope -> isStaleEphemeralMessage(envelope, earliestAllowableEphemeralTimestamp));
discardStaleMessages(destinationUuid, destinationDevice, staleEphemeralMessages, staleEphemeralMessagesCounter, "ephemeral");
discardStaleEphemeralMessages(destinationUuid, destinationDevice, staleEphemeralMessages);
final Flux<MessageProtos.Envelope> staleMrmMessages = allMessages.filter(MessagesCache::isStaleMrmMessage)
// clearing the sharedMrmKey prevents unnecessary calls to update the shared MRM data
.map(envelope -> envelope.toBuilder().clearSharedMrmKey().build());
discardStaleMessages(destinationUuid, destinationDevice, staleMrmMessages, staleMrmMessagesCounter, "mrm");
return messagesToPublish.name(GET_FLUX_NAME)
.tap(Micrometer.metrics(Metrics.globalRegistry));
@@ -317,16 +340,25 @@ public class MessagesCache {
return message.getEphemeral() && message.getClientTimestamp() < earliestAllowableTimestamp;
}
private void discardStaleEphemeralMessages(final UUID destinationUuid, final byte destinationDevice,
Flux<MessageProtos.Envelope> staleEphemeralMessages) {
staleEphemeralMessages
/**
* Checks whether the given message is a stale MRM message
*
* @see #getMessageWithSharedMrmData(MessageProtos.Envelope, byte)
*/
private static boolean isStaleMrmMessage(final MessageProtos.Envelope message) {
return message.hasSharedMrmKey() && STALE_MRM_KEY.equals(message.getSharedMrmKey());
}
private void discardStaleMessages(final UUID destinationUuid, final byte destinationDevice,
Flux<MessageProtos.Envelope> staleMessages, final Counter counter, final String context) {
staleMessages
.map(e -> UUID.fromString(e.getServerGuid()))
.buffer(PAGE_SIZE)
.subscribeOn(messageDeletionScheduler)
.subscribe(staleEphemeralMessageGuids ->
remove(destinationUuid, destinationDevice, staleEphemeralMessageGuids)
.thenAccept(removedMessages -> staleEphemeralMessagesCounter.increment(removedMessages.size())),
e -> logger.warn("Could not remove stale ephemeral messages from cache", e));
.subscribe(messageGuids ->
remove(destinationUuid, destinationDevice, messageGuids)
.thenAccept(removedMessages -> counter.increment(removedMessages.size())),
e -> logger.warn("Could not remove stale {} messages from cache", context, e));
}
@VisibleForTesting
@@ -382,7 +414,13 @@ public class MessagesCache {
}
/**
* Returns the given message with its shared MRM data.
* Returns the given message with its shared MRM data. There are three possible cases:
* <ol>
* <li>The reconstructed message for delivery with {@code content} set and {@code sharedMrmKey} cleared</li>
* <li>The input with {@code sharedMrmKey} set to a static value, indicating that the shared MRM data is no longer available, and the message should be
* discarded from the queue</li>
* <li>An empty {@code Mono}, if an unexpected error occurred</li>
* </ol>
*/
private Mono<MessageProtos.Envelope> getMessageWithSharedMrmData(final MessageProtos.Envelope mrmMessage,
final byte destinationDevice) {
@@ -402,6 +440,18 @@ public class MessagesCache {
try {
assert mrmDataAndView.size() == 2;
if (mrmDataAndView.getFirst().isEmpty()) {
// shared data is missing
//noinspection ReactiveStreamsThrowInOperator
throw new MrmDataMissingException(MrmDataMissingException.Type.SHARED);
}
if (mrmDataAndView.getLast().isEmpty()) {
// recipient's view is missing
//noinspection ReactiveStreamsThrowInOperator
throw new MrmDataMissingException(MrmDataMissingException.Type.RECIPIENT_VIEW);
}
final byte[] content = SealedSenderMultiRecipientMessage.messageForRecipient(
mrmDataAndView.getFirst().getValue(),
mrmDataAndView.getLast().getValue());
@@ -417,12 +467,25 @@ public class MessagesCache {
}
})
.onErrorResume(throwable -> {
logger.warn("Failed to retrieve shared mrm data", throwable);
Metrics.counter(MRM_RETRIEVAL_ERROR_COUNTER_NAME,
EPHEMERAL_TAG_NAME, String.valueOf(mrmMessage.getEphemeral()))
.increment();
return Mono.empty();
final List<Tag> tags = new ArrayList<>();
tags.add(Tag.of(EPHEMERAL_TAG_NAME, String.valueOf(mrmMessage.getEphemeral())));
final Mono<MessageProtos.Envelope> result;
if (throwable instanceof MrmDataMissingException mdme) {
tags.add(Tag.of(MISSING_MRM_DATA_TAG_NAME, mdme.getType().name()));
// MRM data may be missing if either of the two non-transactional writes (delete from queue, update shared
// MRM data) fails after it has been delivered. We return it so that it may be discarded from the queue.
result = Mono.just(mrmMessage.toBuilder().setSharedMrmKey(STALE_MRM_KEY).build());
} else {
logger.warn("Failed to retrieve shared mrm data", throwable);
// For unexpected errors, return empty. The message will remain in the queue and be retried in the future.
result = Mono.empty();
}
Metrics.counter(MRM_RETRIEVAL_ERROR_COUNTER_NAME, tags).increment();
return result;
})
.share();
}
@@ -477,7 +540,37 @@ public class MessagesCache {
});
}
@VisibleForTesting
/**
* Estimate the size of the cached queue if it were to be persisted
* @param accountUuid The account identifier
* @param destinationDevice The destination device id
* @return A future that completes with the approximate size of stored messages that need to be persisted
*/
CompletableFuture<Long> estimatePersistedQueueSizeBytes(final UUID accountUuid, final byte destinationDevice) {
final Function<Optional<Long>, Mono<List<ScoredValue<byte[]>>>> getNextPage = (Optional<Long> start) ->
Mono.fromCompletionStage(() -> redisCluster.withBinaryCluster(connection ->
connection.async().zrangebyscoreWithScores(
getMessageQueueKey(accountUuid, destinationDevice),
Range.from(
start.map(Range.Boundary::excluding).orElse(Range.Boundary.unbounded()),
Range.Boundary.unbounded()),
Limit.from(PAGE_SIZE))));
final Flux<byte[]> allSerializedMessages = getNextPage.apply(Optional.empty())
.expand(scoredValues -> {
if (scoredValues.isEmpty()) {
return Mono.empty();
}
long lastTimestamp = (long) scoredValues.getLast().getScore();
return getNextPage.apply(Optional.of(lastTimestamp));
})
.concatMap(scoredValues -> Flux.fromStream(scoredValues.stream().map(ScoredValue::getValue)));
return parseAndFetchMrms(allSerializedMessages, destinationDevice)
.filter(Predicate.not(envelope -> envelope.getEphemeral() || isStaleMrmMessage(envelope)))
.reduce(0L, (acc, envelope) -> acc + envelope.getSerializedSize())
.toFuture();
}
List<MessageProtos.Envelope> getMessagesToPersist(final UUID accountUuid, final byte destinationDevice,
final int limit) {
@@ -486,7 +579,29 @@ public class MessagesCache {
final List<byte[]> messages = redisCluster.withBinaryCluster(connection ->
connection.sync().zrange(getMessageQueueKey(accountUuid, destinationDevice), 0, limit));
return Flux.fromIterable(messages)
final Flux<MessageProtos.Envelope> allMessages = parseAndFetchMrms(Flux.fromIterable(messages), destinationDevice);
final Flux<MessageProtos.Envelope> messagesToPersist = allMessages
.filter(Predicate.not(envelope ->
envelope.getEphemeral() || isStaleMrmMessage(envelope)));
final Flux<MessageProtos.Envelope> ephemeralMessages = allMessages
.filter(MessageProtos.Envelope::getEphemeral);
discardStaleMessages(accountUuid, destinationDevice, ephemeralMessages, staleEphemeralMessagesCounter, "ephemeral");
final Flux<MessageProtos.Envelope> staleMrmMessages = allMessages.filter(MessagesCache::isStaleMrmMessage)
// clearing the sharedMrmKey prevents unnecessary calls to update the shared MRM data
.map(envelope -> envelope.toBuilder().clearSharedMrmKey().build());
discardStaleMessages(accountUuid, destinationDevice, staleMrmMessages, staleMrmMessagesCounter, "mrm");
return messagesToPersist
.collectList()
.doOnTerminate(() -> sample.stop(getMessagesTimer))
.block(Duration.ofSeconds(5));
}
private Flux<MessageProtos.Envelope> parseAndFetchMrms(final Flux<byte[]> serializedMessages, final byte destinationDevice) {
return serializedMessages
.mapNotNull(message -> {
try {
return MessageProtos.Envelope.parseFrom(message);
@@ -504,10 +619,7 @@ public class MessagesCache {
}
return messageMono;
})
.collectList()
.doOnTerminate(() -> sample.stop(getMessagesTimer))
.block(Duration.ofSeconds(5));
});
}
public CompletableFuture<Void> clear(final UUID destinationUuid) {
@@ -11,7 +11,6 @@ import static io.micrometer.core.instrument.Metrics.timer;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableMap;
import com.google.protobuf.InvalidProtocolBufferException;
import io.micrometer.core.instrument.Timer;
import java.nio.ByteBuffer;
import java.time.Duration;
@@ -24,7 +23,6 @@ import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.function.Predicate;
import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -58,6 +56,9 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
@VisibleForTesting
static final String LOCAL_INDEX_MESSAGE_UUID_KEY_SORT = "U";
@VisibleForTesting
static final int MAY_HAVE_URGENT_MESSAGES_QUERY_LIMIT = 20;
private static final String KEY_TTL = "E";
private static final String KEY_ENVELOPE_BYTES = "EB";
@@ -69,8 +70,6 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
private final ExecutorService messageDeletionExecutor;
private final Scheduler messageDeletionScheduler;
private static final CompletableFuture<?>[] EMPTY_FUTURE_ARRAY = new CompletableFuture<?>[0];
private static final Logger logger = LoggerFactory.getLogger(MessagesDynamoDb.class);
public MessagesDynamoDb(DynamoDbClient dynamoDb, DynamoDbAsyncClient dynamoDbAsyncClient, String tableName,
@@ -128,7 +127,7 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
}
public CompletableFuture<Boolean> mayHaveUrgentMessages(final UUID accountIdentifier, final Device device) {
return Flux.from(load(accountIdentifier, device, null))
return Flux.from(load(accountIdentifier, device, MAY_HAVE_URGENT_MESSAGES_QUERY_LIMIT))
.any(MessageProtos.Envelope::getUrgent)
.toFuture();
}
@@ -48,6 +48,9 @@ public class MessagesManager {
private static final Counter PERSIST_MESSAGE_COUNTER = Metrics.counter(
name(MessagesManager.class, "persistMessage"));
private static final Counter PERSIST_MESSAGE_BYTES_COUNTER = Metrics.counter(
name(MessagesManager.class, "persistMessageBytes"));
private static final String MAY_HAVE_MESSAGES_COUNTER_NAME =
MetricsUtil.name(MessagesManager.class, "mayHaveMessages");
@@ -267,11 +270,7 @@ public class MessagesManager {
final Device destinationDevice,
final List<Envelope> messages) {
final List<Envelope> nonEphemeralMessages = messages.stream()
.filter(envelope -> !envelope.getEphemeral())
.collect(Collectors.toList());
messagesDynamoDb.store(nonEphemeralMessages, destinationUuid, destinationDevice);
messagesDynamoDb.store(messages, destinationUuid, destinationDevice);
final List<UUID> messageGuids = messages.stream().map(message -> UUID.fromString(message.getServerGuid()))
.collect(Collectors.toList());
@@ -279,7 +278,10 @@ public class MessagesManager {
try {
messagesRemovedFromCache = messagesCache.remove(destinationUuid, destinationDevice.getId(), messageGuids)
.get(30, TimeUnit.SECONDS).size();
PERSIST_MESSAGE_COUNTER.increment(nonEphemeralMessages.size());
PERSIST_MESSAGE_COUNTER.increment(messages.size());
PERSIST_MESSAGE_BYTES_COUNTER.increment(messages.stream()
.mapToInt(Envelope::getSerializedSize)
.sum());
} catch (InterruptedException | ExecutionException | TimeoutException e) {
logger.warn("Failed to remove messages from cache", e);
@@ -0,0 +1,26 @@
package org.whispersystems.textsecuregcm.storage;
import org.whispersystems.textsecuregcm.util.NoStackTraceRuntimeException;
class MrmDataMissingException extends NoStackTraceRuntimeException {
enum Type {
SHARED,
RECIPIENT_VIEW
}
private final Type type;
MrmDataMissingException(final Type type) {
this.type = type;
}
Type getType() {
return type;
}
@Override
public String toString() {
return "MrmDataMissingException{type=%s}".formatted(type);
}
}
@@ -142,7 +142,7 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
// We've already acknowledged this purchase on a previous attempt, nothing to do
return CompletableFuture.completedFuture(null);
}
return executeAsync(pub -> pub.purchases().subscriptions()
return executeTokenOperation(pub -> pub.purchases().subscriptions()
.acknowledge(packageName, productId, purchaseToken, new SubscriptionPurchasesAcknowledgeRequest()));
}
@@ -217,9 +217,11 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
}
final SubscriptionPurchaseLineItem purchase = getLineItem(subscription);
return executeAsync(pub ->
return executeTokenOperation(pub ->
pub.purchases().subscriptions().cancel(packageName, purchase.getProductId(), purchaseToken));
});
})
// If the subscription is not found, no need to do anything
.exceptionally(ExceptionUtils.exceptionallyHandler(SubscriptionException.NotFound.class, e -> null));
}
@Override
@@ -339,26 +341,37 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
return CompletableFuture.supplyAsync(() -> {
try {
return apiCall.req(androidPublisher).execute();
} catch (GoogleJsonResponseException e) {
if (e.getStatusCode() == Response.Status.NOT_FOUND.getStatusCode()) {
throw ExceptionUtils.wrap(new SubscriptionException.NotFound());
}
logger.warn("Unexpected HTTP status code {} from androidpublisher: {}", e.getStatusCode(), e.getDetails(), e);
throw ExceptionUtils.wrap(e);
} catch (HttpResponseException e) {
if (e.getStatusCode() == Response.Status.NOT_FOUND.getStatusCode()) {
throw ExceptionUtils.wrap(new SubscriptionException.NotFound());
}
logger.warn("Unexpected HTTP status code {} from androidpublisher", e.getStatusCode(), e);
throw ExceptionUtils.wrap(e);
} catch (IOException e) {
throw ExceptionUtils.wrap(e);
}
}, executor);
}
/**
* Asynchronously execute a synchronous API call on a purchaseToken, mapping expected errors to the appropriate
* {@link SubscriptionException}
*
* @param apiCall An API call that operates on a purchaseToken
* @param <R> The result of the API call
* @return A stage that completes with the result of the API call
*/
private <R> CompletableFuture<R> executeTokenOperation(final ApiCall<R> apiCall) {
return executeAsync(apiCall)
.exceptionally(ExceptionUtils.exceptionallyHandler(HttpResponseException.class, e -> {
if (e.getStatusCode() == Response.Status.NOT_FOUND.getStatusCode()
|| e.getStatusCode() == Response.Status.GONE.getStatusCode()) {
throw ExceptionUtils.wrap(new SubscriptionException.NotFound());
}
final String details = e instanceof GoogleJsonResponseException
? ((GoogleJsonResponseException) e).getDetails().toString()
: "";
logger.warn("Unexpected HTTP status code {} from androidpublisher: {}", e.getStatusCode(), details, e);
throw ExceptionUtils.wrap(e);
}));
}
private CompletableFuture<SubscriptionPurchaseV2> lookupSubscription(final String purchaseToken) {
return executeAsync(publisher -> publisher.purchases().subscriptionsv2().get(packageName, purchaseToken));
return executeTokenOperation(publisher -> publisher.purchases().subscriptionsv2().get(packageName, purchaseToken));
}
private long productIdToLevel(final String productId) {
@@ -385,8 +385,17 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
if (customer == null) {
throw ExceptionUtils.wrap(new IOException("no customer record found for id " + customerId));
}
if (StringUtils.isBlank(customer.getId()) || (!customer.getId().equals(customerId))) {
logger.error("customer ID returned by Stripe ({}) did not match query ({})", customerId, customer.getSubscriptions());
throw ExceptionUtils.wrap(new IOException("unexpected customer ID returned by Stripe"));
}
return listNonCanceledSubscriptions(customer);
}).thenCompose(subscriptions -> {
if (subscriptions.stream()
.anyMatch(subscription -> !subscription.getCustomer().equals(customerId))) {
logger.error("Subscription did not match expected customer ID: {}", customerId);
throw ExceptionUtils.wrap( new IOException("mismatched customer ID"));
}
@SuppressWarnings("unchecked")
CompletableFuture<Subscription>[] futures = (CompletableFuture<Subscription>[]) subscriptions.stream()
.map(this::endSubscription).toArray(CompletableFuture[]::new);
@@ -401,7 +410,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
.build();
try {
return Lists.newArrayList(
stripeClient.subscriptions().list(params, commonOptions()).autoPagingIterable(null, commonOptions()));
stripeClient.subscriptions().list(params, commonOptions()).autoPagingIterable());
} catch (StripeException e) {
throw new CompletionException(e);
}
@@ -450,7 +459,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
try {
final StripeCollection<SubscriptionItem> subscriptionItems = stripeClient.subscriptionItems().list(
SubscriptionItemListParams.builder().setSubscription(subscription.getId()).build(), commonOptions());
return Lists.newArrayList(subscriptionItems.autoPagingIterable(null, commonOptions()));
return Lists.newArrayList(subscriptionItems.autoPagingIterable());
} catch (final StripeException e) {
throw new CompletionException(e);
@@ -519,7 +528,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
.build();
try {
ArrayList<Invoice> invoices = Lists.newArrayList(stripeClient.invoices().list(params, commonOptions())
.autoPagingIterable(null, commonOptions()));
.autoPagingIterable());
invoices.sort(Comparator.comparingLong(Invoice::getCreated).reversed());
return invoices;
} catch (StripeException e) {
@@ -677,7 +686,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
try {
final StripeCollection<InvoiceLineItem> lineItems = stripeClient.invoices().lineItems()
.list(invoice.getId(), commonOptions());
return Lists.newArrayList(lineItems.autoPagingIterable(null, commonOptions()));
return Lists.newArrayList(lineItems.autoPagingIterable());
} catch (final StripeException e) {
throw new CompletionException(e);
}
@@ -1,108 +0,0 @@
/*
* Copyright 2013-2022 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.controllers.StaleDevicesException;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
public class DestinationDeviceValidator {
/**
* @see #validateRegistrationIds(Account, Stream, boolean)
*/
public static <T> void validateRegistrationIds(final Account account,
final Collection<T> messages,
Function<T, Byte> getDeviceId,
Function<T, Integer> getRegistrationId,
boolean usePhoneNumberIdentity) throws StaleDevicesException {
validateRegistrationIds(account,
messages.stream().map(m -> new Pair<>(getDeviceId.apply(m), getRegistrationId.apply(m))),
usePhoneNumberIdentity);
}
/**
* Validates that the given device ID/registration ID pairs exactly match the corresponding device ID/registration ID
* pairs in the given destination account. This method does <em>not</em> validate that all devices associated with the
* destination account are present in the given device ID/registration ID pairs.
*
* @param account the destination account against which to check the given device
* ID/registration ID pairs
* @param deviceIdAndRegistrationIdStream a stream of device ID and registration ID pairs
* @param usePhoneNumberIdentity if {@code true}, compare provided registration IDs against device
* registration IDs associated with the account's PNI (if available); compare
* against the ACI-associated registration ID otherwise
* @throws StaleDevicesException if the device ID/registration ID pairs contained an entry for which the destination
* account does not have a corresponding device or if the registration IDs do not match
*/
public static void validateRegistrationIds(final Account account,
final Stream<Pair<Byte, Integer>> deviceIdAndRegistrationIdStream,
final boolean usePhoneNumberIdentity) throws StaleDevicesException {
final List<Byte> staleDevices = deviceIdAndRegistrationIdStream
.filter(deviceIdAndRegistrationId -> deviceIdAndRegistrationId.second() > 0)
.filter(deviceIdAndRegistrationId -> {
final byte deviceId = deviceIdAndRegistrationId.first();
final int registrationId = deviceIdAndRegistrationId.second();
boolean registrationIdMatches = account.getDevice(deviceId)
.map(device -> registrationId == (usePhoneNumberIdentity
? device.getPhoneNumberIdentityRegistrationId().orElse(device.getRegistrationId())
: device.getRegistrationId()))
.orElse(false);
return !registrationIdMatches;
})
.map(Pair::first)
.collect(Collectors.toList());
if (!staleDevices.isEmpty()) {
throw new StaleDevicesException(staleDevices);
}
}
/**
* Validates that the given set of device IDs from a set of messages matches the set of device IDs associated with the
* given destination account in preparation for sending those messages to the destination account. In general, the set
* of device IDs must exactly match the set of active devices associated with the destination account. When sending a
* "sync," message, though, the authenticated account is sending messages from one of their devices to all other
* devices; in that case, callers must pass the ID of the sending device in the set of {@code excludedDeviceIds}.
*
* @param account the destination account against which to check the given set of device IDs
* @param messageDeviceIds the set of device IDs to check against the destination account
* @param excludedDeviceIds a set of device IDs that may be associated with the destination account, but must not be
* present in the given set of device IDs (i.e. the device that is sending a sync message)
* @throws MismatchedDevicesException if the given set of device IDs contains entries not currently associated with
* the destination account or is missing entries associated with the destination
* account
*/
public static void validateCompleteDeviceList(final Account account,
final Set<Byte> messageDeviceIds,
final Set<Byte> excludedDeviceIds) throws MismatchedDevicesException {
final Set<Byte> accountDeviceIds = account.getDevices().stream()
.map(Device::getId)
.filter(deviceId -> !excludedDeviceIds.contains(deviceId))
.collect(Collectors.toSet());
final Set<Byte> missingDeviceIds = new HashSet<>(accountDeviceIds);
missingDeviceIds.removeAll(messageDeviceIds);
final Set<Byte> extraDeviceIds = new HashSet<>(messageDeviceIds);
extraDeviceIds.removeAll(accountDeviceIds);
if (!missingDeviceIds.isEmpty() || !extraDeviceIds.isEmpty()) {
throw new MismatchedDevicesException(new ArrayList<>(missingDeviceIds), new ArrayList<>(extraDeviceIds));
}
}
}
@@ -0,0 +1,29 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.util;
/**
* An abstract base class for exceptions that do not include a stack trace. Stackless exceptions are generally intended
* for internal error-handling cases where the error will never be logged or otherwise reported.
*/
public abstract class NoStackTraceException extends Exception {
public NoStackTraceException() {
super(null, null, true, false);
}
public NoStackTraceException(final String message) {
super(message, null, true, false);
}
public NoStackTraceException(final String message, final Throwable cause) {
super(message, cause, true, false);
}
public NoStackTraceException(final Throwable cause) {
super(null, cause, true, false);
}
}
@@ -5,7 +5,7 @@
package org.whispersystems.textsecuregcm.util.logging;
import ch.qos.logback.access.spi.IAccessEvent;
import ch.qos.logback.access.common.spi.IAccessEvent;
import ch.qos.logback.core.filter.Filter;
import com.fasterxml.jackson.annotation.JsonTypeName;
import io.dropwizard.logging.common.filter.FilterFactory;
@@ -5,7 +5,7 @@
package org.whispersystems.textsecuregcm.util.logging;
import ch.qos.logback.access.spi.IAccessEvent;
import ch.qos.logback.access.common.spi.IAccessEvent;
import ch.qos.logback.core.filter.Filter;
public class RequestLogManager {
@@ -61,16 +61,14 @@ public class ProvisioningConnectListener implements WebSocketConnectListener {
public void onWebSocketConnect(WebSocketSessionContext context) {
openWebSocketCounter.countOpenWebSocket(context);
final Optional<ScheduledFuture<?>> maybeTimeoutFuture = context.getClient().supportsProvisioningSocketTimeouts()
? Optional.of(timeoutExecutor.schedule(() ->
context.getClient().close(1000, "Timeout"), timeout.toSeconds(), TimeUnit.SECONDS))
: Optional.empty();
final ScheduledFuture<?> timeoutFuture = timeoutExecutor.schedule(() ->
context.getClient().close(1000, "Timeout"), timeout.toSeconds(), TimeUnit.SECONDS);
final String provisioningAddress = generateProvisioningAddress();
context.addWebsocketClosedListener((context1, statusCode, reason) -> {
provisioningManager.removeListener(provisioningAddress);
maybeTimeoutFuture.ifPresent(future -> future.cancel(false));
timeoutFuture.cancel(false);
});
provisioningManager.addListener(provisioningAddress, message -> {
@@ -49,7 +49,7 @@ public class WebSocketAccountAuthenticator implements WebSocketAuthenticator<Aut
return CREDENTIALS_NOT_PRESENTED;
}
return basicCredentialsFromAuthHeader(authHeader)
.flatMap(credentials -> accountAuthenticator.authenticate(credentials))
.flatMap(accountAuthenticator::authenticate)
.map(authenticatedAccount -> ReusableAuth.authenticated(authenticatedAccount, this.principalSupplier))
.orElse(INVALID_CREDENTIALS_PRESENTED);
}
@@ -508,8 +508,8 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
code = 4409;
message = "Connected elsewhere";
} else {
code = 1000;
message = "OK";
code = 4401;
message = "Reauthentication required";
}
client.close(code, message);
@@ -93,7 +93,14 @@ public class BackupMetricsCommand extends AbstractCommandWithDependencies {
}
timeSinceLastRefresh.record(timeSince(backupMetadata.lastRefresh()).getSeconds());
timeSinceLastMediaRefresh.record(timeSince(backupMetadata.lastMediaRefresh()).getSeconds());
Metrics.counter(backupsCounterName, "subscribed", String.valueOf(subscribed)).increment();
// Report that the backup is out of quota if it cannot store a max size media object
final boolean quotaExhausted = backupMetadata.bytesUsed() >=
(BackupManager.MAX_TOTAL_BACKUP_MEDIA_BYTES - BackupManager.MAX_MEDIA_OBJECT_SIZE);
Metrics.counter(backupsCounterName,
"subscribed", String.valueOf(subscribed),
"quotaExhausted", String.valueOf(quotaExhausted)).increment();
})
.count()
.block();
@@ -101,7 +108,7 @@ public class BackupMetricsCommand extends AbstractCommandWithDependencies {
}
private Duration timeSince(Instant t) {
Duration between = Duration.between(clock.instant(), t);
final Duration between = Duration.between(t, clock.instant());
if (between.isNegative()) {
return Duration.ZERO;
}
@@ -22,6 +22,7 @@ import java.util.concurrent.SynchronousQueue;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
import org.whispersystems.textsecuregcm.WhisperServerService;
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
@@ -105,7 +106,7 @@ record CommandDependencies(
final AwsCredentialsProvider awsCredentialsProvider = configuration.getAwsCredentialsConfiguration().build();
ScheduledExecutorService dynamicConfigurationExecutor = environment.lifecycle()
.scheduledExecutorService(name(name, "dynamicConfiguration-%d")).threads(1).build();
.scheduledExecutorService(name(WhisperServerService.class, "dynamicConfiguration-%d")).threads(1).build();
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
new DynamicConfigurationManager<>(
@@ -124,36 +125,36 @@ record CommandDependencies(
Scheduler messageDeliveryScheduler = Schedulers.fromExecutorService(
environment.lifecycle().executorService("messageDelivery").minThreads(4).maxThreads(4).build());
ExecutorService messageDeletionExecutor = environment.lifecycle()
.executorService(name(name, "messageDeletion-%d")).minThreads(4).maxThreads(4).build();
.executorService(name(WhisperServerService.class, "messageDeletion-%d")).minThreads(4).maxThreads(4).build();
ExecutorService secureValueRecoveryServiceExecutor = environment.lifecycle()
.executorService(name(name, "secureValueRecoveryService-%d")).maxThreads(8).minThreads(8).build();
.executorService(name(WhisperServerService.class, "secureValueRecoveryService-%d")).maxThreads(8).minThreads(8).build();
ExecutorService storageServiceExecutor = environment.lifecycle()
.executorService(name(name, "storageService-%d")).maxThreads(8).minThreads(8).build();
.executorService(name(WhisperServerService.class, "storageService-%d")).maxThreads(8).minThreads(8).build();
ExecutorService accountLockExecutor = environment.lifecycle()
.executorService(name(name, "accountLock-%d")).minThreads(8).maxThreads(8).build();
.executorService(name(WhisperServerService.class, "accountLock-%d")).minThreads(8).maxThreads(8).build();
ExecutorService remoteStorageHttpExecutor = environment.lifecycle()
.executorService(name(name, "remoteStorage-%d"))
.executorService(name(WhisperServerService.class, "remoteStorage-%d"))
.minThreads(0).maxThreads(Integer.MAX_VALUE).workQueue(new SynchronousQueue<>())
.keepAliveTime(io.dropwizard.util.Duration.seconds(60L)).build();
ExecutorService apnSenderExecutor = environment.lifecycle().executorService(name(name, "apnSender-%d"))
ExecutorService apnSenderExecutor = environment.lifecycle().executorService(name(WhisperServerService.class, "apnSender-%d"))
.maxThreads(1).minThreads(1).build();
ExecutorService fcmSenderExecutor = environment.lifecycle().executorService(name(name, "fcmSender-%d"))
ExecutorService fcmSenderExecutor = environment.lifecycle().executorService(name(WhisperServerService.class, "fcmSender-%d"))
.maxThreads(16).minThreads(16).build();
ExecutorService clientEventExecutor = environment.lifecycle()
.virtualExecutorService(name(name, "clientEvent-%d"));
.virtualExecutorService(name(WhisperServerService.class, "clientEvent-%d"));
ExecutorService asyncOperationQueueingExecutor = environment.lifecycle()
.executorService(name(name, "asyncOperationQueueing-%d")).minThreads(1).maxThreads(1).build();
.executorService(name(WhisperServerService.class, "asyncOperationQueueing-%d")).minThreads(1).maxThreads(1).build();
ExecutorService disconnectionRequestListenerExecutor = environment.lifecycle()
.virtualExecutorService(name(name, "disconnectionRequest-%d"));
.virtualExecutorService(name(WhisperServerService.class, "disconnectionRequest-%d"));
ScheduledExecutorService secureValueRecoveryServiceRetryExecutor = environment.lifecycle()
.scheduledExecutorService(name(name, "secureValueRecoveryServiceRetry-%d")).threads(1).build();
.scheduledExecutorService(name(WhisperServerService.class, "secureValueRecoveryServiceRetry-%d")).threads(1).build();
ScheduledExecutorService remoteStorageRetryExecutor = environment.lifecycle()
.scheduledExecutorService(name(name, "remoteStorageRetry-%d")).threads(1).build();
.scheduledExecutorService(name(WhisperServerService.class, "remoteStorageRetry-%d")).threads(1).build();
ScheduledExecutorService storageServiceRetryExecutor = environment.lifecycle()
.scheduledExecutorService(name(name, "storageServiceRetry-%d")).threads(1).build();
.scheduledExecutorService(name(WhisperServerService.class, "storageServiceRetry-%d")).threads(1).build();
ScheduledExecutorService messagePollExecutor = environment.lifecycle()
.scheduledExecutorService(name(name, "messagePollExecutor-%d")).threads(1).build();
.scheduledExecutorService(name(WhisperServerService.class, "messagePollExecutor-%d")).threads(1).build();
ExternalServiceCredentialsGenerator storageCredentialsGenerator = SecureStorageController.credentialsGenerator(
configuration.getSecureStorageServiceConfiguration());
@@ -161,7 +162,7 @@ record CommandDependencies(
configuration.getSvr2Configuration());
final ExecutorService awsSdkMetricsExecutor = environment.lifecycle()
.virtualExecutorService(MetricRegistry.name(CommandDependencies.class, "awsSdkMetrics-%d"));
.virtualExecutorService(MetricRegistry.name(WhisperServerService.class, "awsSdkMetrics-%d"));
DynamoDbAsyncClient dynamoDbAsyncClient = configuration.getDynamoDbClientConfiguration()
.buildAsyncClient(awsCredentialsProvider, new MicrometerAwsSdkMetricPublisher(awsSdkMetricsExecutor, "dynamoDbAsyncCommand"));
@@ -16,7 +16,9 @@ import org.whispersystems.textsecuregcm.storage.MessagesManager;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuples;
import reactor.util.retry.Retry;
import java.time.Clock;
import java.time.Duration;
import java.time.LocalTime;
public class NotifyIdleDevicesCommand extends AbstractSinglePassCrawlAccountsCommand {
@@ -79,7 +81,16 @@ public class NotifyIdleDevicesCommand extends AbstractSinglePassCrawlAccountsCom
.doOnNext(ignored -> DEVICE_INSPECTED_COUNTER.increment())
.flatMap(accountAndDevice -> Mono.fromFuture(() ->
idleWakeupEligibilityChecker.isDeviceEligible(accountAndDevice.getT1(), accountAndDevice.getT2()))
.mapNotNull(eligible -> eligible ? accountAndDevice : null),
.mapNotNull(eligible -> eligible ? accountAndDevice : null)
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1)))
.onErrorResume(throwable -> {
log.warn("Failed to check eligibility for {}:{}",
accountAndDevice.getT1().getIdentifier(IdentityType.ACI),
accountAndDevice.getT2().getId(),
throwable);
return Mono.empty();
}),
maxConcurrency)
.flatMap(accountAndDevice -> {
final Account account = accountAndDevice.getT1();
@@ -20,6 +20,7 @@ import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Flux;
import reactor.util.retry.Retry;
public class RemoveExpiredAccountsCommand extends AbstractSinglePassCrawlAccountsCommand {
@@ -70,6 +71,7 @@ public class RemoveExpiredAccountsCommand extends AbstractSinglePassCrawlAccount
return deleteAccountMono
.doOnSuccess(ignored -> deletedAccountCounter.increment())
.retryWhen(Retry.backoff(8, Duration.ofSeconds(1)).maxBackoff(Duration.ofSeconds(4)))
.onErrorResume(throwable -> {
log.warn("Failed to delete account {}", expiredAccount.getUuid(), throwable);
return Mono.empty();
@@ -22,6 +22,7 @@ import org.whispersystems.textsecuregcm.backup.ExpiredBackup;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import reactor.util.retry.Retry;
public class RemoveExpiredBackupsCommand extends AbstractCommandWithDependencies {
@@ -119,6 +120,7 @@ public class RemoveExpiredBackupsCommand extends AbstractCommandWithDependencies
}
return mono
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1)))
.doOnSuccess(ignored -> {
logger.trace("Successfully expired {} for {}",
expiredBackup.expirationType(),
Loaded 100 of 163 files, more files were not shown because too many files have changed in this diff. Show more