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
121 changed files with 2879 additions and 3313 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
@@ -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=
-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
+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>
@@ -301,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
@@ -539,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;
}
@@ -85,7 +85,6 @@ 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;
@@ -179,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;
@@ -365,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());
}
});
}
@@ -509,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
@@ -669,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(),
@@ -959,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
@@ -1075,7 +1076,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
registrationLockVerificationManager, rateLimiters),
new AttachmentControllerV4(rateLimiters, gcsAttachmentGenerator, tusAttachmentGenerator,
experimentEnrollmentManager),
new ArchiveController(backupAuthManager, backupManager),
new ArchiveController(backupAuthManager, backupManager, backupMetrics),
new CallRoutingControllerV2(rateLimiters, cloudflareTurnCredentialsManager),
new CallLinkController(rateLimiters, callingGenericZkSecretParams),
new CertificateController(new CertificateGenerator(config.getDeliveryCertificate().certificate().value(),
@@ -1094,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
);
}
@@ -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
);
}
}
@@ -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,
@@ -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) {
}
@@ -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;
}
}
@@ -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(
@@ -247,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) {
@@ -258,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(
@@ -586,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
@@ -605,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");
@@ -683,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
@@ -701,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())
@@ -836,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(
@@ -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);
@@ -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;
}
}
@@ -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) {
}
@@ -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()
@@ -19,6 +19,7 @@ public class DeviceCapabilityUtil {
case DEVICE_CAPABILITY_TRANSFER -> DeviceCapability.TRANSFER;
case DEVICE_CAPABILITY_DELETE_SYNC -> DeviceCapability.DELETE_SYNC;
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,6 +30,7 @@ public class DeviceCapabilityUtil {
case TRANSFER -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_TRANSFER;
case DELETE_SYNC -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_DELETE_SYNC;
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;
@@ -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) {
@@ -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 {
}
@@ -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);
}
@@ -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());
}
};
}
}
@@ -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){}
@@ -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,11 +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),
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,
}
@@ -24,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,
@@ -45,26 +45,25 @@ public class MessagePersister implements Managed {
private static final String OVERSIZED_QUEUE_COUNTER_NAME = name(MessagePersister.class, "persistQueueOversized");
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 static final Counter trimmedMessageCounter = Metrics.counter(name(MessagePersister.class, "trimmedMessage"));
private static final Counter trimmedMessageBytesCounter = Metrics.counter(name(MessagePersister.class, "trimmedMessageBytes"));
private final DistributionSummary queueCountDistributionSummery = DistributionSummary.builder(
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;
static final int MESSAGE_BATCH_LIMIT = 100;
static final int CACHE_PAGE_SIZE = 100;
private static final long EXCEPTION_PAUSE_MILLIS = Duration.ofSeconds(3).toMillis();
@@ -93,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);
@@ -145,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) {
@@ -165,7 +164,7 @@ 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);
@@ -216,7 +215,7 @@ public class MessagePersister implements Managed {
} while (!messages.isEmpty());
queueSizeDistributionSummery.record(messageCount);
QUEUE_SIZE_DISTRIBUTION_SUMMARY.record(messageCount);
} catch (ItemCollectionSizeLimitExceededException e) {
final boolean isPrimary = deviceId == Device.PRIMARY_ID;
Metrics.counter(OVERSIZED_QUEUE_COUNTER_NAME, "primary", String.valueOf(isPrimary)).increment();
@@ -233,7 +232,7 @@ public class MessagePersister implements Managed {
}
} finally {
messagesCache.unlockQueueForPersistence(accountUuid, deviceId);
sample.stop(persistQueueTimer);
sample.stop(PERSIST_QUEUE_TIMER);
}
}
@@ -250,10 +249,7 @@ public class MessagePersister implements Managed {
final Device device = maybeDevice.get();
// Calculate how many bytes we should trim
final long cachedMessageBytes = Flux
.from(messagesCache.getMessagesToPersistReactive(aci, deviceId, CACHE_PAGE_SIZE))
.reduce(0, (acc, envelope) -> acc + envelope.getSerializedSize())
.block();
final long cachedMessageBytes = messagesCache.estimatePersistedQueueSizeBytes(aci, deviceId).join();
final double extraRoomRatio = this.dynamicConfigurationManager.getConfiguration()
.getMessagePersisterConfiguration()
.getTrimOversizedQueueExtraRoomRatio();
@@ -276,8 +272,8 @@ public class MessagePersister implements Managed {
.takeWhile(Optional::isPresent)
.flatMap(maybeEnvelope -> {
final MessageProtos.Envelope envelope = maybeEnvelope.get();
trimmedMessageCounter.increment();
trimmedMessageBytesCounter.increment(envelope.getSerializedSize());
TRIMMED_MESSAGE_COUNTER.increment();
TRIMMED_MESSAGE_BYTES_COUNTER.increment(envelope.getSerializedSize());
return Mono
.fromCompletionStage(() -> messagesManager
.delete(aci, device, UUID.fromString(envelope.getServerGuid()), envelope.getServerTimestamp()))
@@ -50,7 +50,6 @@ import org.whispersystems.textsecuregcm.util.RedisClusterUtil;
import reactor.core.observability.micrometer.Micrometer;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Sinks;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;
@@ -135,6 +134,7 @@ 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"));
@@ -274,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);
});
}
@@ -534,11 +540,13 @@ public class MessagesCache {
});
}
Flux<MessageProtos.Envelope> getMessagesToPersistReactive(final UUID accountUuid, final byte destinationDevice,
final int pageSize) {
final Timer.Sample sample = Timer.start();
/**
* 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(
@@ -546,12 +554,8 @@ public class MessagesCache {
Range.from(
start.map(Range.Boundary::excluding).orElse(Range.Boundary.unbounded()),
Range.Boundary.unbounded()),
Limit.from(pageSize))));
final Sinks.Many<MessageProtos.Envelope> staleEphemeralMessages = Sinks.many().unicast().onBackpressureBuffer();
final Sinks.Many<MessageProtos.Envelope> staleMrmMessages = Sinks.many().unicast().onBackpressureBuffer();
final Flux<MessageProtos.Envelope> messagesToPersist = getNextPage.apply(Optional.empty())
Limit.from(PAGE_SIZE))));
final Flux<byte[]> allSerializedMessages = getNextPage.apply(Optional.empty())
.expand(scoredValues -> {
if (scoredValues.isEmpty()) {
return Mono.empty();
@@ -559,7 +563,45 @@ public class MessagesCache {
long lastTimestamp = (long) scoredValues.getLast().getScore();
return getNextPage.apply(Optional.of(lastTimestamp));
})
.concatMap(scoredValues -> Flux.fromStream(scoredValues.stream().map(ScoredValue::getValue)))
.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) {
final Timer.Sample sample = Timer.start();
final List<byte[]> messages = redisCluster.withBinaryCluster(connection ->
connection.sync().zrange(getMessageQueueKey(accountUuid, destinationDevice), 0, limit));
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);
@@ -577,36 +619,9 @@ public class MessagesCache {
}
return messageMono;
})
.doOnNext(envelope -> {
if (envelope.getEphemeral()) {
staleEphemeralMessages.tryEmitNext(envelope).orThrow();
} else if (isStaleMrmMessage(envelope)) {
// clearing the sharedMrmKey prevents unnecessary calls to update the shared MRM data
staleMrmMessages.tryEmitNext(envelope.toBuilder().clearSharedMrmKey().build()).orThrow();
}
})
.filter(Predicate.not(envelope -> envelope.getEphemeral() || isStaleMrmMessage(envelope)));
discardStaleMessages(accountUuid, destinationDevice, staleEphemeralMessages.asFlux(), staleEphemeralMessagesCounter, "ephemeral");
discardStaleMessages(accountUuid, destinationDevice, staleMrmMessages.asFlux(), staleMrmMessagesCounter, "mrm");
return messagesToPersist
.doFinally(signal -> {
sample.stop(getMessagesTimer);
staleEphemeralMessages.tryEmitComplete();
staleMrmMessages.tryEmitComplete();
});
}
List<MessageProtos.Envelope> getMessagesToPersist(final UUID accountUuid, final byte destinationDevice,
final int limit) {
return getMessagesToPersistReactive(accountUuid, destinationDevice, limit)
.take(limit)
.collectList()
.block(Duration.ofSeconds(5));
}
public CompletableFuture<Void> clear(final UUID destinationUuid) {
return CompletableFuture.allOf(
Device.ALL_POSSIBLE_DEVICE_IDS.stream()
@@ -56,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";
@@ -67,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,
@@ -126,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");
@@ -276,6 +279,9 @@ public class MessagesManager {
messagesRemovedFromCache = messagesCache.remove(destinationUuid, destinationDevice.getId(), messageGuids)
.get(30, TimeUnit.SECONDS).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);
@@ -410,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);
}
@@ -459,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);
@@ -528,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) {
@@ -686,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 -> {
@@ -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;
}
@@ -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(),
@@ -5,9 +5,18 @@
package org.whispersystems.textsecuregcm.workers;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import net.sourceforge.argparse4j.inf.Subparser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -16,15 +25,7 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import reactor.util.retry.Retry;
public class RemoveExpiredUsernameHoldsCommand extends AbstractSinglePassCrawlAccountsCommand {
@@ -91,6 +92,7 @@ public class RemoveExpiredUsernameHoldsCommand extends AbstractSinglePassCrawlAc
"expiredHolds", String.valueOf(holdsToRemove > 0))
.increment();
return purgeMono
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1)))
.doOnSuccess(ignored -> deletedHoldsCounter.increment(holdsToRemove))
.onErrorResume(throwable -> {
log.warn("Failed to purge {} expired holds on account {}", holdsToRemove, account.getUuid());
+2 -2
View File
@@ -11,13 +11,13 @@ option java_outer_classname = "MessageProtos";
message Envelope {
enum Type {
reserved 2, 7;
UNKNOWN = 0;
CIPHERTEXT = 1;
KEY_EXCHANGE = 2;
PREKEY_BUNDLE = 3;
SERVER_DELIVERY_RECEIPT = 5;
UNIDENTIFIED_SENDER = 6;
reserved 7;
PLAINTEXT_CONTENT = 8; // for decryption error receipts
}
@@ -100,6 +100,7 @@ enum DeviceCapability {
DEVICE_CAPABILITY_DELETE_SYNC = 3;
reserved 4;
DEVICE_CAPABILITY_STORAGE_SERVICE_RECORD_KEY_ROTATION = 5;
DEVICE_CAPABILITY_ATTACHMENT_BACKFILL = 6;
}
message ZkCredential {
@@ -0,0 +1,494 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
syntax = "proto3";
option java_multiple_files = true;
package org.signal.chat.messages;
import "org/signal/chat/common.proto";
import "org/signal/chat/require.proto";
/**
* Provides methods for sending "unsealed sender" messages.
*/
service Messages {
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
/**
* Sends an "unsealed sender" message to all devices linked to a single
* destination account.
*
* This RPC may fail with a `NOT_FOUND` status if the destination account was
* not found. It may also fail with a `RESOURCE_EXHAUSTED` status if a rate
* limit for sending messages has been exceeded, in which case a `retry-after`
* header containing an ISO 8601 duration string may be present in the
* response trailers.
*
* Note that message delivery may not succeed even if this RPC returns an `OK`
* status; callers must check the response object to verify that the message
* was actually accepted and sent.
*/
rpc SendMessage(SendAuthenticatedSenderMessageRequest) returns (SendMessageResponse) {}
/**
* Sends a "sync" message to all other devices linked to the authenticated
* sender's account. This RPC may fail with a `RESOURCE_EXHAUSTED` status if a
* rate limit for sending messages has been exceeded, in which case a
* `retry-after` header containing an ISO 8601 duration string may be present
* in the response trailers.
*
* Note that message delivery may not succeed even if this RPC returns an `OK`
* status; callers must check the response object to verify that the message
* was actually accepted and sent.
*/
rpc SendSyncMessage(SendSyncMessageRequest) returns (SendMessageResponse) {}
}
/**
* Provides methods for sending "sealed sender" messages.
*/
service MessagesAnonymous {
option (require.auth) = AUTH_ONLY_ANONYMOUS;
/**
* Sends a "sealed sender" message to all devices linked to a single
* destination account.
*
* This RPC may fail with an `UNAUTHENTICATED` status if the given credentials
* were not accepted for any reason or if the destination account was not
* found while using an unidentified access key (UAK) for authorization. It
* may also fail with a `NOT_FOUND` status if the destination account was not
* found while using a group send token for authorization. It may also fail
* with a `RESOURCE_EXHAUSTED` status if a rate limit for sending messages has
* been exceeded, in which case a `retry-after` header containing an ISO 8601
* duration string may be present in the response trailers.
*
* Note that message delivery may not succeed even if this RPC returns an `OK`
* status; callers must check the response object to verify that the message
* was actually accepted and sent.
*/
rpc SendSingleRecipientMessage(SendSealedSenderMessageRequest) returns (SendMessageResponse) {}
/**
* Sends a "sealed sender" message with a common payload to all devices linked
* to multiple destination accounts.
*
* This RPC may fail with a `NOT_FOUND` status if one or more destination
* accounts were not found. It may also fail with an `UNAUTHENTICATED` status
* if the given credentials were not accepted for any reason. It may also fail
* with a `RESOURCE_EXHAUSTED` status if a rate limit for sending messages has
* been exceeded, in which case a `retry-after` header containing an ISO 8601
* duration string may be present in the response trailers.
*
* Note that message delivery may not succeed even if this RPC returns an `OK`
* status; callers must check the response object to verify that the message
* was actually accepted and sent.
*/
rpc SendMultiRecipientMessage(SendMultiRecipientMessageRequest) returns (SendMultiRecipientMessageResponse) {}
/**
* Sends a story message to devices linked to a single destination account.
*
* This RPC may fail with a `RESOURCE_EXHAUSTED` status if a rate limit for
* sending stories has been exceeded, in which case a `retry-after` header
* containing an ISO 8601 duration string may be present in the response
* trailers.
*
* Note that message delivery may not succeed even if this RPC returns an `OK`
* status; callers must check the response object to verify that the message
* was actually accepted and sent.
*/
rpc SendStory(SendStoryMessageRequest) returns (SendMessageResponse) {}
/**
* Sends a story message with a common payload to devices linked to devices
* linked to multiple destination accounts.
*
* This RPC may fail with a `RESOURCE_EXHAUSTED` status if a rate limit for
* sending stories has been exceeded, in which case a `retry-after` header
* containing an ISO 8601 duration string may be present in the response
* trailers.
*
* Note that message delivery may not succeed even if this RPC returns an `OK`
* status; callers must check the response object to verify that the message
* was actually accepted and sent.
*/
rpc SendMultiRecipientStory(SendMultiRecipientStoryRequest) returns (SendMultiRecipientMessageResponse) {}
}
message IndividualRecipientMessageBundle {
/**
* A message for an individual device linked to a destination account.
*/
message Message {
/**
* The registration ID for the destination device.
*/
uint32 registration_id = 1 [(require.range).max = 0x3fff];
/**
* The content of the message to deliver to the destination device.
*/
bytes payload = 2 [(require.size).max = 262144]; // 256 KiB
}
/**
* The time, in milliseconds since the epoch, at which this message was
* originally sent from the perspective of the sender.
*/
uint64 timestamp = 1;
/**
* A map of device IDs to individual messages. Generally, callers must include
* one message for each device linked to the destination account. In cases of
* "sync messages" where a sender is distributing information to other devices
* linked to the sender's account, senders may omit a message for the sending
* device.
*/
map<uint32, Message> messages = 2 [(require.nonEmpty) = true];
}
enum AuthenticatedSenderMessageType {
UNSPECIFIED = 0;
/**
* A double-ratchet message represents a "normal," "unsealed-sender" message
* encrypted using the Double Ratchet within an established Signal session.
*/
DOUBLE_RATCHET = 1;
/**
* A prekey message begins a new Signal session. The `content` of a prekey
* message is a superset of a double-ratchet message's `content` and
* contains the sender's identity public key and information identifying the
* pre-keys used in the message's ciphertext.
*/
PREKEY_MESSAGE = 2;
/**
* A plaintext message is used solely to convey encryption error receipts
* and never contains encrypted message content. Encryption error receipts
* must be delivered in plaintext because, encryption/decryption of a prior
* message failed and there is no reason to believe that
* encryption/decryption of subsequent messages with the same key material
* would succeed.
*
* Critically, plaintext messages never have "real" message content
* generated by users. Plaintext messages include sender information.
*/
PLAINTEXT_CONTENT = 3;
}
message SendAuthenticatedSenderMessageRequest {
/**
* The service identifier of the account to which to deliver the message.
*/
common.ServiceIdentifier destination = 1;
/**
* The type identifier for this message.
*/
AuthenticatedSenderMessageType type = 2 [(require.specified) = true];
/**
* If true, this message will only be delivered to destination devices that
* have an active message delivery channel with a Signal server.
*/
bool ephemeral = 3;
/**
* Indicates whether this message is urgent and should trigger a high-priority
* notification if the destination device does not have an active message
* delivery channel with a Signal server
*/
bool urgent = 4;
/**
* The messages to send to the destination account.
*/
IndividualRecipientMessageBundle messages = 5;
}
message SendSyncMessageRequest {
/**
* The type identifier for this message.
*/
AuthenticatedSenderMessageType type = 1 [(require.specified) = true];
/**
* Indicates whether this message is urgent and should trigger a high-priority
* notification if the destination device does not have an active message
* delivery channel with a Signal server
*/
bool urgent = 2;
/**
* The messages to send to the destination account.
*/
IndividualRecipientMessageBundle messages = 3;
}
message SendSealedSenderMessageRequest {
/**
* The service identifier of the account to which to deliver the message.
*/
common.ServiceIdentifier destination = 1;
/**
* If true, this message will only be delivered to destination devices that
* have an active message delivery channel with a Signal server.
*/
bool ephemeral = 2;
/**
* Indicates whether this message is urgent and should trigger a high-priority
* notification if the destination device does not have an active message
* delivery channel with a Signal server
*/
bool urgent = 3;
/**
* The messages to send to the destination account.
*/
IndividualRecipientMessageBundle messages = 4;
/**
* A means to authorize the request.
*/
oneof authorization {
/**
* The unidentified access key (UAK) for the destination account.
*/
bytes unidentified_access_key = 5;
/**
* A group send endorsement token for the destination account.
*/
bytes group_send_token = 6;
}
}
message SendStoryMessageRequest {
/**
* The service identifier of the account to which to deliver the message.
*/
common.ServiceIdentifier destination = 1;
/**
* Indicates whether this message is urgent and should trigger a high-priority
* notification if the destination device does not have an active message
* delivery channel with a Signal server
*/
bool urgent = 2;
/**
* The messages to send to the destination account.
*/
IndividualRecipientMessageBundle messages = 3;
}
message SendMessageResponse {
/**
* An error preventing message delivery. If not set, then the message(s) in
* the original request were sent to all destination devices.
*/
oneof error {
/**
* A list of discrepancies between the destination devices identified in a
* request to send a message and the devices that are actually linked to an
* account.
*/
MismatchedDevices mismatched_devices = 1;
/**
* A description of a challenge callers must complete before sending
* additional messages.
*/
ChallengeRequired challenge_required = 2;
}
}
message MultiRecipientMessage {
/**
* The time, in milliseconds since the epoch, at which this message was
* originally sent from the perspective of the sender.
*/
uint64 timestamp = 1;
/**
* The serialized multi-recipient message payload.
*/
bytes payload = 2 [(require.size).max = 762144]; // 256 KiB payload + (5000 * 100) of overhead
}
message SendMultiRecipientMessageRequest {
/**
* If true, this message will only be delivered to destination devices that
* have an active message delivery channel with a Signal server.
*/
bool ephemeral = 1;
/**
* Indicates whether this message is urgent and should trigger a high-priority
* notification if the destination device does not have an active message
* delivery channel with a Signal server
*/
bool urgent = 2;
/**
* The multi-recipient message to send to all destination accounts and
* devices.
*/
MultiRecipientMessage message = 3;
/**
* A group send endorsement token for the destination account.
*/
bytes group_send_token = 4;
}
message SendMultiRecipientStoryRequest {
/**
* Indicates whether this message is urgent and should trigger a high-priority
* notification if the destination device does not have an active message
* delivery channel with a Signal server
*/
bool urgent = 1;
/**
* The multi-recipient story message to send to all destination accounts and
* devices.
*/
MultiRecipientMessage message = 2;
}
message SendMultiRecipientMessageResponse {
/**
* A list of destination service identifiers that could not be resolved to
* registered Signal accounts. If `mismatched_devices` is empty, then the
* message in the original request was sent to all service identifiers/devices
* in the original request except for the destination devices associated with
* the service identifiers in this list.
*/
repeated common.ServiceIdentifier unresolved_recipients = 1;
/**
* An error preventing message delivery. If not set, then the message was sent
* to some or all destination accounts/devices identified in the original
* request.
*/
oneof error {
/**
* A list of sets of discrepancies between the destination devices
* identified in a request to send a message and the devices that are
* actually linked to a destination account.
*/
MultiRecipientMismatchedDevices mismatched_devices = 2;
/**
* A description of a challenge callers must complete before sending
* additional messages.
*/
ChallengeRequired challenge_required = 3;
}
}
message MismatchedDevices {
/**
* The service identifier to which the devices named in this object are
* linked.
*/
common.ServiceIdentifier service_identifier = 1;
/**
* A list of device IDs that are linked to the destination account, but were
* not included in the collection of messages bound for the destination
* account.
*/
repeated uint32 missing_devices = 2 [(require.range).max = 0x7f];
/**
* A list of device IDs that were included in the collection of messages bound
* for the destination account, but are not currently linked to the
* destination account.
*/
repeated uint32 extra_devices = 3 [(require.range).max = 0x7f];
/**
* A list of device IDs that present in the collection of messages bound for
* the destination account and are linked to the destination account, but have
* a different registration ID than the registration ID presented by the
* sender (indicating that the destination device has likely been replaced by
* another device).
*/
repeated uint32 stale_devices = 4 [(require.range).max = 0x7f];
}
message MultiRecipientMismatchedDevices {
/**
* A list of sets of discrepancies between the destination devices identified
* in a request to send a message and the devices that are actually linked to
* a destination account.
*/
repeated MismatchedDevices mismatched_devices = 1;
}
message ChallengeRequired {
enum ChallengeType {
UNSPECIFIED = 0;
/**
* A challenge that callers can fulfill by completing a captcha.
*/
CAPTCHA = 1;
/**
* A challenge that callers can fulfill by supplying a token delivered via
* push notification.
*/
PUSH_CHALLENGE = 2;
};
/**
* An opaque token identifying this challenge request. Clients must generally
* submit this token when submitting a challenge response.
*/
bytes token = 1;
/**
* A list of challenge types callers may choose to complete to resolve the
* challenge requirement. May be empty, in which case callers cannot resolve
* the challenge by any means other than waiting.
*/
repeated ChallengeType challenge_options = 2;
/**
* A duration (in seconds) after which the challenge requirement may be
* resolved by simply waiting. May not be set if the challenge cannot be
* resolved by waiting.
*/
optional uint64 retry_after_seconds = 3;
}
@@ -133,7 +133,6 @@ public class ProvisioningTimeoutIntegrationTest {
.thenReturn(mock(ScheduledFuture.class));
final ClientUpgradeRequest upgradeRequest = new ClientUpgradeRequest();
upgradeRequest.setHeader(WebsocketHeaders.X_SIGNAL_WEBSOCKET_TIMEOUT_HEADER, "");
try (Session ignored = client.connect(testWebsocketListener,
URI.create(String.format("ws://127.0.0.1:%d/websocket", DROPWIZARD_APP_EXTENSION.getLocalPort())),
upgradeRequest).join()) {
@@ -151,22 +150,6 @@ public class ProvisioningTimeoutIntegrationTest {
}
}
@Test
public void websocketTimeoutNoHeader() throws IOException {
final TestProvisioningListener testWebsocketListener = new TestProvisioningListener();
final ClientUpgradeRequest upgradeRequest = new ClientUpgradeRequest();
try (Session ignored = client.connect(testWebsocketListener,
URI.create(String.format("ws://127.0.0.1:%d/websocket", DROPWIZARD_APP_EXTENSION.getLocalPort())),
upgradeRequest).join()) {
assertThat(testWebsocketListener.closeFuture()).isNotDone();
final TestApplication testApplication = DROPWIZARD_APP_EXTENSION.getApplication();
verify(testApplication.scheduler, never()).schedule(any(Runnable.class), anyLong(), any());
assertThat(testWebsocketListener.closeFuture()).isNotDone();
}
}
@Test
public void websocketTimeoutCancelled() throws IOException {
final TestProvisioningListener testWebsocketListener = new TestProvisioningListener();
@@ -176,7 +159,6 @@ public class ProvisioningTimeoutIntegrationTest {
doReturn(scheduled).when(testApplication.scheduler).schedule(any(Runnable.class), anyLong(), any());
final ClientUpgradeRequest upgradeRequest = new ClientUpgradeRequest();
upgradeRequest.setHeader(WebsocketHeaders.X_SIGNAL_WEBSOCKET_TIMEOUT_HEADER, "");
final Session session = client.connect(testWebsocketListener,
URI.create(String.format("ws://127.0.0.1:%d/websocket", DROPWIZARD_APP_EXTENSION.getLocalPort())),
upgradeRequest).join();
@@ -1,101 +0,0 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.calls.routing;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.stream.Stream;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
public class CallDnsRecordsManagerTest {
@Test
public void testParseDnsRecords() throws IOException {
var input = """
{
"aByRegion": {
"datacenter-1": [
"127.0.0.1"
],
"datacenter-2": [
"127.0.0.2",
"127.0.0.3"
],
"datacenter-3": [
"127.0.0.4",
"127.0.0.5"
],
"datacenter-4": [
"127.0.0.6",
"127.0.0.7"
]
},
"aaaaByRegion": {
"datacenter-1": [
"2600:1111:2222:3333:0:20:0:0",
"2600:1111:2222:3333:0:21:0:0",
"2600:1111:2222:3333:0:22:0:0"
],
"datacenter-2": [
"2600:1111:2222:3333:0:23:0:0",
"2600:1111:2222:3333:0:24:0:0"
],
"datacenter-3": [
"2600:1111:2222:3333:0:25:0:0",
"2600:1111:2222:3333:0:26:0:0"
],
"datacenter-4": [
"2600:1111:2222:3333:0:27:0:0"
]
}
}
""";
var actual = CallDnsRecordsManager.parseRecords(new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)));
var expected = new CallDnsRecords(
Map.of(
"datacenter-1", Stream.of("127.0.0.1").map(this::getAddressByName).toList(),
"datacenter-2", Stream.of("127.0.0.2", "127.0.0.3").map(this::getAddressByName).toList(),
"datacenter-3", Stream.of("127.0.0.4", "127.0.0.5").map(this::getAddressByName).toList(),
"datacenter-4", Stream.of("127.0.0.6", "127.0.0.7").map(this::getAddressByName).toList()
),
Map.of(
"datacenter-1", Stream.of(
"2600:1111:2222:3333:0:20:0:0",
"2600:1111:2222:3333:0:21:0:0",
"2600:1111:2222:3333:0:22:0:0"
).map(this::getAddressByName).toList(),
"datacenter-2", Stream.of(
"2600:1111:2222:3333:0:23:0:0",
"2600:1111:2222:3333:0:24:0:0")
.map(this::getAddressByName).toList(),
"datacenter-3", Stream.of(
"2600:1111:2222:3333:0:25:0:0",
"2600:1111:2222:3333:0:26:0:0")
.map(this::getAddressByName).toList(),
"datacenter-4", Stream.of(
"2600:1111:2222:3333:0:27:0:0"
).map(this::getAddressByName).toList()
)
);
assertThat(actual).isEqualTo(expected);
}
InetAddress getAddressByName(String ip) {
try {
return InetAddress.getByName(ip) ;
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
}
@@ -1,245 +0,0 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.calls.routing;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.io.StringReader;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class CallRoutingTableParserTest {
@Test
public void testParserSuccess() throws IOException {
var input =
"""
192.1.12.0/24 datacenter-1 datacenter-2 datacenter-3
193.123.123.0/24 datacenter-1 datacenter-2
1.123.123.0/24 datacenter-1
2001:db8:b0aa::/48 datacenter-1
2001:db8:b0ab::/48 datacenter-3 datacenter-1 datacenter-2
2001:db8:b0ac::/48 datacenter-2 datacenter-1
SA-SR-v4 datacenter-3
SA-UY-v4 datacenter-3 datacenter-1 datacenter-2
NA-US-VA-v6 datacenter-2 datacenter-1
""";
var actual = CallRoutingTableParser.fromTsv(new StringReader(input));
var expected = new CallRoutingTable(
Map.of(
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("192.1.12.0/24"), List.of("datacenter-1", "datacenter-2", "datacenter-3"),
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("193.123.123.0/24"), List.of("datacenter-1", "datacenter-2"),
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("1.123.123.0/24"), List.of("datacenter-1")
),
Map.of(
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0aa::/48"), List.of("datacenter-1"),
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0ab::/48"), List.of("datacenter-3", "datacenter-1", "datacenter-2"),
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0ac::/48"), List.of("datacenter-2", "datacenter-1")
),
Map.of(
new CallRoutingTable.GeoKey("SA", "SR", Optional.empty(), CallRoutingTable.Protocol.v4), List.of("datacenter-3"),
new CallRoutingTable.GeoKey("SA", "UY", Optional.empty(), CallRoutingTable.Protocol.v4), List.of("datacenter-3", "datacenter-1", "datacenter-2"),
new CallRoutingTable.GeoKey("NA", "US", Optional.of("VA"), CallRoutingTable.Protocol.v6), List.of("datacenter-2", "datacenter-1")
)
);
assertThat(actual).isEqualTo(expected);
}
@Test
public void testParserVariousWhitespaceSuccess() throws IOException {
var input =
"""
192.1.12.0/24\t \tdatacenter-1\t\t datacenter-2 datacenter-3
\t193.123.123.0/24\tdatacenter-1\tdatacenter-2
1.123.123.0/24\t datacenter-1
2001:db8:b0aa::/48\t \tdatacenter-1
2001:db8:b0ab::/48 \tdatacenter-3\tdatacenter-1 datacenter-2
2001:db8:b0ac::/48\tdatacenter-2\tdatacenter-1
SA-SR-v4 datacenter-3
SA-UY-v4\tdatacenter-3\tdatacenter-1\tdatacenter-2
NA-US-VA-v6 datacenter-2 \tdatacenter-1
""";
var actual = CallRoutingTableParser.fromTsv(new StringReader(input));
var expected = new CallRoutingTable(
Map.of(
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("192.1.12.0/24"), List.of("datacenter-1", "datacenter-2", "datacenter-3"),
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("193.123.123.0/24"), List.of("datacenter-1", "datacenter-2"),
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("1.123.123.0/24"), List.of("datacenter-1")
),
Map.of(
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0aa::/48"), List.of("datacenter-1"),
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0ab::/48"), List.of("datacenter-3", "datacenter-1", "datacenter-2"),
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0ac::/48"), List.of("datacenter-2", "datacenter-1")
),
Map.of(
new CallRoutingTable.GeoKey("SA", "SR", Optional.empty(), CallRoutingTable.Protocol.v4), List.of("datacenter-3"),
new CallRoutingTable.GeoKey("SA", "UY", Optional.empty(), CallRoutingTable.Protocol.v4), List.of("datacenter-3", "datacenter-1", "datacenter-2"),
new CallRoutingTable.GeoKey("NA", "US", Optional.of("VA"), CallRoutingTable.Protocol.v6), List.of("datacenter-2", "datacenter-1")
)
);
assertThat(actual).isEqualTo(expected);
}
@Test
public void testParserMissingSection() throws IOException {
var input =
"""
192.1.12.0/24\t \tdatacenter-1\t\t datacenter-2 datacenter-3
193.123.123.0/24\tdatacenter-1\tdatacenter-2
1.123.123.0/24\t datacenter-1
SA-SR-v4 datacenter-3
SA-UY-v4\tdatacenter-3\tdatacenter-1\tdatacenter-2
NA-US-VA-v6 datacenter-2 \tdatacenter-1
""";
var actual = CallRoutingTableParser.fromTsv(new StringReader(input));
var expected = new CallRoutingTable(
Map.of(
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("192.1.12.0/24"), List.of("datacenter-1", "datacenter-2", "datacenter-3"),
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("193.123.123.0/24"), List.of("datacenter-1", "datacenter-2"),
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("1.123.123.0/24"), List.of("datacenter-1")
),
Map.of(),
Map.of(
new CallRoutingTable.GeoKey("SA", "SR", Optional.empty(), CallRoutingTable.Protocol.v4), List.of("datacenter-3"),
new CallRoutingTable.GeoKey("SA", "UY", Optional.empty(), CallRoutingTable.Protocol.v4), List.of("datacenter-3", "datacenter-1", "datacenter-2"),
new CallRoutingTable.GeoKey("NA", "US", Optional.of("VA"), CallRoutingTable.Protocol.v6), List.of("datacenter-2", "datacenter-1")
)
);
assertThat(actual).isEqualTo(expected);
}
@Test
public void testParserMixedSections() throws IOException {
var input =
"""
1.123.123.0/24\t datacenter-1
2001:db8:b0aa::/48\t \tdatacenter-1
2001:db8:b0ab::/48 \tdatacenter-3\tdatacenter-1 datacenter-2
2001:db8:b0ac::/48\tdatacenter-2\tdatacenter-1
192.1.12.0/24\t \tdatacenter-1\t\t datacenter-2 datacenter-3
193.123.123.0/24\tdatacenter-1\tdatacenter-2
SA-SR-v4 datacenter-3
SA-UY-v4\tdatacenter-3\tdatacenter-1\tdatacenter-2
NA-US-VA-v6 datacenter-2 \tdatacenter-1
""";
var actual = CallRoutingTableParser.fromTsv(new StringReader(input));
var expected = new CallRoutingTable(
Map.of(
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("1.123.123.0/24"), List.of("datacenter-1"),
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("192.1.12.0/24"), List.of("datacenter-1", "datacenter-2", "datacenter-3"),
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("193.123.123.0/24"), List.of("datacenter-1", "datacenter-2")
),
Map.of(
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0aa::/48"), List.of("datacenter-1"),
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0ab::/48"), List.of("datacenter-3", "datacenter-1", "datacenter-2"),
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0ac::/48"), List.of("datacenter-2", "datacenter-1")
),
Map.of(
new CallRoutingTable.GeoKey("SA", "SR", Optional.empty(), CallRoutingTable.Protocol.v4), List.of("datacenter-3"),
new CallRoutingTable.GeoKey("SA", "UY", Optional.empty(), CallRoutingTable.Protocol.v4), List.of("datacenter-3", "datacenter-1", "datacenter-2"),
new CallRoutingTable.GeoKey("NA", "US", Optional.of("VA"), CallRoutingTable.Protocol.v6), List.of("datacenter-2", "datacenter-1")
)
);
assertThat(actual).isEqualTo(expected);
}
@Test
public void testJsonParserSuccess() throws IOException {
var input =
"""
{
"ipv4GeoToDataCenters": {
"SA-SR": ["datacenter-3"],
"SA-UY": ["datacenter-3", "datacenter-1", "datacenter-2"]
},
"ipv6GeoToDataCenters": {
"NA-US-VA": ["datacenter-2", "datacenter-1"]
},
"ipv4SubnetsToDatacenters": {
"192.1.12.0": ["datacenter-1", "datacenter-2", "datacenter-3"],
"193.123.123.0": ["datacenter-1", "datacenter-2"],
"1.123.123.0": ["datacenter-1"]
},
"ipv6SubnetsToDatacenters": {
"2001:db8:b0aa::": ["datacenter-1"],
"2001:db8:b0ab::": ["datacenter-3", "datacenter-1", "datacenter-2"],
"2001:db8:b0ac::": ["datacenter-2", "datacenter-1"]
}
}
""";
var actual = CallRoutingTableParser.fromJson(new StringReader(input));
var expected = new CallRoutingTable(
Map.of(
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("192.1.12.0/24"), List.of("datacenter-1", "datacenter-2", "datacenter-3"),
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("193.123.123.0/24"), List.of("datacenter-1", "datacenter-2"),
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("1.123.123.0/24"), List.of("datacenter-1")
),
Map.of(
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0aa::/48"), List.of("datacenter-1"),
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0ab::/48"), List.of("datacenter-3", "datacenter-1", "datacenter-2"),
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0ac::/48"), List.of("datacenter-2", "datacenter-1")
),
Map.of(
new CallRoutingTable.GeoKey("SA", "SR", Optional.empty(), CallRoutingTable.Protocol.v4), List.of("datacenter-3"),
new CallRoutingTable.GeoKey("SA", "UY", Optional.empty(), CallRoutingTable.Protocol.v4), List.of("datacenter-3", "datacenter-1", "datacenter-2"),
new CallRoutingTable.GeoKey("NA", "US", Optional.of("VA"), CallRoutingTable.Protocol.v6), List.of("datacenter-2", "datacenter-1")
)
);
assertThat(actual).isEqualTo(expected);
}
@Test
public void testParseVariousEdgeCases() throws IOException {
var input =
"""
{
"ipv4GeoToDataCenters": {},
"ipv6GeoToDataCenters": {},
"ipv4SubnetsToDatacenters": {},
"ipv6SubnetsToDatacenters": {}
}
""";
assertThat(CallRoutingTableParser.fromJson(new StringReader(input))).isEqualTo(CallRoutingTable.empty());
assertThat(CallRoutingTableParser.fromJson(new StringReader("{}"))).isEqualTo(CallRoutingTable.empty());
}
}
@@ -1,139 +0,0 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.calls.routing;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.junit.jupiter.api.Test;
public class CallRoutingTableTest {
static final CallRoutingTable basicTable = new CallRoutingTable(
Map.of(
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("192.1.12.0/24"), List.of("datacenter-1", "datacenter-2", "datacenter-3"),
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("193.123.123.0/24"), List.of("datacenter-1", "datacenter-2"),
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("1.123.123.0/24"), List.of("datacenter-4")
),
Map.of(
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0aa::/48"), List.of("datacenter-1"),
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0ab::/48"), List.of("datacenter-3", "datacenter-1", "datacenter-2"),
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0ac::/48"), List.of("datacenter-2", "datacenter-1")
),
Map.of(
new CallRoutingTable.GeoKey("SA", "SR", Optional.empty(), CallRoutingTable.Protocol.v4), List.of("datacenter-3"),
new CallRoutingTable.GeoKey("SA", "UY", Optional.empty(), CallRoutingTable.Protocol.v4), List.of("datacenter-3", "datacenter-1", "datacenter-2"),
new CallRoutingTable.GeoKey("NA", "US", Optional.of("VA"), CallRoutingTable.Protocol.v6), List.of("datacenter-2", "datacenter-1"),
new CallRoutingTable.GeoKey("NA", "US", Optional.empty(), CallRoutingTable.Protocol.v6), List.of("datacenter-3", "datacenter-4")
)
);
// has overlapping subnets
static final CallRoutingTable overlappingTable = new CallRoutingTable(
Map.of(
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("192.1.12.0/24"), List.of("datacenter-1", "datacenter-2", "datacenter-3"),
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("1.123.123.0/24"), List.of("datacenter-4"),
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("1.123.0.0/16"), List.of("datacenter-1")
),
Map.of(
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0aa::/48"), List.of("datacenter-1"),
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0ac::/48"), List.of("datacenter-3", "datacenter-1", "datacenter-2"),
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0a0::/44"), List.of("datacenter-2", "datacenter-1")
),
Map.of(
new CallRoutingTable.GeoKey("SA", "SR", Optional.empty(), CallRoutingTable.Protocol.v4), List.of("datacenter-3"),
new CallRoutingTable.GeoKey("SA", "UY", Optional.empty(), CallRoutingTable.Protocol.v4), List.of("datacenter-3", "datacenter-1", "datacenter-2"),
new CallRoutingTable.GeoKey("NA", "US", Optional.of("VA"), CallRoutingTable.Protocol.v6), List.of("datacenter-2", "datacenter-1")
)
);
@Test
void testGetFastestDataCentersBySubnet() throws UnknownHostException {
var v4address = Inet4Address.getByName("1.123.123.1");
var actualV4 = basicTable.getDatacentersBySubnet(v4address);
assertThat(actualV4).isEqualTo(List.of("datacenter-4"));
var v6address = Inet6Address.getByName("2001:db8:b0ac:aaaa:aaaa:aaaa:aaaa:0001");
var actualV6 = basicTable.getDatacentersBySubnet(v6address);
assertThat(actualV6).isEqualTo(List.of("datacenter-2", "datacenter-1"));
}
@Test
void testGetFastestDataCentersBySubnetOverlappingTable() throws UnknownHostException {
var v4address = Inet4Address.getByName("1.123.123.1");
var actualV4 = overlappingTable.getDatacentersBySubnet(v4address);
assertThat(actualV4).isEqualTo(List.of("datacenter-4"));
var v6address = Inet6Address.getByName("2001:db8:b0ac:aaaa:aaaa:aaaa:aaaa:0001");
var actualV6 = overlappingTable.getDatacentersBySubnet(v6address);
assertThat(actualV6).isEqualTo(List.of("datacenter-3", "datacenter-1", "datacenter-2"));
}
@Test
void testGetFastestDataCentersByGeo() {
var actual = basicTable.getDatacentersByGeo("SA", "SR", Optional.empty());
assertThat(actual).isEqualTo(List.of("datacenter-3"));
var actualWithSubdvision = basicTable.getDatacentersByGeo("NA", "US", Optional.of("VA"));
assertThat(actualWithSubdvision).isEqualTo(List.of("datacenter-2", "datacenter-1"));
}
@Test
void testGetFastestDataCentersByGeoFallback() {
var actualExactMatch = basicTable.getDatacentersByGeo("NA", "US", Optional.of("VA"));
assertThat(actualExactMatch).isEqualTo(List.of("datacenter-2", "datacenter-1"));
var actualApproximateMatch = basicTable.getDatacentersByGeo("NA", "US", Optional.of("MD"));
assertThat(actualApproximateMatch).isEqualTo(List.of("datacenter-3", "datacenter-4"));
}
@Test
void testGetFastestDatacentersPrioritizesSubnet() throws UnknownHostException {
var v4address = Inet4Address.getByName("1.123.123.1");
var actual = basicTable.getDatacentersFor(v4address, "NA", "US", Optional.of("VA"));
assertThat(actual).isEqualTo(List.of("datacenter-4", "datacenter-2", "datacenter-1"));
}
@Test
void testGetFastestDatacentersEmptySubnet() throws UnknownHostException {
var v4address = Inet4Address.getByName("200.200.123.1");
var actual = basicTable.getDatacentersFor(v4address, "NA", "US", Optional.of("VA"));
assertThat(actual).isEqualTo(List.of("datacenter-2", "datacenter-1"));
}
@Test
void testGetFastestDatacentersEmptySubnetTakesExtraFromGeo() throws UnknownHostException {
var v4address = Inet4Address.getByName("200.200.123.1");
var actual = basicTable.getDatacentersFor(v4address, "SA", "UY", Optional.empty());
assertThat(actual).isEqualTo(List.of("datacenter-3", "datacenter-1", "datacenter-2"));
}
@Test
void testGetFastestDatacentersEmptyGeoResults() throws UnknownHostException {
var v4address = Inet4Address.getByName("1.123.123.1");
var actual = basicTable.getDatacentersFor(v4address, "ZZ", "AA", Optional.empty());
assertThat(actual).isEqualTo(List.of("datacenter-4"));
}
@Test
void testGetFastestDatacentersEmptyGeoTakesFromSubnet() throws UnknownHostException {
var v4address = Inet4Address.getByName("192.1.12.1");
var actual = basicTable.getDatacentersFor(v4address, "ZZ", "AA", Optional.empty());
assertThat(actual).isEqualTo(List.of("datacenter-1", "datacenter-2", "datacenter-3"));
}
@Test
void testGetFastestDatacentersDistinct() throws UnknownHostException {
var v6address = Inet6Address.getByName("2001:db8:b0ac:aaaa:aaaa:aaaa:aaaa:0001");
var actual = basicTable.getDatacentersFor(v6address, "NA", "US", Optional.of("VA"));
assertThat(actual).isEqualTo(List.of("datacenter-2", "datacenter-1"));
}
}
@@ -1,63 +0,0 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.calls.routing;
import org.junit.jupiter.api.Test;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HexFormat;
import static org.assertj.core.api.Assertions.assertThat;
public class CidrBlockTest {
private HexFormat hex = HexFormat.ofDelimiter(":").withLowerCase();
@Test
public void testIPv4CidrBlockParseSuccess() {
var actual = CidrBlock.parseCidrBlock("255.32.15.0/24");
var expected = new CidrBlock.IpV4CidrBlock(0xFF_20_0F_00, 0xFFFFFF00, 24);
assertThat(actual).isInstanceOf(CidrBlock.IpV4CidrBlock.class);
assertThat(actual).isEqualTo(expected);
}
@Test
public void testIPv6CidrBlockParseSuccess() {
var actual = CidrBlock.parseCidrBlock("2001:db8:b0aa::/48");
var expected = new CidrBlock.IpV6CidrBlock(
new BigInteger(hex.parseHex("20:01:0d:b8:b0:aa:00:00:00:00:00:00:00:00:00:00")),
new BigInteger(hex.parseHex("FF:FF:FF:FF:FF:FF:00:00:00:00:00:00:00:00:00:00")),
48
);
assertThat(actual).isInstanceOf(CidrBlock.IpV6CidrBlock.class);
assertThat(actual).isEqualTo(expected);
}
@Test
public void testIPv4InBlock() throws UnknownHostException {
var block = CidrBlock.parseCidrBlock("255.32.15.0/24");
assertThat(block.ipInBlock(InetAddress.getByName("255.32.15.123"))).isTrue();
assertThat(block.ipInBlock(InetAddress.getByName("255.32.15.0"))).isTrue();
assertThat(block.ipInBlock(InetAddress.getByName("255.32.16.0"))).isFalse();
assertThat(block.ipInBlock(InetAddress.getByName("255.33.15.0"))).isFalse();
assertThat(block.ipInBlock(InetAddress.getByName("254.33.15.0"))).isFalse();
}
@Test
public void testIPv6InBlock() throws UnknownHostException {
var block = CidrBlock.parseCidrBlock("2001:db8:b0aa::/48");
assertThat(block.ipInBlock(InetAddress.getByName("2001:db8:b0aa:1:1::"))).isTrue();
assertThat(block.ipInBlock(InetAddress.getByName("2001:db8:b0aa:0:0::"))).isTrue();
assertThat(block.ipInBlock(InetAddress.getByName("2001:db8:b0ab:1:1::"))).isFalse();
assertThat(block.ipInBlock(InetAddress.getByName("2001:da8:b0aa:1:1::"))).isFalse();
}
}
@@ -1,137 +0,0 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.calls.routing;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.jupiter.api.Test;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class DynamicConfigTurnRouterTest {
@Test
public void testAlwaysSelectFirst() throws JsonProcessingException {
final String configString = """
captcha:
scoreFloor: 1.0
turn:
uriConfigs:
- uris:
- always1.org
- always2.org
- uris:
- never.org
weight: 0
""";
DynamicConfiguration config = DynamicConfigurationManager
.parseConfiguration(configString, DynamicConfiguration.class)
.orElseThrow();
@SuppressWarnings("unchecked")
DynamicConfigurationManager<DynamicConfiguration> mockDynamicConfigManager = mock(
DynamicConfigurationManager.class);
when(mockDynamicConfigManager.getConfiguration()).thenReturn(config);
final DynamicConfigTurnRouter configTurnRouter = new DynamicConfigTurnRouter(mockDynamicConfigManager);
final long COUNT = 1000;
final Map<String, Long> urlCounts = Stream
.generate(configTurnRouter::randomUrls)
.limit(COUNT)
.flatMap(Collection::stream)
.collect(Collectors.groupingBy(i -> i, Collectors.counting()));
assertThat(urlCounts.get("always1.org")).isEqualTo(COUNT);
assertThat(urlCounts.get("always2.org")).isEqualTo(COUNT);
assertThat(urlCounts).doesNotContainKey("never.org");
}
@Test
public void testProbabilisticUrls() throws JsonProcessingException {
final String configString = """
captcha:
scoreFloor: 1.0
turn:
uriConfigs:
- uris:
- always.org
- sometimes1.org
weight: 5
- uris:
- always.org
- sometimes2.org
weight: 5
""";
DynamicConfiguration config = DynamicConfigurationManager
.parseConfiguration(configString, DynamicConfiguration.class)
.orElseThrow();
@SuppressWarnings("unchecked")
DynamicConfigurationManager<DynamicConfiguration> mockDynamicConfigManager = mock(
DynamicConfigurationManager.class);
when(mockDynamicConfigManager.getConfiguration()).thenReturn(config);
final DynamicConfigTurnRouter configTurnRouter = new DynamicConfigTurnRouter(mockDynamicConfigManager);
final long COUNT = 1000;
final Map<String, Long> urlCounts = Stream
.generate(configTurnRouter::randomUrls)
.limit(COUNT)
.flatMap(Collection::stream)
.collect(Collectors.groupingBy(i -> i, Collectors.counting()));
assertThat(urlCounts.get("always.org")).isEqualTo(COUNT);
assertThat(urlCounts.get("sometimes1.org")).isGreaterThan(0);
assertThat(urlCounts.get("sometimes2.org")).isGreaterThan(0);
}
@Test
public void testExplicitEnrollment() throws JsonProcessingException {
final String configString = """
captcha:
scoreFloor: 1.0
turn:
secret: bloop
uriConfigs:
- uris:
- enrolled.org
weight: 0
enrolledAcis:
- 732506d7-d04f-43a4-b1d7-8a3a91ebe8a6
- uris:
- unenrolled.org
weight: 1
""";
DynamicConfiguration config = DynamicConfigurationManager
.parseConfiguration(configString, DynamicConfiguration.class)
.orElseThrow();
@SuppressWarnings("unchecked")
DynamicConfigurationManager<DynamicConfiguration> mockDynamicConfigManager = mock(
DynamicConfigurationManager.class);
when(mockDynamicConfigManager.getConfiguration()).thenReturn(config);
final DynamicConfigTurnRouter configTurnRouter = new DynamicConfigTurnRouter(mockDynamicConfigManager);
List<String> urls = configTurnRouter.targetedUrls(UUID.fromString("732506d7-d04f-43a4-b1d7-8a3a91ebe8a6"));
assertThat(urls.getFirst()).isEqualTo("enrolled.org");
urls = configTurnRouter.targetedUrls(UUID.randomUUID());
assertTrue(urls.isEmpty());
}
}
@@ -1,335 +0,0 @@
/*
* Copyright 2024 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 com.maxmind.geoip2.record.Continent;
import com.maxmind.geoip2.record.Country;
import com.maxmind.geoip2.record.Subdivision;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class TurnCallRouterTest {
private final static String TEST_HOSTNAME = "subdomain.example.org";
private final static List<String> TEST_URLS_WITH_HOSTS = List.of(
"stun:one.example.com",
"turn:two.example.com",
"turn:three.example.com?transport=tcp"
);
private final static List<String> EXPECTED_TEST_URLS_WITH_HOSTS = List.of(
"turn:two.example.com"
);
private CallRoutingTable performanceTable;
private CallRoutingTable manualTable;
private DynamicConfigTurnRouter configTurnRouter;
private DatabaseReader geoIp;
private Country country;
private Continent continent;
private CallDnsRecords callDnsRecords;
private Subdivision subdivision;
private UUID aci = UUID.randomUUID();
@BeforeEach
void setup() throws IOException, GeoIp2Exception {
performanceTable = mock(CallRoutingTable.class);
manualTable = mock(CallRoutingTable.class);
configTurnRouter = mock(DynamicConfigTurnRouter.class);
geoIp = mock(DatabaseReader.class);
continent = mock(Continent.class);
country = mock(Country.class);
subdivision = mock(Subdivision.class);
ArrayList<Subdivision> subdivisions = new ArrayList<>();
subdivisions.add(subdivision);
when(geoIp.city(any())).thenReturn(new CityResponse(null, continent, country, null, null, null, null, null, subdivisions, null));
setupDefault();
}
void setupDefault() {
when(configTurnRouter.targetedUrls(any())).thenReturn(Collections.emptyList());
when(configTurnRouter.randomUrls()).thenReturn(TEST_URLS_WITH_HOSTS);
when(configTurnRouter.getHostname()).thenReturn(TEST_HOSTNAME);
when(configTurnRouter.shouldRandomize()).thenReturn(false);
when(manualTable.getDatacentersFor(any(), any(), any(), any())).thenReturn(Collections.emptyList());
when(continent.getCode()).thenReturn("NA");
when(country.getIsoCode()).thenReturn("US");
when(subdivision.getIsoCode()).thenReturn("VA");
try {
callDnsRecords = new CallDnsRecords(
Map.of(
"dc-manual", List.of(InetAddress.getByName("1.1.1.1")),
"dc-performance1", List.of(
InetAddress.getByName("9.9.9.1"),
InetAddress.getByName("9.9.9.2")
),
"dc-performance2", List.of(InetAddress.getByName("9.9.9.3")),
"dc-performance3", List.of(InetAddress.getByName("9.9.9.4")),
"dc-performance4", List.of(
InetAddress.getByName("9.9.9.5"),
InetAddress.getByName("9.9.9.6"),
InetAddress.getByName("9.9.9.7")
)
),
Map.of(
"dc-manual", List.of(InetAddress.getByName("2222:1111:0:dead::")),
"dc-performance1", List.of(
InetAddress.getByName("2222:1111:0:abc0::"),
InetAddress.getByName("2222:1111:0:abc1::")
),
"dc-performance2", List.of(InetAddress.getByName("2222:1111:0:abc2::")),
"dc-performance3", List.of(InetAddress.getByName("2222:1111:0:abc3::")),
"dc-performance4", List.of(
InetAddress.getByName("2222:1111:0:abc4::"),
InetAddress.getByName("2222:1111:0:abc5::"),
InetAddress.getByName("2222:1111:0:abc6::")
)
)
);
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
private TurnCallRouter router() {
return new TurnCallRouter(
() -> callDnsRecords,
() -> performanceTable,
() -> manualTable,
configTurnRouter,
() -> geoIp,
// set to true so the return values are predictable
true
);
}
TurnServerOptions optionsWithUrls(List<String> urls) {
return new TurnServerOptions(
TEST_HOSTNAME,
Optional.of(urls),
Optional.of(EXPECTED_TEST_URLS_WITH_HOSTS)
);
}
@Test
public void testPrioritizesTargetedUrls() throws UnknownHostException {
List<String> targetedUrls = List.of(
"targeted1.example.com",
"targeted.example.com"
);
when(configTurnRouter.targetedUrls(any()))
.thenReturn(targetedUrls);
assertThat(router().getRoutingFor(aci, Optional.of(InetAddress.getByName("0.0.0.1")), 10))
.isEqualTo(new TurnServerOptions(
TEST_HOSTNAME,
Optional.empty(),
Optional.of(targetedUrls)
));
}
@Test
public void testRandomizes() throws UnknownHostException {
when(configTurnRouter.shouldRandomize())
.thenReturn(true);
assertThat(router().getRoutingFor(aci, Optional.of(InetAddress.getByName("0.0.0.1")), 10))
.isEqualTo(new TurnServerOptions(
TEST_HOSTNAME,
Optional.empty(),
Optional.of(TEST_URLS_WITH_HOSTS)
));
}
@Test
public void testUrlsOnlyNoInstanceIps() throws UnknownHostException {
when(performanceTable.getDatacentersFor(any(), any(), any(), any()))
.thenReturn(List.of("dc-performance2", "dc-performance1"));
when(configTurnRouter.shouldRandomize())
.thenReturn(false);
assertThat(router().getRoutingFor(aci, Optional.of(InetAddress.getByName("0.0.0.1")), 0))
.isEqualTo(new TurnServerOptions(
TEST_HOSTNAME,
Optional.empty(),
Optional.of(TEST_URLS_WITH_HOSTS)
));
}
@Test
public void testOrderedByPerformance() throws UnknownHostException {
when(performanceTable.getDatacentersFor(any(), any(), any(), any()))
.thenReturn(List.of("dc-performance2", "dc-performance1"));
assertThat(router().getRoutingFor(aci, Optional.of(InetAddress.getByName("0.0.0.1")), 10))
.isEqualTo(optionsWithUrls(List.of(
"turn:9.9.9.3",
"turn:9.9.9.3:80?transport=tcp",
"turns:9.9.9.3:443?transport=tcp",
"turn:9.9.9.1",
"turn:9.9.9.1:80?transport=tcp",
"turns:9.9.9.1:443?transport=tcp",
"turn:9.9.9.2",
"turn:9.9.9.2:80?transport=tcp",
"turns:9.9.9.2:443?transport=tcp",
"turn:[2222:1111:0:abc2:0:0:0:0]",
"turn:[2222:1111:0:abc2:0:0:0:0]:80?transport=tcp",
"turns:[2222:1111:0:abc2:0:0:0:0]:443?transport=tcp",
"turn:[2222:1111:0:abc0:0:0:0:0]",
"turn:[2222:1111:0:abc0:0:0:0:0]:80?transport=tcp",
"turns:[2222:1111:0:abc0:0:0:0:0]:443?transport=tcp",
"turn:[2222:1111:0:abc1:0:0:0:0]",
"turn:[2222:1111:0:abc1:0:0:0:0]:80?transport=tcp",
"turns:[2222:1111:0:abc1:0:0:0:0]:443?transport=tcp"
)));
}
@Test
public void testPrioritizesManualRecords() throws UnknownHostException {
when(performanceTable.getDatacentersFor(any(), any(), any(), any()))
.thenReturn(List.of("dc-performance1"));
when(manualTable.getDatacentersFor(any(), any(), any(), any()))
.thenReturn(List.of("dc-manual"));
assertThat(router().getRoutingFor(aci, Optional.of(InetAddress.getByName("0.0.0.1")), 10))
.isEqualTo(optionsWithUrls(List.of(
"turn:1.1.1.1",
"turn:1.1.1.1:80?transport=tcp",
"turns:1.1.1.1:443?transport=tcp",
"turn:[2222:1111:0:dead:0:0:0:0]",
"turn:[2222:1111:0:dead:0:0:0:0]:80?transport=tcp",
"turns:[2222:1111:0:dead:0:0:0:0]:443?transport=tcp"
)));
}
@Test
public void testLimitPrioritizesBestDataCenters() throws UnknownHostException {
when(performanceTable.getDatacentersFor(any(), any(), any(), any()))
.thenReturn(List.of("dc-performance3", "dc-performance2", "dc-performance3"));
// gets one instance from best two datacenters
assertThat(router().getRoutingFor(aci, Optional.of(InetAddress.getByName("0.0.0.1")), 2))
.isEqualTo(optionsWithUrls(List.of(
"turn:9.9.9.4",
"turn:9.9.9.4:80?transport=tcp",
"turns:9.9.9.4:443?transport=tcp",
"turn:9.9.9.3",
"turn:9.9.9.3:80?transport=tcp",
"turns:9.9.9.3:443?transport=tcp",
"turn:[2222:1111:0:abc3:0:0:0:0]",
"turn:[2222:1111:0:abc3:0:0:0:0]:80?transport=tcp",
"turns:[2222:1111:0:abc3:0:0:0:0]:443?transport=tcp",
"turn:[2222:1111:0:abc2:0:0:0:0]",
"turn:[2222:1111:0:abc2:0:0:0:0]:80?transport=tcp",
"turns:[2222:1111:0:abc2:0:0:0:0]:443?transport=tcp"
)));
assertThat(router().getRoutingFor(aci, Optional.of(InetAddress.getByName("2222:1111:0:abc2:0:0:0:1")), 1))
.isEqualTo(optionsWithUrls(List.of(
"turn:9.9.9.4",
"turn:9.9.9.4:80?transport=tcp",
"turns:9.9.9.4:443?transport=tcp",
"turn:[2222:1111:0:abc3:0:0:0:0]",
"turn:[2222:1111:0:abc3:0:0:0:0]:80?transport=tcp",
"turns:[2222:1111:0:abc3:0:0:0:0]:443?transport=tcp"
)));
}
@Test
public void testBackFillsUpToLimit() throws UnknownHostException {
when(performanceTable.getDatacentersFor(any(), any(), any(), any()))
.thenReturn(List.of("dc-performance4", "dc-performance2", "dc-performance3"));
assertThat(router().getRoutingFor(aci, Optional.of(InetAddress.getByName("0.0.0.1")), 5))
.isEqualTo(optionsWithUrls(List.of(
"turn:9.9.9.5",
"turn:9.9.9.5:80?transport=tcp",
"turns:9.9.9.5:443?transport=tcp",
"turn:9.9.9.6",
"turn:9.9.9.6:80?transport=tcp",
"turns:9.9.9.6:443?transport=tcp",
"turn:9.9.9.7",
"turn:9.9.9.7:80?transport=tcp",
"turns:9.9.9.7:443?transport=tcp",
"turn:9.9.9.3",
"turn:9.9.9.3:80?transport=tcp",
"turns:9.9.9.3:443?transport=tcp",
"turn:9.9.9.4",
"turn:9.9.9.4:80?transport=tcp",
"turns:9.9.9.4:443?transport=tcp",
"turn:[2222:1111:0:abc4:0:0:0:0]",
"turn:[2222:1111:0:abc4:0:0:0:0]:80?transport=tcp",
"turns:[2222:1111:0:abc4:0:0:0:0]:443?transport=tcp",
"turn:[2222:1111:0:abc5:0:0:0:0]",
"turn:[2222:1111:0:abc5:0:0:0:0]:80?transport=tcp",
"turns:[2222:1111:0:abc5:0:0:0:0]:443?transport=tcp",
"turn:[2222:1111:0:abc6:0:0:0:0]",
"turn:[2222:1111:0:abc6:0:0:0:0]:80?transport=tcp",
"turns:[2222:1111:0:abc6:0:0:0:0]:443?transport=tcp",
"turn:[2222:1111:0:abc2:0:0:0:0]",
"turn:[2222:1111:0:abc2:0:0:0:0]:80?transport=tcp",
"turns:[2222:1111:0:abc2:0:0:0:0]:443?transport=tcp",
"turn:[2222:1111:0:abc3:0:0:0:0]",
"turn:[2222:1111:0:abc3:0:0:0:0]:80?transport=tcp",
"turns:[2222:1111:0:abc3:0:0:0:0]:443?transport=tcp"
)));
}
@Test
public void testNoDatacentersMatched() throws UnknownHostException {
when(performanceTable.getDatacentersFor(any(), any(), any(), any()))
.thenReturn(List.of());
assertThat(router().getRoutingFor(aci, Optional.of(InetAddress.getByName("0.0.0.1")), 10))
.isEqualTo(optionsWithUrls(List.of()));
}
@Test
public void testHandlesDatacenterNotInDnsRecords() throws UnknownHostException {
when(performanceTable.getDatacentersFor(any(), any(), any(), any()))
.thenReturn(List.of("unsynced-datacenter"));
assertThat(router().getRoutingFor(aci, Optional.of(InetAddress.getByName("0.0.0.1")), 10))
.isEqualTo(optionsWithUrls(List.of()));
}
}
@@ -335,67 +335,6 @@ class DynamicConfigurationTest {
assertThat(resetRateLimiterConfig.permitRegenerationDuration()).isEqualTo(Duration.ofNanos(4_000));
}
@Test
void testParseTurnConfig() throws JsonProcessingException {
{
final String config = REQUIRED_CONFIG.concat("""
turn:
secret: bloop
uriConfigs:
- uris:
- turn:test.org
weight: -1
""");
assertThat(DynamicConfigurationManager.parseConfiguration(config, DynamicConfiguration.class)).isEmpty();
}
{
final String config = REQUIRED_CONFIG.concat("""
turn:
uriConfigs:
- uris:
- turn:test0.org
- turn:test1.org
- uris:
- turn:test2.org
weight: 2
enrolledAcis:
- 732506d7-d04f-43a4-b1d7-8a3a91ebe8a6
randomizeRate: 100_000
hostname: test.domain.org
""");
DynamicTurnConfiguration turnConfiguration = DynamicConfigurationManager
.parseConfiguration(config, DynamicConfiguration.class)
.orElseThrow()
.getTurnConfiguration();
assertThat(turnConfiguration.getUriConfigs().get(0).getUris()).hasSize(2);
assertThat(turnConfiguration.getUriConfigs().get(1).getUris()).hasSize(1);
assertThat(turnConfiguration.getUriConfigs().get(0).getWeight()).isEqualTo(1);
assertThat(turnConfiguration.getUriConfigs().get(1).getWeight()).isEqualTo(2);
assertThat(turnConfiguration.getUriConfigs().get(1).getEnrolledAcis())
.containsExactly(UUID.fromString("732506d7-d04f-43a4-b1d7-8a3a91ebe8a6"));
assertThat(turnConfiguration.getHostname()).isEqualTo("test.domain.org");
assertThat(turnConfiguration.getRandomizeRate()).isEqualTo(100_000L);
assertThat(turnConfiguration.getDefaultInstanceIpCount()).isEqualTo(0);
}
{
final String config = REQUIRED_CONFIG.concat("""
turn:
uriConfigs:
- uris:
- turn:test0.org
- turn:test1.org
defaultInstanceIpCount: 5
""");
DynamicTurnConfiguration turnConfiguration = DynamicConfigurationManager
.parseConfiguration(config, DynamicConfiguration.class)
.orElseThrow()
.getTurnConfiguration();
assertThat(turnConfiguration.getDefaultInstanceIpCount()).isEqualTo(5);
}
}
@Test
void testMessagePersister() throws JsonProcessingException {
{
@@ -59,7 +59,6 @@ import org.signal.libsignal.usernames.BaseUsernameException;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.auth.StoredRegistrationLock;
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.entities.AccountIdentifierResponse;
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
@@ -130,7 +129,6 @@ class AccountControllerTest {
private static final RateLimiter usernameReserveLimiter = mock(RateLimiter.class);
private static final RateLimiter usernameLookupLimiter = mock(RateLimiter.class);
private static final RateLimiter checkAccountExistence = mock(RateLimiter.class);
private static final TurnTokenGenerator turnTokenGenerator = mock(TurnTokenGenerator.class);
private static final Account senderPinAccount = mock(Account.class);
private static final Account senderRegLockAccount = mock(Account.class);
private static final Account senderHasStorage = mock(Account.class);
@@ -234,7 +232,6 @@ class AccountControllerTest {
usernameSetLimiter,
usernameReserveLimiter,
usernameLookupLimiter,
turnTokenGenerator,
senderPinAccount,
senderRegLockAccount,
senderHasStorage,
@@ -16,6 +16,7 @@ import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -79,6 +80,7 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.mappers.ImpossiblePhoneNumberExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.NonNormalizedPhoneNumberExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
import org.whispersystems.textsecuregcm.spam.RegistrationRecoveryChecker;
import org.whispersystems.textsecuregcm.storage.Account;
@@ -139,7 +141,7 @@ class AccountControllerV2Test {
void setUp() throws Exception {
when(rateLimiters.getRegistrationLimiter()).thenReturn(registrationLimiter);
when(changeNumberManager.changeNumber(any(), any(), any(), any(), any(), any(), any())).thenAnswer(
when(changeNumberManager.changeNumber(any(), any(), any(), any(), any(), any(), any(), any())).thenAnswer(
(Answer<Account>) invocation -> {
final Account account = invocation.getArgument(0);
final String number = invocation.getArgument(1);
@@ -189,7 +191,7 @@ class AccountControllerV2Test {
MediaType.APPLICATION_JSON_TYPE), AccountIdentityResponse.class);
verify(changeNumberManager).changeNumber(eq(AuthHelper.VALID_ACCOUNT), eq(NEW_NUMBER), any(), any(), any(),
any(), any());
any(), any(), any());
assertEquals(AuthHelper.VALID_UUID, accountIdentityResponse.uuid());
assertEquals(NEW_NUMBER, accountIdentityResponse.number());
@@ -212,7 +214,7 @@ class AccountControllerV2Test {
MediaType.APPLICATION_JSON_TYPE), AccountIdentityResponse.class);
verify(changeNumberManager).changeNumber(eq(AuthHelper.VALID_ACCOUNT), eq(AuthHelper.VALID_NUMBER), any(), any(), any(),
any(), any());
any(), any(), any());
assertEquals(AuthHelper.VALID_UUID, accountIdentityResponse.uuid());
assertEquals(AuthHelper.VALID_NUMBER, accountIdentityResponse.number());
@@ -220,7 +222,7 @@ class AccountControllerV2Test {
}
@Test
void changeNumberNonNormalizedNumber() throws Exception {
void changeNumberNonNormalizedNumber() {
try (Response response = resources.getJerseyTest()
.target("/v2/accounts/number")
.request()
@@ -293,13 +295,15 @@ class AccountControllerV2Test {
null, NEW_NUMBER, "123", new IdentityKey(Curve.generateKeyPair().getPublicKey()),
Collections.emptyList(), Collections.emptyMap(), null, Map.of((byte) 1, pniRegistrationId));
final Response response = resources.getJerseyTest()
try (final Response response = resources.getJerseyTest()
.target("/v2/accounts/number")
.request()
.header(HttpHeaders.AUTHORIZATION,
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.entity(changeNumberRequest, MediaType.APPLICATION_JSON_TYPE));
assertEquals(expectedStatusCode, response.getStatus());
.put(Entity.entity(changeNumberRequest, MediaType.APPLICATION_JSON_TYPE))) {
assertEquals(expectedStatusCode, response.getStatus());
}
}
private static Stream<Arguments> invalidRegistrationId() {
@@ -422,7 +426,7 @@ class AccountControllerV2Test {
final AccountIdentityResponse accountIdentityResponse = response.readEntity(AccountIdentityResponse.class);
verify(changeNumberManager).changeNumber(eq(AuthHelper.VALID_ACCOUNT), eq(NEW_NUMBER), any(), any(), any(),
any(), any());
any(), any(), any());
assertEquals(AuthHelper.VALID_UUID, accountIdentityResponse.uuid());
assertEquals(NEW_NUMBER, accountIdentityResponse.number());
@@ -481,6 +485,33 @@ class AccountControllerV2Test {
}
}
@Test
void deviceMessageTooLarge() throws Exception {
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(new RegistrationServiceSession(new byte[16], NEW_NUMBER, true, null, null, null,
SESSION_EXPIRATION_SECONDS))));
reset(changeNumberManager);
when(changeNumberManager.changeNumber(any(), any(), any(), any(), any(), any(), any(), any()))
.thenThrow(MessageTooLargeException.class);
try (final Response response = resources.getJerseyTest()
.target("/v2/accounts/number")
.request()
.header(HttpHeaders.AUTHORIZATION,
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.entity(
new ChangeNumberRequest(encodeSessionId("session"), null, NEW_NUMBER, "123", new IdentityKey(Curve.generateKeyPair().getPublicKey()),
Collections.emptyList(),
Collections.emptyMap(), null, Collections.emptyMap()),
MediaType.APPLICATION_JSON_TYPE))) {
assertEquals(413, response.getStatus());
}
}
/**
* Valid request JSON with the given Recovery Password
*/
@@ -558,7 +589,7 @@ class AccountControllerV2Test {
@BeforeEach
void setUp() throws Exception {
when(changeNumberManager.updatePniKeys(any(), any(), any(), any(), any(), any())).thenAnswer(
when(changeNumberManager.updatePniKeys(any(), any(), any(), any(), any(), any(), any())).thenAnswer(
(Answer<Account>) invocation -> {
final Account account = invocation.getArgument(0);
final IdentityKey pniIdentityKey = invocation.getArgument(1);
@@ -594,7 +625,7 @@ class AccountControllerV2Test {
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.json(requestJson()), AccountIdentityResponse.class);
verify(changeNumberManager).updatePniKeys(eq(AuthHelper.VALID_ACCOUNT), eq(IDENTITY_KEY), any(), any(), any(), any());
verify(changeNumberManager).updatePniKeys(eq(AuthHelper.VALID_ACCOUNT), eq(IDENTITY_KEY), any(), any(), any(), any(), any());
assertEquals(AuthHelper.VALID_UUID, accountIdentityResponse.uuid());
assertEquals(AuthHelper.VALID_NUMBER, accountIdentityResponse.number());
@@ -646,6 +677,23 @@ class AccountControllerV2Test {
}
}
@Test
void deviceMessageTooLarge() throws Exception {
reset(changeNumberManager);
when(changeNumberManager.updatePniKeys(any(), any(), any(), any(), any(), any(), any()))
.thenThrow(MessageTooLargeException.class);
try (final Response response = resources.getJerseyTest()
.target("/v2/accounts/phone_number_identity_key_distribution")
.request()
.header(HttpHeaders.AUTHORIZATION,
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.json(requestJson()))) {
assertEquals(413, response.getStatus());
}
}
/**
* Valid request JSON for a {@link org.whispersystems.textsecuregcm.entities.PhoneNumberIdentityKeyDistributionRequest}
*/
@@ -72,6 +72,7 @@ import org.whispersystems.textsecuregcm.entities.RemoteAttachment;
import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.GrpcStatusRuntimeExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.metrics.BackupMetrics;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.util.EnumMapUtil;
import org.whispersystems.textsecuregcm.util.SystemMapper;
@@ -94,7 +95,7 @@ public class ArchiveControllerTest {
.addProvider(new RateLimitExceededExceptionMapper())
.setMapper(SystemMapper.jsonMapper())
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
.addResource(new ArchiveController(backupAuthManager, backupManager))
.addResource(new ArchiveController(backupAuthManager, backupManager, new BackupMetrics()))
.build();
private final UUID aci = UUID.randomUUID();
@@ -20,6 +20,7 @@ import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.anyBoolean;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
@@ -29,7 +30,6 @@ import static org.mockito.Mockito.when;
import static org.whispersystems.textsecuregcm.tests.util.JsonHelpers.asJson;
import static org.whispersystems.textsecuregcm.tests.util.JsonHelpers.jsonFixture;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.protobuf.ByteString;
import io.dropwizard.auth.AuthValueFactoryProvider;
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
@@ -40,6 +40,7 @@ import jakarta.ws.rs.client.Invocation;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
@@ -56,6 +57,7 @@ import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.glassfish.jersey.server.ServerProperties;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.hamcrest.Matcher;
@@ -73,18 +75,15 @@ import org.mockito.ArgumentCaptor;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicInboundMessageByteLimitConfiguration;
import org.whispersystems.textsecuregcm.entities.IncomingMessage;
import org.whispersystems.textsecuregcm.entities.IncomingMessageList;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
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.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.PniServiceIdentifier;
@@ -97,6 +96,7 @@ import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
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;
@@ -105,7 +105,6 @@ 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.RemovedMessage;
@@ -177,10 +176,6 @@ class MessageControllerTest {
private static final ReportMessageManager reportMessageManager = mock(ReportMessageManager.class);
private static final Scheduler messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
@SuppressWarnings("unchecked")
private static final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
mock(DynamicConfigurationManager.class);
private static final ServerSecretParams serverSecretParams = ServerSecretParams.generate();
private static final TestClock clock = TestClock.now();
@@ -198,15 +193,15 @@ class MessageControllerTest {
new MessageController(rateLimiters, cardinalityEstimator, messageSender, receiptSender, accountsManager,
messagesManager, phoneNumberIdentifiers, pushNotificationManager, pushNotificationScheduler,
reportMessageManager, messageDeliveryScheduler, mock(ClientReleaseManager.class),
dynamicConfigurationManager, serverSecretParams, SpamChecker.noop(), new MessageMetrics(), mock(MessageDeliveryLoopMonitor.class),
serverSecretParams, SpamChecker.noop(), new MessageMetrics(), mock(MessageDeliveryLoopMonitor.class),
clock))
.build();
@BeforeEach
void setup() {
void setup() throws MultiRecipientMismatchedDevicesException, MessageTooLargeException {
reset(pushNotificationScheduler);
when(messageSender.sendMultiRecipientMessage(any(), any(), anyLong(), anyBoolean(), anyBoolean(), anyBoolean()))
when(messageSender.sendMultiRecipientMessage(any(), any(), anyLong(), anyBoolean(), anyBoolean(), anyBoolean(), any()))
.thenReturn(CompletableFuture.completedFuture(null));
final List<Device> singleDeviceList = List.of(
@@ -239,16 +234,6 @@ class MessageControllerTest {
when(accountsManager.getByServiceIdentifierAsync(MULTI_DEVICE_PNI_ID)).thenReturn(CompletableFuture.completedFuture(Optional.of(multiDeviceAccount)));
when(accountsManager.getByServiceIdentifierAsync(new AciServiceIdentifier(INTERNATIONAL_UUID))).thenReturn(CompletableFuture.completedFuture(Optional.of(internationalAccount)));
final DynamicInboundMessageByteLimitConfiguration inboundMessageByteLimitConfiguration =
mock(DynamicInboundMessageByteLimitConfiguration.class);
when(inboundMessageByteLimitConfiguration.enforceInboundLimit()).thenReturn(false);
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
when(dynamicConfiguration.getInboundMessageByteLimitConfiguration()).thenReturn(inboundMessageByteLimitConfiguration);
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
when(rateLimiters.getMessagesLimiter()).thenReturn(rateLimiter);
when(rateLimiters.getStoriesLimiter()).thenReturn(rateLimiter);
when(rateLimiters.getInboundMessageBytes()).thenReturn(rateLimiter);
@@ -305,7 +290,7 @@ class MessageControllerTest {
assertThat("Good Response", response.getStatus(), is(equalTo(200)));
@SuppressWarnings("unchecked") final ArgumentCaptor<Map<Byte, Envelope>> captor = ArgumentCaptor.forClass(Map.class);
verify(messageSender).sendMessages(any(), captor.capture());
verify(messageSender).sendMessages(any(), any(), captor.capture(), any(), any());
assertEquals(1, captor.getValue().size());
final Envelope message = captor.getValue().values().stream().findFirst().orElseThrow();
@@ -350,7 +335,7 @@ class MessageControllerTest {
assertThat("Good Response", response.getStatus(), is(equalTo(200)));
@SuppressWarnings("unchecked") final ArgumentCaptor<Map<Byte, Envelope>> captor = ArgumentCaptor.forClass(Map.class);
verify(messageSender).sendMessages(any(), captor.capture());
verify(messageSender).sendMessages(any(), any(), captor.capture(), any(), any());
assertEquals(1, captor.getValue().size());
final Envelope message = captor.getValue().values().stream().findFirst().orElseThrow();
@@ -375,7 +360,7 @@ class MessageControllerTest {
assertThat("Good Response", response.getStatus(), is(equalTo(200)));
@SuppressWarnings("unchecked") final ArgumentCaptor<Map<Byte, Envelope>> captor = ArgumentCaptor.forClass(Map.class);
verify(messageSender).sendMessages(any(), captor.capture());
verify(messageSender).sendMessages(any(), any(), captor.capture(), any(), any());
assertEquals(1, captor.getValue().size());
final Envelope message = captor.getValue().values().stream().findFirst().orElseThrow();
@@ -413,7 +398,7 @@ class MessageControllerTest {
assertThat("Good Response", response.getStatus(), is(equalTo(200)));
@SuppressWarnings("unchecked") final ArgumentCaptor<Map<Byte, Envelope>> captor = ArgumentCaptor.forClass(Map.class);
verify(messageSender).sendMessages(any(), captor.capture());
verify(messageSender).sendMessages(any(), any(), captor.capture(), any(), any());
assertEquals(1, captor.getValue().size());
final Envelope message = captor.getValue().values().stream().findFirst().orElseThrow();
@@ -452,7 +437,7 @@ class MessageControllerTest {
assertThat("Good Response", response.getStatus(), is(equalTo(expectedResponse)));
if (expectedResponse == 200) {
@SuppressWarnings("unchecked") final ArgumentCaptor<Map<Byte, Envelope>> captor = ArgumentCaptor.forClass(Map.class);
verify(messageSender).sendMessages(any(), captor.capture());
verify(messageSender).sendMessages(any(), any(), captor.capture(), any(), any());
assertEquals(1, captor.getValue().size());
final Envelope message = captor.getValue().values().stream().findFirst().orElseThrow();
@@ -507,7 +492,7 @@ class MessageControllerTest {
// `long`) instead of the validation layer, we get a 400 instead of a 422
"99999999999999999999999999999999999, 400"
})
void testSingleDeviceExtremeTimestamp(final String timestamp, final int expectedStatus) throws JsonProcessingException {
void testSingleDeviceExtremeTimestamp(final String timestamp, final int expectedStatus) {
final String jsonTemplate = """
{
"timestamp" : %s,
@@ -548,6 +533,9 @@ class MessageControllerTest {
@Test
void testMultiDeviceMissing() throws Exception {
doThrow(new MismatchedDevicesException(new MismatchedDevices(Set.of((byte) 2, (byte) 3), Collections.emptySet(), Collections.emptySet())))
.when(messageSender).sendMessages(any(), any(), any(), any(), any());
try (final Response response =
resources.getJerseyTest()
.target(String.format("/v1/messages/%s", MULTI_DEVICE_UUID))
@@ -560,15 +548,16 @@ class MessageControllerTest {
assertThat("Good Response Code", response.getStatus(), is(equalTo(409)));
assertThat("Good Response Body",
asJson(response.readEntity(MismatchedDevices.class)),
asJson(response.readEntity(MismatchedDevicesResponse.class)),
is(equalTo(jsonFixture("fixtures/missing_device_response.json"))));
verifyNoMoreInteractions(messageSender);
}
}
@Test
void testMultiDeviceExtra() throws Exception {
doThrow(new MismatchedDevicesException(new MismatchedDevices(Set.of((byte) 2), Set.of((byte) 4), Collections.emptySet())))
.when(messageSender).sendMessages(any(), any(), any(), any(), any());
try (final Response response =
resources.getJerseyTest()
.target(String.format("/v1/messages/%s", MULTI_DEVICE_UUID))
@@ -581,10 +570,8 @@ class MessageControllerTest {
assertThat("Good Response Code", response.getStatus(), is(equalTo(409)));
assertThat("Good Response Body",
asJson(response.readEntity(MismatchedDevices.class)),
asJson(response.readEntity(MismatchedDevicesResponse.class)),
is(equalTo(jsonFixture("fixtures/missing_device_response2.json"))));
verifyNoMoreInteractions(messageSender);
}
}
@@ -620,13 +607,11 @@ class MessageControllerTest {
@SuppressWarnings("unchecked") final ArgumentCaptor<Map<Byte, Envelope>> envelopeCaptor =
ArgumentCaptor.forClass(Map.class);
verify(messageSender).sendMessages(any(Account.class), envelopeCaptor.capture());
verify(messageSender).sendMessages(any(Account.class), any(), envelopeCaptor.capture(), any(), any());
assertEquals(3, envelopeCaptor.getValue().size());
envelopeCaptor.getValue().values().forEach(envelope -> {
assertTrue(envelope.getUrgent());
});
envelopeCaptor.getValue().values().forEach(envelope -> assertTrue(envelope.getUrgent()));
}
}
@@ -646,13 +631,11 @@ class MessageControllerTest {
@SuppressWarnings("unchecked") final ArgumentCaptor<Map<Byte, Envelope>> envelopeCaptor =
ArgumentCaptor.forClass(Map.class);
verify(messageSender).sendMessages(any(Account.class), envelopeCaptor.capture());
verify(messageSender).sendMessages(any(Account.class), any(), envelopeCaptor.capture(), any(), any());
assertEquals(3, envelopeCaptor.getValue().size());
envelopeCaptor.getValue().values().forEach(envelope -> {
assertFalse(envelope.getUrgent());
});
envelopeCaptor.getValue().values().forEach(envelope -> assertFalse(envelope.getUrgent()));
}
}
@@ -670,12 +653,18 @@ class MessageControllerTest {
assertThat("Good Response Code", response.getStatus(), is(equalTo(200)));
verify(messageSender).sendMessages(any(Account.class),
argThat(messagesByDeviceId -> messagesByDeviceId.size() == 3));
any(),
argThat(messagesByDeviceId -> messagesByDeviceId.size() == 3),
any(),
any());
}
}
@Test
void testRegistrationIdMismatch() throws Exception {
doThrow(new MismatchedDevicesException(new MismatchedDevices(Collections.emptySet(), Collections.emptySet(), Set.of((byte) 2))))
.when(messageSender).sendMessages(any(), any(), any(), any(), any());
try (final Response response =
resources.getJerseyTest().target(String.format("/v1/messages/%s", MULTI_DEVICE_UUID))
.request()
@@ -687,10 +676,8 @@ class MessageControllerTest {
assertThat("Good Response Code", response.getStatus(), is(equalTo(410)));
assertThat("Good Response Body",
asJson(response.readEntity(StaleDevices.class)),
asJson(response.readEntity(StaleDevicesResponse.class)),
is(equalTo(jsonFixture("fixtures/mismatched_registration_id.json"))));
verifyNoMoreInteractions(messageSender);
}
}
@@ -965,7 +952,7 @@ class MessageControllerTest {
final UUID senderAci = UUID.randomUUID();
final UUID senderPni = UUID.randomUUID();
final String userAgent = "user-agent";
UUID messageGuid = UUID.randomUUID();
final UUID messageGuid = UUID.randomUUID();
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(senderAci);
@@ -976,8 +963,6 @@ class MessageControllerTest {
when(accountsManager.findRecentlyDeletedPhoneNumberIdentifier(senderAci)).thenReturn(Optional.of(senderPni));
when(phoneNumberIdentifiers.getPhoneNumber(senderPni)).thenReturn(CompletableFuture.completedFuture(List.of(senderNumber)));
messageGuid = UUID.randomUUID();
try (final Response response =
resources.getJerseyTest()
.target(String.format("/v1/messages/report/%s/%s", senderAci, messageGuid))
@@ -1102,24 +1087,19 @@ class MessageControllerTest {
}
@Test
void testValidateContentLength() {
final int contentLength = Math.toIntExact(MessageController.MAX_MESSAGE_SIZE + 1);
final byte[] contentBytes = new byte[contentLength];
Arrays.fill(contentBytes, (byte) 1);
void testValidateContentLength() throws MismatchedDevicesException, MessageTooLargeException, IOException {
doThrow(new MessageTooLargeException()).when(messageSender).sendMessages(any(), any(), any(), any(), any());
try (final Response response =
resources.getJerseyTest()
.target(String.format("/v1/messages/%s", SINGLE_DEVICE_UUID))
.request()
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, Base64.getEncoder().encodeToString(UNIDENTIFIED_ACCESS_BYTES))
.put(Entity.entity(new IncomingMessageList(
List.of(new IncomingMessage(1, (byte) 1, 1, Base64.getEncoder().encodeToString(contentBytes))), false, true,
System.currentTimeMillis()),
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.entity(SystemMapper.jsonMapper().readValue(jsonFixture("fixtures/current_message_single_device.json"),
IncomingMessageList.class),
MediaType.APPLICATION_JSON_TYPE))) {
assertThat("Bad response", response.getStatus(), is(equalTo(413)));
verify(messageSender, never()).sendMessages(any(), any());
assertThat(response.getStatus(), is(equalTo(413)));
}
}
@@ -1137,10 +1117,10 @@ class MessageControllerTest {
if (expectOk) {
assertEquals(200, response.getStatus());
verify(messageSender).sendMessages(any(), any());
verify(messageSender).sendMessages(any(), any(), any(), any(), any());
} else {
assertEquals(422, response.getStatus());
verify(messageSender, never()).sendMessages(any(), any());
verify(messageSender, never()).sendMessages(any(), any(), any(), any(), any());
}
}
}
@@ -1164,7 +1144,9 @@ class MessageControllerTest {
final Optional<String> maybeGroupSendToken,
final int expectedStatus,
final Set<Account> expectedResolvedAccounts,
final Set<ServiceIdentifier> expectedUuids404) {
final Set<ServiceIdentifier> expectedUuids404,
@Nullable final MultiRecipientMismatchedDevicesException mismatchedDevicesException)
throws MultiRecipientMismatchedDevicesException, MessageTooLargeException {
clock.pin(START_OF_DAY);
@@ -1175,6 +1157,11 @@ class MessageControllerTest {
when(accountsManager.getByServiceIdentifierAsync(serviceIdentifier))
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)))));
if (mismatchedDevicesException != null) {
doThrow(mismatchedDevicesException)
.when(messageSender).sendMultiRecipientMessage(any(), any(), anyLong(), anyBoolean(), anyBoolean(), anyBoolean(), any());
}
final boolean ephemeral = true;
final boolean urgent = false;
@@ -1211,16 +1198,18 @@ class MessageControllerTest {
assertThat(Set.copyOf(entity.uuids404()), equalTo(expectedUuids404));
}
if (expectedStatus == 200 && !expectedResolvedAccounts.isEmpty()) {
if ((expectedStatus == 200 && !expectedResolvedAccounts.isEmpty()) || mismatchedDevicesException != null) {
verify(messageSender).sendMultiRecipientMessage(any(),
argThat(resolvedRecipients ->
new HashSet<>(resolvedRecipients.values()).equals(expectedResolvedAccounts)),
anyLong(),
eq(isStory),
eq(ephemeral),
eq(urgent));
eq(urgent),
any());
} else {
verify(messageSender, never()).sendMultiRecipientMessage(any(), any(), anyLong(), anyBoolean(), anyBoolean(), anyBoolean());
verify(messageSender, never())
.sendMultiRecipientMessage(any(), any(), anyLong(), anyBoolean(), anyBoolean(), anyBoolean(), any());
}
}
}
@@ -1291,7 +1280,8 @@ class MessageControllerTest {
Optional.empty(),
200,
Set.of(singleDeviceAccount, multiDeviceAccount),
Set.of()),
Set.of(),
null),
Arguments.argumentSet("Multi-recipient message with combined UAKs",
accountsByServiceIdentifier,
@@ -1303,7 +1293,8 @@ class MessageControllerTest {
Optional.empty(),
200,
Set.of(singleDeviceAccount, multiDeviceAccount),
Set.of()),
Set.of(),
null),
Arguments.argumentSet("Multi-recipient message with group send endorsement",
accountsByServiceIdentifier,
@@ -1315,7 +1306,8 @@ class MessageControllerTest {
Optional.of(groupSendEndorsement),
200,
Set.of(singleDeviceAccount, multiDeviceAccount),
Set.of()),
Set.of(),
null),
Arguments.argumentSet("Incorrect combined UAK",
accountsByServiceIdentifier,
@@ -1327,7 +1319,8 @@ class MessageControllerTest {
Optional.empty(),
401,
Set.of(singleDeviceAccount, multiDeviceAccount),
Set.of()),
Set.of(),
null),
Arguments.argumentSet("Incorrect group send endorsement",
accountsByServiceIdentifier,
@@ -1341,7 +1334,8 @@ class MessageControllerTest {
START_OF_DAY.plus(Duration.ofDays(1)))),
401,
Set.of(singleDeviceAccount, multiDeviceAccount),
Set.of()),
Set.of(),
null),
// Stories don't require credentials of any kind, but for historical reasons, we don't reject a combined UAK if
// provided
@@ -1355,7 +1349,8 @@ class MessageControllerTest {
Optional.empty(),
200,
Set.of(singleDeviceAccount, multiDeviceAccount),
Set.of()),
Set.of(),
null),
Arguments.argumentSet("Story with group send endorsement",
accountsByServiceIdentifier,
@@ -1367,7 +1362,8 @@ class MessageControllerTest {
Optional.of(groupSendEndorsement),
400,
Set.of(singleDeviceAccount, multiDeviceAccount),
Set.of()),
Set.of(),
null),
Arguments.argumentSet("Conflicting credentials",
accountsByServiceIdentifier,
@@ -1379,7 +1375,8 @@ class MessageControllerTest {
Optional.of(groupSendEndorsement),
400,
Set.of(singleDeviceAccount, multiDeviceAccount),
Set.of()),
Set.of(),
null),
Arguments.argumentSet("No credentials",
accountsByServiceIdentifier,
@@ -1391,23 +1388,8 @@ class MessageControllerTest {
Optional.empty(),
401,
Set.of(singleDeviceAccount, multiDeviceAccount),
Set.of()),
Arguments.argumentSet("Oversized payload",
accountsByServiceIdentifier,
MultiRecipientMessageHelper.generateMultiRecipientMessage(List.of(
new TestRecipient(new AciServiceIdentifier(singleDeviceAccountAci), Device.PRIMARY_ID, singleDevicePrimaryRegistrationId, new byte[48]),
new TestRecipient(new AciServiceIdentifier(multiDeviceAccountAci), Device.PRIMARY_ID, multiDevicePrimaryRegistrationId, new byte[48]),
new TestRecipient(new AciServiceIdentifier(multiDeviceAccountAci), (byte) (Device.PRIMARY_ID + 1), multiDeviceLinkedRegistrationId, new byte[48])),
MultiRecipientMessageProvider.MAX_MESSAGE_SIZE),
clock.instant().toEpochMilli(),
false,
false,
Optional.empty(),
Optional.of(groupSendEndorsement),
413,
Set.of(singleDeviceAccount, multiDeviceAccount),
Set.of()),
Set.of(),
null),
Arguments.argumentSet("Negative timestamp",
accountsByServiceIdentifier,
@@ -1419,7 +1401,8 @@ class MessageControllerTest {
Optional.of(groupSendEndorsement),
400,
Set.of(singleDeviceAccount, multiDeviceAccount),
Set.of()),
Set.of(),
null),
Arguments.argumentSet("Excessive timestamp",
accountsByServiceIdentifier,
@@ -1431,7 +1414,8 @@ class MessageControllerTest {
Optional.of(groupSendEndorsement),
400,
Set.of(singleDeviceAccount, multiDeviceAccount),
Set.of()),
Set.of(),
null),
Arguments.argumentSet("Empty recipient list",
accountsByServiceIdentifier,
@@ -1445,7 +1429,8 @@ class MessageControllerTest {
START_OF_DAY.plus(Duration.ofDays(1)))),
400,
Set.of(singleDeviceAccount, multiDeviceAccount),
Set.of()),
Set.of(),
null),
Arguments.argumentSet("Story with empty recipient list",
accountsByServiceIdentifier,
@@ -1457,7 +1442,8 @@ class MessageControllerTest {
Optional.empty(),
400,
Set.of(singleDeviceAccount, multiDeviceAccount),
Set.of()),
Set.of(),
null),
Arguments.argumentSet("Duplicate recipient",
accountsByServiceIdentifier,
@@ -1471,7 +1457,8 @@ class MessageControllerTest {
Optional.of(groupSendEndorsement),
400,
Set.of(singleDeviceAccount, multiDeviceAccount),
Set.of()),
Set.of(),
null),
Arguments.argumentSet("Missing account",
Map.of(),
@@ -1483,7 +1470,8 @@ class MessageControllerTest {
Optional.of(groupSendEndorsement),
200,
Collections.emptySet(),
Set.of(new AciServiceIdentifier(singleDeviceAccountAci), new AciServiceIdentifier(multiDeviceAccountAci))),
Set.of(new AciServiceIdentifier(singleDeviceAccountAci), new AciServiceIdentifier(multiDeviceAccountAci)),
null),
Arguments.argumentSet("One missing and one existing account",
Map.of(new AciServiceIdentifier(singleDeviceAccountAci), singleDeviceAccount),
@@ -1495,7 +1483,8 @@ class MessageControllerTest {
Optional.of(groupSendEndorsement),
200,
Set.of(singleDeviceAccount),
Set.of(new AciServiceIdentifier(multiDeviceAccountAci))),
Set.of(new AciServiceIdentifier(multiDeviceAccountAci)),
null),
Arguments.argumentSet("Missing account for story",
Map.of(),
@@ -1507,7 +1496,8 @@ class MessageControllerTest {
Optional.empty(),
200,
Collections.emptySet(),
Set.of()),
Set.of(),
null),
Arguments.argumentSet("One missing and one existing account for story",
Map.of(new AciServiceIdentifier(singleDeviceAccountAci), singleDeviceAccount),
@@ -1519,7 +1509,8 @@ class MessageControllerTest {
Optional.empty(),
200,
Set.of(singleDeviceAccount),
Set.of()),
Set.of(),
null),
Arguments.argumentSet("Missing device",
accountsByServiceIdentifier,
@@ -1533,7 +1524,9 @@ class MessageControllerTest {
Optional.of(groupSendEndorsement),
409,
Set.of(singleDeviceAccount, multiDeviceAccount),
Set.of()),
Set.of(),
new MultiRecipientMismatchedDevicesException(Map.of(new AciServiceIdentifier(multiDeviceAccountAci),
new MismatchedDevices(Set.of((byte) (Device.PRIMARY_ID + 1)), Collections.emptySet(), Collections.emptySet())))),
Arguments.argumentSet("Extra device",
accountsByServiceIdentifier,
@@ -1549,7 +1542,9 @@ class MessageControllerTest {
Optional.of(groupSendEndorsement),
409,
Set.of(singleDeviceAccount, multiDeviceAccount),
Set.of()),
Set.of(),
new MultiRecipientMismatchedDevicesException(Map.of(new AciServiceIdentifier(multiDeviceAccountAci),
new MismatchedDevices(Collections.emptySet(), Set.of((byte) (Device.PRIMARY_ID + 2)), Collections.emptySet())))),
Arguments.argumentSet("Stale registration ID",
accountsByServiceIdentifier,
@@ -1564,7 +1559,9 @@ class MessageControllerTest {
Optional.of(groupSendEndorsement),
410,
Set.of(singleDeviceAccount, multiDeviceAccount),
Set.of()),
Set.of(),
new MultiRecipientMismatchedDevicesException(Map.of(new AciServiceIdentifier(multiDeviceAccountAci),
new MismatchedDevices(Collections.emptySet(), Collections.emptySet(), Set.of((byte) (Device.PRIMARY_ID + 1)))))),
Arguments.argumentSet("Rate-limited story",
accountsByServiceIdentifier,
@@ -1576,7 +1573,8 @@ class MessageControllerTest {
Optional.empty(),
429,
Set.of(singleDeviceAccount, multiDeviceAccount),
Set.of()),
Set.of(),
null),
Arguments.argumentSet("Story to PNI recipients",
accountsByServiceIdentifier,
@@ -1591,7 +1589,8 @@ class MessageControllerTest {
Optional.empty(),
200,
Set.of(singleDeviceAccount, multiDeviceAccount),
Set.of()),
Set.of(),
null),
Arguments.argumentSet("Multi-recipient message to PNI recipients with UAK",
accountsByServiceIdentifier,
@@ -1606,7 +1605,8 @@ class MessageControllerTest {
Optional.empty(),
401,
Set.of(singleDeviceAccount, multiDeviceAccount),
Set.of()),
Set.of(),
null),
Arguments.argumentSet("Multi-recipient message to PNI recipients with group send endorsement",
accountsByServiceIdentifier,
@@ -1623,10 +1623,102 @@ class MessageControllerTest {
START_OF_DAY.plus(Duration.ofDays(1)))),
200,
Set.of(singleDeviceAccount, multiDeviceAccount),
Set.of())
Set.of(),
null)
);
}
@Test
void sendMultiRecipientMessageOversized() throws Exception {
clock.pin(START_OF_DAY);
final UUID singleDeviceAccountAci = UUID.randomUUID();
final UUID singleDeviceAccountPni = UUID.randomUUID();
final UUID multiDeviceAccountAci = UUID.randomUUID();
final UUID multiDeviceAccountPni = UUID.randomUUID();
final byte[] singleDeviceAccountUak = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final byte[] multiDeviceAccountUak = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final int singleDevicePrimaryRegistrationId = 1;
final int multiDevicePrimaryRegistrationId = 2;
final int multiDeviceLinkedRegistrationId = 3;
final Device singleDeviceAccountPrimary = mock(Device.class);
when(singleDeviceAccountPrimary.getId()).thenReturn(Device.PRIMARY_ID);
when(singleDeviceAccountPrimary.getRegistrationId()).thenReturn(singleDevicePrimaryRegistrationId);
final Device multiDeviceAccountPrimary = mock(Device.class);
when(multiDeviceAccountPrimary.getId()).thenReturn(Device.PRIMARY_ID);
when(multiDeviceAccountPrimary.getRegistrationId()).thenReturn(multiDevicePrimaryRegistrationId);
final Device multiDeviceAccountLinked = mock(Device.class);
when(multiDeviceAccountLinked.getId()).thenReturn((byte) (Device.PRIMARY_ID + 1));
when(multiDeviceAccountLinked.getRegistrationId()).thenReturn(multiDeviceLinkedRegistrationId);
final Account singleDeviceAccount = mock(Account.class);
when(singleDeviceAccount.getIdentifier(IdentityType.ACI)).thenReturn(singleDeviceAccountAci);
when(singleDeviceAccount.getUnidentifiedAccessKey()).thenReturn(Optional.of(singleDeviceAccountUak));
when(singleDeviceAccount.getDevices()).thenReturn(List.of(singleDeviceAccountPrimary));
when(singleDeviceAccount.getDevice(anyByte())).thenReturn(Optional.empty());
when(singleDeviceAccount.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(singleDeviceAccountPrimary));
final Account multiDeviceAccount = mock(Account.class);
when(multiDeviceAccount.getIdentifier(IdentityType.ACI)).thenReturn(multiDeviceAccountAci);
when(multiDeviceAccount.getUnidentifiedAccessKey()).thenReturn(Optional.of(multiDeviceAccountUak));
when(multiDeviceAccount.getDevices()).thenReturn(List.of(multiDeviceAccountPrimary, multiDeviceAccountLinked));
when(multiDeviceAccount.getDevice(anyByte())).thenReturn(Optional.empty());
when(multiDeviceAccount.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(multiDeviceAccountPrimary));
when(multiDeviceAccount.getDevice((byte) (Device.PRIMARY_ID + 1))).thenReturn(Optional.of(multiDeviceAccountLinked));
final Map<ServiceIdentifier, Account> accountsByServiceIdentifier = Map.of(
new AciServiceIdentifier(singleDeviceAccountAci), singleDeviceAccount,
new AciServiceIdentifier(multiDeviceAccountAci), multiDeviceAccount,
new PniServiceIdentifier(singleDeviceAccountPni), singleDeviceAccount,
new PniServiceIdentifier(multiDeviceAccountPni), multiDeviceAccount);
final byte[] aciMessage = MultiRecipientMessageHelper.generateMultiRecipientMessage(List.of(
new TestRecipient(new AciServiceIdentifier(singleDeviceAccountAci), Device.PRIMARY_ID, singleDevicePrimaryRegistrationId, new byte[48]),
new TestRecipient(new AciServiceIdentifier(multiDeviceAccountAci), Device.PRIMARY_ID, multiDevicePrimaryRegistrationId, new byte[48]),
new TestRecipient(new AciServiceIdentifier(multiDeviceAccountAci), (byte) (Device.PRIMARY_ID + 1), multiDeviceLinkedRegistrationId, new byte[48])));
when(accountsManager.getByServiceIdentifierAsync(any()))
.thenReturn(CompletableFuture.completedFuture(Optional.empty()));
accountsByServiceIdentifier.forEach(((serviceIdentifier, account) ->
when(accountsManager.getByServiceIdentifierAsync(serviceIdentifier))
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)))));
final boolean ephemeral = true;
final boolean urgent = false;
final boolean story = false;
final Invocation.Builder invocationBuilder = resources
.getJerseyTest()
.target("/v1/messages/multi_recipient")
.queryParam("ts", clock.millis())
.queryParam("online", ephemeral)
.queryParam("story", story)
.queryParam("urgent", urgent)
.request()
.header(HeaderUtils.GROUP_SEND_TOKEN, AuthHelper.validGroupSendTokenHeader(serverSecretParams,
List.of(new AciServiceIdentifier(singleDeviceAccountAci), new AciServiceIdentifier(multiDeviceAccountAci)),
START_OF_DAY.plus(Duration.ofDays(1))));
when(rateLimiter.validateAsync(any(UUID.class)))
.thenReturn(CompletableFuture.completedFuture(null));
doThrow(new MessageTooLargeException())
.when(messageSender).sendMultiRecipientMessage(any(), any(), anyLong(), anyBoolean(), anyBoolean(), anyBoolean(), any());
try (final Response response = invocationBuilder
.put(Entity.entity(aciMessage, MultiRecipientMessageProvider.MEDIA_TYPE))) {
assertThat(response.getStatus(), is(equalTo(413)));
}
}
@SuppressWarnings("SameParameterValue")
private static Envelope generateEnvelope(UUID guid, int type, long timestamp, UUID sourceUuid,
byte sourceDevice, UUID destinationUuid, UUID updatedPni, byte[] content, long serverTimestamp) {
@@ -1659,14 +1751,4 @@ class MessageControllerTest {
return builder.build();
}
@Test
void decodedSize() {
for (int size = MessageController.MAX_MESSAGE_SIZE - 3; size <= MessageController.MAX_MESSAGE_SIZE + 3; size++) {
final byte[] bytes = TestRandomUtil.nextBytes(size);
final String base64Encoded = Base64.getEncoder().encodeToString(bytes);
assertEquals(bytes.length, MessageController.decodedSize(base64Encoded));
}
}
}
@@ -442,8 +442,10 @@ class ProfileControllerTest {
@CartesianTest
void testProfileCapabilities(
@CartesianTest.Values(booleans = {true, false}) final boolean isDeleteSyncSupported) {
@CartesianTest.Values(booleans = {true, false}) final boolean isDeleteSyncSupported,
@CartesianTest.Values(booleans = {true, false}) final boolean isAttachmentBackfillSupported) {
when(capabilitiesAccount.hasCapability(DeviceCapability.DELETE_SYNC)).thenReturn(isDeleteSyncSupported);
when(capabilitiesAccount.hasCapability(DeviceCapability.ATTACHMENT_BACKFILL)).thenReturn(isAttachmentBackfillSupported);
final BaseProfileResponse profile = resources.getJerseyTest()
.target("/v1/profile/" + AuthHelper.VALID_UUID)
.request()
@@ -451,6 +453,7 @@ class ProfileControllerTest {
.get(BaseProfileResponse.class);
assertEquals(isDeleteSyncSupported, profile.getCapabilities().get("deleteSync"));
assertEquals(isAttachmentBackfillSupported, profile.getCapabilities().get("attachmentBackfill"));
}
@Test
@@ -69,7 +69,7 @@ class OutgoingMessageEntityTest {
final Account account = new Account();
account.setUuid(UUID.randomUUID());
IncomingMessage message = new IncomingMessage(1, (byte) 44, 55, "AAAAAA");
IncomingMessage message = new IncomingMessage(1, (byte) 44, 55, TestRandomUtil.nextBytes(4));
MessageProtos.Envelope baseEnvelope = message.toEnvelope(
new AciServiceIdentifier(UUID.randomUUID()),
@@ -57,6 +57,7 @@ import org.whispersystems.textsecuregcm.backup.BackupManager;
import org.whispersystems.textsecuregcm.backup.BackupUploadDescriptor;
import org.whispersystems.textsecuregcm.backup.CopyResult;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.metrics.BackupMetrics;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import reactor.core.publisher.Flux;
@@ -74,7 +75,7 @@ class BackupsAnonymousGrpcServiceTest extends
@Override
protected BackupsAnonymousGrpcService createServiceBeforeEachTest() {
return new BackupsAnonymousGrpcService(backupManager);
return new BackupsAnonymousGrpcService(backupManager, new BackupMetrics());
}
@BeforeEach
@@ -54,6 +54,7 @@ import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
import org.whispersystems.textsecuregcm.backup.BackupAuthTestUtil;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.metrics.BackupMetrics;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.util.EnumMapUtil;
@@ -77,7 +78,7 @@ class BackupsGrpcServiceTest extends SimpleBaseGrpcTest<BackupsGrpcService, Back
@Override
protected BackupsGrpcService createServiceBeforeEachTest() {
return new BackupsGrpcService(accountsManager, backupAuthManager);
return new BackupsGrpcService(accountsManager, backupAuthManager, new BackupMetrics());
}
@BeforeEach
@@ -434,7 +434,8 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
@CartesianTest.Values(bytes = {Device.PRIMARY_ID, Device.PRIMARY_ID + 1}) final byte deviceId,
@CartesianTest.Values(booleans = {true, false}) final boolean storage,
@CartesianTest.Values(booleans = {true, false}) final boolean transfer,
@CartesianTest.Values(booleans = {true, false}) final boolean deleteSync) {
@CartesianTest.Values(booleans = {true, false}) final boolean deleteSync,
@CartesianTest.Values(booleans = {true, false}) final boolean attachmentBackfill) {
mockAuthenticationInterceptor().setAuthenticatedDevice(AUTHENTICATED_ACI, deviceId);
@@ -455,6 +456,10 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
requestBuilder.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_DELETE_SYNC);
}
if (attachmentBackfill) {
requestBuilder.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_ATTACHMENT_BACKFILL);
}
final SetCapabilitiesResponse ignored = authenticatedServiceStub().setCapabilities(requestBuilder.build());
final Set<DeviceCapability> expectedCapabilities = new HashSet<>();
@@ -471,6 +476,10 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
expectedCapabilities.add(DeviceCapability.DELETE_SYNC);
}
if (attachmentBackfill) {
expectedCapabilities.add(DeviceCapability.ATTACHMENT_BACKFILL);
}
verify(device).setCapabilities(expectedCapabilities);
}
}
@@ -33,6 +33,8 @@ public class RequestAttributesServiceImpl extends RequestAttributesGrpc.RequestA
.setAdditionalSpecifiers(userAgent.getAdditionalSpecifiers().orElse(""))
.build()));
RequestAttributesUtil.getRawUserAgent().ifPresent(responseBuilder::setRawUserAgent);
responseObserver.onNext(responseBuilder.build());
responseObserver.onCompleted();
}
@@ -152,6 +152,21 @@ class RequestAttributesUtilTest {
assertEquals("Linux", response.getUserAgent().getAdditionalSpecifiers());
}
@Test
void getRawUserAgent() {
when(grpcClientConnectionManager.getRawUserAgent(any()))
.thenReturn(Optional.empty());
assertTrue(getRequestAttributes().getRawUserAgent().isBlank());
final String userAgentString = "Signal-Desktop/1.2.3 Linux";
when(grpcClientConnectionManager.getRawUserAgent(any()))
.thenReturn(Optional.of(userAgentString));
assertEquals(userAgentString, getRequestAttributes().getRawUserAgent());
}
private GetRequestAttributesResponse getRequestAttributes() {
return RequestAttributesGrpc.newBlockingStub(managedChannel)
.getRequestAttributes(GetRequestAttributesRequest.newBuilder().build());
Loaded 100 of 121 files, more files were not shown because too many files have changed in this diff. Show more