Compare commits

...
Author SHA1 Message Date
Chris Eager 5ec8628b51 Update to the latest version of the spam filter 2026-02-04 15:59:34 -06:00
Jon Chambers ad21f002ab Add a counter to verify that it's safe to remove legacy combined UAK credentials 2026-02-04 15:50:59 -06:00
Jon Chambers 1e5fcbdd20 Add a utility method for getting UA tags from request contexts 2026-02-04 15:50:59 -06:00
Ravi Khadiwala d34fc29ba2 Add null checks in IncomingMessageList 2026-02-04 15:50:45 -06:00
Chris Eager e0bf1df16f Update to the latest version of the spam filter 2026-02-04 14:19:23 -06:00
Chris Eager 9a1c450458 Make VerificationSession.sessionId not-null 2026-02-04 12:07:44 -06:00
Chris Eager e5209d84bf Update to the latest version of the spam filter 2026-02-04 10:21:45 -06:00
Chris Eager 969788b267 Include sessionId in VerificationSession record 2026-02-04 10:06:25 -06:00
Chris Eager d0bbaaea52 Update to the latest version of the spam filter 2026-01-30 13:13:26 -06:00
Chris Eager b01ef94c69 Update to the latest version of the spam filter 2026-01-30 11:52:34 -06:00
Jonathan Klabunde Tomer 040f3190cb directly subscribe to item publisher in account crawlers 2026-01-30 10:16:26 -06:00
Chris Eager 77bf44fda5 Remove deprecated /v2/accounts/phone_number_identity_key_distribution 2026-01-30 10:13:41 -06:00
Ravi Khadiwala 185654fc10 Use userAgent instead of signalAgent as metrics platform tag 2026-01-30 10:13:21 -06:00
Ravi Khadiwala 159e1f13f0 Fix credential age calculation 2026-01-30 10:13:21 -06:00
Jon Chambers 61ab765391 Require that LinkDeviceRequest has non-null account attributes 2026-01-30 10:13:11 -06:00
Jon Chambers 63c39645d2 Add a (failing!) test for attempting to link a device with null account attributes 2026-01-30 10:13:11 -06:00
Chris Eager cf518ce910 Update to the latest version of the spam filter 2026-01-30 09:44:20 -06:00
Ravi Khadiwala e14dbfc9ad Fix merge conflict in HlrLookupResult 2026-01-29 11:24:18 -06:00
Ravi Khadiwala 734d369fb1 Update to the latest version of the spam filter 2026-01-29 11:17:08 -06:00
ravi-signal ee81faa82d Add an allow-list for gRPC methods 2026-01-29 11:15:04 -06:00
Jon Chambers c0d0d5f5da Extract "is ported" data from HLR Lookup responses 2026-01-29 12:14:26 -05:00
Jon Chambers ff8194ae5f Add "is ported" to CarrierData 2026-01-29 12:14:26 -05:00
Jon Chambers c69abb5200 Instrument credits spent 2026-01-29 12:14:00 -05:00
Ravi Khadiwala fb1c20582e Instrument /v2/svr/auth/check credential age 2026-01-28 17:44:11 -05:00
Ravi Khadiwala 0357b25f92 Update to the latest version of the spam filter 2026-01-28 16:42:23 -06:00
Ravi Khadiwala d197e22e0a Fix argument to updateWithRetries updater 2026-01-28 17:39:32 -05:00
ravi-signal e6116044f8 Instrument registration recovery password modifications 2026-01-28 16:37:50 -06:00
ravi-signal 2a7e99e9f0 Update credentials and calling gRPC services to new error model 2026-01-28 16:36:12 -06:00
Ravi Khadiwala 8023a9346f Convert call quality gRPC service to new error model 2026-01-28 17:35:11 -05:00
Ravi Khadiwala 517c5b8056 Call CallQualitySurveryManager#validateRequest 2026-01-28 17:35:11 -05:00
dependabot[bot] a6a089e93f Bump actions/setup-java in the minor-actions-dependencies group
Bumps the minor-actions-dependencies group with 1 update: [actions/setup-java](https://github.com/actions/setup-java).


Updates `actions/setup-java` from 5.0.0 to 5.2.0
- [Release notes](https://github.com/actions/setup-java/releases)
- [Commits](https://github.com/actions/setup-java/compare/dded0888837ed1f317902acf8a20df0ad188d165...be666c2fcd27ec809703dec50e508c2fdc7f6654)

---
updated-dependencies:
- dependency-name: actions/setup-java
  dependency-version: 5.2.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-actions-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-01-26 13:48:55 -05:00
dependabot[bot] 6c2999dd55 Bump actions/checkout from 5.0.0 to 6.0.2
Bumps [actions/checkout](https://github.com/actions/checkout) from 5.0.0 to 6.0.2.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/08c6903cd8c0fde910a37f88322edcfb5dd907a8...de0fac2e4500dabe0009e67214ff5f5447ce83dd)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: 6.0.2
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-01-26 13:05:12 -05:00
dependabot[bot] 14862c58c8 Bump aws-actions/configure-aws-credentials from 4.2.1 to 5.1.1
Bumps [aws-actions/configure-aws-credentials](https://github.com/aws-actions/configure-aws-credentials) from 4.2.1 to 5.1.1.
- [Release notes](https://github.com/aws-actions/configure-aws-credentials/releases)
- [Changelog](https://github.com/aws-actions/configure-aws-credentials/blob/main/CHANGELOG.md)
- [Commits](https://github.com/aws-actions/configure-aws-credentials/compare/b47578312673ae6fa5b5096b330d9fbac3d116df...61815dcd50bd041e203e49132bacad1fd04d2708)

---
updated-dependencies:
- dependency-name: aws-actions/configure-aws-credentials
  dependency-version: 5.1.1
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-01-26 13:05:02 -05:00
Ravi Khadiwala 645161cc09 add dependabot.yml 2026-01-26 11:36:30 -05:00
Jon Chambers 065e730200 Update to the latest version of the spam filter 2026-01-23 16:37:38 -05:00
Ravi Khadiwala 7e7bef32cc Convert service protos to line comments 2026-01-23 16:37:01 -05:00
ravi-signal 5b1d4ce95e Convert backup services to use new error model 2026-01-23 14:25:15 -06:00
Ravi Khadiwala 12d9637f21 Update to the latest version of the spam filter 2026-01-23 14:24:17 -06:00
ravi-signal 924ab88e93 Update dependencies 2026-01-23 13:32:20 -06:00
Jon Chambers 187cd9e163 Update to the latest version of the spam filter 2026-01-23 12:30:21 -05:00
Jon Chambers 2ed60209b1 Store carrier information in verification sessions 2026-01-23 12:09:19 -05:00
Jon Chambers 9ffb588c6a Pass carrier data from lookup services to registration service 2026-01-23 12:09:19 -05:00
Jon Chambers 5043175cb4 Standardize on javax.annotation.Nullable 2026-01-23 12:09:19 -05:00
Jon Chambers 953a473c74 Resolve minor warnings/suggestions throughout VerificationController 2026-01-23 12:09:19 -05:00
Jon Chambers 3b87527f39 Add a system to look up mobile network data 2026-01-23 11:51:14 -05:00
ravi-signal 023296feaf Make Backup methods synchronous 2026-01-21 14:01:58 -06:00
Jon Chambers b4db86a39b Update to the latest version of the spam filter 2026-01-21 13:52:34 -05:00
Jon Chambers e0b89d6228 Update AWS SDK to 2.41.11 2026-01-21 10:22:07 -06:00
Chris Eager bcd8ed8d35 Update to the latest version of the spam filter 2026-01-21 10:21:32 -06:00
Ameya Lokare cb9b90b81d Update to the latest version of the spam filter 2026-01-14 11:56:36 -08:00
Ameya Lokare 265bcfe51b Update to the latest version of the spam filter 2026-01-14 11:12:04 -08:00
Jon Chambers 4b1a0259fc Resolve a warning about potentially-null results from a Flux#toList call 2026-01-14 09:36:53 -06:00
Jon Chambers 14e7652339 Remove an unused logger 2026-01-14 09:36:53 -06:00
Jon Chambers 8d53b2d8a6 Make key-fetching asynchronous 2026-01-14 09:36:53 -06:00
Chris Eager 8ee097d25a Remove temporary unidentifiedDelivery.rotated.privateKey 2026-01-14 09:36:26 -06:00
Jordan Rose 94c9d48da1 Add option to omit full signer certificate from sealed sender certificates 2026-01-13 13:43:28 -06:00
Ravi Khadiwala a1b1d051f5 Use enriched gRPC status errors 2026-01-13 11:24:35 -05:00
Jon Chambers 77eaec0150 Update to the latest version of the spam filter 2026-01-13 11:16:01 -05:00
Jon Chambers 7d39f72ed6 Update to Testcontainers 2.0.3 2026-01-13 11:02:04 -05:00
Jon Chambers 8c3a38979a Update inadvertent/legacy JUnit 4 imports to JUnit 5 2026-01-13 11:02:04 -05:00
Jon Chambers af02cb93c0 Update to the latest version of the spam filter 2026-01-13 10:41:54 -05:00
Jon Chambers c25c8807a6 Notify registered message delivery listeners when messages are delivered 2026-01-13 10:24:11 -05:00
Jon Chambers dad2bd5c29 Introduce MessageDeliveryListener 2026-01-13 10:24:11 -05:00
Chris Eager 7e511d1f66 Add temporary unidentifiedDelivery.rotated.privateKey 2026-01-12 16:26:37 -06:00
Chris Eager 49daf3909c Set paymentProcessing = true for draft invoices 2026-01-09 16:30:07 -06:00
Chris Eager a1f7710ccb Remove explicit percentile configuration from DistributionStatisticConfig 2026-01-06 15:48:15 -05:00
ravi-signal 807b08b31b Make googlePlayBilling.credentialsJson not a secret 2026-01-06 14:47:45 -06:00
Ravi Khadiwala 9a43f76663 Add source tag to appstore API errors 2026-01-06 15:47:05 -05:00
Chris Eager 7f5097bd33 Update logback to 1.5.23 2026-01-05 17:01:11 -06:00
Chris Eager 54443f7015 Set the logging context on the PatternLayout 2026-01-05 17:01:11 -06:00
Chris Eager e1c44dd374 Remove Datadog fields from logstash output 2026-01-05 17:01:11 -06:00
ravi-signal eaabbd5188 Add nested message validation 2026-01-05 16:23:11 -06:00
ravi-signal 9c4047a90b Remove row-based one-time PQ key store 2025-12-10 16:22:03 -06:00
Katherine Yen 33f506a431 Add registration ID to GetPreKeysResponse 2025-12-10 16:21:34 -06:00
Jon Chambers 7fd0cb32f6 Revert "Include client version in the large message counter tags"
This reverts commit 3ac7a41f9b.
2025-12-10 17:21:26 -05:00
ravi-signal fecb032d8f Ignore failures to update cache after a read 2025-12-10 16:21:18 -06:00
Jon Chambers 1913dbf6f9 Update to the latest version of the spam filter 2025-12-10 11:18:36 -05:00
Jon Chambers de09de895b Update to the latest version of the spam filter 2025-12-10 11:03:04 -05:00
sunday 09942b17a0 feat: add static factory for custom S3 endpoint in S3ObjectMonitor for local testing 2025-12-10 10:52:19 -05:00
Jon Chambers 1d74ecf092 Update to the latest version of the spam filter 2025-12-10 09:56:34 -05:00
Jon Chambers 3ac7a41f9b Include client version in the large message counter tags 2025-12-10 09:46:15 -05:00
Jon Chambers e1c901c5cf Increment a counter when we receive large-but-not-disallowed messages 2025-12-10 09:46:15 -05:00
Jon Chambers 9c35ad0722 Introduce RegistrationFraudChecker#checkSendVerificationCodeAttempt 2025-12-10 09:42:29 -05:00
Jon Chambers 5f25b6a412 Use long instead of int for rate limiter permits 2025-12-10 09:41:51 -05:00
Jon Chambers 77d04ccb70 Rename "dynamic rate limiter" to "leaky bucket rate limiter" 2025-12-10 09:29:44 -05:00
Jonathan Klabunde Tomer 504310cc14 handle Logstash markers in otel logs 2025-12-10 09:29:23 -05:00
Jon Chambers 62798229bf Fix a very (survery?) small typo 2025-12-10 09:29:04 -05:00
Jordan Rose 730e0205f8 Update to libsignal v0.86.6 2025-12-05 11:01:38 -05:00
Katherine 31d6ac71a4 Retire creation timestamp from device endpoints 2025-12-05 10:55:20 -05:00
Chris Eager b887d1f7c0 Fix potentially null errorCode in switch 2025-12-05 10:54:58 -05:00
Jon Chambers 92f8623ad8 Update to the latest version of the spam filter 2025-12-04 09:38:39 -05:00
Jon Chambers 7445225906 Update to the latest version of the spam filter 2025-12-03 16:50:27 -05:00
Jon Chambers 0d2bee7599 Update to the latest version of the spam filter 2025-12-03 15:07:06 -05:00
Jon Chambers 78aa81dd56 Pass client-provided route optimization data to registration service 2025-12-03 14:55:43 -05:00
Jon Chambers 08f6ec639c Update to the latest version of the spam filter 2025-12-02 15:59:54 -05:00
Jonathan Klabunde Tomer 6c3cfc88b5 retire /v1/config
It's been supplanted by /v2/config for all clients beyond the 90-day window.
We still have [some traffic](https://signal.grafana.net/goto/bf5tjk346v1moa?orgId=1)
but it's all from expired/third-party clients (note the lack of a recognized
version number in the client-version tag).
2025-12-02 12:52:39 -08:00
Jon Chambers 389d44fd80 Remove legacy delete-via-REST plumbing 2025-12-02 15:45:18 -05:00
Jon Chambers 7604306818 Retire REST-based message deletion 2025-12-02 15:45:18 -05:00
Jon Chambers 92e133b21f Shut down command dependencies in LIFO order 2025-12-02 15:45:01 -05:00
Jon Chambers 4af50986e0 Minor corrections to docs for POST /v1/registration 2025-12-02 15:44:43 -05:00
Jon Chambers c72458b47a Perform basic input validation on call quality survey responses 2025-12-01 09:56:09 -05:00
Jon Chambers aa2f9e5a65 Accept start/end timestamps as milliseconds since the epoch 2025-11-26 09:00:54 -05:00
208 changed files with 6280 additions and 5081 deletions

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
version: 2
updates:
- package-ecosystem: github-actions
directory: /
schedule:
interval: monthly
groups:
minor-actions-dependencies:
# GitHub Actions: Only group minor and patch updates (we want to carefully review major updates)
update-types: [ minor, patch ]
- package-ecosystem: maven
directory: /
schedule:
interval: monthly
groups:
minor-java-dependencies:
# Java: Only group minor and patch updates (we want to carefully review major updates)
update-types: [ minor, patch ]
+2 -2
View File
@@ -11,8 +11,8 @@ jobs:
contents: write
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
- uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0
with:
distribution: 'temurin'
java-version-file: .java-version
+3 -3
View File
@@ -18,13 +18,13 @@ jobs:
id-token: write
contents: read
steps:
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
- uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0
with:
distribution: 'temurin'
java-version-file: .java-version
cache: 'maven'
- uses: aws-actions/configure-aws-credentials@b47578312673ae6fa5b5096b330d9fbac3d116df # v5.0.0
- uses: aws-actions/configure-aws-credentials@61815dcd50bd041e203e49132bacad1fd04d2708 # v5.0.0
name: Configure AWS credentials from Test account
with:
role-to-assume: ${{ vars.AWS_ROLE }}
+2 -2
View File
@@ -25,9 +25,9 @@ jobs:
options: --name foundationdb1
steps:
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: Set up JDK
uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0
with:
distribution: 'temurin'
java-version-file: .java-version
@@ -18,6 +18,7 @@ import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswords;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
import org.whispersystems.textsecuregcm.storage.VerificationSessions;
import org.whispersystems.textsecuregcm.util.Util;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
@@ -62,7 +63,8 @@ public class IntegrationTools {
public CompletableFuture<Void> populateRecoveryPassword(final String phoneNumber, final byte[] password) {
return phoneNumberIdentifiers
.getPhoneNumberIdentifier(phoneNumber)
.thenCompose(pni -> registrationRecoveryPasswordsManager.store(pni, password));
.thenCompose(pni -> registrationRecoveryPasswordsManager.store(pni, password))
.thenRun(Util.NOOP);
}
public CompletableFuture<Optional<String>> peekVerificationSessionPushChallenge(final String sessionId) {
+29 -16
View File
@@ -14,6 +14,14 @@
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>signal-build-artifacts</id>
<name>Signal Build Artifacts</name>
<url>https://build-artifacts.signal.org/libraries/maven</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
@@ -37,10 +45,10 @@
</modules>
<properties>
<aws.sdk2.version>2.33.8</aws.sdk2.version>
<braintree.version>3.44.0</braintree.version>
<aws.sdk2.version>2.41.11</aws.sdk2.version>
<braintree.version>3.47.0</braintree.version>
<commons-csv.version>1.14.1</commons-csv.version>
<commons-io.version>2.20.0</commons-io.version>
<commons-io.version>2.21.0</commons-io.version>
<dropwizard.version>4.0.16</dropwizard.version>
<!-- Note: when updating FoundationDB, also include a copy of `libfdb_c.so` from the FoundationDB release at
src/main/jib/usr/lib/libfdb_c.so. We use x86_64 builds without AVX instructions enabled (i.e. FoundationDB versions
@@ -49,39 +57,39 @@
<foundationdb.version>7.3.62</foundationdb.version>
<foundationdb.api-version>730</foundationdb.api-version>
<foundationdb.client-library-sha256>bfed237b787fae3cde1222676e6bfbb0d218fc27bf9e903397a7a7aa96fb2d33</foundationdb.client-library-sha256>
<google-cloud-libraries.version>26.67.0</google-cloud-libraries.version>
<google-cloud-libraries.version>26.74.0</google-cloud-libraries.version>
<grpc.version>1.73.0</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
<gson.version>2.13.2</gson.version>
<guava.version>33.5.0-jre</guava.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.20.0</jackson.version>
<jackson.version>2.21.0</jackson.version>
<junit-pioneer.version>2.3.0</junit-pioneer.version>
<jsr305.version>3.0.2</jsr305.version>
<kotlin.version>2.2.20</kotlin.version>
<!-- Logback 1.5.14+ has a null pointer bug: https://github.com/qos-ch/logback/issues/929. -->
<logback.version>1.5.13</logback.version>
<kotlin.version>2.3.0</kotlin.version>
<logback.version>1.5.25</logback.version>
<logback-access-common.version>2.0.6</logback-access-common.version>
<lettuce.version>6.8.1.RELEASE</lettuce.version>
<libphonenumber.version>9.0.13</libphonenumber.version>
<logstash.logback.version>8.1</logstash.logback.version>
<log4j-bom.version>2.25.1</log4j-bom.version>
<log4j-bom.version>2.25.3</log4j-bom.version>
<luajava.version>3.5.0</luajava.version>
<micrometer.version>1.15.4</micrometer.version>
<micrometer.version>1.16.2</micrometer.version>
<netty.version>4.1.127.Final</netty.version>
<!-- Must be less than or equal to the value from Google libraries-bom which controls the protobuf runtime version.
See https://protobuf.dev/support/cross-version-runtime-guarantee/. -->
<protoc.version>4.29.4</protoc.version>
<pushy.version>0.15.4</pushy.version>
<reactive.grpc.version>1.2.4</reactive.grpc.version>
<reactor-bom.version>2024.0.10</reactor-bom.version> <!-- 3.7.11, see https://github.com/reactor/reactor#bom-versioning-scheme -->
<reactor-bom.version>2025.0.2</reactor-bom.version> <!-- 3.8.2, see https://github.com/reactor/reactor#bom-versioning-scheme -->
<resilience4j.version>2.3.0</resilience4j.version>
<semver4j.version>3.1.0</semver4j.version>
<simple-grpc.version>0.1.0</simple-grpc.version>
<simple-grpc.version>0.2.0</simple-grpc.version>
<slf4j.version>2.0.17</slf4j.version>
<stripe.version>30.2.0</stripe.version>
<swagger.version>2.2.36</swagger.version>
<testcontainers.version>1.21.3</testcontainers.version>
<stripe.version>31.2.0</stripe.version>
<swagger.version>2.2.42</swagger.version>
<testcontainers.version>2.0.3</testcontainers.version>
<!-- images to use in tests via testcontainers -->
<dynamodb.image>amazon/dynamodb-local:3.0.0@sha256:2fed5e3a965a4ba5aa6ac82baec57058b5a3848e959d705518f3fd579a77e76b</dynamodb.image>
@@ -277,6 +285,11 @@
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>com.redis</groupId>
<artifactId>testcontainers-redis</artifactId>
@@ -286,7 +299,7 @@
<dependency>
<groupId>org.signal</groupId>
<artifactId>libsignal-server</artifactId>
<version>0.80.3</version>
<version>0.86.6</version>
</dependency>
<dependency>
<groupId>org.signal</groupId>
+3 -3
View File
@@ -4,9 +4,6 @@ stripe.idempotencyKeyGenerator: abcdefg12345678= # base64 for creating request i
braintree.publicKey: unset
braintree.privateKey: unset
googlePlayBilling.credentialsJson: |
{ "json": true }
appleAppStore.encodedKey: unset
directoryV2.client.userAuthenticationTokenSharedSecret: abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG= # base64-encoded secret shared with CDS to generate auth tokens for Signal users
@@ -100,3 +97,6 @@ turn.cloudflare.apiToken: ABCDEFGHIJKLM
linkDevice.secret: AAAAAAAAAAA=
tlsKeyStore.password: unset
hlrLookup.apiKey: AAAAAAAAAAA
hlrLookup.apiSecret: AAAAAAAAAAA
+9 -3
View File
@@ -48,7 +48,10 @@ braintree:
}
googlePlayBilling:
credentialsJson: secret://googlePlayBilling.credentialsJson
credentialsJson: |
{
"credential": "configuration"
}
packageName: package.name
applicationName: test
productIdToLevel: {}
@@ -108,8 +111,6 @@ dynamoDbTables:
tableName: Example_Keys
ecSignedPreKeys:
tableName: Example_EC_Signed_Pre_Keys
pqKeys:
tableName: Example_PQ_Keys
pagedPqKeys:
tableName: Example_PQ_Paged_Keys
pqLastResortKeys:
@@ -275,6 +276,7 @@ unidentifiedDelivery:
certificate: CgIIAQ==
privateKey: secret://unidentifiedDelivery.privateKey
expiresDays: 7
embedSigner: true
shortCode:
baseUrl: https://example.com/shortcodes/
@@ -526,3 +528,7 @@ callQualitySurvey:
{
"credential": "configuration"
}
hlrLookup:
apiKey: secret://hlrLookup.apiKey
apiSecret: secret://hlrLookup.apiSecret
+7 -26
View File
@@ -11,11 +11,11 @@
<artifactId>service</artifactId>
<properties>
<firebase-admin.version>9.6.0</firebase-admin.version>
<java-uuid-generator.version>5.1.0</java-uuid-generator.version>
<firebase-admin.version>9.7.0</firebase-admin.version>
<java-uuid-generator.version>5.2.0</java-uuid-generator.version>
<google-androidpublisher.version>v3-rev20250904-2.0.0</google-androidpublisher.version>
<storekit.version>3.6.0</storekit.version>
<webauthn4j.version>0.29.6.RELEASE</webauthn4j.version>
<storekit.version>4.0.0</storekit.version>
<webauthn4j.version>0.30.2.RELEASE</webauthn4j.version>
<java-jwt.version>4.5.0</java-jwt.version>
</properties>
@@ -205,7 +205,7 @@
<groupId>io.opentelemetry.instrumentation</groupId>
<artifactId>opentelemetry-logback-appender-1.0</artifactId>
<!-- *all* opentelemetry-logback-appender versions are "alpha" despite the advanced version number -->
<version>2.19.0-alpha</version>
<version>2.22.0-alpha</version>
<exclusions>
<!-- incubator packages aren't included in the opentelemetry BOM, and we don't use them -->
<exclusion>
@@ -266,26 +266,12 @@
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-pubsub</artifactId>
<exclusions>
<!-- our direct import of guava brings in a more recent version of failureaccess, so excluding it here -->
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>failureaccess</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.firebase</groupId>
<artifactId>firebase-admin</artifactId>
<version>${firebase-admin.version}</version>
<exclusions>
<!-- our direct import of guava brings in a more recent version of failureaccess, so excluding it here -->
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>failureaccess</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
@@ -297,11 +283,6 @@
<groupId>io.opentelemetry.instrumentation</groupId>
<artifactId>opentelemetry-instrumentation-api-incubator</artifactId>
</exclusion>
<!-- our direct import of guava brings in a more recent version of failureaccess, so excluding it here -->
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>failureaccess</artifactId>
</exclusion>
</exclusions>
</dependency>
@@ -521,13 +502,13 @@
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>localstack</artifactId>
<artifactId>testcontainers-localstack</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<artifactId>testcontainers-junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
@@ -31,6 +31,7 @@ import org.whispersystems.textsecuregcm.configuration.DeviceCheckConfiguration;
import org.whispersystems.textsecuregcm.configuration.DirectoryV2Configuration;
import org.whispersystems.textsecuregcm.configuration.DynamoDbClientFactory;
import org.whispersystems.textsecuregcm.configuration.DynamoDbTables;
import org.whispersystems.textsecuregcm.configuration.GrpcAllowListConfiguration;
import org.whispersystems.textsecuregcm.configuration.ExternalRequestFilterConfiguration;
import org.whispersystems.textsecuregcm.configuration.FaultTolerantRedisClientFactory;
import org.whispersystems.textsecuregcm.configuration.FaultTolerantRedisClusterFactory;
@@ -39,6 +40,7 @@ import org.whispersystems.textsecuregcm.configuration.GcpAttachmentsConfiguratio
import org.whispersystems.textsecuregcm.configuration.GenericZkConfig;
import org.whispersystems.textsecuregcm.configuration.GooglePlayBillingConfiguration;
import org.whispersystems.textsecuregcm.configuration.GrpcConfiguration;
import org.whispersystems.textsecuregcm.configuration.HlrLookupConfiguration;
import org.whispersystems.textsecuregcm.configuration.IdlePrimaryDeviceReminderConfiguration;
import org.whispersystems.textsecuregcm.configuration.KeyTransparencyServiceConfiguration;
import org.whispersystems.textsecuregcm.configuration.LinkDeviceSecretConfiguration;
@@ -332,6 +334,11 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private Map<String, @Valid RetryConfiguration> retries = Collections.emptyMap();
@Valid
@NotNull
@JsonProperty
private HlrLookupConfiguration hlrLookup;
@JsonProperty
@Valid
@NotNull
@@ -342,6 +349,11 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private GrpcConfiguration grpc;
@NotNull
@Valid
@JsonProperty
private GrpcAllowListConfiguration grpcAllowList = new GrpcAllowListConfiguration();
@Valid
@NotNull
@JsonProperty
@@ -583,6 +595,10 @@ public class WhisperServerConfiguration extends Configuration {
return grpc;
}
public GrpcAllowListConfiguration getGrpcAllowList() {
return grpcAllowList;
}
public S3ObjectMonitorFactory getAsnTableConfiguration() {
return asnTable;
}
@@ -590,4 +606,8 @@ public class WhisperServerConfiguration extends Configuration {
public CallQualitySurveyConfiguration getCallQualitySurveyConfiguration() {
return callQualitySurvey;
}
public HlrLookupConfiguration getHlrLookupConfiguration() {
return hlrLookup;
}
}
@@ -4,8 +4,8 @@
*/
package org.whispersystems.textsecuregcm;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import static java.util.Objects.requireNonNull;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.collect.Lists;
import com.webauthn4j.appattest.DeviceCheckManager;
@@ -125,7 +125,6 @@ import org.whispersystems.textsecuregcm.controllers.ProfileController;
import org.whispersystems.textsecuregcm.controllers.ProvisioningController;
import org.whispersystems.textsecuregcm.controllers.RegistrationController;
import org.whispersystems.textsecuregcm.controllers.RemoteConfigController;
import org.whispersystems.textsecuregcm.controllers.RemoteConfigControllerV1;
import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery2Controller;
import org.whispersystems.textsecuregcm.controllers.StickerController;
@@ -144,6 +143,7 @@ import org.whispersystems.textsecuregcm.filters.TimestampResponseFilter;
import org.whispersystems.textsecuregcm.grpc.AccountsAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.AccountsGrpcService;
import org.whispersystems.textsecuregcm.grpc.CallQualitySurveyGrpcService;
import org.whispersystems.textsecuregcm.grpc.GrpcAllowListInterceptor;
import org.whispersystems.textsecuregcm.grpc.ErrorMappingInterceptor;
import org.whispersystems.textsecuregcm.grpc.ExternalServiceCredentialsAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.ExternalServiceCredentialsGrpcService;
@@ -167,6 +167,7 @@ import org.whispersystems.textsecuregcm.limits.RateLimitByIpFilter;
import org.whispersystems.textsecuregcm.limits.RateLimitChallengeManager;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.limits.RedisMessageDeliveryLoopMonitor;
import org.whispersystems.textsecuregcm.mappers.BackupExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.DeviceLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.GrpcStatusRuntimeExceptionMapper;
@@ -244,7 +245,6 @@ import org.whispersystems.textsecuregcm.storage.RepeatedUseKEMSignedPreKeyStore;
import org.whispersystems.textsecuregcm.storage.ReportMessageDynamoDb;
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
import org.whispersystems.textsecuregcm.storage.SingleUseECPreKeyStore;
import org.whispersystems.textsecuregcm.storage.SingleUseKEMPreKeyStore;
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
import org.whispersystems.textsecuregcm.storage.Subscriptions;
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
@@ -258,6 +258,8 @@ import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator;
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
import org.whispersystems.textsecuregcm.telephony.CarrierDataProvider;
import org.whispersystems.textsecuregcm.telephony.hlrlookup.HlrLookupCarrierDataProvider;
import org.whispersystems.textsecuregcm.util.BufferingInterceptor;
import org.whispersystems.textsecuregcm.util.ManagedAwsCrt;
import org.whispersystems.textsecuregcm.util.ManagedExecutors;
@@ -470,7 +472,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
.build();
KeysManager keysManager = new KeysManager(
new SingleUseECPreKeyStore(dynamoDbAsyncClient, config.getDynamoDbTables().getEcKeys().getTableName()),
new SingleUseKEMPreKeyStore(dynamoDbAsyncClient, config.getDynamoDbTables().getKemKeys().getTableName()),
new PagedSingleUseKEMPreKeyStore(
dynamoDbAsyncClient,
asyncKeysS3Client,
@@ -582,6 +583,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
.maxThreads(2)
.minThreads(2)
.build();
ExecutorService hlrLookupHttpExecutor = ExecutorServiceBuilder.of(environment, "hlrLookup")
.maxThreads(2)
.minThreads(2)
.build();
ExecutorService subscriptionProcessorExecutor = ManagedExecutors.newVirtualThreadPerTaskExecutor(
"subscriptionProcessor",
@@ -636,6 +641,14 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords);
UsernameHashZkProofVerifier usernameHashZkProofVerifier = new UsernameHashZkProofVerifier();
final CarrierDataProvider carrierDataProvider =
new HlrLookupCarrierDataProvider(config.getHlrLookupConfiguration().apiKey().value(),
config.getHlrLookupConfiguration().apiSecret().value(),
hlrLookupHttpExecutor,
config.getHlrLookupConfiguration().circuitBreakerConfigurationName(),
config.getHlrLookupConfiguration().retryConfigurationName(),
retryExecutor);
RegistrationServiceClient registrationServiceClient = config.getRegistrationServiceConfiguration()
.build(environment, registrationCallbackExecutor, registrationIdentityTokenRefreshExecutor);
KeyTransparencyServiceClient keyTransparencyServiceClient = new KeyTransparencyServiceClient(
@@ -771,7 +784,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getBraintree().graphqlUrl(), currencyManager, config.getBraintree().pubSubPublisher().build(),
config.getBraintree().circuitBreakerConfigurationName(), subscriptionProcessorExecutor);
GooglePlayBillingManager googlePlayBillingManager = new GooglePlayBillingManager(
new ByteArrayInputStream(config.getGooglePlayBilling().credentialsJson().value().getBytes(StandardCharsets.UTF_8)),
new ByteArrayInputStream(config.getGooglePlayBilling().credentialsJson().getBytes(StandardCharsets.UTF_8)),
config.getGooglePlayBilling().packageName(),
config.getGooglePlayBilling().applicationName(),
config.getGooglePlayBilling().productIdToLevel());
@@ -864,6 +877,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final MetricServerInterceptor metricServerInterceptor = new MetricServerInterceptor(Metrics.globalRegistry, clientReleaseManager);
final ErrorMappingInterceptor errorMappingInterceptor = new ErrorMappingInterceptor();
final GrpcAllowListInterceptor grpcAllowListInterceptor =
new GrpcAllowListInterceptor(config.getGrpcAllowList().enableAll(), config.getGrpcAllowList().enabledServices(), config.getGrpcAllowList().enabledMethods());
final RequestAttributesInterceptor requestAttributesInterceptor = new RequestAttributesInterceptor();
final ValidatingInterceptor validatingInterceptor = new ValidatingInterceptor();
@@ -884,6 +899,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
// Note: interceptors run in the reverse order they are added; the remote deprecation filter
// depends on the user-agent context so it has to come first here!
validatingInterceptor,
grpcAllowListInterceptor,
metricServerInterceptor,
errorMappingInterceptor,
remoteDeprecationFilter,
@@ -903,6 +919,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
// depends on the user-agent context so it has to come first here!
grpcExternalRequestFilter,
validatingInterceptor,
grpcAllowListInterceptor,
metricServerInterceptor,
errorMappingInterceptor,
remoteDeprecationFilter,
@@ -1041,6 +1058,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
});
spamFilter.map(SpamFilter::getReportedMessageListener).ifPresent(reportMessageManager::addListener);
spamFilter.map(SpamFilter::getMessageDeliveryListener).ifPresent(messageSender::addMessageDeliveryListener);
final HttpClient shortCodeRetrieverHttpClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2)
.connectTimeout(Duration.ofSeconds(10)).build();
@@ -1073,7 +1091,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new CallLinkController(rateLimiters, callingGenericZkSecretParams),
new CallQualitySurveyController(callQualitySurveyManager),
new CertificateController(accountsManager, new CertificateGenerator(config.getDeliveryCertificate().certificate(),
config.getDeliveryCertificate().ecPrivateKey(), config.getDeliveryCertificate().expiresDays()),
config.getDeliveryCertificate().ecPrivateKey(), config.getDeliveryCertificate().expiresDays(), config.getDeliveryCertificate().embedSigner()),
zkAuthOperations, callingGenericZkSecretParams, clock),
new ChallengeController(accountsManager, rateLimitChallengeManager, challengeConstraintChecker),
new DeviceController(accountsManager, clientPublicKeysManager, rateLimiters, persistentTimer, config.getMaxDevices()),
@@ -1085,7 +1103,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
ReceiptCredentialPresentation::new),
new KeysController(rateLimiters, keysManager, accountsManager, zkSecretParams, Clock.systemUTC()),
new KeyTransparencyController(keyTransparencyServiceClient),
new MessageController(rateLimiters, messageByteLimitCardinalityEstimator, messageSender, receiptSender,
new MessageController(rateLimiters, messageByteLimitCardinalityEstimator, messageSender,
accountsManager, messagesManager, phoneNumberIdentifiers, pushNotificationManager, pushNotificationScheduler,
reportMessageManager, messageDeliveryScheduler, clientReleaseManager,
zkSecretParams, spamChecker, messageMetrics, messageDeliveryLoopMonitor,
@@ -1097,7 +1115,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new ProvisioningController(rateLimiters, provisioningManager),
new RegistrationController(accountsManager, phoneVerificationTokenManager, registrationLockVerificationManager,
rateLimiters),
new RemoteConfigControllerV1(remoteConfigsManager, config.getRemoteConfigConfiguration().globalConfig(), clock),
new RemoteConfigController(remoteConfigsManager, config.getRemoteConfigConfiguration().globalConfig(), clock),
new SecureStorageController(storageCredentialsGenerator),
new SecureValueRecovery2Controller(svr2CredentialsGenerator, accountsManager),
@@ -1106,7 +1123,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getCdnConfiguration().bucket()),
new VerificationController(registrationServiceClient, new VerificationSessionManager(verificationSessions),
pushNotificationManager, registrationCaptchaManager, registrationRecoveryPasswordsManager,
phoneNumberIdentifiers, rateLimiters, accountsManager, registrationFraudChecker,
phoneNumberIdentifiers, rateLimiters, accountsManager, carrierDataProvider, registrationFraudChecker,
dynamicConfigurationManager, clock)
);
if (config.getSubscription() != null && config.getOneTimeDonations() != null) {
@@ -1188,6 +1205,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new ObsoletePhoneNumberFormatExceptionMapper(),
new RegistrationServiceSenderExceptionMapper(),
new SubscriptionExceptionMapper(),
new BackupExceptionMapper(),
new JsonMappingExceptionMapper()
).forEach(exceptionMapper -> {
environment.jersey().register(exceptionMapper);
@@ -7,39 +7,48 @@ package org.whispersystems.textsecuregcm.auth;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import java.security.InvalidKeyException;
import java.util.concurrent.TimeUnit;
import org.signal.libsignal.protocol.ecc.ECPrivateKey;
import org.whispersystems.textsecuregcm.entities.MessageProtos.SenderCertificate;
import org.whispersystems.textsecuregcm.entities.MessageProtos.ServerCertificate;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
public class CertificateGenerator {
private final ECPrivateKey privateKey;
private final int expiresDays;
private final ECPrivateKey privateKey;
private final int expiresDays;
private final boolean embedSigner;
private final ServerCertificate serverCertificate;
private final int serverCertificateId;
public CertificateGenerator(byte[] serverCertificate, ECPrivateKey privateKey, int expiresDays)
throws InvalidProtocolBufferException
{
this.privateKey = privateKey;
this.expiresDays = expiresDays;
public CertificateGenerator(byte[] serverCertificate, ECPrivateKey privateKey, int expiresDays, boolean embedSigner)
throws InvalidProtocolBufferException {
this.privateKey = privateKey;
this.expiresDays = expiresDays;
this.embedSigner = embedSigner;
this.serverCertificate = ServerCertificate.parseFrom(serverCertificate);
this.serverCertificateId = ServerCertificate.Certificate
.parseFrom(this.serverCertificate.getCertificate())
.getId();
}
public byte[] createFor(final Account account, final byte deviceId, boolean includeE164) throws InvalidKeyException {
public byte[] createFor(final Account account, final byte deviceId, boolean includeE164) {
SenderCertificate.Certificate.Builder builder = SenderCertificate.Certificate.newBuilder()
.setSenderDevice(Math.toIntExact(deviceId))
.setExpires(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(expiresDays))
.setIdentityKey(ByteString.copyFrom(account.getIdentityKey(IdentityType.ACI).serialize()))
.setSigner(serverCertificate)
.setSenderUuid(account.getUuid().toString());
.setSenderUuid(UUIDUtil.toByteString(account.getUuid()));
if (includeE164) {
builder.setSender(account.getNumber());
builder.setSenderE164(account.getNumber());
}
if (embedSigner) {
builder.setSignerCertificate(serverCertificate);
} else {
builder.setSignerId(serverCertificateId);
}
byte[] certificate = builder.build().toByteArray();
@@ -47,10 +56,10 @@ public class CertificateGenerator {
signature = privateKey.calculateSignature(certificate);
return SenderCertificate.newBuilder()
.setCertificate(ByteString.copyFrom(certificate))
.setSignature(ByteString.copyFrom(signature))
.build()
.toByteArray();
.setCertificate(ByteString.copyFrom(certificate))
.setSignature(ByteString.copyFrom(signature))
.build()
.toByteArray();
}
}
@@ -192,17 +192,9 @@ public class ExternalServiceCredentialsGenerator {
: Optional.empty();
}
/**
* Given an instance of {@link ExternalServiceCredentials} object and the max allowed age for those credentials,
* checks if credentials are valid and not expired.
* @param credentials an instance of {@link ExternalServiceCredentials}
* @param maxAgeSeconds age in seconds
* @return An optional with a timestamp (seconds) of when the credentials were generated,
* or an empty optional if the password doesn't match the username for any reason (including malformed data)
*/
public Optional<Long> validateAndGetTimestamp(final ExternalServiceCredentials credentials, final long maxAgeSeconds) {
return validateAndGetTimestamp(credentials)
.filter(ts -> currentTimeSeconds() - ts <= maxAgeSeconds);
@VisibleForTesting
boolean isCredentialExpired(final long credentialTimestamp, final long maxAgeSeconds) {
return currentTimeSeconds() - credentialTimestamp > maxAgeSeconds;
}
private boolean shouldDeriveUsername() {
@@ -15,12 +15,27 @@ public class ExternalServiceCredentialsSelector {
private ExternalServiceCredentialsSelector() {}
public record CredentialInfo(String token, boolean valid, ExternalServiceCredentials credentials, long timestamp) {
public enum CredentialStatus {
// The token passes verification, is not expired, and is the most recent token available
VALID,
// The token was malformed or the signature was invalid
FAILED_VERIFICATION,
// The credential was correctly signed, but exceeded the maximum credential age
EXPIRED,
// There was a more recent credential available with the same username
REPLACED
}
public record CredentialInfo(String token, ExternalServiceCredentials credentials, long timestamp, CredentialStatus status) {
/**
* @return a copy of this record with valid=false
* @return a copy of this record that indicates it has been replaced with a more up-to-date token
*/
private CredentialInfo invalidate() {
return new CredentialInfo(token, false, credentials, timestamp);
private CredentialInfo replaced() {
return new CredentialInfo(token, credentials, timestamp, CredentialStatus.REPLACED);
}
public boolean valid() {
return status == CredentialStatus.VALID;
}
}
@@ -47,13 +62,18 @@ public class ExternalServiceCredentialsSelector {
// (note that password part may also contain ':' characters)
final String[] parts = token.split(":", 2);
if (parts.length != 2) {
results.add(new CredentialInfo(token, false, null, 0L));
results.add(new CredentialInfo(token, null, 0L, CredentialStatus.FAILED_VERIFICATION));
continue;
}
final ExternalServiceCredentials credentials = new ExternalServiceCredentials(parts[0], parts[1]);
final Optional<Long> maybeTimestamp = credentialsGenerator.validateAndGetTimestamp(credentials, maxAgeSeconds);
final Optional<Long> maybeTimestamp = credentialsGenerator.validateAndGetTimestamp(credentials);
if (maybeTimestamp.isEmpty()) {
results.add(new CredentialInfo(token, false, null, 0L));
results.add(new CredentialInfo(token, credentials, 0L, CredentialStatus.FAILED_VERIFICATION));
continue;
}
final long credentialTs = maybeTimestamp.get();
if (credentialsGenerator.isCredentialExpired(credentialTs, maxAgeSeconds)) {
results.add(new CredentialInfo(token, credentials, credentialTs, CredentialStatus.EXPIRED));
continue;
}
@@ -62,17 +82,17 @@ public class ExternalServiceCredentialsSelector {
final long timestamp = maybeTimestamp.get();
final CredentialInfo best = bestForUsername.get(credentials.username());
if (best == null) {
bestForUsername.put(credentials.username(), new CredentialInfo(token, true, credentials, timestamp));
bestForUsername.put(credentials.username(), new CredentialInfo(token, credentials, timestamp, CredentialStatus.VALID));
continue;
}
if (best.timestamp() < timestamp) {
// we found a better credential for the username
bestForUsername.put(credentials.username(), new CredentialInfo(token, true, credentials, timestamp));
bestForUsername.put(credentials.username(), new CredentialInfo(token, credentials, timestamp, CredentialStatus.VALID));
// mark the previous best as an invalid credential, since we have a better credential now
results.add(best.invalidate());
results.add(best.replaced());
} else {
// the credential we already had was more recent, this one can be marked invalid
results.add(new CredentialInfo(token, false, null, 0L));
results.add(new CredentialInfo(token, null, 0L, CredentialStatus.REPLACED));
}
}
@@ -153,7 +153,7 @@ public class RegistrationLockVerificationManager {
// This allows users to re-register via registration recovery password
// instead of always being forced to fall back to SMS verification.
if (!phoneVerificationType.equals(PhoneVerificationRequest.VerificationType.RECOVERY_PASSWORD) || clientRegistrationLock != null) {
registrationRecoveryPasswordsManager.remove(updatedAccount.getIdentifier(IdentityType.PNI));
registrationRecoveryPasswordsManager.remove(updatedAccount.getIdentifier(IdentityType.PNI)).join();
}
final List<Byte> deviceIds = updatedAccount.getDevices().stream().map(Device::getId).toList();
@@ -6,8 +6,8 @@
package org.whispersystems.textsecuregcm.auth.grpc;
import io.grpc.Context;
import io.grpc.Status;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.grpc.GrpcExceptions;
import org.whispersystems.textsecuregcm.storage.Device;
/**
@@ -18,13 +18,11 @@ public class AuthenticationUtil {
static final Context.Key<AuthenticatedDevice> CONTEXT_AUTHENTICATED_DEVICE = Context.key("authenticated-device");
/**
* Returns the account/device authenticated in the current gRPC context or throws an "unauthenticated" exception if
* no authenticated account/device is available.
* Returns the account/device authenticated in the current gRPC context. Should only be called from a service run with
* the {@link RequireAuthenticationInterceptor}.
*
* @return the account/device identifier authenticated in the current gRPC context
*
* @throws io.grpc.StatusRuntimeException with a status of {@code UNAUTHENTICATED} if no authenticated account/device
* could be retrieved from the current gRPC context
* @throws IllegalStateException if no authenticated account/device could be retrieved from the current gRPC context
*/
public static AuthenticatedDevice requireAuthenticatedDevice() {
@Nullable final AuthenticatedDevice authenticatedDevice = CONTEXT_AUTHENTICATED_DEVICE.get();
@@ -33,27 +31,25 @@ public class AuthenticationUtil {
return authenticatedDevice;
}
throw Status.UNAUTHENTICATED.asRuntimeException();
throw new IllegalStateException(
"Configuration issue: service expects an authenticated device, but none was found. Request should have failed from an interceptor");
}
/**
* Returns the account/device authenticated in the current gRPC context or throws an "unauthenticated" exception if
* no authenticated account/device is available or "permission denied" if the authenticated device is not the primary
* device for the account.
* Returns the account/device authenticated in the current gRPC context or "invalid argument" if the authenticated
* device is not the primary device for the account.
*
* @return the account/device identifier authenticated in the current gRPC context
*
* @throws io.grpc.StatusRuntimeException with a status of {@code UNAUTHENTICATED} if no authenticated account/device
* could be retrieved from the current gRPC context or a status of {@code PERMISSION_DENIED} if the authenticated
* device is not the primary device for the authenticated account
* @throws io.grpc.StatusRuntimeException with a status of {@code INVALID_ARGUMENT} if the authenticated device is not
* the primary device for the authenticated account
* @throws IllegalStateException if no authenticated account/device could be retrieved from the current gRPC
* context
*/
public static AuthenticatedDevice requireAuthenticatedPrimaryDevice() {
final AuthenticatedDevice authenticatedDevice = requireAuthenticatedDevice();
if (authenticatedDevice.deviceId() != Device.PRIMARY_ID) {
throw Status.PERMISSION_DENIED.asRuntimeException();
throw GrpcExceptions.badAuthentication("RPC requires a primary device");
}
return authenticatedDevice;
}
}
@@ -9,6 +9,8 @@ import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.Status;
import org.whispersystems.textsecuregcm.grpc.GrpcExceptions;
import org.whispersystems.textsecuregcm.grpc.ServerInterceptorUtil;
/**
* A "prohibit authentication" interceptor ensures that requests to endpoints that should be invoked anonymously do not
@@ -22,8 +24,8 @@ public class ProhibitAuthenticationInterceptor implements ServerInterceptor {
final Metadata headers, final ServerCallHandler<ReqT, RespT> next) {
final String authHeaderString = headers.get(Metadata.Key.of(RequireAuthenticationInterceptor.AUTHORIZATION_HEADER, Metadata.ASCII_STRING_MARSHALLER));
if (authHeaderString != null) {
call.close(Status.UNAUTHENTICATED.withDescription("authorization header forbidden"), new Metadata());
return new ServerCall.Listener<>() {};
return ServerInterceptorUtil.closeWithStatusException(call,
GrpcExceptions.badAuthentication("The service forbids requests with an authentication header"));
}
return next.startCall(call, headers);
}
@@ -14,6 +14,7 @@ import io.grpc.ServerInterceptor;
import io.grpc.Status;
import java.util.Optional;
import org.whispersystems.textsecuregcm.auth.AccountAuthenticator;
import org.whispersystems.textsecuregcm.grpc.GrpcExceptions;
import org.whispersystems.textsecuregcm.grpc.ServerInterceptorUtil;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
@@ -40,21 +41,21 @@ public class RequireAuthenticationInterceptor implements ServerInterceptor {
Metadata.Key.of(AUTHORIZATION_HEADER, Metadata.ASCII_STRING_MARSHALLER));
if (authHeaderString == null) {
return ServerInterceptorUtil.closeWithStatus(call,
Status.UNAUTHENTICATED.withDescription("missing authorization header"));
return ServerInterceptorUtil.closeWithStatusException(call,
GrpcExceptions.invalidCredentials("missing authorization header"));
}
final Optional<BasicCredentials> basicCredentials = HeaderUtils.basicCredentialsFromAuthHeader(authHeaderString);
if (basicCredentials.isEmpty()) {
return ServerInterceptorUtil.closeWithStatus(call,
Status.UNAUTHENTICATED.withDescription("malformed authorization header"));
return ServerInterceptorUtil.closeWithStatusException(call,
GrpcExceptions.invalidCredentials("malformed authorization header"));
}
final Optional<org.whispersystems.textsecuregcm.auth.AuthenticatedDevice> authenticated =
authenticator.authenticate(basicCredentials.get());
if (authenticated.isEmpty()) {
return ServerInterceptorUtil.closeWithStatus(call,
Status.UNAUTHENTICATED.withDescription("invalid credentials"));
return ServerInterceptorUtil.closeWithStatusException(call,
GrpcExceptions.invalidCredentials("invalid credentials"));
}
final AuthenticatedDevice authenticatedDevice = new AuthenticatedDevice(
@@ -5,7 +5,8 @@
package org.whispersystems.textsecuregcm.backup;
import io.grpc.Status;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.security.MessageDigest;
import java.time.Clock;
import java.time.Duration;
@@ -40,7 +41,6 @@ import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
import org.whispersystems.textsecuregcm.util.Util;
/**
* Issues ZK backup auth credentials for authenticated accounts
@@ -57,7 +57,6 @@ public class BackupAuthManager {
private static final Logger logger = LoggerFactory.getLogger(BackupAuthManager.class);
final static Duration MAX_REDEMPTION_DURATION = Duration.ofDays(7);
final static String BACKUP_MEDIA_EXPERIMENT_NAME = "backupMedia";
private final ExperimentEnrollmentManager experimentEnrollmentManager;
@@ -94,22 +93,20 @@ public class BackupAuthManager {
* message backups
* @param mediaBackupCredentialRequest A request containing the blinded backup-id the client will use to upload
* media backups
* @return A future that completes when the credentialRequest has been stored
* @throws RateLimitExceededException If too many backup-ids have been committed
*/
public CompletableFuture<Void> commitBackupId(
public void commitBackupId(
final Account account,
final Device device,
final Optional<BackupAuthCredentialRequest> messagesBackupCredentialRequest,
final Optional<BackupAuthCredentialRequest> mediaBackupCredentialRequest) {
final Optional<BackupAuthCredentialRequest> mediaBackupCredentialRequest)
throws RateLimitExceededException, BackupPermissionException, BackupInvalidArgumentException {
if (!device.isPrimary()) {
throw Status.PERMISSION_DENIED.withDescription("Only primary device can set backup-id").asRuntimeException();
throw new BackupPermissionException("Only primary device can set backup-id");
}
if (messagesBackupCredentialRequest.isEmpty() && mediaBackupCredentialRequest.isEmpty()) {
throw Status.INVALID_ARGUMENT
.withDescription("Must set at least one of message/media credential requests")
.asRuntimeException();
throw new BackupInvalidArgumentException("Must set at least one of message/media credential requests");
}
final byte[] storedMessageCredentialRequest = account.getBackupCredentialRequest(BackupCredentialType.MESSAGES)
@@ -133,33 +130,24 @@ public class BackupAuthManager {
if (!requiresMessageRotation && !requiresMediaRotation) {
// No need to update or enforce rate limits, this is the credential that the user has already
// committed to.
return CompletableFuture.completedFuture(null);
return;
}
CompletableFuture<Void> rateLimitFuture = CompletableFuture.completedFuture(null);
if (requiresMessageRotation) {
rateLimitFuture = rateLimitFuture.thenCombine(
rateLimiters.forDescriptor(RateLimiters.For.SET_BACKUP_ID).validateAsync(account.getUuid()),
(_, _) -> null);
rateLimiters.forDescriptor(RateLimiters.For.SET_BACKUP_ID).validate(account.getUuid());
}
if (requiresMediaRotation && hasActiveVoucher(account)) {
rateLimitFuture = rateLimitFuture.thenCombine(
rateLimiters.forDescriptor(RateLimiters.For.SET_PAID_MEDIA_BACKUP_ID).validateAsync(account.getUuid()),
(_, _) -> null);
rateLimiters.forDescriptor(RateLimiters.For.SET_PAID_MEDIA_BACKUP_ID).validate(account.getUuid());
}
return rateLimitFuture.thenCompose(ignored -> this.accountsManager
.updateAsync(account, a ->
a.setBackupCredentialRequests(targetMessageCredentialRequest, targetMediaCredentialRequest))
.thenRun(Util.NOOP))
.toCompletableFuture();
this.accountsManager.update(account, a ->
a.setBackupCredentialRequests(targetMessageCredentialRequest, targetMediaCredentialRequest));
}
public record BackupIdRotationLimit(boolean hasPermitsRemaining, Duration nextPermitAvailable) {}
public CompletionStage<BackupIdRotationLimit> checkBackupIdRotationLimit(final Account account) {
public BackupIdRotationLimit checkBackupIdRotationLimit(final Account account) {
final RateLimiter messagesLimiter = rateLimiters.forDescriptor(RateLimiters.For.SET_BACKUP_ID);
final RateLimiter mediaLimiter = rateLimiters.forDescriptor(RateLimiters.For.SET_PAID_MEDIA_BACKUP_ID);
@@ -180,7 +168,7 @@ public class BackupAuthManager {
isPaid ? mediaLimiter.config().permitRegenerationDuration() : Duration.ZERO));
return new BackupIdRotationLimit(false, timeToNextPermit);
}
});
}).toCompletableFuture().join();
}
public record Credential(BackupAuthCredentialResponse credential, Instant redemptionTime) {}
@@ -200,31 +188,32 @@ public class BackupAuthManager {
* @param redemptionRange The time range to return credentials for
* @return Credentials and the day on which they may be redeemed
*/
public CompletableFuture<List<Credential>> getBackupAuthCredentials(
public List<Credential> getBackupAuthCredentials(
final Account account,
final BackupCredentialType credentialType,
final RedemptionRange redemptionRange) {
final RedemptionRange redemptionRange) throws BackupNotFoundException {
// If the account has an expired payment, clear it before continuing
if (hasExpiredVoucher(account)) {
return accountsManager.updateAsync(account, a -> {
final Account updated = accountsManager.update(account, a -> {
// Re-check in case we raced with an update
if (hasExpiredVoucher(a)) {
a.setBackupVoucher(null);
}
}).thenCompose(updated -> getBackupAuthCredentials(updated, credentialType, redemptionRange));
});
return getBackupAuthCredentials(updated, credentialType, redemptionRange);
}
// fetch the blinded backup-id the account should have previously committed to
final byte[] committedBytes = account.getBackupCredentialRequest(credentialType)
.orElseThrow(() -> Status.NOT_FOUND.withDescription("No blinded backup-id has been added to the account").asRuntimeException());
.orElseThrow(() -> new BackupNotFoundException("No blinded backup-id has been added to the account"));
try {
final BackupLevel defaultBackupLevel = configuredBackupLevel(account);
// create a credential for every day in the requested period
final BackupAuthCredentialRequest credentialReq = new BackupAuthCredentialRequest(committedBytes);
return CompletableFuture.completedFuture(StreamSupport.stream(redemptionRange.spliterator(), false)
return StreamSupport.stream(redemptionRange.spliterator(), false)
.map(redemptionTime -> {
// Check if the account has a voucher that's good for a certain receiptLevel at redemption time, otherwise
// use the default receipt level
@@ -233,12 +222,9 @@ public class BackupAuthManager {
credentialReq.issueCredential(redemptionTime, backupLevel, credentialType, serverSecretParams),
redemptionTime);
})
.toList());
.toList();
} catch (InvalidInputException e) {
throw Status.INTERNAL
.withDescription("Could not deserialize stored request credential")
.withCause(e)
.asRuntimeException();
throw new UncheckedIOException(new IOException("Could not deserialize stored request credential", e));
}
}
@@ -247,48 +233,39 @@ public class BackupAuthManager {
*
* @param account The account to enable backups on
* @param receiptCredentialPresentation A ZK receipt presentation proving payment
* @return A future that completes successfully when the account has been updated
*/
public CompletableFuture<Void> redeemReceipt(
public void redeemReceipt(
final Account account,
final ReceiptCredentialPresentation receiptCredentialPresentation) {
final ReceiptCredentialPresentation receiptCredentialPresentation)
throws BackupBadReceiptException, BackupInvalidArgumentException, BackupMissingIdCommitmentException {
try {
serverZkReceiptOperations.verifyReceiptCredentialPresentation(receiptCredentialPresentation);
} catch (VerificationFailedException e) {
throw Status.INVALID_ARGUMENT
.withDescription("receipt credential presentation verification failed")
.asRuntimeException();
throw new BackupBadReceiptException("receipt credential presentation verification failed");
}
final ReceiptSerial receiptSerial = receiptCredentialPresentation.getReceiptSerial();
final Instant receiptExpiration = Instant.ofEpochSecond(receiptCredentialPresentation.getReceiptExpirationTime());
if (clock.instant().isAfter(receiptExpiration)) {
throw Status.INVALID_ARGUMENT.withDescription("receipt is already expired").asRuntimeException();
throw new BackupBadReceiptException("receipt is already expired");
}
final long receiptLevel = receiptCredentialPresentation.getReceiptLevel();
if (BackupLevelUtil.fromReceiptLevel(receiptLevel) != BackupLevel.PAID) {
throw Status.INVALID_ARGUMENT
.withDescription("server does not recognize the requested receipt level")
.asRuntimeException();
throw new BackupInvalidArgumentException("server does not recognize the requested receipt level");
}
if (account.getBackupCredentialRequest(BackupCredentialType.MEDIA).isEmpty()) {
throw Status.ABORTED
.withDescription("account must have a backup-id commitment")
.asRuntimeException();
throw new BackupMissingIdCommitmentException();
}
return redeemedReceiptsManager
boolean receiptAllowed = redeemedReceiptsManager
.put(receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, account.getUuid())
.thenCompose(receiptAllowed -> {
if (!receiptAllowed) {
throw Status.INVALID_ARGUMENT
.withDescription("receipt serial is already redeemed")
.asRuntimeException();
}
return extendBackupVoucher(account, new Account.BackupVoucher(receiptLevel, receiptExpiration));
});
.join();
if (!receiptAllowed) {
throw new BackupBadReceiptException("receipt serial is already redeemed");
}
extendBackupVoucher(account, new Account.BackupVoucher(receiptLevel, receiptExpiration));
}
/**
@@ -296,11 +273,9 @@ public class BackupAuthManager {
*
* @param account The account to update
* @param backupVoucher The backup voucher to apply to this account
* @return A future that completes once the account has been updated to have at least the level and expiration
* in the provided voucher.
*/
public CompletableFuture<Void> extendBackupVoucher(final Account account, final Account.BackupVoucher backupVoucher) {
return accountsManager.updateAsync(account, a -> {
public void extendBackupVoucher(final Account account, final Account.BackupVoucher backupVoucher) {
accountsManager.update(account, a -> {
// Receipt credential expirations must be day aligned. Make sure any manually set backupVoucher is also day
// aligned
final Account.BackupVoucher newPayment = new Account.BackupVoucher(
@@ -308,7 +283,7 @@ public class BackupAuthManager {
backupVoucher.expiration().truncatedTo(ChronoUnit.DAYS));
final Account.BackupVoucher existingPayment = a.getBackupVoucher();
a.setBackupVoucher(merge(existingPayment, newPayment));
}).thenRun(Util.NOOP);
});
}
private static Account.BackupVoucher merge(@Nullable final Account.BackupVoucher prev,
@@ -0,0 +1,12 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.backup;
public class BackupBadReceiptException extends BackupException {
public BackupBadReceiptException(String message) {
super(message);
}
}
@@ -0,0 +1,16 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.backup;
public class BackupException extends Exception {
public BackupException() {
super();
}
public BackupException(String message) {
super(message);
}
}
@@ -0,0 +1,12 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.backup;
public class BackupFailedZkAuthenticationException extends BackupException {
public BackupFailedZkAuthenticationException(String message) {
super(message);
}
}
@@ -0,0 +1,11 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.backup;
public class BackupInvalidArgumentException extends BackupException {
public BackupInvalidArgumentException(final String message) {
super(message);
}
}
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.backup;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.util.DataSize;
import io.grpc.Status;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
@@ -42,12 +41,12 @@ import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicBackupConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.util.AsyncTimerUtil;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
@@ -127,11 +126,12 @@ public class BackupManager {
* @param presentation a ZK credential presentation that encodes the backupId
* @param signature the signature of the presentation
* @param publicKey the public key of a key-pair that the presentation must be signed with
* @throws BackupFailedZkAuthenticationException If the provided presentation or signature were invalid
*/
public CompletableFuture<Void> setPublicKey(
public void setPublicKey(
final BackupAuthCredentialPresentation presentation,
final byte[] signature,
final ECPublicKey publicKey) {
final ECPublicKey publicKey) throws BackupFailedZkAuthenticationException {
// Note: this is a special case where we can't validate the presentation signature against the stored public key
// because we are currently setting it. We check against the provided public key, but we must also verify that
@@ -139,16 +139,16 @@ public class BackupManager {
final Pair<BackupCredentialType, BackupLevel> credentialTypeAndBackupLevel =
verifyPresentation(presentation).verifySignature(signature, publicKey);
return backupsDb.setPublicKey(presentation.getBackupId(), credentialTypeAndBackupLevel.second(), publicKey)
.exceptionally(ExceptionUtils.exceptionallyHandler(PublicKeyConflictException.class, ex -> {
ExceptionUtils.unwrapSupply(
BackupPublicKeyConflictException.class,
() -> backupsDb.setPublicKey(presentation.getBackupId(), credentialTypeAndBackupLevel.second(), publicKey).join(),
_ -> {
Metrics.counter(ZK_AUTHN_COUNTER_NAME,
SUCCESS_TAG_NAME, String.valueOf(false),
FAILURE_REASON_TAG_NAME, "public_key_conflict")
.increment();
throw Status.UNAUTHENTICATED
.withDescription("public key does not match existing public key for the backup-id")
.asRuntimeException();
}));
return new BackupFailedZkAuthenticationException("The provided public key did not match the stored public key");
});
}
/**
@@ -158,69 +158,67 @@ public class BackupManager {
*
* @param backupUser an already ZK authenticated backup user
* @return the upload form
* @throws BackupPermissionException if the credential does not have the correct level
* @throws BackupWrongCredentialTypeException if the credential does not have the messages type
*/
public CompletableFuture<BackupUploadDescriptor> createMessageBackupUploadDescriptor(
final AuthenticatedBackupUser backupUser) {
public BackupUploadDescriptor createMessageBackupUploadDescriptor(
final AuthenticatedBackupUser backupUser) throws BackupPermissionException, BackupWrongCredentialTypeException {
checkBackupLevel(backupUser, BackupLevel.FREE);
checkBackupCredentialType(backupUser, BackupCredentialType.MESSAGES);
// this could race with concurrent updates, but the only effect would be last-writer-wins on the timestamp
return backupsDb
.addMessageBackup(backupUser)
.thenApply(_ ->
cdn3BackupCredentialGenerator.generateUpload(cdnMessageBackupName(backupUser)));
backupsDb.addMessageBackup(backupUser).join();
return cdn3BackupCredentialGenerator.generateUpload(cdnMessageBackupName(backupUser));
}
public CompletableFuture<BackupUploadDescriptor> createTemporaryAttachmentUploadDescriptor(
final AuthenticatedBackupUser backupUser) {
public BackupUploadDescriptor createTemporaryAttachmentUploadDescriptor(final AuthenticatedBackupUser backupUser)
throws RateLimitExceededException, BackupPermissionException, BackupWrongCredentialTypeException {
checkBackupLevel(backupUser, BackupLevel.PAID);
checkBackupCredentialType(backupUser, BackupCredentialType.MEDIA);
return rateLimiters.forDescriptor(RateLimiters.For.BACKUP_ATTACHMENT)
.validateAsync(rateLimitKey(backupUser)).thenApply(ignored -> {
final byte[] bytes = new byte[15];
secureRandom.nextBytes(bytes);
final String attachmentKey = Base64.getUrlEncoder().encodeToString(bytes);
final AttachmentGenerator.Descriptor descriptor = tusAttachmentGenerator.generateAttachment(attachmentKey);
return new BackupUploadDescriptor(3, attachmentKey, descriptor.headers(), descriptor.signedUploadLocation());
}).toCompletableFuture();
rateLimiters.forDescriptor(RateLimiters.For.BACKUP_ATTACHMENT).validate(rateLimitKey(backupUser));
final byte[] bytes = new byte[15];
secureRandom.nextBytes(bytes);
final String attachmentKey = Base64.getUrlEncoder().encodeToString(bytes);
final AttachmentGenerator.Descriptor descriptor = tusAttachmentGenerator.generateAttachment(attachmentKey);
return new BackupUploadDescriptor(3, attachmentKey, descriptor.headers(), descriptor.signedUploadLocation());
}
/**
* Update the last update timestamps for the backupId in the presentation
*
* @param backupUser an already ZK authenticated backup user
* @throws BackupPermissionException if the credential does not have the correct level
*/
public CompletableFuture<Void> ttlRefresh(final AuthenticatedBackupUser backupUser) {
public void ttlRefresh(final AuthenticatedBackupUser backupUser) throws BackupPermissionException {
checkBackupLevel(backupUser, BackupLevel.FREE);
// update message backup TTL
return backupsDb.ttlRefresh(backupUser).thenAccept(storedBackupAttributes -> {
if (backupUser.credentialType() == BackupCredentialType.MEDIA) {
final long maxTotalMediaSize =
dynamicConfigurationManager.getConfiguration().getBackupConfiguration().maxTotalMediaSize();
final StoredBackupAttributes storedBackupAttributes = backupsDb.ttlRefresh(backupUser).join();
if (backupUser.credentialType() == BackupCredentialType.MEDIA) {
final long maxTotalMediaSize =
dynamicConfigurationManager.getConfiguration().getBackupConfiguration().maxTotalMediaSize();
// Report that the backup is out of quota if it cannot store a max size media object
final boolean quotaExhausted = storedBackupAttributes.bytesUsed() >=
(maxTotalMediaSize - BackupManager.MAX_MEDIA_OBJECT_SIZE);
// Report that the backup is out of quota if it cannot store a max size media object
final boolean quotaExhausted = storedBackupAttributes.bytesUsed() >=
(maxTotalMediaSize - BackupManager.MAX_MEDIA_OBJECT_SIZE);
final Tags tags = Tags.of(
UserAgentTagUtil.getPlatformTag(backupUser.userAgent()),
Tag.of("type", backupUser.credentialType().name()),
Tag.of("tier", backupUser.backupLevel().name()),
Tag.of("quotaExhausted", String.valueOf(quotaExhausted)));
final Tags tags = Tags.of(
UserAgentTagUtil.getPlatformTag(backupUser.userAgent()),
Tag.of("type", backupUser.credentialType().name()),
Tag.of("tier", backupUser.backupLevel().name()),
Tag.of("quotaExhausted", String.valueOf(quotaExhausted)));
DistributionSummary.builder(NUM_OBJECTS_SUMMARY_NAME)
.tags(tags)
.publishPercentileHistogram()
.register(Metrics.globalRegistry)
.record(storedBackupAttributes.numObjects());
DistributionSummary.builder(BYTES_USED_SUMMARY_NAME)
.tags(tags)
.publishPercentileHistogram()
.register(Metrics.globalRegistry)
.record(storedBackupAttributes.bytesUsed());
}
});
DistributionSummary.builder(NUM_OBJECTS_SUMMARY_NAME)
.tags(tags)
.publishPercentileHistogram()
.register(Metrics.globalRegistry)
.record(storedBackupAttributes.numObjects());
DistributionSummary.builder(BYTES_USED_SUMMARY_NAME)
.tags(tags)
.publishPercentileHistogram()
.register(Metrics.globalRegistry)
.record(storedBackupAttributes.bytesUsed());
}
}
public record BackupInfo(int cdn, String backupSubdir, String mediaSubdir, String messageBackupKey,
@@ -231,16 +229,21 @@ public class BackupManager {
*
* @param backupUser an already ZK authenticated backup user
* @return Information about the existing backup
* @throws BackupPermissionException if the credential does not have the correct level
* @throws BackupNotFoundException if the provided backupuser does not exist
*/
public CompletableFuture<BackupInfo> backupInfo(final AuthenticatedBackupUser backupUser) {
public BackupInfo backupInfo(final AuthenticatedBackupUser backupUser)
throws BackupNotFoundException, BackupPermissionException {
checkBackupLevel(backupUser, BackupLevel.FREE);
return backupsDb.describeBackup(backupUser)
.thenApply(backupDescription -> new BackupInfo(
backupDescription.cdn(),
backupUser.backupDir(),
backupUser.mediaDir(),
MESSAGE_BACKUP_NAME,
backupDescription.mediaUsedSpace()));
final BackupsDb.BackupDescription backupDescription = ExceptionUtils.unwrapSupply(
BackupNotFoundException.class,
() -> backupsDb.describeBackup(backupUser).join());
return new BackupInfo(
backupDescription.cdn(),
backupUser.backupDir(),
backupUser.mediaDir(),
MESSAGE_BACKUP_NAME,
backupDescription.mediaUsedSpace());
}
/**
@@ -255,46 +258,42 @@ public class BackupManager {
* @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 Flux<CopyResult> copyToBackup(final AuthenticatedBackupUser backupUser, List<CopyParameters> toCopy) {
checkBackupLevel(backupUser, BackupLevel.PAID);
checkBackupCredentialType(backupUser, BackupCredentialType.MEDIA);
public Flux<CopyResult> copyToBackup(final CopyQuota copyQuota) {
final AuthenticatedBackupUser backupUser = copyQuota.backupUser();
final DynamicBackupConfiguration backupConfiguration =
dynamicConfigurationManager.getConfiguration().getBackupConfiguration();
return Mono.fromFuture(() -> allowedCopies(backupUser, toCopy))
.flatMapMany(quotaResult -> Flux.concat(
return Flux.concat(
// Perform copies for requests that fit in our quota, first updating the usage. If the copy fails, our
// estimated quota usage may not be exact since we update usage first. We make a best-effort attempt
// to undo the usage update if we know that the copied failed for sure.
Flux.fromIterable(quotaResult.requestsToCopy())
// Perform copies for requests that fit in our quota, first updating the usage. If the copy fails, our
// estimated quota usage may not be exact since we update usage first. We make a best-effort attempt
// to undo the usage update if we know that the copied failed for sure.
Flux.fromIterable(copyQuota.requestsToCopy())
// Update the usage in reasonable chunk sizes to bound how out of sync our claimed and actual usage gets
.buffer(backupConfiguration.usageCheckpointCount())
.concatMap(copyParameters -> {
final long quotaToConsume = copyParameters.stream()
.mapToLong(CopyParameters::destinationObjectSize)
.sum();
return Mono
.fromFuture(backupsDb.trackMedia(backupUser, copyParameters.size(), quotaToConsume))
.thenMany(Flux.fromIterable(copyParameters));
})
// Update the usage in reasonable chunk sizes to bound how out of sync our claimed and actual usage gets
.buffer(backupConfiguration.usageCheckpointCount())
.concatMap(copyParameters -> {
final long quotaToConsume = copyParameters.stream()
.mapToLong(CopyParameters::destinationObjectSize)
.sum();
return Mono
.fromFuture(backupsDb.trackMedia(backupUser, copyParameters.size(), quotaToConsume))
.thenMany(Flux.fromIterable(copyParameters));
})
// Actually perform the copies now that we've updated the quota
.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);
}),
backupConfiguration.copyConcurrency(), 1),
// Actually perform the copies now that we've updated the quota
.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);
}),
backupConfiguration.copyConcurrency(), 1),
// 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))
));
// There wasn't enough quota remaining to perform these copies
Flux.fromIterable(copyQuota.requestsToReject())
.map(arg -> new CopyResult(CopyResult.Outcome.OUT_OF_QUOTA, arg.destinationMediaId(), null)));
}
private Mono<CopyResult> copyToBackup(final AuthenticatedBackupUser backupUser, final CopyParameters copyParameters) {
@@ -317,64 +316,67 @@ public class BackupManager {
Mono.just(CopyResult.fromCopyError(throwable, copyParameters.destinationMediaId()).orElseThrow()));
}
private record QuotaResult(List<CopyParameters> requestsToCopy, List<CopyParameters> requestsToReject) {}
public record CopyQuota(AuthenticatedBackupUser backupUser, List<CopyParameters> requestsToCopy, List<CopyParameters> requestsToReject) {
private static CopyQuota create(AuthenticatedBackupUser backupUser, final List<CopyParameters> toCopy, long remainingQuota) {
// Figure out how many of the requested objects fit in the remaining quota
final int index = indexWhereTotalExceeds(toCopy, CopyParameters::destinationObjectSize, remainingQuota);
return new CopyQuota(backupUser, toCopy.subList(0, index), toCopy.subList(index, toCopy.size()));
}
}
/**
* Determine which copy requests can be performed with the user's remaining quota. This does not update the quota.
*
* @param backupUser The user quota to check against
* @param toCopy The proposed copy requests
* @return list of QuotaResult indicating which requests fit into the remaining quota and which requests should be
* @return QuotaResult indicating which requests fit into the remaining quota and which requests should be
* rejected with {@link CopyResult.Outcome#OUT_OF_QUOTA}
* @throws BackupInvalidArgumentException if toCopy contains an invalid copy request
* @throws BackupPermissionException if the credential does not have the correct level
* @throws BackupWrongCredentialTypeException if the credential does not have the media type
*/
private CompletableFuture<QuotaResult> allowedCopies(
public CopyQuota getCopyQuota(
final AuthenticatedBackupUser backupUser,
final List<CopyParameters> toCopy) {
final long totalBytesAdded = toCopy.stream()
.mapToLong(copyParameters -> {
if (copyParameters.sourceLength() > MAX_MEDIA_OBJECT_SIZE || copyParameters.sourceLength() < 0) {
throw Status.INVALID_ARGUMENT
.withDescription("Invalid sourceObject size")
.asRuntimeException();
}
return copyParameters.destinationObjectSize();
})
.sum();
final List<CopyParameters> toCopy)
throws BackupWrongCredentialTypeException, BackupPermissionException, BackupInvalidArgumentException {
checkBackupLevel(backupUser, BackupLevel.PAID);
checkBackupCredentialType(backupUser, BackupCredentialType.MEDIA);
for (CopyParameters copyParameters : toCopy) {
if (copyParameters.sourceLength() > MAX_MEDIA_OBJECT_SIZE || copyParameters.sourceLength() < 0) {
throw new BackupInvalidArgumentException("Invalid sourceObject size");
}
}
final long totalBytesAdded = toCopy.stream().mapToLong(CopyParameters::destinationObjectSize).sum();
final DynamicBackupConfiguration backupConfiguration =
dynamicConfigurationManager.getConfiguration().getBackupConfiguration();
final Duration maxQuotaStaleness = backupConfiguration.maxQuotaStaleness();
final long maxTotalMediaSize = backupConfiguration.maxTotalMediaSize();
return backupsDb.getMediaUsage(backupUser)
.thenComposeAsync(info -> {
long remainingQuota = maxTotalMediaSize - info.usageInfo().bytesUsed();
final boolean canStore = remainingQuota >= totalBytesAdded;
if (canStore || info.lastRecalculationTime().isAfter(clock.instant().minus(maxQuotaStaleness))) {
return CompletableFuture.completedFuture(remainingQuota);
}
final BackupsDb.TimestampedUsageInfo info = backupsDb.getMediaUsage(backupUser).join();
long estimatedRemainingQuota = maxTotalMediaSize - info.usageInfo().bytesUsed();
final boolean canStore = estimatedRemainingQuota >= totalBytesAdded;
if (canStore || info.lastRecalculationTime().isAfter(clock.instant().minus(maxQuotaStaleness))) {
return CopyQuota.create(backupUser, toCopy, estimatedRemainingQuota);
}
// The user is out of quota, and we have not recently recalculated the user's usage. Double check by doing a
// hard recalculation before actually forbidding the user from storing additional media.
return this.remoteStorageManager.calculateBytesUsed(cdnMediaDirectory(backupUser))
.thenCompose(usage -> backupsDb
.setMediaUsage(backupUser, usage)
.thenApply(ignored -> usage))
.whenComplete((newUsage, throwable) -> {
boolean usageChanged = throwable == null && !newUsage.equals(info.usageInfo());
Metrics.counter(USAGE_RECALCULATION_COUNTER_NAME, Tags.of(
UserAgentTagUtil.getPlatformTag(backupUser.userAgent()),
Tag.of("usageChanged", String.valueOf(usageChanged))))
.increment();
})
.thenApply(newUsage -> maxTotalMediaSize - newUsage.bytesUsed());
})
.thenApply(remainingQuota -> {
// Figure out how many of the requested objects fit in the remaining quota
final int index = indexWhereTotalExceeds(toCopy, CopyParameters::destinationObjectSize,
remainingQuota);
return new QuotaResult(toCopy.subList(0, index), toCopy.subList(index, toCopy.size()));
});
// The user is out of quota, and we have not recently recalculated the user's usage. Double check by doing a
// hard recalculation before actually forbidding the user from storing additional media.
boolean usageChanged = false;
try {
final UsageInfo usage =
this.remoteStorageManager.calculateBytesUsed(cdnMediaDirectory(backupUser)).toCompletableFuture().join();
backupsDb.setMediaUsage(backupUser, usage).join();
usageChanged = !usage.equals(info.usageInfo());
final long remainingQuota = maxTotalMediaSize - usage.bytesUsed();
return CopyQuota.create(backupUser, toCopy, remainingQuota);
} finally {
Metrics.counter(USAGE_RECALCULATION_COUNTER_NAME, Tags.of(
UserAgentTagUtil.getPlatformTag(backupUser.userAgent()),
Tag.of("usageChanged", String.valueOf(usageChanged))))
.increment();
}
}
public record RecalculationResult(UsageInfo oldUsage, UsageInfo newUsage) {}
@@ -415,11 +417,14 @@ public class BackupManager {
* @param backupUser an already ZK authenticated backup user
* @param cdnNumber the cdn number to get backup credentials for
* @return A map of headers to include with CDN requests
* @throws BackupPermissionException if the credential does not have the correct level
* @throws BackupInvalidArgumentException if the provided cdnNumber is invalid
*/
public Map<String, String> generateReadAuth(final AuthenticatedBackupUser backupUser, final int cdnNumber) {
public Map<String, String> generateReadAuth(final AuthenticatedBackupUser backupUser, final int cdnNumber)
throws BackupInvalidArgumentException, BackupPermissionException {
checkBackupLevel(backupUser, BackupLevel.FREE);
if (cdnNumber != 3) {
throw Status.INVALID_ARGUMENT.withDescription("unknown cdn").asRuntimeException();
throw new BackupInvalidArgumentException("unknown cdn");
}
return cdn3BackupCredentialGenerator.readHeaders(backupUser.backupDir());
}
@@ -429,8 +434,11 @@ public class BackupManager {
*
* @param backupUser an already ZK authenticated backup user
* @return the credential that may be used with SVRB
* @throws BackupPermissionException if the credential does not have the correct level
* @throws BackupWrongCredentialTypeException if the credential does not have the messages type
*/
public ExternalServiceCredentials generateSvrbAuth(final AuthenticatedBackupUser backupUser) {
public ExternalServiceCredentials generateSvrbAuth(final AuthenticatedBackupUser backupUser)
throws BackupPermissionException, BackupWrongCredentialTypeException {
checkBackupLevel(backupUser, BackupLevel.FREE);
// Clients may only use SVRB with their messages backup-id
checkBackupCredentialType(backupUser, BackupCredentialType.MESSAGES);
@@ -460,59 +468,61 @@ public class BackupManager {
* @param cursor A cursor returned by a previous call that can be used to resume listing
* @param limit The maximum number of list results to return
* @return A {@link ListMediaResult}
* @throws BackupPermissionException if the credential does not have the correct level
*/
public CompletionStage<ListMediaResult> list(
public ListMediaResult list(
final AuthenticatedBackupUser backupUser,
final Optional<String> cursor,
final int limit) {
final int limit) throws BackupPermissionException {
checkBackupLevel(backupUser, BackupLevel.FREE);
return remoteStorageManager.list(cdnMediaDirectory(backupUser), cursor, limit)
.thenApply(result ->
new ListMediaResult(
result
.objects()
.stream()
.map(entry -> new StorageDescriptorWithLength(
remoteStorageManager.cdnNumber(),
decodeMediaIdFromCdn(entry.key()),
entry.length()
))
.toList(),
result.cursor()
));
final RemoteStorageManager.ListResult result =
remoteStorageManager.list(cdnMediaDirectory(backupUser), cursor, limit).toCompletableFuture().join();
return new ListMediaResult(result
.objects()
.stream()
.map(entry -> new StorageDescriptorWithLength(
remoteStorageManager.cdnNumber(),
decodeMediaIdFromCdn(entry.key()),
entry.length()
))
.toList(),
result.cursor());
}
public CompletableFuture<Void> deleteEntireBackup(final AuthenticatedBackupUser backupUser) {
public void deleteEntireBackup(final AuthenticatedBackupUser backupUser) throws BackupPermissionException {
checkBackupLevel(backupUser, BackupLevel.FREE);
final int deletionConcurrency =
dynamicConfigurationManager.getConfiguration().getBackupConfiguration().deletionConcurrency();
// Clients only include SVRB data with their messages backup-id
final CompletableFuture<Void> svrbRemoval = switch(backupUser.credentialType()) {
case BackupCredentialType.MESSAGES -> secureValueRecoveryBClient.removeData(svrbIdentifier(backupUser));
case BackupCredentialType.MEDIA -> CompletableFuture.completedFuture(null);
};
return svrbRemoval.thenCompose(_ -> backupsDb
// Try to swap out the backupDir for the user
.scheduleBackupDeletion(backupUser)
if (backupUser.credentialType() == BackupCredentialType.MESSAGES) {
secureValueRecoveryBClient.removeData(svrbIdentifier(backupUser)).join();
}
try {
// Try to swap out the backupDir for the user
backupsDb.scheduleBackupDeletion(backupUser).join();
} catch (Exception e) {
final Throwable unwrapped = ExceptionUtils.unwrap(e);
if (unwrapped instanceof BackupsDb.PendingDeletionException) {
// If there was already a pending swap, try to delete the cdn objects directly
.exceptionallyCompose(ExceptionUtils.exceptionallyHandler(BackupsDb.PendingDeletionException.class, e ->
AsyncTimerUtil.record(SYNCHRONOUS_DELETE_TIMER, () ->
deletePrefix(backupUser.backupDir(), deletionConcurrency)))));
SYNCHRONOUS_DELETE_TIMER.record(() -> deletePrefix(backupUser.backupDir(), deletionConcurrency).join());
} else {
throw e;
}
}
}
public Flux<StorageDescriptor> deleteMedia(final AuthenticatedBackupUser backupUser,
final List<StorageDescriptor> storageDescriptors) {
final List<StorageDescriptor> storageDescriptors)
throws BackupPermissionException, BackupWrongCredentialTypeException {
checkBackupLevel(backupUser, BackupLevel.FREE);
checkBackupCredentialType(backupUser, BackupCredentialType.MEDIA);
// 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.error(new BackupInvalidArgumentException("unsupported media cdn provided"));
}
final DynamicBackupConfiguration backupConfiguration =
dynamicConfigurationManager.getConfiguration().getBackupConfiguration();
@@ -614,42 +624,40 @@ public class BackupManager {
* @param presentation A {@link BackupAuthCredentialPresentation}
* @param signature An XEd25519 signature of the presentation bytes
* @return On authentication success, the authenticated backup-id and backup-tier encoded in the presentation
* @throws BackupFailedZkAuthenticationException If the provided presentation or signature were invalid
*/
public CompletableFuture<AuthenticatedBackupUser> authenticateBackupUser(
public AuthenticatedBackupUser authenticateBackupUser(
final BackupAuthCredentialPresentation presentation,
final byte[] signature,
final String userAgentString) {
final String userAgentString) throws BackupFailedZkAuthenticationException {
final PresentationSignatureVerifier signatureVerifier = verifyPresentation(presentation);
return backupsDb
.retrieveAuthenticationData(presentation.getBackupId())
.thenApply(optionalAuthenticationData -> {
final UserAgent userAgent = parseUserAgent(userAgentString);
final BackupsDb.AuthenticationData authenticationData = optionalAuthenticationData
.orElseGet(() -> {
Metrics.counter(ZK_AUTHN_COUNTER_NAME, Tags.of(
Tag.of(SUCCESS_TAG_NAME, String.valueOf(false)),
Tag.of(FAILURE_REASON_TAG_NAME, "missing_public_key"),
UserAgentTagUtil.getPlatformTag(userAgent)))
.increment();
// There was no stored public key, use a bunk public key so that validation will fail
return new BackupsDb.AuthenticationData(INVALID_PUBLIC_KEY, null, null);
});
final Pair<BackupCredentialType, BackupLevel> credentialTypeAndBackupLevel =
signatureVerifier.verifySignature(signature, authenticationData.publicKey());
return new AuthenticatedBackupUser(
presentation.getBackupId(),
credentialTypeAndBackupLevel.first(),
credentialTypeAndBackupLevel.second(),
authenticationData.backupDir(),
authenticationData.mediaDir(),
userAgent);
})
.thenApply(result -> {
Metrics.counter(ZK_AUTHN_COUNTER_NAME, SUCCESS_TAG_NAME, String.valueOf(true)).increment();
return result;
final Optional<BackupsDb.AuthenticationData> optionalAuthenticationData =
backupsDb.retrieveAuthenticationData(presentation.getBackupId()).join();
final UserAgent userAgent = parseUserAgent(userAgentString);
final BackupsDb.AuthenticationData authenticationData = optionalAuthenticationData
.orElseGet(() -> {
Metrics.counter(ZK_AUTHN_COUNTER_NAME, Tags.of(
Tag.of(SUCCESS_TAG_NAME, String.valueOf(false)),
Tag.of(FAILURE_REASON_TAG_NAME, "missing_public_key"),
UserAgentTagUtil.getPlatformTag(userAgent)))
.increment();
// There was no stored public key, use a bunk public key so that validation will fail
return new BackupsDb.AuthenticationData(INVALID_PUBLIC_KEY, null, null);
});
final Pair<BackupCredentialType, BackupLevel> credentialTypeAndBackupLevel =
signatureVerifier.verifySignature(signature, authenticationData.publicKey());
Metrics.counter(ZK_AUTHN_COUNTER_NAME, SUCCESS_TAG_NAME, String.valueOf(true)).increment();
return new AuthenticatedBackupUser(
presentation.getBackupId(),
credentialTypeAndBackupLevel.first(),
credentialTypeAndBackupLevel.second(),
authenticationData.backupDir(),
authenticationData.mediaDir(),
userAgent);
}
/**
@@ -701,7 +709,6 @@ public class BackupManager {
* List and delete all files associated with a prefix
*
* @param prefixToDelete The prefix to expire.
* @return A stage that completes when all objects with the given prefix have been deleted
*/
private CompletableFuture<Void> deletePrefix(final String prefixToDelete, int concurrentDeletes) {
if (prefixToDelete.length() != BackupsDb.BACKUP_DIRECTORY_PATH_LENGTH
@@ -732,7 +739,7 @@ public class BackupManager {
interface PresentationSignatureVerifier {
Pair<BackupCredentialType, BackupLevel> verifySignature(byte[] signature, ECPublicKey publicKey);
Pair<BackupCredentialType, BackupLevel> verifySignature(byte[] signature, ECPublicKey publicKey) throws BackupFailedZkAuthenticationException;
}
/**
@@ -741,7 +748,8 @@ public class BackupManager {
* @param presentation A ZK credential presentation that encodes the backupId and the receipt level of the requester
* @return A function that can be used to verify a signature provided with the presentation
*/
private PresentationSignatureVerifier verifyPresentation(final BackupAuthCredentialPresentation presentation) {
private PresentationSignatureVerifier verifyPresentation(final BackupAuthCredentialPresentation presentation)
throws BackupFailedZkAuthenticationException {
try {
presentation.verify(clock.instant(), serverSecretParams);
} catch (VerificationFailedException e) {
@@ -749,10 +757,7 @@ public class BackupManager {
SUCCESS_TAG_NAME, String.valueOf(false),
FAILURE_REASON_TAG_NAME, "presentation_verification")
.increment();
throw Status.UNAUTHENTICATED
.withDescription("backup auth credential presentation verification failed")
.withCause(e)
.asRuntimeException();
throw new BackupFailedZkAuthenticationException("backup auth credential presentation verification failed");
}
return (signature, publicKey) -> {
if (!publicKey.verifySignature(presentation.serialize(), signature)) {
@@ -760,9 +765,7 @@ public class BackupManager {
SUCCESS_TAG_NAME, String.valueOf(false),
FAILURE_REASON_TAG_NAME, "signature_validation")
.increment();
throw Status.UNAUTHENTICATED
.withDescription("backup auth credential presentation signature verification failed")
.asRuntimeException();
throw new BackupFailedZkAuthenticationException("backup auth credential presentation signature verification failed");
}
return new Pair<>(presentation.getType(), presentation.getBackupLevel());
};
@@ -773,19 +776,18 @@ public class BackupManager {
*
* @param backupUser The backup user to check
* @param backupLevel The authorization level to verify the backupUser has access to
* @throws {@link Status#PERMISSION_DENIED} error if the backup user is not authorized to access {@code backupLevel}
* @throws BackupPermissionException if the backupUser is not authorized to access {@code backupLevel}
*/
@VisibleForTesting
static void checkBackupLevel(final AuthenticatedBackupUser backupUser, final BackupLevel backupLevel) {
static void checkBackupLevel(final AuthenticatedBackupUser backupUser, final BackupLevel backupLevel)
throws BackupPermissionException {
if (backupUser.backupLevel().compareTo(backupLevel) < 0) {
Metrics.counter(ZK_AUTHZ_FAILURE_COUNTER_NAME, Tags.of(
UserAgentTagUtil.getPlatformTag(backupUser.userAgent()),
Tag.of(FAILURE_REASON_TAG_NAME, "level")))
.increment();
throw Status.PERMISSION_DENIED
.withDescription("credential does not support the requested operation")
.asRuntimeException();
throw new BackupPermissionException("credential does not support the requested operation");
}
}
@@ -794,19 +796,17 @@ public class BackupManager {
*
* @param backupUser The backup user to check
* @param credentialType The credential type to require
* @throws {@link Status#UNAUTHENTICATED} error if the backup user is not authenticated with the given
* @throws BackupWrongCredentialTypeException error if the backup user is not authenticated with the given
* {@code credentialType}
*/
@VisibleForTesting
static void checkBackupCredentialType(final AuthenticatedBackupUser backupUser, final BackupCredentialType credentialType) {
static void checkBackupCredentialType(final AuthenticatedBackupUser backupUser, final BackupCredentialType credentialType) throws BackupWrongCredentialTypeException {
if (backupUser.credentialType() != credentialType) {
Metrics.counter(ZK_AUTHZ_FAILURE_COUNTER_NAME,
FAILURE_REASON_TAG_NAME, "credential_type")
.increment();
throw Status.UNAUTHENTICATED
.withDescription("wrong credential type for the requested operation")
.asRuntimeException();
throw new BackupWrongCredentialTypeException("wrong credential type for the requested operation");
}
}
@@ -0,0 +1,11 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.backup;
public class BackupMissingIdCommitmentException extends BackupException {
public BackupMissingIdCommitmentException() {
super();
}
}
@@ -0,0 +1,12 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.backup;
public class BackupNotFoundException extends BackupException {
public BackupNotFoundException(final String message) {
super(message);
}
}
@@ -0,0 +1,11 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.backup;
public class BackupPermissionException extends BackupException {
public BackupPermissionException(String message) {
super(message);
}
}
@@ -0,0 +1,8 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.backup;
public class BackupPublicKeyConflictException extends BackupException {
}
@@ -0,0 +1,11 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.backup;
public class BackupWrongCredentialTypeException extends BackupException {
public BackupWrongCredentialTypeException(String message) {
super(message);
}
}
@@ -4,8 +4,8 @@
*/
package org.whispersystems.textsecuregcm.backup;
import io.grpc.Status;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
@@ -22,18 +22,12 @@ import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.Predicate;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import org.signal.libsignal.protocol.InvalidKeyException;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
import org.signal.libsignal.zkgroup.backups.BackupLevel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.Util;
@@ -133,7 +127,7 @@ public class BackupsDb {
* @param authenticatedBackupLevel The backup level
* @param publicKey The public key to associate with the backup id
* @return A stage that completes when the public key has been set. If the backup-id already has a set public key that
* does not match, the stage will be completed exceptionally with a {@link PublicKeyConflictException}
* does not match, the stage will be completed exceptionally with a {@link BackupPublicKeyConflictException}
*/
CompletableFuture<Void> setPublicKey(
final byte[] authenticatedBackupId,
@@ -152,7 +146,7 @@ public class BackupsDb {
.build())
.exceptionally(ExceptionUtils.marshal(ConditionalCheckFailedException.class, e ->
// There was already a row for this backup-id and it contained a different publicKey
new PublicKeyConflictException()))
new BackupPublicKeyConflictException()))
.thenRun(Util.NOOP);
}
@@ -190,9 +184,7 @@ public class BackupsDb {
private static String getDirName(final Map<String, AttributeValue> item, final String attr) {
return AttributeValues.get(item, attr).map(AttributeValue::s).orElseThrow(() -> {
logger.error("Backups with public keys should have directory names");
return Status.INTERNAL
.withDescription("Backups with public keys must have directory names")
.asRuntimeException();
throw new UncheckedIOException(new IOException("Backups with public keys must have directory names"));
});
}
@@ -208,10 +200,7 @@ public class BackupsDb {
return new ECPublicKey(publicKeyBytes);
} catch (InvalidKeyException e) {
logger.error("Invalid publicKey {}", HexFormat.of().formatHex(publicKeyBytes), e);
throw Status.INTERNAL
.withCause(e)
.withDescription("Could not deserialize stored public key")
.asRuntimeException();
throw new UncheckedIOException(new IOException("Could not deserialize stored public key"));
}
}
@@ -330,6 +319,7 @@ public class BackupsDb {
* @param backupUser an already authorized backup user
* @return A {@link BackupDescription} containing the cdn of the message backup and the total number of media space
* bytes used by the backup user.
* @throws BackupNotFoundException If the provided backupUser's backup-id does not exist
*/
CompletableFuture<BackupDescription> describeBackup(final AuthenticatedBackupUser backupUser) {
return dynamoClient.getItem(GetItemRequest.builder()
@@ -341,7 +331,7 @@ public class BackupsDb {
.build())
.thenApply(response -> {
if (!response.hasItem()) {
throw Status.NOT_FOUND.withDescription("Backup ID not found").asRuntimeException();
throw ExceptionUtils.wrap(new BackupNotFoundException("Backup ID not found"));
}
// If the client hasn't already uploaded a backup, return the cdn we would return if they did create one
final int cdn = AttributeValues.getInt(response.item(), ATTR_CDN, BACKUP_CDN);
@@ -1,6 +0,0 @@
package org.whispersystems.textsecuregcm.backup;
import java.io.IOException;
public class PublicKeyConflictException extends IOException {
}
@@ -58,7 +58,6 @@ public class DynamoDbTables {
private final IssuedReceiptsTableConfiguration issuedReceipts;
private final Table ecKeys;
private final Table ecSignedPreKeys;
private final Table kemKeys;
private final Table kemLastResortKeys;
private final Table pagedKemKeys;
private final TableWithExpiration messages;
@@ -87,7 +86,6 @@ public class DynamoDbTables {
@JsonProperty("issuedReceipts") final IssuedReceiptsTableConfiguration issuedReceipts,
@JsonProperty("ecKeys") final Table ecKeys,
@JsonProperty("ecSignedPreKeys") final Table ecSignedPreKeys,
@JsonProperty("pqKeys") final Table kemKeys,
@JsonProperty("pqLastResortKeys") final Table kemLastResortKeys,
@JsonProperty("pagedPqKeys") final Table pagedKemKeys,
@JsonProperty("messages") final TableWithExpiration messages,
@@ -115,7 +113,6 @@ public class DynamoDbTables {
this.issuedReceipts = issuedReceipts;
this.ecKeys = ecKeys;
this.ecSignedPreKeys = ecSignedPreKeys;
this.kemKeys = kemKeys;
this.pagedKemKeys = pagedKemKeys;
this.kemLastResortKeys = kemLastResortKeys;
this.messages = messages;
@@ -199,12 +196,6 @@ public class DynamoDbTables {
return ecSignedPreKeys;
}
@NotNull
@Valid
public Table getKemKeys() {
return kemKeys;
}
@NotNull
@Valid
public Table getPagedKemKeys() {
@@ -18,7 +18,7 @@ import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
* signal subscription level
*/
public record GooglePlayBillingConfiguration(
@NotNull SecretString credentialsJson,
@NotBlank String credentialsJson,
@NotNull String packageName,
@NotBlank String applicationName,
@NotNull Map<String, Long> productIdToLevel) {}
@@ -0,0 +1,37 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import java.util.Collections;
import java.util.List;
/// Configure which gRPC methods are enabled
///
/// @param enableAll enable all gRPC methods
/// @param enabledServices A list of fully qualified service names for which all RPCs should be enabled. For example,
/// `org.signal.chat.account.AccountsAnonymous` would enable all RPCs on that service, regardless
/// of whether the RPCs on that service appear in `enabledMethods`
/// @param enabledMethods A list of fully qualified method names of RPCs that should be enabled. For example,
/// `org.signal.chat.account.AccountsAnonymous/LookupUsernameHash` would enable the
/// `LookupUsernameHash` RPC method
public record GrpcAllowListConfiguration(
boolean enableAll,
List<String> enabledServices,
List<String> enabledMethods) {
public GrpcAllowListConfiguration {
if (enabledServices == null) {
enabledServices = Collections.emptyList();
}
if (enabledMethods == null) {
enabledMethods = Collections.emptyList();
}
}
public GrpcAllowListConfiguration() {
// By default, no GRPC methods are accessible
this(false, Collections.emptyList(), Collections.emptyList());
}
}
@@ -0,0 +1,15 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
import javax.annotation.Nullable;
public record HlrLookupConfiguration(SecretString apiKey,
SecretString apiSecret,
@Nullable String circuitBreakerConfigurationName,
@Nullable String retryConfigurationName) {
}
@@ -7,16 +7,19 @@ package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonTypeName;
import jakarta.validation.constraints.NotBlank;
import java.net.URI;
import java.time.Duration;
import java.util.concurrent.ScheduledExecutorService;
import org.whispersystems.textsecuregcm.s3.S3ObjectMonitor;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import javax.annotation.Nullable;
@JsonTypeName("default")
public record MonitoredS3ObjectConfiguration(
@NotBlank String s3Region,
@NotBlank String s3Bucket,
@NotBlank String objectKey,
@Nullable URI endpointOverride,
Long maxSize,
Duration refreshInterval) implements S3ObjectMonitorFactory {
@@ -36,6 +39,10 @@ public record MonitoredS3ObjectConfiguration(
public S3ObjectMonitor build(final AwsCredentialsProvider awsCredentialsProvider,
final ScheduledExecutorService refreshExecutorService) {
if (endpointOverride != null && !endpointOverride.toString().isEmpty()) {
return new S3ObjectMonitor(awsCredentialsProvider, endpointOverride, s3Region, s3Bucket, objectKey,
maxSize, refreshExecutorService, refreshInterval);
}
return new S3ObjectMonitor(awsCredentialsProvider, s3Region, s3Bucket, objectKey, maxSize, refreshExecutorService,
refreshInterval);
}
@@ -14,7 +14,8 @@ import org.whispersystems.textsecuregcm.util.ExactlySize;
public record UnidentifiedDeliveryConfiguration(@NotNull @NotEmpty byte[] certificate,
@ExactlySize(32) SecretBytes privateKey,
int expiresDays) {
int expiresDays,
boolean embedSigner) {
public ECPrivateKey ecPrivateKey() throws InvalidKeyException {
return new ECPrivateKey(privateKey.value());
}
@@ -0,0 +1,24 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration.dynamic;
import jakarta.validation.constraints.NotNull;
import java.time.Duration;
public record DynamicCarrierDataLookupConfiguration(boolean enabled, @NotNull Duration maxCacheAge) {
public static Duration DEFAULT_MAX_CACHE_AGE = Duration.ofDays(7);
public DynamicCarrierDataLookupConfiguration() {
this(false, DEFAULT_MAX_CACHE_AGE);
}
public DynamicCarrierDataLookupConfiguration {
if (maxCacheAge == null) {
maxCacheAge = DEFAULT_MAX_CACHE_AGE;
}
}
}
@@ -68,6 +68,10 @@ public class DynamicConfiguration {
@Valid
private DynamicBackupConfiguration backup = new DynamicBackupConfiguration();
@JsonProperty
@Valid
private DynamicCarrierDataLookupConfiguration carrierDataLookup = new DynamicCarrierDataLookupConfiguration();
public Optional<DynamicExperimentEnrollmentConfiguration> getExperimentEnrollmentConfiguration(
final String experimentName) {
return Optional.ofNullable(experiments.get(experimentName));
@@ -121,4 +125,8 @@ public class DynamicConfiguration {
public DynamicBackupConfiguration getBackupConfiguration() {
return backup;
}
public DynamicCarrierDataLookupConfiguration getCarrierDataLookupConfiguration() {
return carrierDataLookup;
}
}
@@ -5,6 +5,9 @@
package org.whispersystems.textsecuregcm.controllers;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
@@ -25,6 +28,7 @@ import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
@@ -56,6 +60,7 @@ import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
@@ -67,6 +72,8 @@ import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
import org.whispersystems.textsecuregcm.util.Util;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@Path("/v1/accounts")
@io.swagger.v3.oas.annotations.tags.Tag(name = "Account")
@@ -75,6 +82,10 @@ public class AccountController {
public static final int USERNAME_HASH_LENGTH = 32;
public static final int MAXIMUM_USERNAME_CIPHERTEXT_LENGTH = 128;
private static final String RECOVERY_PASSWORD_SET_COUNTER_NAME =
name(AccountController.class, "recoveryPasswordSet");
private final AccountsManager accounts;
private final RateLimiters rateLimiters;
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
@@ -239,7 +250,8 @@ public class AccountController {
@Produces(MediaType.APPLICATION_JSON)
public void setAccountAttributes(
@Auth AuthenticatedDevice auth,
@HeaderParam(HeaderUtils.X_SIGNAL_AGENT) String userAgent,
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent,
@HeaderParam(HeaderUtils.X_SIGNAL_AGENT) String signalAgent,
@NotNull @Valid AccountAttributes attributes) {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
@@ -250,8 +262,8 @@ public class AccountController {
d.setName(attributes.getName());
d.setLastSeen(Util.todayInMillis());
d.setCapabilities(attributes.getCapabilities());
if (StringUtils.isNotBlank(userAgent)) {
d.setUserAgent(userAgent);
if (StringUtils.isNotBlank(signalAgent)) {
d.setUserAgent(signalAgent);
}
});
@@ -262,8 +274,15 @@ public class AccountController {
});
// if registration recovery password was sent to us, store it (or refresh its expiration)
attributes.recoveryPassword().ifPresent(registrationRecoveryPassword ->
registrationRecoveryPasswordsManager.store(updatedAccount.getIdentifier(IdentityType.PNI), registrationRecoveryPassword));
attributes.recoveryPassword().ifPresent(registrationRecoveryPassword -> {
final boolean rrpCreated = registrationRecoveryPasswordsManager
.store(updatedAccount.getIdentifier(IdentityType.PNI), registrationRecoveryPassword)
.join();
Metrics.counter(RECOVERY_PASSWORD_SET_COUNTER_NAME, Tags.of(
UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of("outcome", rrpCreated ? "created" : "updated")))
.increment();
});
}
@GET
@@ -35,7 +35,6 @@ import jakarta.ws.rs.core.Response;
import java.time.Instant;
import java.util.Optional;
import java.util.UUID;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.ChangesPhoneNumber;
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
@@ -45,7 +44,6 @@ import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
import org.whispersystems.textsecuregcm.entities.ChangeNumberRequest;
import org.whispersystems.textsecuregcm.entities.MismatchedDevicesResponse;
import org.whispersystems.textsecuregcm.entities.PhoneNumberDiscoverabilityRequest;
import org.whispersystems.textsecuregcm.entities.PhoneNumberIdentityKeyDistributionRequest;
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
import org.whispersystems.textsecuregcm.entities.StaleDevicesResponse;
@@ -171,35 +169,6 @@ public class AccountControllerV2 {
}
}
// TODO Remove entirely on or after 2025-10-08
@Deprecated(forRemoval = true)
@PUT
@Path("/phone_number_identity_key_distribution")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(summary = "Set phone-number identity keys",
description = "Updates key material for the phone-number identity for all devices and sends a synchronization message to companion devices")
@ApiResponse(responseCode = "200", description = "Indicates the transaction was successful and returns basic information about this account.", useReturnTypeSchema = true)
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
@ApiResponse(responseCode = "403", description = "This endpoint can only be invoked from the account's primary device.")
@ApiResponse(responseCode = "422", description = "The request body failed validation.")
public AccountIdentityResponse distributePhoneNumberIdentityKeys(
@Auth final AuthenticatedDevice authenticatedDevice,
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgentString,
@NotNull @Valid final PhoneNumberIdentityKeyDistributionRequest request) {
if (authenticatedDevice.deviceId() != Device.PRIMARY_ID) {
throw new ForbiddenException();
}
if (!request.isSignatureValidOnEachSignedPreKey(userAgentString)) {
throw new WebApplicationException("Invalid signature", 422);
}
return AccountIdentityResponseBuilder.fromAccount(accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED)));
}
@PUT
@Path("/phone_number_discoverability")
@Consumes(MediaType.APPLICATION_JSON)
@@ -47,28 +47,35 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.time.Clock;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.glassfish.jersey.server.ManagedAsync;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialPresentation;
import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialRequest;
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
import org.whispersystems.textsecuregcm.auth.RedemptionRange;
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
import org.whispersystems.textsecuregcm.backup.BackupBadReceiptException;
import org.whispersystems.textsecuregcm.backup.BackupFailedZkAuthenticationException;
import org.whispersystems.textsecuregcm.backup.BackupInvalidArgumentException;
import org.whispersystems.textsecuregcm.backup.BackupManager;
import org.whispersystems.textsecuregcm.backup.BackupMissingIdCommitmentException;
import org.whispersystems.textsecuregcm.backup.BackupNotFoundException;
import org.whispersystems.textsecuregcm.backup.BackupPermissionException;
import org.whispersystems.textsecuregcm.backup.BackupUploadDescriptor;
import org.whispersystems.textsecuregcm.backup.BackupWrongCredentialTypeException;
import org.whispersystems.textsecuregcm.backup.CopyParameters;
import org.whispersystems.textsecuregcm.backup.CopyResult;
import org.whispersystems.textsecuregcm.backup.MediaEncryptionParameters;
@@ -83,8 +90,6 @@ import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import org.whispersystems.textsecuregcm.util.ByteArrayBase64UrlAdapter;
import org.whispersystems.textsecuregcm.util.ECPublicKeyAdapter;
import org.whispersystems.textsecuregcm.util.ExactlySize;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Mono;
@Path("/v1/archives")
@io.swagger.v3.oas.annotations.tags.Tag(name = "Archive")
@@ -149,24 +154,21 @@ public class ArchiveController {
@ApiResponse(responseCode = "400", description = "The provided backup auth credential request was invalid")
@ApiResponse(responseCode = "403", description = "The device did not have permission to set the backup-id. Only the primary device can set the backup-id for an account")
@ApiResponse(responseCode = "429", description = "Rate limited. Too many attempts to change the backup-id have been made")
public CompletionStage<Response> setBackupId(
@ManagedAsync
public void setBackupId(
@Auth final AuthenticatedDevice authenticatedDevice,
@Valid @NotNull final SetBackupIdRequest setBackupIdRequest) throws RateLimitExceededException {
@Valid @NotNull final SetBackupIdRequest setBackupIdRequest)
throws RateLimitExceededException, BackupInvalidArgumentException, BackupPermissionException {
return accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier())
.thenCompose(maybeAccount -> {
final Account account = maybeAccount
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
final Device device = account.getDevice(authenticatedDevice.deviceId())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
final Device device = account.getDevice(authenticatedDevice.deviceId())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
return backupAuthManager
.commitBackupId(account, device,
Optional.ofNullable(setBackupIdRequest.messagesBackupAuthCredentialRequest),
Optional.ofNullable(setBackupIdRequest.mediaBackupAuthCredentialRequest))
.thenApply(Util.ASYNC_EMPTY_RESPONSE);
});
backupAuthManager
.commitBackupId(account, device,
Optional.ofNullable(setBackupIdRequest.messagesBackupAuthCredentialRequest),
Optional.ofNullable(setBackupIdRequest.mediaBackupAuthCredentialRequest));
}
@@ -186,15 +188,13 @@ public class ArchiveController {
""")
@ApiResponse(responseCode = "200", description = "Successfully retrieved backup-id rotation limits", useReturnTypeSchema = true)
@ApiResponse(responseCode = "403", description = "Invalid account authentication")
public CompletionStage<BackupIdLimitResponse> checkLimits(@Auth final AuthenticatedDevice authenticatedDevice) {
return accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier())
.thenCompose(maybeAccount -> {
final Account account = maybeAccount
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
@ManagedAsync
public BackupIdLimitResponse checkLimits(@Auth final AuthenticatedDevice authenticatedDevice) {
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
return backupAuthManager.checkBackupIdRotationLimit(account).thenApply(limit ->
new BackupIdLimitResponse(limit.hasPermitsRemaining(), limit.nextPermitAvailable().getSeconds()));
});
final BackupAuthManager.BackupIdRotationLimit limit = backupAuthManager.checkBackupIdRotationLimit(account);
return new BackupIdLimitResponse(limit.hasPermitsRemaining(), limit.nextPermitAvailable().getSeconds());
}
public record RedeemBackupReceiptRequest(
@@ -237,18 +237,17 @@ public class ArchiveController {
@ApiResponse(responseCode = "400", description = "The provided presentation or receipt was invalid")
@ApiResponse(responseCode = "409", description = "The target account does not have a backup-id commitment")
@ApiResponse(responseCode = "429", description = "Rate limited.")
public CompletionStage<Response> redeemReceipt(
@ManagedAsync
public Response redeemReceipt(
@Auth final AuthenticatedDevice authenticatedDevice,
@Valid @NotNull final RedeemBackupReceiptRequest redeemBackupReceiptRequest) {
@Valid @NotNull final RedeemBackupReceiptRequest redeemBackupReceiptRequest)
throws BackupInvalidArgumentException, BackupMissingIdCommitmentException, BackupBadReceiptException {
return accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier())
.thenCompose(maybeAccount -> {
final Account account = maybeAccount
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
return backupAuthManager.redeemReceipt(account, redeemBackupReceiptRequest.receiptCredentialPresentation())
.thenApply(Util.ASYNC_EMPTY_RESPONSE);
});
backupAuthManager.redeemReceipt(account, redeemBackupReceiptRequest.receiptCredentialPresentation());
return Response.noContent().build();
}
public record BackupAuthCredentialsResponse(
@@ -306,14 +305,15 @@ public class ArchiveController {
@ApiResponse(responseCode = "400", description = "The start/end did not meet alignment/duration requirements")
@ApiResponse(responseCode = "404", description = "Could not find an existing blinded backup id")
@ApiResponse(responseCode = "429", description = "Rate limited.")
public CompletionStage<BackupAuthCredentialsResponse> getBackupZKCredentials(
@ManagedAsync
public BackupAuthCredentialsResponse getBackupZKCredentials(
@Auth AuthenticatedDevice authenticatedDevice,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@NotNull @QueryParam("redemptionStartSeconds") Long startSeconds,
@NotNull @QueryParam("redemptionEndSeconds") Long endSeconds) {
@NotNull @QueryParam("redemptionEndSeconds") Long endSeconds) throws BackupNotFoundException {
final Map<BackupCredentialType, List<BackupAuthCredentialsResponse.BackupAuthCredential>> credentialsByType =
new ConcurrentHashMap<>();
new HashMap<>();
final RedemptionRange redemptionRange;
try {
@@ -322,33 +322,26 @@ public class ArchiveController {
throw new BadRequestException(e.getMessage());
}
return accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier())
.thenCompose(maybeAccount -> {
final Account account = maybeAccount
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
return CompletableFuture.allOf(Arrays.stream(BackupCredentialType.values())
.map(credentialType -> this.backupAuthManager.getBackupAuthCredentials(
account,
credentialType,
redemptionRange)
.thenAccept(credentials -> {
backupMetrics.updateGetCredentialCounter(
UserAgentTagUtil.getPlatformTag(userAgent),
credentialType,
credentials.size());
credentialsByType.put(credentialType, credentials.stream()
.map(credential -> new BackupAuthCredentialsResponse.BackupAuthCredential(
credential.credential().serialize(),
credential.redemptionTime().getEpochSecond()))
.toList());
}))
.toArray(CompletableFuture[]::new))
.thenApply(ignored -> new BackupAuthCredentialsResponse(credentialsByType.entrySet().stream()
.collect(Collectors.toMap(
e -> BackupAuthCredentialsResponse.CredentialType.fromLibsignalType(e.getKey()),
Map.Entry::getValue))));
});
for (BackupCredentialType credentialType : BackupCredentialType.values()) {
final List<BackupAuthManager.Credential> credentials =
backupAuthManager.getBackupAuthCredentials(account, credentialType, redemptionRange);
backupMetrics.updateGetCredentialCounter(
UserAgentTagUtil.getPlatformTag(userAgent),
credentialType,
credentials.size());
credentialsByType.put(credentialType, credentials.stream()
.map(credential -> new BackupAuthCredentialsResponse.BackupAuthCredential(
credential.credential().serialize(),
credential.redemptionTime().getEpochSecond()))
.toList());
}
return new BackupAuthCredentialsResponse(credentialsByType.entrySet().stream()
.collect(Collectors.toMap(
e -> BackupAuthCredentialsResponse.CredentialType.fromLibsignalType(e.getKey()),
Map.Entry::getValue)));
}
@@ -408,9 +401,11 @@ public class ArchiveController {
summary = "Get CDN read credentials",
description = "Retrieve credentials used to read objects stored on the backup cdn")
@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = ReadAuthResponse.class)))
@ApiResponse(responseCode = "400", description = "Bad arguments. The request may have been made on an authenticated channel, or an invalid cdn number was provided")
@ApiResponse(responseCode = "429", description = "Rate limited.")
@ApiResponseZkAuth
public CompletionStage<ReadAuthResponse> readAuth(
@ManagedAsync
public ReadAuthResponse readAuth(
@Auth final Optional<AuthenticatedDevice> account,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@@ -422,13 +417,14 @@ public class ArchiveController {
@NotNull
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature,
@NotNull @Parameter(description = "The number of the CDN to get credentials for") @QueryParam("cdn") final Integer cdn) {
@NotNull @Parameter(description = "The number of the CDN to get credentials for") @QueryParam("cdn") final Integer cdn)
throws BackupFailedZkAuthenticationException, BackupInvalidArgumentException, BackupPermissionException {
if (account.isPresent()) {
throw new BadRequestException("must not use authenticated connection for anonymous operations");
}
return backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent)
.thenApply(user -> backupManager.generateReadAuth(user, cdn))
.thenApply(ReadAuthResponse::new);
final AuthenticatedBackupUser backupUser =
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
return new ReadAuthResponse(backupManager.generateReadAuth(backupUser, cdn));
}
@GET
@@ -441,7 +437,8 @@ public class ArchiveController {
""")
@ApiResponse(responseCode = "200", description = "`JSON` with generated credentials.", useReturnTypeSchema = true)
@ApiResponseZkAuth
public CompletionStage<ExternalServiceCredentials> svrbAuth(
@ManagedAsync
public ExternalServiceCredentials svrbAuth(
@Auth final Optional<AuthenticatedDevice> account,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@@ -451,13 +448,14 @@ public class ArchiveController {
@Parameter(description = BackupAuthCredentialPresentationSignature.DESCRIPTION, schema = @Schema(implementation = String.class))
@NotNull
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature) {
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature)
throws BackupFailedZkAuthenticationException, BackupWrongCredentialTypeException, BackupPermissionException {
if (account.isPresent()) {
throw new BadRequestException("must not use authenticated connection for anonymous operations");
}
return backupManager
.authenticateBackupUser(presentation.presentation, signature.signature, userAgent)
.thenApply(backupManager::generateSvrbAuth);
final AuthenticatedBackupUser backupUser =
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
return backupManager.generateSvrbAuth(backupUser);
}
public record BackupInfoResponse(
@@ -491,7 +489,8 @@ public class ArchiveController {
@ApiResponse(responseCode = "404", description = "No existing backups found")
@ApiResponse(responseCode = "429", description = "Rate limited.")
@ApiResponseZkAuth
public CompletionStage<BackupInfoResponse> backupInfo(
@ManagedAsync
public BackupInfoResponse backupInfo(
@Auth final Optional<AuthenticatedDevice> account,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@@ -501,19 +500,21 @@ public class ArchiveController {
@Parameter(description = BackupAuthCredentialPresentationSignature.DESCRIPTION, schema = @Schema(implementation = String.class))
@NotNull
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature) {
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature)
throws BackupFailedZkAuthenticationException, BackupNotFoundException, BackupPermissionException {
if (account.isPresent()) {
throw new BadRequestException("must not use authenticated connection for anonymous operations");
}
return backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent)
.thenCompose(backupManager::backupInfo)
.thenApply(backupInfo -> new BackupInfoResponse(
final AuthenticatedBackupUser backupUser =
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
final BackupManager.BackupInfo backupInfo = backupManager.backupInfo(backupUser);
return new BackupInfoResponse(
backupInfo.cdn(),
backupInfo.backupSubdir(),
backupInfo.mediaSubdir(),
backupInfo.messageBackupKey(),
backupInfo.mediaUsedSpace().orElse(0L)));
backupInfo.mediaUsedSpace().orElse(0L));
}
public record SetPublicKeyRequest(
@@ -531,13 +532,14 @@ public class ArchiveController {
summary = "Set public key",
description = """
Permanently set the public key of an ED25519 key-pair for the backup-id. All requests that provide a anonymous
BackupAuthCredentialPresentation (including this one!) must also sign the presentation with the private key
BackupAuthCredentialPresentation (including this one!) must also sign the presentation with the private key
corresponding to the provided public key.
""")
@ApiResponseZkAuth
@ApiResponse(responseCode = "204", description = "The public key was set")
@ApiResponse(responseCode = "429", description = "Rate limited.")
public CompletionStage<Response> setPublicKey(
@ManagedAsync
public void setPublicKey(
@Auth final Optional<AuthenticatedDevice> account,
@Parameter(description = BackupAuthCredentialPresentationHeader.DESCRIPTION, schema = @Schema(implementation = String.class))
@@ -548,13 +550,12 @@ public class ArchiveController {
@NotNull
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature,
@Valid @NotNull SetPublicKeyRequest setPublicKeyRequest) {
@Valid @NotNull SetPublicKeyRequest setPublicKeyRequest)
throws BackupFailedZkAuthenticationException {
if (account.isPresent()) {
throw new BadRequestException("must not use authenticated connection for anonymous operations");
}
return backupManager
.setPublicKey(presentation.presentation, signature.signature, setPublicKeyRequest.backupIdPublicKey)
.thenApply(Util.ASYNC_EMPTY_RESPONSE);
backupManager.setPublicKey(presentation.presentation, signature.signature, setPublicKeyRequest.backupIdPublicKey);
}
@@ -578,7 +579,8 @@ public class ArchiveController {
@ApiResponse(responseCode = "429", description = "Rate limited.")
@ApiResponse(responseCode = "413", description = "The provided uploadLength is larger than the maximum supported upload size. The maximum upload size is subject to change.")
@ApiResponseZkAuth
public CompletionStage<UploadDescriptorResponse> backup(
@ManagedAsync
public UploadDescriptorResponse backup(
@Auth final Optional<AuthenticatedDevice> account,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@@ -591,26 +593,30 @@ public class ArchiveController {
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature,
@Parameter(description = "The size of the message backup to upload in bytes")
@QueryParam("uploadLength") final Optional<Long> uploadLength) {
@QueryParam("uploadLength") final Optional<Long> uploadLength)
throws BackupFailedZkAuthenticationException, BackupWrongCredentialTypeException, BackupPermissionException {
if (account.isPresent()) {
throw new BadRequestException("must not use authenticated connection for anonymous operations");
}
return backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent)
.thenCompose(backupUser -> {
final boolean oversize = uploadLength
.map(length -> length > BackupManager.MAX_MESSAGE_BACKUP_OBJECT_SIZE)
.orElse(false);
backupMetrics.updateMessageBackupSizeDistribution(backupUser, oversize, uploadLength);
if (oversize) {
throw new ClientErrorException("exceeded maximum uploadLength", Response.Status.REQUEST_ENTITY_TOO_LARGE);
}
return backupManager.createMessageBackupUploadDescriptor(backupUser);
})
.thenApply(result -> new UploadDescriptorResponse(
result.cdn(),
result.key(),
result.headers(),
result.signedUploadLocation()));
final AuthenticatedBackupUser backupUser =
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
final boolean oversize = uploadLength
.map(length -> length > BackupManager.MAX_MESSAGE_BACKUP_OBJECT_SIZE)
.orElse(false);
backupMetrics.updateMessageBackupSizeDistribution(backupUser, oversize, uploadLength);
if (oversize) {
throw new ClientErrorException("exceeded maximum uploadLength", Response.Status.REQUEST_ENTITY_TOO_LARGE);
}
final BackupUploadDescriptor uploadDescriptor =
backupManager.createMessageBackupUploadDescriptor(backupUser);
return new UploadDescriptorResponse(
uploadDescriptor.cdn(),
uploadDescriptor.key(),
uploadDescriptor.headers(),
uploadDescriptor.signedUploadLocation());
}
@GET
@@ -627,7 +633,8 @@ public class ArchiveController {
@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = UploadDescriptorResponse.class)))
@ApiResponse(responseCode = "429", description = "Rate limited.")
@ApiResponseZkAuth
public CompletionStage<UploadDescriptorResponse> uploadTemporaryAttachment(
@ManagedAsync
public UploadDescriptorResponse uploadTemporaryAttachment(
@Auth final Optional<AuthenticatedDevice> account,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@@ -638,17 +645,20 @@ public class ArchiveController {
@Parameter(description = BackupAuthCredentialPresentationSignature.DESCRIPTION, schema = @Schema(implementation = String.class))
@NotNull
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature) {
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature)
throws RateLimitExceededException, BackupFailedZkAuthenticationException, BackupWrongCredentialTypeException, BackupPermissionException {
if (account.isPresent()) {
throw new BadRequestException("must not use authenticated connection for anonymous operations");
}
return backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent)
.thenCompose(backupManager::createTemporaryAttachmentUploadDescriptor)
.thenApply(result -> new UploadDescriptorResponse(
result.cdn(),
result.key(),
result.headers(),
result.signedUploadLocation()));
final AuthenticatedBackupUser backupUser =
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
final BackupUploadDescriptor uploadDescriptor =
backupManager.createTemporaryAttachmentUploadDescriptor(backupUser);
return new UploadDescriptorResponse(
uploadDescriptor.cdn(),
uploadDescriptor.key(),
uploadDescriptor.headers(),
uploadDescriptor.signedUploadLocation());
}
public record CopyMediaRequest(
@@ -715,7 +725,8 @@ public class ArchiveController {
@ApiResponse(responseCode = "410", description = "The source object was not found.")
@ApiResponse(responseCode = "429", description = "Rate limited.")
@ApiResponseZkAuth
public CompletionStage<CopyMediaResponse> copyMedia(
@ManagedAsync
public CopyMediaResponse copyMedia(
@Auth final Optional<AuthenticatedDevice> account,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@@ -728,24 +739,27 @@ public class ArchiveController {
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature,
@NotNull
@Valid final ArchiveController.CopyMediaRequest copyMediaRequest) {
@Valid final ArchiveController.CopyMediaRequest copyMediaRequest)
throws BackupFailedZkAuthenticationException, BackupWrongCredentialTypeException, BackupPermissionException, BackupInvalidArgumentException {
if (account.isPresent()) {
throw new BadRequestException("must not use authenticated connection for anonymous operations");
}
return Mono
.fromFuture(backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent))
.flatMap(backupUser -> backupManager.copyToBackup(backupUser, List.of(copyMediaRequest.toCopyParameters()))
.next()
.doOnNext(result -> backupMetrics.updateCopyCounter(result, UserAgentTagUtil.getPlatformTag(userAgent)))
.map(copyResult -> switch (copyResult.outcome()) {
case SUCCESS -> new CopyMediaResponse(copyResult.cdn());
case SOURCE_WRONG_LENGTH -> throw new BadRequestException("Invalid length");
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();
final AuthenticatedBackupUser backupUser =
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
final BackupManager.CopyQuota copyQuota =
backupManager.getCopyQuota(backupUser, List.of(copyMediaRequest.toCopyParameters()));
final CopyResult copyResult = backupManager.copyToBackup(copyQuota).next()
.blockOptional()
.orElseThrow(() -> new IllegalStateException("Non empty copy request must return result"));
backupMetrics.updateCopyCounter(copyResult, UserAgentTagUtil.getPlatformTag(userAgent));
return 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);
};
}
public record CopyMediaBatchRequest(
@@ -808,13 +822,14 @@ public class ArchiveController {
be provided as a separate entry in the response.
""")
@ApiResponse(responseCode = "207", description = """
The request was processed and each operation's outcome must be inspected individually. This does NOT necessarily
The request was processed and each operation's outcome must be inspected individually. This does NOT necessarily
indicate the operation was a success.
""", content = @Content(schema = @Schema(implementation = CopyMediaBatchResponse.class)))
@ApiResponse(responseCode = "413", description = "All media capacity has been consumed. Free some space to continue.")
@ApiResponse(responseCode = "429", description = "Rate limited.")
@ApiResponseZkAuth
public CompletionStage<Response> copyMedia(
@ManagedAsync
public Response copyMedia(
@Auth final Optional<AuthenticatedDevice> account,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@@ -827,19 +842,21 @@ public class ArchiveController {
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature,
@NotNull
@Valid final ArchiveController.CopyMediaBatchRequest copyMediaRequest) {
@Valid final ArchiveController.CopyMediaBatchRequest copyMediaRequest)
throws BackupFailedZkAuthenticationException, BackupWrongCredentialTypeException, BackupPermissionException, BackupInvalidArgumentException {
if (account.isPresent()) {
throw new BadRequestException("must not use authenticated connection for anonymous operations");
}
final Stream<CopyParameters> copyParams = copyMediaRequest.items().stream().map(CopyMediaRequest::toCopyParameters);
return Mono.fromFuture(backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent))
.flatMapMany(backupUser -> backupManager.copyToBackup(backupUser, copyParams.toList()))
final AuthenticatedBackupUser backupUser =
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
final BackupManager.CopyQuota copyQuota = backupManager.getCopyQuota(backupUser, copyParams.toList());
final List<CopyMediaBatchResponse.Entry> copyResults = backupManager.copyToBackup(copyQuota)
.doOnNext(result -> backupMetrics.updateCopyCounter(result, UserAgentTagUtil.getPlatformTag(userAgent)))
.map(CopyMediaBatchResponse.Entry::fromCopyResult)
.collectList()
.map(list -> Response.status(207).entity(new CopyMediaBatchResponse(list)).build())
.toFuture();
.collectList().block();
return Response.status(207).entity(new CopyMediaBatchResponse(copyResults)).build();
}
@POST
@@ -853,7 +870,8 @@ public class ArchiveController {
@ApiResponse(responseCode = "204", description = "The backup was successfully refreshed")
@ApiResponse(responseCode = "429", description = "Rate limited.")
@ApiResponseZkAuth
public CompletionStage<Response> refresh(
@ManagedAsync
public void refresh(
@Auth final Optional<AuthenticatedDevice> account,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@@ -863,14 +881,14 @@ public class ArchiveController {
@Parameter(description = BackupAuthCredentialPresentationSignature.DESCRIPTION, schema = @Schema(implementation = String.class))
@NotNull
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature) {
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature)
throws BackupFailedZkAuthenticationException, BackupPermissionException {
if (account.isPresent()) {
throw new BadRequestException("must not use authenticated connection for anonymous operations");
}
return backupManager
.authenticateBackupUser(presentation.presentation, signature.signature, userAgent)
.thenCompose(backupManager::ttlRefresh)
.thenApply(Util.ASYNC_EMPTY_RESPONSE);
final AuthenticatedBackupUser backupUser =
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
backupManager.ttlRefresh(backupUser);
}
record StoredMediaObject(
@@ -920,7 +938,8 @@ public class ArchiveController {
@ApiResponse(responseCode = "400", description = "Invalid cursor or limit")
@ApiResponse(responseCode = "429", description = "Rate limited.")
@ApiResponseZkAuth
public CompletionStage<ListResponse> listMedia(
@ManagedAsync
public ListResponse listMedia(
@Auth final Optional<AuthenticatedDevice> account,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@@ -936,20 +955,21 @@ public class ArchiveController {
@QueryParam("cursor") final Optional<String> cursor,
@Parameter(description = "The number of entries to return per call")
@QueryParam("limit") final Optional<@Min(1) @Max(10_000) Integer> limit) {
@QueryParam("limit") final Optional<@Min(1) @Max(10_000) Integer> limit)
throws BackupPermissionException, BackupFailedZkAuthenticationException {
if (account.isPresent()) {
throw new BadRequestException("must not use authenticated connection for anonymous operations");
}
return backupManager
.authenticateBackupUser(presentation.presentation, signature.signature, userAgent)
.thenCompose(backupUser -> backupManager.list(backupUser, cursor, limit.orElse(1000))
.thenApply(result -> new ListResponse(
result.media()
.stream().map(entry -> new StoredMediaObject(entry.cdn(), entry.key(), entry.length()))
.toList(),
backupUser.backupDir(),
backupUser.mediaDir(),
result.cursor().orElse(null))));
final AuthenticatedBackupUser backupUser =
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
final BackupManager.ListMediaResult listResult =
backupManager.list(backupUser, cursor, limit.orElse(1000));
return new ListResponse(listResult.media()
.stream().map(entry -> new StoredMediaObject(entry.cdn(), entry.key(), entry.length()))
.toList(),
backupUser.backupDir(),
backupUser.mediaDir(),
listResult.cursor().orElse(null));
}
public record DeleteMedia(@Size(min = 1, max = 1000) List<@Valid MediaToDelete> mediaToDelete) {
@@ -976,7 +996,8 @@ public class ArchiveController {
@ApiResponse(responseCode = "204", description = "The provided objects were successfully deleted or they do not exist")
@ApiResponse(responseCode = "429", description = "Rate limited.")
@ApiResponseZkAuth
public CompletionStage<Response> deleteMedia(
@ManagedAsync
public void deleteMedia(
@Auth final Optional<AuthenticatedDevice> account,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@@ -988,7 +1009,8 @@ public class ArchiveController {
@NotNull
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature,
@Valid @NotNull DeleteMedia deleteMedia) {
@Valid @NotNull DeleteMedia deleteMedia)
throws BackupFailedZkAuthenticationException, BackupWrongCredentialTypeException, BackupPermissionException {
if (account.isPresent()) {
throw new BadRequestException("must not use authenticated connection for anonymous operations");
}
@@ -997,12 +1019,9 @@ public class ArchiveController {
.map(media -> new BackupManager.StorageDescriptor(media.cdn(), media.mediaId))
.toList();
return backupManager
.authenticateBackupUser(presentation.presentation, signature.signature, userAgent)
.thenCompose(authenticatedBackupUser -> backupManager
.deleteMedia(authenticatedBackupUser, toDelete)
.then().toFuture())
.thenApply(Util.ASYNC_EMPTY_RESPONSE);
final AuthenticatedBackupUser backupUser =
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
backupManager.deleteMedia(backupUser, toDelete).then().block();
}
@DELETE
@@ -1013,7 +1032,8 @@ public class ArchiveController {
@ApiResponse(responseCode = "204", description = "The backup has been successfully removed")
@ApiResponse(responseCode = "429", description = "Rate limited.")
@ApiResponseZkAuth
public CompletionStage<Response> deleteBackup(
@ManagedAsync
public void deleteBackup(
@Auth final Optional<AuthenticatedDevice> account,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@@ -1023,14 +1043,15 @@ public class ArchiveController {
@Parameter(description = BackupAuthCredentialPresentationSignature.DESCRIPTION, schema = @Schema(implementation = String.class))
@NotNull
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature) {
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature)
throws BackupPermissionException, BackupFailedZkAuthenticationException {
if (account.isPresent()) {
throw new BadRequestException("must not use authenticated connection for anonymous operations");
}
return backupManager
.authenticateBackupUser(presentation.presentation, signature.signature, userAgent)
.thenCompose(backupManager::deleteEntireBackup)
.thenApply(Util.ASYNC_EMPTY_RESPONSE);
final AuthenticatedBackupUser backupUser =
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
backupManager.deleteEntireBackup(backupUser);
}
}
@@ -29,6 +29,7 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.CallQualityInvalidArgumentsException;
import org.whispersystems.textsecuregcm.metrics.CallQualitySurveyManager;
@Path("/v1/call_quality_survey")
@@ -50,7 +51,7 @@ public class CallQualitySurveyController {
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
name = "Retry-After",
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
@RateLimitedByIp(RateLimiters.For.SUBMIT_CALL_QUALITY_SURVERY)
@RateLimitedByIp(RateLimiters.For.SUBMIT_CALL_QUALITY_SURVEY)
public void submitCallQualitySurvey(@Auth final Optional<AuthenticatedDevice> authenticatedDevice,
@RequestBody(description = "A serialized survey response protobuf entity")
@NotNull final byte[] surveyResponse,
@@ -66,11 +67,15 @@ public class CallQualitySurveyController {
try {
submitCallQualitySurveyRequest = SubmitCallQualitySurveyRequest.parseFrom(surveyResponse);
} catch (final InvalidProtocolBufferException e) {
throw new WebApplicationException(422);
throw new WebApplicationException("Invalid protobuf entity", 422);
}
final String remoteAddress = (String) requestContext.getProperty(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
callQualitySurveyManager.submitCallQualitySurvey(submitCallQualitySurveyRequest, remoteAddress, userAgentString);
try {
callQualitySurveyManager.submitCallQualitySurvey(submitCallQualitySurveyRequest, remoteAddress, userAgentString);
} catch (final CallQualityInvalidArgumentsException e) {
throw new WebApplicationException(e.getMessage(), 422);
}
}
}
@@ -252,8 +252,7 @@ public class DeviceCheckController {
switch (request.assertionRequest().action()) {
case BACKUP -> backupAuthManager.extendBackupVoucher(
account,
new Account.BackupVoucher(backupRedemptionLevel, clock.instant().plus(backupRedemptionDuration)))
.join();
new Account.BackupVoucher(backupRedemptionLevel, clock.instant().plus(backupRedemptionDuration)));
}
}
@@ -115,9 +115,6 @@ public class DeviceController {
private static final String WAIT_FOR_TRANSFER_ARCHIVE_TIMER_NAME =
MetricsUtil.name(DeviceController.class, "waitForTransferArchiveDuration");
private static final String RECORD_TRANSFER_ARCHIVE_UPLOADED_COUNTER_NAME = MetricsUtil.name(DeviceController.class, "recordTransferArchiveUploaded");
private static final String HAS_REGISTRATION_ID_TAG_NAME = "hasRegistrationId";
@VisibleForTesting
static final int MIN_TOKEN_IDENTIFIER_LENGTH = 32;
@@ -537,14 +534,7 @@ public class DeviceController {
@ApiResponse(responseCode = "422", description = "The request object could not be parsed or was otherwise invalid")
@ApiResponse(responseCode = "429", description = "Rate-limited; try again after the prescribed delay")
public CompletionStage<Void> recordTransferArchiveUploaded(@Auth final AuthenticatedDevice authenticatedDevice,
@NotNull @Valid final TransferArchiveUploadedRequest transferArchiveUploadedRequest,
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable String userAgent) {
Metrics.counter(RECORD_TRANSFER_ARCHIVE_UPLOADED_COUNTER_NAME, Tags.of(
UserAgentTagUtil.getPlatformTag(userAgent),
io.micrometer.core.instrument.Tag.of(
HAS_REGISTRATION_ID_TAG_NAME,
String.valueOf(transferArchiveUploadedRequest.destinationDeviceRegistrationId().isPresent()))
)).increment();
@NotNull @Valid final TransferArchiveUploadedRequest transferArchiveUploadedRequest) {
return rateLimiters.getUploadTransferArchiveLimiter()
.validateAsync(authenticatedDevice.accountIdentifier())
.thenCompose(ignored -> accounts.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
@@ -554,7 +544,6 @@ public class DeviceController {
return accounts.recordTransferArchiveUpload(account,
transferArchiveUploadedRequest.destinationDeviceId(),
transferArchiveUploadedRequest.destinationDeviceCreated().map(Instant::ofEpochMilli),
transferArchiveUploadedRequest.destinationDeviceRegistrationId(),
transferArchiveUploadedRequest.transferArchive());
});
@@ -38,18 +38,18 @@ import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Clock;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import javax.annotation.Nullable;
import org.glassfish.jersey.server.ManagedAsync;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.groupsend.GroupSendDerivedKeyPair;
import org.signal.libsignal.zkgroup.groupsend.GroupSendFullToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.Anonymous;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.GroupSendTokenHeader;
@@ -82,7 +82,6 @@ import reactor.core.publisher.Mono;
@io.swagger.v3.oas.annotations.tags.Tag(name = "Keys")
public class KeysController {
private static final Logger log = LoggerFactory.getLogger(KeysController.class);
private final RateLimiters rateLimiters;
private final KeysManager keysManager;
private final AccountsManager accounts;
@@ -319,6 +318,7 @@ public class KeysController {
}
@GET
@ManagedAsync
@Path("/{identifier}/{device_id}")
@Produces(MediaType.APPLICATION_JSON)
@Operation(summary = "Fetch public keys for another user",
@@ -385,7 +385,8 @@ public class KeysController {
devicePreKeys.ecPreKey().orElse(null),
devicePreKeys.kemSignedPreKey())))
.collectList()
.block();
.blockOptional()
.orElseGet(Collections::emptyList);
final IdentityKey identityKey = target.getIdentityKey(targetIdentifier.identityType());
@@ -21,7 +21,6 @@ import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import jakarta.ws.rs.BadRequestException;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.DefaultValue;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.HeaderParam;
@@ -74,7 +73,6 @@ import org.whispersystems.textsecuregcm.entities.AccountStaleDevices;
import org.whispersystems.textsecuregcm.entities.IncomingMessage;
import org.whispersystems.textsecuregcm.entities.IncomingMessageList;
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope.Type;
import org.whispersystems.textsecuregcm.entities.MismatchedDevicesResponse;
import org.whispersystems.textsecuregcm.entities.OutgoingMessageEntity;
import org.whispersystems.textsecuregcm.entities.OutgoingMessageEntityList;
@@ -97,7 +95,6 @@ import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
import org.whispersystems.textsecuregcm.push.MessageUtil;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
import org.whispersystems.textsecuregcm.push.ReceiptSender;
import org.whispersystems.textsecuregcm.spam.MessageType;
import org.whispersystems.textsecuregcm.spam.SpamCheckResult;
import org.whispersystems.textsecuregcm.spam.SpamChecker;
@@ -123,7 +120,6 @@ public class MessageController {
private final RateLimiters rateLimiters;
private final CardinalityEstimator messageByteLimitEstimator;
private final MessageSender messageSender;
private final ReceiptSender receiptSender;
private final AccountsManager accountsManager;
private final MessagesManager messagesManager;
private final PhoneNumberIdentifiers phoneNumberIdentifiers;
@@ -163,6 +159,9 @@ public class MessageController {
private static final String INCORRECT_SYNC_MESSAGE_REGISTRATION_IDS_COUNTER_NAME =
MetricsUtil.name(MessageController.class, "incorrectSyncMessageRegistrationIds");
private static final String LEGACY_COMBINED_UAK_COUNTER_NAME =
MetricsUtil.name(MessageController.class, "legacyCombinedUak");
// The Signal desktop client (really, JavaScript in general) can handle message timestamps at most 100,000,000 days
// past the epoch; please see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date
// for additional details.
@@ -177,7 +176,6 @@ public class MessageController {
RateLimiters rateLimiters,
CardinalityEstimator messageByteLimitEstimator,
MessageSender messageSender,
ReceiptSender receiptSender,
AccountsManager accountsManager,
MessagesManager messagesManager,
PhoneNumberIdentifiers phoneNumberIdentifiers,
@@ -194,7 +192,6 @@ public class MessageController {
this.rateLimiters = rateLimiters;
this.messageByteLimitEstimator = messageByteLimitEstimator;
this.messageSender = messageSender;
this.receiptSender = receiptSender;
this.accountsManager = accountsManager;
this.messagesManager = messagesManager;
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
@@ -590,6 +587,8 @@ public class MessageController {
// Group send endorsements are checked before we even attempt to resolve any accounts, since
// the lists of service IDs in the envelope are all that we need to check against
checkGroupSendToken(multiRecipientMessage.getRecipients().keySet(), groupSendTokenHeader);
} else {
Metrics.counter(LEGACY_COMBINED_UAK_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(context))).increment();
}
// At this point, the caller has at least superficially provided the information needed to send a multi-recipient
@@ -843,37 +842,6 @@ public class MessageController {
return size;
}
@DELETE
@Path("/uuid/{uuid}")
public CompletableFuture<Response> removePendingMessage(@Auth AuthenticatedDevice auth, @PathParam("uuid") UUID uuid) {
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
final Device device = account.getDevice(auth.deviceId())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
return messagesManager.delete(auth.accountIdentifier(), device, uuid, null)
.thenAccept(maybeRemovedMessage -> maybeRemovedMessage.ifPresent(removedMessage -> {
if (removedMessage.sourceServiceId().isPresent()
&& removedMessage.envelopeType() != Type.SERVER_DELIVERY_RECEIPT) {
if (removedMessage.sourceServiceId().get() instanceof AciServiceIdentifier aciServiceIdentifier) {
try {
receiptSender.sendReceipt(removedMessage.destinationServiceId(), auth.deviceId(),
aciServiceIdentifier, removedMessage.clientTimestamp());
} catch (Exception e) {
logger.warn("Failed to send delivery receipt", e);
}
} else {
// If source service ID is present and the envelope type is not a server delivery receipt, then
// the source service ID *should always* be an ACI -- PNIs are receive-only, so they can only be the
// "source" via server delivery receipts
logger.warn("Source service ID unexpectedly a PNI service ID");
}
}
}))
.thenApply(Util.ASYNC_EMPTY_RESPONSE);
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("/report/{source}/{messageGuid}")
@@ -4,28 +4,15 @@
*/
package org.whispersystems.textsecuregcm.controllers;
import io.grpc.Metadata;
import io.grpc.Status;
import java.time.Duration;
import java.util.Optional;
import javax.annotation.Nullable;
import io.grpc.StatusRuntimeException;
import org.whispersystems.textsecuregcm.grpc.ConvertibleToGrpcStatus;
import org.whispersystems.textsecuregcm.grpc.GrpcExceptions;
public class RateLimitExceededException extends Exception implements ConvertibleToGrpcStatus {
public static final Metadata.Key<Duration> RETRY_AFTER_DURATION_KEY =
Metadata.Key.of("retry-after", new Metadata.AsciiMarshaller<>() {
@Override
public String toAsciiString(final Duration value) {
return value.toString();
}
@Override
public Duration parseAsciiString(final String serialized) {
return Duration.parse(serialized);
}
});
@Nullable
private final Duration retryDuration;
@@ -44,17 +31,7 @@ public class RateLimitExceededException extends Exception implements Convertible
}
@Override
public Status grpcStatus() {
return Status.RESOURCE_EXHAUSTED;
}
@Override
public Optional<Metadata> grpcMetadata() {
return getRetryDuration()
.map(duration -> {
final Metadata metadata = new Metadata();
metadata.put(RETRY_AFTER_DURATION_KEY, duration);
return metadata;
});
public StatusRuntimeException toStatusRuntimeException() {
return GrpcExceptions.rateLimitExceeded(retryDuration);
}
}
@@ -92,7 +92,8 @@ public class RegistrationController {
2. gets 409 from device available for transfer \n
3. success \n
""")
@ApiResponse(responseCode = "200", description = "The phone number associated with the authenticated account was changed successfully", useReturnTypeSchema = true)
@ApiResponse(responseCode = "200", description = "Account creation succeeded", useReturnTypeSchema = true)
@ApiResponse(responseCode = "401", description = "The session identified in the request is not verified")
@ApiResponse(responseCode = "403", description = "Verification failed for the provided Registration Recovery Password")
@ApiResponse(responseCode = "409", description = "The caller has not explicitly elected to skip transferring data from another device, but a device transfer is technically possible")
@ApiResponse(responseCode = "422", description = "The request did not pass validation")
@@ -1,107 +0,0 @@
/*
* Copyright 2013 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.controllers;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.auth.Auth;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Clock;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.entities.UserRemoteConfig;
import org.whispersystems.textsecuregcm.entities.UserRemoteConfigList;
import org.whispersystems.textsecuregcm.storage.RemoteConfigsManager;
import org.whispersystems.textsecuregcm.util.Conversions;
import org.whispersystems.textsecuregcm.util.Util;
@Path("/v1/config")
@Tag(name = "Remote Config")
public class RemoteConfigControllerV1 {
private final RemoteConfigsManager remoteConfigsManager;
private final Map<String, String> globalConfig;
private final Clock clock;
private static final String GLOBAL_CONFIG_PREFIX = "global.";
public RemoteConfigControllerV1(RemoteConfigsManager remoteConfigsManager,
Map<String, String> globalConfig,
final Clock clock) {
this.remoteConfigsManager = remoteConfigsManager;
this.globalConfig = globalConfig;
this.clock = clock;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Deprecated
@Operation(
summary = "Fetch remote configuration (deprecated)",
description = """
Remote configuration is a list of namespaced keys that clients may use for consistent configuration or behavior.
Configuration values change over time, and the list should be refreshed periodically, typically at client
launch and every few hours thereafter.
This endpoint is deprecated; use GET /v2/config instead
"""
)
@ApiResponse(responseCode = "200", description = "Remote configuration values for the authenticated user", useReturnTypeSchema = true)
public UserRemoteConfigList getAll(@Auth AuthenticatedDevice auth) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
final Stream<UserRemoteConfig> globalConfigStream = globalConfig.entrySet().stream()
.map(entry -> new UserRemoteConfig(GLOBAL_CONFIG_PREFIX + entry.getKey(), true, entry.getValue()));
return new UserRemoteConfigList(Stream.concat(remoteConfigsManager.getAll().stream().map(config -> {
final byte[] hashKey = config.getHashKey() != null ? config.getHashKey().getBytes(StandardCharsets.UTF_8)
: config.getName().getBytes(StandardCharsets.UTF_8);
boolean inBucket = isInBucket(digest, auth.accountIdentifier(), hashKey, config.getPercentage(),
config.getUuids());
return new UserRemoteConfig(config.getName(), inBucket,
inBucket ? config.getValue() : config.getDefaultValue());
}), globalConfigStream).collect(Collectors.toList()), clock.instant());
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
@VisibleForTesting
public static boolean isInBucket(MessageDigest digest, UUID uid, byte[] hashKey, int configPercentage,
Set<UUID> uuidsInBucket) {
if (uuidsInBucket.contains(uid)) {
return true;
}
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(uid.getMostSignificantBits());
bb.putLong(uid.getLeastSignificantBits());
digest.update(bb.array());
byte[] hash = digest.digest(hashKey);
int bucket = (int) (Util.ensureNonNegativeLong(Conversions.byteArrayToLong(hash)) % 100);
return bucket < configPercentage;
}
}
@@ -7,22 +7,29 @@ package org.whispersystems.textsecuregcm.controllers;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.HeaderParam;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
@@ -33,15 +40,20 @@ import org.whispersystems.textsecuregcm.entities.AuthCheckRequest;
import org.whispersystems.textsecuregcm.entities.AuthCheckResponseV2;
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
@Path("/v2/{name: backup|svr}")
@Tag(name = "Secure Value Recovery")
@io.swagger.v3.oas.annotations.tags.Tag(name = "Secure Value Recovery")
@Schema(description = "Note: /v2/backup is deprecated. Use /v2/svr instead.")
public class SecureValueRecovery2Controller {
private static final String CREDENTIAL_AGE_DISTRIBUTION_NAME =
MetricsUtil.name(SecureValueRecovery2Controller.class, "credentialAge");
private static final long MAX_AGE_SECONDS = TimeUnit.DAYS.toSeconds(30);
public static final Duration MAX_AGE = Duration.ofDays(30);
public static ExternalServiceCredentialsGenerator credentialsGenerator(final SecureValueRecoveryConfiguration cfg) {
return credentialsGenerator(cfg, Clock.systemUTC());
@@ -101,11 +113,13 @@ public class SecureValueRecovery2Controller {
@ApiResponse(responseCode = "200", description = "`JSON` with the check results.", useReturnTypeSchema = true)
@ApiResponse(responseCode = "422", description = "Provided list of SVR2 credentials could not be parsed")
@ApiResponse(responseCode = "400", description = "`POST` request body is not a valid `JSON`")
public AuthCheckResponseV2 authCheck(@NotNull @Valid final AuthCheckRequest request) {
public AuthCheckResponseV2 authCheck(
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@NotNull @Valid final AuthCheckRequest request) {
final List<ExternalServiceCredentialsSelector.CredentialInfo> credentials = ExternalServiceCredentialsSelector.check(
request.tokens(),
backupServiceCredentialGenerator,
MAX_AGE_SECONDS);
MAX_AGE.getSeconds());
// the username associated with the provided number
final Optional<String> matchingUsername = accountsManager
@@ -114,6 +128,22 @@ public class SecureValueRecovery2Controller {
.map(backupServiceCredentialGenerator::generateForUuid)
.map(ExternalServiceCredentials::username);
// Instrument how expired or not the best credential is
credentials.stream()
.filter(info -> switch (info.status()) {
case VALID, EXPIRED -> true;
default -> false;
})
// Look only at credentials that match the current account for the e164
.filter(info -> matchingUsername.filter(info.credentials().username()::equals).isPresent())
// Instrument the matching credential with the most recent timestamp
.max(Comparator.comparing(ExternalServiceCredentialsSelector.CredentialInfo::timestamp))
.ifPresent(info -> DistributionSummary.builder(CREDENTIAL_AGE_DISTRIBUTION_NAME)
.baseUnit("days")
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent), Tag.of("valid", Boolean.toString(info.valid()))))
.register(Metrics.globalRegistry)
.record(Duration.between(Instant.ofEpochSecond(info.timestamp()), Instant.now()).toDays()));
return new AuthCheckResponseV2(credentials.stream().collect(Collectors.toMap(
ExternalServiceCredentialsSelector.CredentialInfo::token,
info -> {
@@ -59,7 +59,6 @@ import javax.annotation.Nullable;
import org.glassfish.jersey.server.ManagedAsync;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.backup.BackupManager;
import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationCurrencyConfiguration;
@@ -74,7 +73,6 @@ import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.PaymentTime;
import org.whispersystems.textsecuregcm.storage.SubscriberCredentials;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionException;
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
import org.whispersystems.textsecuregcm.storage.Subscriptions;
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
@@ -88,6 +86,7 @@ import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidLevelException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiresActionException;
@@ -733,9 +732,9 @@ public class SubscriptionController {
Clients MUST validate that the generated receipt credential's level and expiration matches their expectations.
""")
@ApiResponse(responseCode = "200", description = "Successfully created receipt", useReturnTypeSchema = true)
@ApiResponse(responseCode = "204", description = "No invoice has been issued for this subscription OR invoice is in 'open' state")
@ApiResponse(responseCode = "204", description = "No invoice has been issued for this subscription OR invoice is in 'draft' or 'open' state")
@ApiResponse(responseCode = "400", description = "Bad ReceiptCredentialRequest")
@ApiResponse(responseCode = "402", description = "Invoice is in any state other than 'open' or 'paid'. May include chargeFailure details in body.",
@ApiResponse(responseCode = "402", description = "Invoice is in any state other than 'draft', 'open', or 'paid'. May include chargeFailure details in body.",
content = @Content(schema = @Schema(
nullable = true,
example = """
@@ -50,6 +50,7 @@ import java.security.MessageDigest;
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.Collections;
@@ -60,7 +61,7 @@ import java.util.Optional;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletionException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Strings;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -76,6 +77,7 @@ import org.whispersystems.textsecuregcm.entities.VerificationSessionResponse;
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExceptionMapper;
import org.whispersystems.textsecuregcm.metrics.DevicePlatformUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.PushNotification;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
@@ -89,15 +91,20 @@ import org.whispersystems.textsecuregcm.registration.TransportNotAllowedExceptio
import org.whispersystems.textsecuregcm.registration.VerificationSession;
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker.VerificationCheck;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
import org.whispersystems.textsecuregcm.telephony.CarrierData;
import org.whispersystems.textsecuregcm.telephony.CarrierDataException;
import org.whispersystems.textsecuregcm.telephony.CarrierDataProvider;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.ObsoletePhoneNumberFormatException;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.Util;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
@Path("/v1/verification")
@io.swagger.v3.oas.annotations.tags.Tag(name = "Verification")
@@ -120,6 +127,10 @@ public class VerificationController {
private static final String VERIFICATION_TRANSPORT_TAG_NAME = "transport";
private static final String VERIFIED_COUNTER_NAME = name(VerificationController.class, "verified");
private static final String SUCCESS_TAG_NAME = "success";
private static final String RECOVERY_PASSWORD_REMOVED_TAG_NAME = "recoveryPasswordRemoved";
private static final String REREGISTRATION_TAG_NAME = "reregistration";
private static final String EXISTING_ACCOUNT_PLATFORM = "existingAccountPlatform";
private static final String EXISTING_ACCOUNT_RECENTLY_SEEN_TAG_NAME = "existingAccountRecentlySeen";
private final RegistrationServiceClient registrationServiceClient;
private final VerificationSessionManager verificationSessionManager;
@@ -129,6 +140,7 @@ public class VerificationController {
private final PhoneNumberIdentifiers phoneNumberIdentifiers;
private final RateLimiters rateLimiters;
private final AccountsManager accountsManager;
private final CarrierDataProvider carrierDataProvider;
private final RegistrationFraudChecker registrationFraudChecker;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private final Clock clock;
@@ -141,6 +153,7 @@ public class VerificationController {
final PhoneNumberIdentifiers phoneNumberIdentifiers,
final RateLimiters rateLimiters,
final AccountsManager accountsManager,
final CarrierDataProvider carrierDataProvider,
final RegistrationFraudChecker registrationFraudChecker,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final Clock clock) {
@@ -152,6 +165,7 @@ public class VerificationController {
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
this.rateLimiters = rateLimiters;
this.accountsManager = accountsManager;
this.carrierDataProvider = carrierDataProvider;
this.registrationFraudChecker = registrationFraudChecker;
this.dynamicConfigurationManager = dynamicConfigurationManager;
this.clock = clock;
@@ -164,7 +178,7 @@ public class VerificationController {
@Operation(
summary = "Creates a new verification session for a specific phone number",
description = """
Initiates a session to be able to verify the phone number for account registration. Check the response and
Initiates a session to be able to verify the phone number for account registration. Check the response and
submit requested information at PATCH /session/{sessionId}
""")
@ApiResponse(responseCode = "200", description = "The verification session was created successfully", useReturnTypeSchema = true)
@@ -187,12 +201,29 @@ public class VerificationController {
throw new ServerErrorException("could not parse already validated number", Response.Status.INTERNAL_SERVER_ERROR);
}
Optional<CarrierData> maybeCarrierData;
if (dynamicConfigurationManager.getConfiguration().getCarrierDataLookupConfiguration().enabled()) {
try {
maybeCarrierData = carrierDataProvider.lookupCarrierData(phoneNumber,
dynamicConfigurationManager.getConfiguration().getCarrierDataLookupConfiguration().maxCacheAge());
} catch (final IOException | CarrierDataException e) {
logger.warn("Failed to retrieve carrier data", e);
maybeCarrierData = Optional.empty();
}
} else {
maybeCarrierData = Optional.empty();
}
final RegistrationServiceSession registrationServiceSession;
try {
final String sourceHost = (String) requestContext.getProperty(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
registrationServiceSession = registrationServiceClient.createRegistrationSession(phoneNumber, sourceHost,
registrationServiceSession = registrationServiceClient.createRegistrationSession(phoneNumber,
sourceHost,
accountsManager.getByE164(request.number()).isPresent(),
maybeCarrierData.flatMap(CarrierData::mcc).orElse(null),
maybeCarrierData.flatMap(CarrierData::mnc).orElse(null),
REGISTRATION_RPC_TIMEOUT).join();
} catch (final CancellationException e) {
@@ -206,16 +237,24 @@ public class VerificationController {
throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR, e);
}
VerificationSession verificationSession = new VerificationSession(null, new ArrayList<>(),
Collections.emptyList(), null, null, false,
clock.millis(), clock.millis(), registrationServiceSession.expiration());
VerificationSession verificationSession = new VerificationSession(registrationServiceSession.encodedSessionId(),
null,
maybeCarrierData.orElse(null),
new ArrayList<>(),
Collections.emptyList(),
null,
null,
false,
clock.millis(),
clock.millis(),
registrationServiceSession.expiration());
verificationSession = handlePushToken(pushTokenAndType, verificationSession);
// unconditionally request a captcha -- it will either be the only requested information, or a fallback
// if a push challenge sent in `handlePushToken` doesn't arrive in time
verificationSession.requestedInformation().add(VerificationSession.Information.CAPTCHA);
storeVerificationSession(registrationServiceSession, verificationSession);
storeVerificationSession(verificationSession);
return buildResponse(registrationServiceSession, verificationSession);
}
@@ -227,9 +266,9 @@ public class VerificationController {
@Operation(
summary = "Update a registration verification session",
description = """
Updates the session with requested information like an answer to a push challenge or captcha.
If `requestedInformation` in the response is empty, and `allowedToRequestCode` is `true`, proceed to call
`POST /session/{sessionId}/code`. If `requestedInformation` is empty and `allowedToRequestCode` is `false`,
Updates the session with requested information like an answer to a push challenge or captcha.
If `requestedInformation` in the response is empty, and `allowedToRequestCode` is `true`, proceed to call
`POST /session/{sessionId}/code`. If `requestedInformation` is empty and `allowedToRequestCode` is `false`,
then the caller must create a new verification session.
""")
@ApiResponse(responseCode = "200", description = "Session was updated successfully with the information provided", useReturnTypeSchema = true)
@@ -288,22 +327,20 @@ public class VerificationController {
} finally {
// Each of the handle* methods may update requestedInformation, submittedInformation, and allowedToRequestCode,
// and we want to be sure to store a changes, even if a later method throws
updateStoredVerificationSession(registrationServiceSession, verificationSession);
updateStoredVerificationSession(verificationSession);
}
return buildResponse(registrationServiceSession, verificationSession);
}
private void storeVerificationSession(final RegistrationServiceSession registrationServiceSession,
final VerificationSession verificationSession) {
verificationSessionManager.insert(registrationServiceSession.encodedSessionId(), verificationSession)
private void storeVerificationSession(final VerificationSession verificationSession) {
verificationSessionManager.insert(verificationSession)
.orTimeout(DYNAMODB_TIMEOUT.toSeconds(), TimeUnit.SECONDS)
.join();
}
private void updateStoredVerificationSession(final RegistrationServiceSession registrationServiceSession,
final VerificationSession verificationSession) {
verificationSessionManager.update(registrationServiceSession.encodedSessionId(), verificationSession)
private void updateStoredVerificationSession(final VerificationSession verificationSession) {
verificationSessionManager.update(verificationSession)
.orTimeout(DYNAMODB_TIMEOUT.toSeconds(), TimeUnit.SECONDS)
.join();
}
@@ -324,10 +361,17 @@ public class VerificationController {
requestedInformation.add(VerificationSession.Information.PUSH_CHALLENGE);
requestedInformation.addAll(verificationSession.requestedInformation());
verificationSession = new VerificationSession(generatePushChallenge(), requestedInformation,
verificationSession.submittedInformation(), verificationSession.smsSenderOverride(),
verificationSession.voiceSenderOverride(), verificationSession.allowedToRequestCode(),
verificationSession.createdTimestamp(), clock.millis(), verificationSession.remoteExpirationSeconds()
verificationSession = new VerificationSession(verificationSession.sessionId(),
generatePushChallenge(),
verificationSession.carrierData(),
requestedInformation,
verificationSession.submittedInformation(),
verificationSession.smsSenderOverride(),
verificationSession.voiceSenderOverride(),
verificationSession.allowedToRequestCode(),
verificationSession.createdTimestamp(),
clock.millis(),
verificationSession.remoteExpirationSeconds()
);
}
@@ -392,9 +436,16 @@ public class VerificationController {
|| requestedInformation.remove(VerificationSession.Information.PUSH_CHALLENGE))
&& requestedInformation.isEmpty();
verificationSession = new VerificationSession(verificationSession.pushChallenge(), requestedInformation,
submittedInformation, verificationSession.smsSenderOverride(), verificationSession.voiceSenderOverride(),
allowedToRequestCode, verificationSession.createdTimestamp(), clock.millis(),
verificationSession = new VerificationSession(verificationSession.sessionId(),
verificationSession.pushChallenge(),
verificationSession.carrierData(),
requestedInformation,
submittedInformation,
verificationSession.smsSenderOverride(),
verificationSession.voiceSenderOverride(),
allowedToRequestCode,
verificationSession.createdTimestamp(),
clock.millis(),
verificationSession.remoteExpirationSeconds());
} else if (pushChallengePresent) {
@@ -459,9 +510,16 @@ public class VerificationController {
|| requestedInformation.remove(VerificationSession.Information.CAPTCHA))
&& requestedInformation.isEmpty();
verificationSession = new VerificationSession(verificationSession.pushChallenge(), requestedInformation,
submittedInformation, verificationSession.smsSenderOverride(), verificationSession.voiceSenderOverride(),
allowedToRequestCode, verificationSession.createdTimestamp(), clock.millis(),
verificationSession = new VerificationSession(verificationSession.sessionId(),
verificationSession.pushChallenge(),
verificationSession.carrierData(),
requestedInformation,
submittedInformation,
verificationSession.smsSenderOverride(),
verificationSession.voiceSenderOverride(),
allowedToRequestCode,
verificationSession.createdTimestamp(),
clock.millis(),
verificationSession.remoteExpirationSeconds());
} else {
throw new ForbiddenException();
@@ -509,9 +567,9 @@ public class VerificationController {
content = @Content(schema = @Schema(implementation = VerificationSessionResponse.class)))
@ApiResponse(responseCode = "422", description = "Request did not pass validation")
@ApiResponse(responseCode = "429", description = """
Too may attempts; the caller is not permitted to send a verification code via the requested channel at this time
and may need to wait before trying again; if the session metadata does not specify a time at which the caller may
try again, then the caller has exhausted their permitted attempts and must either try a different transport or
Too may attempts; the caller is not permitted to send a verification code via the requested channel at this time
and may need to wait before trying again; if the session metadata does not specify a time at which the caller may
try again, then the caller has exhausted their permitted attempts and must either try a different transport or
create a new verification session.
""",
content = @Content(schema = @Schema(implementation = VerificationSessionResponse.class)),
@@ -521,10 +579,10 @@ public class VerificationController {
schema = @Schema(implementation = Integer.class)
))
@ApiResponse(responseCode = "440", description = """
The attempt to send a verification code failed because an external service (e.g. the SMS provider) refused to
deliver the code. This may be a temporary or permanent failure, as indicated in the response body. If temporary,
clients may try again after a reasonable delay. If permanent, clients should not retry the request and should
communicate the permanent failure to the end user. Permanent failures may result in the server disallowing all
The attempt to send a verification code failed because an external service (e.g. the SMS provider) refused to
deliver the code. This may be a temporary or permanent failure, as indicated in the response body. If temporary,
clients may try again after a reasonable delay. If permanent, clients should not retry the request and should
communicate the permanent failure to the end user. Permanent failures may result in the server disallowing all
future attempts to request or submit verification codes (since those attempts would be all but guaranteed to fail).
""",
content = @Content(schema = @Schema(implementation = RegistrationServiceSenderExceptionMapper.SendVerificationCodeFailureResponse.class)))
@@ -532,10 +590,21 @@ public class VerificationController {
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@Parameter(in = ParameterIn.HEADER, description = "Ordered list of languages in which the client prefers to receive SMS or voice verification messages") @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE)
final Optional<String> acceptLanguage,
@NotNull @Valid final VerificationCodeRequest verificationCodeRequest) throws Throwable {
@NotNull @Valid final VerificationCodeRequest verificationCodeRequest,
@Context final ContainerRequestContext requestContext) throws Throwable {
final RegistrationServiceSession registrationServiceSession = retrieveRegistrationServiceSession(encodedSessionId);
final VerificationSession verificationSession = retrieveVerificationSession(registrationServiceSession);
final VerificationSession verificationSession;
{
final VerificationSession storedVerificationSession = retrieveVerificationSession(registrationServiceSession);
verificationSession =
registrationFraudChecker.checkSendVerificationCodeAttempt(requestContext, storedVerificationSession,
registrationServiceSession.number())
.updatedSession()
.orElse(storedVerificationSession);
}
if (registrationServiceSession.verified()) {
throw new ClientErrorException(
@@ -561,7 +630,7 @@ public class VerificationController {
case "ios" -> ClientType.IOS;
case "android-2021-03" -> ClientType.ANDROID_WITH_FCM;
default -> {
if (StringUtils.startsWithIgnoreCase(verificationCodeRequest.client(), "android")) {
if (Strings.CI.startsWith(verificationCodeRequest.client(), "android")) {
yield ClientType.ANDROID_WITHOUT_FCM;
}
yield ClientType.UNKNOWN;
@@ -585,38 +654,41 @@ public class VerificationController {
throw new ServerErrorException("registration service unavailable", Response.Status.SERVICE_UNAVAILABLE);
} catch (final CompletionException e) {
final Throwable unwrappedException = ExceptionUtils.unwrap(e);
if (unwrappedException instanceof RateLimitExceededException rateLimitExceededException) {
if (rateLimitExceededException instanceof VerificationSessionRateLimitExceededException ve) {
final Response response = buildResponseForRateLimitExceeded(verificationSession, ve.getRegistrationSession(),
ve.getRetryDuration());
throw new ClientErrorException(response);
switch (unwrappedException) {
case RateLimitExceededException rateLimitExceededException -> {
if (rateLimitExceededException instanceof VerificationSessionRateLimitExceededException ve) {
final Response response = buildResponseForRateLimitExceeded(verificationSession,
ve.getRegistrationSession(),
ve.getRetryDuration());
throw new ClientErrorException(response);
}
throw new RateLimitExceededException(rateLimitExceededException.getRetryDuration().orElse(null));
}
case RegistrationServiceException registrationServiceException ->
throw registrationServiceException.getRegistrationSession()
.map(s -> buildResponse(s, verificationSession))
.map(verificationSessionResponse -> {
final Response response = registrationServiceException instanceof TransportNotAllowedException
? Response.status(418).entity(verificationSessionResponse).build()
: Response.status(Response.Status.CONFLICT).entity(verificationSessionResponse).build();
throw new RateLimitExceededException(rateLimitExceededException.getRetryDuration().orElse(null));
} else if (unwrappedException instanceof RegistrationServiceException registrationServiceException) {
throw registrationServiceException.getRegistrationSession()
.map(s -> buildResponse(s, verificationSession))
.map(verificationSessionResponse -> {
final Response response = registrationServiceException instanceof TransportNotAllowedException
? Response.status(418).entity(verificationSessionResponse).build()
: Response.status(Response.Status.CONFLICT).entity(verificationSessionResponse).build();
return new ClientErrorException(response);
})
.orElseGet(NotFoundException::new);
} else if (unwrappedException instanceof RegistrationFraudException) {
if (dynamicConfigurationManager.getConfiguration().getRegistrationConfiguration().squashDeclinedAttemptErrors()) {
return buildResponse(registrationServiceSession, verificationSession);
} else {
throw unwrappedException.getCause();
return new ClientErrorException(response);
})
.orElseGet(NotFoundException::new);
case RegistrationFraudException _ -> {
if (dynamicConfigurationManager.getConfiguration().getRegistrationConfiguration()
.squashDeclinedAttemptErrors()) {
return buildResponse(registrationServiceSession, verificationSession);
} else {
throw unwrappedException.getCause();
}
}
case RegistrationServiceSenderException _ -> throw unwrappedException;
case null, default -> {
logger.error("Registration service failure", unwrappedException);
throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR);
}
} else if (unwrappedException instanceof RegistrationServiceSenderException) {
throw unwrappedException;
} else {
logger.error("Registration service failure", unwrappedException);
throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR);
}
}
@@ -648,8 +720,8 @@ public class VerificationController {
@ApiResponse(responseCode = "409", description = "The session is already verified or no code has been requested yet for this session",
content = @Content(schema = @Schema(implementation = VerificationSessionResponse.class)))
@ApiResponse(responseCode = "429", description = """
Too many attempts; the caller is not permitted to submit a verification code at this time and may need to wait
before trying again; if the session metadata does not specify a time at which the caller may try again, then the
Too many attempts; the caller is not permitted to submit a verification code at this time and may need to wait
before trying again; if the session metadata does not specify a time at which the caller may try again, then the
caller has exhausted their permitted attempts and must create a new verification session.
""",
content = @Content(schema = @Schema(implementation = VerificationSessionResponse.class)),
@@ -708,16 +780,43 @@ public class VerificationController {
}
}
boolean existingRRP = false;
if (resultSession.verified()) {
registrationRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join());
existingRRP = registrationRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join()).join();
}
Metrics.counter(VERIFIED_COUNTER_NAME, Tags.of(
UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(COUNTRY_CODE_TAG_NAME, Util.getCountryCode(registrationServiceSession.number())),
Tag.of(REGION_CODE_TAG_NAME, Util.getRegion(registrationServiceSession.number())),
Tag.of(SUCCESS_TAG_NAME, Boolean.toString(resultSession.verified()))))
.increment();
Optional<Account> maybeExistingAccount;
try {
maybeExistingAccount = accountsManager.getByE164(registrationServiceSession.number());
} catch (RuntimeException e) {
// Only for metrics, so it's ok if we fail to lookup the account
maybeExistingAccount = Optional.empty();
}
Tags tags = Tags.of(
UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(COUNTRY_CODE_TAG_NAME, Util.getCountryCode(registrationServiceSession.number())),
Tag.of(REGION_CODE_TAG_NAME, Util.getRegion(registrationServiceSession.number())),
Tag.of(SUCCESS_TAG_NAME, Boolean.toString(resultSession.verified())),
Tag.of(RECOVERY_PASSWORD_REMOVED_TAG_NAME, Boolean.toString(existingRRP)),
Tag.of(REREGISTRATION_TAG_NAME, Boolean.toString(maybeExistingAccount.isPresent())));
if (maybeExistingAccount.isPresent()) {
final Account existingAccount = maybeExistingAccount.get();
final Duration timeSinceLastSeen =
Duration.between(Instant.ofEpochMilli(existingAccount.getLastSeen()), clock.instant());
// Clients may reuse recent SVR2 credentials to authenticate via recovery password instead of SMS verification.
// If this is a re-registering account, check if the client could possibly have an unexpired SVR2 credential.
final boolean recentlySeen = timeSinceLastSeen.compareTo(SecureValueRecovery2Controller.MAX_AGE) < 0;
final String existingPlatform = DevicePlatformUtil
.getDevicePlatform(existingAccount.getPrimaryDevice())
.map(ClientPlatform::name).orElse("unknown");
tags = tags
.and(EXISTING_ACCOUNT_PLATFORM, existingPlatform)
.and(EXISTING_ACCOUNT_RECENTLY_SEEN_TAG_NAME, Boolean.toString(recentlySeen));
}
Metrics.counter(VERIFIED_COUNTER_NAME, tags).increment();
return buildResponse(resultSession, verificationSession);
}
@@ -774,7 +873,7 @@ public class VerificationController {
}
/**
* @throws NotFoundException if the session is has no record
* @throws NotFoundException if the session has no record
*/
private VerificationSession retrieveVerificationSession(final RegistrationServiceSession registrationServiceSession) {
@@ -21,13 +21,6 @@ public record DeviceInfo(long id,
long lastSeen,
@Deprecated
@Schema(description = """
The time in milliseconds since epoch when the device was linked.
Deprecated in favor of `createdAtCiphertext`.
""", deprecated = true)
long created,
@Schema(description = "The registration ID of the given device.")
int registrationId,
@@ -40,7 +33,7 @@ public record DeviceInfo(long id,
byte[] createdAtCiphertext) {
public static DeviceInfo forDevice(final Device device) {
return new DeviceInfo(device.getId(), device.getName(), device.getLastSeen(), device.getCreated(), device.getRegistrationId(
return new DeviceInfo(device.getId(), device.getName(), device.getLastSeen(), device.getRegistrationId(
IdentityType.ACI), device.getCreatedAtCiphertext());
}
}
@@ -49,6 +49,9 @@ public record IncomingMessageList(@NotNull
@AssertTrue
@Schema(hidden = true)
public boolean isNotDuplicateRecipients() {
if (messages == null) {
return false;
}
final boolean valid = messages.stream()
.filter(Objects::nonNull)
.map(IncomingMessage::destinationDeviceId).distinct().count() == messages.size();
@@ -17,6 +17,7 @@ public record LinkDeviceRequest(@Schema(requiredMode = Schema.RequiredMode.REQUI
@NotBlank
String verificationCode,
@NotNull
@Valid
AccountAttributes accountAttributes,
@@ -44,7 +45,7 @@ public record LinkDeviceRequest(@Schema(requiredMode = Schema.RequiredMode.REQUI
@AssertTrue
@Schema(hidden = true)
public boolean isExactlyOneMessageDeliveryChannel() {
if (accountAttributes.getFetchesMessages()) {
if (accountAttributes != null && accountAttributes.getFetchesMessages()) {
return deviceActivationRequest().apnToken().isEmpty() && deviceActivationRequest().gcmToken().isEmpty();
} else {
return deviceActivationRequest().apnToken().isPresent() ^ deviceActivationRequest().gcmToken().isPresent();
@@ -22,15 +22,8 @@ public record TransferArchiveUploadedRequest(
@Schema(description = "The ID of the device for which the transfer archive has been prepared")
byte destinationDeviceId,
@Schema(description = """
The timestamp, in milliseconds since the epoch, at which the destination device was created.
Deprecated in favor of `destinationDeviceRegistrationId`.
""", deprecated = true)
@Deprecated
Optional<@Positive Long> destinationDeviceCreated,
@Schema(description = "The registration ID of the destination device")
Optional<@Min(0) @Max(Device.MAX_REGISTRATION_ID) Integer> destinationDeviceRegistrationId,
@Min(0) @Max(Device.MAX_REGISTRATION_ID) int destinationDeviceRegistrationId,
@NotNull
@Valid
@@ -39,9 +32,4 @@ public record TransferArchiveUploadedRequest(
the upload has failed and the destination device should stop waiting
""", oneOf = {RemoteAttachment.class, RemoteAttachmentError.class})
TransferArchiveResult transferArchive) {
@AssertTrue
@Schema(hidden = true)
public boolean isExactlyOneDisambiguatorProvided() {
return destinationDeviceCreated.isPresent() ^ destinationDeviceRegistrationId.isPresent();
}
}
@@ -27,8 +27,9 @@ import java.util.Set;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicRemoteDeprecationConfiguration;
import org.whispersystems.textsecuregcm.grpc.GrpcExceptions;
import org.whispersystems.textsecuregcm.grpc.RequestAttributesUtil;
import org.whispersystems.textsecuregcm.grpc.StatusConstants;
import org.whispersystems.textsecuregcm.grpc.ServerInterceptorUtil;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
@@ -91,8 +92,7 @@ public class RemoteDeprecationFilter implements Filter, ServerInterceptor {
}).orElse(null);
if (shouldBlock(userAgent)) {
call.close(StatusConstants.UPGRADE_NEEDED_STATUS, new Metadata());
return new ServerCall.Listener<>() {};
return ServerInterceptorUtil.closeWithStatusException(call, GrpcExceptions.upgradeRequired());
} else {
return next.startCall(call, headers);
}
@@ -6,7 +6,6 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import io.grpc.Status;
import org.signal.chat.account.CheckAccountExistenceRequest;
import org.signal.chat.account.CheckAccountExistenceResponse;
import org.signal.chat.account.LookupUsernameHashRequest;
@@ -14,6 +13,7 @@ import org.signal.chat.account.LookupUsernameHashResponse;
import org.signal.chat.account.LookupUsernameLinkRequest;
import org.signal.chat.account.LookupUsernameLinkResponse;
import org.signal.chat.account.ReactorAccountsAnonymousGrpc;
import org.signal.chat.errors.NotFound;
import org.whispersystems.textsecuregcm.controllers.AccountController;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
@@ -51,18 +51,18 @@ public class AccountsAnonymousGrpcService extends ReactorAccountsAnonymousGrpc.A
@Override
public Mono<LookupUsernameHashResponse> lookupUsernameHash(final LookupUsernameHashRequest request) {
if (request.getUsernameHash().size() != AccountController.USERNAME_HASH_LENGTH) {
throw Status.INVALID_ARGUMENT
.withDescription(String.format("Illegal username hash length; expected %d bytes, but got %d bytes",
AccountController.USERNAME_HASH_LENGTH, request.getUsernameHash().size()))
.asRuntimeException();
throw GrpcExceptions.fieldViolation("username_hash",
String.format("Illegal username hash length; expected %d bytes, but got %d bytes",
AccountController.USERNAME_HASH_LENGTH, request.getUsernameHash().size()));
}
return RateLimitUtil.rateLimitByRemoteAddress(rateLimiters.getUsernameLookupLimiter())
.then(Mono.fromFuture(() -> accountsManager.getByUsernameHash(request.getUsernameHash().toByteArray())))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.NOT_FOUND::asRuntimeException))
.map(account -> LookupUsernameHashResponse.newBuilder()
.setServiceIdentifier(ServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getUuid())))
.build());
.map(maybeAccount -> maybeAccount
.map(account -> LookupUsernameHashResponse.newBuilder()
.setServiceIdentifier(ServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getUuid())))
.build())
.orElseGet(() -> LookupUsernameHashResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build()));
}
@Override
@@ -72,19 +72,16 @@ public class AccountsAnonymousGrpcService extends ReactorAccountsAnonymousGrpc.A
try {
linkHandle = UUIDUtil.fromByteString(request.getUsernameLinkHandle());
} catch (final IllegalArgumentException e) {
throw Status.INVALID_ARGUMENT
.withDescription("Could not interpret link handle as UUID")
.withCause(e)
.asRuntimeException();
throw GrpcExceptions.fieldViolation("username_link_handle", "Could not interpret link handle as UUID");
}
return RateLimitUtil.rateLimitByRemoteAddress(rateLimiters.getUsernameLinkLookupLimiter())
.then(Mono.fromFuture(() -> accountsManager.getByUsernameLinkHandle(linkHandle)))
.map(maybeAccount -> maybeAccount
.flatMap(Account::getEncryptedUsername)
.orElseThrow(Status.NOT_FOUND::asRuntimeException))
.map(usernameCiphertext -> LookupUsernameLinkResponse.newBuilder()
.setUsernameCiphertext(ByteString.copyFrom(usernameCiphertext))
.build());
.map(usernameCiphertext -> LookupUsernameLinkResponse.newBuilder()
.setUsernameCiphertext(ByteString.copyFrom(usernameCiphertext))
.build())
.orElseGet(() -> LookupUsernameLinkResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build()));
}
}
@@ -6,7 +6,6 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import io.grpc.Status;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.List;
@@ -26,8 +25,6 @@ import org.signal.chat.account.DeleteUsernameLinkResponse;
import org.signal.chat.account.GetAccountIdentityRequest;
import org.signal.chat.account.GetAccountIdentityResponse;
import org.signal.chat.account.ReactorAccountsGrpc;
import org.signal.chat.account.ReserveUsernameHashError;
import org.signal.chat.account.ReserveUsernameHashErrorType;
import org.signal.chat.account.ReserveUsernameHashRequest;
import org.signal.chat.account.ReserveUsernameHashResponse;
import org.signal.chat.account.SetDiscoverableByPhoneNumberRequest;
@@ -38,7 +35,9 @@ import org.signal.chat.account.SetRegistrationRecoveryPasswordRequest;
import org.signal.chat.account.SetRegistrationRecoveryPasswordResponse;
import org.signal.chat.account.SetUsernameLinkRequest;
import org.signal.chat.account.SetUsernameLinkResponse;
import org.signal.chat.account.UsernameNotAvailable;
import org.signal.chat.common.AccountIdentifiers;
import org.signal.chat.errors.FailedPrecondition;
import org.signal.libsignal.usernames.BaseUsernameException;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
@@ -50,6 +49,7 @@ import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableException;
@@ -78,10 +78,7 @@ public class AccountsGrpcService extends ReactorAccountsGrpc.AccountsImplBase {
@Override
public Mono<GetAccountIdentityResponse> getAccountIdentity(final GetAccountIdentityRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
return getAccount()
.map(account -> {
final AccountIdentifiers.Builder accountIdentifiersBuilder = AccountIdentifiers.newBuilder()
.addServiceIdentifiers(ServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getUuid())))
@@ -99,10 +96,7 @@ public class AccountsGrpcService extends ReactorAccountsGrpc.AccountsImplBase {
@Override
public Mono<DeleteAccountResponse> deleteAccount(final DeleteAccountRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedPrimaryDevice();
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
return getAccount(AuthenticationUtil.requireAuthenticatedPrimaryDevice())
.flatMap(account -> Mono.fromFuture(() -> accountsManager.delete(account, AccountsManager.DeletionReason.USER_REQUEST)))
.thenReturn(DeleteAccountResponse.newBuilder().build());
}
@@ -112,11 +106,10 @@ public class AccountsGrpcService extends ReactorAccountsGrpc.AccountsImplBase {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedPrimaryDevice();
if (request.getRegistrationLock().isEmpty()) {
throw Status.INVALID_ARGUMENT.withDescription("Registration lock secret must not be empty").asRuntimeException();
throw GrpcExceptions.fieldViolation("registration_lock", "Registration lock secret must not be empty");
}
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
return getAccount(authenticatedDevice)
.flatMap(account -> {
// In the previous REST-based API, clients would send hex strings directly. For backward compatibility, we
// convert the registration lock secret to a lowercase hex string before turning it into a salted hash.
@@ -131,10 +124,7 @@ public class AccountsGrpcService extends ReactorAccountsGrpc.AccountsImplBase {
@Override
public Mono<ClearRegistrationLockResponse> clearRegistrationLock(final ClearRegistrationLockRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedPrimaryDevice();
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
return getAccount(AuthenticationUtil.requireAuthenticatedPrimaryDevice())
.flatMap(account -> Mono.fromFuture(() -> accountsManager.updateAsync(account,
a -> a.setRegistrationLock(null, null))))
.map(ignored -> ClearRegistrationLockResponse.newBuilder().build());
@@ -145,42 +135,34 @@ public class AccountsGrpcService extends ReactorAccountsGrpc.AccountsImplBase {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
if (request.getUsernameHashesCount() == 0) {
throw Status.INVALID_ARGUMENT
.withDescription("List of username hashes must not be empty")
.asRuntimeException();
throw GrpcExceptions.fieldViolation("username_hashes", "List of username hashes must not be empty");
}
if (request.getUsernameHashesCount() > AccountController.MAXIMUM_USERNAME_HASHES_LIST_LENGTH) {
throw Status.INVALID_ARGUMENT
.withDescription(String.format("List of username hashes may have at most %d elements, but actually had %d",
AccountController.MAXIMUM_USERNAME_HASHES_LIST_LENGTH, request.getUsernameHashesCount()))
.asRuntimeException();
throw GrpcExceptions.fieldViolation("username_hashes",
String.format("List of username hashes may have at most %d elements, but actually had %d",
AccountController.MAXIMUM_USERNAME_HASHES_LIST_LENGTH, request.getUsernameHashesCount()));
}
final List<byte[]> usernameHashes = new ArrayList<>(request.getUsernameHashesCount());
for (final ByteString usernameHash : request.getUsernameHashesList()) {
if (usernameHash.size() != AccountController.USERNAME_HASH_LENGTH) {
throw Status.INVALID_ARGUMENT
.withDescription(String.format("Username hash length must be %d bytes, but was actually %d",
AccountController.USERNAME_HASH_LENGTH, usernameHash.size()))
.asRuntimeException();
throw GrpcExceptions.fieldViolation("username_hashes",
String.format("Username hash length must be %d bytes, but was actually %d",
AccountController.USERNAME_HASH_LENGTH, usernameHash.size()));
}
usernameHashes.add(usernameHash.toByteArray());
}
return rateLimiters.getUsernameReserveLimiter().validateReactive(authenticatedDevice.accountIdentifier())
.then(Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier())))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
.then(getAccount())
.flatMap(account -> Mono.fromFuture(() -> accountsManager.reserveUsernameHash(account, usernameHashes)))
.map(reservation -> ReserveUsernameHashResponse.newBuilder()
.setUsernameHash(ByteString.copyFrom(reservation.reservedUsernameHash()))
.build())
.onErrorReturn(UsernameHashNotAvailableException.class, ReserveUsernameHashResponse.newBuilder()
.setError(ReserveUsernameHashError.newBuilder()
.setErrorType(ReserveUsernameHashErrorType.RESERVE_USERNAME_HASH_ERROR_TYPE_NO_HASHES_AVAILABLE)
.build())
.setUsernameNotAvailable(UsernameNotAvailable.getDefaultInstance())
.build());
}
@@ -189,61 +171,57 @@ public class AccountsGrpcService extends ReactorAccountsGrpc.AccountsImplBase {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
if (request.getUsernameHash().isEmpty()) {
throw Status.INVALID_ARGUMENT
.withDescription("Username hash must not be empty")
.asRuntimeException();
throw GrpcExceptions.fieldViolation("username_hash", "Username hash must not be empty");
}
if (request.getUsernameHash().size() != AccountController.USERNAME_HASH_LENGTH) {
throw Status.INVALID_ARGUMENT
.withDescription(String.format("Username hash length must be %d bytes, but was actually %d",
AccountController.USERNAME_HASH_LENGTH, request.getUsernameHash().size()))
.asRuntimeException();
throw GrpcExceptions.fieldViolation("username_hash",
String.format("Username hash length must be %d bytes, but was actually %d",
AccountController.USERNAME_HASH_LENGTH, request.getUsernameHash().size()));
}
if (request.getZkProof().isEmpty()) {
throw Status.INVALID_ARGUMENT
.withDescription("Zero-knowledge proof must not be empty")
.asRuntimeException();
throw GrpcExceptions.fieldViolation("zk_proof", "Zero-knowledge proof must not be empty");
}
if (request.getUsernameCiphertext().isEmpty()) {
throw Status.INVALID_ARGUMENT
.withDescription("Username ciphertext must not be empty")
.asRuntimeException();
throw GrpcExceptions.fieldViolation("username_ciphertext", "Username ciphertext must not be empty");
}
if (request.getUsernameCiphertext().size() > AccountController.MAXIMUM_USERNAME_CIPHERTEXT_LENGTH) {
throw Status.INVALID_ARGUMENT
.withDescription(String.format("Username hash length must at most %d bytes, but was actually %d",
AccountController.MAXIMUM_USERNAME_CIPHERTEXT_LENGTH, request.getUsernameCiphertext().size()))
.asRuntimeException();
throw GrpcExceptions.fieldViolation("username_ciphertext",
String.format("Username ciphertext length must at most %d bytes, but was actually %d",
AccountController.MAXIMUM_USERNAME_CIPHERTEXT_LENGTH, request.getUsernameCiphertext().size()));
}
try {
usernameHashZkProofVerifier.verifyProof(request.getZkProof().toByteArray(), request.getUsernameHash().toByteArray());
} catch (final BaseUsernameException e) {
throw Status.INVALID_ARGUMENT.withDescription("Could not verify proof").asRuntimeException();
throw GrpcExceptions.constraintViolation("Could not verify proof");
}
return rateLimiters.getUsernameSetLimiter().validateReactive(authenticatedDevice.accountIdentifier())
.then(Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier())))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
.then(getAccount())
.flatMap(account -> Mono.fromFuture(() -> accountsManager.confirmReservedUsernameHash(account, request.getUsernameHash().toByteArray(), request.getUsernameCiphertext().toByteArray())))
.map(updatedAccount -> ConfirmUsernameHashResponse.newBuilder()
.setUsernameHash(ByteString.copyFrom(updatedAccount.getUsernameHash().orElseThrow()))
.setUsernameLinkHandle(UUIDUtil.toByteString(updatedAccount.getUsernameLinkHandle()))
.setConfirmedUsernameHash(ConfirmUsernameHashResponse.ConfirmedUsernameHash.newBuilder()
.setUsernameHash(ByteString.copyFrom(updatedAccount.getUsernameHash().orElseThrow()))
.setUsernameLinkHandle(UUIDUtil.toByteString(updatedAccount.getUsernameLinkHandle()))
.build())
.build())
.onErrorMap(UsernameReservationNotFoundException.class, throwable -> Status.FAILED_PRECONDITION.asRuntimeException())
.onErrorMap(UsernameHashNotAvailableException.class, throwable -> Status.NOT_FOUND.asRuntimeException());
.onErrorResume(UsernameReservationNotFoundException.class, _ -> Mono.just(ConfirmUsernameHashResponse
.newBuilder()
.setReservationNotFound(FailedPrecondition.getDefaultInstance())
.build()))
.onErrorResume(UsernameHashNotAvailableException.class, _ -> Mono.just(ConfirmUsernameHashResponse
.newBuilder()
.setUsernameNotAvailable(UsernameNotAvailable.getDefaultInstance())
.build()));
}
@Override
public Mono<DeleteUsernameHashResponse> deleteUsernameHash(final DeleteUsernameHashRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
return getAccount()
.flatMap(account -> Mono.fromFuture(() -> accountsManager.clearUsernameHash(account)))
.thenReturn(DeleteUsernameHashResponse.newBuilder().build());
}
@@ -253,19 +231,16 @@ public class AccountsGrpcService extends ReactorAccountsGrpc.AccountsImplBase {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
if (request.getUsernameCiphertext().isEmpty() || request.getUsernameCiphertext().size() > EncryptedUsername.MAX_SIZE) {
throw Status.INVALID_ARGUMENT
.withDescription(String.format("Username ciphertext must not be empty and must be shorter than %d bytes", EncryptedUsername.MAX_SIZE))
.asRuntimeException();
throw GrpcExceptions.fieldViolation("username_ciphertext",
String.format("Username ciphertext must not be empty and must be shorter than %d bytes", EncryptedUsername.MAX_SIZE));
}
return rateLimiters.getUsernameLinkOperationLimiter().validateReactive(authenticatedDevice.accountIdentifier())
.then(Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier())))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
.then(getAccount())
.flatMap(account -> {
final SetUsernameLinkResponse.Builder responseBuilder = SetUsernameLinkResponse.newBuilder();
if (account.getUsernameHash().isEmpty()) {
return Mono.error(Status.FAILED_PRECONDITION
.withDescription("Account does not have a username hash")
.asRuntimeException());
return Mono.just(responseBuilder.setNoUsernameSet(FailedPrecondition.getDefaultInstance()).build());
}
final UUID linkHandle;
@@ -276,37 +251,28 @@ public class AccountsGrpcService extends ReactorAccountsGrpc.AccountsImplBase {
}
return Mono.fromFuture(() -> accountsManager.updateAsync(account, a -> a.setUsernameLinkDetails(linkHandle, request.getUsernameCiphertext().toByteArray())))
.thenReturn(linkHandle);
})
.map(linkHandle -> SetUsernameLinkResponse.newBuilder()
.setUsernameLinkHandle(UUIDUtil.toByteString(linkHandle))
.build());
.thenReturn(responseBuilder.setUsernameLinkHandle(UUIDUtil.toByteString(linkHandle)).build());
});
}
@Override
public Mono<DeleteUsernameLinkResponse> deleteUsernameLink(final DeleteUsernameLinkRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
return rateLimiters.getUsernameLinkOperationLimiter().validateReactive(authenticatedDevice.accountIdentifier())
.then(Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier())))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
.then(getAccount())
.flatMap(account -> Mono.fromFuture(() -> accountsManager.updateAsync(account, a -> a.setUsernameLinkDetails(null, null))))
.thenReturn(DeleteUsernameLinkResponse.newBuilder().build());
}
@Override
public Mono<ConfigureUnidentifiedAccessResponse> configureUnidentifiedAccess(final ConfigureUnidentifiedAccessRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
if (!request.getAllowUnrestrictedUnidentifiedAccess() && request.getUnidentifiedAccessKey().size() != UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH) {
throw Status.INVALID_ARGUMENT
.withDescription(String.format("Unidentified access key must be %d bytes, but was actually %d",
UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH, request.getUnidentifiedAccessKey().size()))
.asRuntimeException();
throw GrpcExceptions.fieldViolation("unidentified_access_key",
String.format("Unidentified access key must be %d bytes, but was actually %d",
UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH, request.getUnidentifiedAccessKey().size()));
}
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
return getAccount()
.flatMap(account -> Mono.fromFuture(() -> accountsManager.updateAsync(account, a -> {
a.setUnrestrictedUnidentifiedAccess(request.getAllowUnrestrictedUnidentifiedAccess());
a.setUnidentifiedAccessKey(request.getAllowUnrestrictedUnidentifiedAccess() ? null : request.getUnidentifiedAccessKey().toByteArray());
@@ -316,10 +282,7 @@ public class AccountsGrpcService extends ReactorAccountsGrpc.AccountsImplBase {
@Override
public Mono<SetDiscoverableByPhoneNumberResponse> setDiscoverableByPhoneNumber(final SetDiscoverableByPhoneNumberRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
return getAccount()
.flatMap(account -> Mono.fromFuture(() -> accountsManager.updateAsync(account,
a -> a.setDiscoverableByPhoneNumber(request.getDiscoverableByPhoneNumber()))))
.thenReturn(SetDiscoverableByPhoneNumberResponse.newBuilder().build());
@@ -327,17 +290,22 @@ public class AccountsGrpcService extends ReactorAccountsGrpc.AccountsImplBase {
@Override
public Mono<SetRegistrationRecoveryPasswordResponse> setRegistrationRecoveryPassword(final SetRegistrationRecoveryPasswordRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
if (request.getRegistrationRecoveryPassword().isEmpty()) {
throw Status.INVALID_ARGUMENT
.withDescription("Registration recovery password must not be empty")
.asRuntimeException();
throw GrpcExceptions.fieldViolation("registration_recovery_password", "Registration recovery password must not be empty");
}
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
return getAccount()
.flatMap(account -> Mono.fromFuture(() -> registrationRecoveryPasswordsManager.store(account.getIdentifier(IdentityType.PNI), request.getRegistrationRecoveryPassword().toByteArray())))
.thenReturn(SetRegistrationRecoveryPasswordResponse.newBuilder().build());
}
private Mono<Account> getAccount() {
return getAccount(AuthenticationUtil.requireAuthenticatedDevice());
}
private Mono<Account> getAccount(AuthenticatedDevice authenticatedDevice) {
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials")));
}
}
@@ -5,16 +5,13 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import io.grpc.Status;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import java.util.concurrent.Flow;
import org.signal.chat.backup.CopyMediaRequest;
import org.signal.chat.backup.CopyMediaResponse;
import org.signal.chat.backup.DeleteAllRequest;
import org.signal.chat.backup.DeleteAllResponse;
import org.signal.chat.backup.DeleteMediaItem;
import org.signal.chat.backup.DeleteMediaRequest;
import org.signal.chat.backup.DeleteMediaResponse;
import org.signal.chat.backup.GetBackupInfoRequest;
@@ -27,29 +24,37 @@ import org.signal.chat.backup.GetUploadFormRequest;
import org.signal.chat.backup.GetUploadFormResponse;
import org.signal.chat.backup.ListMediaRequest;
import org.signal.chat.backup.ListMediaResponse;
import org.signal.chat.backup.ReactorBackupsAnonymousGrpc;
import org.signal.chat.backup.RefreshRequest;
import org.signal.chat.backup.RefreshResponse;
import org.signal.chat.backup.SetPublicKeyRequest;
import org.signal.chat.backup.SetPublicKeyResponse;
import org.signal.chat.backup.SignedPresentation;
import org.signal.chat.backup.SimpleBackupsAnonymousGrpc;
import org.signal.chat.errors.FailedPrecondition;
import org.signal.chat.errors.FailedZkAuthentication;
import org.signal.libsignal.protocol.InvalidKeyException;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialPresentation;
import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
import org.whispersystems.textsecuregcm.backup.BackupFailedZkAuthenticationException;
import org.whispersystems.textsecuregcm.backup.BackupInvalidArgumentException;
import org.whispersystems.textsecuregcm.backup.BackupManager;
import org.whispersystems.textsecuregcm.backup.BackupNotFoundException;
import org.whispersystems.textsecuregcm.backup.BackupPermissionException;
import org.whispersystems.textsecuregcm.backup.BackupUploadDescriptor;
import org.whispersystems.textsecuregcm.backup.BackupWrongCredentialTypeException;
import org.whispersystems.textsecuregcm.backup.CopyParameters;
import org.whispersystems.textsecuregcm.backup.MediaEncryptionParameters;
import org.whispersystems.textsecuregcm.controllers.ArchiveController;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.metrics.BackupMetrics;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import reactor.adapter.JdkFlowAdapter;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
public class BackupsAnonymousGrpcService extends ReactorBackupsAnonymousGrpc.BackupsAnonymousImplBase {
public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.BackupsAnonymousImplBase {
private final BackupManager backupManager;
private final BackupMetrics backupMetrics;
@@ -60,94 +65,148 @@ public class BackupsAnonymousGrpcService extends ReactorBackupsAnonymousGrpc.Bac
}
@Override
public Mono<GetCdnCredentialsResponse> getCdnCredentials(final GetCdnCredentialsRequest request) {
return authenticateBackupUserMono(request.getSignedPresentation())
.map(user -> backupManager.generateReadAuth(user, request.getCdn()))
.map(credentials -> GetCdnCredentialsResponse.newBuilder().putAllHeaders(credentials).build());
public GetCdnCredentialsResponse getCdnCredentials(final GetCdnCredentialsRequest request)
throws BackupInvalidArgumentException, BackupPermissionException {
try {
final AuthenticatedBackupUser backupUser = authenticateBackupUser(request.getSignedPresentation());
return GetCdnCredentialsResponse.newBuilder()
.setCdnCredentials(GetCdnCredentialsResponse.CdnCredentials.newBuilder()
.putAllHeaders(backupManager.generateReadAuth(backupUser, request.getCdn())))
.build();
} catch (BackupFailedZkAuthenticationException e) {
return GetCdnCredentialsResponse.newBuilder()
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()).build())
.build();
}
}
@Override
public Mono<GetSvrBCredentialsResponse> getSvrBCredentials(final GetSvrBCredentialsRequest request) {
return authenticateBackupUserMono(request.getSignedPresentation())
.map(backupManager::generateSvrbAuth)
.map(credentials -> GetSvrBCredentialsResponse.newBuilder()
.setUsername(credentials.username())
.setPassword(credentials.password())
.build());
public GetSvrBCredentialsResponse getSvrBCredentials(final GetSvrBCredentialsRequest request)
throws BackupWrongCredentialTypeException, BackupPermissionException {
try {
final AuthenticatedBackupUser backupUser = authenticateBackupUser(request.getSignedPresentation());
final ExternalServiceCredentials credentials = backupManager.generateSvrbAuth(backupUser);
return GetSvrBCredentialsResponse.newBuilder()
.setSvrbCredentials(GetSvrBCredentialsResponse.SvrBCredentials.newBuilder()
.setUsername(credentials.username())
.setPassword(credentials.password()))
.build();
} catch (BackupFailedZkAuthenticationException e) {
return GetSvrBCredentialsResponse.newBuilder()
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()).build())
.build();
}
}
@Override
public Mono<GetBackupInfoResponse> getBackupInfo(final GetBackupInfoRequest request) {
return Mono.fromFuture(() ->
authenticateBackupUser(request.getSignedPresentation()).thenCompose(backupManager::backupInfo))
.map(info -> GetBackupInfoResponse.newBuilder()
.setBackupName(info.messageBackupKey())
.setCdn(info.cdn())
.setBackupDir(info.backupSubdir())
.setMediaDir(info.mediaSubdir())
.setUsedSpace(info.mediaUsedSpace().orElse(0L))
.build());
public GetBackupInfoResponse getBackupInfo(final GetBackupInfoRequest request)
throws BackupNotFoundException, BackupPermissionException {
try {
final AuthenticatedBackupUser backupUser = authenticateBackupUser(request.getSignedPresentation());
final BackupManager.BackupInfo info = backupManager.backupInfo(backupUser);
return GetBackupInfoResponse.newBuilder().setBackupInfo(GetBackupInfoResponse.BackupInfo.newBuilder()
.setBackupName(info.messageBackupKey())
.setCdn(info.cdn())
.setBackupDir(info.backupSubdir())
.setMediaDir(info.mediaSubdir())
.setUsedSpace(info.mediaUsedSpace().orElse(0L)))
.build();
} catch (BackupFailedZkAuthenticationException e) {
return GetBackupInfoResponse.newBuilder()
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()).build())
.build();
}
}
@Override
public Mono<RefreshResponse> refresh(final RefreshRequest request) {
return Mono.fromFuture(() -> authenticateBackupUser(request.getSignedPresentation())
.thenCompose(backupManager::ttlRefresh))
.thenReturn(RefreshResponse.getDefaultInstance());
public RefreshResponse refresh(final RefreshRequest request) throws BackupPermissionException {
try {
final AuthenticatedBackupUser backupUser = authenticateBackupUser(request.getSignedPresentation());
backupManager.ttlRefresh(backupUser);
return RefreshResponse.getDefaultInstance();
} catch (BackupFailedZkAuthenticationException e) {
return RefreshResponse.newBuilder()
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()).build())
.build();
}
}
@Override
public Mono<SetPublicKeyResponse> setPublicKey(final SetPublicKeyRequest request) {
public SetPublicKeyResponse setPublicKey(final SetPublicKeyRequest request)
throws BackupFailedZkAuthenticationException {
final ECPublicKey publicKey = deserialize(ECPublicKey::new, request.getPublicKey().toByteArray());
final BackupAuthCredentialPresentation presentation = deserialize(
BackupAuthCredentialPresentation::new,
request.getSignedPresentation().getPresentation().toByteArray());
final byte[] signature = request.getSignedPresentation().getPresentationSignature().toByteArray();
return Mono.fromFuture(() -> backupManager.setPublicKey(presentation, signature, publicKey))
.thenReturn(SetPublicKeyResponse.getDefaultInstance());
backupManager.setPublicKey(presentation, signature, publicKey);
return SetPublicKeyResponse.getDefaultInstance();
}
@Override
public Mono<GetUploadFormResponse> getUploadForm(final GetUploadFormRequest request) {
return authenticateBackupUserMono(request.getSignedPresentation())
.flatMap(backupUser -> switch (request.getUploadTypeCase()) {
case MESSAGES -> {
final long uploadLength = request.getMessages().getUploadLength();
final boolean oversize = uploadLength > BackupManager.MAX_MESSAGE_BACKUP_OBJECT_SIZE;
backupMetrics.updateMessageBackupSizeDistribution(backupUser, oversize, Optional.of(uploadLength));
if (oversize) {
yield Mono.error(Status.FAILED_PRECONDITION
.withDescription("Exceeds max upload length")
.asRuntimeException());
}
yield Mono.fromFuture(backupManager.createMessageBackupUploadDescriptor(backupUser));
}
case MEDIA -> Mono.fromCompletionStage(backupManager.createTemporaryAttachmentUploadDescriptor(backupUser));
case UPLOADTYPE_NOT_SET -> Mono.error(Status.INVALID_ARGUMENT
.withDescription("Must set upload_type")
.asRuntimeException());
})
.map(uploadDescriptor -> GetUploadFormResponse.newBuilder()
public GetUploadFormResponse getUploadForm(final GetUploadFormRequest request)
throws RateLimitExceededException, BackupWrongCredentialTypeException, BackupPermissionException {
final AuthenticatedBackupUser backupUser;
try {
backupUser = authenticateBackupUser(request.getSignedPresentation());
} catch (BackupFailedZkAuthenticationException e) {
return GetUploadFormResponse.newBuilder()
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()).build())
.build();
}
final GetUploadFormResponse.Builder builder = GetUploadFormResponse.newBuilder();
switch (request.getUploadTypeCase()) {
case MESSAGES -> {
final long uploadLength = request.getMessages().getUploadLength();
final boolean oversize = uploadLength > BackupManager.MAX_MESSAGE_BACKUP_OBJECT_SIZE;
backupMetrics.updateMessageBackupSizeDistribution(backupUser, oversize, Optional.of(uploadLength));
if (oversize) {
builder.setExceedsMaxUploadLength(FailedPrecondition.getDefaultInstance());
} else {
final BackupUploadDescriptor uploadDescriptor = backupManager.createMessageBackupUploadDescriptor(backupUser);
builder.setUploadForm(builder.getUploadFormBuilder()
.setCdn(uploadDescriptor.cdn())
.setKey(uploadDescriptor.key())
.setSignedUploadLocation(uploadDescriptor.signedUploadLocation())
.putAllHeaders(uploadDescriptor.headers())).build();
}
}
case MEDIA -> {
final BackupUploadDescriptor uploadDescriptor = backupManager.createTemporaryAttachmentUploadDescriptor(
backupUser);
builder.setUploadForm(builder.getUploadFormBuilder()
.setCdn(uploadDescriptor.cdn())
.setKey(uploadDescriptor.key())
.setSignedUploadLocation(uploadDescriptor.signedUploadLocation())
.putAllHeaders(uploadDescriptor.headers())
.build());
.putAllHeaders(uploadDescriptor.headers())).build();
}
case UPLOADTYPE_NOT_SET -> throw GrpcExceptions.fieldViolation("upload_type", "Must set upload_type");
}
return builder.build();
}
@Override
public Flux<CopyMediaResponse> copyMedia(final CopyMediaRequest request) {
return authenticateBackupUserMono(request.getSignedPresentation())
.flatMapMany(backupUser -> backupManager.copyToBackup(backupUser,
request.getItemsList().stream().map(item -> new CopyParameters(
item.getSourceAttachmentCdn(), item.getSourceKey(),
// uint32 in proto, make sure it fits in a signed int
fromUnsignedExact(item.getObjectLength()),
new MediaEncryptionParameters(item.getEncryptionKey().toByteArray(), item.getHmacKey().toByteArray()),
item.getMediaId().toByteArray())).toList()))
public Flow.Publisher<CopyMediaResponse> copyMedia(final CopyMediaRequest request)
throws BackupWrongCredentialTypeException, BackupPermissionException, BackupInvalidArgumentException {
final BackupManager.CopyQuota copyQuota;
try {
final AuthenticatedBackupUser backupUser = authenticateBackupUser(request.getSignedPresentation());
copyQuota = backupManager.getCopyQuota(backupUser,
request.getItemsList().stream().map(item -> new CopyParameters(
item.getSourceAttachmentCdn(), item.getSourceKey(),
// uint32 in proto, make sure it fits in a signed int
fromUnsignedExact(item.getObjectLength()),
new MediaEncryptionParameters(item.getEncryptionKey().toByteArray(), item.getHmacKey().toByteArray()),
item.getMediaId().toByteArray())).toList());
} catch (BackupFailedZkAuthenticationException e) {
return JdkFlowAdapter.publisherToFlowPublisher(Mono.just(CopyMediaResponse
.newBuilder()
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()))
.build()));
}
return JdkFlowAdapter.publisherToFlowPublisher(backupManager.copyToBackup(copyQuota)
.doOnNext(result -> backupMetrics.updateCopyCounter(
result,
UserAgentTagUtil.getPlatformTag(RequestAttributesUtil.getUserAgent().orElse(null))))
@@ -166,65 +225,89 @@ public class BackupsAnonymousGrpcService extends ReactorBackupsAnonymousGrpc.Bac
.setSourceNotFound(CopyMediaResponse.SourceNotFound.getDefaultInstance());
};
return builder.build();
});
}));
}
@Override
public Mono<ListMediaResponse> listMedia(final ListMediaRequest request) {
return authenticateBackupUserMono(request.getSignedPresentation()).zipWhen(
backupUser -> Mono.fromFuture(backupManager.list(
backupUser,
request.hasCursor() ? Optional.of(request.getCursor()) : Optional.empty(),
request.getLimit()).toCompletableFuture()),
(backupUser, listResult) -> {
final ListMediaResponse.Builder builder = ListMediaResponse.newBuilder();
for (BackupManager.StorageDescriptorWithLength sd : listResult.media()) {
builder.addPage(ListMediaResponse.ListEntry.newBuilder()
.setMediaId(ByteString.copyFrom(sd.key()))
.setCdn(sd.cdn())
.setLength(sd.length())
.build());
}
builder
.setBackupDir(backupUser.backupDir())
.setMediaDir(backupUser.mediaDir());
listResult.cursor().ifPresent(builder::setCursor);
return builder.build();
});
public ListMediaResponse listMedia(final ListMediaRequest request) throws BackupPermissionException {
try {
final AuthenticatedBackupUser backupUser = authenticateBackupUser(request.getSignedPresentation());
final BackupManager.ListMediaResult listResult = backupManager.list(
backupUser,
request.hasCursor() ? Optional.of(request.getCursor()) : Optional.empty(),
request.getLimit());
final ListMediaResponse.ListResult.Builder builder = ListMediaResponse.ListResult.newBuilder();
for (BackupManager.StorageDescriptorWithLength sd : listResult.media()) {
builder.addPage(ListMediaResponse.ListEntry.newBuilder()
.setMediaId(ByteString.copyFrom(sd.key()))
.setCdn(sd.cdn())
.setLength(sd.length())
.build());
}
builder
.setBackupDir(backupUser.backupDir())
.setMediaDir(backupUser.mediaDir());
listResult.cursor().ifPresent(builder::setCursor);
return ListMediaResponse.newBuilder().setListResult(builder).build();
} catch (BackupFailedZkAuthenticationException e) {
return ListMediaResponse.newBuilder()
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()))
.build();
}
}
@Override
public Mono<DeleteAllResponse> deleteAll(final DeleteAllRequest request) {
return Mono.fromFuture(() -> authenticateBackupUser(request.getSignedPresentation())
.thenCompose(backupManager::deleteEntireBackup))
.thenReturn(DeleteAllResponse.getDefaultInstance());
public DeleteAllResponse deleteAll(final DeleteAllRequest request) throws BackupPermissionException {
try {
final AuthenticatedBackupUser backupUser = authenticateBackupUser(request.getSignedPresentation());
backupManager.deleteEntireBackup(backupUser);
return DeleteAllResponse.getDefaultInstance();
} catch (BackupFailedZkAuthenticationException e) {
return DeleteAllResponse.newBuilder()
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()))
.build();
}
}
@Override
public Flux<DeleteMediaResponse> deleteMedia(final DeleteMediaRequest request) {
return Mono
.fromFuture(() -> authenticateBackupUser(request.getSignedPresentation()))
.flatMapMany(backupUser -> backupManager.deleteMedia(backupUser, request
.getItemsList()
.stream()
.map(item -> new BackupManager.StorageDescriptor(item.getCdn(), item.getMediaId().toByteArray()))
.toList()))
public Flow.Publisher<DeleteMediaResponse> deleteMedia(final DeleteMediaRequest request)
throws BackupWrongCredentialTypeException, BackupPermissionException {
final Flux<BackupManager.StorageDescriptor> deleteItems;
try {
final AuthenticatedBackupUser backupUser = authenticateBackupUser(request.getSignedPresentation());
deleteItems = backupManager.deleteMedia(backupUser, request
.getItemsList()
.stream()
.map(item -> new BackupManager.StorageDescriptor(item.getCdn(), item.getMediaId().toByteArray()))
.toList());
} catch (BackupFailedZkAuthenticationException e) {
return JdkFlowAdapter.publisherToFlowPublisher(Mono.just(DeleteMediaResponse
.newBuilder()
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()))
.build()));
}
return JdkFlowAdapter.publisherToFlowPublisher(deleteItems
.map(storageDescriptor -> DeleteMediaResponse.newBuilder()
.setMediaId(ByteString.copyFrom(storageDescriptor.key()))
.setCdn(storageDescriptor.cdn()).build());
.setDeletedItem(DeleteMediaItem.newBuilder()
.setMediaId(ByteString.copyFrom(storageDescriptor.key()))
.setCdn(storageDescriptor.cdn()))
.build()));
}
private Mono<AuthenticatedBackupUser> authenticateBackupUserMono(final SignedPresentation signedPresentation) {
return Mono.fromFuture(() -> authenticateBackupUser(signedPresentation));
@Override
public Throwable mapException(final Throwable throwable) {
return switch (throwable) {
case BackupInvalidArgumentException e -> GrpcExceptions.invalidArguments(e.getMessage());
case BackupPermissionException e -> GrpcExceptions.badAuthentication(e.getMessage());
case BackupWrongCredentialTypeException e -> GrpcExceptions.badAuthentication(e.getMessage());
default -> throwable;
};
}
private CompletableFuture<AuthenticatedBackupUser> authenticateBackupUser(
final SignedPresentation signedPresentation) {
private AuthenticatedBackupUser authenticateBackupUser(final SignedPresentation signedPresentation)
throws BackupFailedZkAuthenticationException {
if (signedPresentation == null) {
throw Status.UNAUTHENTICATED.asRuntimeException();
throw GrpcExceptions.badAuthentication("Missing required signedPresentation");
}
try {
return backupManager.authenticateBackupUser(
@@ -232,7 +315,7 @@ public class BackupsAnonymousGrpcService extends ReactorBackupsAnonymousGrpc.Bac
signedPresentation.getPresentationSignature().toByteArray(),
RequestAttributesUtil.getUserAgent().orElse(null));
} catch (InvalidInputException e) {
throw Status.UNAUTHENTICATED.withDescription("Could not deserialize presentation").asRuntimeException();
throw GrpcExceptions.badAuthentication("Could not deserialize presentation");
}
}
@@ -242,7 +325,7 @@ public class BackupsAnonymousGrpcService extends ReactorBackupsAnonymousGrpc.Bac
*/
private static int fromUnsignedExact(final int i) {
if (i < 0) {
throw Status.INVALID_ARGUMENT.withDescription("Invalid size").asRuntimeException();
throw GrpcExceptions.invalidArguments("integer length too large");
}
return i;
}
@@ -256,7 +339,7 @@ public class BackupsAnonymousGrpcService extends ReactorBackupsAnonymousGrpc.Bac
try {
return deserializer.deserialize(bytes);
} catch (InvalidInputException | InvalidKeyException e) {
throw Status.INVALID_ARGUMENT.withDescription("Invalid serialization").asRuntimeException();
throw GrpcExceptions.invalidArguments("invalid serialization");
}
}
@@ -5,6 +5,7 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import com.google.protobuf.Empty;
import io.grpc.Status;
import io.micrometer.core.instrument.Tag;
import java.time.Clock;
@@ -14,12 +15,13 @@ import java.util.Optional;
import java.util.stream.Collectors;
import org.signal.chat.backup.GetBackupAuthCredentialsRequest;
import org.signal.chat.backup.GetBackupAuthCredentialsResponse;
import org.signal.chat.backup.ReactorBackupsGrpc;
import org.signal.chat.backup.RedeemReceiptRequest;
import org.signal.chat.backup.RedeemReceiptResponse;
import org.signal.chat.backup.SetBackupIdRequest;
import org.signal.chat.backup.SetBackupIdResponse;
import org.signal.chat.backup.SimpleBackupsGrpc;
import org.signal.chat.common.ZkCredential;
import org.signal.chat.errors.FailedPrecondition;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialRequest;
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
@@ -28,14 +30,20 @@ import org.whispersystems.textsecuregcm.auth.RedemptionRange;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
import org.whispersystems.textsecuregcm.backup.BackupBadReceiptException;
import org.whispersystems.textsecuregcm.backup.BackupInvalidArgumentException;
import org.whispersystems.textsecuregcm.backup.BackupMissingIdCommitmentException;
import org.whispersystems.textsecuregcm.backup.BackupNotFoundException;
import org.whispersystems.textsecuregcm.backup.BackupPermissionException;
import org.whispersystems.textsecuregcm.backup.BackupWrongCredentialTypeException;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.metrics.BackupMetrics;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import reactor.core.publisher.Mono;
public class BackupsGrpcService extends ReactorBackupsGrpc.BackupsImplBase {
public class BackupsGrpcService extends SimpleBackupsGrpc.BackupsImplBase {
private final AccountsManager accountManager;
private final BackupAuthManager backupAuthManager;
@@ -48,7 +56,8 @@ public class BackupsGrpcService extends ReactorBackupsGrpc.BackupsImplBase {
}
@Override
public Mono<SetBackupIdResponse> setBackupId(SetBackupIdRequest request) {
public SetBackupIdResponse setBackupId(SetBackupIdRequest request)
throws RateLimitExceededException, BackupInvalidArgumentException, BackupPermissionException {
final Optional<BackupAuthCredentialRequest> messagesCredentialRequest = deserializeWithEmptyPresenceCheck(
BackupAuthCredentialRequest::new,
@@ -59,28 +68,33 @@ public class BackupsGrpcService extends ReactorBackupsGrpc.BackupsImplBase {
request.getMediaBackupAuthCredentialRequest());
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
return authenticatedAccount()
.flatMap(account -> {
final Device device = account
.getDevice(authenticatedDevice.deviceId())
.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException);
return Mono.fromFuture(
backupAuthManager.commitBackupId(account, device, messagesCredentialRequest, mediaCredentialRequest));
})
.thenReturn(SetBackupIdResponse.getDefaultInstance());
final Account account = authenticatedAccount();
final Device device = account
.getDevice(authenticatedDevice.deviceId())
.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException);
backupAuthManager.commitBackupId(account, device, messagesCredentialRequest, mediaCredentialRequest);
return SetBackupIdResponse.getDefaultInstance();
}
public Mono<RedeemReceiptResponse> redeemReceipt(RedeemReceiptRequest request) {
public RedeemReceiptResponse redeemReceipt(RedeemReceiptRequest request) throws BackupInvalidArgumentException {
final ReceiptCredentialPresentation receiptCredentialPresentation = deserialize(
ReceiptCredentialPresentation::new,
request.getPresentation().toByteArray());
return authenticatedAccount()
.flatMap(account -> Mono.fromFuture(backupAuthManager.redeemReceipt(account, receiptCredentialPresentation)))
.thenReturn(RedeemReceiptResponse.getDefaultInstance());
final Account account = authenticatedAccount();
final RedeemReceiptResponse.Builder builder = RedeemReceiptResponse.newBuilder();
try {
backupAuthManager.redeemReceipt(account, receiptCredentialPresentation);
builder.setSuccess(Empty.getDefaultInstance());
} catch (BackupBadReceiptException e) {
builder.setInvalidReceipt(FailedPrecondition.newBuilder().setDescription(e.getMessage()).build());
} catch (BackupMissingIdCommitmentException e) {
builder.setAccountMissingCommitment(FailedPrecondition.newBuilder().build());
}
return builder.build();
}
@Override
public Mono<GetBackupAuthCredentialsResponse> getBackupAuthCredentials(GetBackupAuthCredentialsRequest request) {
public GetBackupAuthCredentialsResponse getBackupAuthCredentials(GetBackupAuthCredentialsRequest request) {
final Tag platformTag = UserAgentTagUtil.getPlatformTag(RequestAttributesUtil.getUserAgent().orElse(null));
final RedemptionRange redemptionRange;
try {
@@ -90,46 +104,58 @@ public class BackupsGrpcService extends ReactorBackupsGrpc.BackupsImplBase {
} catch (IllegalArgumentException e) {
throw Status.INVALID_ARGUMENT.withDescription(e.getMessage()).asRuntimeException();
}
return authenticatedAccount().flatMap(account -> {
final Mono<List<BackupAuthManager.Credential>> messageCredentials = Mono.fromCompletionStage(() ->
final Account account = authenticatedAccount();
try {
final List<BackupAuthManager.Credential> messageCredentials =
backupAuthManager.getBackupAuthCredentials(
account,
BackupCredentialType.MESSAGES,
redemptionRange))
.doOnSuccess(credentials ->
backupMetrics.updateGetCredentialCounter(platformTag, BackupCredentialType.MESSAGES, credentials.size()));
redemptionRange);
backupMetrics.updateGetCredentialCounter(platformTag, BackupCredentialType.MESSAGES, messageCredentials.size());
final Mono<List<BackupAuthManager.Credential>> mediaCredentials = Mono.fromCompletionStage(() ->
final List<BackupAuthManager.Credential> mediaCredentials =
backupAuthManager.getBackupAuthCredentials(
account,
BackupCredentialType.MEDIA,
redemptionRange))
.doOnSuccess(credentials ->
backupMetrics.updateGetCredentialCounter(platformTag, BackupCredentialType.MEDIA, credentials.size()));
redemptionRange);
backupMetrics.updateGetCredentialCounter(platformTag, BackupCredentialType.MEDIA, mediaCredentials.size());
return messageCredentials.zipWith(mediaCredentials, (messageCreds, mediaCreds) ->
GetBackupAuthCredentialsResponse.newBuilder()
.putAllMessageCredentials(messageCreds.stream().collect(Collectors.toMap(
return GetBackupAuthCredentialsResponse.newBuilder()
.setCredentials(GetBackupAuthCredentialsResponse.Credentials.newBuilder()
.putAllMessageCredentials(messageCredentials.stream().collect(Collectors.toMap(
c -> c.redemptionTime().getEpochSecond(),
c -> ZkCredential.newBuilder()
.setCredential(ByteString.copyFrom(c.credential().serialize()))
.setRedemptionTime(c.redemptionTime().getEpochSecond())
.build())))
.putAllMediaCredentials(mediaCreds.stream().collect(Collectors.toMap(
.putAllMediaCredentials(mediaCredentials.stream().collect(Collectors.toMap(
c -> c.redemptionTime().getEpochSecond(),
c -> ZkCredential.newBuilder()
.setCredential(ByteString.copyFrom(c.credential().serialize()))
.setRedemptionTime(c.redemptionTime().getEpochSecond())
.build())))
.build());
});
.build())
.build();
} catch (BackupNotFoundException _) {
// Return an empty response to indicate that the authenticated account had no associated blinded backup-id
return GetBackupAuthCredentialsResponse.getDefaultInstance();
}
}
private Mono<Account> authenticatedAccount() {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
return Mono
.fromFuture(() -> accountManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException));
@Override
public Throwable mapException(final Throwable throwable) {
return switch (throwable) {
case BackupInvalidArgumentException e -> GrpcExceptions.invalidArguments(e.getMessage());
case BackupPermissionException e -> GrpcExceptions.badAuthentication(e.getMessage());
case BackupWrongCredentialTypeException e -> GrpcExceptions.badAuthentication(e.getMessage());
default -> throwable;
};
}
private Account authenticatedAccount() {
return accountManager
.getByAccountIdentifier(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier())
.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException);
}
private interface Deserializer<T> {
@@ -5,11 +5,14 @@
package org.whispersystems.textsecuregcm.grpc;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import org.signal.chat.calling.quality.SimpleCallQualityGrpc;
import org.signal.chat.calling.quality.SubmitCallQualitySurveyRequest;
import org.signal.chat.calling.quality.SubmitCallQualitySurveyResponse;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.CallQualityInvalidArgumentsException;
import org.whispersystems.textsecuregcm.metrics.CallQualitySurveyManager;
public class CallQualitySurveyGrpcService extends SimpleCallQualityGrpc.CallQualityImplBase {
@@ -32,9 +35,15 @@ public class CallQualitySurveyGrpcService extends SimpleCallQualityGrpc.CallQual
rateLimiters.getSubmitCallQualitySurveyLimiter().validate(remoteAddress);
callQualitySurveyManager.submitCallQualitySurvey(request,
remoteAddress,
RequestAttributesUtil.getUserAgent().orElse(null));
try {
callQualitySurveyManager.submitCallQualitySurvey(request,
remoteAddress,
RequestAttributesUtil.getUserAgent().orElse(null));
} catch (final CallQualityInvalidArgumentsException e) {
throw e.getField()
.map(fieldName -> GrpcExceptions.fieldViolation(fieldName, e.getMessage()))
.orElseGet(() -> GrpcExceptions.invalidArguments(e.getMessage()));
}
return SubmitCallQualitySurveyResponse.getDefaultInstance();
}
@@ -7,14 +7,12 @@ package org.whispersystems.textsecuregcm.grpc;
import io.grpc.Metadata;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import java.util.Optional;
/**
* Interface to be implemented by our custom exceptions that are consistently mapped to a gRPC status.
*/
public interface ConvertibleToGrpcStatus {
Status grpcStatus();
Optional<Metadata> grpcMetadata();
StatusRuntimeException toStatusRuntimeException();
}
@@ -11,6 +11,12 @@ import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import java.io.IOException;
import java.io.UncheckedIOException;
/**
* This interceptor observes responses from the service and if the response status is {@link Status#UNKNOWN}
@@ -21,6 +27,8 @@ import io.grpc.Status;
*/
public class ErrorMappingInterceptor implements ServerInterceptor {
private static final Logger log = LoggerFactory.getLogger(ErrorMappingInterceptor.class);
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
final ServerCall<ReqT, RespT> call,
@@ -34,15 +42,35 @@ public class ErrorMappingInterceptor implements ServerInterceptor {
// I.e. if at this point we see anything but the `UNKNOWN`,
// that means that some logic in the service made this decision already
// and automatic conversion may conflict with it.
if (status.getCode().equals(Status.Code.UNKNOWN)
&& status.getCause() instanceof ConvertibleToGrpcStatus convertibleToGrpcStatus) {
super.close(
convertibleToGrpcStatus.grpcStatus(),
convertibleToGrpcStatus.grpcMetadata().orElseGet(Metadata::new)
);
} else {
if (!status.getCode().equals(Status.Code.UNKNOWN)) {
super.close(status, trailers);
return;
}
final Throwable cause = ExceptionUtils.unwrap(status.getCause());
final StatusRuntimeException statusException = switch (cause) {
case ConvertibleToGrpcStatus e -> e.toStatusRuntimeException();
case UncheckedIOException e -> {
log.warn("RPC {} encountered UncheckedIOException", call.getMethodDescriptor().getFullMethodName(), e.getCause());
yield GrpcExceptions.unavailable(e.getCause().getMessage());
}
case IOException e -> {
log.warn("RPC {} encountered IOException", call.getMethodDescriptor().getFullMethodName(), e);
yield GrpcExceptions.unavailable(e.getMessage());
}
case null -> {
log.error("RPC {} finished with status UNKNOWN: {}",
call.getMethodDescriptor().getFullMethodName(), status.getDescription());
yield GrpcExceptions.unavailable(status.getDescription());
}
default -> {
log.error("RPC {} finished with status UNKNOWN",
call.getMethodDescriptor().getFullMethodName(), status.getCause());
yield GrpcExceptions.unavailable(status.getCause().getMessage());
}
};
super.close(statusException.getStatus(), statusException.getTrailers());
}
}, headers);
}
@@ -15,19 +15,16 @@ import java.util.concurrent.TimeUnit;
import org.signal.chat.credentials.AuthCheckResult;
import org.signal.chat.credentials.CheckSvrCredentialsRequest;
import org.signal.chat.credentials.CheckSvrCredentialsResponse;
import org.signal.chat.credentials.ReactorExternalServiceCredentialsAnonymousGrpc;
import org.signal.chat.credentials.SimpleExternalServiceCredentialsAnonymousGrpc;
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsSelector;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuples;
public class ExternalServiceCredentialsAnonymousGrpcService extends
ReactorExternalServiceCredentialsAnonymousGrpc.ExternalServiceCredentialsAnonymousImplBase {
SimpleExternalServiceCredentialsAnonymousGrpc.ExternalServiceCredentialsAnonymousImplBase {
private static final long MAX_SVR_PASSWORD_AGE_SECONDS = TimeUnit.DAYS.toSeconds(30);
@@ -54,36 +51,34 @@ public class ExternalServiceCredentialsAnonymousGrpcService extends
}
@Override
public Mono<CheckSvrCredentialsResponse> checkSvrCredentials(final CheckSvrCredentialsRequest request) {
public CheckSvrCredentialsResponse checkSvrCredentials(final CheckSvrCredentialsRequest request) {
final List<String> tokens = request.getPasswordsList();
if (tokens.size() > 10) {
throw GrpcExceptions.fieldViolation("passwordsList", "At most 10 passwords may be provided");
}
final List<ExternalServiceCredentialsSelector.CredentialInfo> credentials = ExternalServiceCredentialsSelector.check(
tokens,
svrCredentialsGenerator,
MAX_SVR_PASSWORD_AGE_SECONDS);
return Mono.fromFuture(() -> accountsManager.getByE164Async(request.getNumber()))
// the username associated with the provided number
.map(maybeAccount -> maybeAccount.map(Account::getUuid)
.map(svrCredentialsGenerator::generateForUuid)
.map(ExternalServiceCredentials::username))
.flatMapMany(maybeMatchingUsername -> Flux.fromIterable(credentials)
.map(credential -> Tuples.of(maybeMatchingUsername, credential)))
.reduce(CheckSvrCredentialsResponse.newBuilder(), ((builder, usernameAndCredentialInfo) -> {
final Optional<String> matchingUsername = usernameAndCredentialInfo.getT1();
final ExternalServiceCredentialsSelector.CredentialInfo credentialInfo = usernameAndCredentialInfo.getT2();
final AuthCheckResult authCheckResult;
if (!credentialInfo.valid()) {
authCheckResult = AuthCheckResult.AUTH_CHECK_RESULT_INVALID;
} else {
final String username = credentialInfo.credentials().username();
// does this credential match the account id for the e164 provided in the request?
authCheckResult = matchingUsername.map(username::equals).orElse(false)
? AuthCheckResult.AUTH_CHECK_RESULT_MATCH
: AuthCheckResult.AUTH_CHECK_RESULT_NO_MATCH;
}
return builder.putMatches(credentialInfo.token(), authCheckResult);
}))
.map(CheckSvrCredentialsResponse.Builder::build);
// the username associated with the provided number
final Optional<String> maybeUsername = accountsManager.getByE164(request.getNumber())
.map(Account::getUuid)
.map(svrCredentialsGenerator::generateForUuid)
.map(ExternalServiceCredentials::username);
final CheckSvrCredentialsResponse.Builder builder = CheckSvrCredentialsResponse.newBuilder();
for (ExternalServiceCredentialsSelector.CredentialInfo credentialInfo : credentials) {
final AuthCheckResult authCheckResult;
if (!credentialInfo.valid()) {
authCheckResult = AuthCheckResult.AUTH_CHECK_RESULT_INVALID;
} else {
final String username = credentialInfo.credentials().username();
// does this credential match the account id for the e164 provided in the request?
authCheckResult = maybeUsername.map(username::equals).orElse(false)
? AuthCheckResult.AUTH_CHECK_RESULT_MATCH
: AuthCheckResult.AUTH_CHECK_RESULT_NO_MATCH;
}
builder.putMatches(credentialInfo.token(), authCheckResult);
}
return builder.build();
}
}
@@ -8,22 +8,21 @@ package org.whispersystems.textsecuregcm.grpc;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.VisibleForTesting;
import io.grpc.Status;
import java.time.Clock;
import java.util.Map;
import org.signal.chat.credentials.ExternalServiceType;
import org.signal.chat.credentials.GetExternalServiceCredentialsRequest;
import org.signal.chat.credentials.GetExternalServiceCredentialsResponse;
import org.signal.chat.credentials.ReactorExternalServiceCredentialsGrpc;
import org.signal.chat.credentials.SimpleExternalServiceCredentialsGrpc;
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import reactor.core.publisher.Mono;
public class ExternalServiceCredentialsGrpcService extends ReactorExternalServiceCredentialsGrpc.ExternalServiceCredentialsImplBase {
public class ExternalServiceCredentialsGrpcService extends SimpleExternalServiceCredentialsGrpc.ExternalServiceCredentialsImplBase {
private final Map<ExternalServiceType, ExternalServiceCredentialsGenerator> credentialsGeneratorByType;
@@ -48,21 +47,20 @@ public class ExternalServiceCredentialsGrpcService extends ReactorExternalServic
}
@Override
public Mono<GetExternalServiceCredentialsResponse> getExternalServiceCredentials(final GetExternalServiceCredentialsRequest request) {
public GetExternalServiceCredentialsResponse getExternalServiceCredentials(final GetExternalServiceCredentialsRequest request)
throws RateLimitExceededException {
final ExternalServiceCredentialsGenerator credentialsGenerator = this.credentialsGeneratorByType
.get(request.getExternalService());
if (credentialsGenerator == null) {
return Mono.error(Status.INVALID_ARGUMENT.asException());
throw GrpcExceptions.fieldViolation("externalService", "Invalid external service type");
}
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
return rateLimiters.forDescriptor(RateLimiters.For.EXTERNAL_SERVICE_CREDENTIALS).validateReactive(authenticatedDevice.accountIdentifier())
.then(Mono.fromSupplier(() -> {
final ExternalServiceCredentials externalServiceCredentials = credentialsGenerator
.generateForUuid(authenticatedDevice.accountIdentifier());
return GetExternalServiceCredentialsResponse.newBuilder()
.setUsername(externalServiceCredentials.username())
.setPassword(externalServiceCredentials.password())
.build();
}));
rateLimiters.forDescriptor(RateLimiters.For.EXTERNAL_SERVICE_CREDENTIALS).validate(authenticatedDevice.accountIdentifier());
final ExternalServiceCredentials externalServiceCredentials = credentialsGenerator
.generateForUuid(authenticatedDevice.accountIdentifier());
return GetExternalServiceCredentialsResponse.newBuilder()
.setUsername(externalServiceCredentials.username())
.setPassword(externalServiceCredentials.password())
.build();
}
}
@@ -0,0 +1,42 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.Status;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class GrpcAllowListInterceptor implements ServerInterceptor {
private final boolean enableAll;
private final Set<String> enabledServices;
private final Set<String> enabledMethods;
public GrpcAllowListInterceptor(
final boolean enableAll,
final List<String> enabledServices,
final List<String> enabledMethods) {
this.enableAll = enableAll;
this.enabledServices = new HashSet<>(enabledServices);
this.enabledMethods = new HashSet<>(enabledMethods);
}
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> serverCall,
final Metadata metadata, final ServerCallHandler<ReqT, RespT> next) {
final MethodDescriptor<ReqT, RespT> methodDescriptor = serverCall.getMethodDescriptor();
if (!enableAll && !enabledServices.contains(methodDescriptor.getServiceName()) && !enabledMethods.contains(methodDescriptor.getFullMethodName())) {
return ServerInterceptorUtil.closeWithStatus(serverCall, Status.UNIMPLEMENTED);
}
return next.startCall(serverCall, metadata);
}
}
@@ -0,0 +1,178 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.Any;
import com.google.rpc.BadRequest;
import com.google.rpc.ErrorInfo;
import com.google.rpc.RetryInfo;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import io.grpc.protobuf.StatusProto;
import java.time.Duration;
import javax.annotation.Nullable;
public class GrpcExceptions {
public static final String DOMAIN = "grpc.chat.signal.org";
private static final Any ERROR_INFO_CONSTRAINT_VIOLATED = Any.pack(ErrorInfo.newBuilder()
.setDomain(DOMAIN)
.setReason("CONSTRAINT_VIOLATED")
.build());
private static final Any ERROR_INFO_RESOURCE_EXHAUSTED = Any.pack(ErrorInfo.newBuilder()
.setDomain(DOMAIN)
.setReason("RESOURCE_EXHAUSTED")
.build());
private static final Any ERROR_INFO_INVALID_CREDENTIALS = Any.pack(ErrorInfo.newBuilder()
.setDomain(DOMAIN)
.setReason("INVALID_CREDENTIALS")
.build());
private static final Any ERROR_INFO_BAD_AUTHENTICATION = Any.pack(ErrorInfo.newBuilder()
.setDomain(DOMAIN)
.setReason("BAD_AUTHENTICATION")
.build());
private static final com.google.rpc.Status UPGRADE_REQUIRED = com.google.rpc.Status.newBuilder()
.setCode(Status.Code.INVALID_ARGUMENT.value())
.setMessage("Upgrade required")
.addDetails(Any.pack(ErrorInfo.newBuilder()
.setDomain(DOMAIN)
.setReason("UPGRADE_REQUIRED")
.build()))
.build();
private GrpcExceptions() {
}
/// The client version provided in the User-Agent is no longer supported. The client must upgrade to use the service.
///
/// @return A [StatusRuntimeException] encoding the error
public static StatusRuntimeException upgradeRequired() {
return StatusProto.toStatusRuntimeException(UPGRADE_REQUIRED);
}
/// The RPC argument violated a constraint that was annotated or documented in the service definition. It is always
/// possible to check this constraint without communicating with the chat server. This always represents a client bug
/// or out of date client. Additional information about the violating field will be included in the metadata.
///
/// @param fieldName The name of the field that violated a service constraint
/// @param message Additional context about the constraint violation
/// @return A [StatusRuntimeException] encoding the error
public static StatusRuntimeException fieldViolation(final String fieldName, @Nullable final String message) {
return StatusProto.toStatusRuntimeException(com.google.rpc.Status.newBuilder()
.setCode(Status.Code.INVALID_ARGUMENT.value())
.setMessage(messageOrDefault(message, Status.Code.INVALID_ARGUMENT))
.addDetails(ERROR_INFO_CONSTRAINT_VIOLATED)
.addDetails(Any.pack(BadRequest.newBuilder()
.addFieldViolations(BadRequest.FieldViolation.newBuilder()
.setField(fieldName)
.setDescription(messageOrDefault(message, Status.Code.INVALID_ARGUMENT)))
.build()))
.build());
}
/// The RPC argument violated a constraint that was annotated or documented in the service definition. It is always
/// possible to check this constraint without communicating with the chat server. This always represents a client bug
/// or out of date client.
///
/// @param message Additional context about the constraint violation
/// @return A [StatusRuntimeException] encoding the error
public static StatusRuntimeException invalidArguments(@Nullable final String message) {
return StatusProto.toStatusRuntimeException(com.google.rpc.Status.newBuilder()
.setCode(Status.Code.INVALID_ARGUMENT.value())
.setMessage(messageOrDefault(message, Status.Code.INVALID_ARGUMENT))
.addDetails(ERROR_INFO_CONSTRAINT_VIOLATED)
.build());
}
/// The RPC argument violated a constraint that was annotated or documented in the service definition. It is always
/// possible to check this constraint without communicating with the chat server. This always represents a client bug
/// or out of date client.
///
/// @param message Additional context about the constraint violation
/// @return A [StatusRuntimeException] encoding the error
public static StatusRuntimeException constraintViolation(@Nullable final String message) {
return StatusProto.toStatusRuntimeException(com.google.rpc.Status.newBuilder()
.setCode(Status.Code.INVALID_ARGUMENT.value())
.setMessage(messageOrDefault(message, Status.Code.INVALID_ARGUMENT))
.addDetails(ERROR_INFO_CONSTRAINT_VIOLATED)
.build());
}
/// The request has incorrectly set authentication credentials for the RPC. This represents a client bug where the
/// authorization header is not correct for the RPC. For example,
///
/// - The RPC was for an anonymous service, but included an Authentication header in the RPC metadata
/// - The RPC should only be made by the primary device, but the request had linked device credentials
///
/// @param message indicating why the credentials were set incorrectly
/// @return A [StatusRuntimeException] encoding the error
public static StatusRuntimeException badAuthentication(@Nullable final String message) {
return StatusProto.toStatusRuntimeException(com.google.rpc.Status.newBuilder()
.setCode(Status.Code.INVALID_ARGUMENT.value())
.setMessage(messageOrDefault(message, Status.Code.INVALID_ARGUMENT))
.addDetails(ERROR_INFO_BAD_AUTHENTICATION)
.build());
}
/// The account credentials provided in the authorization header are no longer valid.
///
/// @param message indicating why the credentials were invalid
/// @return A [StatusRuntimeException] encoding the error
public static StatusRuntimeException invalidCredentials(@Nullable final String message) {
return StatusProto.toStatusRuntimeException(com.google.rpc.Status.newBuilder()
.setCode(Status.Code.UNAUTHENTICATED.value())
.setMessage(messageOrDefault(message, Status.Code.UNAUTHENTICATED))
.addDetails(ERROR_INFO_INVALID_CREDENTIALS)
.build());
}
/// A server-side resource was exhausted. The details field may include a RetryInfo message that includes the amount
/// of time in seconds the client should wait before retrying the request.
///
/// If a RetryInfo is present, the client must wait the indicated time before retrying the request. If absent, the
/// client should retry with an exponential backoff.
///
/// @param retryDuration If present, the duration the client should wait before retrying the request
/// @return A [StatusRuntimeException] encoding the error
public static StatusRuntimeException rateLimitExceeded(@Nullable final Duration retryDuration) {
final com.google.rpc.Status.Builder builder = com.google.rpc.Status.newBuilder()
.setCode(Status.Code.RESOURCE_EXHAUSTED.value())
.addDetails(ERROR_INFO_RESOURCE_EXHAUSTED);
if (retryDuration != null) {
builder.addDetails(Any.pack(RetryInfo.newBuilder()
.setRetryDelay(com.google.protobuf.Duration.newBuilder()
.setSeconds(retryDuration.getSeconds())
.setNanos(retryDuration.getNano()))
.build()));
}
return StatusProto.toStatusRuntimeException(builder.build());
}
/// There was an internal error processing the RPC. The client should retry the request with exponential backoff.
///
/// @return A [StatusRuntimeException] encoding the error
public static StatusRuntimeException unavailable(@Nullable final String message) {
return StatusProto.toStatusRuntimeException(com.google.rpc.Status.newBuilder()
.setCode(Status.Code.UNAVAILABLE.value())
.setMessage(messageOrDefault(message, Status.Code.UNAVAILABLE))
.addDetails(Any.pack(ErrorInfo.newBuilder()
.setDomain(DOMAIN)
.setReason("UNAVAILABLE")
.build()))
.build());
}
private static String messageOrDefault(@Nullable final String message, Status.Code code) {
return message == null ? code.toString() : message;
}
}
@@ -35,28 +35,32 @@ class KeysGrpcHelper {
final String userAgent = RequestAttributesUtil.getUserAgent().orElse(null);
return devices
.flatMap(device -> Mono
.fromFuture(keysManager.takeDevicePreKeys(device.getId(), targetServiceIdentifier, userAgent))
.flatMap(Mono::justOrEmpty)
.map(devicePreKeys -> {
final GetPreKeysResponse.PreKeyBundle.Builder builder = GetPreKeysResponse.PreKeyBundle.newBuilder()
.setEcSignedPreKey(EcSignedPreKey.newBuilder()
.setKeyId(devicePreKeys.ecSignedPreKey().keyId())
.setPublicKey(ByteString.copyFrom(devicePreKeys.ecSignedPreKey().serializedPublicKey()))
.setSignature(ByteString.copyFrom(devicePreKeys.ecSignedPreKey().signature()))
.build())
.setKemOneTimePreKey(KemSignedPreKey.newBuilder()
.setKeyId(devicePreKeys.kemSignedPreKey().keyId())
.setPublicKey(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().serializedPublicKey()))
.setSignature(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().signature()))
.build());
devicePreKeys.ecPreKey().ifPresent(ecPreKey -> builder.setEcOneTimePreKey(EcPreKey.newBuilder()
.setKeyId(ecPreKey.keyId())
.setPublicKey(ByteString.copyFrom(ecPreKey.serializedPublicKey()))
.build()));
// Cast device IDs to `int` to match data types in the response object’s protobuf definition
return Tuples.of((int) device.getId(), builder.build());
}))
.flatMap(device -> {
final int registrationId = device.getRegistrationId(targetServiceIdentifier.identityType());
return Mono
.fromFuture(keysManager.takeDevicePreKeys(device.getId(), targetServiceIdentifier, userAgent))
.flatMap(Mono::justOrEmpty)
.map(devicePreKeys -> {
final GetPreKeysResponse.PreKeyBundle.Builder builder = GetPreKeysResponse.PreKeyBundle.newBuilder()
.setEcSignedPreKey(EcSignedPreKey.newBuilder()
.setKeyId(devicePreKeys.ecSignedPreKey().keyId())
.setPublicKey(ByteString.copyFrom(devicePreKeys.ecSignedPreKey().serializedPublicKey()))
.setSignature(ByteString.copyFrom(devicePreKeys.ecSignedPreKey().signature()))
.build())
.setKemOneTimePreKey(KemSignedPreKey.newBuilder()
.setKeyId(devicePreKeys.kemSignedPreKey().keyId())
.setPublicKey(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().serializedPublicKey()))
.setSignature(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().signature()))
.build())
.setRegistrationId(registrationId);
devicePreKeys.ecPreKey().ifPresent(ecPreKey -> builder.setEcOneTimePreKey(EcPreKey.newBuilder()
.setKeyId(ecPreKey.keyId())
.setPublicKey(ByteString.copyFrom(ecPreKey.serializedPublicKey()))
.build()));
// Cast device IDs to `int` to match data types in the response object’s protobuf definition
return Tuples.of((int) device.getId(), builder.build());
});
})
// If there were no devices with valid prekey bundles in the account, the account is gone
.switchIfEmpty(Mono.error(Status.NOT_FOUND.asException()))
.collectMap(Tuple2::getT1, Tuple2::getT2)
@@ -6,26 +6,50 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.common.annotations.VisibleForTesting;
import io.grpc.*;
import com.google.protobuf.Descriptors;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Message;
import com.google.rpc.ErrorInfo;
import io.grpc.ForwardingServerCall;
import io.grpc.ForwardingServerCallListener;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.Status;
import io.grpc.protobuf.StatusProto;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.Timer;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
public class MetricServerInterceptor implements ServerInterceptor {
private static final Logger log = LoggerFactory.getLogger(MetricServerInterceptor.class);
private static final String TAG_SERVICE_NAME = "grpcService";
private static final String TAG_METHOD_NAME = "method";
private static final String TAG_METHOD_TYPE = "methodType";
private static final String TAG_STATUS_CODE = "statusCode";
private static final String TAG_REASON = "reason";
@VisibleForTesting
static final String DEFAULT_SUCCESS_REASON = "success";
@VisibleForTesting
static final String DEFAULT_ERROR_REASON = "n/a";
@VisibleForTesting
static final String REQUEST_MESSAGE_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "requestMessage");
@@ -77,6 +101,7 @@ public class MetricServerInterceptor implements ServerInterceptor {
private final Counter responseMessageCounter;
private final Tags tags;
private @Nullable String reason = null;
MetricServerCall(final ServerCall<ReqT, RespT> delegate, final Tags tags) {
super(delegate);
@@ -86,15 +111,59 @@ public class MetricServerInterceptor implements ServerInterceptor {
@Override
public void close(final Status status, final Metadata responseHeaders) {
meterRegistry.counter(RPC_COUNTER_NAME, tags.and(TAG_STATUS_CODE, status.getCode().name())).increment();
if (!status.isOk()) {
reason = errorInfo(StatusProto.fromStatusAndTrailers(status, responseHeaders))
.map(ErrorInfo::getReason)
.orElse(DEFAULT_ERROR_REASON);
}
Tags responseTags = tags.and(Tag.of(TAG_STATUS_CODE, status.getCode().name()));
if (reason != null) {
responseTags = responseTags.and(TAG_REASON, reason);
}
meterRegistry.counter(RPC_COUNTER_NAME, responseTags).increment();
super.close(status, responseHeaders);
}
@Override
public void sendMessage(final RespT responseMessage) {
this.responseMessageCounter.increment();
// Extract the annotated reason (if any) from the message
final String messageReason = MetricServerCall.reason(responseMessage);
// If there are multiple messages sent on this RPC (server-side streaming), just use the most recent reason
this.reason = messageReason == null ? DEFAULT_SUCCESS_REASON : messageReason;
super.sendMessage(responseMessage);
}
@Nullable
private static String reason(final Object obj) {
if (!(obj instanceof Message msg)) {
return null;
}
// iterate through all fields on the message
for (Map.Entry<Descriptors.FieldDescriptor, Object> field : msg.getAllFields().entrySet()) {
// iterate through all options on the field
for (Map.Entry<Descriptors.FieldDescriptor, Object> option : field.getKey().getOptions().getAllFields().entrySet()) {
if (option.getKey().getFullName().equals("org.signal.chat.tag.reason")) {
if (!(option.getValue() instanceof String s)) {
log.error("Invalid value for option tag.reason {}", option.getValue());
continue;
}
// return the first tag we see
return s;
}
}
// No reason on this field. Recursively check subfields of this field for a reason
final String subReason = reason(field.getValue());
if (subReason != null) {
return subReason;
}
}
// No field or subfield contained an annotated reason
return null;
}
}
/**
@@ -131,4 +200,17 @@ public class MetricServerInterceptor implements ServerInterceptor {
super.onCancel();
}
}
private static Optional<ErrorInfo> errorInfo(final com.google.rpc.Status statusProto) {
return statusProto.getDetailsList().stream()
.filter(any -> any.is(ErrorInfo.class))
.map(errorInfo -> {
try {
return errorInfo.unpack(ErrorInfo.class);
} catch (final InvalidProtocolBufferException e) {
throw new UncheckedIOException(e);
}
})
.findFirst();
}
}
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.grpc;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
public class ServerInterceptorUtil {
@@ -36,4 +37,23 @@ public class ServerInterceptorUtil {
//noinspection unchecked
return NO_OP_LISTENER;
}
/**
* Closes the given server call with the status and metadata from the provided exception, returning a no-op listener.
*
* @param call the server call to close
* @param exception the {@link StatusRuntimeException} with which to close the call
*
* @return a no-op server call listener
*
* @param <ReqT> the type of request object handled by the server call
* @param <RespT> the type of response object returned by the server call
*/
public static <ReqT, RespT> ServerCall.Listener<ReqT> closeWithStatusException(final ServerCall<ReqT, RespT> call, final StatusRuntimeException exception) {
call.close(exception.getStatus(), exception.getTrailers());
//noinspection unchecked
return NO_OP_LISTENER;
}
}
@@ -1,12 +0,0 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import io.grpc.Status;
public abstract class StatusConstants {
public static final Status UPGRADE_NEEDED_STATUS = Status.INVALID_ARGUMENT.withDescription("signal-upgrade-required");
}
@@ -15,6 +15,7 @@ import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.StatusException;
import java.util.List;
import java.util.Map;
import org.whispersystems.textsecuregcm.grpc.validators.E164FieldValidator;
import org.whispersystems.textsecuregcm.grpc.validators.EnumSpecifiedFieldValidator;
@@ -81,12 +82,28 @@ public class ValidatingInterceptor implements ServerInterceptor {
for (final Map.Entry<Descriptors.FieldDescriptor, Object> entry: fd.getOptions().getAllFields().entrySet()) {
final Descriptors.FieldDescriptor extensionFieldDescriptor = entry.getKey();
final String extensionName = extensionFieldDescriptor.getFullName();
// first validate the field
final FieldValidator validator = fieldValidators.get(extensionName);
// not all extensions are validators, so `validator` value here could legitimately be `null`
if (validator != null) {
validator.validate(entry.getValue(), fd, msg);
}
}
// Recursively validate the field's value(s) if it is a message or a repeated field
// gRPC's proto deserialization limits nesting to 100 so this has bounded stack usage
if (fd.isRepeated() && msg.getField(fd) instanceof List list) {
// Checking for repeated fields also handles maps, because maps are syntax sugar for repeated MapEntries
// which themselves are Messages that will be recursively descended.
for (final Object o : list) {
validateMessage(o);
}
} else if (fd.hasPresence() && msg.hasField(fd)) {
// If the field has presence information and is present, recursively validate it. Not all fields have
// presence, but we only validate Message type fields anyway, which always have explicit presence.
validateMessage(msg.getField(fd));
}
}
} catch (final StatusException e) {
throw e;
@@ -9,6 +9,7 @@ import com.google.common.annotations.VisibleForTesting;
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.github.resilience4j.retry.Retry;
import io.github.resilience4j.retry.RetryConfig;
import java.io.IOException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
@@ -18,6 +19,7 @@ import java.time.Duration;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.Executor;
@@ -29,8 +31,8 @@ import java.util.stream.IntStream;
import javax.annotation.Nullable;
import org.glassfish.jersey.SslConfigurator;
import org.whispersystems.textsecuregcm.util.CertificateUtil;
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
public class FaultTolerantHttpClient {
@@ -65,17 +67,31 @@ public class FaultTolerantHttpClient {
return this.httpClients.get(ThreadLocalRandom.current().nextInt(this.httpClients.size()));
}
public <T> CompletableFuture<HttpResponse<T>> sendAsync(HttpRequest request,
public <T> HttpResponse<T> send(final HttpRequest request, final HttpResponse.BodyHandler<T> bodyHandler)
throws IOException {
final Callable<HttpResponse<T>> requestCallable =
() -> httpClient().send(requestWithTimeout(request, defaultRequestTimeout), bodyHandler);
try {
return retry != null
? breaker.executeCallable(retry.decorateCallable(requestCallable))
: breaker.executeCallable(requestCallable);
} catch (final IOException e) {
throw e;
} catch (final Exception e) {
if (e instanceof RuntimeException runtimeException) {
throw runtimeException;
}
throw new RuntimeException(e);
}
}
public <T> CompletableFuture<HttpResponse<T>> sendAsync(final HttpRequest request,
final HttpResponse.BodyHandler<T> bodyHandler) {
if (request.timeout().isEmpty()) {
request = HttpRequest.newBuilder(request, (_, _) -> true)
.timeout(defaultRequestTimeout)
.build();
}
final Supplier<CompletionStage<HttpResponse<T>>> asyncRequestSupplier =
sendAsync(httpClient(), request, bodyHandler);
() -> httpClient().sendAsync(requestWithTimeout(request, defaultRequestTimeout), bodyHandler);
if (retry != null) {
assert retryExecutor != null;
@@ -87,10 +103,12 @@ public class FaultTolerantHttpClient {
}
}
private <T> Supplier<CompletionStage<HttpResponse<T>>> sendAsync(HttpClient client, HttpRequest request,
HttpResponse.BodyHandler<T> bodyHandler) {
return () -> client.sendAsync(request, bodyHandler);
private static HttpRequest requestWithTimeout(final HttpRequest request, final Duration defaultRequestTimeout) {
return request.timeout().isPresent()
? request
: HttpRequest.newBuilder(request, (_, _) -> true)
.timeout(defaultRequestTimeout)
.build();
}
public static class Builder {
@@ -102,7 +120,7 @@ public class FaultTolerantHttpClient {
private int numClients = 1;
private final String name;
private Executor executor;
private final Executor executor;
private KeyStore trustStore;
private String securityProtocol = SECURITY_PROTOCOL_TLS_1_2;
private String retryConfigurationName;
@@ -62,6 +62,6 @@ public abstract class BaseRateLimiters<T extends RateLimiterDescriptor> {
final Clock clock) {
final Supplier<RateLimiterConfig> configResolver =
() -> dynamicConfigurationManager.getConfiguration().getLimits().getOrDefault(descriptor.id(), descriptor.defaultConfig());
return new DynamicRateLimiter(descriptor.id(), configResolver, validateScript, cacheCluster, retryExecutor, clock);
return new LeakyBucketRateLimiter(descriptor.id(), configResolver, validateScript, cacheCluster, retryExecutor, clock);
}
}
@@ -24,7 +24,7 @@ import org.whispersystems.textsecuregcm.util.ResilienceUtil;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.Util;
public class DynamicRateLimiter implements RateLimiter {
public class LeakyBucketRateLimiter implements RateLimiter {
private final String name;
private final Supplier<RateLimiterConfig> configResolver;
@@ -38,9 +38,20 @@ public class DynamicRateLimiter implements RateLimiter {
private final Clock clock;
private static final String RETRY_NAME = ResilienceUtil.name(DynamicRateLimiter.class);
private static final String RETRY_NAME = ResilienceUtil.name(LeakyBucketRateLimiter.class);
public DynamicRateLimiter(
public LeakyBucketRateLimiter(
final String name,
final RateLimiterConfig rateLimiterConfig,
final ClusterLuaScript validateScript,
final FaultTolerantRedisClusterClient cluster,
final ScheduledExecutorService retryExecutor,
final Clock clock) {
this(name, () -> rateLimiterConfig, validateScript, cluster, retryExecutor, clock);
}
public LeakyBucketRateLimiter(
final String name,
final Supplier<RateLimiterConfig> configResolver,
final ClusterLuaScript validateScript,
@@ -57,7 +68,7 @@ public class DynamicRateLimiter implements RateLimiter {
}
@Override
public void validate(final String key, final int amount) throws RateLimitExceededException {
public void validate(final String key, final long amount) throws RateLimitExceededException {
final RateLimiterConfig config = config();
try {
final long deficitPermitsAmount = executeValidateScript(config, key, amount, true);
@@ -79,7 +90,7 @@ public class DynamicRateLimiter implements RateLimiter {
}
@Override
public CompletionStage<Void> validateAsync(final String key, final int amount) {
public CompletionStage<Void> validateAsync(final String key, final long amount) {
final RateLimiterConfig config = config();
return executeValidateScriptAsync(config, key, amount, true)
@@ -106,7 +117,7 @@ public class DynamicRateLimiter implements RateLimiter {
}
@Override
public boolean hasAvailablePermits(final String key, final int permits) {
public boolean hasAvailablePermits(final String key, final long permits) {
final RateLimiterConfig config = config();
try {
final long deficitPermitsAmount = executeValidateScript(config, key, permits, false);
@@ -121,7 +132,7 @@ public class DynamicRateLimiter implements RateLimiter {
}
@Override
public CompletionStage<Boolean> hasAvailablePermitsAsync(final String key, final int amount) {
public CompletionStage<Boolean> hasAvailablePermitsAsync(final String key, final long amount) {
final RateLimiterConfig config = config();
return executeValidateScriptAsync(config, key, amount, false)
.thenApply(deficitPermitsAmount -> deficitPermitsAmount == 0)
@@ -151,7 +162,7 @@ public class DynamicRateLimiter implements RateLimiter {
return configResolver.get();
}
private long executeValidateScript(final RateLimiterConfig config, final String key, final int amount, final boolean applyChanges) {
private long executeValidateScript(final RateLimiterConfig config, final String key, final long amount, final boolean applyChanges) {
final List<String> keys = List.of(bucketName(name, key));
final List<String> arguments = List.of(
String.valueOf(config.bucketSize()),
@@ -163,7 +174,7 @@ public class DynamicRateLimiter implements RateLimiter {
return (Long) validateScript.execute(keys, arguments);
}
private CompletionStage<Long> executeValidateScriptAsync(final RateLimiterConfig config, final String key, final int amount, final boolean applyChanges) {
private CompletionStage<Long> executeValidateScriptAsync(final RateLimiterConfig config, final String key, final long amount, final boolean applyChanges) {
final List<String> keys = List.of(bucketName(name, key));
final List<String> arguments = List.of(
String.valueOf(config.bucketSize()),
@@ -13,13 +13,13 @@ import reactor.core.publisher.Mono;
public interface RateLimiter {
void validate(String key, int amount) throws RateLimitExceededException;
void validate(String key, long amount) throws RateLimitExceededException;
CompletionStage<Void> validateAsync(String key, int amount);
CompletionStage<Void> validateAsync(String key, long amount);
boolean hasAvailablePermits(String key, int permits);
boolean hasAvailablePermits(String key, long permits);
CompletionStage<Boolean> hasAvailablePermitsAsync(String key, int amount);
CompletionStage<Boolean> hasAvailablePermitsAsync(String key, long amount);
void clear(String key);
@@ -35,7 +35,7 @@ public interface RateLimiter {
validate(accountUuid.toString());
}
default void validate(final UUID accountUuid, final int permits) throws RateLimitExceededException {
default void validate(final UUID accountUuid, final long permits) throws RateLimitExceededException {
validate(accountUuid.toString(), permits);
}
@@ -63,11 +63,11 @@ public interface RateLimiter {
return validateReactive(accountUuid.toString());
}
default boolean hasAvailablePermits(final UUID accountUuid, final int permits) {
default boolean hasAvailablePermits(final UUID accountUuid, final long permits) {
return hasAvailablePermits(accountUuid.toString(), permits);
}
default CompletionStage<Boolean> hasAvailablePermitsAsync(final UUID accountUuid, final int permits) {
default CompletionStage<Boolean> hasAvailablePermitsAsync(final UUID accountUuid, final long permits) {
return hasAvailablePermitsAsync(accountUuid.toString(), permits);
}
@@ -9,7 +9,7 @@ import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.AssertTrue;
import java.time.Duration;
public record RateLimiterConfig(int bucketSize, Duration permitRegenerationDuration, boolean failOpen) {
public record RateLimiterConfig(long bucketSize, Duration permitRegenerationDuration, boolean failOpen) {
public double leakRatePerMillis() {
return 1.0 / (permitRegenerationDuration.toNanos() / 1e6);
@@ -56,7 +56,7 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
RECORD_DEVICE_TRANSFER_REQUEST("recordDeviceTransferRequest", new RateLimiterConfig(10, Duration.ofMillis(100), true)),
WAIT_FOR_DEVICE_TRANSFER_REQUEST("waitForDeviceTransferRequest", new RateLimiterConfig(10, Duration.ofMillis(100), true)),
DEVICE_CHECK_CHALLENGE("deviceCheckChallenge", new RateLimiterConfig(10, Duration.ofMinutes(1), false)),
SUBMIT_CALL_QUALITY_SURVERY("submitCallQualitySurvey", new RateLimiterConfig(100, Duration.ofMinutes(1), true))
SUBMIT_CALL_QUALITY_SURVEY("submitCallQualitySurvey", new RateLimiterConfig(100, Duration.ofMinutes(1), true))
;
private final String id;
@@ -224,6 +224,6 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
}
public RateLimiter getSubmitCallQualitySurveyLimiter() {
return forDescriptor(For.SUBMIT_CALL_QUALITY_SURVERY);
return forDescriptor(For.SUBMIT_CALL_QUALITY_SURVEY);
}
}
@@ -0,0 +1,45 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.mappers;
import io.dropwizard.jersey.errors.ErrorMessage;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
import org.whispersystems.textsecuregcm.backup.BackupBadReceiptException;
import org.whispersystems.textsecuregcm.backup.BackupException;
import org.whispersystems.textsecuregcm.backup.BackupFailedZkAuthenticationException;
import org.whispersystems.textsecuregcm.backup.BackupInvalidArgumentException;
import org.whispersystems.textsecuregcm.backup.BackupMissingIdCommitmentException;
import org.whispersystems.textsecuregcm.backup.BackupNotFoundException;
import org.whispersystems.textsecuregcm.backup.BackupPermissionException;
import org.whispersystems.textsecuregcm.backup.BackupWrongCredentialTypeException;
public class BackupExceptionMapper implements ExceptionMapper<BackupException> {
@Override
public Response toResponse(final BackupException exception) {
final Response.Status status = (switch (exception) {
case BackupNotFoundException _ -> Response.Status.NOT_FOUND;
case BackupInvalidArgumentException _, BackupBadReceiptException _ -> Response.Status.BAD_REQUEST;
case BackupPermissionException _ -> Response.Status.FORBIDDEN;
case BackupMissingIdCommitmentException _ -> Response.Status.CONFLICT;
case BackupWrongCredentialTypeException _,
BackupFailedZkAuthenticationException _ -> Response.Status.UNAUTHORIZED;
default -> Response.Status.INTERNAL_SERVER_ERROR;
});
final WebApplicationException wae =
new WebApplicationException(exception.getMessage(), exception, Response.status(status).build());
return Response
.fromResponse(wae.getResponse())
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new ErrorMessage(wae.getResponse().getStatus(), wae.getLocalizedMessage())).build();
}
}
@@ -0,0 +1,25 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.metrics;
import javax.annotation.Nullable;
import java.util.Optional;
public class CallQualityInvalidArgumentsException extends Exception {
private final @Nullable String field;
public CallQualityInvalidArgumentsException(final String message) {
this(message, null);
}
public CallQualityInvalidArgumentsException(final String message, final String field) {
super(message);
this.field = field;
}
public Optional<String> getField() {
return Optional.ofNullable(field);
}
}
@@ -6,6 +6,7 @@
package org.whispersystems.textsecuregcm.metrics;
import com.google.cloud.pubsub.v1.PublisherInterface;
import com.google.common.annotations.VisibleForTesting;
import com.google.pubsub.v1.PubsubMessage;
import io.micrometer.core.instrument.Metrics;
import java.time.Clock;
@@ -48,15 +49,18 @@ public class CallQualitySurveyManager {
public void submitCallQualitySurvey(final SubmitCallQualitySurveyRequest submitCallQualitySurveyRequest,
final String remoteAddress,
final String userAgentString) {
final String userAgentString) throws CallQualityInvalidArgumentsException {
validateRequest(submitCallQualitySurveyRequest);
final CallQualitySurveyResponsePubSubMessage.Builder pubSubMessageBuilder =
CallQualitySurveyResponsePubSubMessage.newBuilder()
.setResponseId(UUID.randomUUID().toString())
.setSubmissionTimestamp(clock.millis() * 1000)
.setUserSatisfied(submitCallQualitySurveyRequest.getUserSatisfied())
.setStartTimestamp(submitCallQualitySurveyRequest.getStartTimestamp())
.setEndTimestamp(submitCallQualitySurveyRequest.getEndTimestamp())
// We receive timestamps as milliseconds since the epoch, but the backing data store wants microseconds
.setStartTimestamp(submitCallQualitySurveyRequest.getStartTimestamp() * 1_000)
.setEndTimestamp(submitCallQualitySurveyRequest.getEndTimestamp() * 1_000)
.setCallType(submitCallQualitySurveyRequest.getCallType())
.setSuccess(submitCallQualitySurveyRequest.getSuccess())
.setCallEndReason(submitCallQualitySurveyRequest.getCallEndReason());
@@ -146,4 +150,23 @@ public class CallQualitySurveyManager {
.increment();
});
}
@VisibleForTesting
static void validateRequest(final SubmitCallQualitySurveyRequest request) throws CallQualityInvalidArgumentsException {
if (request.getStartTimestamp() == 0) {
throw new CallQualityInvalidArgumentsException("Start timestamp not specified", "startTimestamp");
}
if (request.getEndTimestamp() == 0) {
throw new CallQualityInvalidArgumentsException("End timestamp not specified", "endTimestamp");
}
if (StringUtils.isBlank(request.getCallType())) {
throw new CallQualityInvalidArgumentsException("Call type not specified", "callType");
}
if (StringUtils.isBlank(request.getCallEndReason())) {
throw new CallQualityInvalidArgumentsException("Call end reason not specified", "callEndReason");
}
}
}
@@ -27,7 +27,6 @@ import java.time.Duration;
import java.util.Optional;
import net.logstash.logback.appender.LogstashTcpSocketAppender;
import net.logstash.logback.encoder.LogstashEncoder;
import org.whispersystems.textsecuregcm.WhisperServerVersion;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
import org.whispersystems.textsecuregcm.util.HostnameUtil;
@@ -97,13 +96,12 @@ public class LogstashTcpSocketAppenderFactory extends AbstractAppenderFactory<IL
final ObjectNode customFieldsNode = new ObjectNode(JsonNodeFactory.instance);
customFieldsNode.set("host", TextNode.valueOf(HostnameUtil.getLocalHostname()));
customFieldsNode.set("service", TextNode.valueOf("chat"));
customFieldsNode.set("ddsource", TextNode.valueOf("logstash"));
customFieldsNode.set("ddtags", TextNode.valueOf("env:" + environment + ",version:" + WhisperServerVersion.getServerVersion()));
encoder.setCustomFields(customFieldsNode.toString());
final LayoutWrappingEncoder<ILoggingEvent> prefix = new LayoutWrappingEncoder<>();
final PatternLayout layout = new PatternLayout();
layout.setPattern(String.format("%s ", apiKey.value()));
layout.setContext(context);
prefix.setLayout(layout);
encoder.setPrefix(prefix);
appender.setEncoder(encoder);
@@ -135,7 +135,6 @@ public class MetricsUtil {
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
final DistributionStatisticConfig defaultDistributionStatisticConfig = DistributionStatisticConfig.builder()
.percentilesHistogram(true)
.percentiles(.75, .95, .99, .999)
.build();
final String awsSdkMetricNamePrefix = MetricsUtil.name(MicrometerAwsSdkMetricPublisher.class);
@@ -33,7 +33,7 @@ public class OpenTelemetryAppenderFactory extends AbstractAppenderFactory<ILoggi
final OpenTelemetryAppender appender = new OpenTelemetryAppender();
appender.setCaptureCodeAttributes(true);
appender.setCaptureLoggerContext(true);
appender.setCaptureMarkerAttribute(true);
appender.setCaptureLogstashMarkerAttributes(true);
// The installation of an OpenTelemetry configuration happens in
// WhisperServerService (or CommandDependencies), in order to let us tie
@@ -9,6 +9,8 @@ import io.micrometer.core.instrument.Tag;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.HttpHeaders;
import org.apache.commons.lang3.StringUtils;
import org.whispersystems.textsecuregcm.WhisperServerVersion;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
@@ -32,6 +34,10 @@ public class UserAgentTagUtil {
private UserAgentTagUtil() {
}
public static Tag getPlatformTag(final ContainerRequestContext containerRequestContext) {
return getPlatformTag(containerRequestContext.getHeaderString(HttpHeaders.USER_AGENT));
}
public static Tag getPlatformTag(final String userAgentString) {
if (SERVER_UA.equals(userAgentString)) {
@@ -13,17 +13,19 @@ import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import kotlin.Pair;
import org.apache.commons.lang3.StringUtils;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
import org.signal.libsignal.protocol.util.Pair;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevices;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.controllers.MultiRecipientMismatchedDevicesException;
@@ -31,6 +33,7 @@ import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.spam.MessageDeliveryListener;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
@@ -52,8 +55,11 @@ public class MessageSender {
private final MessagesManager messagesManager;
private final PushNotificationManager pushNotificationManager;
private final List<MessageDeliveryListener> messageDeliveryListeners = new ArrayList<>();
// Note that these names deliberately reference `MessageController` for metric continuity
private static final String REJECT_OVERSIZE_MESSAGE_COUNTER_NAME = name(MessageSender.class, "rejectOversizeMessage");
private static final String OVERSIZE_MESSAGE_WARNING_COUNTER_NAME = name(MessageSender.class, "oversizeMessageWarning");
private static final String CONTENT_SIZE_DISTRIBUTION_NAME = MetricsUtil.name(MessageSender.class, "messageContentSize");
private static final String EMPTY_MESSAGE_LIST_COUNTER_NAME = MetricsUtil.name(MessageSender.class, "emptyMessageList");
@@ -69,6 +75,8 @@ public class MessageSender {
@VisibleForTesting
public static final int MAX_MESSAGE_SIZE = (int) DataSize.kibibytes(256).toBytes();
private static final int OVERSIZE_MESSAGE_WARNING_THRESHOLD = (int) DataSize.kibibytes(96).toBytes();
@VisibleForTesting
static final byte NO_EXCLUDED_DEVICE_ID = -1;
@@ -77,6 +85,10 @@ public class MessageSender {
this.pushNotificationManager = pushNotificationManager;
}
public void addMessageDeliveryListener(final MessageDeliveryListener messageDeliveryListener) {
messageDeliveryListeners.add(messageDeliveryListener);
}
/**
* Sends messages to devices associated with the given destination account. If a destination device has a valid push
* notification token and does not have an active connection to a Signal server, then this method will also send a
@@ -133,6 +145,16 @@ public class MessageSender {
.and(platformTag);
Metrics.counter(SEND_COUNTER_NAME, tags).increment();
messageDeliveryListeners.forEach(messageDeliveryListener ->
messageDeliveryListener.handleMessageDelivered(destination,
deviceId,
message.getEphemeral(),
message.getUrgent(),
message.getStory(),
!message.hasSourceServiceId(),
false,
syncMessageSenderDeviceId.isPresent()));
});
}
@@ -186,7 +208,7 @@ public class MessageSender {
final ServiceIdentifier serviceIdentifier = ServiceIdentifier.fromLibsignal(serviceId);
final Map<Byte, Integer> registrationIdsByDeviceId = recipient.getDevicesAndRegistrationIds()
.collect(Collectors.toMap(Pair::first, pair -> (int) pair.second()));
.collect(Collectors.toMap(Pair::getFirst, pair -> (int) pair.getSecond()));
getMismatchedDevices(account, serviceIdentifier, registrationIdsByDeviceId, NO_EXCLUDED_DEVICE_ID)
.ifPresent(mismatchedDevices ->
@@ -220,6 +242,16 @@ public class MessageSender {
.and(platformTag);
Metrics.counter(SEND_COUNTER_NAME, tags).increment();
messageDeliveryListeners.forEach(messageDeliveryListener ->
messageDeliveryListener.handleMessageDelivered(account,
deviceId,
isEphemeral,
isUrgent,
isStory,
true,
true,
false));
})))
.thenRun(Util.NOOP);
}
@@ -324,6 +356,14 @@ public class MessageSender {
.register(Metrics.globalRegistry)
.record(contentLength);
if (contentLength > OVERSIZE_MESSAGE_WARNING_THRESHOLD) {
Metrics.counter(OVERSIZE_MESSAGE_WARNING_COUNTER_NAME, Tags.of(platformTag,
Tag.of("multiRecipientMessage", String.valueOf(isMultiRecipientMessage)),
Tag.of("syncMessage", String.valueOf(isSyncMessage)),
Tag.of("story", String.valueOf(isStory))))
.increment();
}
if (oversize) {
Metrics.counter(REJECT_OVERSIZE_MESSAGE_COUNTER_NAME, Tags.of(platformTag,
Tag.of("multiRecipientMessage", String.valueOf(isMultiRecipientMessage)),
@@ -23,10 +23,10 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.signal.registration.rpc.CheckVerificationCodeRequest;
import org.signal.registration.rpc.CreateRegistrationSessionRequest;
import org.signal.registration.rpc.GetRegistrationSessionMetadataRequest;
@@ -94,7 +94,12 @@ public class RegistrationServiceClient implements Managed {
}
public CompletableFuture<RegistrationServiceSession> createRegistrationSession(
final Phonenumber.PhoneNumber phoneNumber, final String sourceHost, final boolean accountExistsWithPhoneNumber, final Duration timeout) {
final Phonenumber.PhoneNumber phoneNumber,
final String sourceHost,
final boolean accountExistsWithPhoneNumber,
@Nullable final String clientMcc,
@Nullable final String clientMnc,
final Duration timeout) {
final long e164 = Long.parseLong(
PhoneNumberUtil.getInstance().format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164).substring(1));
@@ -105,6 +110,8 @@ public class RegistrationServiceClient implements Managed {
.setE164(e164)
.setAccountExistsWithE164(accountExistsWithPhoneNumber)
.setRateLimitCollationKey(rateLimitCollationKey)
.setMcc(clientMcc != null ? clientMcc : "")
.setMnc(clientMnc != null ? clientMnc : "")
.build()), callbackExecutor)
.thenApply(response -> switch (response.getResponseCase()) {
case SESSION_METADATA -> buildSessionResponseFromMetadata(response.getSessionMetadata());
@@ -7,10 +7,10 @@ package org.whispersystems.textsecuregcm.registration;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.storage.SerializedExpireableJsonDynamoStore;
import org.whispersystems.textsecuregcm.telephony.CarrierData;
/**
* Server-internal stored session object. Primarily used by
@@ -18,7 +18,9 @@ import org.whispersystems.textsecuregcm.storage.SerializedExpireableJsonDynamoSt
* requesting codes from Registration Service, in order to get a verified session to be provided to
* {@link org.whispersystems.textsecuregcm.controllers.RegistrationController}.
*
* @param sessionId the session ID returned by Registration Service
* @param pushChallenge the value of a push challenge sent to a client, after it submitted a push token
* @param carrierData information about the phone number's carrier if available
* @param requestedInformation information requested that a client send to the server
* @param submittedInformation information that a client has submitted and that the server has verified
* @param smsSenderOverride if present, indicates a sender override argument that should be forwarded to the
@@ -35,7 +37,9 @@ import org.whispersystems.textsecuregcm.storage.SerializedExpireableJsonDynamoSt
* @see org.whispersystems.textsecuregcm.entities.VerificationSessionResponse
*/
public record VerificationSession(
String sessionId,
@Nullable String pushChallenge,
@Nullable CarrierData carrierData,
List<Information> requestedInformation,
List<Information> submittedInformation,
@Nullable String smsSenderOverride,
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.s3;
import com.google.common.annotations.VisibleForTesting;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.time.Duration;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
@@ -21,10 +22,13 @@ import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.S3ClientBuilder;
import software.amazon.awssdk.services.s3.S3Configuration;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.HeadObjectRequest;
import software.amazon.awssdk.services.s3.model.HeadObjectResponse;
import javax.annotation.Nullable;
/**
* An S3 object monitor watches a specific object in an S3 bucket and notifies a listener if that object changes.
@@ -65,6 +69,29 @@ public class S3ObjectMonitor {
refreshInterval);
}
// construction with s3Endpoint
public S3ObjectMonitor(final AwsCredentialsProvider awsCredentialsProvider,
final URI s3Endpoint,
final String s3Region,
final String s3Bucket,
final String objectKey,
final long maxObjectSize,
final ScheduledExecutorService refreshExecutorService,
final Duration refreshInterval) {
this(S3Client.builder()
.region(Region.of(s3Region))
.credentialsProvider(awsCredentialsProvider)
.endpointOverride(s3Endpoint)
.serviceConfiguration(S3Configuration.builder()
.pathStyleAccessEnabled(true).build())
.build(),
s3Bucket,
objectKey,
maxObjectSize,
refreshExecutorService,
refreshInterval);
}
@VisibleForTesting
S3ObjectMonitor(
final S3Client s3Client,
@@ -0,0 +1,20 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.spam;
import org.whispersystems.textsecuregcm.storage.Account;
public interface MessageDeliveryListener {
void handleMessageDelivered(Account destinationAccount,
byte destinationDeviceId,
boolean ephemeral,
boolean urgent,
boolean story,
boolean sealedSender,
boolean multiRecipient,
boolean sync);
}
@@ -11,7 +11,9 @@ import org.whispersystems.textsecuregcm.registration.VerificationSession;
public interface RegistrationFraudChecker {
record VerificationCheck(Optional<VerificationSession> updatedSession, Optional<Float> scoreThreshold) {}
record VerificationCheck(Optional<VerificationSession> updatedSession, Optional<Float> scoreThreshold) {
public static VerificationCheck DEFAULT = new VerificationCheck(Optional.empty(), Optional.empty());
}
/**
* Determine if a registration attempt is suspicious
@@ -20,8 +22,9 @@ public interface RegistrationFraudChecker {
* @param verificationSession The target verification session
* @param e164 The target phone number
* @param request The information to add to the verification session
* @return A SessionUpdate including updates to the verification session that should be persisted to the caller along
* with other constraints to enforce when evaluating the UpdateVerificationSessionRequest.
*
* @return a VerificationCheck including updates to the verification session that should be sent to the caller
* along with other constraints to enforce when evaluating the UpdateVerificationSessionRequest
*/
VerificationCheck checkVerificationAttempt(
final ContainerRequestContext requestContext,
@@ -29,9 +32,38 @@ public interface RegistrationFraudChecker {
final String e164,
final UpdateVerificationSessionRequest request);
/**
* Determine if an attempt to send a verification code is suspicious
*
* @param requestContext The request context for a "send code" attempt
* @param verificationSession The target verification session
* @param e164 The target phone number
*
* @return a VerificationCheck including updates to the verification session that should be sent to the caller
* along with other constraints to enforce when evaluating the request to send a verification code
*/
VerificationCheck checkSendVerificationCodeAttempt(
final ContainerRequestContext requestContext,
final VerificationSession verificationSession,
final String e164);
static RegistrationFraudChecker noop() {
return (ignoredContext, ignoredSession, ignoredE164, ignoredRequest) -> new VerificationCheck(
Optional.empty(),
Optional.empty());
return new RegistrationFraudChecker() {
@Override
public VerificationCheck checkVerificationAttempt(final ContainerRequestContext requestContext,
final VerificationSession verificationSession, final String e164,
final UpdateVerificationSessionRequest request) {
return VerificationCheck.DEFAULT;
}
@Override
public VerificationCheck checkSendVerificationCodeAttempt(final ContainerRequestContext requestContext,
final VerificationSession verificationSession, final String e164) {
return VerificationCheck.DEFAULT;
}
};
}
}
@@ -46,6 +46,13 @@ public interface SpamFilter extends Managed {
*/
Collection<ConfiguredCommand<WhisperServerConfiguration>> getCommands();
/**
* Returns a message delivery listener controlled by the spam filter.
*
* @return a message delivery listener controlled by the spam filter
*/
MessageDeliveryListener getMessageDeliveryListener();
/**
* Return a reported message listener controlled by the spam filter. Listeners will be registered with the
* {@link org.whispersystems.textsecuregcm.storage.ReportMessageManager}.
@@ -1253,11 +1253,7 @@ public class Accounts {
.totalSegments(segments)
.build());
// Subscribe to the publisher of responses (i.e. `scanPublisher`) rather than the publisher of items
// (i.e. `scanPublisher.items()`) to work around https://github.com/aws/aws-sdk-java-v2/issues/6411
return Flux.from(scanPublisher)
.flatMap(scanResponse -> Flux.fromIterable(scanResponse.items()))
.map(Accounts::fromItem);
return Flux.from(scanPublisher.items()).map(Accounts::fromItem);
})
.sequential();
}
@@ -37,7 +37,6 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
@@ -51,7 +50,6 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
@@ -111,12 +109,12 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
private static final Timer redisUuidGetTimer = Metrics.timer(name(AccountsManager.class, "redisUuidGet"));
private static final Timer redisDeleteTimer = Metrics.timer(name(AccountsManager.class, "redisDelete"));
private static final String CREATE_COUNTER_NAME = name(AccountsManager.class, "createCounter");
private static final String DELETE_COUNTER_NAME = name(AccountsManager.class, "deleteCounter");
private static final String COUNTRY_CODE_TAG_NAME = "country";
private static final String DELETION_REASON_TAG_NAME = "reason";
private static final String TIMESTAMP_BASED_TRANSFER_ARCHIVE_KEY_COUNTER_NAME = name(AccountsManager.class, "timestampRedisKeyCounter");
private static final String REGISTRATION_ID_BASED_TRANSFER_ARCHIVE_KEY_COUNTER_NAME = name(AccountsManager.class,"registrationIdRedisKeyCounter");
private static final String CREATE_COUNTER_NAME = name(AccountsManager.class, "createCounter");
private static final String DELETE_COUNTER_NAME = name(AccountsManager.class, "deleteCounter");
private static final String COUNTRY_CODE_TAG_NAME = "country";
private static final String DELETION_REASON_TAG_NAME = "reason";
private static final String REGISTRATION_ID_BASED_TRANSFER_ARCHIVE_KEY_COUNTER_NAME =
name(AccountsManager.class, "registrationIdRedisKeyCounter");
private static final String RETRY_NAME = ResilienceUtil.name(AccountsManager.class);
@@ -175,7 +173,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
.writer(SystemMapper.excludingField(Account.class, List.of("uuid")));
private static final Duration MESSAGE_POLL_INTERVAL = Duration.ofSeconds(1);
private static final Duration MAX_SERVER_CLOCK_DRIFT = Duration.ofSeconds(5);
// An account that's used at least daily will get reset in the cache at least once per day when its "last seen"
// timestamp updates; expiring entries after two days will help clear out "zombie" cache entries that are read
@@ -205,14 +202,8 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
}
private interface DeviceIdentifier {}
private record TimestampDeviceIdentifier(UUID accountIdentifier, byte deviceId, Instant deviceCreationTimestamp)
implements DeviceIdentifier {
}
private record RegistrationIdDeviceIdentifier(UUID accountIdentifier, byte deviceId,
int registrationId) implements DeviceIdentifier {
private record DeviceIdentifier(UUID accountIdentifier, byte deviceId,
int registrationId) {
}
public AccountsManager(final Accounts accounts,
@@ -430,23 +421,28 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
redisSet(account);
final boolean rrpCreated = accountAttributes.recoveryPassword().map(registrationRecoveryPassword ->
registrationRecoveryPasswordsManager
.store(account.getIdentifier(IdentityType.PNI), registrationRecoveryPassword)
.join())
.orElse(false);
Tags tags = Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of("type", accountCreationType),
Tag.of("hasPushToken", String.valueOf(
primaryDeviceSpec.apnRegistrationId().isPresent() || primaryDeviceSpec.gcmRegistrationId()
.isPresent())),
Tag.of("pushTokenType", pushTokenType));
Tag.of("pushTokenType", pushTokenType),
Tag.of("hasRecoveryPassword", String.valueOf(accountAttributes.recoveryPassword().isPresent())));
if (StringUtils.isNotBlank(previousPushTokenType)) {
tags = tags.and(Tag.of("previousPushTokenType", previousPushTokenType));
}
if (accountAttributes.recoveryPassword().isPresent()) {
tags = tags.and(Tag.of("recoveryPasswordOutcome", rrpCreated ? "created" : "updated"));
}
Metrics.counter(CREATE_COUNTER_NAME, tags).increment();
accountAttributes.recoveryPassword().ifPresent(registrationRecoveryPassword ->
registrationRecoveryPasswordsManager.store(account.getIdentifier(IdentityType.PNI),
registrationRecoveryPassword));
return account;
}
@@ -771,7 +767,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
return updateWithRetries(
account,
a -> {
setPniKeys(account, pniIdentityKey, pniRegistrationIds);
setPniKeys(a, pniIdentityKey, pniRegistrationIds);
return true;
},
a -> accounts.changeNumber(a, targetNumber, targetPhoneNumberIdentifier, maybeDisplacedUuid, keyWriteItems),
@@ -1037,7 +1033,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
MAX_UPDATE_ATTEMPTS);
})
.thenCompose(updatedAccount -> redisSetAsync(updatedAccount).thenApply(ignored -> updatedAccount))
.whenComplete((ignored, throwable) -> timerSample.stop(updateTimer));
.whenComplete((_, _) -> timerSample.stop(updateTimer));
}
private Account updateWithRetries(Account account,
@@ -1319,7 +1315,11 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
Optional<Account> account = resolveFromRedis.get();
if (account.isEmpty()) {
account = resolveFromAccounts.get();
account.ifPresent(this::redisSet);
try {
account.ifPresent(this::redisSet);
} catch (RedisException e) {
logger.warn("Failed to cache retrieved account", e);
}
}
return account;
});
@@ -1334,12 +1334,17 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
return resolveFromRedis.get()
.thenCompose(maybeAccountFromRedis -> maybeAccountFromRedis
.map(accountFromRedis -> CompletableFuture.completedFuture(maybeAccountFromRedis))
.map(_ -> CompletableFuture.completedFuture(maybeAccountFromRedis))
.orElseGet(() -> resolveFromAccounts.get()
.thenCompose(maybeAccountFromAccounts -> maybeAccountFromAccounts
.map(account -> redisSetAsync(account).thenApply(ignored -> maybeAccountFromAccounts))
.map(account -> redisSetAsync(account)
.exceptionally(ExceptionUtils.exceptionallyHandler(RedisException.class, e -> {
logger.warn("Failed to cache retrieved account", e);
return null;
}))
.thenApply(ignored -> maybeAccountFromAccounts))
.orElseGet(() -> CompletableFuture.completedFuture(maybeAccountFromAccounts)))))
.whenComplete((ignored, throwable) -> sample.stop(overallTimer));
.whenComplete((_, _) -> sample.stop(overallTimer));
}
private Optional<Account> redisGetBySecondaryKey(final String secondaryKey, final Timer timer) {
@@ -1352,7 +1357,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
logger.warn("Deserialization error", e);
return Optional.empty();
} catch (RedisException e) {
logger.warn("Redis failure", e);
logger.warn("Failed fetching account from cache by secondary key", e);
return Optional.empty();
}
});
@@ -1373,7 +1378,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
logger.warn("Failed to retrieve account from Redis", throwable);
return Optional.empty();
})
.whenComplete((ignored, throwable) -> sample.stop(timer))
.whenComplete((_, _) -> sample.stop(timer))
.toCompletableFuture();
}
@@ -1384,7 +1389,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
return parseAccountJson(json, uuid);
} catch (final RedisException e) {
logger.warn("Redis failure", e);
logger.warn("Failed to retrieve account from cache", e);
return Optional.empty();
}
});
@@ -1469,21 +1474,14 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
linkDeviceTokenIdentifier, getLinkedDeviceKey(linkDeviceTokenIdentifier), timeout, this::handleDeviceAdded);
return deviceAdded.thenCompose(maybeDeviceInfo -> maybeDeviceInfo.map(deviceInfo -> {
// The device finished linking, we now want to make sure the client has fetched messages that could
// have come in before the device's mailbox was set up.
// The device finished linking, we now want to make sure the primary client has fetched messages that could
// have come in before the linked device's mailbox was set up. This avoids a race where the linked device
// misses out on messages that were sent before its mailbox was set up but received by the primary *after*
// creating its backup for the linked device.
// A worst case estimate of the wall clock time at which the linked device was added to the account record
Instant deviceLinked = Instant.ofEpochMilli(deviceInfo.created()).plus(MAX_SERVER_CLOCK_DRIFT);
Instant now = clock.instant();
// We know at `now` the device finished linking, so if we waited for all the messages before now it would be
// sufficient. However, now might be much later that the device was linked, so we don't want to force
// the client to wait for messages that are past our worst case estimate of when the device was linked
Instant messageEpoch = Collections.min(List.of(deviceLinked, now));
// We assume that any message with a timestamp after the messageEpoch made it into the linked device's queues
return waitForPreLinkMessagesToBeFetched(accountIdentifier, linkingDevice, deviceInfo, messageEpoch, deadline);
// We know the device finished linking at the current time, so waiting for all messages
// before now is sufficient.
return waitForPreLinkMessagesToBeFetched(accountIdentifier, linkingDevice, deviceInfo, clock.instant(), deadline);
})
.orElseGet(() -> CompletableFuture.completedFuture(maybeDeviceInfo)));
}
@@ -1547,59 +1545,24 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
public CompletableFuture<Optional<TransferArchiveResult>> waitForTransferArchive(final Account account, final Device device, final Duration timeout) {
final DeviceIdentifier timestampDeviceIdentifier = new TimestampDeviceIdentifier(account.getIdentifier(IdentityType.ACI), device.getId(), Instant.ofEpochMilli(device.getCreated()));
final String timestampTransferArchiveKey = getTimestampTransferArchiveKey(account.getIdentifier(IdentityType.ACI), device.getId(), Instant.ofEpochMilli(device.getCreated()));
final DeviceIdentifier registrationIdDeviceIdentifier = new RegistrationIdDeviceIdentifier(account.getIdentifier(IdentityType.ACI), device.getId(), device.getRegistrationId(IdentityType.ACI));
final DeviceIdentifier deviceIdentifier = new DeviceIdentifier(account.getIdentifier(IdentityType.ACI), device.getId(), device.getRegistrationId(IdentityType.ACI));
final String registrationIdTransferArchiveKey = getRegistrationIdTransferArchiveKey(account.getIdentifier(IdentityType.ACI), device.getId(), device.getRegistrationId(IdentityType.ACI));
final CompletableFuture<Optional<TransferArchiveResult>> timestampFuture = waitForPubSubKey(waitForTransferArchiveFuturesByDeviceIdentifier,
timestampDeviceIdentifier,
timestampTransferArchiveKey,
timeout,
this::handleTransferArchiveAdded);
final CompletableFuture<Optional<TransferArchiveResult>> registrationIdFuture = waitForPubSubKey(waitForTransferArchiveFuturesByDeviceIdentifier,
registrationIdDeviceIdentifier,
return waitForPubSubKey(waitForTransferArchiveFuturesByDeviceIdentifier,
deviceIdentifier,
registrationIdTransferArchiveKey,
timeout,
this::handleTransferArchiveAdded);
return firstSuccessfulTransferArchiveFuture(List.of(timestampFuture, registrationIdFuture));
}
@VisibleForTesting
static CompletableFuture<Optional<TransferArchiveResult>> firstSuccessfulTransferArchiveFuture(
final List<CompletableFuture<Optional<TransferArchiveResult>>> futures) {
final CompletableFuture<Optional<TransferArchiveResult>> result = new CompletableFuture<>();
final AtomicInteger remaining = new AtomicInteger(futures.size());
for (CompletableFuture<Optional<TransferArchiveResult>> future : futures) {
future.whenComplete((value, _) -> {
if (value.isPresent()) {
result.complete(value);
} else if (remaining.decrementAndGet() == 0) {
result.complete(Optional.empty());
}
});
}
return result;
}
public CompletableFuture<Void> recordTransferArchiveUpload(final Account account,
final byte destinationDeviceId,
@SuppressWarnings("OptionalUsedAsFieldOrParameterType") final Optional<Instant> destinationDeviceCreationTimestamp,
@SuppressWarnings("OptionalUsedAsFieldOrParameterType") final Optional<Integer> maybeRegistrationId,
final int registrationId,
final TransferArchiveResult transferArchiveResult) {
try {
final String transferArchiveJson = SystemMapper.jsonMapper().writeValueAsString(transferArchiveResult);
final String key = destinationDeviceCreationTimestamp
.map(timestamp -> getTimestampTransferArchiveKey(account.getIdentifier(IdentityType.ACI), destinationDeviceId, timestamp))
.orElseGet(() -> maybeRegistrationId
.map(registrationId -> getRegistrationIdTransferArchiveKey(account.getIdentifier(IdentityType.ACI), destinationDeviceId, registrationId))
// We validate the request object so this should never happen
.orElseThrow(() -> new AssertionError("No creation timestamp or registration ID provided")));
final String key = getRegistrationIdTransferArchiveKey(account.getIdentifier(IdentityType.ACI), destinationDeviceId, registrationId);
return ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
.executeCompletionStage(retryExecutor, () -> pubSubRedisClient.withConnection(connection -> connection.async()
@@ -1622,16 +1585,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
}
private static String getTimestampTransferArchiveKey(final UUID accountIdentifier,
final byte destinationDeviceId,
final Instant destinationDeviceCreationTimestamp) {
Metrics.counter(TIMESTAMP_BASED_TRANSFER_ARCHIVE_KEY_COUNTER_NAME).increment();
return TRANSFER_ARCHIVE_PREFIX + accountIdentifier.toString() +
":" + destinationDeviceId +
":" + destinationDeviceCreationTimestamp.toEpochMilli();
}
private static String getRegistrationIdTransferArchiveKey(final UUID accountIdentifier,
final byte destinationDeviceId,
final int registrationId) {
@@ -1692,7 +1645,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final CompletableFuture<Optional<T>> future = new CompletableFuture<>();
future.completeOnTimeout(Optional.empty(), TimeUnit.MILLISECONDS.convert(timeout), TimeUnit.MILLISECONDS)
.whenComplete((maybeBackup, throwable) -> futureMap.remove(mapKey, future));
.whenComplete((_, _) -> futureMap.remove(mapKey, future));
{
final CompletableFuture<Optional<T>> displacedFuture = futureMap.put(mapKey, future);
@@ -1734,8 +1687,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final String[] deviceIdentifierComponents =
channel.substring(TRANSFER_ARCHIVE_KEYSPACE_PATTERN.length() - 1).split(":", 4);
if (deviceIdentifierComponents.length != 3 && deviceIdentifierComponents.length != 4) {
logger.error("Could not parse device identifier; unexpected component count");
if (deviceIdentifierComponents.length != 4) {
logger.error("Could not parse device identifier; unexpected component count: {}",
deviceIdentifierComponents.length);
return;
}
@@ -1745,24 +1699,16 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final UUID accountIdentifier = UUID.fromString(deviceIdentifierComponents[0]);
final byte deviceId = Byte.parseByte(deviceIdentifierComponents[1]);
if (deviceIdentifierComponents.length == 3) {
// Parse the old transfer archive Redis key format
final Instant deviceCreationTimestamp = Instant.ofEpochMilli(Long.parseLong(deviceIdentifierComponents[2]));
deviceIdentifier = new TimestampDeviceIdentifier(accountIdentifier, deviceId, deviceCreationTimestamp);
transferArchiveKey = getTimestampTransferArchiveKey(accountIdentifier, deviceId, deviceCreationTimestamp);
} else {
final String maybeRegistrationIdPattern = deviceIdentifierComponents[2];
if (!maybeRegistrationIdPattern.equals(TRANSFER_ARCHIVE_REGISTRATION_ID_PATTERN)) {
throw new IllegalArgumentException("Could not parse Redis key with pattern " + maybeRegistrationIdPattern);
}
final int registrationId = Integer.parseInt(deviceIdentifierComponents[3]);
if (!RegistrationIdValidator.validRegistrationId(registrationId)) {
throw new IllegalArgumentException("Invalid registration ID: " + registrationId);
}
deviceIdentifier = new RegistrationIdDeviceIdentifier(accountIdentifier, deviceId, registrationId);
transferArchiveKey = getRegistrationIdTransferArchiveKey(accountIdentifier, deviceId, registrationId);
final String registrationIdPattern = deviceIdentifierComponents[2];
if (!registrationIdPattern.equals(TRANSFER_ARCHIVE_REGISTRATION_ID_PATTERN)) {
throw new IllegalArgumentException("Could not parse Redis key with pattern " + registrationIdPattern);
}
final int registrationId = Integer.parseInt(deviceIdentifierComponents[3]);
if (!RegistrationIdValidator.validRegistrationId(registrationId)) {
throw new IllegalArgumentException("Invalid registration ID: " + registrationId);
}
deviceIdentifier = new DeviceIdentifier(accountIdentifier, deviceId, registrationId);
transferArchiveKey = getRegistrationIdTransferArchiveKey(accountIdentifier, deviceId, registrationId);
Optional.ofNullable(waitForTransferArchiveFuturesByDeviceIdentifier.remove(deviceIdentifier))
.ifPresent(future -> pubSubRedisClient.withConnection(connection -> connection.async().get(transferArchiveKey))
@@ -7,12 +7,13 @@ package org.whispersystems.textsecuregcm.storage;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.entities.ECPreKey;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
@@ -23,14 +24,12 @@ import org.whispersystems.textsecuregcm.util.Futures;
import org.whispersystems.textsecuregcm.util.Optionals;
import reactor.core.publisher.Flux;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
import javax.annotation.Nullable;
public class KeysManager {
// KeysController for backwards compatibility
private static final String GET_KEYS_COUNTER_NAME = MetricsUtil.name(KeysManager.class, "getKeys");
private final SingleUseECPreKeyStore ecPreKeys;
private final SingleUseKEMPreKeyStore pqPreKeys;
private final PagedSingleUseKEMPreKeyStore pagedPqPreKeys;
private final RepeatedUseECSignedPreKeyStore ecSignedPreKeys;
private final RepeatedUseKEMSignedPreKeyStore pqLastResortKeys;
@@ -39,12 +38,10 @@ public class KeysManager {
public KeysManager(
final SingleUseECPreKeyStore ecPreKeys,
final SingleUseKEMPreKeyStore pqPreKeys,
final PagedSingleUseKEMPreKeyStore pagedPqPreKeys,
final RepeatedUseECSignedPreKeyStore ecSignedPreKeys,
final RepeatedUseKEMSignedPreKeyStore pqLastResortKeys) {
this.ecPreKeys = ecPreKeys;
this.pqPreKeys = pqPreKeys;
this.pagedPqPreKeys = pagedPqPreKeys;
this.ecSignedPreKeys = ecSignedPreKeys;
this.pqLastResortKeys = pqLastResortKeys;
@@ -109,9 +106,7 @@ public class KeysManager {
public CompletableFuture<Void> storeKemOneTimePreKeys(final UUID identifier, final byte deviceId,
final List<KEMSignedPreKey> preKeys) {
// Unconditionally delete keys in old format keystore, then write to the pagedPqPreKeys store
return pqPreKeys.delete(identifier, deviceId)
.thenCompose(_ -> pagedPqPreKeys.store(identifier, deviceId, preKeys));
return pagedPqPreKeys.store(identifier, deviceId, preKeys);
}
@@ -124,16 +119,12 @@ public class KeysManager {
CompletableFuture<Optional<KEMSignedPreKey>> takePQ(final UUID identifier, final byte deviceId) {
return tagTakePQ(pagedPqPreKeys.take(identifier, deviceId), PQSource.PAGE)
.thenCompose(maybeSingleUsePreKey -> maybeSingleUsePreKey
.map(ignored -> CompletableFuture.completedFuture(maybeSingleUsePreKey))
.orElseGet(() -> tagTakePQ(pqPreKeys.take(identifier, deviceId), PQSource.ROW)))
.thenCompose(maybeSingleUsePreKey -> maybeSingleUsePreKey
.map(singleUsePreKey -> CompletableFuture.completedFuture(maybeSingleUsePreKey))
.map(_ -> CompletableFuture.completedFuture(maybeSingleUsePreKey))
.orElseGet(() -> tagTakePQ(pqLastResortKeys.find(identifier, deviceId), PQSource.LAST_RESORT)));
}
private enum PQSource {
PAGE,
ROW,
LAST_RESORT
}
private CompletableFuture<Optional<KEMSignedPreKey>> tagTakePQ(CompletableFuture<Optional<KEMSignedPreKey>> prekey, final PQSource source) {
@@ -163,15 +154,12 @@ public class KeysManager {
}
public CompletableFuture<Integer> getPqCount(final UUID identifier, final byte deviceId) {
// We only return the paged prekey count to encourage clients to upload more prekeys if they only have prekeys
// stored in the previous key store format
return pagedPqPreKeys.getCount(identifier, deviceId);
}
public CompletableFuture<Void> deleteSingleUsePreKeys(final UUID identifier) {
return CompletableFuture.allOf(
ecPreKeys.delete(identifier),
pqPreKeys.delete(identifier),
pagedPqPreKeys.delete(identifier)
);
}
@@ -179,7 +167,6 @@ public class KeysManager {
public CompletableFuture<Void> deleteSingleUsePreKeys(final UUID accountUuid, final byte deviceId) {
return CompletableFuture.allOf(
ecPreKeys.delete(accountUuid, deviceId),
pqPreKeys.delete(accountUuid, deviceId),
pagedPqPreKeys.delete(accountUuid, deviceId)
);
}
@@ -5,8 +5,8 @@
package org.whispersystems.textsecuregcm.storage;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import static io.micrometer.core.instrument.Metrics.timer;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableMap;
@@ -30,9 +30,6 @@ import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
@@ -51,9 +48,6 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
@VisibleForTesting
static final String KEY_SORT = "S";
@VisibleForTesting
static final String LOCAL_INDEX_MESSAGE_UUID_NAME = "Message_UUID_Index";
@VisibleForTesting
static final String LOCAL_INDEX_MESSAGE_UUID_KEY_SORT = "U";
@@ -69,7 +63,6 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
private final String tableName;
private final Duration timeToLive;
private final ExecutorService messageDeletionExecutor;
private final Scheduler messageDeletionScheduler;
private final ExperimentEnrollmentManager experimentEnrollmentManager;
private static final Logger logger = LoggerFactory.getLogger(MessagesDynamoDb.class);
@@ -84,7 +77,6 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
this.timeToLive = timeToLive;
this.messageDeletionExecutor = messageDeletionExecutor;
this.messageDeletionScheduler = Schedulers.fromExecutor(messageDeletionExecutor);
this.experimentEnrollmentManager = experimentEnrollmentManager;
}
@@ -164,48 +156,6 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
.filter(Predicate.not(Objects::isNull));
}
public CompletableFuture<Optional<MessageProtos.Envelope>> deleteMessageByDestinationAndGuid(
final UUID destinationAccountUuid, final Device destinationDevice, final UUID messageUuid) {
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid, destinationDevice);
final QueryRequest queryRequest = QueryRequest.builder()
.tableName(tableName)
.indexName(LOCAL_INDEX_MESSAGE_UUID_NAME)
.projectionExpression(KEY_SORT)
.consistentRead(true)
.keyConditionExpression("#part = :part AND #uuid = :uuid")
.expressionAttributeNames(Map.of(
"#part", KEY_PARTITION,
"#uuid", LOCAL_INDEX_MESSAGE_UUID_KEY_SORT))
.expressionAttributeValues(Map.of(
":part", partitionKey,
":uuid", convertLocalIndexMessageUuidSortKey(messageUuid)))
.build();
// because we are filtering on message UUID, this query should return at most one item,
// but it’s simpler to handle the full stream and return the “last” item
return Flux.from(dbAsyncClient.queryPaginator(queryRequest).items())
.flatMap(item -> Mono.fromCompletionStage(dbAsyncClient.deleteItem(DeleteItemRequest.builder()
.tableName(tableName)
.key(Map.of(KEY_PARTITION, partitionKey, KEY_SORT,
AttributeValues.fromByteArray(item.get(KEY_SORT).b().asByteArray())))
.returnValues(ReturnValue.ALL_OLD)
.build())))
.mapNotNull(deleteItemResponse -> {
try {
if (deleteItemResponse.attributes() != null && deleteItemResponse.attributes().containsKey(KEY_PARTITION)) {
return convertItemToEnvelope(deleteItemResponse.attributes(), experimentEnrollmentManager);
}
} catch (final InvalidProtocolBufferException e) {
logger.error("Failed to parse envelope", e);
}
return null;
})
.map(Optional::ofNullable)
.subscribeOn(messageDeletionScheduler)
.last(Optional.empty()) // if the flux is empty, last() will throw without a default
.toFuture();
}
public CompletableFuture<Optional<MessageProtos.Envelope>> deleteMessage(final UUID destinationAccountUuid,
final Device destinationDevice, final UUID messageUuid, final long serverTimestamp) {
DeleteItemRequest.Builder deleteItemRequest = DeleteItemRequest.builder()
@@ -28,7 +28,6 @@ import org.reactivestreams.Publisher;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
@@ -253,26 +252,17 @@ public class MessagesManager {
return messagesCache.clear(destinationUuid, deviceId);
}
public CompletableFuture<Optional<RemovedMessage>> delete(UUID destinationUuid, Device destinationDevice, UUID guid,
@Nullable Long serverTimestamp) {
public CompletableFuture<Optional<RemovedMessage>> delete(final UUID destinationUuid,
final Device destinationDevice,
final UUID guid,
final long serverTimestamp) {
return messagesCache.remove(destinationUuid, destinationDevice.getId(), guid)
.thenComposeAsync(removed -> {
if (removed.isPresent()) {
return CompletableFuture.completedFuture(removed);
}
final CompletableFuture<Optional<MessageProtos.Envelope>> maybeDeletedEnvelope;
if (serverTimestamp == null) {
maybeDeletedEnvelope = messagesDynamoDb.deleteMessageByDestinationAndGuid(destinationUuid,
destinationDevice, guid);
} else {
maybeDeletedEnvelope = messagesDynamoDb.deleteMessage(destinationUuid, destinationDevice, guid,
serverTimestamp);
}
return maybeDeletedEnvelope.thenApply(maybeEnvelope -> maybeEnvelope.map(RemovedMessage::fromEnvelope));
}, messageDeletionExecutor);
.thenComposeAsync(removed -> removed
.map(_ -> CompletableFuture.completedFuture(removed))
.orElseGet(() -> messagesDynamoDb.deleteMessage(destinationUuid, destinationDevice, guid, serverTimestamp)
.thenApply(maybeEnvelope -> maybeEnvelope.map(RemovedMessage::fromEnvelope))
), messageDeletionExecutor);
}
/**
@@ -51,11 +51,11 @@ import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Object;
/**
* @implNote This version of a {@link SingleUsePreKeyStore} store bundles prekeys into "pages", which are stored in on
* @implNote This an analog of {@link SingleUseECPreKeyStore} store bundles prekeys into "pages", which are stored in on
* an object store and referenced via dynamodb. Each device may only have a single active page at a time. Crashes or
* errors may leave orphaned pages which are no longer referenced by the database. A background process must
* periodically check for orphaned pages and remove them.
* @see SingleUsePreKeyStore
* @see SingleUseECPreKeyStore
*/
public class PagedSingleUseKEMPreKeyStore {
Loaded 100 of 208 files, more files were not shown because too many files have changed in this diff. Show more