Compare commits

..
Author SHA1 Message Date
Ameya Lokare 8afc0e6ab2 Update to the latest version of the spam filter 2024-07-31 12:34:54 -07:00
Jon Chambers 822092044b Add a method to check for the presence of persisted messages, skipping the cache 2024-07-31 10:50:47 -04:00
Jon Chambers f1c153f39f Log max concurrency when starting/finishing experiments 2024-07-31 10:50:31 -04:00
Jon Chambers 7e62dc64dc Replace filterWhen with flatMap 2024-07-31 10:50:31 -04:00
Jon Chambers 2104a60703 Also check legacy parittion keys for message presence 2024-07-31 10:50:19 -04:00
Jon Chambers 97785fa570 Remove unused metrics and arguments 2024-07-31 10:50:19 -04:00
Chris Eager 9341fe9584 Add endpoint tag and story to auth type tag values 2024-07-31 09:38:14 -05:00
Ravi Khadiwala 3a582721cf Throw error for oversized inbound noise messages 2024-07-30 11:25:09 -05:00
Ravi Khadiwala 3d96d73169 Break up large outbound noise messages 2024-07-30 11:25:09 -05:00
Ravi Khadiwala 542422b7b8 Replace XX/NX handshakes with IK/NK 2024-07-30 11:25:09 -05:00
Jon Chambers c835d85256 Drop opentest4j from dependency management 2024-07-30 12:24:26 -04:00
Jon Chambers 56ada7f0e9 Add a "dry run" mode for the "start push notification experiment" command 2024-07-30 12:19:00 -04:00
Jon Chambers 56fdebde75 Check for cached/persisted messages in parallel 2024-07-30 12:18:46 -04:00
Jon Chambers 4ee67064bb Remove a pair of unused methods 2024-07-30 12:18:34 -04:00
Jon Chambers 045ec9689d Introduce a job scheduler and experiment for sending notifications to idle devices 2024-07-29 11:16:53 -04:00
Jon Chambers 4ebad2c473 Add a framework for running experiments to improve push notification reliability 2024-07-25 11:36:05 -04:00
Jonathan Klabunde Tomer 1fe6dac760 read old new key and new new key 2024-07-24 07:44:44 -07:00
Jonathan Klabunde Tomer f12a6ff73f Remove migration paths for lazy message deletion 2024-07-23 14:07:19 -07:00
Chris Eager 6eed458ceb Use server timestamp for delivery duration metrics 2024-07-18 12:22:59 -05:00
Jon Chambers 54fb0a6acb Add a general job scheduler 2024-07-18 13:22:31 -04:00
Jon Chambers 5147d9cb6d Mark old attachment endpoints as @Deprecated 2024-07-17 15:01:44 -04:00
Jon Chambers 37369929f3 Retire PushLatencyManager 2024-07-17 15:01:23 -04:00
Jon Chambers 4f10014902 Add an "is primary" dimension to message latency measurements 2024-07-17 15:01:08 -04:00
Ravi Khadiwala 0ef3e00ba7 Use non-legacy rate limit error in BackupAuthManager 2024-07-11 16:39:11 -05:00
Chris Eager 2408590430 Update GitHub Actions 2024-07-11 16:38:15 -05:00
Chris Eager b7f4fe4d73 Update various dependencies 2024-07-11 16:38:15 -05:00
Chris Eager b811492acd Update maven-wrapper.properties 2024-07-11 16:38:15 -05:00
Chris Eager a63e0e0390 Remove unused RateLimiters 2024-07-11 16:37:55 -05:00
Jon Chambers 5e8a0b2cfa Introduce a utility class for finding reasonable times to send push notifications 2024-07-11 17:36:54 -04:00
Chris Eager eac75aad03 Add distribution of multi-recipient message recipient counts 2024-07-09 15:04:47 -05:00
Chris Eager b05fbc2102 Add metric for group send token adoption 2024-07-09 15:04:12 -05:00
Jon Chambers 6d166fdfc5 Return futures from "send push notification" operations 2024-07-08 15:36:17 -04:00
Ravi Khadiwala 2e36673702 Add warn log if changeNumber messages fail 2024-07-08 15:28:08 -04:00
ravi-signal 0c81ffe8b7 Count unregistered APNS tokens with a recent update 2024-07-08 15:27:48 -04:00
Jon Chambers 02b9ceb4c7 Discard APNs tokens if the APNs server reports that the token is expired 2024-07-08 15:27:23 -04:00
Chris Eager 775889c0b6 Remove deprecated PUT /v2/keys/signed endpoint 2024-07-08 15:26:26 -04:00
Chris Eager 98f2cdaf5a Reduce DynamoDB test client API timeouts 2024-07-08 15:26:11 -04:00
Jon Chambers ff5cc3cb4f Avoid duplicate metric registry configuration in commands 2024-07-08 15:25:16 -04:00
Jon Chambers ebecb1caec Throw an exception if metric registries are configured more than once 2024-07-08 15:25:16 -04:00
Jon Chambers 73e0aea85c Retire Device#hasMessageDeliveryChannel() 2024-06-26 14:46:39 -04:00
Ameya Lokare 1a09f5807b Update to the latest version of the spam filter 2024-06-26 11:45:58 -07:00
Ameya Lokare ec009a2bba Pass AccountAndAuthenticatedDeviceHolder to spam filter 2024-06-26 11:32:49 -07:00
Jon Chambers f52c40a492 Update to the latest version of the spam filter 2024-06-25 11:57:37 -04:00
Jon Chambers 1959c059ed Rename AuthEnablementRefreshRequirementProvider to LinkedDeviceRefreshRequirementProvider 2024-06-25 11:57:25 -04:00
Jon Chambers 2d1610b075 Stop monitoring device "enabled" state changes from auth enablement refresh requirement provider
Device enabled states no longer affect anything at an authentication level
2024-06-25 11:57:25 -04:00
Jon Chambers 2f76738b50 Expire APNs tokens if they haven't been updated since the expiration timestamp 2024-06-25 11:53:23 -04:00
Jon Chambers 1cf174a613 Include "token invalidation timestamp" in push notification responses 2024-06-25 11:53:23 -04:00
Jon Chambers d743454d07 Store updated APNs tokens unconditionally 2024-06-25 11:53:23 -04:00
Jon Chambers 1cd16eaa08 Delete FCM tokens immediately if FCM reports that they're no longer active 2024-06-25 11:53:23 -04:00
Jon Chambers 90e622b307 Require that message bundles include all linked devices 2024-06-25 11:51:09 -04:00
Jon Chambers cb5cd64c05 Gracefully handle NotPushRegisteredException 2024-06-25 11:23:16 -04:00
Jon Chambers 2619569549 Update to the latest version of the spam filter 2024-06-25 09:57:32 -04:00
Jon Chambers d306cafbcc Allow, but do not require, message delivery to devices without active delivery channels 2024-06-25 09:53:31 -04:00
Jon Chambers f5ce34fb69 Update to the latest version of the spam filter 2024-06-24 15:41:11 -04:00
Jon Chambers dbeba4f173 Reduce "delete after idle" time for accounts from 180 days to 120 days 2024-06-24 15:20:35 -04:00
Jon Chambers 86f83635bc Document a missing "capability downgrade" response 2024-06-24 15:20:06 -04:00
Jon Chambers fceda00d83 Consider all device when checking device capabilities 2024-06-24 15:20:06 -04:00
Jon Chambers 9b7af00cf5 Add methods to test whether a device may have unread messages 2024-06-24 15:19:48 -04:00
Chris Eager fa1281ae86 Update maven plugin versions 2024-06-24 14:16:05 -05:00
Chris Eager f5de4d7b71 Update various library dependencies 2024-06-24 14:16:05 -05:00
Chris Eager 1134df88e2 Remove obsolete "recaptcha" 2024-06-24 14:15:27 -05:00
ravi-signal 4aadabfac0 Make copy/delete streaming friendly 2024-06-20 16:00:09 -05:00
Jon Chambers c27898a993 Update to the latest version of the spam filter 2024-06-20 11:36:00 -04:00
Ravi Khadiwala daa897db93 Add some extra validation in integration tests 2024-06-18 15:29:58 -05:00
Jon Chambers 7a907bb44d Update to the latest version of the spam filter 2024-06-14 15:01:37 -04:00
Jon Chambers d7cb219577 Update to the latest version of the spam filter 2024-06-14 11:03:42 -04:00
Jon Chambers b28f8b0e7f Update to the latest version of the spam filter 2024-06-14 10:34:37 -04:00
Jon Chambers 51721dde50 Update to the latest version of the spam filter 2024-06-13 14:40:35 -04:00
Jon Chambers 09547ba788 Update to the latest version of the spam filter 2024-06-13 10:39:11 -04:00
Jon Chambers 3dc8acc385 Update to the latest version of the spam filter 2024-06-13 09:10:30 -04:00
Katherine 0414da8c32 Add delete sync capability 2024-06-12 13:54:06 -04:00
Jon Chambers 155450380e Fix weird indentation 2024-06-12 13:53:48 -04:00
Jon Chambers 09bc4ef1d6 Measure sizes of group messages 2024-06-12 13:53:48 -04:00
Jon Chambers 3aa4d8713c Switch to a remote-aggregated distribution for message size metrics 2024-06-12 13:53:48 -04:00
Jon Chambers 5fc926271f Remove a metrics tag for "has spam reporting token" 2024-06-12 13:53:33 -04:00
Katherine f435b612c9 Remove stale pni, pnp, and giftBadges capabilities 2024-06-12 13:42:18 -04:00
Jon Chambers 5b78c0d3e0 Update to the latest version of the spam filter 2024-06-10 17:21:04 -04:00
Jon Chambers 6a14bf70e0 Extend push token removal grace period from 3 days to 14 2024-06-10 17:16:49 -04:00
Jon Chambers 138b368951 Add an explicit "incorrect password" authentication failure reason 2024-06-10 17:16:32 -04:00
Jon Chambers 0871d6ebc1 Add a log filter for spurious warnings about unsupported channel options 2024-06-10 17:16:10 -04:00
Jon Chambers ad5ef76e8e Update to the latest version of the spam filter 2024-06-10 11:20:52 -04:00
Jon Chambers 2f55747601 Remove expiration check from Device#isEnabled() 2024-06-07 10:39:11 -07:00
Jonathan Klabunde Tomer b376458963 include deleted-messages counter on both message deletion paths 2024-06-07 10:24:42 -07:00
Jon Chambers 64ac22a918 Resolve warnings/suggestions throughout MessageControllerTest 2024-06-06 14:11:44 -04:00
Alan Liu ffb81e4ff7 Retrieve Cloudflare Turn Credentials from Cloudflare 2024-06-05 12:03:40 -04:00
Jonathan Klabunde Tomer 01743e5c88 Delete messages lazily on account and device deletion to prevent timeouts when deleting accounts/devices with large queues 2024-06-04 12:16:43 -07:00
204 changed files with 7483 additions and 4472 deletions

No files matched your search

+2 -2
View File
@@ -11,8 +11,8 @@ jobs:
contents: write
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
- uses: actions/setup-java@9704b39bf258b59bc04b50fa2dd55e9ed76b47a8 # v4.1.0
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
- uses: actions/setup-java@99b8673ff64fbf99d8d325f52d9a5bdedb8483e9 # v4.2.1
with:
distribution: 'temurin'
java-version: '21'
+3 -3
View File
@@ -13,13 +13,13 @@ jobs:
id-token: write
contents: read
steps:
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
- uses: actions/setup-java@9704b39bf258b59bc04b50fa2dd55e9ed76b47a8 # v4.1.0
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
- uses: actions/setup-java@99b8673ff64fbf99d8d325f52d9a5bdedb8483e9 # v4.2.1
with:
distribution: 'temurin'
java-version: '21'
cache: 'maven'
- uses: aws-actions/configure-aws-credentials@e3dd6a429d7300a6a4c196c26e071d42e0343502 #v4.0.2
- uses: aws-actions/configure-aws-credentials@5579c002bb4778aa43395ef1df492868a9a1c83f # v4.0.2
name: Configure AWS credentials from Test account
with:
role-to-assume: ${{ vars.AWS_ROLE }}
+2 -2
View File
@@ -11,9 +11,9 @@ jobs:
container: ubuntu:22.04
steps:
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
- name: Set up JDK 21
uses: actions/setup-java@9704b39bf258b59bc04b50fa2dd55e9ed76b47a8 # v4.1.0
uses: actions/setup-java@99b8673ff64fbf99d8d325f52d9a5bdedb8483e9 # v4.2.1
with:
distribution: 'temurin'
java-version: 21
BIN
View File
Binary file not shown.
+4 -4
View File
@@ -14,7 +14,7 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.4/apache-maven-3.9.4-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar
distributionSha256Sum=e896b60329a71b719d77bb4388b251a50aebcd73c62f69d510c858ce360afe0f
wrapperSha256Sum=e63a53cfb9c4d291ebe3c2b0edacb7622bbc480326beaa5a0456e412f52f066a
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.8/apache-maven-3.9.8-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.2/maven-wrapper-3.3.2.jar
distributionSha256Sum=8351955a9acf2f83c136c4eee0f6db894ab6265fdbe0a94b32a380307dbaa3e1
wrapperSha256Sum=3d8f20ce6103913be8b52aef6d994e0c54705fb527324ceb9b835b338739c7a8
+2 -2
View File
@@ -28,7 +28,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.1.2</version>
<version>3.3.0</version>
<configuration>
<excludes>
<exclude>**</exclude>
@@ -39,7 +39,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>3.1.2</version>
<version>3.3.0</version>
<configuration>
<additionalClasspathElements>
<additionalClasspathElement>${project.basedir}/.libs/software.amazon.awssdk-sso.jar</additionalClasspathElement>
@@ -50,6 +50,7 @@ import org.whispersystems.textsecuregcm.entities.RegistrationRequest;
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.HttpUtils;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import javax.validation.ConstraintViolation;
@@ -249,7 +250,7 @@ public final class Operations {
public Pair<Integer, Void> executeExpectSuccess() {
final Pair<Integer, Void> execute = execute();
Validate.isTrue(
execute.getLeft() >= 200 && execute.getLeft() < 300,
HttpUtils.isSuccessfulResponse(execute.getLeft()),
"Unexpected response code: %d",
execute.getLeft());
return execute;
@@ -257,6 +258,10 @@ public final class Operations {
public <T> T executeExpectSuccess(final Class<T> expectedType) {
final Pair<Integer, T> execute = execute(expectedType);
Validate.isTrue(
HttpUtils.isSuccessfulResponse(execute.getLeft()),
"Unexpected response code: %d : %s",
execute.getLeft(), execute.getRight());
return requireNonNull(execute.getRight());
}
@@ -126,7 +126,7 @@ public class TestUser {
}
public AccountAttributes accountAttributes() {
return new AccountAttributes(true, registrationId, pniRegistrationId, "".getBytes(StandardCharsets.UTF_8), "", true, new Device.DeviceCapabilities(false, false, false))
return new AccountAttributes(true, registrationId, pniRegistrationId, "".getBytes(StandardCharsets.UTF_8), "", true, new Device.DeviceCapabilities(false, false, false, false))
.withUnidentifiedAccessKey(unidentifiedAccessKey)
.withRecoveryPassword(registrationPassword);
}
@@ -5,6 +5,7 @@
package org.signal.integration;
import io.micrometer.common.util.StringUtils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.whispersystems.textsecuregcm.entities.CreateVerificationSessionRequest;
@@ -29,6 +30,8 @@ public class RegistrationTest {
.executeExpectSuccess(VerificationSessionResponse.class);
final String sessionId = verificationSessionResponse.id();
Assertions.assertTrue(StringUtils.isNotBlank(sessionId));
final String pushChallenge = Operations.peekVerificationSessionPushChallenge(sessionId);
// supply push challenge
+31 -31
View File
@@ -38,40 +38,40 @@
<properties>
<aws.sdk2.version>2.23.8</aws.sdk2.version>
<braintree.version>3.27.0</braintree.version>
<commons-csv.version>1.10.0</commons-csv.version>
<commons-io.version>2.14.0</commons-io.version>
<dropwizard.version>3.0.6</dropwizard.version>
<braintree.version>3.34.0</braintree.version>
<commons-csv.version>1.11.0</commons-csv.version>
<commons-io.version>2.16.1</commons-io.version>
<dropwizard.version>3.0.7</dropwizard.version>
<dropwizard-metrics-datadog.version>1.1.13</dropwizard-metrics-datadog.version>
<dynamodblocal.version>1.23.0</dynamodblocal.version>
<google-cloud-libraries.version>26.33.0</google-cloud-libraries.version>
<grpc.version>1.61.1</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
<gson.version>2.10.1</gson.version>
<gson.version>2.11.0</gson.version>
<!-- several libraries (AWS, Google Cloud) use Apache http components transitively, and we need to align them -->
<httpcore.version>4.4.16</httpcore.version>
<httpclient.version>4.5.14</httpclient.version>
<jackson.version>2.16.0</jackson.version>
<jackson.version>2.17.2</jackson.version>
<jaxb.version>2.3.1</jaxb.version>
<junit-pioneer.version>2.1.0</junit-pioneer.version>
<junit-pioneer.version>2.2.0</junit-pioneer.version>
<jsr305.version>3.0.2</jsr305.version>
<kotlin.version>1.9.10</kotlin.version>
<kotlin.version>1.9.24</kotlin.version>
<kotlinx-serialization.version>1.5.1</kotlinx-serialization.version>
<lettuce.version>6.3.2.RELEASE</lettuce.version>
<libphonenumber.version>8.13.23</libphonenumber.version>
<libphonenumber.version>8.13.40</libphonenumber.version>
<logstash.logback.version>7.3</logstash.logback.version>
<log4j-bom.version>2.21.0</log4j-bom.version>
<log4j-bom.version>2.23.1</log4j-bom.version>
<luajava.version>3.4.0</luajava.version>
<micrometer.version>1.12.4</micrometer.version>
<netty.version>4.1.108.Final</netty.version>
<opentest4j.version>1.3.0</opentest4j.version>
<micrometer.version>1.13.2</micrometer.version>
<netty.version>4.1.111.Final</netty.version>
<protobuf.version>3.25.2</protobuf.version> <!-- should be kept in sync with the value from Google libraries-bom -->
<pushy.version>0.15.4</pushy.version>
<reactive.grpc.version>1.2.4</reactive.grpc.version>
<reactor-bom.version>2023.0.4</reactor-bom.version> <!-- 3.6.x, see https://github.com/reactor/reactor#bom-versioning-scheme -->
<reactor-bom.version>2023.0.8</reactor-bom.version> <!-- 3.6.x, see https://github.com/reactor/reactor#bom-versioning-scheme -->
<resilience4j.version>2.2.0</resilience4j.version>
<semver4j.version>3.1.0</semver4j.version>
<slf4j.version>2.0.9</slf4j.version>
<slf4j.version>2.0.13</slf4j.version>
<stripe.version>23.10.0</stripe.version>
<swagger.version>2.2.17</swagger.version>
<swagger.version>2.2.22</swagger.version>
<!-- 21.0.3_9-jre-jammy -->
<docker.image.sha256>434c26bd14f3208b9e739277e2679c2c7ef3f85d4a4f32c5a27b12a7fc206b09</docker.image.sha256>
@@ -221,12 +221,6 @@
<version>${jaxb.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.opentest4j</groupId>
<artifactId>opentest4j</artifactId>
<version>${opentest4j.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
@@ -278,7 +272,7 @@
<dependency>
<groupId>org.signal</groupId>
<artifactId>libsignal-server</artifactId>
<version>0.45.0</version>
<version>0.51.1</version>
</dependency>
<dependency>
<groupId>org.signal.forks</groupId>
@@ -302,6 +296,12 @@
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>DynamoDBLocal</artifactId>
<version>${dynamodblocal.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</dependencyManagement>
@@ -383,7 +383,7 @@
<plugin>
<groupId>com.google.cloud.tools</groupId>
<artifactId>jib-maven-plugin</artifactId>
<version>3.4.0</version>
<version>3.4.3</version>
</plugin>
</plugins>
</pluginManagement>
@@ -424,7 +424,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.11.0</version>
<version>3.13.0</version>
<configuration>
<release>21</release>
</configuration>
@@ -433,7 +433,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.3.0</version>
<version>3.4.2</version>
<configuration>
<archive>
<manifest>
@@ -446,7 +446,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.3.0</version>
<version>3.7.1</version>
<executions>
<execution>
<id>copy</id>
@@ -466,7 +466,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.1.2</version>
<version>3.3.0</version>
<configuration>
<systemProperties>
<property>
@@ -480,7 +480,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.3.0</version>
<version>3.5.0</version>
<executions>
<execution>
<goals>
@@ -501,7 +501,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<version>3.1.1</version>
<version>3.1.2</version>
<configuration>
<skip>true</skip>
</configuration>
@@ -510,7 +510,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>3.1.1</version>
<version>3.1.2</version>
<configuration>
<skip>true</skip>
</configuration>
+1 -2
View File
@@ -91,8 +91,7 @@ currentReportingKey.secret: AAAAAAAAAAA=
currentReportingKey.salt: AAAAAAAAAAA=
turn.secret: AAAAAAAAAAA=
turn.cloudflare.username: ABCDEFGHIJKLM
turn.cloudflare.password: NOPQRSTUVWXYZ
turn.cloudflare.apiToken: ABCDEFGHIJKLM
linkDevice.secret: AAAAAAAAAAA=
+13 -4
View File
@@ -116,6 +116,8 @@ dynamoDbTables:
tableName: Example_Profiles
pushChallenge:
tableName: Example_PushChallenge
pushNotificationExperimentSamples:
tableName: Example_PushNotificationExperimentSamples
redeemedReceipts:
tableName: Example_RedeemedReceipts
expiration: P30D # Duration of time until rows expire
@@ -126,6 +128,9 @@ dynamoDbTables:
tableName: Example_RemoteConfig
reportMessage:
tableName: Example_ReportMessage
scheduledJobs:
tableName: Example_ScheduledJobs
expiration: P7D
subscriptions:
tableName: Example_Subscriptions
clientPublicKeys:
@@ -429,10 +434,15 @@ registrationService:
turn:
secret: secret://turn.secret
cloudflare:
username: secret://turn.cloudflare.username
password: secret://turn.cloudflare.password
apiToken: secret://turn.cloudflare.apiToken
endpoint: https://rtc.live.cloudflare.com/v1/turn/keys/LMNOP/credentials/generate
urls:
- turns:turn.cloudflare.example.com:443?transport=tcp
- turn:turn.example.com:80
urlsWithIps:
- turn:%s
- turn:%s:80?transport=tcp
- turns:%s:443?transport=tcp
ttl: 86400
hostname: turn.cloudflare.example.com
linkDevice:
@@ -468,7 +478,6 @@ noiseTunnel:
tlsKeyStoreEntryAlias: example.com
tlsKeyStorePassword: secret://noiseTunnel.tlsKeyStorePassword
noiseStaticPrivateKey: secret://noiseTunnel.noiseStaticPrivateKey
noiseRootPublicKeySignature: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
recognizedProxySecret: secret://noiseTunnel.recognizedProxySecret
externalRequestFilter:
+15 -8
View File
@@ -12,7 +12,7 @@
<properties>
<firebase-admin.version>9.2.0</firebase-admin.version>
<java-uuid-generator.version>4.3.0</java-uuid-generator.version>
<java-uuid-generator.version>5.1.0</java-uuid-generator.version>
<sqlite4java.version>1.0.392</sqlite4java.version>
</properties>
@@ -393,6 +393,14 @@
<artifactId>libphonenumber</artifactId>
</dependency>
<!-- Provides tools for mapping phone numbers to time zones, which is helpful for scheduling push notifications
during waking hours -->
<dependency>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>geocoder</artifactId>
<version>2.234</version>
</dependency>
<dependency>
<groupId>net.sourceforge.argparse4j</groupId>
<artifactId>argparse4j</artifactId>
@@ -463,7 +471,6 @@
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>DynamoDBLocal</artifactId>
<version>1.23.0</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -512,7 +519,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.5.1</version>
<version>3.6.0</version>
<configuration>
<createDependencyReducedPom>true</createDependencyReducedPom>
<filters>
@@ -547,7 +554,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.6.0</version>
<version>3.7.1</version>
<configuration>
<descriptors>
<descriptor>assembly.xml</descriptor>
@@ -567,7 +574,7 @@
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.2.0</version>
<version>1.2.1</version>
<executions>
<execution>
<id>read-deploy-configuration</id>
@@ -678,7 +685,7 @@
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>templating-maven-plugin</artifactId>
<version>1.0.0</version>
<version>3.0.0</version>
<executions>
<execution>
<id>filter-src</id>
@@ -692,7 +699,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.1.2</version>
<version>3.3.0</version>
<configuration>
<!-- work around PATCH not being a supported method on HttpUrlConnection -->
<argLine>--add-opens=java.base/java.net=ALL-UNNAMED</argLine>
@@ -714,7 +721,7 @@
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.1.0</version>
<version>3.3.0</version>
<executions>
<execution>
<id>check-all-service-config</id>
@@ -28,6 +28,11 @@ import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.binder.grpc.MetricCollectingServerInterceptor;
import io.micrometer.core.instrument.binder.jvm.ExecutorServiceMetrics;
import io.netty.channel.local.LocalAddress;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.resolver.ResolvedAddressTypes;
import io.netty.resolver.dns.DnsNameResolver;
import io.netty.resolver.dns.DnsNameResolverBuilder;
import java.io.FileInputStream;
import java.net.http.HttpClient;
import java.security.KeyStore;
@@ -73,6 +78,7 @@ import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
import org.whispersystems.textsecuregcm.auth.AccountAuthenticator;
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
import org.whispersystems.textsecuregcm.auth.CloudflareTurnCredentialsManager;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
@@ -183,7 +189,6 @@ import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
import org.whispersystems.textsecuregcm.push.FcmSender;
import org.whispersystems.textsecuregcm.push.MessageSender;
import org.whispersystems.textsecuregcm.push.ProvisioningManager;
import org.whispersystems.textsecuregcm.push.PushLatencyManager;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.ReceiptSender;
import org.whispersystems.textsecuregcm.redis.ConnectionEventLogger;
@@ -246,8 +251,12 @@ import org.whispersystems.textsecuregcm.workers.BackupMetricsCommand;
import org.whispersystems.textsecuregcm.workers.CertificateCommand;
import org.whispersystems.textsecuregcm.workers.CheckDynamicConfigurationCommand;
import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
import org.whispersystems.textsecuregcm.workers.DiscardPushNotificationExperimentSamplesCommand;
import org.whispersystems.textsecuregcm.workers.FinishPushNotificationExperimentCommand;
import org.whispersystems.textsecuregcm.workers.IdleDeviceNotificationSchedulerFactory;
import org.whispersystems.textsecuregcm.workers.MessagePersisterServiceCommand;
import org.whispersystems.textsecuregcm.workers.ProcessPushNotificationFeedbackCommand;
import org.whispersystems.textsecuregcm.workers.NotifyIdleDevicesWithoutMessagesExperimentFactory;
import org.whispersystems.textsecuregcm.workers.ProcessScheduledJobsServiceCommand;
import org.whispersystems.textsecuregcm.workers.RemoveExpiredAccountsCommand;
import org.whispersystems.textsecuregcm.workers.RemoveExpiredBackupsCommand;
import org.whispersystems.textsecuregcm.workers.RemoveExpiredLinkedDevicesCommand;
@@ -256,6 +265,7 @@ import org.whispersystems.textsecuregcm.workers.ScheduledApnPushNotificationSend
import org.whispersystems.textsecuregcm.workers.ServerVersionCommand;
import org.whispersystems.textsecuregcm.workers.SetRequestLoggingEnabledTask;
import org.whispersystems.textsecuregcm.workers.SetUserDiscoverabilityCommand;
import org.whispersystems.textsecuregcm.workers.StartPushNotificationExperimentCommand;
import org.whispersystems.textsecuregcm.workers.UnlinkDeviceCommand;
import org.whispersystems.textsecuregcm.workers.ZkParamsCommand;
import org.whispersystems.websocket.WebSocketResourceProviderFactory;
@@ -308,8 +318,25 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
bootstrap.addCommand(new RemoveExpiredUsernameHoldsCommand(Clock.systemUTC()));
bootstrap.addCommand(new RemoveExpiredBackupsCommand(Clock.systemUTC()));
bootstrap.addCommand(new BackupMetricsCommand(Clock.systemUTC()));
bootstrap.addCommand(new ProcessPushNotificationFeedbackCommand(Clock.systemUTC()));
bootstrap.addCommand(new RemoveExpiredLinkedDevicesCommand());
bootstrap.addCommand(new ProcessScheduledJobsServiceCommand("process-idle-device-notification-jobs",
"Processes scheduled jobs to send notifications to idle devices",
new IdleDeviceNotificationSchedulerFactory()));
bootstrap.addCommand(
new StartPushNotificationExperimentCommand<>("start-notify-idle-devices-without-messages-experiment",
"Start an experiment to send push notifications to idle devices with empty message queues",
new NotifyIdleDevicesWithoutMessagesExperimentFactory()));
bootstrap.addCommand(
new FinishPushNotificationExperimentCommand<>("finish-notify-idle-devices-without-messages-experiment",
"Finish an experiment to send push notifications to idle devices with empty message queues",
new NotifyIdleDevicesWithoutMessagesExperimentFactory()));
bootstrap.addCommand(
new DiscardPushNotificationExperimentSamplesCommand("discard-notify-idle-devices-without-messages-samples",
"Discard samples from the \"notify idle devices without messages\" experiment",
new NotifyIdleDevicesWithoutMessagesExperimentFactory()));
}
@Override
@@ -538,9 +565,24 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
.workQueue(new SynchronousQueue<>())
.keepAliveTime(io.dropwizard.util.Duration.seconds(60L))
.build();
ExecutorService cloudflareTurnHttpExecutor = environment.lifecycle()
.executorService(name(getClass(), "cloudflareTurn-%d"))
.maxThreads(2)
.minThreads(2)
.build();
ScheduledExecutorService subscriptionProcessorRetryExecutor = environment.lifecycle()
.scheduledExecutorService(name(getClass(), "subscriptionProcessorRetry-%d")).threads(1).build();
ScheduledExecutorService cloudflareTurnRetryExecutor = environment.lifecycle()
.scheduledExecutorService(name(getClass(), "cloudflareTurnRetry-%d")).threads(1).build();
final ManagedNioEventLoopGroup dnsResolutionEventLoopGroup = new ManagedNioEventLoopGroup();
final DnsNameResolver cloudflareDnsResolver = new DnsNameResolverBuilder(dnsResolutionEventLoopGroup.next())
.resolvedAddressTypes(ResolvedAddressTypes.IPV6_PREFERRED)
.completeOncePreferredResolved(false)
.channelType(NioDatagramChannel.class)
.socketChannelType(NioSocketChannel.class)
.build();
ExternalServiceCredentialsGenerator directoryV2CredentialsGenerator = DirectoryV2Controller.credentialsGenerator(
config.getDirectoryV2Configuration().getDirectoryV2ClientConfiguration());
@@ -576,7 +618,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
recurringJobExecutor,
config.getClientReleaseConfiguration().refreshInterval(),
Clock.systemUTC());
PushLatencyManager pushLatencyManager = new PushLatencyManager(metricsCluster, clientReleaseManager);
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster,
config.getReportMessageConfiguration().getCounterTtl());
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager,
@@ -596,8 +637,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
FcmSender fcmSender = new FcmSender(fcmSenderExecutor, config.getFcmConfiguration().credentials().value());
ApnPushNotificationScheduler apnPushNotificationScheduler = new ApnPushNotificationScheduler(pushSchedulerCluster,
apnSender, accountsManager, 0);
PushNotificationManager pushNotificationManager = new PushNotificationManager(accountsManager, apnSender, fcmSender,
apnPushNotificationScheduler, pushLatencyManager);
PushNotificationManager pushNotificationManager =
new PushNotificationManager(accountsManager, apnSender, fcmSender, apnPushNotificationScheduler);
RateLimiters rateLimiters = RateLimiters.createAndValidate(config.getLimitsConfiguration(),
dynamicConfigurationManager, rateLimitersCluster);
ProvisioningManager provisioningManager = new ProvisioningManager(
@@ -629,12 +670,24 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final AccountAuthenticator accountAuthenticator = new AccountAuthenticator(accountsManager);
final MessageSender messageSender = new MessageSender(clientPresenceManager, messagesManager,
pushNotificationManager,
pushLatencyManager);
final MessageSender messageSender =
new MessageSender(clientPresenceManager, messagesManager, pushNotificationManager);
final ReceiptSender receiptSender = new ReceiptSender(accountsManager, messageSender, receiptSenderExecutor);
final TurnTokenGenerator turnTokenGenerator = new TurnTokenGenerator(dynamicConfigurationManager,
config.getTurnConfiguration().secret().value(), config.getTurnConfiguration().cloudflare());
config.getTurnConfiguration().secret().value());
final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager = new CloudflareTurnCredentialsManager(
config.getTurnConfiguration().cloudflare().apiToken().value(),
config.getTurnConfiguration().cloudflare().endpoint(),
config.getTurnConfiguration().cloudflare().ttl(),
config.getTurnConfiguration().cloudflare().urls(),
config.getTurnConfiguration().cloudflare().urlsWithIps(),
config.getTurnConfiguration().cloudflare().hostname(),
config.getTurnConfiguration().cloudflare().circuitBreaker(),
cloudflareTurnHttpExecutor,
config.getTurnConfiguration().cloudflare().retry(),
cloudflareTurnRetryExecutor,
cloudflareDnsResolver
);
final CardinalityEstimator messageByteLimitCardinalityEstimator = new CardinalityEstimator(
rateLimitersCluster,
@@ -880,12 +933,12 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
clientConnectionManager,
clientPublicKeysManager,
config.getNoiseWebSocketTunnelConfiguration().noiseStaticKeyPair(),
config.getNoiseWebSocketTunnelConfiguration().noiseRootPublicKeySignature(),
authenticatedGrpcServerAddress,
anonymousGrpcServerAddress,
config.getNoiseWebSocketTunnelConfiguration().recognizedProxySecret().value());
environment.lifecycle().manage(localEventLoopGroup);
environment.lifecycle().manage(dnsResolutionEventLoopGroup);
environment.lifecycle().manage(anonymousGrpcServer);
environment.lifecycle().manage(authenticatedGrpcServer);
environment.lifecycle().manage(noiseWebSocketEventLoopGroup);
@@ -1017,7 +1070,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new AttachmentControllerV4(rateLimiters, gcsAttachmentGenerator, tusAttachmentGenerator,
experimentEnrollmentManager),
new ArchiveController(backupAuthManager, backupManager),
new CallRoutingController(rateLimiters, callRouter, turnTokenGenerator, experimentEnrollmentManager),
new CallRoutingController(rateLimiters, callRouter, turnTokenGenerator, experimentEnrollmentManager, cloudflareTurnCredentialsManager),
new CallLinkController(rateLimiters, callingGenericZkSecretParams),
new CertificateController(new CertificateGenerator(config.getDeliveryCertificate().certificate().value(),
config.getDeliveryCertificate().ecPrivateKey(), config.getDeliveryCertificate().expiresDays()),
@@ -108,9 +108,10 @@ public class AccountAuthenticator implements Authenticator<BasicCredentials, Aut
SaltedTokenHash.generateFor(basicCredentials.getPassword())); // new credentials have current version
}
return Optional.of(new AuthenticatedAccount(authenticatedAccount, device.get()));
} else {
failureReason = "incorrectPassword";
return Optional.empty();
}
return Optional.empty();
} catch (IllegalArgumentException | InvalidAuthorizationHeaderException iae) {
failureReason = "invalidHeader";
return Optional.empty();
@@ -16,5 +16,5 @@ import java.lang.annotation.Target;
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ChangesDeviceEnabledState {
public @interface ChangesLinkedDevices {
}
@@ -0,0 +1,116 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.auth;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.netty.resolver.dns.DnsNameResolver;
import java.io.IOException;
import java.net.Inet6Address;
import java.net.URI;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import javax.ws.rs.core.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.SystemMapper;
public class CloudflareTurnCredentialsManager {
private static final Logger logger = LoggerFactory.getLogger(CloudflareTurnCredentialsManager.class);
private final List<String> cloudflareTurnUrls;
private final List<String> cloudflareTurnUrlsWithIps;
private final String cloudflareTurnHostname;
private final HttpRequest request;
private final FaultTolerantHttpClient cloudflareTurnClient;
private final DnsNameResolver dnsNameResolver;
record CredentialRequest(long ttl) {}
record CloudflareTurnResponse(IceServer iceServers) {
record IceServer(
String username,
String credential,
List<String> urls) {
}
}
public CloudflareTurnCredentialsManager(final String cloudflareTurnApiToken,
final String cloudflareTurnEndpoint, final long cloudflareTurnTtl, final List<String> cloudflareTurnUrls,
final List<String> cloudflareTurnUrlsWithIps, final String cloudflareTurnHostname,
final CircuitBreakerConfiguration circuitBreaker, final ExecutorService executor, final RetryConfiguration retry,
final ScheduledExecutorService retryExecutor, final DnsNameResolver dnsNameResolver) {
this.cloudflareTurnClient = FaultTolerantHttpClient.newBuilder()
.withName("cloudflare-turn")
.withCircuitBreaker(circuitBreaker)
.withExecutor(executor)
.withRetry(retry)
.withRetryExecutor(retryExecutor)
.build();
this.cloudflareTurnUrls = cloudflareTurnUrls;
this.cloudflareTurnUrlsWithIps = cloudflareTurnUrlsWithIps;
this.cloudflareTurnHostname = cloudflareTurnHostname;
this.dnsNameResolver = dnsNameResolver;
try {
final String body = SystemMapper.jsonMapper().writeValueAsString(new CredentialRequest(cloudflareTurnTtl));
this.request = HttpRequest.newBuilder()
.uri(URI.create(cloudflareTurnEndpoint))
.header("Content-Type", "application/json")
.header("Authorization", String.format("Bearer %s", cloudflareTurnApiToken))
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
} catch (JsonProcessingException e) {
throw new IllegalArgumentException(e);
}
}
public TurnToken retrieveFromCloudflare() throws IOException {
final List<String> cloudflareTurnComposedUrls;
try {
cloudflareTurnComposedUrls = dnsNameResolver.resolveAll(cloudflareTurnHostname).get().stream()
.map(i -> switch (i) {
case Inet6Address i6 -> "[" + i6.getHostAddress() + "]";
default -> i.getHostAddress();
})
.flatMap(i -> cloudflareTurnUrlsWithIps.stream().map(u -> u.formatted(i)))
.toList();
} catch (Exception e) {
throw new IOException(e);
}
final HttpResponse<String> response;
try {
response = cloudflareTurnClient.sendAsync(request, HttpResponse.BodyHandlers.ofString()).join();
} catch (CompletionException e) {
logger.warn("failed to make http request to Cloudflare Turn: {}", e.getMessage());
throw new IOException(ExceptionUtils.unwrap(e));
}
if (response.statusCode() != Response.Status.CREATED.getStatusCode()) {
logger.warn("failure request credentials from Cloudflare Turn (code={}): {}", response.statusCode(), response);
throw new IOException("Cloudflare Turn http failure : " + response.statusCode());
}
final CloudflareTurnResponse cloudflareTurnResponse = SystemMapper.jsonMapper()
.readValue(response.body(), CloudflareTurnResponse.class);
return new TurnToken(cloudflareTurnResponse.iceServers().username(),
cloudflareTurnResponse.iceServers().credential(),
cloudflareTurnUrls, cloudflareTurnComposedUrls, cloudflareTurnHostname);
}
}
@@ -11,26 +11,23 @@ import org.whispersystems.textsecuregcm.storage.Device;
import javax.ws.rs.core.SecurityContext;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
class ContainerRequestUtil {
private static Map<Byte, Boolean> buildDevicesEnabledMap(final Account account) {
return account.getDevices().stream().collect(Collectors.toMap(Device::getId, Device::isEnabled));
}
/**
* A read-only subset of the authenticated Account object, to enforce that filter-based consumers do not perform
* account modifying operations.
*/
record AccountInfo(UUID accountId, String e164, Map<Byte, Boolean> devicesEnabled) {
record AccountInfo(UUID accountId, String e164, Set<Byte> deviceIds) {
static AccountInfo fromAccount(final Account account) {
return new AccountInfo(
account.getUuid(),
account.getNumber(),
buildDevicesEnabledMap(account));
account.getDevices().stream().map(Device::getId).collect(Collectors.toSet()));
}
}
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.auth;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
@@ -18,76 +17,73 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.util.Pair;
/**
* This {@link WebsocketRefreshRequirementProvider} observes intra-request changes in {@link Account#isEnabled()} and
* {@link Device#isEnabled()}.
* <p>
* If a change in {@link Account#isEnabled()} or any associated {@link Device#isEnabled()} is observed, then any active
* WebSocket connections for the account must be closed in order for clients to get a refreshed
* This {@link WebsocketRefreshRequirementProvider} observes intra-request changes in devices linked to an
* {@link Account} and triggers a WebSocket refresh if that set changes. If a change in linked devices is observed, then
* any active WebSocket connections for the account must be closed in order for clients to get a refreshed
* {@link io.dropwizard.auth.Auth} object with a current device list.
*
* @see AuthenticatedAccount
*/
public class AuthEnablementRefreshRequirementProvider implements WebsocketRefreshRequirementProvider {
public class LinkedDeviceRefreshRequirementProvider implements WebsocketRefreshRequirementProvider {
private final AccountsManager accountsManager;
private static final Logger logger = LoggerFactory.getLogger(AuthEnablementRefreshRequirementProvider.class);
private static final Logger logger = LoggerFactory.getLogger(LinkedDeviceRefreshRequirementProvider.class);
private static final String ACCOUNT_UUID = AuthEnablementRefreshRequirementProvider.class.getName() + ".accountUuid";
private static final String DEVICES_ENABLED = AuthEnablementRefreshRequirementProvider.class.getName() + ".devicesEnabled";
private static final String ACCOUNT_UUID = LinkedDeviceRefreshRequirementProvider.class.getName() + ".accountUuid";
private static final String LINKED_DEVICE_IDS = LinkedDeviceRefreshRequirementProvider.class.getName() + ".deviceIds";
public AuthEnablementRefreshRequirementProvider(final AccountsManager accountsManager) {
public LinkedDeviceRefreshRequirementProvider(final AccountsManager accountsManager) {
this.accountsManager = accountsManager;
}
@Override
public void handleRequestFiltered(final RequestEvent requestEvent) {
if (requestEvent.getUriInfo().getMatchedResourceMethod().getInvocable().getHandlingMethod().getAnnotation(ChangesDeviceEnabledState.class) != null) {
// The authenticated principal, if any, will be available after filters have run.
// Now that the account is known, capture a snapshot of `isEnabled` for the account's devices before carrying out
// the request’s business logic.
ContainerRequestUtil.getAuthenticatedAccount(requestEvent.getContainerRequest()).ifPresent(account ->
setAccount(requestEvent.getContainerRequest(), account));
if (requestEvent.getUriInfo().getMatchedResourceMethod().getInvocable().getHandlingMethod().getAnnotation(
ChangesLinkedDevices.class) != null) {
// The authenticated principal, if any, will be available after filters have run. Now that the account is known,
// capture a snapshot of the account's linked devices before carrying out the request’s business logic.
ContainerRequestUtil.getAuthenticatedAccount(requestEvent.getContainerRequest())
.ifPresent(account -> setAccount(requestEvent.getContainerRequest(), account));
}
}
public static void setAccount(final ContainerRequest containerRequest, final Account account) {
setAccount(containerRequest, ContainerRequestUtil.AccountInfo.fromAccount(account));
}
private static void setAccount(final ContainerRequest containerRequest, final ContainerRequestUtil.AccountInfo info) {
containerRequest.setProperty(ACCOUNT_UUID, info.accountId());
containerRequest.setProperty(DEVICES_ENABLED, info.devicesEnabled());
containerRequest.setProperty(LINKED_DEVICE_IDS, info.deviceIds());
}
@Override
public List<Pair<UUID, Byte>> handleRequestFinished(final RequestEvent requestEvent) {
// Now that the request is finished, check whether `isEnabled` changed for any of the devices. If the value did
// change or if a devices was added or removed, all devices must disconnect and reauthenticate.
if (requestEvent.getContainerRequest().getProperty(DEVICES_ENABLED) != null) {
// Now that the request is finished, check whether the set of linked devices has changed. If the value did change or
// if a devices was added or removed, all devices must disconnect and reauthenticate.
if (requestEvent.getContainerRequest().getProperty(LINKED_DEVICE_IDS) != null) {
@SuppressWarnings("unchecked") final Map<Byte, Boolean> initialDevicesEnabled =
(Map<Byte, Boolean>) requestEvent.getContainerRequest().getProperty(DEVICES_ENABLED);
@SuppressWarnings("unchecked") final Set<Byte> initialLinkedDeviceIds =
(Set<Byte>) requestEvent.getContainerRequest().getProperty(LINKED_DEVICE_IDS);
return accountsManager.getByAccountIdentifier((UUID) requestEvent.getContainerRequest().getProperty(ACCOUNT_UUID))
.map(ContainerRequestUtil.AccountInfo::fromAccount)
.map(account -> {
.map(accountInfo -> {
final Set<Byte> deviceIdsToDisplace;
final Map<Byte, Boolean> currentDevicesEnabled = account.devicesEnabled();
final Set<Byte> currentLinkedDeviceIds = accountInfo.deviceIds();
if (!initialDevicesEnabled.equals(currentDevicesEnabled)) {
deviceIdsToDisplace = new HashSet<>(initialDevicesEnabled.keySet());
deviceIdsToDisplace.addAll(currentDevicesEnabled.keySet());
if (!initialLinkedDeviceIds.equals(currentLinkedDeviceIds)) {
deviceIdsToDisplace = new HashSet<>(initialLinkedDeviceIds);
deviceIdsToDisplace.addAll(currentLinkedDeviceIds);
} else {
deviceIdsToDisplace = Collections.emptySet();
}
return deviceIdsToDisplace.stream()
.map(deviceId -> new Pair<>(account.accountId(), deviceId))
.map(deviceId -> new Pair<>(accountInfo.accountId(), deviceId))
.collect(Collectors.toList());
}).orElseGet(() -> {
logger.error("Request had account, but it is no longer present");
@@ -18,6 +18,8 @@ import java.util.Optional;
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public class OptionalAccess {
public static String ALL_DEVICES_SELECTOR = "*";
public static void verify(Optional<Account> requestAccount,
Optional<Anonymous> accessKey,
Optional<Account> targetAccount,
@@ -26,12 +28,12 @@ public class OptionalAccess {
try {
verify(requestAccount, accessKey, targetAccount);
if (!deviceSelector.equals("*")) {
if (!ALL_DEVICES_SELECTOR.equals(deviceSelector)) {
byte deviceId = Byte.parseByte(deviceSelector);
Optional<Device> targetDevice = targetAccount.get().getDevice(deviceId);
if (targetDevice.isPresent() && targetDevice.get().isEnabled()) {
if (targetDevice.isPresent()) {
return;
}
@@ -48,11 +50,10 @@ public class OptionalAccess {
public static void verify(Optional<Account> requestAccount,
Optional<Anonymous> accessKey,
Optional<Account> targetAccount)
{
Optional<Account> targetAccount) {
if (requestAccount.isPresent()) {
// Authenticated requests are never unauthorized; if the target exists and is enabled, return OK, otherwise throw not-found.
if (targetAccount.isPresent() && targetAccount.get().isEnabled()) {
// Authenticated requests are never unauthorized; if the target exists, return OK, otherwise throw not-found.
if (targetAccount.isPresent()) {
return;
} else {
throw new NotFoundException();
@@ -63,7 +64,7 @@ public class OptionalAccess {
// has unrestricted unidentified access, callers need to supply a fake access key. Likewise, if
// the target account does not exist, we *also* report unauthorized here (*not* not-found,
// since that would provide a free exists check).
if (accessKey.isEmpty() || !targetAccount.map(Account::isEnabled).orElse(false)) {
if (accessKey.isEmpty() || targetAccount.isEmpty()) {
throw new NotAuthorizedException(Response.Status.UNAUTHORIZED);
}
@@ -80,9 +80,4 @@ public class StoredRegistrationLock {
return false;
}
}
@VisibleForTesting
public StoredRegistrationLock forTime(long timestamp) {
return new StoredRegistrationLock(registrationLock, registrationLockSalt, Instant.ofEpochMilli(timestamp));
}
}
@@ -17,7 +17,6 @@ import java.util.UUID;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.whispersystems.textsecuregcm.calls.routing.TurnServerOptions;
import org.whispersystems.textsecuregcm.configuration.CloudflareTurnConfiguration;
import org.whispersystems.textsecuregcm.configuration.TurnUriConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicTurnConfiguration;
@@ -38,21 +37,10 @@ public class TurnTokenGenerator {
private static final String WithIpsProtocol = "01";
private final String cloudflareTurnUsername;
private final String cloudflareTurnPassword;
private final List<String> cloudflareTurnUrls;
private final String cloudflareTurnHostname;
public TurnTokenGenerator(final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final byte[] turnSecret, final CloudflareTurnConfiguration cloudflareTurnConfiguration) {
final byte[] turnSecret) {
this.dynamicConfigurationManager = dynamicConfigurationManager;
this.turnSecret = turnSecret;
this.cloudflareTurnUsername = cloudflareTurnConfiguration.username().value();
this.cloudflareTurnPassword = cloudflareTurnConfiguration.password().value();
this.cloudflareTurnUrls = cloudflareTurnConfiguration.urls();
this.cloudflareTurnHostname = cloudflareTurnConfiguration.hostname();
}
@Deprecated
@@ -64,10 +52,6 @@ public class TurnTokenGenerator {
return generateToken(options.hostname(), options.urlsWithIps(), options.urlsWithHostname());
}
public TurnToken generateForCloudflareBeta() {
return new TurnToken(cloudflareTurnUsername, cloudflareTurnPassword, cloudflareTurnUrls, null, cloudflareTurnHostname);
}
private TurnToken generateToken(String hostname, List<String> urlsWithIps, List<String> urlsWithHostname) {
try {
final Mac mac = Mac.getInstance(ALGORITHM);
@@ -23,7 +23,7 @@ public class WebsocketRefreshApplicationEventListener implements ApplicationEven
final ClientPresenceManager clientPresenceManager) {
this.websocketRefreshRequestEventListener = new WebsocketRefreshRequestEventListener(clientPresenceManager,
new AuthEnablementRefreshRequirementProvider(accountsManager),
new LinkedDeviceRefreshRequirementProvider(accountsManager),
new PhoneNumberChangeRefreshRequirementProvider(accountsManager));
}
@@ -15,6 +15,7 @@ import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
@@ -28,12 +29,12 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
import org.whispersystems.textsecuregcm.util.Util;
import javax.annotation.Nullable;
/**
* Issues ZK backup auth credentials for authenticated accounts
@@ -101,8 +102,9 @@ public class BackupAuthManager {
return CompletableFuture.completedFuture(null);
}
return rateLimiters.forDescriptor(RateLimiters.For.SET_BACKUP_ID)
.validateAsync(account.getUuid())
return RateLimiter.adaptLegacyException(rateLimiters
.forDescriptor(RateLimiters.For.SET_BACKUP_ID)
.validateAsync(account.getUuid()))
.thenCompose(ignored -> this.accountsManager
.updateAsync(account, acc -> acc.setBackupCredentialRequest(serializedRequest))
.thenRun(Util.NOOP))
@@ -14,13 +14,14 @@ import java.security.SecureRandom;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
@@ -32,7 +33,6 @@ import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
@@ -56,6 +56,9 @@ public class BackupManager {
// How many cdn object deletion requests can be outstanding at a time per backup deletion operation
private static final int DELETION_CONCURRENCY = 10;
// How many cdn object copy requests can be outstanding at a time per batch copy-to-backup operation
private static final int COPY_CONCURRENCY = 10;
private static final String ZK_AUTHN_COUNTER_NAME = MetricsUtil.name(BackupManager.class, "authentication");
private static final String ZK_AUTHZ_FAILURE_COUNTER_NAME = MetricsUtil.name(BackupManager.class,
@@ -148,7 +151,7 @@ public class BackupManager {
.thenApply(result -> cdn3BackupCredentialGenerator.generateUpload(cdnMessageBackupName(backupUser)));
}
public CompletionStage<BackupUploadDescriptor> createTemporaryAttachmentUploadDescriptor(
public CompletableFuture<BackupUploadDescriptor> createTemporaryAttachmentUploadDescriptor(
final AuthenticatedBackupUser backupUser) {
checkBackupLevel(backupUser, BackupLevel.MEDIA);
@@ -160,7 +163,7 @@ public class BackupManager {
final String attachmentKey = Base64.getUrlEncoder().encodeToString(bytes);
final AttachmentGenerator.Descriptor descriptor = tusAttachmentGenerator.generateAttachment(attachmentKey);
return new BackupUploadDescriptor(3, attachmentKey, descriptor.headers(), descriptor.signedUploadLocation());
});
}).toCompletableFuture();
}
/**
@@ -195,19 +198,96 @@ public class BackupManager {
}
/**
* Check if there is enough capacity to store the requested amount of media
* Copy an encrypted object to the backup cdn, adding a layer of encryption
* <p>
* Implementation notes: <p> This method guarantees that any object that gets successfully copied to the backup cdn
* will also be deducted from the user's quota. </p>
* <p>
* However, the converse isn't true. It's possible we may charge the user for media they failed to copy. As a result,
* the quota may be over reported. It should be recalculated before taking quota enforcement actions.
*
* @param backupUser an already ZK authenticated backup user
* @param mediaLength the desired number of media bytes to store
* @return true if mediaLength bytes can be stored
* @return A Flux that emits the locations of the double-encrypted objects on the backup cdn, or includes an error
* detailing why the object could not be copied.
*/
public CompletableFuture<Boolean> canStoreMedia(final AuthenticatedBackupUser backupUser, final long mediaLength) {
public Flux<CopyResult> copyToBackup(final AuthenticatedBackupUser backupUser, List<CopyParameters> toCopy) {
checkBackupLevel(backupUser, BackupLevel.MEDIA);
return Mono
// Figure out how many objects we're allowed to copy, updating the quota usage for the amount we are allowed
.fromFuture(enforceQuota(backupUser, toCopy))
// Copy the ones we have enough quota to hold
.flatMapMany(quotaResult -> Flux.concat(
// These fit in our remaining quota, so perform the copy. If the copy fails, our estimated quota usage may not
// be exact since we already updated our usage. We make a best-effort attempt to undo the usage update if we
// know that the copied failed for sure though.
Flux.fromIterable(quotaResult.requestsToCopy()).flatMapSequential(
copyParams -> copyToBackup(backupUser, copyParams)
.flatMap(copyResult -> switch (copyResult.outcome()) {
case SUCCESS -> Mono.just(copyResult);
case SOURCE_WRONG_LENGTH, SOURCE_NOT_FOUND, OUT_OF_QUOTA -> Mono
.fromFuture(this.backupsDb.trackMedia(backupUser, -1, -copyParams.destinationObjectSize()))
.thenReturn(copyResult);
}),
COPY_CONCURRENCY),
// There wasn't enough quota remaining to perform these copies
Flux.fromIterable(quotaResult.requestsToReject())
.map(arg -> new CopyResult(CopyResult.Outcome.OUT_OF_QUOTA, arg.destinationMediaId(), null))));
}
private Mono<CopyResult> copyToBackup(final AuthenticatedBackupUser backupUser, final CopyParameters copyParameters) {
return Mono.fromCompletionStage(() -> remoteStorageManager.copy(
copyParameters.sourceCdn(), copyParameters.sourceKey(), copyParameters.sourceLength(),
copyParameters.encryptionParameters(),
cdnMediaPath(backupUser, copyParameters.destinationMediaId())))
// Successfully copied!
.thenReturn(new CopyResult(
CopyResult.Outcome.SUCCESS, copyParameters.destinationMediaId(), remoteStorageManager.cdnNumber()))
// Otherwise, squash per-item copy errors that don't fail the entire operation
.onErrorResume(
// If the error maps to an explicit result type
throwable ->
CopyResult.fromCopyError(throwable, copyParameters.destinationMediaId()).isPresent(),
// return that result type instead of propagating the error
throwable ->
Mono.just(CopyResult.fromCopyError(throwable, copyParameters.destinationMediaId()).orElseThrow()));
}
private record QuotaResult(List<CopyParameters> requestsToCopy, List<CopyParameters> requestsToReject) {}
/**
* Determine which copy requests can be performed with the user's remaining quota and update the used quota. If a copy
* request subsequently fails, the caller should attempt to restore the quota for the failed copy.
*
* @param backupUser The user quota to update
* @param toCopy The proposed copy requests
* @return QuotaResult indicating which requests fit into the remaining quota and which requests should be rejected
* with {@link CopyResult.Outcome#OUT_OF_QUOTA}
*/
private CompletableFuture<QuotaResult> enforceQuota(
final AuthenticatedBackupUser backupUser,
final List<CopyParameters> toCopy) {
final long totalBytesAdded = toCopy.stream()
.mapToLong(copyParameters -> {
if (copyParameters.sourceLength() > MAX_MEDIA_OBJECT_SIZE) {
throw Status.INVALID_ARGUMENT
.withDescription("Invalid sourceObject size")
.asRuntimeException();
}
return copyParameters.destinationObjectSize();
})
.sum();
return backupsDb.getMediaUsage(backupUser)
.thenComposeAsync(info -> {
final boolean canStore = MAX_TOTAL_BACKUP_MEDIA_BYTES - info.usageInfo().bytesUsed() >= mediaLength;
long remainingQuota = MAX_TOTAL_BACKUP_MEDIA_BYTES - info.usageInfo().bytesUsed();
final boolean canStore = remainingQuota >= totalBytesAdded;
if (canStore || info.lastRecalculationTime().isAfter(clock.instant().minus(MAX_QUOTA_STALENESS))) {
return CompletableFuture.completedFuture(canStore);
return CompletableFuture.completedFuture(remainingQuota);
}
// The user is out of quota, and we have not recently recalculated the user's usage. Double check by doing a
@@ -221,69 +301,46 @@ public class BackupManager {
Metrics.counter(USAGE_RECALCULATION_COUNTER_NAME, "usageChanged", String.valueOf(usageChanged))
.increment();
})
.thenApply(newUsage -> MAX_TOTAL_BACKUP_MEDIA_BYTES - newUsage.bytesUsed() >= mediaLength);
.thenApply(newUsage -> MAX_TOTAL_BACKUP_MEDIA_BYTES - newUsage.bytesUsed());
})
.thenCompose(remainingQuota -> {
// Figure out how many of the requested objects fit in the remaining quota
final int index = indexWhereTotalExceeds(toCopy, CopyParameters::destinationObjectSize,
remainingQuota);
final QuotaResult result = new QuotaResult(toCopy.subList(0, index),
toCopy.subList(index, toCopy.size()));
if (index == 0) {
// Skip the usage update if we're not able to write anything
return CompletableFuture.completedFuture(result);
}
// Update the usage
final long quotaToConsume = result.requestsToCopy.stream()
.mapToLong(CopyParameters::destinationObjectSize)
.sum();
return backupsDb.trackMedia(backupUser, index, quotaToConsume).thenApply(ignored -> result);
});
}
/**
* @return the largest index i such that sum(ts[0],...ts[i - 1]) <= max
*/
private static <T> int indexWhereTotalExceeds(List<T> ts, Function<T, Long> valueFunction, long max) {
long sum = 0;
for (int index = 0; index < ts.size(); index++) {
sum += valueFunction.apply(ts.get(index));
if (sum > max) {
return index;
}
}
return ts.size();
}
public record StorageDescriptor(int cdn, byte[] key) {}
public record StorageDescriptorWithLength(int cdn, byte[] key, long length) {}
/**
* Copy an encrypted object to the backup cdn, adding a layer of encryption
* <p>
* Implementation notes: <p> This method guarantees that any object that gets successfully copied to the backup cdn
* will also be deducted from the user's quota. </p>
* <p>
* However, the converse isn't true. It's possible we may charge the user for media they failed to copy. As a result,
* the quota may be over reported and it should be recalculated before taking quota enforcement actions.
*
* @return A stage that completes successfully with location of the twice-encrypted object on the backup cdn. The
* returned CompletionStage can be completed exceptionally with the following exceptions.
* <ul>
* <li> {@link InvalidLengthException} If the expectedSourceLength does not match the length of the sourceUri </li>
* <li> {@link SourceObjectNotFoundException} If the no object at sourceUri is found </li>
* <li> {@link java.io.IOException} If there was a generic IO issue </li>
* </ul>
*/
public CompletableFuture<StorageDescriptor> copyToBackup(
final AuthenticatedBackupUser backupUser,
final int sourceCdn,
final String sourceKey,
final int sourceLength,
final MediaEncryptionParameters encryptionParameters,
final byte[] destinationMediaId) {
checkBackupLevel(backupUser, BackupLevel.MEDIA);
if (sourceLength > MAX_MEDIA_OBJECT_SIZE) {
throw Status.INVALID_ARGUMENT
.withDescription("Invalid sourceObject size")
.asRuntimeException();
}
final String destination = cdnMediaPath(backupUser, destinationMediaId);
final int destinationLength = encryptionParameters.outputSize(sourceLength);
return this.backupsDb
// Write the ddb updates before actually updating backing storage
.trackMedia(backupUser, 1, destinationLength)
// Actually copy the objects. If the copy fails, our estimated quota usage may not be exact
.thenComposeAsync(ignored ->
remoteStorageManager.copy(sourceCdn, sourceKey, sourceLength, encryptionParameters, destination))
.exceptionallyCompose(throwable -> {
final Throwable unwrapped = ExceptionUtils.unwrap(throwable);
if (!(unwrapped instanceof SourceObjectNotFoundException) && !(unwrapped instanceof InvalidLengthException)) {
throw ExceptionUtils.wrap(unwrapped);
}
// In cases where we know the copy fails without writing anything, we can try to restore the user's quota
return this.backupsDb.trackMedia(backupUser, -1, -destinationLength).whenComplete((ignored, ignoredEx) -> {
throw ExceptionUtils.wrap(unwrapped);
});
})
// indicates where the backup was stored
.thenApply(ignore -> new StorageDescriptor(remoteStorageManager.cdnNumber(), destinationMediaId));
}
/**
* Generate credentials that can be used to read from the backup CDN
*
@@ -348,66 +405,60 @@ public class BackupManager {
deletePrefix(backupUser.backupDir(), DELETION_CONCURRENCY))));
}
private sealed interface Either permits DeleteSuccess, DeleteFailure {}
private record DeleteSuccess(long usage) implements Either {}
private record DeleteFailure(Throwable e) implements Either {}
public CompletableFuture<Void> delete(final AuthenticatedBackupUser backupUser,
public Flux<StorageDescriptor> deleteMedia(final AuthenticatedBackupUser backupUser,
final List<StorageDescriptor> storageDescriptors) {
checkBackupLevel(backupUser, BackupLevel.MESSAGES);
// Check for a cdn we don't know how to process
if (storageDescriptors.stream().anyMatch(sd -> sd.cdn() != remoteStorageManager.cdnNumber())) {
throw Status.INVALID_ARGUMENT
.withDescription("unsupported media cdn provided")
.asRuntimeException();
}
return Flux
.fromIterable(storageDescriptors)
return Flux.usingWhen(
// Issue deletes for all storage descriptors (proceeds with default flux concurrency)
.flatMap(descriptor -> Mono.fromCompletionStage(
remoteStorageManager
.delete(cdnMediaPath(backupUser, descriptor.key))
// Squash errors/success into a single type
.handle((bytesDeleted, throwable) -> throwable != null
? new DeleteFailure(throwable)
: new DeleteSuccess(bytesDeleted))
))
// Gather usage updates into the UsageBatcher to apply during the cleanup operation
Mono.just(new UsageBatcher()),
// Update backupsDb with the change in usage
.collectList()
.<Void>flatMap(eithers -> {
// count up usage changes
long totalBytesDeleted = 0;
long totalCountDeleted = 0;
final List<Throwable> toThrow = new ArrayList<>();
for (Either either : eithers) {
switch (either) {
case DeleteFailure f:
toThrow.add(f.e());
break;
case DeleteSuccess s when s.usage() > 0:
totalBytesDeleted += s.usage();
totalCountDeleted++;
break;
default:
break;
}
}
final Mono<Void> result = toThrow.isEmpty()
? Mono.empty()
: Mono.error(toThrow.stream().reduce((t1, t2) -> {
t1.addSuppressed(t2);
return t1;
}).get());
return Mono
.fromCompletionStage(this.backupsDb.trackMedia(backupUser, -totalCountDeleted, -totalBytesDeleted))
.then(result);
})
.toFuture();
// Deletes the objects, returning their former location. Tracks bytes removed so the quota can be updated on
// completion
batcher -> Flux.fromIterable(storageDescriptors)
.flatMapSequential(sd -> Mono
// Delete the object
.fromCompletionStage(remoteStorageManager.delete(cdnMediaPath(backupUser, sd.key())))
// Track how much the remote storage manager indicated was deleted as part of the operation
.doOnNext(deletedBytes -> batcher.update(-deletedBytes))
.thenReturn(sd), DELETION_CONCURRENCY),
// On cleanup, update the quota using whatever updates were accumulated in the batcher
batcher ->
Mono.fromFuture(backupsDb.trackMedia(backupUser, batcher.countDelta.get(), batcher.usageDelta.get())));
}
/**
* Track pending media usage updates
*/
private static class UsageBatcher {
AtomicLong countDelta = new AtomicLong();
AtomicLong usageDelta = new AtomicLong();
/**
* Stage a usage update that will be applied later
*
* @param bytesDelta The amount of bytes that should be tracked as used (or if negative, freed). If the delta is
* non-zero, the count will also be updated.
*/
void update(long bytesDelta) {
if (bytesDelta < 0) {
countDelta.decrementAndGet();
} else if (bytesDelta > 0) {
countDelta.incrementAndGet();
}
usageDelta.addAndGet(bytesDelta);
}
}
private static final ECPublicKey INVALID_PUBLIC_KEY = Curve.generateKeyPair().getPublicKey();
@@ -0,0 +1,29 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.backup;
/**
* Descriptor for a single copy-and-encrypt operation
*
* @param sourceCdn The cdn of the object to copy
* @param sourceKey The mediaId within the cdn of the object to copy
* @param sourceLength The length of the object to copy
* @param encryptionParameters Encryption parameters to double encrypt the object
* @param destinationMediaId The mediaId of the destination object
*/
public record CopyParameters(
int sourceCdn,
String sourceKey,
int sourceLength,
MediaEncryptionParameters encryptionParameters,
byte[] destinationMediaId) {
/**
* @return The size of the double-encrypted destination object after it is copied
*/
long destinationObjectSize() {
return encryptionParameters().outputSize(sourceLength());
}
}
@@ -0,0 +1,46 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.backup;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import javax.annotation.Nullable;
import java.util.Optional;
/**
* The result of a copy operation
*
* @param outcome Whether the copy was a success
* @param mediaId The destination mediaId
* @param cdn On success, the destination cdn
*/
public record CopyResult(Outcome outcome, byte[] mediaId, @Nullable Integer cdn) {
public enum Outcome {
SUCCESS,
SOURCE_NOT_FOUND,
SOURCE_WRONG_LENGTH,
OUT_OF_QUOTA
}
/**
* Map an exception returned by {@link RemoteStorageManager#copy} to CopyResult with the appropriate outcome.
*
* @param throwable result of a failed copy operation
* @param key the copy destination mediaId
* @return The appropriate CopyResult, or empty if the exception does not match to an Outcome.
*/
static Optional<CopyResult> fromCopyError(final Throwable throwable, final byte[] key) {
final Throwable unwrapped = ExceptionUtils.unwrap(throwable);
if (unwrapped instanceof SourceObjectNotFoundException) {
return Optional.of(new CopyResult(Outcome.SOURCE_NOT_FOUND, key, null));
} else if (unwrapped instanceof InvalidLengthException) {
return Optional.of(new CopyResult(Outcome.SOURCE_WRONG_LENGTH, key, null));
} else {
return Optional.empty();
}
}
}
@@ -11,7 +11,25 @@ import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
public record CloudflareTurnConfiguration(@NotNull SecretString username, @NotNull SecretString password,
@Valid @NotNull List<@NotBlank String> urls, @NotBlank String hostname) {
public record CloudflareTurnConfiguration(@NotNull SecretString apiToken,
@NotBlank String endpoint,
@NotBlank long ttl,
@NotBlank List<String> urls,
@NotBlank List<String> urlsWithIps,
@NotNull @Valid CircuitBreakerConfiguration circuitBreaker,
@NotNull @Valid RetryConfiguration retry,
@NotBlank String hostname) {
public CloudflareTurnConfiguration {
if (circuitBreaker == null) {
// It’s a little counter-intuitive, but this compact constructor allows a default value
// to be used when one isn’t specified (e.g. in YAML), allowing the field to still be
// validated as @NotNull
circuitBreaker = new CircuitBreakerConfiguration();
}
if (retry == null) {
retry = new RetryConfiguration();
}
}
}
@@ -63,10 +63,12 @@ public class DynamoDbTables {
private final Table phoneNumberIdentifiers;
private final Table profiles;
private final Table pushChallenge;
private final Table pushNotificationExperimentSamples;
private final TableWithExpiration redeemedReceipts;
private final TableWithExpiration registrationRecovery;
private final Table remoteConfig;
private final Table reportMessage;
private final TableWithExpiration scheduledJobs;
private final Table subscriptions;
private final Table verificationSessions;
@@ -87,10 +89,12 @@ public class DynamoDbTables {
@JsonProperty("phoneNumberIdentifiers") final Table phoneNumberIdentifiers,
@JsonProperty("profiles") final Table profiles,
@JsonProperty("pushChallenge") final Table pushChallenge,
@JsonProperty("pushNotificationExperimentSamples") final Table pushNotificationExperimentSamples,
@JsonProperty("redeemedReceipts") final TableWithExpiration redeemedReceipts,
@JsonProperty("registrationRecovery") final TableWithExpiration registrationRecovery,
@JsonProperty("remoteConfig") final Table remoteConfig,
@JsonProperty("reportMessage") final Table reportMessage,
@JsonProperty("scheduledJobs") final TableWithExpiration scheduledJobs,
@JsonProperty("subscriptions") final Table subscriptions,
@JsonProperty("verificationSessions") final Table verificationSessions) {
@@ -110,10 +114,12 @@ public class DynamoDbTables {
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
this.profiles = profiles;
this.pushChallenge = pushChallenge;
this.pushNotificationExperimentSamples = pushNotificationExperimentSamples;
this.redeemedReceipts = redeemedReceipts;
this.registrationRecovery = registrationRecovery;
this.remoteConfig = remoteConfig;
this.reportMessage = reportMessage;
this.scheduledJobs = scheduledJobs;
this.subscriptions = subscriptions;
this.verificationSessions = verificationSessions;
}
@@ -214,6 +220,12 @@ public class DynamoDbTables {
return pushChallenge;
}
@NotNull
@Valid
public Table getPushNotificationExperimentSamples() {
return pushNotificationExperimentSamples;
}
@NotNull
@Valid
public TableWithExpiration getRedeemedReceipts() {
@@ -238,6 +250,12 @@ public class DynamoDbTables {
return reportMessage;
}
@NotNull
@Valid
public TableWithExpiration getScheduledJobs() {
return scheduledJobs;
}
@NotNull
@Valid
public Table getSubscriptions() {
@@ -15,7 +15,6 @@ public record NoiseWebSocketTunnelConfiguration(@Positive int port,
@Nullable String tlsKeyStoreEntryAlias,
@Nullable SecretString tlsKeyStorePassword,
@NotNull SecretBytes noiseStaticPrivateKey,
@NotNull byte[] noiseRootPublicKeySignature,
@NotNull SecretString recognizedProxySecret) {
public ECKeyPair noiseStaticKeyPair() throws InvalidKeyException {
@@ -67,6 +67,10 @@ public class DynamicConfiguration {
@Valid
DynamicMetricsConfiguration metricsConfiguration = new DynamicMetricsConfiguration(false);
@JsonProperty
@Valid
DynamicMessagesConfiguration messagesConfiguration = new DynamicMessagesConfiguration();
public Optional<DynamicExperimentEnrollmentConfiguration> getExperimentEnrollmentConfiguration(
final String experimentName) {
return Optional.ofNullable(experiments.get(experimentName));
@@ -121,4 +125,8 @@ public class DynamicConfiguration {
return metricsConfiguration;
}
public DynamicMessagesConfiguration getMessagesConfiguration() {
return messagesConfiguration;
}
}
@@ -0,0 +1,25 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration.dynamic;
import java.util.List;
import javax.validation.constraints.NotNull;
public record DynamicMessagesConfiguration(@NotNull List<DynamoKeyScheme> dynamoKeySchemes) {
public enum DynamoKeyScheme {
TRADITIONAL,
LAZY_DELETION;
}
public DynamicMessagesConfiguration() {
this(List.of(DynamoKeyScheme.TRADITIONAL));
}
public DynamoKeyScheme writeKeyScheme() {
return dynamoKeySchemes().getLast();
}
}
@@ -34,7 +34,6 @@ import javax.ws.rs.core.Response.Status;
import org.signal.libsignal.usernames.BaseUsernameException;
import org.whispersystems.textsecuregcm.auth.AccountAndAuthenticatedDeviceHolder;
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
import org.whispersystems.textsecuregcm.auth.ChangesDeviceEnabledState;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.auth.TurnToken;
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
@@ -109,7 +108,6 @@ public class AccountController {
@Path("/gcm/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ChangesDeviceEnabledState
public void setGcmRegistrationId(@Mutable @Auth AuthenticatedAccount auth,
@NotNull @Valid GcmRegistrationId registrationId) {
@@ -130,7 +128,6 @@ public class AccountController {
@DELETE
@Path("/gcm/")
@ChangesDeviceEnabledState
public void deleteGcmRegistrationId(@Mutable @Auth AuthenticatedAccount auth) {
Account account = auth.getAccount();
Device device = auth.getAuthenticatedDevice();
@@ -146,19 +143,14 @@ public class AccountController {
@Path("/apn/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ChangesDeviceEnabledState
public void setApnRegistrationId(@Mutable @Auth AuthenticatedAccount auth,
@NotNull @Valid ApnRegistrationId registrationId) {
final Account account = auth.getAccount();
final Device device = auth.getAuthenticatedDevice();
if (Objects.equals(device.getApnId(), registrationId.apnRegistrationId()) &&
Objects.equals(device.getVoipApnId(), registrationId.voipRegistrationId())) {
return;
}
// Unlike FCM tokens, we need current "last updated" timestamps for APNs tokens and so update device records
// unconditionally
accounts.updateDevice(account, device.getId(), d -> {
d.setApnId(registrationId.apnRegistrationId());
d.setVoipApnId(registrationId.voipRegistrationId());
@@ -169,7 +161,6 @@ public class AccountController {
@DELETE
@Path("/apn/")
@ChangesDeviceEnabledState
public void deleteApnRegistrationId(@Mutable @Auth AuthenticatedAccount auth) {
Account account = auth.getAccount();
Device device = auth.getAuthenticatedDevice();
@@ -214,7 +205,6 @@ public class AccountController {
@Path("/attributes/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ChangesDeviceEnabledState
public void setAccountAttributes(
@Mutable @Auth AuthenticatedAccount auth,
@HeaderParam(HeaderUtils.X_SIGNAL_AGENT) String userAgent,
@@ -27,8 +27,8 @@ import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.stream.Stream;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
@@ -54,22 +54,19 @@ import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialPresentation;
import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialRequest;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
import org.whispersystems.textsecuregcm.backup.BackupManager;
import org.whispersystems.textsecuregcm.backup.InvalidLengthException;
import org.whispersystems.textsecuregcm.backup.CopyParameters;
import org.whispersystems.textsecuregcm.backup.CopyResult;
import org.whispersystems.textsecuregcm.backup.MediaEncryptionParameters;
import org.whispersystems.textsecuregcm.backup.SourceObjectNotFoundException;
import org.whispersystems.textsecuregcm.util.BackupAuthCredentialAdapter;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import org.whispersystems.textsecuregcm.util.ByteArrayBase64UrlAdapter;
import org.whispersystems.textsecuregcm.util.ECPublicKeyAdapter;
import org.whispersystems.textsecuregcm.util.ExactlySize;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.Util;
import org.whispersystems.websocket.auth.Mutable;
import org.whispersystems.websocket.auth.ReadOnly;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Path("/v1/archives")
@@ -124,7 +121,7 @@ public class ArchiveController {
public record RedeemBackupReceiptRequest(
@Schema(description = "Presentation of a ZK receipt encoded in standard padded base64", implementation = String.class)
@JsonDeserialize(using = RedeemBackupReceiptRequest.Deserializer.class)
@JsonDeserialize(using = Deserializer.class)
@NotNull
ReceiptCredentialPresentation receiptCredentialPresentation) {
@@ -503,7 +500,16 @@ public class ArchiveController {
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
@NotNull
@ExactlySize(16)
byte[] iv) {}
byte[] iv) {
CopyParameters toCopyParameters() {
return new CopyParameters(
sourceAttachment.cdn, sourceAttachment.key,
objectLength,
new MediaEncryptionParameters(encryptionKey, hmacKey, iv),
mediaId);
}
}
public record CopyMediaResponse(
@Schema(description = "The backup cdn where this media object is stored")
@@ -547,48 +553,20 @@ public class ArchiveController {
throw new BadRequestException("must not use authenticated connection for anonymous operations");
}
return backupManager
.authenticateBackupUser(presentation.presentation, signature.signature)
.thenCompose(backupUser -> checkMediaFits(backupUser, copyMediaRequest.objectLength)
.thenCompose(ignored -> copyMediaImpl(backupUser, copyMediaRequest)))
.thenApply(result -> new CopyMediaResponse(result.cdn()))
.exceptionally(e -> {
final Throwable unwrapped = ExceptionUtils.unwrap(e);
if (unwrapped instanceof SourceObjectNotFoundException) {
throw new ClientErrorException("Source object not found " + unwrapped.getMessage(), Response.Status.GONE);
} else if (unwrapped instanceof InvalidLengthException) {
throw new BadRequestException("Invalid length " + unwrapped.getMessage());
} else {
throw ExceptionUtils.wrap(e);
}
});
return Mono
.fromFuture(backupManager.authenticateBackupUser(presentation.presentation, signature.signature))
.flatMap(backupUser -> backupManager.copyToBackup(backupUser, List.of(copyMediaRequest.toCopyParameters()))
.next()
.map(copyResult -> switch (copyResult.outcome()) {
case SUCCESS -> new CopyMediaResponse(copyResult.cdn());
case SOURCE_WRONG_LENGTH -> throw new BadRequestException("Invalid length");
case SOURCE_NOT_FOUND -> throw new ClientErrorException("Source object not found", Response.Status.GONE);
case OUT_OF_QUOTA ->
throw new ClientErrorException("Media quota exhausted", Response.Status.REQUEST_ENTITY_TOO_LARGE);
}))
.toFuture();
}
private CompletableFuture<Void> checkMediaFits(AuthenticatedBackupUser backupUser, long amountToStore) {
return backupManager.canStoreMedia(backupUser, amountToStore)
.thenApply(fits -> {
if (!fits) {
throw new ClientErrorException("Media quota exhausted", Response.Status.REQUEST_ENTITY_TOO_LARGE);
}
return null;
});
}
private CompletionStage<BackupManager.StorageDescriptor> copyMediaImpl(final AuthenticatedBackupUser backupUser,
final CopyMediaRequest copyMediaRequest) {
return this.backupManager.copyToBackup(
backupUser,
copyMediaRequest.sourceAttachment.cdn,
copyMediaRequest.sourceAttachment.key,
copyMediaRequest.objectLength,
new MediaEncryptionParameters(
copyMediaRequest.encryptionKey,
copyMediaRequest.hmacKey,
copyMediaRequest.iv),
copyMediaRequest.mediaId);
}
public record CopyMediaBatchRequest(
@Schema(description = "A list of media objects to copy from the attachments CDN to the backup CDN")
@NotNull
@@ -606,6 +584,7 @@ public class ArchiveController {
A 200 indicates the object was successfully copied.
A 400 indicates an invalid argument in the request
A 410 indicates that the source object was not found
A 413 indicates that the media quota was exhausted
""")
int status,
@@ -620,7 +599,17 @@ public class ArchiveController {
@JsonDeserialize(using = ByteArrayBase64UrlAdapter.Deserializing.class)
@NotNull
@ExactlySize(15)
byte[] mediaId) {}
byte[] mediaId) {
static Entry fromCopyResult(final CopyResult copyResult) {
return switch (copyResult.outcome()) {
case SUCCESS -> new Entry(200, null, copyResult.cdn(), copyResult.mediaId());
case SOURCE_WRONG_LENGTH -> new Entry(400, "Invalid source length", null, copyResult.mediaId());
case SOURCE_NOT_FOUND -> new Entry(410, "Source not found", null, copyResult.mediaId());
case OUT_OF_QUOTA -> new Entry(413, "Media quota exhausted", null, copyResult.mediaId());
};
}
}
}
@PUT
@@ -661,37 +650,13 @@ public class ArchiveController {
if (account.isPresent()) {
throw new BadRequestException("must not use authenticated connection for anonymous operations");
}
// If the entire batch won't fit in the user's remaining quota, reject the whole request.
final long expectedStorage = copyMediaRequest.items().stream().mapToLong(CopyMediaRequest::objectLength).sum();
return backupManager.authenticateBackupUser(presentation.presentation, signature.signature)
.thenCompose(backupUser -> checkMediaFits(backupUser, expectedStorage).thenCompose(
ignored -> Flux.fromIterable(copyMediaRequest.items)
// Operate sequentially, waiting for one copy to finish before starting the next one. At least right now,
// copying concurrently will introduce contention over the metadata.
.concatMap(request -> Mono
.fromCompletionStage(copyMediaImpl(backupUser, request))
.map(result -> new CopyMediaBatchResponse.Entry(200, null, result.cdn(), result.key()))
.onErrorResume(throwable -> ExceptionUtils.unwrap(throwable) instanceof IOException, throwable -> {
final Throwable unwrapped = ExceptionUtils.unwrap(throwable);
int status;
String error;
if (unwrapped instanceof SourceObjectNotFoundException) {
status = 410;
error = "Source object not found " + unwrapped.getMessage();
} else if (unwrapped instanceof InvalidLengthException) {
status = 400;
error = "Invalid length " + unwrapped.getMessage();
} else {
throw ExceptionUtils.wrap(throwable);
}
return Mono.just(new CopyMediaBatchResponse.Entry(status, error, null, request.mediaId));
}))
.collectList()
.map(list -> Response.status(207).entity(new CopyMediaBatchResponse(list)).build())
.toFuture()));
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()))
.map(CopyMediaBatchResponse.Entry::fromCopyResult)
.collectList()
.map(list -> Response.status(207).entity(new CopyMediaBatchResponse(list)).build())
.toFuture();
}
@POST
@@ -842,12 +807,15 @@ public class ArchiveController {
throw new BadRequestException("must not use authenticated connection for anonymous operations");
}
final List<BackupManager.StorageDescriptor> toDelete = deleteMedia.mediaToDelete().stream()
.map(media -> new BackupManager.StorageDescriptor(media.cdn(), media.mediaId))
.toList();
return backupManager
.authenticateBackupUser(presentation.presentation, signature.signature)
.thenCompose(authenticatedBackupUser -> backupManager.delete(authenticatedBackupUser,
deleteMedia.mediaToDelete().stream()
.map(media -> new BackupManager.StorageDescriptor(media.cdn(), media.mediaId))
.toList()))
.thenCompose(authenticatedBackupUser -> backupManager
.deleteMedia(authenticatedBackupUser, toDelete)
.then().toFuture())
.thenApply(Util.ASYNC_EMPTY_RESPONSE);
}
@@ -31,6 +31,8 @@ import org.whispersystems.textsecuregcm.util.Conversions;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.websocket.auth.ReadOnly;
// To be removed when Android 7.12 reaches saturation, likely some time toward the end of October 2024
@Deprecated(forRemoval = true)
@Path("/v2/attachments")
@Tag(name = "Attachments")
public class AttachmentControllerV2 {
@@ -25,6 +25,8 @@ import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.websocket.auth.ReadOnly;
// To be removed when Desktop 7.17 reaches saturation, likely some time toward the end of October 2024
@Deprecated(forRemoval = true)
@Path("/v3/attachments")
@Tag(name = "Attachments")
public class AttachmentControllerV3 {
@@ -7,6 +7,7 @@ import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Optional;
@@ -20,6 +21,7 @@ import javax.ws.rs.core.MediaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
import org.whispersystems.textsecuregcm.auth.CloudflareTurnCredentialsManager;
import org.whispersystems.textsecuregcm.auth.TurnToken;
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
import org.whispersystems.textsecuregcm.calls.routing.TurnCallRouter;
@@ -40,17 +42,20 @@ public class CallRoutingController {
private final TurnCallRouter turnCallRouter;
private final TurnTokenGenerator tokenGenerator;
private final ExperimentEnrollmentManager experimentEnrollmentManager;
private final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager;
public CallRoutingController(
final RateLimiters rateLimiters,
final TurnCallRouter turnCallRouter,
final TurnTokenGenerator tokenGenerator,
final ExperimentEnrollmentManager experimentEnrollmentManager
final ExperimentEnrollmentManager experimentEnrollmentManager,
final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager
) {
this.rateLimiters = rateLimiters;
this.turnCallRouter = turnCallRouter;
this.tokenGenerator = tokenGenerator;
this.experimentEnrollmentManager = experimentEnrollmentManager;
this.cloudflareTurnCredentialsManager = cloudflareTurnCredentialsManager;
}
@GET
@@ -70,12 +75,12 @@ public class CallRoutingController {
public TurnToken getCallingRelays(
final @ReadOnly @Auth AuthenticatedAccount auth,
@Context ContainerRequestContext requestContext
) throws RateLimitExceededException {
) throws RateLimitExceededException, IOException {
UUID aci = auth.getAccount().getUuid();
rateLimiters.getCallEndpointLimiter().validate(aci);
if (experimentEnrollmentManager.isEnrolled(aci, "cloudflareTurn")) {
return tokenGenerator.generateForCloudflareBeta();
return cloudflareTurnCredentialsManager.retrieveFromCloudflare();
}
Optional<InetAddress> address = Optional.empty();
@@ -46,10 +46,10 @@ import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.server.ContainerRequest;
import org.whispersystems.textsecuregcm.auth.AuthEnablementRefreshRequirementProvider;
import org.whispersystems.textsecuregcm.auth.LinkedDeviceRefreshRequirementProvider;
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
import org.whispersystems.textsecuregcm.auth.ChangesDeviceEnabledState;
import org.whispersystems.textsecuregcm.auth.ChangesLinkedDevices;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.entities.DeviceActivationRequest;
import org.whispersystems.textsecuregcm.entities.DeviceInfo;
@@ -132,7 +132,7 @@ public class DeviceController {
@DELETE
@Produces(MediaType.APPLICATION_JSON)
@Path("/{device_id}")
@ChangesDeviceEnabledState
@ChangesLinkedDevices
public void removeDevice(@Mutable @Auth AuthenticatedAccount auth, @PathParam("device_id") byte deviceId) {
if (auth.getAuthenticatedDevice().getId() != Device.PRIMARY_ID) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
@@ -176,13 +176,14 @@ public class DeviceController {
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/link")
@ChangesDeviceEnabledState
@ChangesLinkedDevices
@Operation(summary = "Link a device to an account",
description = """
Links a device to an account identified by a given phone number.
""")
@ApiResponse(responseCode = "200", description = "The new device was linked to the calling account", useReturnTypeSchema = true)
@ApiResponse(responseCode = "403", description = "The given account was not found or the given verification code was incorrect")
@ApiResponse(responseCode = "409", description = "The new device is missing a capability supported by all other devices on the account")
@ApiResponse(responseCode = "411", description = "The given account already has its maximum number of linked devices")
@ApiResponse(responseCode = "422", description = "The request did not pass validation")
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
@@ -220,7 +221,7 @@ public class DeviceController {
// Normally, the "do we need to refresh somebody's websockets" listener can do this on its own. In this case,
// we're not using the conventional authentication system, and so we need to give it a hint so it knows who the
// active user is and what their device states look like.
AuthEnablementRefreshRequirementProvider.setAccount(containerRequest, account);
LinkedDeviceRefreshRequirementProvider.setAccount(containerRequest, account);
final int maxDeviceLimit = maxDeviceConfiguration.getOrDefault(account.getNumber(), MAX_DEVICES);
@@ -232,6 +233,8 @@ public class DeviceController {
if (capabilities == null) {
throw new WebApplicationException(Response.status(422, "Missing device capabilities").build());
} else if (isCapabilityDowngrade(account, capabilities)) {
throw new WebApplicationException(Response.status(409).build());
}
final String signalAgent;
@@ -387,6 +390,10 @@ public class DeviceController {
return Optional.of(aci);
}
private static boolean isCapabilityDowngrade(Account account, DeviceCapabilities capabilities) {
return account.isDeleteSyncSupported() && !capabilities.deleteSync();
}
private static String getUsedTokenKey(final String token) {
return "usedToken::" + token;
}
@@ -313,7 +313,7 @@ public class KeysController {
@ApiResponse(responseCode = "200", description = "Indicates at least one prekey was available for at least one requested device.", useReturnTypeSchema = true)
@ApiResponse(responseCode = "400", description = "A group send endorsement and other authorization (account authentication or unidentified-access key) were both provided.")
@ApiResponse(responseCode = "401", description = "Account authentication check failed and unidentified-access key or group send endorsement token was not supplied or invalid.")
@ApiResponse(responseCode = "404", description = "Requested identity or device does not exist, is not active, or has no available prekeys.")
@ApiResponse(responseCode = "404", description = "Requested identity or device does not exist or device has no available prekeys.")
@ApiResponse(responseCode = "429", description = "Rate limit exceeded.", headers = @Header(
name = "Retry-After",
description = "If present, a positive integer indicating the number of seconds before a subsequent attempt could succeed"))
@@ -409,42 +409,13 @@ public class KeysController {
return new PreKeyResponse(identityKey, responseItems);
}
@PUT
@Path("/signed")
@Consumes(MediaType.APPLICATION_JSON)
@Operation(summary = "Upload a new signed prekey",
description = """
Upload a new signed elliptic-curve prekey for this device. Deprecated; use PUT /v2/keys instead.
""")
@ApiResponse(responseCode = "200", description = "Indicates that new prekey was successfully stored.")
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
@ApiResponse(responseCode = "422", description = "Invalid request format.")
// TODO Remove this endpoint on or after 2024-05-24
@Deprecated(forRemoval = true)
public CompletableFuture<Response> setSignedKey(
@ReadOnly @Auth final AuthenticatedAccount auth,
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgent,
@Valid final ECSignedPreKey signedPreKey,
@QueryParam("identity") @DefaultValue("aci") final IdentityType identityType) {
final UUID identifier = auth.getAccount().getIdentifier(identityType);
final byte deviceId = auth.getAuthenticatedDevice().getId();
if (!PreKeySignatureValidator.validatePreKeySignatures(auth.getAccount().getIdentityKey(identityType), List.of(signedPreKey), userAgent, "set-signed-pre-key")) {
throw new WebApplicationException("Invalid signature", 422);
}
return keysManager.storeEcSignedPreKeys(identifier, deviceId, signedPreKey)
.thenApply(Util.ASYNC_EMPTY_RESPONSE);
}
private List<Device> parseDeviceId(String deviceId, Account account) {
if (deviceId.equals("*")) {
return account.getDevices().stream().filter(Device::isEnabled).toList();
return account.getDevices();
}
try {
byte id = Byte.parseByte(deviceId);
return account.getDevice(id).filter(Device::isEnabled).map(List::of).orElse(List.of());
return account.getDevice(id).map(List::of).orElse(List.of());
} catch (NumberFormatException e) {
throw new WebApplicationException(Response.status(422).build());
}
@@ -8,13 +8,12 @@ import static com.codahale.metrics.MetricRegistry.name;
import com.codahale.metrics.annotation.Timed;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.net.HttpHeaders;
import com.google.protobuf.ByteString;
import io.dropwizard.auth.Auth;
import io.dropwizard.util.DataSize;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
@@ -113,7 +112,6 @@ 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.NotPushRegisteredException;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.ReceiptSender;
import org.whispersystems.textsecuregcm.spam.ReportSpamTokenProvider;
@@ -176,12 +174,11 @@ public class MessageController {
private static final String REJECT_OVERSIZE_MESSAGE_COUNTER = name(MessageController.class, "rejectOversizeMessage");
private static final String SENT_MESSAGE_COUNTER_NAME = name(MessageController.class, "sentMessages");
private static final String CONTENT_SIZE_DISTRIBUTION_NAME = name(MessageController.class, "messageContentSize");
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 REJECT_INVALID_ENVELOPE_TYPE = name(MessageController.class, "rejectInvalidEnvelopeType");
private static final String UNEXPECTED_MISSING_USER_COUNTER_NAME = name(MessageController.class, "unexpectedMissingDestinationForMultiRecipientMessage");
private static final Timer SEND_MESSAGE_LATENCY_TIMER =
Timer.builder(MetricsUtil.name(MessageController.class, "sendMessageLatency"))
.publishPercentileHistogram(true)
@@ -189,15 +186,25 @@ public class MessageController {
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 ENVELOPE_TYPE_TAG_NAME = "envelopeType";
private static final String IDENTITY_TYPE_TAG_NAME = "identityType";
private static final String ENDPOINT_TYPE_TAG_NAME = "endpoint";
private static final String SENDER_TYPE_IDENTIFIED = "identified";
private static final String SENDER_TYPE_UNIDENTIFIED = "unidentified";
private static final String SENDER_TYPE_SELF = "self";
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 long MAX_MESSAGE_SIZE = DataSize.kibibytes(256).toBytes();
@@ -330,7 +337,7 @@ public class MessageController {
final Optional<byte[]> spamReportToken = switch (senderType) {
case SENDER_TYPE_IDENTIFIED ->
reportSpamTokenProvider.makeReportSpamToken(context, source.get().getAccount(), destination);
reportSpamTokenProvider.makeReportSpamToken(context, source.get(), destination);
default -> Optional.empty();
};
@@ -343,7 +350,7 @@ public class MessageController {
contentLength += message.content().length();
}
validateContentLength(contentLength, userAgent);
validateContentLength(contentLength, false, userAgent);
validateEnvelopeType(message.type(), userAgent);
totalContentLength += contentLength;
@@ -370,7 +377,7 @@ public class MessageController {
OptionalAccess.verify(source.map(AuthenticatedAccount::getAccount), accessKey, destination);
}
boolean needsSync = !isSyncMessage && source.isPresent() && source.get().getAccount().hasEnabledLinkedDevice();
boolean needsSync = !isSyncMessage && source.isPresent() && source.get().getAccount().getDevices().size() > 1;
// We return 200 when stories are sent to a non-existent account. Since story sends bypass OptionalAccess.verify
// we leak information about whether a destination UUID exists if we return any other code (e.g. 404) from
@@ -409,9 +416,22 @@ public class MessageController {
IncomingMessage::destinationRegistrationId,
destination.get().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;
}
final List<Tag> tags = List.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(ENDPOINT_TYPE_TAG_NAME, ENDPOINT_TYPE_SINGLE),
Tag.of(EPHEMERAL_TAG_NAME, String.valueOf(messages.online())),
Tag.of(SENDER_TYPE_TAG_NAME, senderType),
Tag.of(AUTH_TYPE_TAG_NAME, authType),
Tag.of(IDENTITY_TYPE_TAG_NAME, destinationIdentifier.identityType().name()));
for (IncomingMessage incomingMessage : messages.messages()) {
@@ -435,8 +455,6 @@ public class MessageController {
}
return Response.ok(new SendMessageResponse(needsSync)).build();
} catch (NoSuchUserException e) {
throw new WebApplicationException(Response.status(404).build());
} catch (MismatchedDevicesException e) {
throw new WebApplicationException(Response.status(409)
.type(MediaType.APPLICATION_JSON_TYPE)
@@ -628,42 +646,47 @@ public class MessageController {
.build();
}
List<ServiceIdentifier> uuids404 = Collections.synchronizedList(new ArrayList<>());
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;
}
try {
CompletableFuture.allOf(
recipients.values().stream()
.flatMap(recipientData -> {
final Counter sentMessageCounter = Metrics.counter(SENT_MESSAGE_COUNTER_NAME, Tags.of(
UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(EPHEMERAL_TAG_NAME, String.valueOf(online)),
Tag.of(SENDER_TYPE_TAG_NAME, SENDER_TYPE_UNIDENTIFIED),
Tag.of(IDENTITY_TYPE_TAG_NAME, recipientData.serviceIdentifier().identityType().name())));
recipients.values().stream()
.flatMap(recipientData -> {
final Counter sentMessageCounter = Metrics.counter(SENT_MESSAGE_COUNTER_NAME, Tags.of(
UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(ENDPOINT_TYPE_TAG_NAME, ENDPOINT_TYPE_MULTI),
Tag.of(EPHEMERAL_TAG_NAME, String.valueOf(online)),
Tag.of(SENDER_TYPE_TAG_NAME, SENDER_TYPE_UNIDENTIFIED),
Tag.of(AUTH_TYPE_TAG_NAME, authType),
Tag.of(IDENTITY_TYPE_TAG_NAME, recipientData.serviceIdentifier().identityType().name())));
return recipientData.deviceIdToRegistrationId().keySet().stream().map(
deviceId ->CompletableFuture.runAsync(
() -> {
final Account destinationAccount = recipientData.account();
final byte[] payload = multiRecipientMessage.messageForRecipient(recipientData.recipient());
validateContentLength(multiRecipientMessage.messageSizeForRecipient(recipientData.recipient()), true, userAgent);
return recipientData.deviceIdToRegistrationId().keySet().stream().map(
deviceId -> CompletableFuture.runAsync(
() -> {
final Account destinationAccount = recipientData.account();
final byte[] payload = multiRecipientMessage.messageForRecipient(recipientData.recipient());
// we asserted this must exist in validateCompleteDeviceList
final Device destinationDevice = destinationAccount.getDevice(deviceId).orElseThrow();
// we asserted this must exist in validateCompleteDeviceList
final Device destinationDevice = destinationAccount.getDevice(deviceId).orElseThrow();
try {
sentMessageCounter.increment();
sendCommonPayloadMessage(
destinationAccount, destinationDevice, recipientData.serviceIdentifier(), timestamp, online,
destinationAccount, destinationDevice, recipientData.serviceIdentifier(), timestamp,
online,
isStory, isUrgent, payload);
} catch (NoSuchUserException e) {
// this should never happen, because we already asserted the device is present and enabled
Metrics.counter(
UNEXPECTED_MISSING_USER_COUNTER_NAME,
Tags.of("isPrimary", String.valueOf(destinationDevice.isPrimary()))).increment();
uuids404.add(recipientData.serviceIdentifier());
}
},
multiRecipientMessageExecutor));
})
.toArray(CompletableFuture[]::new))
},
multiRecipientMessageExecutor));
})
.toArray(CompletableFuture[]::new))
.get();
} catch (InterruptedException e) {
logger.error("interrupted while delivering multi-recipient messages", e);
@@ -675,7 +698,7 @@ public class MessageController {
logger.error("partial failure while delivering multi-recipient messages", e.getCause());
return Response.serverError().entity("failure during delivery").build();
}
return Response.ok(new SendMultiRecipientMessageResponse(uuids404)).build();
return Response.ok(new SendMultiRecipientMessageResponse(Collections.emptyList())).build();
}
private void checkGroupSendToken(
@@ -724,7 +747,7 @@ public class MessageController {
return messagesManager.getMessagesForDevice(
auth.getAccount().getUuid(),
auth.getAuthenticatedDevice().getId(),
auth.getAuthenticatedDevice(),
false)
.map(messagesAndHasMore -> {
Stream<Envelope> envelopes = messagesAndHasMore.first().stream();
@@ -736,7 +759,11 @@ public class MessageController {
.map(OutgoingMessageEntity::fromEnvelope)
.peek(outgoingMessageEntity -> {
messageMetrics.measureAccountOutgoingMessageUuidMismatches(auth.getAccount(), outgoingMessageEntity);
messageMetrics.measureOutgoingMessageLatency(outgoingMessageEntity.serverTimestamp(), "rest", userAgent, clientReleaseManager);
messageMetrics.measureOutgoingMessageLatency(outgoingMessageEntity.serverTimestamp(),
"rest",
auth.getAuthenticatedDevice().isPrimary(),
userAgent,
clientReleaseManager);
})
.collect(Collectors.toList()),
messagesAndHasMore.second());
@@ -768,13 +795,13 @@ public class MessageController {
public CompletableFuture<Response> removePendingMessage(@ReadOnly @Auth AuthenticatedAccount auth, @PathParam("uuid") UUID uuid) {
return messagesManager.delete(
auth.getAccount().getUuid(),
auth.getAuthenticatedDevice().getId(),
auth.getAuthenticatedDevice(),
uuid,
null)
.thenAccept(maybeDeletedMessage -> {
maybeDeletedMessage.ifPresent(deletedMessage -> {
WebSocketConnection.recordMessageDeliveryDuration(deletedMessage.getTimestamp(),
WebSocketConnection.recordMessageDeliveryDuration(deletedMessage.getServerTimestamp(),
auth.getAuthenticatedDevice());
if (deletedMessage.hasSourceUuid() && deletedMessage.getType() != Type.SERVER_DELIVERY_RECEIPT) {
@@ -856,32 +883,27 @@ public class MessageController {
boolean urgent,
IncomingMessage incomingMessage,
String userAgentString,
Optional<byte[]> spamReportToken)
throws NoSuchUserException {
Optional<byte[]> spamReportToken) {
final Envelope envelope;
try {
final Envelope envelope;
try {
Account sourceAccount = source.map(AuthenticatedAccount::getAccount).orElse(null);
Byte sourceDeviceId = source.map(account -> account.getAuthenticatedDevice().getId()).orElse(null);
envelope = incomingMessage.toEnvelope(
destinationIdentifier,
sourceAccount,
sourceDeviceId,
timestamp == 0 ? System.currentTimeMillis() : timestamp,
story,
urgent,
spamReportToken.orElse(null));
} catch (final IllegalArgumentException e) {
logger.warn("Received bad envelope type {} from {}", incomingMessage.type(), userAgentString);
throw new BadRequestException(e);
}
messageSender.sendMessage(destinationAccount, destinationDevice, envelope, online);
} catch (NotPushRegisteredException e) {
if (destinationDevice.isPrimary()) throw new NoSuchUserException(e);
else logger.debug("Not registered", e);
final Account sourceAccount = source.map(AuthenticatedAccount::getAccount).orElse(null);
final Byte sourceDeviceId = source.map(account -> account.getAuthenticatedDevice().getId()).orElse(null);
envelope = incomingMessage.toEnvelope(
destinationIdentifier,
sourceAccount,
sourceDeviceId,
timestamp == 0 ? System.currentTimeMillis() : timestamp,
story,
urgent,
spamReportToken.orElse(null));
} catch (final IllegalArgumentException e) {
logger.warn("Received bad envelope type {} from {}", incomingMessage.type(), userAgentString);
throw new BadRequestException(e);
}
messageSender.sendMessage(destinationAccount, destinationDevice, envelope, online);
}
private void sendCommonPayloadMessage(Account destinationAccount,
@@ -891,28 +913,21 @@ public class MessageController {
boolean online,
boolean story,
boolean urgent,
byte[] payload) throws NoSuchUserException {
try {
Envelope.Builder messageBuilder = Envelope.newBuilder();
long serverTimestamp = System.currentTimeMillis();
byte[] payload) {
messageBuilder
.setType(Type.UNIDENTIFIED_SENDER)
.setTimestamp(timestamp == 0 ? serverTimestamp : timestamp)
.setServerTimestamp(serverTimestamp)
.setContent(ByteString.copyFrom(payload))
.setStory(story)
.setUrgent(urgent)
.setDestinationUuid(serviceIdentifier.toServiceIdentifierString());
final Envelope.Builder messageBuilder = Envelope.newBuilder();
final long serverTimestamp = System.currentTimeMillis();
messageSender.sendMessage(destinationAccount, destinationDevice, messageBuilder.build(), online);
} catch (NotPushRegisteredException e) {
if (destinationDevice.isPrimary()) {
throw new NoSuchUserException(e);
} else {
logger.debug("Not registered", e);
}
}
messageBuilder
.setType(Type.UNIDENTIFIED_SENDER)
.setTimestamp(timestamp == 0 ? serverTimestamp : timestamp)
.setServerTimestamp(serverTimestamp)
.setContent(ByteString.copyFrom(payload))
.setStory(story)
.setUrgent(urgent)
.setDestinationUuid(serviceIdentifier.toServiceIdentifierString());
messageSender.sendMessage(destinationAccount, destinationDevice, messageBuilder.build(), online);
}
private void checkMessageRateLimit(AuthenticatedAccount source, Account destination, String userAgent)
@@ -932,16 +947,22 @@ public class MessageController {
}
}
private void validateContentLength(final int contentLength, final String userAgent) {
Metrics.summary(CONTENT_SIZE_DISTRIBUTION_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)))
private void validateContentLength(final int contentLength, final boolean multiRecipientMessage, 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(multiRecipientMessage))))
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry)
.record(contentLength);
if (contentLength > MAX_MESSAGE_SIZE) {
if (oversize) {
Metrics.counter(REJECT_OVERSIZE_MESSAGE_COUNTER, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)))
.increment();
throw new WebApplicationException(Status.REQUEST_ENTITY_TOO_LARGE);
}
}
private void validateEnvelopeType(final int type, final String userAgent) {
@@ -1,18 +0,0 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.controllers;
import java.util.UUID;
public class NoSuchUserException extends Exception {
public NoSuchUserException(final UUID uuid) {
super(uuid.toString());
}
public NoSuchUserException(Exception e) {
super(e);
}
}
@@ -447,7 +447,7 @@ public class ProfileController {
return new BaseProfileResponse(account.getIdentityKey(IdentityType.ACI),
account.getUnidentifiedAccessKey().map(UnidentifiedAccessChecksum::generateFor).orElse(null),
account.isUnrestrictedUnidentifiedAccess(),
new UserCapabilities(),
UserCapabilities.createForAccount(account),
profileBadgeConverter.convert(
getAcceptableLanguagesForRequest(containerRequestContext),
account.getBadges(),
@@ -459,7 +459,7 @@ public class ProfileController {
return new BaseProfileResponse(account.getIdentityKey(IdentityType.PNI),
null,
false,
new UserCapabilities(),
UserCapabilities.createForAccount(account),
Collections.emptyList(),
new PniServiceIdentifier(account.getPhoneNumberIdentifier()));
}
@@ -11,8 +11,7 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = AnswerPushChallengeRequest.class, name = "rateLimitPushChallenge"),
@JsonSubTypes.Type(value = AnswerCaptchaChallengeRequest.class, name = "captcha"),
@JsonSubTypes.Type(value = AnswerCaptchaChallengeRequest.class, name = "recaptcha")
@JsonSubTypes.Type(value = AnswerCaptchaChallengeRequest.class, name = "captcha")
})
public abstract class AnswerChallengeRequest {
}
@@ -5,16 +5,14 @@
package org.whispersystems.textsecuregcm.entities;
import org.whispersystems.textsecuregcm.storage.Account;
public record UserCapabilities(
// TODO: Remove the paymentActivation capability entirely sometime soon after 2024-06-30
boolean paymentActivation,
// TODO Remove the PNI and PNP capabilities entirely on or after 2024-05-18
boolean pni,
boolean pnp,
// TODO Remove the giftBadges capability on or after 2024-05-26
boolean giftBadges) {
boolean deleteSync) {
public UserCapabilities() {
this(true, true, true, true);
public static UserCapabilities createForAccount(final Account account) {
return new UserCapabilities(true, account.isDeleteSyncSupported());
}
}
@@ -0,0 +1,17 @@
package org.whispersystems.textsecuregcm.experiment;
import javax.annotation.Nullable;
public record DeviceLastSeenState(boolean deviceExists,
long createdAtMillis,
boolean hasPushToken,
long lastSeenMillis,
@Nullable PushTokenType pushTokenType) {
public static DeviceLastSeenState MISSING_DEVICE_STATE = new DeviceLastSeenState(false, 0, false, 0, null);
public enum PushTokenType {
APNS,
FCM
}
}
@@ -0,0 +1,159 @@
package org.whispersystems.textsecuregcm.experiment;
import com.google.common.annotations.VisibleForTesting;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.push.IdleDeviceNotificationScheduler;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import reactor.core.publisher.Flux;
import javax.annotation.Nullable;
import java.util.EnumMap;
import java.util.Map;
import java.time.LocalTime;
import java.util.concurrent.CompletableFuture;
public class NotifyIdleDevicesWithoutMessagesPushNotificationExperiment implements PushNotificationExperiment<DeviceLastSeenState> {
private final MessagesManager messagesManager;
private final IdleDeviceNotificationScheduler idleDeviceNotificationScheduler;
private static final LocalTime PREFERRED_NOTIFICATION_TIME = LocalTime.of(14, 0);
private static final Logger log = LoggerFactory.getLogger(NotifyIdleDevicesWithoutMessagesPushNotificationExperiment.class);
@VisibleForTesting
enum Population {
APNS_CONTROL,
APNS_EXPERIMENT,
FCM_CONTROL,
FCM_EXPERIMENT
}
@VisibleForTesting
enum Outcome {
DELETED,
UNINSTALLED,
REACTIVATED,
UNCHANGED
}
public NotifyIdleDevicesWithoutMessagesPushNotificationExperiment(final MessagesManager messagesManager,
final IdleDeviceNotificationScheduler idleDeviceNotificationScheduler) {
this.messagesManager = messagesManager;
this.idleDeviceNotificationScheduler = idleDeviceNotificationScheduler;
}
@Override
public String getExperimentName() {
return "notify-idle-devices-without-messages";
}
@Override
public CompletableFuture<Boolean> isDeviceEligible(final Account account, final Device device) {
if (!hasPushToken(device)) {
return CompletableFuture.completedFuture(false);
}
if (!idleDeviceNotificationScheduler.isIdle(device)) {
return CompletableFuture.completedFuture(false);
}
return messagesManager.mayHavePersistedMessages(account.getIdentifier(IdentityType.ACI), device)
.thenApply(mayHavePersistedMessages -> !mayHavePersistedMessages);
}
@VisibleForTesting
static boolean hasPushToken(final Device device) {
// Exclude VOIP tokens since they have their own, distinct delivery mechanism
return !StringUtils.isAllBlank(device.getApnId(), device.getGcmId()) && StringUtils.isBlank(device.getVoipApnId());
}
@Override
public DeviceLastSeenState getState(@Nullable final Account account, @Nullable final Device device) {
if (account != null && device != null) {
final DeviceLastSeenState.PushTokenType pushTokenType = StringUtils.isNotBlank(device.getApnId())
? DeviceLastSeenState.PushTokenType.APNS
: DeviceLastSeenState.PushTokenType.FCM;
return new DeviceLastSeenState(true, device.getCreated(), hasPushToken(device), device.getLastSeen(), pushTokenType);
} else {
return DeviceLastSeenState.MISSING_DEVICE_STATE;
}
}
@Override
public CompletableFuture<Void> applyExperimentTreatment(final Account account, final Device device) {
return idleDeviceNotificationScheduler.scheduleNotification(account, device.getId(), PREFERRED_NOTIFICATION_TIME);
}
@Override
public void analyzeResults(final Flux<PushNotificationExperimentSample<DeviceLastSeenState>> samples) {
final Map<Population, Map<Outcome, Integer>> contingencyTable = new EnumMap<>(Population.class);
for (final Population population : Population.values()) {
final Map<Outcome, Integer> countsByOutcome = new EnumMap<>(Outcome.class);
for (final Outcome outcome : Outcome.values()) {
countsByOutcome.put(outcome, 0);
}
contingencyTable.put(population, countsByOutcome);
}
samples.doOnNext(sample -> contingencyTable.get(getPopulation(sample)).merge(getOutcome(sample), 1, Integer::sum))
.then()
.block();
final StringBuilder reportBuilder = new StringBuilder("population,deleted,uninstalled,reactivated,unchanged\n");
for (final Population population : Population.values()) {
final Map<Outcome, Integer> countsByOutcome = contingencyTable.get(population);
reportBuilder.append(population.name());
reportBuilder.append(",");
reportBuilder.append(countsByOutcome.getOrDefault(Outcome.DELETED, 0));
reportBuilder.append(",");
reportBuilder.append(countsByOutcome.getOrDefault(Outcome.UNINSTALLED, 0));
reportBuilder.append(",");
reportBuilder.append(countsByOutcome.getOrDefault(Outcome.REACTIVATED, 0));
reportBuilder.append(",");
reportBuilder.append(countsByOutcome.getOrDefault(Outcome.UNCHANGED, 0));
reportBuilder.append("\n");
}
log.info(reportBuilder.toString());
}
@VisibleForTesting
static Population getPopulation(final PushNotificationExperimentSample<DeviceLastSeenState> sample) {
assert sample.initialState() != null && sample.initialState().pushTokenType() != null;
return switch (sample.initialState().pushTokenType()) {
case APNS -> sample.inExperimentGroup() ? Population.APNS_EXPERIMENT : Population.APNS_CONTROL;
case FCM -> sample.inExperimentGroup() ? Population.FCM_EXPERIMENT : Population.FCM_CONTROL;
};
}
@VisibleForTesting
static Outcome getOutcome(final PushNotificationExperimentSample<DeviceLastSeenState> sample) {
final Outcome outcome;
if (!sample.finalState().deviceExists() || sample.initialState().createdAtMillis() != sample.finalState().createdAtMillis()) {
outcome = Outcome.DELETED;
} else if (!sample.finalState().hasPushToken()) {
outcome = Outcome.UNINSTALLED;
} else if (sample.initialState().lastSeenMillis() != sample.finalState().lastSeenMillis()) {
outcome = Outcome.REACTIVATED;
} else {
outcome = Outcome.UNCHANGED;
}
return outcome;
}
}
@@ -0,0 +1,77 @@
package org.whispersystems.textsecuregcm.experiment;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import reactor.core.publisher.Flux;
import javax.annotation.Nullable;
import java.util.concurrent.CompletableFuture;
/**
* A push notification selects for eligible devices, applies a control or experimental treatment, and provides a
* mechanism for comparing device states before and after receiving the treatment.
*
* @param <T> the type of state object stored for this experiment
*/
public interface PushNotificationExperiment<T> {
/**
* Returns the unique name of this experiment.
*
* @return the unique name of this experiment
*/
String getExperimentName();
/**
* Tests whether a device is eligible for this experiment. An eligible device may be assigned to either the control
* or experiment group within an experiment. Ineligible devices will not participate in the experiment in any way.
*
* @param account the account to which the device belongs
* @param device the device to test for eligibility in this experiment
*
* @return a future that yields a boolean value indicating whether the target device is eligible for this experiment
*/
CompletableFuture<Boolean> isDeviceEligible(Account account, Device device);
/**
* Generates an experiment specific state "snapshot" of the given device. Experiment results are generally evaluated
* by comparing a device's state before a treatment is applied and its state after the treatment is applied.
*
* @param account the account to which the device belongs
* @param device the device for which to generate a state "snapshot"
*
* @return an experiment-specific state "snapshot" of the given device
*/
T getState(@Nullable Account account, @Nullable Device device);
/**
* Applies a control treatment to the given device. In many cases (and by default) no action is taken for devices in
* the control group.
*
* @param account the account to which the device belongs
* @param device the device to which to apply the control treatment for this experiment
*
* @return a future that completes when the control treatment has been applied for the given device
*/
default CompletableFuture<Void> applyControlTreatment(Account account, Device device) {
return CompletableFuture.completedFuture(null);
};
/**
* Applies an experimental treatment to the given device. This generally involves sending or scheduling a specific
* type of push notification for the given device.
*
* @param account the account to which the device belongs
* @param device the device to which to apply the experimental treatment for this experiment
*
* @return a future that completes when the experimental treatment has been applied for the given device
*/
CompletableFuture<Void> applyExperimentTreatment(Account account, Device device);
/**
* Consumes a stream of finished samples and emits an analysis of the results via an implementation-specific channel
* (e.g. a log message). Implementations must block until all samples have been consumed and analyzed.
*
* @param samples a stream of finished samples from this experiment
*/
void analyzeResults(Flux<PushNotificationExperimentSample<T>> samples);
}
@@ -0,0 +1,4 @@
package org.whispersystems.textsecuregcm.experiment;
public record PushNotificationExperimentSample<T>(boolean inExperimentGroup, T initialState, T finalState) {
}
@@ -0,0 +1,284 @@
package org.whispersystems.textsecuregcm.experiment;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.nio.ByteBuffer;
import java.time.Clock;
import java.time.Duration;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import com.google.common.annotations.VisibleForTesting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuples;
import reactor.util.retry.Retry;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
import software.amazon.awssdk.services.dynamodb.model.ScanRequest;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
public class PushNotificationExperimentSamples {
private final DynamoDbAsyncClient dynamoDbAsyncClient;
private final String tableName;
private final Clock clock;
// Experiment name; DynamoDB string; partition key
public static final String KEY_EXPERIMENT_NAME = "N";
// Combined ACI and device ID; DynamoDB byte array; sort key
public static final String ATTR_ACI_AND_DEVICE_ID = "AD";
// Whether the device is enrolled in the experiment group (as opposed to control group); DynamoDB boolean
static final String ATTR_IN_EXPERIMENT_GROUP = "X";
// The experiment-specific state of the device at the start of the experiment, represented as a JSON blob; DynamoDB
// string
static final String ATTR_INITIAL_STATE = "I";
// The experiment-specific state of the device at the end of the experiment, represented as a JSON blob; DynamoDB
// string
static final String ATTR_FINAL_STATE = "F";
// The time, in seconds since the epoch, at which this sample should be deleted automatically
static final String ATTR_TTL = "E";
private static final Duration FINAL_SAMPLE_TTL = Duration.ofDays(7);
private static final Logger log = LoggerFactory.getLogger(PushNotificationExperimentSamples.class);
public PushNotificationExperimentSamples(final DynamoDbAsyncClient dynamoDbAsyncClient,
final String tableName,
final Clock clock) {
this.dynamoDbAsyncClient = dynamoDbAsyncClient;
this.tableName = tableName;
this.clock = clock;
}
/**
* Writes the initial state of a device participating in a push notification experiment.
*
* @param accountIdentifier the account identifier for the account to which the target device is linked
* @param deviceId the identifier for the device within the given account
* @param experimentName the name of the experiment
* @param inExperimentGroup whether the given device is in the experiment group (as opposed to control group)
* @param initialState the initial state of the object; must be serializable as a JSON text
*
* @return a future that completes when the record has been stored; the future yields {@code true} if a new record
* was stored or {@code false} if a conflicting record already exists
*
* @param <T> the type of state object for this sample
*
* @throws JsonProcessingException if the given {@code initialState} could not be serialized as a JSON text
*/
public <T> CompletableFuture<Boolean> recordInitialState(final UUID accountIdentifier,
final byte deviceId,
final String experimentName,
final boolean inExperimentGroup,
final T initialState) throws JsonProcessingException {
final AttributeValue initialStateAttributeValue =
AttributeValue.fromS(SystemMapper.jsonMapper().writeValueAsString(initialState));
final AttributeValue inExperimentGroupAttributeValue = AttributeValue.fromBool(inExperimentGroup);
return dynamoDbAsyncClient.putItem(PutItemRequest.builder()
.tableName(tableName)
.item(Map.of(
KEY_EXPERIMENT_NAME, AttributeValue.fromS(experimentName),
ATTR_ACI_AND_DEVICE_ID, buildSortKey(accountIdentifier, deviceId),
ATTR_IN_EXPERIMENT_GROUP, inExperimentGroupAttributeValue,
ATTR_INITIAL_STATE, initialStateAttributeValue,
ATTR_TTL, AttributeValue.fromN(String.valueOf(clock.instant().plus(FINAL_SAMPLE_TTL).getEpochSecond()))))
.conditionExpression("(attribute_not_exists(#inExperimentGroup) OR #inExperimentGroup = :inExperimentGroup) AND (attribute_not_exists(#initialState) OR #initialState = :initialState) AND attribute_not_exists(#finalState)")
.expressionAttributeNames(Map.of(
"#inExperimentGroup", ATTR_IN_EXPERIMENT_GROUP,
"#initialState", ATTR_INITIAL_STATE,
"#finalState", ATTR_FINAL_STATE))
.expressionAttributeValues(Map.of(
":inExperimentGroup", inExperimentGroupAttributeValue,
":initialState", initialStateAttributeValue))
.build())
.thenApply(ignored -> true)
.exceptionally(throwable -> {
if (ExceptionUtils.unwrap(throwable) instanceof ConditionalCheckFailedException) {
return false;
}
throw ExceptionUtils.wrap(throwable);
});
}
/**
* Writes the final state of a device participating in a push notification experiment.
*
* @param accountIdentifier the account identifier for the account to which the target device is linked
* @param deviceId the identifier for the device within the given account
* @param experimentName the name of the experiment
* @param finalState the final state of the object; must be serializable as a JSON text and of the same type as the
* previously-stored initial state
* @return a future that completes when the final state has been stored; yields a finished sample if an initial sample
* was found or empty if no initial sample was found for the given account, device, and experiment
*
* @param <T> the type of state object for this sample
*
* @throws JsonProcessingException if the given {@code finalState} could not be serialized as a JSON text
*/
public <T> CompletableFuture<PushNotificationExperimentSample<T>> recordFinalState(final UUID accountIdentifier,
final byte deviceId,
final String experimentName,
final T finalState) throws JsonProcessingException {
final AttributeValue aciAndDeviceIdAttributeValue = buildSortKey(accountIdentifier, deviceId);
return dynamoDbAsyncClient.updateItem(UpdateItemRequest.builder()
.tableName(tableName)
.key(Map.of(
KEY_EXPERIMENT_NAME, AttributeValue.fromS(experimentName),
ATTR_ACI_AND_DEVICE_ID, aciAndDeviceIdAttributeValue))
// `UpdateItem` will, by default, create a new item if one does not already exist for the given primary key. We
// want update-only-if-exists behavior, though, and so check that there's already an existing item for this ACI
// and device ID.
.conditionExpression("#aciAndDeviceId = :aciAndDeviceId")
.updateExpression("SET #finalState = if_not_exists(#finalState, :finalState)")
.expressionAttributeNames(Map.of(
"#aciAndDeviceId", ATTR_ACI_AND_DEVICE_ID,
"#finalState", ATTR_FINAL_STATE))
.expressionAttributeValues(Map.of(
":aciAndDeviceId", aciAndDeviceIdAttributeValue,
":finalState", AttributeValue.fromS(SystemMapper.jsonMapper().writeValueAsString(finalState))))
.returnValues(ReturnValue.ALL_NEW)
.build())
.thenApply(updateItemResponse -> {
try {
final boolean inExperimentGroup = updateItemResponse.attributes().get(ATTR_IN_EXPERIMENT_GROUP).bool();
@SuppressWarnings("unchecked") final T parsedInitialState =
(T) parseState(updateItemResponse.attributes().get(ATTR_INITIAL_STATE).s(), finalState.getClass());
@SuppressWarnings("unchecked") final T parsedFinalState =
(T) parseState(updateItemResponse.attributes().get(ATTR_FINAL_STATE).s(), finalState.getClass());
return new PushNotificationExperimentSample<>(inExperimentGroup, parsedInitialState, parsedFinalState);
} catch (final JsonProcessingException e) {
throw ExceptionUtils.wrap(e);
}
});
}
/**
* Returns a publisher across all samples pending a final state for a given experiment.
*
* @param experimentName the name of the experiment for which to retrieve samples pending a final state
*
* @return a publisher across all samples pending a final state for a given experiment
*/
public Flux<Tuple2<UUID, Byte>> getDevicesPendingFinalState(final String experimentName) {
return Flux.from(dynamoDbAsyncClient.queryPaginator(QueryRequest.builder()
.tableName(tableName)
.keyConditionExpression("#experiment = :experiment")
.filterExpression("attribute_not_exists(#finalState)")
.expressionAttributeNames(Map.of(
"#experiment", KEY_EXPERIMENT_NAME,
"#finalState", ATTR_FINAL_STATE))
.expressionAttributeValues(Map.of(":experiment", AttributeValue.fromS(experimentName)))
.projectionExpression(ATTR_ACI_AND_DEVICE_ID)
.build())
.items())
.map(item -> parseSortKey(item.get(ATTR_ACI_AND_DEVICE_ID)));
}
/**
* Returns a publisher across all finished samples (i.e. samples with a recorded final state) for a given experiment.
*
* @param experimentName the name of the experiment for which to retrieve finished samples
* @param stateClass the type of state object for sample in the given experiment
*
* @return a publisher across all finished samples for the given experiment
*
* @param <T> the type of the sample's state objects
*/
public <T> Flux<PushNotificationExperimentSample<T>> getFinishedSamples(final String experimentName,
final Class<T> stateClass) {
return Flux.from(dynamoDbAsyncClient.queryPaginator(QueryRequest.builder()
.tableName(tableName)
.keyConditionExpression("#experiment = :experiment")
.filterExpression("attribute_exists(#finalState)")
.expressionAttributeNames(Map.of(
"#experiment", KEY_EXPERIMENT_NAME,
"#finalState", ATTR_FINAL_STATE))
.expressionAttributeValues(Map.of(":experiment", AttributeValue.fromS(experimentName)))
.build())
.items())
.handle((item, sink) -> {
try {
final boolean inExperimentGroup = item.get(ATTR_IN_EXPERIMENT_GROUP).bool();
final T initialState = parseState(item.get(ATTR_INITIAL_STATE).s(), stateClass);
final T finalState = parseState(item.get(ATTR_FINAL_STATE).s(), stateClass);
sink.next(new PushNotificationExperimentSample<>(inExperimentGroup, initialState, finalState));
} catch (final JsonProcessingException e) {
sink.error(e);
}
});
}
public CompletableFuture<Void> discardSamples(final String experimentName, final int maxConcurrency) {
final AttributeValue experimentNameAttributeValue = AttributeValue.fromS(experimentName);
return Flux.from(dynamoDbAsyncClient.scanPaginator(ScanRequest.builder()
.tableName(tableName)
.filterExpression("#experiment = :experiment")
.expressionAttributeNames(Map.of("#experiment", KEY_EXPERIMENT_NAME))
.expressionAttributeValues(Map.of(":experiment", experimentNameAttributeValue))
.projectionExpression(ATTR_ACI_AND_DEVICE_ID)
.build())
.items())
.map(item -> item.get(ATTR_ACI_AND_DEVICE_ID))
.flatMap(aciAndDeviceId -> Mono.fromFuture(() -> dynamoDbAsyncClient.deleteItem(DeleteItemRequest.builder()
.tableName(tableName)
.key(Map.of(
KEY_EXPERIMENT_NAME, experimentNameAttributeValue,
ATTR_ACI_AND_DEVICE_ID, aciAndDeviceId))
.build()))
.retryWhen(Retry.backoff(5, Duration.ofSeconds(5)))
.onErrorResume(throwable -> {
log.warn("Failed to delete sample for experiment {}", experimentName, throwable);
return Mono.empty();
}), maxConcurrency)
.then()
.toFuture();
}
@VisibleForTesting
static AttributeValue buildSortKey(final UUID accountIdentifier, final byte deviceId) {
return AttributeValue.fromB(SdkBytes.fromByteBuffer(ByteBuffer.allocate(17)
.putLong(accountIdentifier.getMostSignificantBits())
.putLong(accountIdentifier.getLeastSignificantBits())
.put(deviceId)
.flip()));
}
private static Tuple2<UUID, Byte> parseSortKey(final AttributeValue sortKey) {
final ByteBuffer byteBuffer = sortKey.b().asByteBuffer();
return Tuples.of(new UUID(byteBuffer.getLong(), byteBuffer.getLong()), byteBuffer.get());
}
private static <T> T parseState(final String state, final Class<T> clazz) throws JsonProcessingException {
return SystemMapper.jsonMapper().readValue(state, clazz);
}
}
@@ -201,7 +201,8 @@ public class DevicesGrpcService extends ReactorDevicesGrpc.DevicesImplBase {
d -> d.setCapabilities(new Device.DeviceCapabilities(
request.getStorage(),
request.getTransfer(),
request.getPaymentActivation())))))
request.getPaymentActivation(),
request.getDeleteSync())))))
.thenReturn(SetCapabilitiesResponse.newBuilder().build());
}
}
@@ -39,7 +39,6 @@ class KeysGrpcHelper {
: Flux.from(Mono.justOrEmpty(targetAccount.getDevice(targetDeviceId)));
return devices
.filter(Device::isEnabled)
.switchIfEmpty(Mono.error(Status.NOT_FOUND.asException()))
.flatMap(device -> Flux.merge(
Mono.fromFuture(() -> keysManager.takeEC(targetAccount.getIdentifier(identityType), device.getId())),
@@ -83,7 +83,7 @@ public class ProfileGrpcHelper {
static UserCapabilities buildUserCapabilities(final org.whispersystems.textsecuregcm.entities.UserCapabilities capabilities) {
return UserCapabilities.newBuilder()
.setPaymentActivation(capabilities.paymentActivation())
.setPni(capabilities.pni())
.setDeleteSync(capabilities.deleteSync())
.build();
}
@@ -105,7 +105,7 @@ public class ProfileGrpcHelper {
final ProfileBadgeConverter profileBadgeConverter) {
final GetUnversionedProfileResponse.Builder responseBuilder = GetUnversionedProfileResponse.newBuilder()
.setIdentityKey(ByteString.copyFrom(targetAccount.getIdentityKey(targetIdentifier.identityType()).serialize()))
.setCapabilities(buildUserCapabilities(new org.whispersystems.textsecuregcm.entities.UserCapabilities()));
.setCapabilities(buildUserCapabilities(org.whispersystems.textsecuregcm.entities.UserCapabilities.createForAccount(targetAccount)));
switch (targetIdentifier.identityType()) {
case ACI -> {
@@ -1,124 +0,0 @@
package org.whispersystems.textsecuregcm.grpc.net;
import com.southernstorm.noise.protocol.HandshakeState;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.util.internal.EmptyArrays;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.ShortBufferException;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
/**
* An abstract base class for XX- and NX-patterned Noise responder handshake handlers.
*
* @see <a href="https://noiseprotocol.org/noise.html">The Noise Protocol Framework</a>
*/
abstract class AbstractNoiseHandshakeHandler extends ChannelInboundHandlerAdapter {
private final ECKeyPair ecKeyPair;
private final byte[] publicKeySignature;
private final HandshakeState handshakeState;
private static final int EXPECTED_EPHEMERAL_KEY_MESSAGE_LENGTH = 32;
/**
* Constructs a new Noise handler with the given static server keys and static public key signature. The static public
* key must be signed by a trusted root private key whose public key is known to and trusted by authenticating
* clients.
*
* @param noiseProtocolName the name of the Noise protocol implemented by this handshake handler
* @param ecKeyPair the static key pair for this server
* @param publicKeySignature an Ed25519 signature of the raw bytes of the static public key
*/
AbstractNoiseHandshakeHandler(final String noiseProtocolName,
final ECKeyPair ecKeyPair,
final byte[] publicKeySignature) {
this.ecKeyPair = ecKeyPair;
this.publicKeySignature = publicKeySignature;
try {
this.handshakeState = new HandshakeState(noiseProtocolName, HandshakeState.RESPONDER);
} catch (final NoSuchAlgorithmException e) {
throw new AssertionError("Unsupported Noise algorithm: " + noiseProtocolName, e);
}
}
protected HandshakeState getHandshakeState() {
return handshakeState;
}
/**
* Handles an initial ephemeral key message from a client, advancing the handshake state and sending the server's
* static keys to the client. Both XX and NX patterns begin with a client sending its ephemeral key to the server.
* Clients must not include an additional payload with their ephemeral key message. The server's reply contains its
* static keys along with an Ed25519 signature of its public static key by a trusted root key.
*
* @param context the channel handler context for this message
* @param frame the websocket frame containing the ephemeral key message
*
* @throws NoiseHandshakeException if the ephemeral key message from the client was not of the expected size or if a
* general Noise encryption error occurred
*/
protected void handleEphemeralKeyMessage(final ChannelHandlerContext context, final BinaryWebSocketFrame frame)
throws NoiseHandshakeException {
if (frame.content().readableBytes() != EXPECTED_EPHEMERAL_KEY_MESSAGE_LENGTH) {
throw new NoiseHandshakeException("Unexpected ephemeral key message length");
}
// Cryptographically initializing a handshake is expensive, and so we defer it until we're confident the client is
// making a good-faith effort to perform a handshake (i.e. now). Noise-java in particular will derive a public key
// from the supplied private key (and will in fact overwrite any previously-set public key when setting a private
// key), so we just set the private key here.
handshakeState.getLocalKeyPair().setPrivateKey(ecKeyPair.getPrivateKey().serialize(), 0);
handshakeState.start();
// The initial message from the client should just include a plaintext ephemeral key with no payload. The frame is
// coming off the wire and so will be in a direct buffer that doesn't have a backing array.
final byte[] ephemeralKeyMessage = ByteBufUtil.getBytes(frame.content());
frame.content().readBytes(ephemeralKeyMessage);
try {
handshakeState.readMessage(ephemeralKeyMessage, 0, ephemeralKeyMessage.length, EmptyArrays.EMPTY_BYTES, 0);
} catch (final ShortBufferException e) {
// This should never happen since we're checking the length of the frame up front
throw new NoiseHandshakeException("Unexpected client payload");
} catch (final BadPaddingException e) {
// It turns out this should basically never happen because (a) we're not using padding and (b) the "bad AEAD tag"
// subclass of a bad padding exception can only happen if we have some AD to check, which we don't for an
// ephemeral-key-only message
throw new NoiseHandshakeException("Invalid keys");
}
// Send our key material and public key signature back to the client; this buffer will include:
//
// - A 32-byte plaintext ephemeral key
// - A 32-byte encrypted static key
// - A 16-byte AEAD tag for the static key
// - The public key signature payload
// - A 16-byte AEAD tag for the payload
final byte[] keyMaterial = new byte[32 + 32 + 16 + publicKeySignature.length + 16];
try {
handshakeState.writeMessage(keyMaterial, 0, publicKeySignature, 0, publicKeySignature.length);
context.writeAndFlush(new BinaryWebSocketFrame(Unpooled.wrappedBuffer(keyMaterial)))
.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
} catch (final ShortBufferException e) {
// This should never happen for messages of known length that we control
throw new AssertionError("Key material buffer was too short for message", e);
}
}
@Override
public void handlerRemoved(final ChannelHandlerContext context) {
handshakeState.destroy();
}
}
@@ -9,6 +9,7 @@ import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import javax.crypto.BadPaddingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
/**
* An error handler serves as a general backstop for exceptions elsewhere in the pipeline. If the client has completed a
@@ -38,10 +39,11 @@ class ErrorHandler extends ChannelInboundHandlerAdapter {
@Override
public void exceptionCaught(final ChannelHandlerContext context, final Throwable cause) {
if (websocketHandshakeComplete) {
final WebSocketCloseStatus webSocketCloseStatus = switch (cause) {
final WebSocketCloseStatus webSocketCloseStatus = switch (ExceptionUtils.unwrap(cause)) {
case NoiseHandshakeException e -> ApplicationWebSocketCloseReason.NOISE_HANDSHAKE_ERROR.toWebSocketCloseStatus(e.getMessage());
case ClientAuthenticationException ignored -> ApplicationWebSocketCloseReason.CLIENT_AUTHENTICATION_ERROR.toWebSocketCloseStatus("Not authenticated");
case BadPaddingException ignored -> ApplicationWebSocketCloseReason.NOISE_ENCRYPTION_ERROR.toWebSocketCloseStatus("Noise encryption error");
case NoiseException ignored -> ApplicationWebSocketCloseReason.NOISE_ENCRYPTION_ERROR.toWebSocketCloseStatus("Noise encryption error");
default -> {
log.warn("An unexpected exception reached the end of the pipeline", cause);
yield WebSocketCloseStatus.INTERNAL_SERVER_ERROR;
@@ -51,6 +53,7 @@ class ErrorHandler extends ChannelInboundHandlerAdapter {
context.writeAndFlush(new CloseWebSocketFrame(webSocketCloseStatus))
.addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
} else {
log.debug("Error occurred before websocket handshake complete", cause);
// We haven't completed a websocket handshake, so we can't really communicate errors in a semantically-meaningful
// way; just close the connection instead.
context.close();
@@ -48,12 +48,12 @@ class EstablishLocalGrpcConnectionHandler extends ChannelInboundHandlerAdapter {
@Override
public void userEventTriggered(final ChannelHandlerContext remoteChannelContext, final Object event) {
if (event instanceof NoiseHandshakeCompleteEvent noiseHandshakeCompleteEvent) {
if (event instanceof NoiseIdentityDeterminedEvent noiseIdentityDeterminedEvent) {
// We assume that we'll only get a completed handshake event if the handshake met all authentication requirements
// for the requested service. If the handshake doesn't have an authenticated device, we assume we're trying to
// connect to the anonymous service. If it does have an authenticated device, we assume we're aiming for the
// authenticated service.
final LocalAddress grpcServerAddress = noiseHandshakeCompleteEvent.authenticatedDevice().isPresent()
final LocalAddress grpcServerAddress = noiseIdentityDeterminedEvent.authenticatedDevice().isPresent()
? authenticatedGrpcServerAddress
: anonymousGrpcServerAddress;
@@ -72,7 +72,7 @@ class EstablishLocalGrpcConnectionHandler extends ChannelInboundHandlerAdapter {
if (localChannelFuture.isSuccess()) {
clientConnectionManager.handleConnectionEstablished((LocalChannel) localChannelFuture.channel(),
remoteChannelContext.channel(),
noiseHandshakeCompleteEvent.authenticatedDevice());
noiseIdentityDeterminedEvent.authenticatedDevice());
// Close the local connection if the remote channel closes and vice versa
remoteChannelContext.channel().closeFuture().addListener(closeFuture -> localChannelFuture.channel().close());
@@ -0,0 +1,21 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc.net;
enum HandshakePattern {
NK("Noise_NK_25519_ChaChaPoly_BLAKE2b"),
IK("Noise_IK_25519_ChaChaPoly_BLAKE2b");
private final String protocol;
public String protocol() {
return protocol;
}
HandshakePattern(String protocol) {
this.protocol = protocol;
}
}
@@ -0,0 +1,34 @@
package org.whispersystems.textsecuregcm.grpc.net;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
/**
* A NoiseAnonymousHandler is a netty pipeline element that handles the responder side of an unauthenticated handshake
* and noise encryption/decryption.
* <p>
* A noise NK handshake must be used for unauthenticated connections. Optionally, the initiator can also include an
* initial request in their payload. If provided, this allows the server to begin processing the request without an
* initial message delay (fast open).
* <p>
* Once the handler receives the handshake initiator message, it will fire a {@link NoiseIdentityDeterminedEvent}
* indicating that initiator connected anonymously.
*/
class NoiseAnonymousHandler extends NoiseHandler {
public NoiseAnonymousHandler(final ECKeyPair ecKeyPair) {
super(new NoiseHandshakeHelper(HandshakePattern.NK, ecKeyPair));
}
@Override
CompletableFuture<HandshakeResult> handleHandshakePayload(final ChannelHandlerContext context,
final Optional<byte[]> initiatorPublicKey, final ByteBuf handshakePayload) {
return CompletableFuture.completedFuture(new HandshakeResult(
handshakePayload,
Optional.empty()
));
}
}
@@ -0,0 +1,96 @@
package org.whispersystems.textsecuregcm.grpc.net;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;
import java.security.MessageDigest;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.storage.ClientPublicKeysManager;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
/**
* A NoiseAuthenticatedHandler is a netty pipeline element that handles the responder side of an authenticated handshake
* and noise encryption/decryption. Authenticated handshakes are noise IK handshakes where the initiator's static public
* key is authenticated by the responder.
* <p>
* The authenticated handshake requires the initiator to provide a payload with their first handshake message that
* includes their account identifier and device id in network byte-order. Optionally, the initiator can also include an
* initial request in their payload. If provided, this allows the server to begin processing the request without an
* initial message delay (fast open).
* <pre>
* +-----------------+----------------+------------------------+
* | UUID (16) | deviceId (1) | request bytes (N) |
* +-----------------+----------------+------------------------+
* </pre>
* <p>
* For a successful handshake, the static key provided in the handshake message must match the server's stored public
* key for the device identified by the provided ACI and deviceId.
* <p>
* As soon as the handler authenticates the caller, it will fire a {@link NoiseIdentityDeterminedEvent}.
*/
class NoiseAuthenticatedHandler extends NoiseHandler {
private final ClientPublicKeysManager clientPublicKeysManager;
NoiseAuthenticatedHandler(final ClientPublicKeysManager clientPublicKeysManager,
final ECKeyPair ecKeyPair) {
super(new NoiseHandshakeHelper(HandshakePattern.IK, ecKeyPair));
this.clientPublicKeysManager = clientPublicKeysManager;
}
@Override
CompletableFuture<HandshakeResult> handleHandshakePayload(
final ChannelHandlerContext context,
final Optional<byte[]> initiatorPublicKey,
final ByteBuf handshakePayload) throws NoiseHandshakeException {
if (handshakePayload.readableBytes() < 17) {
throw new NoiseHandshakeException("Invalid handshake payload");
}
final byte[] publicKeyFromClient = initiatorPublicKey
.orElseThrow(() -> new IllegalStateException("No remote public key"));
// Advances the read index by 16 bytes
final UUID accountIdentifier = parseUUID(handshakePayload);
// Advances the read index by 1 byte
final byte deviceId = handshakePayload.readByte();
final ByteBuf fastOpenRequest = handshakePayload.slice();
return clientPublicKeysManager
.findPublicKey(accountIdentifier, deviceId)
.handleAsync((storedPublicKey, throwable) -> {
if (throwable != null) {
ReferenceCountUtil.release(fastOpenRequest);
throw ExceptionUtils.wrap(throwable);
}
final boolean valid = storedPublicKey
.map(spk -> MessageDigest.isEqual(publicKeyFromClient, spk.getPublicKeyBytes()))
.orElse(false);
if (!valid) {
throw ExceptionUtils.wrap(new ClientAuthenticationException());
}
return new HandshakeResult(
fastOpenRequest,
Optional.of(new AuthenticatedDevice(accountIdentifier, deviceId)));
}, context.executor());
}
/**
* Parse a {@link UUID} out of bytes, advancing the readerIdx by 16
*
* @param bytes The {@link ByteBuf} to read from
* @return The parsed UUID
* @throws NoiseHandshakeException If a UUID could not be parsed from bytes
*/
private UUID parseUUID(final ByteBuf bytes) throws NoiseHandshakeException {
if (bytes.readableBytes() < 16) {
throw new NoiseHandshakeException("Could not parse account identifier");
}
return new UUID(bytes.readLong(), bytes.readLong());
}
}
@@ -0,0 +1,11 @@
package org.whispersystems.textsecuregcm.grpc.net;
/**
* Indicates that some problem occurred while processing an encrypted noise message (e.g. an unexpected message size/
* format or a general encryption error).
*/
class NoiseException extends Exception {
public NoiseException(final String message) {
super(message);
}
}
@@ -0,0 +1,211 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc.net;
import com.southernstorm.noise.protocol.CipherState;
import com.southernstorm.noise.protocol.CipherStatePair;
import com.southernstorm.noise.protocol.Noise;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.PromiseCombiner;
import io.netty.util.internal.EmptyArrays;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import javax.crypto.BadPaddingException;
import javax.crypto.ShortBufferException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
/**
* A bidirectional {@link io.netty.channel.ChannelHandler} that establishes a noise session with an initiator, decrypts
* inbound messages, and encrypts outbound messages
*/
abstract class NoiseHandler extends ChannelDuplexHandler {
private static final Logger log = LoggerFactory.getLogger(NoiseHandler.class);
private enum State {
// Waiting for handshake to complete
HANDSHAKE,
// Can freely exchange encrypted noise messages on an established session
TRANSPORT,
// Finished with error
ERROR
}
private final NoiseHandshakeHelper handshakeHelper;
private State state = State.HANDSHAKE;
private CipherStatePair cipherStatePair;
NoiseHandler(NoiseHandshakeHelper handshakeHelper) {
this.handshakeHelper = handshakeHelper;
}
/**
* The result of processing an initiator handshake payload
*
* @param fastOpenRequest A fast-open request included in the handshake. If none was present, this should be an
* empty ByteBuf
* @param authenticatedDevice If present, the successfully authenticated initiator identity
*/
record HandshakeResult(ByteBuf fastOpenRequest, Optional<AuthenticatedDevice> authenticatedDevice) {}
/**
* Parse and potentially authenticate the initiator handshake message
*
* @param context A {@link ChannelHandlerContext}
* @param initiatorPublicKey The initiator's static public key, if a handshake pattern that includes it was used
* @param handshakePayload The handshake payload provided in the initiator message
* @return A {@link HandshakeResult} that includes an authenticated device and a parsed fast-open request if one was
* present in the handshake payload.
* @throws NoiseHandshakeException If the handshake payload was invalid
* @throws ClientAuthenticationException If the initiatorPublicKey could not be authenticated
*/
abstract CompletableFuture<HandshakeResult> handleHandshakePayload(
final ChannelHandlerContext context,
final Optional<byte[]> initiatorPublicKey,
final ByteBuf handshakePayload) throws NoiseHandshakeException, ClientAuthenticationException;
@Override
public void channelRead(final ChannelHandlerContext context, final Object message) throws Exception {
try {
if (message instanceof BinaryWebSocketFrame frame) {
if (frame.content().readableBytes() > Noise.MAX_PACKET_LEN) {
final String error = "Invalid noise message length " + frame.content().readableBytes();
throw state == State.HANDSHAKE ? new NoiseHandshakeException(error) : new NoiseException(error);
}
// We've read this frame off the wire, and so it's most likely a direct buffer that's not backed by an array.
// We'll need to copy it to a heap buffer.
handleInboundMessage(context, ByteBufUtil.getBytes(frame.content()));
} else {
// Anything except binary WebSocket frames should have been filtered out of the pipeline by now; treat this as an
// error
throw new IllegalArgumentException("Unexpected message in pipeline: " + message);
}
} catch (Exception e) {
fail(context, e);
} finally {
ReferenceCountUtil.release(message);
}
}
private void handleInboundMessage(final ChannelHandlerContext context, final byte[] frameBytes)
throws NoiseHandshakeException, ShortBufferException, BadPaddingException, ClientAuthenticationException {
switch (state) {
// Got an initiator handshake message
case HANDSHAKE -> {
final ByteBuf payload = handshakeHelper.read(frameBytes);
handleHandshakePayload(context, handshakeHelper.remotePublicKey(), payload).whenCompleteAsync(
(result, throwable) -> {
if (state == State.ERROR) {
return;
}
if (throwable != null) {
fail(context, ExceptionUtils.unwrap(throwable));
return;
}
context.fireUserEventTriggered(new NoiseIdentityDeterminedEvent(result.authenticatedDevice()));
// Now that we've authenticated, write the handshake response
byte[] handshakeMessage = handshakeHelper.write(EmptyArrays.EMPTY_BYTES);
context.writeAndFlush(new BinaryWebSocketFrame(Unpooled.wrappedBuffer(handshakeMessage)))
.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
// The handshake is complete. We can start intercepting read/write for noise encryption/decryption
this.state = State.TRANSPORT;
this.cipherStatePair = handshakeHelper.getHandshakeState().split();
if (result.fastOpenRequest().isReadable()) {
// The handshake had a fast-open request. Forward the plaintext of the request to the server, we'll
// encrypt the response when the server writes back through us
context.fireChannelRead(result.fastOpenRequest());
} else {
ReferenceCountUtil.release(result.fastOpenRequest());
}
}, context.executor());
}
// Got a client message that should be decrypted and forwarded
case TRANSPORT -> {
final CipherState cipherState = cipherStatePair.getReceiver();
// Overwrite the ciphertext with the plaintext to avoid an extra allocation for a dedicated plaintext buffer
final int plaintextLength = cipherState.decryptWithAd(null,
frameBytes, 0,
frameBytes, 0,
frameBytes.length);
// Forward the decrypted plaintext along
context.fireChannelRead(Unpooled.wrappedBuffer(frameBytes, 0, plaintextLength));
}
// The session is already in an error state, drop the message
case ERROR -> {
}
}
}
/**
* Set the state to the error state (so subsequent messages fast-fail) and propagate the failure reason on the
* context
*/
private void fail(final ChannelHandlerContext context, final Throwable cause) {
this.state = State.ERROR;
context.fireExceptionCaught(cause);
}
@Override
public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise promise)
throws Exception {
if (message instanceof ByteBuf byteBuf) {
try {
// TODO Buffer/consolidate Noise writes to avoid sending a bazillion tiny (or empty) frames
final CipherState cipherState = cipherStatePair.getSender();
// Server message might not fit in a single noise packet, break it up into as many chunks as we need
final PromiseCombiner pc = new PromiseCombiner(context.executor());
while (byteBuf.isReadable()) {
final ByteBuf plaintext = byteBuf.readSlice(Math.min(
// need room for a 16-byte AEAD tag
Noise.MAX_PACKET_LEN - 16,
byteBuf.readableBytes()));
final int plaintextLength = plaintext.readableBytes();
// We've read these bytes from a local connection; although that likely means they're backed by a heap array, the
// buffer is read-only and won't grant us access to the underlying array. Instead, we need to copy the bytes to a
// mutable array. We also want to encrypt in place, so we allocate enough extra space for the trailing MAC.
final byte[] noiseBuffer = new byte[plaintext.readableBytes() + cipherState.getMACLength()];
plaintext.readBytes(noiseBuffer, 0, plaintext.readableBytes());
// Overwrite the plaintext with the ciphertext to avoid an extra allocation for a dedicated ciphertext buffer
cipherState.encryptWithAd(null, noiseBuffer, 0, noiseBuffer, 0, plaintextLength);
pc.add(context.write(new BinaryWebSocketFrame(Unpooled.wrappedBuffer(noiseBuffer))));
}
pc.finish(promise);
} finally {
ReferenceCountUtil.release(byteBuf);
}
} else {
if (!(message instanceof WebSocketFrame)) {
// Downstream handlers may write WebSocket frames that don't need to be encrypted (e.g. "close" frames that
// get issued in response to exceptions)
log.warn("Unexpected object in pipeline: {}", message);
}
context.write(message, promise);
}
}
}
@@ -1,13 +0,0 @@
package org.whispersystems.textsecuregcm.grpc.net;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import java.util.Optional;
/**
* An event that indicates that a Noise handshake has completed, possibly authenticating a caller in the process.
*
* @param authenticatedDevice the device authenticated as part of the handshake, or empty if the handshake was not of a
* type that performs authentication
*/
record NoiseHandshakeCompleteEvent(Optional<AuthenticatedDevice> authenticatedDevice) {
}
@@ -0,0 +1,124 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc.net;
import com.southernstorm.noise.protocol.HandshakeState;
import com.southernstorm.noise.protocol.Noise;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.security.NoSuchAlgorithmException;
import java.util.Optional;
import javax.crypto.BadPaddingException;
import javax.crypto.ShortBufferException;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
/**
* Helper for the responder of a 2-message handshake with a pre-shared responder static key
*/
class NoiseHandshakeHelper {
private final static int AEAD_TAG_LENGTH = 16;
private final static int KEY_LENGTH = 32;
private final HandshakePattern handshakePattern;
private final ECKeyPair serverStaticKeyPair;
private final HandshakeState handshakeState;
NoiseHandshakeHelper(HandshakePattern handshakePattern, ECKeyPair serverStaticKeyPair) {
this.handshakePattern = handshakePattern;
this.serverStaticKeyPair = serverStaticKeyPair;
try {
this.handshakeState = new HandshakeState(handshakePattern.protocol(), HandshakeState.RESPONDER);
} catch (final NoSuchAlgorithmException e) {
throw new AssertionError("Unsupported Noise algorithm: " + handshakePattern.protocol(), e);
}
}
/**
* Get the length of the initiator's keys
*
* @return length of the handshake message sent by the remote party (the initiator) not including the payload
*/
private int initiatorHandshakeMessageKeyLength() {
return switch (handshakePattern) {
// ephemeral key, static key (encrypted), AEAD tag for static key
case IK -> KEY_LENGTH + KEY_LENGTH + AEAD_TAG_LENGTH;
// ephemeral key only
case NK -> KEY_LENGTH;
};
}
HandshakeState getHandshakeState() {
return this.handshakeState;
}
ByteBuf read(byte[] remoteHandshakeMessage) throws NoiseHandshakeException {
if (handshakeState.getAction() != HandshakeState.NO_ACTION) {
throw new NoiseHandshakeException("Cannot send more data before handshake is complete");
}
// Length for an empty payload
final int minMessageLength = initiatorHandshakeMessageKeyLength() + AEAD_TAG_LENGTH;
if (remoteHandshakeMessage.length < minMessageLength || remoteHandshakeMessage.length > Noise.MAX_PACKET_LEN) {
throw new NoiseHandshakeException("Unexpected ephemeral key message length");
}
final int payloadLength = remoteHandshakeMessage.length - initiatorHandshakeMessageKeyLength() - AEAD_TAG_LENGTH;
// Cryptographically initializing a handshake is expensive, and so we defer it until we're confident the client is
// making a good-faith effort to perform a handshake (i.e. now). Noise-java in particular will derive a public key
// from the supplied private key (and will in fact overwrite any previously-set public key when setting a private
// key), so we just set the private key here.
handshakeState.getLocalKeyPair().setPrivateKey(serverStaticKeyPair.getPrivateKey().serialize(), 0);
handshakeState.start();
int payloadBytesRead;
try {
payloadBytesRead = handshakeState.readMessage(remoteHandshakeMessage, 0, remoteHandshakeMessage.length,
remoteHandshakeMessage, 0);
} catch (final ShortBufferException e) {
// This should never happen since we're checking the length of the frame up front
throw new NoiseHandshakeException("Unexpected client payload");
} catch (final BadPaddingException e) {
// We aren't using padding but may get this error if the AEAD tag does not match the encrypted client static key
// or payload
throw new NoiseHandshakeException("Invalid keys or payload");
}
if (payloadBytesRead != payloadLength) {
throw new NoiseHandshakeException(
"Unexpected payload length, required " + payloadLength + " but got " + payloadBytesRead);
}
return Unpooled.wrappedBuffer(remoteHandshakeMessage, 0, payloadBytesRead);
}
byte[] write(byte[] payload) {
if (handshakeState.getAction() != HandshakeState.WRITE_MESSAGE) {
throw new IllegalStateException("Cannot send data before handshake is complete");
}
// Currently only support handshake patterns where the server static key is known
// Send our ephemeral key and the response to the initiator with the encrypted payload
final byte[] response = new byte[KEY_LENGTH + payload.length + AEAD_TAG_LENGTH];
try {
int written = handshakeState.writeMessage(response, 0, payload, 0, payload.length);
if (written != response.length) {
throw new IllegalStateException("Unexpected handshake response length");
}
return response;
} catch (final ShortBufferException e) {
// This should never happen for messages of known length that we control
throw new IllegalStateException("Key material buffer was too short for message", e);
}
}
Optional<byte[]> remotePublicKey() {
return Optional.ofNullable(handshakeState.getRemotePublicKey()).map(dhstate -> {
final byte[] publicKeyFromClient = new byte[handshakeState.getRemotePublicKey().getPublicKeyLength()];
handshakeState.getRemotePublicKey().getPublicKey(publicKeyFromClient, 0);
return publicKeyFromClient;
});
}
}
@@ -0,0 +1,13 @@
package org.whispersystems.textsecuregcm.grpc.net;
import java.util.Optional;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
/**
* An event that indicates that an identity of a noise handshake initiator has been determined. If the initiator is
* connecting anonymously, the identity is empty, otherwise it will be present and already authenticated.
*
* @param authenticatedDevice the device authenticated as part of the handshake, or empty if the handshake was not of a
* type that performs authentication
*/
record NoiseIdentityDeterminedEvent(Optional<AuthenticatedDevice> authenticatedDevice) {}
@@ -1,40 +0,0 @@
package org.whispersystems.textsecuregcm.grpc.net;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import java.util.Optional;
import io.netty.util.ReferenceCountUtil;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
/**
* A Noise NX handler handles the responder side of a Noise NX handshake.
*/
class NoiseNXHandshakeHandler extends AbstractNoiseHandshakeHandler {
static final String NOISE_PROTOCOL_NAME = "Noise_NX_25519_ChaChaPoly_BLAKE2b";
NoiseNXHandshakeHandler(final ECKeyPair ecKeyPair, final byte[] publicKeySignature) {
super(NOISE_PROTOCOL_NAME, ecKeyPair, publicKeySignature);
}
@Override
public void channelRead(final ChannelHandlerContext context, final Object message) throws Exception {
if (message instanceof BinaryWebSocketFrame frame) {
try {
handleEphemeralKeyMessage(context, frame);
} finally {
frame.release();
}
// All we need to do is accept the client's ephemeral key and send our own static keys; after that, we can consider
// the handshake complete
context.fireUserEventTriggered(new NoiseHandshakeCompleteEvent(Optional.empty()));
context.pipeline().replace(NoiseNXHandshakeHandler.this, null, new NoiseTransportHandler(getHandshakeState().split()));
} else {
// Anything except binary WebSocket frames should have been filtered out of the pipeline by now; treat this as an
// error
ReferenceCountUtil.release(message);
throw new IllegalArgumentException("Unexpected message in pipeline: " + message);
}
}
}
@@ -53,7 +53,6 @@ public class NoiseWebSocketTunnelServer implements Managed {
final ClientConnectionManager clientConnectionManager,
final ClientPublicKeysManager clientPublicKeysManager,
final ECKeyPair ecKeyPair,
final byte[] publicKeySignature,
final LocalAddress authenticatedGrpcServerAddress,
final LocalAddress anonymousGrpcServerAddress,
final String recognizedProxySecret) throws SSLException {
@@ -107,7 +106,7 @@ public class NoiseWebSocketTunnelServer implements Managed {
.addLast(new RejectUnsupportedMessagesHandler())
// The WebSocket handshake complete listener will replace itself with an appropriate Noise handshake handler once
// a WebSocket handshake has been completed
.addLast(new WebsocketHandshakeCompleteHandler(clientPublicKeysManager, ecKeyPair, publicKeySignature, recognizedProxySecret))
.addLast(new WebsocketHandshakeCompleteHandler(clientPublicKeysManager, ecKeyPair, recognizedProxySecret))
// This handler will open a local connection to the appropriate gRPC server and install a ProxyHandler
// once the Noise handshake has completed
.addLast(new EstablishLocalGrpcConnectionHandler(clientConnectionManager, authenticatedGrpcServerAddress, anonymousGrpcServerAddress))
@@ -1,178 +0,0 @@
package org.whispersystems.textsecuregcm.grpc.net;
import com.southernstorm.noise.protocol.HandshakeState;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.util.ReferenceCountUtil;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import javax.crypto.BadPaddingException;
import javax.crypto.ShortBufferException;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.storage.ClientPublicKeysManager;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
/**
* A Noise XX handler handles the responder side of a Noise XX handshake. This implementation expects clients to send
* identifying information (an account identifier and device ID) as an additional payload when sending its static key
* material. It compares the static public key against the stored public key for the identified device asynchronously,
* buffering traffic from the client until the authentication check completes.
*/
class NoiseXXHandshakeHandler extends AbstractNoiseHandshakeHandler {
private final ClientPublicKeysManager clientPublicKeysManager;
private AuthenticationState authenticationState = AuthenticationState.GET_EPHEMERAL_KEY;
private final List<BinaryWebSocketFrame> pendingInboundFrames = new ArrayList<>();
static final String NOISE_PROTOCOL_NAME = "Noise_XX_25519_ChaChaPoly_BLAKE2b";
// When the client sends its static key message, we expect:
//
// - A 32-byte encrypted static public key
// - A 16-byte AEAD tag for the static key
// - 17 bytes of identity data in the message payload (a UUID and a one-byte device ID)
// - A 16-byte AEAD tag for the identity payload
private static final int EXPECTED_CLIENT_STATIC_KEY_MESSAGE_LENGTH = 81;
private enum AuthenticationState {
GET_EPHEMERAL_KEY,
GET_STATIC_KEY,
CHECK_PUBLIC_KEY,
ERROR
}
public NoiseXXHandshakeHandler(final ClientPublicKeysManager clientPublicKeysManager,
final ECKeyPair ecKeyPair,
final byte[] publicKeySignature) {
super(NOISE_PROTOCOL_NAME, ecKeyPair, publicKeySignature);
this.clientPublicKeysManager = clientPublicKeysManager;
}
@Override
public void channelRead(final ChannelHandlerContext context, final Object message) throws Exception {
if (message instanceof BinaryWebSocketFrame frame) {
try {
switch (authenticationState) {
case GET_EPHEMERAL_KEY -> {
try {
handleEphemeralKeyMessage(context, frame);
authenticationState = AuthenticationState.GET_STATIC_KEY;
} finally {
frame.release();
}
}
case GET_STATIC_KEY -> {
try {
handleStaticKey(context, frame);
authenticationState = AuthenticationState.CHECK_PUBLIC_KEY;
} finally {
frame.release();
}
}
case CHECK_PUBLIC_KEY -> {
// Buffer any inbound traffic until we've finished checking the client's public key
pendingInboundFrames.add(frame);
}
case ERROR -> {
// If authentication has failed for any reason, just discard inbound traffic until the channel closes
frame.release();
}
}
} catch (final ShortBufferException e) {
authenticationState = AuthenticationState.ERROR;
throw new NoiseHandshakeException("Unexpected payload length");
} catch (final BadPaddingException e) {
authenticationState = AuthenticationState.ERROR;
throw new ClientAuthenticationException();
}
} else {
// Anything except binary WebSocket frames should have been filtered out of the pipeline by now; treat this as an
// error
ReferenceCountUtil.release(message);
throw new IllegalArgumentException("Unexpected message in pipeline: " + message);
}
}
private void handleStaticKey(final ChannelHandlerContext context, final BinaryWebSocketFrame frame)
throws NoiseHandshakeException, ShortBufferException, BadPaddingException {
if (frame.content().readableBytes() != EXPECTED_CLIENT_STATIC_KEY_MESSAGE_LENGTH) {
throw new NoiseHandshakeException("Unexpected client static key message length");
}
final HandshakeState handshakeState = getHandshakeState();
// The websocket frame will have come right off the wire, and so needs to be copied from a non-array-backed direct
// buffer into a heap buffer.
final byte[] staticKeyAndClientIdentityMessage = ByteBufUtil.getBytes(frame.content());
// The payload from the client should be a UUID (16 bytes) followed by a device ID (1 byte)
final byte[] payload = new byte[17];
final UUID accountIdentifier;
final byte deviceId;
final int payloadBytesRead = handshakeState.readMessage(staticKeyAndClientIdentityMessage,
0, staticKeyAndClientIdentityMessage.length, payload, 0);
if (payloadBytesRead != 17) {
throw new NoiseHandshakeException("Unexpected identity payload length");
}
try {
accountIdentifier = UUIDUtil.fromBytes(payload, 0);
} catch (final IllegalArgumentException e) {
throw new NoiseHandshakeException("Could not parse account identifier");
}
deviceId = payload[16];
// Verify the identity of the caller by comparing the submitted static public key against the stored public key for
// the identified device
clientPublicKeysManager.findPublicKey(accountIdentifier, deviceId)
.whenCompleteAsync((maybePublicKey, throwable) -> maybePublicKey.ifPresentOrElse(storedPublicKey -> {
final byte[] publicKeyFromClient = new byte[handshakeState.getRemotePublicKey().getPublicKeyLength()];
handshakeState.getRemotePublicKey().getPublicKey(publicKeyFromClient, 0);
if (MessageDigest.isEqual(publicKeyFromClient, storedPublicKey.getPublicKeyBytes())) {
context.fireUserEventTriggered(new NoiseHandshakeCompleteEvent(
Optional.of(new AuthenticatedDevice(accountIdentifier, deviceId))));
context.pipeline().addAfter(context.name(), null, new NoiseTransportHandler(handshakeState.split()));
// Flush any buffered reads
pendingInboundFrames.forEach(context::fireChannelRead);
pendingInboundFrames.clear();
context.pipeline().remove(NoiseXXHandshakeHandler.this);
} else {
// We found a key, but it doesn't match what the caller submitted
context.fireExceptionCaught(new ClientAuthenticationException());
authenticationState = AuthenticationState.ERROR;
}
},
() -> {
// We couldn't find a key for the identified account/device
context.fireExceptionCaught(new ClientAuthenticationException());
authenticationState = AuthenticationState.ERROR;
}),
context.executor());
}
@Override
public void handlerRemoved(final ChannelHandlerContext context) {
super.handlerRemoved(context);
pendingInboundFrames.forEach(BinaryWebSocketFrame::release);
pendingInboundFrames.clear();
}
}
@@ -31,7 +31,6 @@ class WebsocketHandshakeCompleteHandler extends ChannelInboundHandlerAdapter {
private final ClientPublicKeysManager clientPublicKeysManager;
private final ECKeyPair ecKeyPair;
private final byte[] publicKeySignature;
private final byte[] recognizedProxySecret;
@@ -45,12 +44,10 @@ class WebsocketHandshakeCompleteHandler extends ChannelInboundHandlerAdapter {
WebsocketHandshakeCompleteHandler(final ClientPublicKeysManager clientPublicKeysManager,
final ECKeyPair ecKeyPair,
final byte[] publicKeySignature,
final String recognizedProxySecret) {
this.clientPublicKeysManager = clientPublicKeysManager;
this.ecKeyPair = ecKeyPair;
this.publicKeySignature = publicKeySignature;
// The recognized proxy secret is an arbitrary string, and not an encoded byte sequence (i.e. a base64- or hex-
// encoded value). We convert it into a byte array here for easier constant-time comparisons via
@@ -84,10 +81,10 @@ class WebsocketHandshakeCompleteHandler extends ChannelInboundHandlerAdapter {
final ChannelHandler noiseHandshakeHandler = switch (handshakeCompleteEvent.requestUri()) {
case NoiseWebSocketTunnelServer.AUTHENTICATED_SERVICE_PATH ->
new NoiseXXHandshakeHandler(clientPublicKeysManager, ecKeyPair, publicKeySignature);
new NoiseAuthenticatedHandler(clientPublicKeysManager, ecKeyPair);
case NoiseWebSocketTunnelServer.ANONYMOUS_SERVICE_PATH ->
new NoiseNXHandshakeHandler(ecKeyPair, publicKeySignature);
new NoiseAnonymousHandler(ecKeyPair);
default -> {
// The WebSocketOpeningHandshakeHandler should have caught all of these cases already; we'll consider it an
@@ -13,7 +13,7 @@ public class RateLimitChallengeOptionManager {
private final RateLimiters rateLimiters;
public static final String OPTION_CAPTCHA = "recaptcha";
public static final String OPTION_CAPTCHA = "captcha";
public static final String OPTION_PUSH_CHALLENGE = "pushChallenge";
public RateLimitChallengeOptionManager(final RateLimiters rateLimiters) {
@@ -18,8 +18,6 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
public enum For implements RateLimiterDescriptor {
BACKUP_AUTH_CHECK("backupAuthCheck", false, new RateLimiterConfig(100, Duration.ofMinutes(15))),
SMS_DESTINATION("smsDestination", false, new RateLimiterConfig(2, Duration.ofSeconds(30))),
VERIFY("verify", false, new RateLimiterConfig(6, Duration.ofSeconds(30))),
PIN("pin", false, new RateLimiterConfig(10, Duration.ofDays(1))),
ATTACHMENT("attachmentCreate", false, new RateLimiterConfig(50, Duration.ofMillis(1200))),
BACKUP_ATTACHMENT("backupAttachmentCreate", true, new RateLimiterConfig(10_000, Duration.ofSeconds(1))),
@@ -118,14 +116,6 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
return forDescriptor(For.ATTACHMENT);
}
public RateLimiter getSmsDestinationLimiter() {
return forDescriptor(For.SMS_DESTINATION);
}
public RateLimiter getVerifyLimiter() {
return forDescriptor(For.VERIFY);
}
public RateLimiter getPinLimiter() {
return forDescriptor(For.PIN);
}
@@ -70,12 +70,14 @@ public final class MessageMetrics {
public void measureOutgoingMessageLatency(final long serverTimestamp,
final String channel,
final boolean isPrimaryDevice,
final String userAgent,
final ClientReleaseManager clientReleaseManager) {
final List<Tag> tags = new ArrayList<>(3);
final List<Tag> tags = new ArrayList<>(4);
tags.add(UserAgentTagUtil.getPlatformTag(userAgent));
tags.add(Tag.of("channel", channel));
tags.add(Tag.of("isPrimary", String.valueOf(isPrimaryDevice)));
UserAgentTagUtil.getClientVersionTag(userAgent, clientReleaseManager).ifPresent(tags::add);
@@ -22,7 +22,6 @@ import io.micrometer.statsd.StatsdMeterRegistry;
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
import org.whispersystems.textsecuregcm.WhisperServerVersion;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.push.PushLatencyManager;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.util.Constants;
@@ -30,6 +29,8 @@ public class MetricsUtil {
public static final String PREFIX = "chat";
private static volatile boolean registeredMetrics = false;
/**
* Returns a dot-separated ('.') name for the given class and name parts
*/
@@ -48,6 +49,13 @@ public class MetricsUtil {
public static void configureRegistries(final WhisperServerConfiguration config, final Environment environment,
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
if (registeredMetrics) {
throw new IllegalStateException("Metric registries configured more than once");
}
registeredMetrics = true;
SharedMetricRegistries.add(Constants.METRICS_NAME, environment.metrics());
{
@@ -100,7 +108,6 @@ public class MetricsUtil {
return MeterFilter.super.map(id);
}
})
.meterFilter(MeterFilter.denyNameStartsWith(PushLatencyManager.TIMER_NAME + ".percentile"))
.meterFilter(MeterFilter.denyNameStartsWith(MessageMetrics.DELIVERY_LATENCY_TIMER_NAME + ".percentile"));
}
@@ -5,7 +5,11 @@
package org.whispersystems.textsecuregcm.providers;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import io.dropwizard.util.DataSizeUnit;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
@@ -18,9 +22,9 @@ import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.NoContentException;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
import org.signal.libsignal.protocol.InvalidMessageException;
import org.signal.libsignal.protocol.InvalidVersionException;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
@Provider
@Consumes(MultiRecipientMessageProvider.MEDIA_TYPE)
@@ -30,6 +34,11 @@ public class MultiRecipientMessageProvider implements MessageBodyReader<SealedSe
public static final int MAX_RECIPIENT_COUNT = 5000;
public static final int MAX_MESSAGE_SIZE = Math.toIntExact(32 + DataSizeUnit.KIBIBYTES.toBytes(256));
private static final DistributionSummary RECIPIENT_COUNT_DISTRIBUTION = DistributionSummary
.builder(name(MultiRecipientMessageProvider.class, "recipients"))
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry);
@Override
public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return MEDIA_TYPE.equals(mediaType.toString()) && SealedSenderMultiRecipientMessage.class.isAssignableFrom(type);
@@ -46,6 +55,8 @@ public class MultiRecipientMessageProvider implements MessageBodyReader<SealedSe
try {
final SealedSenderMultiRecipientMessage message = SealedSenderMultiRecipientMessage.parse(fullMessage);
RECIPIENT_COUNT_DISTRIBUTION.record(message.getRecipients().keySet().size());
if (message.getRecipients().values().stream().anyMatch(r -> message.messageSizeForRecipient(r) > MAX_MESSAGE_SIZE)) {
throw new BadRequestException("message payload too large");
}
@@ -23,6 +23,7 @@ import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import org.whispersystems.textsecuregcm.configuration.ApnConfiguration;
@@ -156,20 +157,21 @@ public class APNSender implements Managed, PushNotificationSender {
})
.thenApplyAsync(response -> {
final boolean accepted;
final String rejectionReason;
final Optional<String> rejectionReason;
final boolean unregistered;
if (response.isAccepted()) {
accepted = true;
rejectionReason = null;
rejectionReason = Optional.empty();
unregistered = false;
} else {
accepted = false;
rejectionReason = response.getRejectionReason().orElse("unknown");
unregistered = ("Unregistered".equals(rejectionReason) || "BadDeviceToken".equals(rejectionReason));
rejectionReason = response.getRejectionReason();
unregistered = response.getRejectionReason().map(reason -> "Unregistered".equals(reason) || "BadDeviceToken".equals(reason) || "ExpiredToken".equals(reason))
.orElse(false);
}
return new SendPushNotificationResult(accepted, rejectionReason, unregistered);
return new SendPushNotificationResult(accepted, rejectionReason, unregistered, response.getTokenInvalidationTimestamp());
}, executor);
}
@@ -23,6 +23,7 @@ import io.micrometer.core.instrument.Timer;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
@@ -96,7 +97,7 @@ public class FcmSender implements PushNotificationSender {
return GoogleApiUtil.toCompletableFuture(firebaseMessagingClient.sendAsync(builder.build()), executor)
.whenComplete((ignored, throwable) -> sample.stop(SEND_NOTIFICATION_TIMER))
.thenApply(ignored -> new SendPushNotificationResult(true, null, false))
.thenApply(ignored -> new SendPushNotificationResult(true, Optional.empty(), false, Optional.empty()))
.exceptionally(throwable -> {
if (ExceptionUtils.unwrap(throwable) instanceof final FirebaseMessagingException firebaseMessagingException) {
final String errorCode;
@@ -111,7 +112,7 @@ public class FcmSender implements PushNotificationSender {
final boolean unregistered =
firebaseMessagingException.getMessagingErrorCode() == MessagingErrorCode.UNREGISTERED;
return new SendPushNotificationResult(false, errorCode, unregistered);
return new SendPushNotificationResult(false, Optional.of(errorCode), unregistered, Optional.empty());
} else {
throw ExceptionUtils.wrap(throwable);
}
@@ -0,0 +1,99 @@
package org.whispersystems.textsecuregcm.push;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.annotations.VisibleForTesting;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.scheduler.JobScheduler;
import org.whispersystems.textsecuregcm.scheduler.SchedulingUtil;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import javax.annotation.Nullable;
import java.io.IOException;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalTime;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
public class IdleDeviceNotificationScheduler extends JobScheduler {
private final AccountsManager accountsManager;
private final PushNotificationManager pushNotificationManager;
private final Clock clock;
@VisibleForTesting
static final Duration MIN_IDLE_DURATION = Duration.ofDays(14);
@VisibleForTesting
record AccountAndDeviceIdentifier(UUID accountIdentifier, byte deviceId) {}
public IdleDeviceNotificationScheduler(final AccountsManager accountsManager,
final PushNotificationManager pushNotificationManager,
final DynamoDbAsyncClient dynamoDbAsyncClient,
final String tableName,
final Duration jobExpiration,
final Clock clock) {
super(dynamoDbAsyncClient, tableName, jobExpiration, clock);
this.accountsManager = accountsManager;
this.pushNotificationManager = pushNotificationManager;
this.clock = clock;
}
@Override
public String getSchedulerName() {
return "IdleDeviceNotification";
}
@Override
protected CompletableFuture<String> processJob(@Nullable final byte[] jobData) {
final AccountAndDeviceIdentifier accountAndDeviceIdentifier;
try {
accountAndDeviceIdentifier = SystemMapper.jsonMapper().readValue(jobData, AccountAndDeviceIdentifier.class);
} catch (final IOException e) {
return CompletableFuture.failedFuture(e);
}
return accountsManager.getByAccountIdentifierAsync(accountAndDeviceIdentifier.accountIdentifier())
.thenCompose(maybeAccount -> maybeAccount.map(account ->
account.getDevice(accountAndDeviceIdentifier.deviceId()).map(device -> {
if (!isIdle(device)) {
return CompletableFuture.completedFuture("deviceSeenRecently");
}
try {
return pushNotificationManager
.sendNewMessageNotification(account, accountAndDeviceIdentifier.deviceId(), true)
.thenApply(ignored -> "sent");
} catch (final NotPushRegisteredException e) {
return CompletableFuture.completedFuture("deviceTokenDeleted");
}
})
.orElse(CompletableFuture.completedFuture("deviceDeleted")))
.orElse(CompletableFuture.completedFuture("accountDeleted")));
}
public boolean isIdle(final Device device) {
final Duration idleDuration = Duration.between(Instant.ofEpochMilli(device.getLastSeen()), clock.instant());
return idleDuration.compareTo(MIN_IDLE_DURATION) >= 0;
}
public CompletableFuture<Void> scheduleNotification(final Account account, final byte deviceId, final LocalTime preferredDeliveryTime) {
final Instant runAt = SchedulingUtil.getNextRecommendedNotificationTime(account, preferredDeliveryTime, clock);
try {
return scheduleJob(runAt, SystemMapper.jsonMapper().writeValueAsBytes(
new AccountAndDeviceIdentifier(account.getIdentifier(IdentityType.ACI), deviceId)));
} catch (final JsonProcessingException e) {
// This should never happen when serializing an `AccountAndDeviceIdentifier`
throw new AssertionError(e);
}
}
}
@@ -8,8 +8,6 @@ import static com.codahale.metrics.MetricRegistry.name;
import static org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
import io.micrometer.core.instrument.Metrics;
import org.apache.commons.lang3.StringUtils;
import org.whispersystems.textsecuregcm.redis.RedisOperation;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
@@ -32,7 +30,6 @@ public class MessageSender {
private final ClientPresenceManager clientPresenceManager;
private final MessagesManager messagesManager;
private final PushNotificationManager pushNotificationManager;
private final PushLatencyManager pushLatencyManager;
private static final String SEND_COUNTER_NAME = name(MessageSender.class, "sendMessage");
private static final String CHANNEL_TAG_NAME = "channel";
@@ -41,20 +38,17 @@ public class MessageSender {
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 HAS_SPAM_REPORTING_TOKEN_TAG_NAME = "hasSpamReportingToken";
public MessageSender(ClientPresenceManager clientPresenceManager,
MessagesManager messagesManager,
PushNotificationManager pushNotificationManager,
PushLatencyManager pushLatencyManager) {
public MessageSender(final ClientPresenceManager clientPresenceManager,
final MessagesManager messagesManager,
final PushNotificationManager pushNotificationManager) {
this.clientPresenceManager = clientPresenceManager;
this.messagesManager = messagesManager;
this.pushNotificationManager = pushNotificationManager;
this.pushLatencyManager = pushLatencyManager;
}
public void sendMessage(final Account account, final Device device, final Envelope message, final boolean online)
throws NotPushRegisteredException {
public void sendMessage(final Account account, final Device device, final Envelope message, final boolean online) {
final String channel;
@@ -65,7 +59,7 @@ public class MessageSender {
} else if (device.getFetchesMessages()) {
channel = "websocket";
} else {
throw new AssertionError();
channel = "none";
}
final boolean clientPresent;
@@ -87,13 +81,7 @@ public class MessageSender {
if (!clientPresent) {
try {
pushNotificationManager.sendNewMessageNotification(account, device.getId(), message.getUrgent());
final boolean useVoip = StringUtils.isNotBlank(device.getVoipApnId());
RedisOperation.unchecked(() -> pushLatencyManager.recordPushSent(account.getUuid(), device.getId(), useVoip, message.getUrgent()));
} catch (final NotPushRegisteredException e) {
if (!device.getFetchesMessages()) {
throw e;
}
} catch (final NotPushRegisteredException ignored) {
}
}
}
@@ -104,8 +92,7 @@ public class MessageSender {
CLIENT_ONLINE_TAG_NAME, String.valueOf(clientPresent),
URGENT_TAG_NAME, String.valueOf(message.getUrgent()),
STORY_TAG_NAME, String.valueOf(message.getStory()),
SEALED_SENDER_TAG_NAME, String.valueOf(!message.hasSourceUuid()),
HAS_SPAM_REPORTING_TOKEN_TAG_NAME, String.valueOf(message.getReportSpamToken() != null && !message.getReportSpamToken().isEmpty()))
SEALED_SENDER_TAG_NAME, String.valueOf(!message.hasSourceUuid()))
.increment();
}
}
@@ -1,147 +0,0 @@
/*
* Copyright 2013 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.push;
import com.codahale.metrics.MetricRegistry;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.annotations.VisibleForTesting;
import io.lettuce.core.SetArgs;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Timer;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import org.whispersystems.textsecuregcm.util.SystemMapper;
/**
* Measures and records the latency between sending a push notification to a device and that device draining its queue
* of messages.
* <p/>
* When the server sends a push notification to a device, the push latency manager creates a Redis key/value pair
* mapping the current timestamp to the given device if such a mapping doesn't already exist. When a client connects and
* clears its message queue, the push latency manager gets and clears the time of the initial push notification to that
* device and records the time elapsed since the push notification timestamp as a latency observation.
*/
public class PushLatencyManager {
private final FaultTolerantRedisCluster redisCluster;
private final ClientReleaseManager clientReleaseManager;
private final Clock clock;
public static final String TIMER_NAME = MetricRegistry.name(PushLatencyManager.class, "latency");
private static final int TTL = (int) Duration.ofDays(1).toSeconds();
private static final Logger log = LoggerFactory.getLogger(PushLatencyManager.class);
@VisibleForTesting
enum PushType {
STANDARD,
VOIP
}
record PushRecord(Instant timestamp, PushType pushType, Optional<Boolean> urgent) {
}
public PushLatencyManager(final FaultTolerantRedisCluster redisCluster,
final ClientReleaseManager clientReleaseManager) {
this(redisCluster, clientReleaseManager, Clock.systemUTC());
}
@VisibleForTesting
PushLatencyManager(final FaultTolerantRedisCluster redisCluster,
final ClientReleaseManager clientReleaseManager,
final Clock clock) {
this.redisCluster = redisCluster;
this.clientReleaseManager = clientReleaseManager;
this.clock = clock;
}
void recordPushSent(final UUID accountUuid, final byte deviceId, final boolean isVoip, final boolean isUrgent) {
try {
final String recordJson = SystemMapper.jsonMapper().writeValueAsString(
new PushRecord(Instant.now(clock), isVoip ? PushType.VOIP : PushType.STANDARD, Optional.of(isUrgent)));
redisCluster.useCluster(connection ->
connection.async().set(getFirstUnacknowledgedPushKey(accountUuid, deviceId),
recordJson,
SetArgs.Builder.nx().ex(TTL)));
} catch (final JsonProcessingException e) {
// This should never happen
log.error("Failed to write push latency record JSON", e);
}
}
void recordQueueRead(final UUID accountUuid, final byte deviceId, final String userAgentString) {
takePushRecord(accountUuid, deviceId).thenAccept(pushRecord -> {
if (pushRecord != null) {
final Duration latency = Duration.between(pushRecord.timestamp(), Instant.now());
final List<Tag> tags = new ArrayList<>(3);
tags.add(UserAgentTagUtil.getPlatformTag(userAgentString));
tags.add(Tag.of("pushType", pushRecord.pushType().name().toLowerCase()));
UserAgentTagUtil.getClientVersionTag(userAgentString, clientReleaseManager)
.ifPresent(tags::add);
pushRecord.urgent().ifPresent(urgent -> tags.add(Tag.of("urgent", String.valueOf(urgent))));
Timer.builder(TIMER_NAME)
.publishPercentileHistogram(true)
.tags(tags)
.register(Metrics.globalRegistry)
.record(latency);
}
});
}
@VisibleForTesting
CompletableFuture<PushRecord> takePushRecord(final UUID accountUuid, final byte deviceId) {
final String key = getFirstUnacknowledgedPushKey(accountUuid, deviceId);
return redisCluster.withCluster(connection -> {
final CompletableFuture<PushRecord> getFuture = connection.async().get(key).toCompletableFuture()
.thenApply(recordJson -> {
if (StringUtils.isNotEmpty(recordJson)) {
try {
return SystemMapper.jsonMapper().readValue(recordJson, PushRecord.class);
} catch (JsonProcessingException e) {
return null;
}
} else {
return null;
}
});
getFuture.whenComplete((record, cause) -> {
if (cause == null) {
connection.async().del(key);
}
});
return getFuture;
});
}
private static String getFirstUnacknowledgedPushKey(final UUID accountUuid, final byte deviceId) {
return "push_latency::v2::" + accountUuid.toString() + "::" + deviceId;
}
}
@@ -10,7 +10,9 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import java.time.Instant;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
@@ -20,7 +22,6 @@ import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.Util;
public class PushNotificationManager {
@@ -28,59 +29,59 @@ public class PushNotificationManager {
private final APNSender apnSender;
private final FcmSender fcmSender;
private final ApnPushNotificationScheduler apnPushNotificationScheduler;
private final PushLatencyManager pushLatencyManager;
private static final String SENT_NOTIFICATION_COUNTER_NAME = name(PushNotificationManager.class, "sentPushNotification");
private static final String FAILED_NOTIFICATION_COUNTER_NAME = name(PushNotificationManager.class, "failedPushNotification");
private static final String DEVICE_TOKEN_UNREGISTERED_COUNTER_NAME = name(PushNotificationManager.class, "deviceTokenUnregistered");
private static final Logger logger = LoggerFactory.getLogger(PushNotificationManager.class);
public PushNotificationManager(final AccountsManager accountsManager,
final APNSender apnSender,
final FcmSender fcmSender,
final ApnPushNotificationScheduler apnPushNotificationScheduler,
final PushLatencyManager pushLatencyManager) {
final ApnPushNotificationScheduler apnPushNotificationScheduler) {
this.accountsManager = accountsManager;
this.apnSender = apnSender;
this.fcmSender = fcmSender;
this.apnPushNotificationScheduler = apnPushNotificationScheduler;
this.pushLatencyManager = pushLatencyManager;
}
public void sendNewMessageNotification(final Account destination, final byte destinationDeviceId, final boolean urgent) throws NotPushRegisteredException {
public CompletableFuture<Optional<SendPushNotificationResult>> sendNewMessageNotification(final Account destination, final byte destinationDeviceId, final boolean urgent) throws NotPushRegisteredException {
final Device device = destination.getDevice(destinationDeviceId).orElseThrow(NotPushRegisteredException::new);
final Pair<String, PushNotification.TokenType> tokenAndType = getToken(device);
sendNotification(new PushNotification(tokenAndType.first(), tokenAndType.second(),
return sendNotification(new PushNotification(tokenAndType.first(), tokenAndType.second(),
PushNotification.NotificationType.NOTIFICATION, null, destination, device, urgent));
}
public void sendRegistrationChallengeNotification(final String deviceToken, final PushNotification.TokenType tokenType, final String challengeToken) {
sendNotification(new PushNotification(deviceToken, tokenType, PushNotification.NotificationType.CHALLENGE, challengeToken, null, null, true));
public CompletableFuture<SendPushNotificationResult> sendRegistrationChallengeNotification(final String deviceToken, final PushNotification.TokenType tokenType, final String challengeToken) {
return sendNotification(new PushNotification(deviceToken, tokenType, PushNotification.NotificationType.CHALLENGE, challengeToken, null, null, true))
.thenApply(maybeResponse -> maybeResponse.orElseThrow(() -> new AssertionError("Responses must be present for urgent notifications")));
}
public void sendRateLimitChallengeNotification(final Account destination, final String challengeToken)
public CompletableFuture<SendPushNotificationResult> sendRateLimitChallengeNotification(final Account destination, final String challengeToken)
throws NotPushRegisteredException {
final Device device = destination.getPrimaryDevice();
final Pair<String, PushNotification.TokenType> tokenAndType = getToken(device);
sendNotification(new PushNotification(tokenAndType.first(), tokenAndType.second(),
PushNotification.NotificationType.RATE_LIMIT_CHALLENGE, challengeToken, destination, device, true));
return sendNotification(new PushNotification(tokenAndType.first(), tokenAndType.second(),
PushNotification.NotificationType.RATE_LIMIT_CHALLENGE, challengeToken, destination, device, true))
.thenApply(maybeResponse -> maybeResponse.orElseThrow(() -> new AssertionError("Responses must be present for urgent notifications")));
}
public void sendAttemptLoginNotification(final Account destination, final String context) throws NotPushRegisteredException {
public CompletableFuture<SendPushNotificationResult> sendAttemptLoginNotification(final Account destination, final String context) throws NotPushRegisteredException {
final Device device = destination.getDevice(Device.PRIMARY_ID).orElseThrow(NotPushRegisteredException::new);
final Pair<String, PushNotification.TokenType> tokenAndType = getToken(device);
sendNotification(new PushNotification(tokenAndType.first(), tokenAndType.second(),
return sendNotification(new PushNotification(tokenAndType.first(), tokenAndType.second(),
PushNotification.NotificationType.ATTEMPT_LOGIN_NOTIFICATION_HIGH_PRIORITY,
context, destination, device, true));
context, destination, device, true))
.thenApply(maybeResponse -> maybeResponse.orElseThrow(() -> new AssertionError("Responses must be present for urgent notifications")));
}
public void handleMessagesRetrieved(final Account account, final Device device, final String userAgent) {
RedisOperation.unchecked(() -> pushLatencyManager.recordQueueRead(account.getUuid(), device.getId(), userAgent));
apnPushNotificationScheduler.cancelScheduledNotifications(account, device).whenComplete(logErrors());
}
@@ -102,59 +103,66 @@ public class PushNotificationManager {
}
@VisibleForTesting
void sendNotification(final PushNotification pushNotification) {
CompletableFuture<Optional<SendPushNotificationResult>> sendNotification(final PushNotification pushNotification) {
if (pushNotification.tokenType() == PushNotification.TokenType.APN && !pushNotification.urgent()) {
// APNs imposes a per-device limit on background push notifications; schedule a notification for some time in the
// future (possibly even now!) rather than sending a notification directly
apnPushNotificationScheduler
return apnPushNotificationScheduler
.scheduleBackgroundNotification(pushNotification.destination(), pushNotification.destinationDevice())
.whenComplete(logErrors());
} else {
final PushNotificationSender sender = switch (pushNotification.tokenType()) {
case FCM -> fcmSender;
case APN, APN_VOIP -> apnSender;
};
sender.sendNotification(pushNotification).whenComplete((result, throwable) -> {
if (throwable == null) {
Tags tags = Tags.of("tokenType", pushNotification.tokenType().name(),
"notificationType", pushNotification.notificationType().name(),
"urgent", String.valueOf(pushNotification.urgent()),
"accepted", String.valueOf(result.accepted()),
"unregistered", String.valueOf(result.unregistered()));
if (StringUtils.isNotBlank(result.errorCode())) {
tags = tags.and("errorCode", result.errorCode());
}
Metrics.counter(SENT_NOTIFICATION_COUNTER_NAME, tags).increment();
if (result.unregistered() && pushNotification.destination() != null
&& pushNotification.destinationDevice() != null) {
handleDeviceUnregistered(pushNotification.destination(), pushNotification.destinationDevice());
}
if (result.accepted() &&
pushNotification.tokenType() == PushNotification.TokenType.APN_VOIP &&
pushNotification.notificationType() == PushNotification.NotificationType.NOTIFICATION &&
pushNotification.destination() != null &&
pushNotification.destinationDevice() != null) {
apnPushNotificationScheduler.scheduleRecurringVoipNotification(
pushNotification.destination(),
pushNotification.destinationDevice())
.whenComplete(logErrors());
}
} else {
logger.debug("Failed to deliver {} push notification to {} ({})",
pushNotification.notificationType(), pushNotification.deviceToken(), pushNotification.tokenType(),
throwable);
Metrics.counter(FAILED_NOTIFICATION_COUNTER_NAME, "cause", throwable.getClass().getSimpleName()).increment();
}
});
.whenComplete(logErrors())
.thenApply(ignored -> Optional.<SendPushNotificationResult>empty())
.toCompletableFuture();
}
final PushNotificationSender sender = switch (pushNotification.tokenType()) {
case FCM -> fcmSender;
case APN, APN_VOIP -> apnSender;
};
return sender.sendNotification(pushNotification).whenComplete((result, throwable) -> {
if (throwable == null) {
Tags tags = Tags.of("tokenType", pushNotification.tokenType().name(),
"notificationType", pushNotification.notificationType().name(),
"urgent", String.valueOf(pushNotification.urgent()),
"accepted", String.valueOf(result.accepted()),
"unregistered", String.valueOf(result.unregistered()));
if (result.errorCode().isPresent()) {
tags = tags.and("errorCode", result.errorCode().get());
}
Metrics.counter(SENT_NOTIFICATION_COUNTER_NAME, tags).increment();
if (result.unregistered() && pushNotification.destination() != null
&& pushNotification.destinationDevice() != null) {
handleDeviceUnregistered(pushNotification.destination(),
pushNotification.destinationDevice(),
pushNotification.tokenType(),
result.errorCode(),
result.unregisteredTimestamp());
}
if (result.accepted() &&
pushNotification.tokenType() == PushNotification.TokenType.APN_VOIP &&
pushNotification.notificationType() == PushNotification.NotificationType.NOTIFICATION &&
pushNotification.destination() != null &&
pushNotification.destinationDevice() != null) {
apnPushNotificationScheduler.scheduleRecurringVoipNotification(
pushNotification.destination(),
pushNotification.destinationDevice())
.whenComplete(logErrors());
}
} else {
logger.debug("Failed to deliver {} push notification to {} ({})",
pushNotification.notificationType(), pushNotification.deviceToken(), pushNotification.tokenType(),
throwable);
Metrics.counter(FAILED_NOTIFICATION_COUNTER_NAME, "cause", throwable.getClass().getSimpleName()).increment();
}
})
.thenApply(Optional::of);
}
private static <T> BiConsumer<T, Throwable> logErrors() {
@@ -165,27 +173,60 @@ public class PushNotificationManager {
};
}
private void handleDeviceUnregistered(final Account account, final Device device) {
if (StringUtils.isNotBlank(device.getGcmId())) {
if (device.getUninstalledFeedbackTimestamp() == 0) {
// Reread the account to avoid marking the caller's account as stale. The consumers of this class tend to
// promise not to modify accounts. There's no need to force the caller to be considered mutable just for
// updating an uninstalled feedback timestamp though.
final Optional<Account> rereadAccount = accountsManager.getByAccountIdentifier(account.getUuid());
if (rereadAccount.isEmpty()) {
// don't bother adding the uninstalled timestamp, the account is gone
return;
}
final Optional<Device> rereadDevice = rereadAccount.get().getDevice(device.getId());
if (rereadDevice.map(Device::getUninstalledFeedbackTimestamp).orElse(-1L) != 0) {
// don't bother adding the uninstalled timestamp, the device is gone or already updated
return;
}
accountsManager.updateDevice(rereadAccount.get(), device.getId(), d ->
d.setUninstalledFeedbackTimestamp(Util.todayInMillis()));
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
private void handleDeviceUnregistered(final Account account,
final Device device,
final PushNotification.TokenType tokenType,
final Optional<String> maybeErrorCode,
final Optional<Instant> maybeTokenInvalidationTimestamp) {
final boolean tokenExpired = maybeTokenInvalidationTimestamp.map(tokenInvalidationTimestamp ->
tokenInvalidationTimestamp.isAfter(Instant.ofEpochMilli(device.getPushTimestamp()))).orElse(true);
if (tokenExpired) {
if (tokenType == PushNotification.TokenType.APN || tokenType == PushNotification.TokenType.APN_VOIP) {
apnPushNotificationScheduler.cancelScheduledNotifications(account, device).whenComplete(logErrors());
}
} else {
apnPushNotificationScheduler.cancelScheduledNotifications(account, device).whenComplete(logErrors());
clearPushToken(account, device, tokenType);
}
Metrics.counter(DEVICE_TOKEN_UNREGISTERED_COUNTER_NAME,
"errorCode", maybeErrorCode.orElse("unknown"),
"isPrimary", String.valueOf(device.isPrimary()),
"hasUnregisteredTimestamp", String.valueOf(maybeTokenInvalidationTimestamp.isPresent()),
"tokenType", tokenType.name(),
"tokenExpired", String.valueOf(tokenExpired)).increment();
}
private void clearPushToken(final Account account, final Device device, final PushNotification.TokenType tokenType) {
final String originalToken = getPushToken(device, tokenType);
if (originalToken == null) {
return;
}
// Reread the account to avoid marking the caller's account as stale. The consumers of this class tend to
// promise not to modify accounts. There's no need to force the caller to be considered mutable just for
// updating an uninstalled feedback timestamp though.
accountsManager.getByAccountIdentifier(account.getUuid()).ifPresent(rereadAccount ->
rereadAccount.getDevice(device.getId()).ifPresent(rereadDevice ->
accountsManager.updateDevice(rereadAccount, device.getId(), d -> {
// Don't clear the token if it's already changed
if (originalToken.equals(getPushToken(d, tokenType))) {
switch (tokenType) {
case FCM -> d.setGcmId(null);
case APN -> d.setApnId(null);
case APN_VOIP -> d.setVoipApnId(null);
}
}
})));
}
private static String getPushToken(final Device device, final PushNotification.TokenType tokenType) {
return switch (tokenType) {
case FCM -> device.getGcmId();
case APN -> device.getApnId();
case APN_VOIP -> device.getVoipApnId();
};
}
}
@@ -55,8 +55,6 @@ public class ReceiptSender {
for (final Device destinationDevice : destinationAccount.getDevices()) {
try {
messageSender.sendMessage(destinationAccount, destinationDevice, message.build(), false);
} catch (final NotPushRegisteredException e) {
logger.debug("User no longer push registered for delivery receipt: {}", e.getMessage());
} catch (final Exception e) {
logger.warn("Could not send delivery receipt", e);
}
@@ -5,7 +5,11 @@
package org.whispersystems.textsecuregcm.push;
import javax.annotation.Nullable;
import java.time.Instant;
import java.util.Optional;
public record SendPushNotificationResult(boolean accepted, @Nullable String errorCode, boolean unregistered) {
public record SendPushNotificationResult(boolean accepted,
Optional<String> errorCode,
boolean unregistered,
Optional<Instant> unregisteredTimestamp) {
}
@@ -0,0 +1,222 @@
package org.whispersystems.textsecuregcm.scheduler;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Metrics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.retry.Retry;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import javax.annotation.Nullable;
import java.nio.ByteBuffer;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
/**
* A job scheduler maintains a delay queue of tasks to be run at some time in the future. Callers schedule jobs with
* the {@link #scheduleJob(Instant, byte[])} method, and concrete subclasses actually execute jobs by implementing the
* {@link #processJob(byte[])} method. Some entity must call {@link #processAvailableJobs()} to actually find and
* process jobs that are ready for execution.
*/
public abstract class JobScheduler {
private final DynamoDbAsyncClient dynamoDbAsyncClient;
private final String tableName;
private final Duration jobExpiration;
private final Clock clock;
private final Logger logger = LoggerFactory.getLogger(getClass());
// The name of this scheduler (DynamoDB string)
@VisibleForTesting
public static final String KEY_SCHEDULER_NAME = "S";
// The timestamp (and additional random data; please see #buildRunAtAttribute for details) for the job
// (DynamoDB byte array)
@VisibleForTesting
public static final String ATTR_RUN_AT = "T";
// Additional application-specific data for the job (DynamoDB byte array)
private static final String ATTR_JOB_DATA = "D";
// The time at which this job should be garbage-collected if not already deleted (DynamoDB number;
// seconds from the epoch)
private static final String ATTR_TTL = "E";
private static final String SCHEDULE_JOB_COUNTER_NAME = MetricsUtil.name(JobScheduler.class, "scheduleJob");
private static final String PROCESS_JOB_COUNTER_NAME = MetricsUtil.name(JobScheduler.class, "processJob");
private static final String SCHEDULER_NAME_TAG = "schedulerName";
private static final String OUTCOME_TAG = "outcome";
private static final int MAX_CONCURRENCY = 16;
protected JobScheduler(final DynamoDbAsyncClient dynamoDbAsyncClient,
final String tableName,
final Duration jobExpiration,
final Clock clock) {
this.dynamoDbAsyncClient = dynamoDbAsyncClient;
this.tableName = tableName;
this.jobExpiration = jobExpiration;
this.clock = clock;
}
/**
* Returns the unique name of this scheduler. Scheduler names are used to "namespace" jobs.
*
* @return the unique name of this scheduler
*/
public abstract String getSchedulerName();
/**
* Processes a previously-scheduled job.
*
* @param jobData opaque, application-specific data provided at the time the job was scheduled
*
* @return A future that yields a brief, human-readable status code when the job has been fully processed. On
* successful completion, the job will be deleted. The job will not be deleted if the future completes exceptionally.
*/
protected abstract CompletableFuture<String> processJob(@Nullable byte[] jobData);
/**
* Schedules a job to run at or after the given {@code runAt} time. Concrete implementations must override this method
* to expose it publicly, or provide some more application-appropriate method for public callers.
*
* @param runAt the time at or after which to run the job
* @param jobData application-specific data describing the job; may be {@code null}
*
* @return a future that completes when the job has been scheduled
*/
protected CompletableFuture<Void> scheduleJob(final Instant runAt, @Nullable final byte[] jobData) {
return Mono.fromFuture(() -> scheduleJob(buildRunAtAttribute(runAt), runAt.plus(jobExpiration), jobData))
.retryWhen(Retry.backoff(8, Duration.ofSeconds(1)).maxBackoff(Duration.ofSeconds(4)))
.toFuture()
.thenRun(() -> Metrics.counter(SCHEDULE_JOB_COUNTER_NAME, SCHEDULER_NAME_TAG, getSchedulerName()).increment());
}
@VisibleForTesting
CompletableFuture<Void> scheduleJob(final AttributeValue runAt, final Instant expiration, @Nullable final byte[] jobData) {
final Map<String, AttributeValue> item = new HashMap<>(Map.of(
KEY_SCHEDULER_NAME, AttributeValue.fromS(getSchedulerName()),
ATTR_RUN_AT, runAt,
ATTR_TTL, AttributeValue.fromN(String.valueOf(expiration.getEpochSecond()))));
if (jobData != null) {
item.put(ATTR_JOB_DATA, AttributeValue.fromB(SdkBytes.fromByteArray(jobData)));
}
return dynamoDbAsyncClient.putItem(PutItemRequest.builder()
.tableName(tableName)
.item(item)
.conditionExpression("attribute_not_exists(#schedulerName)")
.expressionAttributeNames(Map.of("#schedulerName", KEY_SCHEDULER_NAME))
.build())
.thenRun(Util.NOOP);
}
/**
* Finds and processes all jobs whose {@code runAt} time is less than or equal to the current time. Scheduled jobs
* will be deleted once they have been processed successfully.
*
* @return a future that completes when all available jobs have been processed
*
* @see #processJob(byte[])
*/
public CompletableFuture<Void> processAvailableJobs() {
return Flux.from(dynamoDbAsyncClient.queryPaginator(QueryRequest.builder()
.tableName(tableName)
.keyConditionExpression("#schedulerName = :schedulerName AND #runAt <= :maxRunAt")
.expressionAttributeNames(Map.of(
"#schedulerName", KEY_SCHEDULER_NAME,
"#runAt", ATTR_RUN_AT))
.expressionAttributeValues(Map.of(
":schedulerName", AttributeValue.fromS(getSchedulerName()),
":maxRunAt", buildMaxRunAtAttribute(clock.instant())))
.build())
.items())
.flatMap(item -> {
final byte[] jobData = item.containsKey(ATTR_JOB_DATA)
? item.get(ATTR_JOB_DATA).b().asByteArray()
: null;
return Mono.fromFuture(processJob(jobData))
.doOnNext(outcome -> Metrics.counter(PROCESS_JOB_COUNTER_NAME,
SCHEDULER_NAME_TAG, getSchedulerName(),
OUTCOME_TAG, outcome)
.increment())
.then(Mono.fromFuture(() -> deleteJob(item.get(KEY_SCHEDULER_NAME), item.get(ATTR_RUN_AT))))
.onErrorResume(throwable -> {
logger.warn("Failed to process job", throwable);
return Mono.empty();
});
}, MAX_CONCURRENCY)
.then()
.toFuture();
}
private CompletableFuture<Void> deleteJob(final AttributeValue schedulerName, final AttributeValue runAt) {
return dynamoDbAsyncClient.deleteItem(DeleteItemRequest.builder()
.tableName(tableName)
.key(Map.of(
KEY_SCHEDULER_NAME, schedulerName,
ATTR_RUN_AT, runAt))
.build())
.thenRun(Util.NOOP);
}
/**
* Constructs an attribute value that contains a sort key that will be greater than any sort key generated for an
* earlier {@code runAt} time and less than a sort key generated for a later {@code runAt} time. The returned value
* begins with the 8-byte, big-endian representation of the given {@code runAt} time in milliseconds since the epoch
* and ends with a random 8-byte suffix. The random suffix ensures that multiple jobs scheduled for the same
* {@code runAt} time will have distinct primary keys; the order in which jobs scheduled at the same time will be
* executed is also random as a result.
*
* @param runAt the time for which to generate a sort key
*
* @return a probably-unique sort key for the given {@code runAt} time
*/
AttributeValue buildRunAtAttribute(final Instant runAt) {
return buildRunAtAttribute(runAt, ThreadLocalRandom.current().nextLong());
}
@VisibleForTesting
AttributeValue buildRunAtAttribute(final Instant runAt, final long salt) {
return AttributeValue.fromB(SdkBytes.fromByteBuffer(ByteBuffer.allocate(24)
.putLong(runAt.toEpochMilli())
.putLong(clock.millis())
.putLong(salt)
.flip()));
}
/**
* Constructs a sort key value that is greater than or equal to all other sort keys for jobs with the same or earlier
* {@code runAt} time.
*
* @param runAt the maximum scheduled time for jobs to match
*
* @return an attribute value for a sort key that is greater than or equal to the sort key for all other jobs
* scheduled to run at or before the given {@code runAt} time
*/
static AttributeValue buildMaxRunAtAttribute(final Instant runAt) {
return AttributeValue.fromB(SdkBytes.fromByteBuffer(ByteBuffer.allocate(24)
.putLong(runAt.toEpochMilli())
.putLong(0xfffffffffffffffL)
.putLong(0xfffffffffffffffL)
.flip()));
}
}
@@ -0,0 +1,94 @@
package org.whispersystems.textsecuregcm.scheduler;
import com.google.common.annotations.VisibleForTesting;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberToTimeZonesMapper;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import org.whispersystems.textsecuregcm.storage.Account;
import java.time.Clock;
import java.time.Instant;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
public class SchedulingUtil {
/**
* Gets a present or future time at which to send a notification to a device associated with the given account. This
* is mainly intended to facilitate scheduling notifications such that they arrive during a recipient's waking hours.
* <p/>
* This method will attempt to use a timezone derived from the account's phone number to choose an appropriate time
* to send a notification. If a timezone cannot be derived from the account's phone number, then this method will use
* the account's creation time as a hint. As an example, if the account was created at 07:17 in the server's local
* time, we can assume that the account holder was awake at that time of day, and it's likely a safe time to send a
* notification in the absence of other hints.
*
* @param account the account that will receive the notification
* @param preferredTime the preferred local time (e.g. "noon") at which to deliver the notification
* @param clock a source of the current time
*
* @return the next time in the present or future at which to send a notification for the target account
*/
public static Instant getNextRecommendedNotificationTime(final Account account,
final LocalTime preferredTime,
final Clock clock) {
final ZonedDateTime candidateNotificationTime = getZoneOffset(account, clock)
.map(zoneOffset -> ZonedDateTime.now(zoneOffset).with(preferredTime))
.orElseGet(() -> {
// We couldn't find a reasonable timezone for the account for some reason, so make an educated guess at a
// reasonable time to send a notification based on the account's creation time.
final Instant accountCreation = Instant.ofEpochMilli(account.getPrimaryDevice().getCreated());
final LocalTime accountCreationLocalTime = LocalTime.ofInstant(accountCreation, ZoneId.systemDefault());
return ZonedDateTime.now(ZoneId.systemDefault()).with(accountCreationLocalTime);
});
if (candidateNotificationTime.toInstant().isBefore(clock.instant())) {
// We've missed our opportunity today, so go for the same time tomorrow
return candidateNotificationTime.plusDays(1).toInstant();
} else {
// The best time to send a notification hasn't happened yet today
return candidateNotificationTime.toInstant();
}
}
@VisibleForTesting
static Optional<ZoneOffset> getZoneOffset(final Account account, final Clock clock) {
try {
final Phonenumber.PhoneNumber phoneNumber = PhoneNumberUtil.getInstance().parse(account.getNumber(), null);
final List<String> timeZonesForNumber =
PhoneNumberToTimeZonesMapper.getInstance().getTimeZonesForNumber(phoneNumber);
if (timeZonesForNumber.equals(List.of(PhoneNumberToTimeZonesMapper.getUnknownTimeZone()))) {
return Optional.empty();
}
final List<ZoneOffset> sortedZoneOffsets = timeZonesForNumber
.stream()
.map(id -> {
try {
return ZoneId.of(id);
} catch (final Exception e) {
return null;
}
})
.filter(Objects::nonNull)
.map(ZoneId::getRules)
.distinct()
.map(zoneRules -> zoneRules.getOffset(clock.instant()))
.sorted()
.toList();
return Optional.of(sortedZoneOffsets.get(sortedZoneOffsets.size() / 2));
} catch (final NumberParseException e) {
return Optional.empty();
}
}
}
@@ -1,9 +1,9 @@
package org.whispersystems.textsecuregcm.spam;
import org.whispersystems.textsecuregcm.auth.AccountAndAuthenticatedDeviceHolder;
import org.whispersystems.textsecuregcm.storage.Account;
import javax.ws.rs.container.ContainerRequestContext;
import java.util.Optional;
import java.util.function.Function;
/**
* Generates ReportSpamTokens to be used for spam reports.
@@ -18,7 +18,7 @@ public interface ReportSpamTokenProvider {
* @param maybeDestination the intended recepient of the message if available
* @return either a generated token or nothing
*/
Optional<byte[]> makeReportSpamToken(ContainerRequestContext context, final Account sender,
Optional<byte[]> makeReportSpamToken(ContainerRequestContext context, final AccountAndAuthenticatedDeviceHolder sender,
final Optional<Account> maybeDestination);
/**
@@ -289,23 +289,20 @@ public class Account {
}
public boolean isPaymentActivationSupported() {
return allEnabledDevicesHaveCapability(DeviceCapabilities::paymentActivation);
return allDevicesHaveCapability(DeviceCapabilities::paymentActivation);
}
private boolean allEnabledDevicesHaveCapability(final Predicate<DeviceCapabilities> predicate) {
public boolean isDeleteSyncSupported() {
return allDevicesHaveCapability(DeviceCapabilities::deleteSync);
}
private boolean allDevicesHaveCapability(final Predicate<DeviceCapabilities> predicate) {
requireNotStale();
return devices.stream()
.filter(Device::isEnabled)
.allMatch(device -> device.getCapabilities() != null && predicate.test(device.getCapabilities()));
}
public boolean isEnabled() {
requireNotStale();
return getPrimaryDevice().isEnabled();
}
public byte getNextDeviceId() {
requireNotStale();
@@ -322,14 +319,6 @@ public class Account {
return candidateId;
}
public boolean hasEnabledLinkedDevice() {
requireNotStale();
return devices.stream()
.filter(d -> Device.PRIMARY_ID != d.getId())
.anyMatch(Device::isEnabled);
}
public void setIdentityKey(final IdentityKey identityKey) {
requireNotStale();
@@ -500,12 +489,6 @@ public class Account {
this.discoverableByPhoneNumber = discoverableByPhoneNumber;
}
public boolean shouldBeVisibleInDirectory() {
requireNotStale();
return isEnabled() && isDiscoverableByPhoneNumber();
}
public int getVersion() {
requireNotStale();
@@ -575,10 +558,6 @@ public class Account {
this.usernameHolds = usernameHolds;
}
boolean isStale() {
return stale;
}
public void markStale() {
stale = true;
}
@@ -443,7 +443,7 @@ public class Accounts extends AbstractDynamoDbStore {
.expressionAttributeValues(Map.of(
":number", numberAttr,
":data", accountDataAttributeValue(account),
":cds", AttributeValues.fromBool(account.shouldBeVisibleInDirectory()),
":cds", AttributeValues.fromBool(account.isDiscoverableByPhoneNumber()),
":pni", pniAttr,
":version", AttributeValues.fromInt(account.getVersion()),
":version_increment", AttributeValues.fromInt(1)))
@@ -924,7 +924,7 @@ public class Accounts extends AbstractDynamoDbStore {
final Map<String, AttributeValue> attrValues = new HashMap<>(Map.of(
":data", accountDataAttributeValue(account),
":cds", AttributeValues.fromBool(account.shouldBeVisibleInDirectory()),
":cds", AttributeValues.fromBool(account.isDiscoverableByPhoneNumber()),
":version", AttributeValues.fromInt(account.getVersion()),
":version_increment", AttributeValues.fromInt(1)));
@@ -1359,7 +1359,7 @@ public class Accounts extends AbstractDynamoDbStore {
ATTR_PNI_UUID, pniUuidAttr,
ATTR_ACCOUNT_DATA, accountDataAttributeValue(account),
ATTR_VERSION, AttributeValues.fromInt(account.getVersion()),
ATTR_CANONICALLY_DISCOVERABLE, AttributeValues.fromBool(account.shouldBeVisibleInDirectory())));
ATTR_CANONICALLY_DISCOVERABLE, AttributeValues.fromBool(account.isDiscoverableByPhoneNumber())));
// Add the UAK if it's in the account
account.getUnidentifiedAccessKey()
@@ -490,7 +490,6 @@ public class AccountsManager {
account.getDevices()
.stream()
.filter(Device::isEnabled)
.forEach(device -> device.setPhoneNumberIdentityRegistrationId(pniRegistrationIds.get(device.getId())));
account.setPhoneNumberIdentityKey(pniIdentityKey);
@@ -115,8 +115,13 @@ public class ChangeNumberManager {
}
private void sendDeviceMessages(final Account account, final List<IncomingMessage> deviceMessages) {
deviceMessages.forEach(message ->
sendMessageToSelf(account, account.getDevice(message.destinationDeviceId()), message));
try {
deviceMessages.forEach(message ->
sendMessageToSelf(account, account.getDevice(message.destinationDeviceId()), message));
} catch (RuntimeException e) {
logger.warn("Changed number but could not send all device messages on {}", account.getUuid(), e);
throw e;
}
}
@VisibleForTesting
@@ -130,23 +135,20 @@ public class ChangeNumberManager {
logger.debug("destination device not present");
return;
}
try {
long serverTimestamp = System.currentTimeMillis();
Envelope envelope = Envelope.newBuilder()
.setType(Envelope.Type.forNumber(message.type()))
.setTimestamp(serverTimestamp)
.setServerTimestamp(serverTimestamp)
.setDestinationUuid(new AciServiceIdentifier(sourceAndDestinationAccount.getUuid()).toServiceIdentifierString())
.setContent(ByteString.copyFrom(contents.get()))
.setSourceUuid(new AciServiceIdentifier(sourceAndDestinationAccount.getUuid()).toServiceIdentifierString())
.setSourceDevice((int) Device.PRIMARY_ID)
.setUpdatedPni(sourceAndDestinationAccount.getPhoneNumberIdentifier().toString())
.setUrgent(true)
.build();
messageSender.sendMessage(sourceAndDestinationAccount, destinationDevice.get(), envelope, false);
} catch (NotPushRegisteredException e) {
logger.debug("Not registered", e);
}
final long serverTimestamp = System.currentTimeMillis();
final Envelope envelope = Envelope.newBuilder()
.setType(Envelope.Type.forNumber(message.type()))
.setTimestamp(serverTimestamp)
.setServerTimestamp(serverTimestamp)
.setDestinationUuid(new AciServiceIdentifier(sourceAndDestinationAccount.getUuid()).toServiceIdentifierString())
.setContent(ByteString.copyFrom(contents.get()))
.setSourceUuid(new AciServiceIdentifier(sourceAndDestinationAccount.getUuid()).toServiceIdentifierString())
.setSourceDevice((int) Device.PRIMARY_ID)
.setUpdatedPni(sourceAndDestinationAccount.getPhoneNumberIdentifier().toString())
.setUrgent(true)
.build();
messageSender.sendMessage(sourceAndDestinationAccount, destinationDevice.get(), envelope, false);
}
}
@@ -11,11 +11,9 @@ import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.time.Duration;
import java.util.List;
import java.util.OptionalInt;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.util.DeviceNameByteArrayAdapter;
@@ -57,9 +55,6 @@ public class Device {
@JsonProperty
private long pushTimestamp;
@JsonProperty
private long uninstalledFeedback;
@JsonProperty
private boolean fetchesMessages;
@@ -102,14 +97,6 @@ public class Device {
this.voipApnId = voipApnId;
}
public void setUninstalledFeedbackTimestamp(long uninstalledFeedback) {
this.uninstalledFeedback = uninstalledFeedback;
}
public long getUninstalledFeedbackTimestamp() {
return uninstalledFeedback;
}
public void setLastSeen(long lastSeen) {
this.lastSeen = lastSeen;
}
@@ -199,12 +186,6 @@ public class Device {
this.capabilities = capabilities;
}
public boolean isEnabled() {
boolean hasChannel = fetchesMessages || StringUtils.isNotEmpty(getApnId()) || StringUtils.isNotEmpty(getGcmId());
return (id == PRIMARY_ID && hasChannel) || (id != PRIMARY_ID && hasChannel && !isExpired());
}
public boolean isExpired() {
return isPrimary()
? lastSeen < (System.currentTimeMillis() - ALLOWED_PRIMARY_IDLE_MILLIS)
@@ -251,6 +232,6 @@ public class Device {
return this.userAgent;
}
public record DeviceCapabilities(boolean storage, boolean transfer, boolean paymentActivation) {
public record DeviceCapabilities(boolean storage, boolean transfer, boolean paymentActivation, boolean deleteSync) {
}
}
@@ -22,6 +22,7 @@ import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
@@ -161,8 +162,13 @@ public class MessagePersister implements Managed {
logger.error("No account record found for account {}", accountUuid);
continue;
}
final Optional<Device> maybeDevice = maybeAccount.flatMap(account -> account.getDevice(deviceId));
if (maybeDevice.isEmpty()) {
logger.error("Account {} does not have a device with id {}", accountUuid, deviceId);
continue;
}
try {
persistQueue(maybeAccount.get(), deviceId);
persistQueue(maybeAccount.get(), maybeDevice.get());
} catch (final Exception e) {
persistQueueExceptionMeter.increment();
logger.warn("Failed to persist queue {}::{}; will schedule for retry", accountUuid, deviceId, e);
@@ -180,8 +186,9 @@ public class MessagePersister implements Managed {
}
@VisibleForTesting
void persistQueue(final Account account, final byte deviceId) throws MessagePersistenceException {
void persistQueue(final Account account, final Device device) throws MessagePersistenceException {
final UUID accountUuid = account.getUuid();
final byte deviceId = device.getId();
final Timer.Sample sample = Timer.start();
@@ -196,7 +203,7 @@ public class MessagePersister implements Managed {
do {
messages = messagesCache.getMessagesToPersist(accountUuid, deviceId, MESSAGE_BATCH_LIMIT);
int messagesRemovedFromCache = messagesManager.persistMessages(accountUuid, deviceId, messages);
int messagesRemovedFromCache = messagesManager.persistMessages(accountUuid, device, messages);
messageCount += messages.size();
if (messagesRemovedFromCache == 0) {
@@ -239,14 +246,14 @@ public class MessagePersister implements Managed {
// its messages) is unlinked
final Device deviceToDelete = account.getDevices()
.stream()
.filter(d -> !d.isPrimary() && !d.isEnabled())
.filter(d -> !d.isPrimary() && !deviceHasMessageDeliveryChannel(d))
.min(Comparator.comparing(Device::getLastSeen))
.or(() ->
Flux.fromIterable(account.getDevices())
.filter(d -> !d.isPrimary())
.flatMap(d ->
messagesManager
.getEarliestUndeliveredTimestampForDevice(account.getUuid(), d.getId())
.getEarliestUndeliveredTimestampForDevice(account.getUuid(), d)
.map(t -> Tuples.of(d, t)))
.sort(Comparator.comparing(Tuple2::getT2))
.map(Tuple2::getT1)
@@ -282,4 +289,8 @@ public class MessagePersister implements Managed {
}
});
}
private static boolean deviceHasMessageDeliveryChannel(final Device device) {
return device.getFetchesMessages() || StringUtils.isNotEmpty(device.getApnId()) || StringUtils.isNotEmpty(device.getGcmId());
}
}
@@ -213,6 +213,13 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
connection -> connection.sync().zcard(getMessageQueueKey(destinationUuid, destinationDevice)) > 0);
}
public CompletableFuture<Boolean> hasMessagesAsync(final UUID destinationUuid, final byte destinationDevice) {
return redisCluster.withBinaryCluster(connection ->
connection.async().zcard(getMessageQueueKey(destinationUuid, destinationDevice))
.thenApply(cardinality -> cardinality > 0))
.toCompletableFuture();
}
public Publisher<MessageProtos.Envelope> get(final UUID destinationUuid, final byte destinationDevice) {
final long earliestAllowableEphemeralTimestamp =
@@ -11,6 +11,7 @@ import static io.micrometer.core.instrument.Metrics.timer;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableMap;
import com.google.protobuf.InvalidProtocolBufferException;
import io.micrometer.core.instrument.Timer;
import java.nio.ByteBuffer;
import java.time.Duration;
@@ -23,6 +24,8 @@ import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.function.Predicate;
import java.util.stream.Stream;
import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -60,8 +63,6 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
private static final String KEY_ENVELOPE_BYTES = "EB";
private final Timer storeTimer = timer(name(getClass(), "store"));
private final String DELETE_BY_ACCOUNT_TIMER_NAME = name(getClass(), "delete", "account");
private final String DELETE_BY_DEVICE_TIMER_NAME = name(getClass(), "delete", "device");
private final DynamoDbAsyncClient dbAsyncClient;
private final String tableName;
@@ -69,6 +70,8 @@ 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,
@@ -84,24 +87,24 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
}
public void store(final List<MessageProtos.Envelope> messages, final UUID destinationAccountUuid,
final byte destinationDeviceId) {
storeTimer.record(() -> writeInBatches(messages, (messageBatch) -> storeBatch(messageBatch, destinationAccountUuid, destinationDeviceId)));
final Device destinationDevice) {
storeTimer.record(() -> writeInBatches(messages, (messageBatch) -> storeBatch(messageBatch, destinationAccountUuid, destinationDevice)));
}
private void storeBatch(final List<MessageProtos.Envelope> messages, final UUID destinationAccountUuid,
final byte destinationDeviceId) {
final Device destinationDevice) {
if (messages.size() > DYNAMO_DB_MAX_BATCH_SIZE) {
throw new IllegalArgumentException("Maximum batch size of " + DYNAMO_DB_MAX_BATCH_SIZE + " exceeded with " + messages.size() + " messages");
}
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid);
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid, destinationDevice);
List<WriteRequest> writeItems = new ArrayList<>();
for (MessageProtos.Envelope message : messages) {
final UUID messageUuid = UUID.fromString(message.getServerGuid());
final ImmutableMap.Builder<String, AttributeValue> item = ImmutableMap.<String, AttributeValue>builder()
.put(KEY_PARTITION, partitionKey)
.put(KEY_SORT, convertSortKey(destinationDeviceId, message.getServerTimestamp(), messageUuid))
.put(KEY_SORT, convertSortKey(message.getServerTimestamp(), messageUuid))
.put(LOCAL_INDEX_MESSAGE_UUID_KEY_SORT, convertLocalIndexMessageUuidSortKey(messageUuid))
.put(KEY_TTL, AttributeValues.fromLong(getTtlForMessage(message)))
.put(KEY_ENVELOPE_BYTES, AttributeValue.builder().b(SdkBytes.fromByteArray(message.toByteArray())).build());
@@ -114,20 +117,39 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
executeTableWriteItemsUntilComplete(Map.of(tableName, writeItems));
}
public Publisher<MessageProtos.Envelope> load(final UUID destinationAccountUuid, final byte destinationDeviceId,
final Integer limit) {
public CompletableFuture<Boolean> mayHaveMessages(final UUID accountIdentifier, final Device device) {
final List<CompletableFuture<Boolean>> mayHaveMessagesFutures =
Stream.of(convertPartitionKeyDeprecated(accountIdentifier, device), convertPartitionKey(accountIdentifier, device))
.distinct()
.map(partitionKey -> dbAsyncClient.query(QueryRequest.builder()
.tableName(tableName)
.consistentRead(false)
.limit(1)
.keyConditionExpression("#part = :part")
.expressionAttributeNames(Map.of("#part", KEY_PARTITION))
.expressionAttributeValues(Map.of(":part", partitionKey)).build())
.thenApply(queryResponse -> queryResponse.count() > 0))
.toList();
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid);
final QueryRequest.Builder queryRequestBuilder = QueryRequest.builder()
return CompletableFuture.allOf(mayHaveMessagesFutures.toArray(EMPTY_FUTURE_ARRAY))
.thenApply(ignored -> mayHaveMessagesFutures.stream().anyMatch(CompletableFuture::join));
}
public Publisher<MessageProtos.Envelope> load(final UUID destinationAccountUuid, final Device device, final Integer limit) {
return Flux.concat(
Stream.of(convertPartitionKeyDeprecated(destinationAccountUuid, device), convertPartitionKey(destinationAccountUuid, device))
.distinct()
.map(pk -> load(limit, pk))
.toList());
}
public Publisher<MessageProtos.Envelope> load(final Integer limit, final AttributeValue partitionKey) {
QueryRequest.Builder queryRequestBuilder = QueryRequest.builder()
.tableName(tableName)
.consistentRead(true)
.keyConditionExpression("#part = :part AND begins_with ( #sort , :sortprefix )")
.expressionAttributeNames(Map.of(
"#part", KEY_PARTITION,
"#sort", KEY_SORT))
.expressionAttributeValues(Map.of(
":part", partitionKey,
":sortprefix", convertDestinationDeviceIdToSortKeyPrefix(destinationDeviceId)));
.keyConditionExpression("#part = :part")
.expressionAttributeNames(Map.of("#part", KEY_PARTITION))
.expressionAttributeValues(Map.of(":part", partitionKey));
if (limit != null) {
// some callers don’t take advantage of reactive streams, so we want to support limiting the fetch size. Otherwise,
@@ -150,9 +172,20 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
}
public CompletableFuture<Optional<MessageProtos.Envelope>> deleteMessageByDestinationAndGuid(
final UUID destinationAccountUuid, final UUID messageUuid) {
final UUID destinationAccountUuid, final Device destinationDevice, final UUID messageUuid) {
return Stream.of(convertPartitionKey(destinationAccountUuid, destinationDevice),
convertPartitionKeyDeprecated(destinationAccountUuid, destinationDevice))
.distinct()
.map(pk -> deleteMessageByDestinationAndGuid(pk, messageUuid))
// this combines the futures by producing a future that returns an arbitrary nonempty
// result if there is one, which should be OK because only one of the keys
// should produce a nonempty result for any given message uuid
.reduce((f, g) -> f.thenCombine(g, (a, b) -> a.or(() -> b)))
.get();
}
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid);
public CompletableFuture<Optional<MessageProtos.Envelope>> deleteMessageByDestinationAndGuid(
final AttributeValue partitionKey, final UUID messageUuid) {
final QueryRequest queryRequest = QueryRequest.builder()
.tableName(tableName)
.indexName(LOCAL_INDEX_MESSAGE_UUID_NAME)
@@ -193,10 +226,20 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
}
public CompletableFuture<Optional<MessageProtos.Envelope>> deleteMessage(final UUID destinationAccountUuid,
final byte destinationDeviceId, final UUID messageUuid, final long serverTimestamp) {
final Device destinationDevice, final UUID messageUuid, final long serverTimestamp) {
return Stream.of(convertPartitionKey(destinationAccountUuid, destinationDevice),
convertPartitionKeyDeprecated(destinationAccountUuid, destinationDevice))
.distinct()
.map(pk -> deleteMessage(pk, destinationDevice, messageUuid, serverTimestamp))
// this combines the futures by producing a future that returns an arbitrary nonempty
// result if there is one, which should be OK because only one of the keys
// should produce a nonempty result for any given message uuid
.reduce((f, g) -> f.thenCombine(g, (a, b) -> a.or(() -> b)))
.get();
}
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid);
final AttributeValue sortKey = convertSortKey(destinationDeviceId, serverTimestamp, messageUuid);
public CompletableFuture<Optional<MessageProtos.Envelope>> deleteMessage(final AttributeValue partitionKey, final Device destinationDevice, final UUID messageUuid, final long serverTimestamp) {
final AttributeValue sortKey = convertSortKey(serverTimestamp, messageUuid);
DeleteItemRequest.Builder deleteItemRequest = DeleteItemRequest.builder()
.tableName(tableName)
.key(Map.of(KEY_PARTITION, partitionKey, KEY_SORT, sortKey))
@@ -216,64 +259,6 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
}, messageDeletionExecutor);
}
public CompletableFuture<Void> deleteAllMessagesForAccount(final UUID destinationAccountUuid) {
final Timer.Sample sample = Timer.start();
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid);
return Flux.from(dbAsyncClient.queryPaginator(QueryRequest.builder()
.tableName(tableName)
.projectionExpression(KEY_SORT)
.consistentRead(true)
.keyConditionExpression("#part = :part")
.expressionAttributeNames(Map.of("#part", KEY_PARTITION))
.expressionAttributeValues(Map.of(":part", partitionKey))
.build())
.items())
.flatMap(item -> Mono.fromFuture(() -> dbAsyncClient.deleteItem(DeleteItemRequest.builder()
.tableName(tableName)
.key(Map.of(
KEY_PARTITION, partitionKey,
KEY_SORT, item.get(KEY_SORT)))
.build())),
DYNAMO_DB_MAX_BATCH_SIZE)
.then()
.doOnSuccess(ignored -> sample.stop(timer(DELETE_BY_ACCOUNT_TIMER_NAME, "outcome", "success")))
.doOnError(ignored -> sample.stop(timer(DELETE_BY_ACCOUNT_TIMER_NAME, "outcome", "error")))
.toFuture();
}
public CompletableFuture<Void> deleteAllMessagesForDevice(final UUID destinationAccountUuid,
final byte destinationDeviceId) {
final Timer.Sample sample = Timer.start();
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid);
return Flux.from(dbAsyncClient.queryPaginator(QueryRequest.builder()
.tableName(tableName)
.keyConditionExpression("#part = :part AND begins_with ( #sort , :sortprefix )")
.expressionAttributeNames(Map.of(
"#part", KEY_PARTITION,
"#sort", KEY_SORT))
.expressionAttributeValues(Map.of(
":part", partitionKey,
":sortprefix", convertDestinationDeviceIdToSortKeyPrefix(destinationDeviceId)))
.projectionExpression(KEY_SORT)
.consistentRead(true)
.build())
.items())
.flatMap(item -> Mono.fromFuture(() -> dbAsyncClient.deleteItem(DeleteItemRequest.builder()
.tableName(tableName)
.key(Map.of(
KEY_PARTITION, partitionKey,
KEY_SORT, item.get(KEY_SORT)))
.build())),
DYNAMO_DB_MAX_BATCH_SIZE)
.then()
.doOnSuccess(ignored -> sample.stop(timer(DELETE_BY_DEVICE_TIMER_NAME, "outcome", "success")))
.doOnError(ignored -> sample.stop(timer(DELETE_BY_DEVICE_TIMER_NAME, "outcome", "error")))
.toFuture();
}
@VisibleForTesting
static MessageProtos.Envelope convertItemToEnvelope(final Map<String, AttributeValue> item)
throws InvalidProtocolBufferException {
@@ -285,25 +270,27 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
return message.getServerTimestamp() / 1000 + timeToLive.getSeconds();
}
private static AttributeValue convertPartitionKey(final UUID destinationAccountUuid) {
return AttributeValues.fromUUID(destinationAccountUuid);
}
private static AttributeValue convertSortKey(final byte destinationDeviceId, final long serverTimestamp,
final UUID messageUuid) {
ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[32]);
// for compatibility - destinationDeviceId was previously `long`
byteBuffer.putLong(destinationDeviceId);
byteBuffer.putLong(serverTimestamp);
byteBuffer.putLong(messageUuid.getMostSignificantBits());
byteBuffer.putLong(messageUuid.getLeastSignificantBits());
private static AttributeValue convertPartitionKey(final UUID destinationAccountUuid, final Device destinationDevice) {
final ByteBuffer byteBuffer = ByteBuffer.allocate(24);
byteBuffer.putLong(destinationAccountUuid.getMostSignificantBits());
byteBuffer.putLong(destinationAccountUuid.getLeastSignificantBits());
byteBuffer.putLong((destinationDevice.getCreated() & ~0x7f) + destinationDevice.getId());
return AttributeValues.fromByteBuffer(byteBuffer.flip());
}
private static AttributeValue convertDestinationDeviceIdToSortKeyPrefix(final byte destinationDeviceId) {
ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[8]);
// for compatibility - destinationDeviceId was previously `long`
byteBuffer.putLong(destinationDeviceId);
private static AttributeValue convertPartitionKeyDeprecated(final UUID destinationAccountUuid, final Device destinationDevice) {
final ByteBuffer byteBuffer = ByteBuffer.allocate(24);
byteBuffer.putLong(destinationAccountUuid.getMostSignificantBits());
byteBuffer.putLong(destinationAccountUuid.getLeastSignificantBits());
byteBuffer.putLong(destinationDevice.getCreated() & ~0x7f + destinationDevice.getId());
return AttributeValues.fromByteBuffer(byteBuffer.flip());
}
private static AttributeValue convertSortKey(final long serverTimestamp, final UUID messageUuid) {
final ByteBuffer byteBuffer = ByteBuffer.allocate(24);
byteBuffer.putLong(serverTimestamp);
byteBuffer.putLong(messageUuid.getMostSignificantBits());
byteBuffer.putLong(messageUuid.getLeastSignificantBits());
return AttributeValues.fromByteBuffer(byteBuffer.flip());
}
@@ -22,6 +22,7 @@ import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.util.Pair;
import reactor.core.observability.micrometer.Micrometer;
import reactor.core.publisher.Flux;
@@ -37,6 +38,9 @@ public class MessagesManager {
private static final Counter PERSIST_MESSAGE_COUNTER = Metrics.counter(
name(MessagesManager.class, "persistMessage"));
private static final String MAY_HAVE_MESSAGES_COUNTER_NAME =
MetricsUtil.name(MessagesManager.class, "mayHaveMessages");
private final MessagesDynamoDb messagesDynamoDb;
private final MessagesCache messagesCache;
private final ReportMessageManager reportMessageManager;
@@ -63,11 +67,37 @@ public class MessagesManager {
}
}
public CompletableFuture<Boolean> mayHavePersistedMessages(final UUID destinationUuid, final Device destinationDevice) {
return messagesDynamoDb.mayHaveMessages(destinationUuid, destinationDevice);
}
public CompletableFuture<Boolean> mayHaveMessages(final UUID destinationUuid, final Device destinationDevice) {
return messagesCache.hasMessagesAsync(destinationUuid, destinationDevice.getId())
.thenCombine(messagesDynamoDb.mayHaveMessages(destinationUuid, destinationDevice),
(mayHaveCachedMessages, mayHavePersistedMessages) -> {
final String outcome;
if (mayHaveCachedMessages && mayHavePersistedMessages) {
outcome = "both";
} else if (mayHaveCachedMessages) {
outcome = "cached";
} else if (mayHavePersistedMessages) {
outcome = "persisted";
} else {
outcome = "none";
}
Metrics.counter(MAY_HAVE_MESSAGES_COUNTER_NAME, "outcome", outcome).increment();
return mayHaveCachedMessages || mayHavePersistedMessages;
});
}
public boolean hasCachedMessages(final UUID destinationUuid, final byte destinationDevice) {
return messagesCache.hasMessages(destinationUuid, destinationDevice);
}
public Mono<Pair<List<Envelope>, Boolean>> getMessagesForDevice(UUID destinationUuid, byte destinationDevice,
public Mono<Pair<List<Envelope>, Boolean>> getMessagesForDevice(UUID destinationUuid, Device destinationDevice,
boolean cachedMessagesOnly) {
return Flux.from(
@@ -77,43 +107,39 @@ public class MessagesManager {
.map(envelopes -> new Pair<>(envelopes, envelopes.size() >= RESULT_SET_CHUNK_SIZE));
}
public Publisher<Envelope> getMessagesForDeviceReactive(UUID destinationUuid, byte destinationDevice,
public Publisher<Envelope> getMessagesForDeviceReactive(UUID destinationUuid, Device destinationDevice,
final boolean cachedMessagesOnly) {
return getMessagesForDevice(destinationUuid, destinationDevice, null, cachedMessagesOnly);
}
private Publisher<Envelope> getMessagesForDevice(UUID destinationUuid, byte destinationDevice,
private Publisher<Envelope> getMessagesForDevice(UUID destinationUuid, Device destinationDevice,
@Nullable Integer limit, final boolean cachedMessagesOnly) {
final Publisher<Envelope> dynamoPublisher =
cachedMessagesOnly ? Flux.empty() : messagesDynamoDb.load(destinationUuid, destinationDevice, limit);
final Publisher<Envelope> cachePublisher = messagesCache.get(destinationUuid, destinationDevice);
final Publisher<Envelope> cachePublisher = messagesCache.get(destinationUuid, destinationDevice.getId());
return Flux.concat(dynamoPublisher, cachePublisher)
.name(GET_MESSAGES_FOR_DEVICE_FLUX_NAME)
.tap(Micrometer.metrics(Metrics.globalRegistry));
}
public Mono<Long> getEarliestUndeliveredTimestampForDevice(UUID destinationUuid, byte destinationDevice) {
public Mono<Long> getEarliestUndeliveredTimestampForDevice(UUID destinationUuid, Device destinationDevice) {
return Mono.from(messagesDynamoDb.load(destinationUuid, destinationDevice, 1)).map(Envelope::getServerTimestamp);
}
public CompletableFuture<Void> clear(UUID destinationUuid) {
return CompletableFuture.allOf(
messagesCache.clear(destinationUuid),
messagesDynamoDb.deleteAllMessagesForAccount(destinationUuid));
return messagesCache.clear(destinationUuid);
}
public CompletableFuture<Void> clear(UUID destinationUuid, byte deviceId) {
return CompletableFuture.allOf(
messagesCache.clear(destinationUuid, deviceId),
messagesDynamoDb.deleteAllMessagesForDevice(destinationUuid, deviceId));
return messagesCache.clear(destinationUuid, deviceId);
}
public CompletableFuture<Optional<Envelope>> delete(UUID destinationUuid, byte destinationDeviceId, UUID guid,
public CompletableFuture<Optional<Envelope>> delete(UUID destinationUuid, Device destinationDevice, UUID guid,
@Nullable Long serverTimestamp) {
return messagesCache.remove(destinationUuid, destinationDeviceId, guid)
return messagesCache.remove(destinationUuid, destinationDevice.getId(), guid)
.thenComposeAsync(removed -> {
if (removed.isPresent()) {
@@ -121,9 +147,9 @@ public class MessagesManager {
}
if (serverTimestamp == null) {
return messagesDynamoDb.deleteMessageByDestinationAndGuid(destinationUuid, guid);
return messagesDynamoDb.deleteMessageByDestinationAndGuid(destinationUuid, destinationDevice, guid);
} else {
return messagesDynamoDb.deleteMessage(destinationUuid, destinationDeviceId, guid, serverTimestamp);
return messagesDynamoDb.deleteMessage(destinationUuid, destinationDevice, guid, serverTimestamp);
}
}, messageDeletionExecutor);
@@ -134,20 +160,20 @@ public class MessagesManager {
*/
public int persistMessages(
final UUID destinationUuid,
final byte destinationDeviceId,
final Device destinationDevice,
final List<Envelope> messages) {
final List<Envelope> nonEphemeralMessages = messages.stream()
.filter(envelope -> !envelope.getEphemeral())
.collect(Collectors.toList());
messagesDynamoDb.store(nonEphemeralMessages, destinationUuid, destinationDeviceId);
messagesDynamoDb.store(nonEphemeralMessages, destinationUuid, destinationDevice);
final List<UUID> messageGuids = messages.stream().map(message -> UUID.fromString(message.getServerGuid()))
.collect(Collectors.toList());
int messagesRemovedFromCache = 0;
try {
messagesRemovedFromCache = messagesCache.remove(destinationUuid, destinationDeviceId, messageGuids)
messagesRemovedFromCache = messagesCache.remove(destinationUuid, destinationDevice.getId(), messageGuids)
.get(30, TimeUnit.SECONDS).size();
PERSIST_MESSAGE_COUNTER.increment(nonEphemeralMessages.size());
@@ -89,7 +89,6 @@ public class DestinationDeviceValidator {
final Set<Byte> excludedDeviceIds) throws MismatchedDevicesException {
final Set<Byte> accountDeviceIds = account.getDevices().stream()
.filter(Device::isEnabled)
.map(Device::getId)
.filter(deviceId -> !excludedDeviceIds.contains(deviceId))
.collect(Collectors.toSet());
@@ -14,18 +14,11 @@ import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.util.Base64;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.InvalidKeyException;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
public class IdentityKeyAdapter {
private static final Counter IDENTITY_KEY_WITHOUT_VERSION_BYTE_COUNTER =
Metrics.counter(MetricsUtil.name(IdentityKeyAdapter.class, "identityKeyWithoutVersionByte"));
public static class Serializer extends JsonSerializer<IdentityKey> {
@Override
@@ -56,11 +49,6 @@ public class IdentityKeyAdapter {
try {
return new IdentityKey(identityKeyBytes);
} catch (final InvalidKeyException e) {
if (identityKeyBytes.length == ECPublicKey.KEY_SIZE - 1) {
IDENTITY_KEY_WITHOUT_VERSION_BYTE_COUNTER.increment();
return new IdentityKey(ECPublicKey.fromPublicKeyBytes(identityKeyBytes));
}
throw new JsonParseException(parser, "Could not interpret identity key bytes as an EC public key", e);
}
}
@@ -0,0 +1,26 @@
package org.whispersystems.textsecuregcm.util.logging;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;
/**
* Filters spurious warnings about setting a very specific channel option on local channels.
* <p/>
* gRPC unconditionally tries to set the {@code SO_KEEPALIVE} option on all of its channels, but local channels, which
* are used by the Noise-over-WebSocket tunnel, do not support {@code SO_KEEPALIVE} and log a warning on each new
* channel. We don't want to filter <em>all</em> warnings from the relevant logger, and so this custom filter denies
* attempts to log the specific spurious message.
*/
public class UnknownKeepaliveOptionFilter extends Filter<ILoggingEvent> {
private static final String MESSAGE_PREFIX = "Unknown channel option 'SO_KEEPALIVE'";
@Override
public FilterReply decide(final ILoggingEvent event) {
final boolean loggerNameMatches = "io.netty.bootstrap.Bootstrap".equals(event.getLoggerName()) ||
"io.netty.bootstrap.ServerBootstrap".equals(event.getLoggerName());
return loggerNameMatches && event.getMessage().startsWith(MESSAGE_PREFIX) ? FilterReply.DENY : FilterReply.NEUTRAL;
}
}
@@ -0,0 +1,15 @@
package org.whispersystems.textsecuregcm.util.logging;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.filter.Filter;
import com.fasterxml.jackson.annotation.JsonTypeName;
import io.dropwizard.logging.common.filter.FilterFactory;
@JsonTypeName("unknownKeepaliveOption")
public class UnknownKeepaliveOptionFilterFactory implements FilterFactory<ILoggingEvent> {
@Override
public Filter<ILoggingEvent> build() {
return new UnknownKeepaliveOptionFilter();
}
}
@@ -222,18 +222,22 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
if (throwable != null) {
sendFailuresCounter.increment();
} else {
messageMetrics.measureOutgoingMessageLatency(message.getServerTimestamp(), "websocket", client.getUserAgent(), clientReleaseManager);
messageMetrics.measureOutgoingMessageLatency(message.getServerTimestamp(),
"websocket",
device.isPrimary(),
client.getUserAgent(),
clientReleaseManager);
}
}).thenCompose(response -> {
final CompletableFuture<Void> result;
if (isSuccessResponse(response)) {
result = messagesManager.delete(auth.getAccount().getUuid(), device.getId(),
result = messagesManager.delete(auth.getAccount().getUuid(), device,
storedMessageInfo.guid(), storedMessageInfo.serverTimestamp())
.thenApply(ignored -> null);
if (message.getType() != Envelope.Type.SERVER_DELIVERY_RECEIPT) {
recordMessageDeliveryDuration(message.getTimestamp(), device);
recordMessageDeliveryDuration(message.getServerTimestamp(), device);
sendDeliveryReceiptFor(message);
}
} else {
@@ -355,7 +359,7 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
private void sendMessages(final boolean cachedMessagesOnly, final CompletableFuture<Void> queueCleared) {
final Publisher<Envelope> messages =
messagesManager.getMessagesForDeviceReactive(auth.getAccount().getUuid(), device.getId(), cachedMessagesOnly);
messagesManager.getMessagesForDeviceReactive(auth.getAccount().getUuid(), device, cachedMessagesOnly);
final AtomicBoolean hasErrored = new AtomicBoolean();
@@ -414,7 +418,7 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
final UUID messageGuid = UUID.fromString(envelope.getServerGuid());
if (envelope.getStory() && !client.shouldDeliverStories()) {
messagesManager.delete(auth.getAccount().getUuid(), device.getId(), messageGuid, envelope.getServerTimestamp());
messagesManager.delete(auth.getAccount().getUuid(), device, messageGuid, envelope.getServerTimestamp());
return CompletableFuture.completedFuture(null);
} else {
@@ -11,6 +11,8 @@ import com.fasterxml.jackson.databind.DeserializationFeature;
import io.dropwizard.core.setup.Environment;
import io.lettuce.core.resource.ClientResources;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.time.Clock;
import java.util.concurrent.ExecutorService;
@@ -28,9 +30,13 @@ import org.whispersystems.textsecuregcm.backup.Cdn3RemoteStorageManager;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery2Controller;
import org.whispersystems.textsecuregcm.experiment.PushNotificationExperimentSamples;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.push.APNSender;
import org.whispersystems.textsecuregcm.push.ApnPushNotificationScheduler;
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
import org.whispersystems.textsecuregcm.push.FcmSender;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
@@ -69,15 +75,20 @@ record CommandDependencies(
MessagesManager messagesManager,
ClientPresenceManager clientPresenceManager,
KeysManager keysManager,
PushNotificationManager pushNotificationManager,
PushNotificationExperimentSamples pushNotificationExperimentSamples,
FaultTolerantRedisCluster cacheCluster,
FaultTolerantRedisCluster pushSchedulerCluster,
ClientResources.Builder redisClusterClientResourcesBuilder,
BackupManager backupManager,
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
DynamoDbAsyncClient dynamoDbAsyncClient) {
static CommandDependencies build(
final String name,
final Environment environment,
final WhisperServerConfiguration configuration) throws IOException, CertificateException {
final WhisperServerConfiguration configuration)
throws IOException, CertificateException, NoSuchAlgorithmException, InvalidKeyException {
Clock clock = Clock.systemUTC();
environment.getObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
@@ -91,12 +102,12 @@ record CommandDependencies(
DynamicConfiguration.class, dynamicConfigurationExecutor, awsCredentialsProvider);
dynamicConfigurationManager.start();
MetricsUtil.configureRegistries(configuration, environment, dynamicConfigurationManager);
final ClientResources.Builder redisClientResourcesBuilder = ClientResources.builder();
FaultTolerantRedisCluster cacheCluster = configuration.getCacheClusterConfiguration().build("main_cache",
redisClientResourcesBuilder);
FaultTolerantRedisCluster cacheCluster = configuration.getCacheClusterConfiguration()
.build("main_cache", redisClientResourcesBuilder);
FaultTolerantRedisCluster pushSchedulerCluster = configuration.getPushSchedulerCluster()
.build("push_scheduler", redisClientResourcesBuilder);
ScheduledExecutorService recurringJobExecutor = environment.lifecycle()
.scheduledExecutorService(name(name, "recurringJob-%d")).threads(2).build();
@@ -118,6 +129,10 @@ record CommandDependencies(
.executorService(name(name, "remoteStorage-%d"))
.minThreads(0).maxThreads(Integer.MAX_VALUE).workQueue(new SynchronousQueue<>())
.keepAliveTime(io.dropwizard.util.Duration.seconds(60L)).build();
ExecutorService apnSenderExecutor = environment.lifecycle().executorService(name(name, "apnSender-%d"))
.maxThreads(1).minThreads(1).build();
ExecutorService fcmSenderExecutor = environment.lifecycle().executorService(name(name, "fcmSender-%d"))
.maxThreads(16).minThreads(16).build();
ScheduledExecutorService secureValueRecoveryServiceRetryExecutor = environment.lifecycle()
.scheduledExecutorService(name(name, "secureValueRecoveryServiceRetry-%d")).threads(1).build();
@@ -228,6 +243,16 @@ record CommandDependencies(
remoteStorageRetryExecutor,
configuration.getCdn3StorageManagerConfiguration()),
clock);
APNSender apnSender = new APNSender(apnSenderExecutor, configuration.getApnConfiguration());
FcmSender fcmSender = new FcmSender(fcmSenderExecutor, configuration.getFcmConfiguration().credentials().value());
ApnPushNotificationScheduler apnPushNotificationScheduler = new ApnPushNotificationScheduler(pushSchedulerCluster,
apnSender, accountsManager, 0);
PushNotificationManager pushNotificationManager =
new PushNotificationManager(accountsManager, apnSender, fcmSender, apnPushNotificationScheduler);
PushNotificationExperimentSamples pushNotificationExperimentSamples =
new PushNotificationExperimentSamples(dynamoDbAsyncClient,
configuration.getDynamoDbTables().getPushNotificationExperimentSamples().getTableName(),
Clock.systemUTC());
environment.lifecycle().manage(messagesCache);
environment.lifecycle().manage(clientPresenceManager);
@@ -241,10 +266,14 @@ record CommandDependencies(
messagesManager,
clientPresenceManager,
keys,
pushNotificationManager,
pushNotificationExperimentSamples,
cacheCluster,
pushSchedulerCluster,
redisClientResourcesBuilder,
backupManager,
dynamicConfigurationManager
dynamicConfigurationManager,
dynamoDbAsyncClient
);
}
@@ -0,0 +1,62 @@
package org.whispersystems.textsecuregcm.workers;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.core.Application;
import io.dropwizard.core.setup.Environment;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
import org.whispersystems.textsecuregcm.experiment.PushNotificationExperiment;
public class DiscardPushNotificationExperimentSamplesCommand extends AbstractCommandWithDependencies {
private final PushNotificationExperimentFactory<?> experimentFactory;
private static final int DEFAULT_MAX_CONCURRENCY = 16;
@VisibleForTesting
static final String MAX_CONCURRENCY_ARGUMENT = "max-concurrency";
private static final Logger log = LoggerFactory.getLogger(DiscardPushNotificationExperimentSamplesCommand.class);
public DiscardPushNotificationExperimentSamplesCommand(final String name,
final String description,
final PushNotificationExperimentFactory<?> experimentFactory) {
super(new Application<>() {
@Override
public void run(final WhisperServerConfiguration configuration, final Environment environment) {
}
}, name, description);
this.experimentFactory = experimentFactory;
}
@Override
public void configure(final Subparser subparser) {
super.configure(subparser);
subparser.addArgument("--max-concurrency")
.type(Integer.class)
.dest(MAX_CONCURRENCY_ARGUMENT)
.setDefault(DEFAULT_MAX_CONCURRENCY)
.help("Max concurrency for DynamoDB operations");
}
@Override
protected void run(final Environment environment,
final Namespace namespace,
final WhisperServerConfiguration configuration,
final CommandDependencies commandDependencies) throws Exception {
final PushNotificationExperiment<?> experiment =
experimentFactory.buildExperiment(commandDependencies, configuration);
final int maxConcurrency = namespace.getInt(MAX_CONCURRENCY_ARGUMENT);
commandDependencies.pushNotificationExperimentSamples()
.discardSamples(experiment.getExperimentName(), maxConcurrency).join();
}
}
@@ -0,0 +1,124 @@
package org.whispersystems.textsecuregcm.workers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.core.Application;
import io.dropwizard.core.setup.Environment;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
import org.whispersystems.textsecuregcm.experiment.PushNotificationExperiment;
import org.whispersystems.textsecuregcm.experiment.PushNotificationExperimentSample;
import org.whispersystems.textsecuregcm.experiment.PushNotificationExperimentSamples;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuples;
import reactor.util.retry.Retry;
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
import javax.annotation.Nullable;
import java.time.Duration;
import java.util.UUID;
public class FinishPushNotificationExperimentCommand<T> extends AbstractCommandWithDependencies {
private final PushNotificationExperimentFactory<T> experimentFactory;
private static final int DEFAULT_MAX_CONCURRENCY = 16;
@VisibleForTesting
static final String MAX_CONCURRENCY_ARGUMENT = "max-concurrency";
private static final Logger log = LoggerFactory.getLogger(FinishPushNotificationExperimentCommand.class);
public FinishPushNotificationExperimentCommand(final String name,
final String description,
final PushNotificationExperimentFactory<T> experimentFactory) {
super(new Application<>() {
@Override
public void run(final WhisperServerConfiguration configuration, final Environment environment) {
}
}, name, description);
this.experimentFactory = experimentFactory;
}
@Override
public void configure(final Subparser subparser) {
super.configure(subparser);
subparser.addArgument("--max-concurrency")
.type(Integer.class)
.dest(MAX_CONCURRENCY_ARGUMENT)
.setDefault(DEFAULT_MAX_CONCURRENCY)
.help("Max concurrency for DynamoDB operations");
}
@Override
protected void run(final Environment environment,
final Namespace namespace,
final WhisperServerConfiguration configuration,
final CommandDependencies commandDependencies) throws Exception {
final PushNotificationExperiment<T> experiment =
experimentFactory.buildExperiment(commandDependencies, configuration);
final int maxConcurrency = namespace.getInt(MAX_CONCURRENCY_ARGUMENT);
log.info("Finishing \"{}\" with max concurrency: {}", experiment.getExperimentName(), maxConcurrency);
final AccountsManager accountsManager = commandDependencies.accountsManager();
final PushNotificationExperimentSamples pushNotificationExperimentSamples = commandDependencies.pushNotificationExperimentSamples();
final Flux<PushNotificationExperimentSample<T>> finishedSamples =
pushNotificationExperimentSamples.getDevicesPendingFinalState(experiment.getExperimentName())
.flatMap(accountIdentifierAndDeviceId ->
Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(accountIdentifierAndDeviceId.getT1()))
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1)))
.map(maybeAccount -> Tuples.of(accountIdentifierAndDeviceId.getT1(),
accountIdentifierAndDeviceId.getT2(), maybeAccount)), maxConcurrency)
.map(accountIdentifierAndDeviceIdAndMaybeAccount -> {
final UUID accountIdentifier = accountIdentifierAndDeviceIdAndMaybeAccount.getT1();
final byte deviceId = accountIdentifierAndDeviceIdAndMaybeAccount.getT2();
@Nullable final Account account = accountIdentifierAndDeviceIdAndMaybeAccount.getT3()
.orElse(null);
@Nullable final Device device = accountIdentifierAndDeviceIdAndMaybeAccount.getT3()
.flatMap(a -> a.getDevice(deviceId))
.orElse(null);
return Tuples.of(accountIdentifier, deviceId, experiment.getState(account, device));
})
.flatMap(accountIdentifierAndDeviceIdAndFinalState -> {
final UUID accountIdentifier = accountIdentifierAndDeviceIdAndFinalState.getT1();
final byte deviceId = accountIdentifierAndDeviceIdAndFinalState.getT2();
final T finalState = accountIdentifierAndDeviceIdAndFinalState.getT3();
return Mono.fromFuture(() -> {
try {
return pushNotificationExperimentSamples.recordFinalState(accountIdentifier, deviceId,
experiment.getExperimentName(), finalState);
} catch (final JsonProcessingException e) {
throw new RuntimeException(e);
}
})
.onErrorResume(ConditionalCheckFailedException.class, throwable -> Mono.empty())
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1)))
.onErrorResume(throwable -> {
log.warn("Failed to record final state for {}:{} in experiment {}",
accountIdentifier, deviceId, experiment.getExperimentName(), throwable);
return Mono.empty();
});
}, maxConcurrency)
.flatMap(Mono::justOrEmpty);
experiment.analyzeResults(finishedSamples);
}
}
Loaded 100 of 204 files, more files were not shown because too many files have changed in this diff. Show more