Compare commits

...
Author SHA1 Message Date
Jon Chambers 175c9ad823 Remove DynamicConfigurationManager (unused) from AccountsManager 2026-02-27 17:25:56 -05:00
Ravi Khadiwala 13c017c869 Update to the latest version of the spam filter 2026-02-27 16:24:53 -06:00
ravi-signal f872ade347 Remove ChallengeRequired variants from sealed-sender gRPC responses 2026-02-27 16:01:44 -06:00
Jon Chambers 80893152c9 Remove reactor-grpc as a dependency 2026-02-27 16:59:36 -05:00
Chris Eager 6d87b24ba3 Remove deprecated X-Signal-Key header 2026-02-27 15:50:38 -06:00
Jon Chambers 065809e34f Use simple-grpc in KeysGrpcService and KeysAnonymousGrpcService 2026-02-27 16:49:15 -05:00
Jon Chambers c63cbc304f Use simple-grpc in DevicesGrpcService 2026-02-26 17:31:13 -05:00
Jon Chambers 5d306f8d15 Make username-related operations blocking 2026-02-26 17:20:34 -05:00
Jon Chambers ad9c03186a Use simple-grpc in AccountsGrpcService/AccountsAnonymousGrpcService 2026-02-26 17:08:54 -05:00
Jon Chambers 69825dd2a4 Remove unused ClientPublicKeys infrastructure
We're planning on using a different authentication strategy for gRPC
2026-02-26 17:08:05 -05:00
Ravi Khadiwala c8d4ea97e4 Make GrpcAllowListInterceptor dynamically configurable 2026-02-24 16:44:05 -05:00
Ravi Khadiwala f17a39386b Rearrange gRPC interceptor ordering 2026-02-24 16:40:07 -05:00
Ravi Khadiwala 77c4962db8 Don't reuse metadata in ServerInterceptorUtil 2026-02-24 16:40:07 -05:00
Jon Chambers eedc4e23fe Use simple-grpc for PaymentsGrpcService 2026-02-24 16:36:23 -05:00
Chris Eager b43e63c6f0 Update to the latest version of the spam filter 2026-02-24 15:33:59 -06:00
Katherine b318dd2db7 Remove support for searching identifiers by version 2026-02-24 16:33:48 -05:00
Chris Eager 5b3679f56e Update to the latest version of the spam filter 2026-02-23 12:38:34 -06:00
Ravi Khadiwala 8f13beb53b Increse SVR credential validity period to match max account idle duration 2026-02-23 13:38:20 -05:00
Chris Eager c0432d828d Handle MCC-only HLR responses 2026-02-23 12:37:49 -06:00
Jon Chambers f390aabb3a Add "additional specifiers" dimensions to open WebSocket counters and simplify meter construction 2026-02-20 16:33:21 -05:00
Jon Chambers cb3363410c Revert "Add tags from "additional specifiers" to requests-by-version counter"
This reverts commit e0632e9800.
2026-02-20 16:33:21 -05:00
Ravi Khadiwala 1d1570464d Fix one missed int32->uint32 cdn number conversion 2026-02-20 16:18:02 -05:00
Chris Eager 541e93fc98 Remove explicit percentile configuration 2026-02-20 15:12:44 -06:00
Chris Eager d87cf01a9b Use default distribution statistic config as parent 2026-02-20 15:12:26 -06:00
Chris Eager b61c7e2345 Update to the latest version of the spam filter 2026-02-20 15:11:22 -06:00
Ravi Khadiwala 2137fc519d Split BackupInfo RPC into media/message variants 2026-02-19 13:34:21 -05:00
Ravi Khadiwala f7922856fe Use consistent success indicator in backups.proto 2026-02-19 13:34:21 -05:00
Jon Chambers 99c811273b Correctly parse iOS/Android additional specifiers 2026-02-19 12:59:54 -05:00
Jon Chambers ac5b62478c Add a (failing!) test for parsing OS information for iOS/Android 2026-02-19 12:59:54 -05:00
ravi-signalandJon Chambers 207d95dfdd Select only matching entitlements from storekit list
Co-authored-by: Jon Chambers <63609320+jon-signal@users.noreply.github.com>
2026-02-19 11:59:11 -06:00
Jon Chambers c78541f00b Update to the latest version of the spam filter 2026-02-18 13:46:22 -05:00
Jon Chambers 6b9734f70f Add an "is disposable?" field to CarrierData 2026-02-18 13:31:55 -05:00
Ravi Khadiwala a99635fbee Actually use updated account in getBackupAuthCredentials 2026-02-18 13:31:35 -05:00
Jon Chambers e0632e9800 Add tags from "additional specifiers" to requests-by-version counter 2026-02-18 13:30:50 -05:00
Jon Chambers 24029ef00c Add a utility method to get OS, OS version, and libsignal version tags from UA additional specifiers 2026-02-18 13:30:50 -05:00
Jon Chambers 5ffcdb1c3f Avoid unnecessary re-parsing of User-Agent strings 2026-02-18 13:21:12 -05:00
Jon Chambers d659af566b Remove utility method for testing if clients are using libsignal networking 2026-02-18 13:07:45 -05:00
Ravi Khadiwala 5850eeb87b Avoid reading modified account when generating backup credentials 2026-02-17 15:23:57 -05:00
Chris Eager 368e705b68 Migrate one-time donations tests to OneTimeDonationControllerTest 2026-02-17 13:58:56 -06:00
Chris Eager 39beb59b58 Add PayPalLineItemInput with localized description 2026-02-17 13:58:56 -06:00
Chris Eager 118b1d31cf Update apollo-client-maven-plugin to 7.1.0 2026-02-17 13:58:56 -06:00
Chris Eager 24a483a689 Update to the latest version of the spam filter 2026-02-17 13:58:24 -06:00
Chris Eager 183cbab4f3 Remove duplicate integration AccountTest#testCreateAccountAtomic 2026-02-17 13:58:09 -06:00
ravi-signal 81031b7b2f Ensure details are included on all gRPC error statuses 2026-02-17 13:54:16 -06:00
Ravi Khadiwala d6a0129c5a Treat missing backup after authentication as an authentication failure 2026-02-17 14:52:27 -05:00
Ravi Khadiwala 225e756e38 cdn number can be unsigned 2026-02-17 14:52:27 -05:00
Ameya Lokare f5a3b93849 Improve captcha response error handling 2026-02-12 11:57:27 -08:00
Ravi Khadiwala 8fa1f85924 Update to the latest version of the spam filter 2026-02-11 16:44:13 -06:00
Ravi Khadiwala 809ba29ce8 Update error model in messages.proto 2026-02-11 16:35:38 -06:00
Ravi Khadiwala 1009f3ba51 Update error model in keys.proto 2026-02-11 16:33:04 -06:00
Ravi Khadiwala 8804f28cb8 Update error model in device.proto 2026-02-11 17:21:42 -05:00
Chris Eager a9f81e2ba6 Update to the latest version of the spam filter 2026-02-09 12:35:55 -06:00
ravi-signal 7e9da6d7ce Add a request tag for listen port 2026-02-05 16:18:09 -06:00
Ravi Khadiwala ea80077c25 Fix incorrect comment in account.proto 2026-02-05 17:17:24 -05:00
Chris Eager 0ab471f7dd Update to the latest version of the spam filter 2026-02-05 16:07:03 -06:00
Chris Eager fa9fb1f0a2 Move inline versions to properties in service/pom.xml 2026-02-05 15:53:25 -06:00
Chris Eager 800902414f Update libphonenumber geocoder to 3.23 2026-02-05 15:53:25 -06:00
Chris Eager c13a34b2c8 Improve SchedulingUtil.getZoneId for PhoneNumberType.UNKONWN numbers 2026-02-05 15:51:41 -06:00
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
194 changed files with 4302 additions and 3908 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) {
@@ -45,19 +45,6 @@ public class AccountTest {
}
}
@Test
public void testCreateAccountAtomic() {
final TestUser user = Operations.newRegisteredUser("+19995550201");
try {
final Pair<Integer, AccountIdentityResponse> execute = Operations.apiGet("/v1/accounts/whoami")
.authorized(user)
.execute(AccountIdentityResponse.class);
assertEquals(HttpStatus.SC_OK, execute.getLeft());
} finally {
Operations.deleteUser(user);
}
}
@Test
public void changePhoneNumber() {
final TestUser user = Operations.newRegisteredUser("+19995550301");
-14
View File
@@ -81,7 +81,6 @@
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>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>
@@ -151,11 +150,6 @@
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.salesforce.servicelibs</groupId>
<artifactId>reactor-grpc-stub</artifactId>
<version>${reactive.grpc.version}</version>
</dependency>
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-bom</artifactId>
@@ -483,14 +477,6 @@
<pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact>
<protocPlugins>
<protocPlugin>
<id>reactor-grpc</id>
<groupId>com.salesforce.servicelibs</groupId>
<artifactId>reactor-grpc</artifactId>
<version>${reactive.grpc.version}</version>
<mainClass>com.salesforce.reactorgrpc.ReactorGrpcGenerator</mainClass>
</protocPlugin>
<protocPlugin>
<id>simple</id>
<groupId>org.signal</groupId>
+16 -14
View File
@@ -11,12 +11,18 @@
<artifactId>service</artifactId>
<properties>
<apollo-api-jvm.version>3.8.5</apollo-api-jvm.version>
<commons-compress.version>1.28.0</commons-compress.version>
<dynamodb-lock-client.version>1.4.0</dynamodb-lock-client.version>
<firebase-admin.version>9.7.0</firebase-admin.version>
<java-uuid-generator.version>5.2.0</java-uuid-generator.version>
<libphonenumber-geocoder.version>3.23</libphonenumber-geocoder.version>
<google-androidpublisher.version>v3-rev20250904-2.0.0</google-androidpublisher.version>
<java-jwt.version>4.5.0</java-jwt.version>
<java-uuid-generator.version>5.2.0</java-uuid-generator.version>
<!-- *all* opentelemetry-logback-appender versions are "alpha" despite the advanced version number -->
<opentelemetry-logback-appender-1.0.version>2.22.0-alpha</opentelemetry-logback-appender-1.0.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>
<dependencies>
@@ -204,8 +210,7 @@
<dependency>
<groupId>io.opentelemetry.instrumentation</groupId>
<artifactId>opentelemetry-logback-appender-1.0</artifactId>
<!-- *all* opentelemetry-logback-appender versions are "alpha" despite the advanced version number -->
<version>2.22.0-alpha</version>
<version>${opentelemetry-logback-appender-1.0.version}</version>
<exclusions>
<!-- incubator packages aren't included in the opentelemetry BOM, and we don't use them -->
<exclusion>
@@ -260,7 +265,7 @@
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.28.0</version>
<version>${commons-compress.version}</version>
</dependency>
<dependency>
@@ -356,11 +361,6 @@
<artifactId>jackson-jaxrs-json-provider</artifactId>
</dependency>
<dependency>
<groupId>com.salesforce.servicelibs</groupId>
<artifactId>reactor-grpc-stub</artifactId>
</dependency>
<dependency>
<groupId>org.foundationdb</groupId>
<artifactId>fdb-java</artifactId>
@@ -389,7 +389,7 @@
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>dynamodb-lock-client</artifactId>
<version>1.4.0</version>
<version>${dynamodb-lock-client.version}</version>
</dependency>
<dependency>
@@ -431,7 +431,7 @@
<dependency>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>geocoder</artifactId>
<version>3.14</version>
<version>${libphonenumber-geocoder.version}</version>
</dependency>
<dependency>
@@ -536,7 +536,7 @@
<dependency>
<groupId>com.apollographql.apollo3</groupId>
<artifactId>apollo-api-jvm</artifactId>
<version>3.8.5</version>
<version>${apollo-api-jvm.version}</version>
<exclusions>
<exclusion>
@@ -828,7 +828,7 @@
<plugin>
<groupId>com.github.aoudiamoncef</groupId>
<artifactId>apollo-client-maven-plugin</artifactId>
<version>5.0.0</version>
<version>7.1.0</version>
<executions>
<execution>
<goals>
@@ -841,6 +841,8 @@
<name>braintree</name>
<compilerParams>
<schemaPackageName>com.braintree.graphql.client</schemaPackageName>
<!-- override the default in 7.1.0, see https://github.com/aoudiamoncef/apollo-client-maven-plugin/issues/84 -->
<operationManifestFormat>none</operationManifestFormat>
</compilerParams>
</compilationUnit>
</braintree>
@@ -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.dynamic.DynamicGrpcAllowListConfiguration;
import org.whispersystems.textsecuregcm.configuration.ExternalRequestFilterConfiguration;
import org.whispersystems.textsecuregcm.configuration.FaultTolerantRedisClientFactory;
import org.whispersystems.textsecuregcm.configuration.FaultTolerantRedisClusterFactory;
@@ -348,6 +349,11 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private GrpcConfiguration grpc;
@NotNull
@Valid
@JsonProperty
private DynamicGrpcAllowListConfiguration grpcAllowList = new DynamicGrpcAllowListConfiguration();
@Valid
@NotNull
@JsonProperty
@@ -589,6 +595,10 @@ public class WhisperServerConfiguration extends Configuration {
return grpc;
}
public DynamicGrpcAllowListConfiguration getGrpcAllowList() {
return grpcAllowList;
}
public S3ObjectMonitorFactory getAsnTableConfiguration() {
return asnTable;
}
@@ -143,15 +143,15 @@ 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.ErrorConformanceInterceptor;
import org.whispersystems.textsecuregcm.grpc.ErrorMappingInterceptor;
import org.whispersystems.textsecuregcm.grpc.ExternalServiceCredentialsAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.ExternalServiceCredentialsGrpcService;
import org.whispersystems.textsecuregcm.grpc.GrpcAllowListInterceptor;
import org.whispersystems.textsecuregcm.grpc.KeysAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.KeysGrpcService;
import org.whispersystems.textsecuregcm.grpc.MetricServerInterceptor;
import org.whispersystems.textsecuregcm.grpc.PaymentsGrpcService;
import org.whispersystems.textsecuregcm.grpc.ProfileAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.ProfileGrpcService;
import org.whispersystems.textsecuregcm.grpc.RequestAttributesInterceptor;
import org.whispersystems.textsecuregcm.grpc.ValidatingInterceptor;
import org.whispersystems.textsecuregcm.grpc.net.ManagedGrpcServer;
@@ -209,7 +209,6 @@ import org.whispersystems.textsecuregcm.s3.S3MonitoringSupplier;
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient;
import org.whispersystems.textsecuregcm.spam.ChallengeConstraintChecker;
import org.whispersystems.textsecuregcm.spam.MessageDeliveryListener;
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
import org.whispersystems.textsecuregcm.spam.RegistrationRecoveryChecker;
import org.whispersystems.textsecuregcm.spam.SpamChecker;
@@ -218,8 +217,6 @@ import org.whispersystems.textsecuregcm.storage.AccountLockManager;
import org.whispersystems.textsecuregcm.storage.Accounts;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
import org.whispersystems.textsecuregcm.storage.ClientPublicKeys;
import org.whispersystems.textsecuregcm.storage.ClientPublicKeysManager;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import org.whispersystems.textsecuregcm.storage.ClientReleases;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
@@ -257,6 +254,7 @@ import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator;
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator;
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
import org.whispersystems.textsecuregcm.telephony.CarrierDataProvider;
import org.whispersystems.textsecuregcm.telephony.hlrlookup.HlrLookupCarrierDataProvider;
@@ -418,6 +416,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
ConfiguredProfileBadgeConverter profileBadgeConverter = new ConfiguredProfileBadgeConverter(
clock, config.getBadges(), headerControlledResourceBundleLookup);
BankMandateTranslator bankMandateTranslator = new BankMandateTranslator(headerControlledResourceBundleLookup);
PayPalDonationsTranslator payPalDonationsTranslator =
new PayPalDonationsTranslator(headerControlledResourceBundleLookup);
environment.lifecycle().manage(new ManagedAwsCrt());
@@ -495,8 +495,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getDynamoDbTables().getRegistrationRecovery().getExpiration(),
dynamoDbAsyncClient,
clock);
ClientPublicKeys clientPublicKeys =
new ClientPublicKeys(dynamoDbAsyncClient, config.getDynamoDbTables().getClientPublicKeys().getTableName());
final VerificationSessions verificationSessions = new VerificationSessions(dynamoDbAsyncClient,
config.getDynamoDbTables().getVerificationSessions().getTableName(), clock);
@@ -689,13 +687,11 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
reportMessageManager, messageDeletionAsyncExecutor, Clock.systemUTC());
AccountLockManager accountLockManager = new AccountLockManager(dynamoDbClient,
config.getDynamoDbTables().getDeletedAccountsLock().getTableName());
ClientPublicKeysManager clientPublicKeysManager =
new ClientPublicKeysManager(clientPublicKeys, accountLockManager, accountLockExecutor);
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
pubsubClient, accountLockManager, keysManager, messagesManager, profilesManager,
secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
registrationRecoveryPasswordsManager, clientPublicKeysManager, accountLockExecutor, messagePollExecutor,
retryExecutor, clock, config.getLinkDeviceSecretConfiguration().secret().value(), dynamicConfigurationManager);
registrationRecoveryPasswordsManager, accountLockExecutor, messagePollExecutor,
retryExecutor, clock, config.getLinkDeviceSecretConfiguration().secret().value());
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs);
APNSender apnSender = new APNSender(apnSenderExecutor, config.getApnConfiguration());
FcmSender fcmSender = new FcmSender(fcmSenderExecutor, config.getFcmConfiguration().credentials().value());
@@ -877,6 +873,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final MetricServerInterceptor metricServerInterceptor = new MetricServerInterceptor(Metrics.globalRegistry, clientReleaseManager);
final ErrorMappingInterceptor errorMappingInterceptor = new ErrorMappingInterceptor();
final ErrorConformanceInterceptor errorConformanceInterceptor = new ErrorConformanceInterceptor();
final GrpcAllowListInterceptor grpcAllowListInterceptor = new GrpcAllowListInterceptor(dynamicConfigurationManager);
final RequestAttributesInterceptor requestAttributesInterceptor = new RequestAttributesInterceptor();
final ValidatingInterceptor validatingInterceptor = new ValidatingInterceptor();
@@ -890,16 +888,16 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final List<ServerServiceDefinition> authenticatedServices = Stream.of(
new AccountsGrpcService(accountsManager, rateLimiters, usernameHashZkProofVerifier, registrationRecoveryPasswordsManager),
ExternalServiceCredentialsGrpcService.createForAllExternalServices(config, rateLimiters),
new KeysGrpcService(accountsManager, keysManager, rateLimiters),
new ProfileGrpcService(clock, accountsManager, profilesManager, dynamicConfigurationManager,
config.getBadges(), profileCdnPolicyGenerator, profileCdnPolicySigner, profileBadgeConverter, rateLimiters, zkProfileOperations))
new KeysGrpcService(accountsManager, keysManager, rateLimiters))
.map(bindableService -> ServerInterceptors.intercept(bindableService,
// 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,
metricServerInterceptor,
errorMappingInterceptor,
errorConformanceInterceptor,
grpcAllowListInterceptor,
remoteDeprecationFilter,
metricServerInterceptor,
requestAttributesInterceptor,
requireAuthenticationInterceptor))
.toList();
@@ -909,16 +907,17 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new CallQualitySurveyGrpcService(callQualitySurveyManager, rateLimiters),
new KeysAnonymousGrpcService(accountsManager, keysManager, zkSecretParams, Clock.systemUTC()),
new PaymentsGrpcService(currencyManager),
ExternalServiceCredentialsAnonymousGrpcService.create(accountsManager, config),
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, zkSecretParams))
ExternalServiceCredentialsAnonymousGrpcService.create(accountsManager, config))
.map(bindableService -> ServerInterceptors.intercept(bindableService,
// 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!
grpcExternalRequestFilter,
validatingInterceptor,
metricServerInterceptor,
errorMappingInterceptor,
errorConformanceInterceptor,
grpcAllowListInterceptor,
remoteDeprecationFilter,
metricServerInterceptor,
requestAttributesInterceptor,
prohibitAuthenticationInterceptor))
.toList();
@@ -1090,7 +1089,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
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()),
new DeviceController(accountsManager, rateLimiters, persistentTimer, config.getMaxDevices()),
new DeviceCheckController(clock, accountsManager, backupAuthManager, appleDeviceCheckManager, rateLimiters,
config.getDeviceCheck().backupRedemptionLevel(),
config.getDeviceCheck().backupRedemptionDuration()),
@@ -1130,7 +1129,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
subscriptionManager, stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager,
profileBadgeConverter, bankMandateTranslator, dynamicConfigurationManager));
commonControllers.add(new OneTimeDonationController(clock, config.getOneTimeDonations(), stripeManager, braintreeManager,
zkReceiptOperations, issuedReceiptsManager, oneTimeDonationsManager));
payPalDonationsTranslator, zkReceiptOperations, issuedReceiptsManager, oneTimeDonationsManager));
}
for (Object controller : commonControllers) {
@@ -1140,7 +1139,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
WebSocketEnvironment<AuthenticatedDevice> provisioningEnvironment = new WebSocketEnvironment<>(environment,
webSocketEnvironment.getRequestLog(), Duration.ofMillis(60000));
provisioningEnvironment.setConnectListener(new ProvisioningConnectListener(provisioningManager, provisioningWebsocketTimeoutExecutor, Duration.ofSeconds(90)));
provisioningEnvironment.setConnectListener(new ProvisioningConnectListener(provisioningManager, clientReleaseManager, provisioningWebsocketTimeoutExecutor, Duration.ofSeconds(90)));
provisioningEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET, clientReleaseManager));
provisioningEnvironment.jersey().register(new KeepAliveController(redisMessageAvailabilityManager));
provisioningEnvironment.jersey().register(new TimestampResponseFilter());
@@ -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));
}
}
@@ -125,7 +125,6 @@ public class RegistrationLockVerificationManager {
final DistributionSummary registrationLockIdleDays = DistributionSummary
.builder(name(RegistrationLockVerificationManager.class, "registrationLockIdleDays"))
.tags(additionalTags)
.publishPercentiles(0.75, 0.95, 0.99, 0.999)
.distributionStatisticExpiry(Duration.ofHours(2))
.register(Metrics.globalRegistry);
@@ -153,7 +152,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();
@@ -14,7 +14,9 @@ import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
@@ -183,49 +185,53 @@ public class BackupAuthManager {
* voucher's expiration will include paid backup access. If the BackupVoucher exists but is already expired, this
* method will also remove the expired voucher from the account.
*
* @param account The account to create the credentials for
* @param credentialType The type of backup credentials to create
* @param originalAccount The account to create the credentials for
* @param redemptionRange The time range to return credentials for
* @return Credentials and the day on which they may be redeemed
*/
public List<Credential> getBackupAuthCredentials(
final Account account,
final BackupCredentialType credentialType,
public Map<BackupCredentialType, List<Credential>> getBackupAuthCredentials(
final Account originalAccount,
final RedemptionRange redemptionRange) throws BackupNotFoundException {
// If the account has an expired payment, clear it before continuing
if (hasExpiredVoucher(account)) {
final Account updated = accountsManager.update(account, a -> {
final Account account;
if (hasExpiredVoucher(originalAccount)) {
account = accountsManager.update(originalAccount, a -> {
// Re-check in case we raced with an update
if (hasExpiredVoucher(a)) {
a.setBackupVoucher(null);
}
});
return getBackupAuthCredentials(updated, credentialType, redemptionRange);
} else {
account = originalAccount;
}
// fetch the blinded backup-id the account should have previously committed to
final byte[] committedBytes = account.getBackupCredentialRequest(credentialType)
.orElseThrow(() -> new BackupNotFoundException("No blinded backup-id has been added to the account"));
final Map<BackupCredentialType, List<Credential>> credentials = new HashMap<>();
for (BackupCredentialType credentialType : BackupCredentialType.values()) {
// fetch the blinded backup-id the account should have previously committed to
final byte[] committedBytes = account.getBackupCredentialRequest(credentialType)
.orElseThrow(() -> new BackupNotFoundException("No blinded backup-id has been added to the account"));
try {
final BackupLevel defaultBackupLevel = configuredBackupLevel(account);
try {
final BackupLevel defaultBackupLevel = configuredBackupLevel(account);
// create a credential for every day in the requested period
final BackupAuthCredentialRequest credentialReq = new BackupAuthCredentialRequest(committedBytes);
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
final BackupLevel backupLevel = storedBackupLevel(account, redemptionTime).orElse(defaultBackupLevel);
return new Credential(
credentialReq.issueCredential(redemptionTime, backupLevel, credentialType, serverSecretParams),
redemptionTime);
})
.toList();
} catch (InvalidInputException e) {
throw new UncheckedIOException(new IOException("Could not deserialize stored request credential", e));
// create a credential for every day in the requested period
final BackupAuthCredentialRequest credentialReq = new BackupAuthCredentialRequest(committedBytes);
final List<Credential> credentialList = StreamSupport.stream(redemptionRange.spliterator(), false)
.map(redemptionTime -> {
// Check if the account has a voucher that's good for a certain receiptLevel at redemption time, otherwise
// use the default receipt level
final BackupLevel backupLevel = storedBackupLevel(account, redemptionTime).orElse(defaultBackupLevel);
return new Credential(
credentialReq.issueCredential(redemptionTime, backupLevel, credentialType, serverSecretParams),
redemptionTime);
})
.toList();
credentials.put(credentialType, credentialList);
} catch (InvalidInputException e) {
throw new UncheckedIOException(new IOException("Could not deserialize stored request credential", e));
}
}
return credentials;
}
/**
@@ -210,12 +210,10 @@ public class BackupManager {
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());
}
@@ -230,13 +228,12 @@ 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
* @throws BackupFailedZkAuthenticationException if the provided backupuser does not exist
*/
public BackupInfo backupInfo(final AuthenticatedBackupUser backupUser)
throws BackupNotFoundException, BackupPermissionException {
public BackupInfo backupInfo(final AuthenticatedBackupUser backupUser) throws BackupPermissionException, BackupFailedZkAuthenticationException {
checkBackupLevel(backupUser, BackupLevel.FREE);
final BackupsDb.BackupDescription backupDescription = ExceptionUtils.unwrapSupply(
BackupNotFoundException.class,
BackupFailedZkAuthenticationException.class,
() -> backupsDb.describeBackup(backupUser).join());
return new BackupInfo(
backupDescription.cdn(),
@@ -730,7 +727,6 @@ public class BackupManager {
concurrentDeletes)
.count()
.doOnSuccess(itemsRemoved -> DistributionSummary.builder(DELETE_COUNT_DISTRIBUTION_NAME)
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry)
.record(itemsRemoved))
.then()
@@ -331,7 +331,9 @@ public class BackupsDb {
.build())
.thenApply(response -> {
if (!response.hasItem()) {
throw ExceptionUtils.wrap(new BackupNotFoundException("Backup ID not found"));
// At this point, the user has already authenticated against this backup record, so we must have raced
// with a deletion. Just throw the same error we would have thrown if authentication had failed
throw ExceptionUtils.wrap(new BackupFailedZkAuthenticationException("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);
@@ -72,6 +72,10 @@ public class DynamicConfiguration {
@Valid
private DynamicCarrierDataLookupConfiguration carrierDataLookup = new DynamicCarrierDataLookupConfiguration();
@JsonProperty
@Valid
private DynamicGrpcAllowListConfiguration grpcAllowList = new DynamicGrpcAllowListConfiguration();
public Optional<DynamicExperimentEnrollmentConfiguration> getExperimentEnrollmentConfiguration(
final String experimentName) {
return Optional.ofNullable(experiments.get(experimentName));
@@ -129,4 +133,8 @@ public class DynamicConfiguration {
public DynamicCarrierDataLookupConfiguration getCarrierDataLookupConfiguration() {
return carrierDataLookup;
}
public DynamicGrpcAllowListConfiguration getGrpcAllowList() {
return grpcAllowList;
}
}
@@ -0,0 +1,38 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration.dynamic;
import java.util.Collections;
import java.util.List;
import java.util.Set;
/// 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 DynamicGrpcAllowListConfiguration(
boolean enableAll,
Set<String> enabledServices,
Set<String> enabledMethods) {
public DynamicGrpcAllowListConfiguration {
if (enabledServices == null) {
enabledServices = Collections.emptySet();
}
if (enabledMethods == null) {
enabledMethods = Collections.emptySet();
}
}
public DynamicGrpcAllowListConfiguration() {
// By default, no GRPC methods are accessible
this(false, Collections.emptySet(), Collections.emptySet());
}
}
@@ -4,7 +4,12 @@
*/
package org.whispersystems.textsecuregcm.controllers;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
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 +30,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,13 +62,13 @@ 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;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableException;
import org.whispersystems.textsecuregcm.storage.UsernameReservationNotFoundException;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
import org.whispersystems.textsecuregcm.util.Util;
@@ -75,6 +81,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 +249,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 +261,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 +273,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
@@ -287,12 +305,11 @@ public class AccountController {
)
@ApiResponse(responseCode = "204", description = "Username successfully deleted.", useReturnTypeSchema = true)
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
public CompletableFuture<Response> deleteUsernameHash(@Auth final AuthenticatedDevice auth) {
public void deleteUsernameHash(@Auth final AuthenticatedDevice auth) {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
return accounts.clearUsernameHash(account)
.thenApply(Util.ASYNC_EMPTY_RESPONSE);
accounts.clearUsernameHash(account);
}
@PUT
@@ -311,7 +328,7 @@ public class AccountController {
@ApiResponse(responseCode = "409", description = "All username hashes from the list are taken.")
@ApiResponse(responseCode = "422", description = "Invalid request format.")
@ApiResponse(responseCode = "429", description = "Ratelimited.")
public CompletableFuture<ReserveUsernameHashResponse> reserveUsernameHash(
public ReserveUsernameHashResponse reserveUsernameHash(
@Auth final AuthenticatedDevice auth,
@NotNull @Valid final ReserveUsernameHashRequest usernameRequest) throws RateLimitExceededException {
@@ -326,15 +343,14 @@ public class AccountController {
}
}
return accounts.reserveUsernameHash(account, usernameRequest.usernameHashes())
.thenApply(reservation -> new ReserveUsernameHashResponse(reservation.reservedUsernameHash()))
.exceptionally(throwable -> {
if (ExceptionUtils.unwrap(throwable) instanceof UsernameHashNotAvailableException) {
throw new WebApplicationException(Status.CONFLICT);
}
try {
final AccountsManager.UsernameReservation reservation =
accounts.reserveUsernameHash(account, usernameRequest.usernameHashes());
throw ExceptionUtils.wrap(throwable);
});
return new ReserveUsernameHashResponse(reservation.reservedUsernameHash());
} catch (final UsernameHashNotAvailableException e) {
throw new WebApplicationException(Status.CONFLICT);
}
}
@PUT
@@ -354,9 +370,9 @@ public class AccountController {
@ApiResponse(responseCode = "410", description = "Username hash not available (username can't be used).")
@ApiResponse(responseCode = "422", description = "Invalid request format.")
@ApiResponse(responseCode = "429", description = "Ratelimited.")
public CompletableFuture<UsernameHashResponse> confirmUsernameHash(
public UsernameHashResponse confirmUsernameHash(
@Auth final AuthenticatedDevice auth,
@NotNull @Valid final ConfirmUsernameHashRequest confirmRequest) {
@NotNull @Valid final ConfirmUsernameHashRequest confirmRequest) throws RateLimitExceededException {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
@@ -367,26 +383,22 @@ public class AccountController {
throw new WebApplicationException(Response.status(422).build());
}
return rateLimiters.getUsernameSetLimiter().validateAsync(account.getUuid())
.thenCompose(ignored -> accounts.confirmReservedUsernameHash(
account,
confirmRequest.usernameHash(),
confirmRequest.encryptedUsername()))
.thenApply(updatedAccount -> new UsernameHashResponse(updatedAccount.getUsernameHash()
.orElseThrow(() -> new IllegalStateException("Could not get username after setting")),
updatedAccount.getUsernameLinkHandle()))
.exceptionally(throwable -> {
if (ExceptionUtils.unwrap(throwable) instanceof UsernameReservationNotFoundException) {
throw new WebApplicationException(Status.CONFLICT);
}
rateLimiters.getUsernameSetLimiter().validate(account.getUuid());
if (ExceptionUtils.unwrap(throwable) instanceof UsernameHashNotAvailableException) {
throw new WebApplicationException(Status.GONE);
}
try {
final Account updatedAccount = accounts.confirmReservedUsernameHash(
account,
confirmRequest.usernameHash(),
confirmRequest.encryptedUsername());
throw ExceptionUtils.wrap(throwable);
})
.toCompletableFuture();
return new UsernameHashResponse(updatedAccount.getUsernameHash()
.orElseThrow(() -> new IllegalStateException("Could not get username after setting")),
updatedAccount.getUsernameLinkHandle());
} catch (final UsernameReservationNotFoundException e) {
throw new WebApplicationException(Status.CONFLICT);
} catch (UsernameHashNotAvailableException e) {
throw new WebApplicationException(Status.GONE);
}
}
@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)
@@ -15,6 +15,7 @@ import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.net.HttpHeaders;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.Tag;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
@@ -48,7 +49,6 @@ import java.lang.annotation.Target;
import java.time.Clock;
import java.time.Instant;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@@ -312,9 +312,6 @@ public class ArchiveController {
@NotNull @QueryParam("redemptionStartSeconds") Long startSeconds,
@NotNull @QueryParam("redemptionEndSeconds") Long endSeconds) throws BackupNotFoundException {
final Map<BackupCredentialType, List<BackupAuthCredentialsResponse.BackupAuthCredential>> credentialsByType =
new HashMap<>();
final RedemptionRange redemptionRange;
try {
redemptionRange = RedemptionRange.inclusive(Clock.systemUTC(), Instant.ofEpochSecond(startSeconds), Instant.ofEpochSecond(endSeconds));
@@ -325,23 +322,20 @@ public class ArchiveController {
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
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(
final Map<BackupCredentialType, List<BackupAuthManager.Credential>> credentials =
backupAuthManager.getBackupAuthCredentials(account, redemptionRange);
final Tag platformTag = UserAgentTagUtil.getPlatformTag(userAgent);
credentials.forEach((type, credentialList) ->
backupMetrics.updateGetCredentialCounter(platformTag, type, credentialList.size()));
return new BackupAuthCredentialsResponse(credentials.entrySet().stream().collect(Collectors.toMap(
e -> BackupAuthCredentialsResponse.CredentialType.fromLibsignalType(e.getKey()),
Map.Entry::getValue)));
e -> e.getValue().stream()
.map(credential -> new BackupAuthCredentialsResponse.BackupAuthCredential(
credential.credential().serialize(),
credential.redemptionTime().getEpochSecond()))
.toList())));
}
@@ -486,7 +480,6 @@ public class ArchiveController {
summary = "Fetch backup info",
description = "Retrieve information about the currently stored backup")
@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = BackupInfoResponse.class)))
@ApiResponse(responseCode = "404", description = "No existing backups found")
@ApiResponse(responseCode = "429", description = "Rate limited.")
@ApiResponseZkAuth
@ManagedAsync
@@ -501,7 +494,7 @@ public class ArchiveController {
@Parameter(description = BackupAuthCredentialPresentationSignature.DESCRIPTION, schema = @Schema(implementation = String.class))
@NotNull
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature)
throws BackupFailedZkAuthenticationException, BackupNotFoundException, BackupPermissionException {
throws BackupFailedZkAuthenticationException, BackupPermissionException {
if (account.isPresent()) {
throw new BadRequestException("must not use authenticated connection for anonymous operations");
}
@@ -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")
@@ -73,7 +74,7 @@ public class CallQualitySurveyController {
try {
callQualitySurveyManager.submitCallQualitySurvey(submitCallQualitySurveyRequest, remoteAddress, userAgentString);
} catch (final IllegalArgumentException e) {
} catch (final CallQualityInvalidArgumentsException e) {
throw new WebApplicationException(e.getMessage(), 422);
}
}
@@ -31,6 +31,8 @@ import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.entities.AnswerCaptchaChallengeRequest;
import org.whispersystems.textsecuregcm.entities.AnswerChallengeRequest;
@@ -52,6 +54,8 @@ public class ChallengeController {
private final RateLimitChallengeManager rateLimitChallengeManager;
private final ChallengeConstraintChecker challengeConstraintChecker;
private static final Logger logger = LoggerFactory.getLogger(ChallengeController.class);
private static final String CHALLENGE_RESPONSE_COUNTER_NAME = name(ChallengeController.class, "challengeResponse");
private static final String CHALLENGE_TYPE_TAG = "type";
@@ -85,8 +89,8 @@ public class ChallengeController {
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
public Response handleChallengeResponse(@Auth final AuthenticatedDevice auth,
@Valid final AnswerChallengeRequest answerRequest,
@Context ContainerRequestContext requestContext,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws RateLimitExceededException, IOException {
@Context final ContainerRequestContext requestContext,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws RateLimitExceededException {
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
@@ -103,12 +107,12 @@ public class ChallengeController {
return Response.status(429).build();
}
rateLimitChallengeManager.answerPushChallenge(account, pushChallengeRequest.getChallenge());
} else if (answerRequest instanceof AnswerCaptchaChallengeRequest captchaChallengeRequest) {
} else if (answerRequest instanceof final AnswerCaptchaChallengeRequest captchaChallengeRequest) {
tags = tags.and(CHALLENGE_TYPE_TAG, "captcha");
final String remoteAddress = (String) requestContext.getProperty(
RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
boolean success = rateLimitChallengeManager.answerCaptchaChallenge(
final boolean success = rateLimitChallengeManager.answerCaptchaChallenge(
account,
captchaChallengeRequest.getCaptcha(),
remoteAddress,
@@ -122,6 +126,9 @@ public class ChallengeController {
} else {
tags = tags.and(CHALLENGE_TYPE_TAG, "unrecognized");
}
} catch (final IOException e) {
logger.error("error assessing captcha during challenge response handling", e);
return Response.status(Response.Status.SERVICE_UNAVAILABLE).build();
} finally {
Metrics.counter(CHALLENGE_RESPONSE_COUNTER_NAME, tags).increment();
}
@@ -37,14 +37,12 @@ import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.atomic.AtomicInteger;
@@ -64,7 +62,6 @@ import org.whispersystems.textsecuregcm.entities.ProvisioningMessage;
import org.whispersystems.textsecuregcm.entities.RemoteAttachment;
import org.whispersystems.textsecuregcm.entities.RemoteAttachmentError;
import org.whispersystems.textsecuregcm.entities.RestoreAccountRequest;
import org.whispersystems.textsecuregcm.entities.SetPublicKeyRequest;
import org.whispersystems.textsecuregcm.entities.TransferArchiveUploadedRequest;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
@@ -74,7 +71,6 @@ import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.ClientPublicKeysManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.DeviceSpec;
@@ -96,7 +92,6 @@ public class DeviceController {
static final int MAX_DEVICES = 6;
private final AccountsManager accounts;
private final ClientPublicKeysManager clientPublicKeysManager;
private final RateLimiters rateLimiters;
private final PersistentTimer persistentTimer;
private final Map<String, Integer> maxDeviceConfiguration;
@@ -122,13 +117,11 @@ public class DeviceController {
static final int MAX_TOKEN_IDENTIFIER_LENGTH = 64;
public DeviceController(final AccountsManager accounts,
final ClientPublicKeysManager clientPublicKeysManager,
final RateLimiters rateLimiters,
final PersistentTimer persistentTimer,
final Map<String, Integer> maxDeviceConfiguration) {
this.accounts = accounts;
this.clientPublicKeysManager = clientPublicKeysManager;
this.rateLimiters = rateLimiters;
this.persistentTimer = persistentTimer;
this.maxDeviceConfiguration = maxDeviceConfiguration;
@@ -390,7 +383,6 @@ public class DeviceController {
if (response != null && response.getStatus() == Response.Status.OK.getStatusCode()) {
accountAndSample.second().stop(Timer.builder(WAIT_FOR_LINKED_DEVICE_TIMER_NAME)
.publishPercentileHistogram(true)
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)))
.register(Metrics.globalRegistry));
}
@@ -420,29 +412,6 @@ public class DeviceController {
d -> d.setCapabilities(DeviceCapabilityAdapter.mapToSet(capabilities)));
}
@PUT
@Produces(MediaType.APPLICATION_JSON)
@Path("/public_key")
@Operation(
summary = "Sets a public key for authentication",
description = """
Sets the authentication public key for the authenticated device. The public key will be used for
authentication in the nascent gRPC-over-Noise API. Existing devices must upload a public key before they can
use the gRPC-over-Noise API, and this endpoint exists to facilitate migration to the new API.
"""
)
@ApiResponse(responseCode = "200", description = "Public key stored successfully")
@ApiResponse(responseCode = "401", description = "Account authentication check failed")
@ApiResponse(responseCode = "422", description = "Invalid request format")
public CompletableFuture<Void> setPublicKey(@Auth final AuthenticatedDevice auth,
final SetPublicKeyRequest setPublicKeyRequest) {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
return clientPublicKeysManager.setPublicKey(account, auth.deviceId(), setPublicKeyRequest.publicKey());
}
private static boolean isCapabilityDowngrade(final Account account, final Set<DeviceCapability> capabilities) {
final Set<DeviceCapability> requiredCapabilities = Arrays.stream(DeviceCapability.values())
// `ALWAYS_CAPABLE` capabilities are always assumed to be present, so we don't require callers to specify them
@@ -602,7 +571,6 @@ public class DeviceController {
.whenComplete((response, throwable) -> {
if (response != null && response.getStatus() == Response.Status.OK.getStatusCode()) {
accountAndSample.second().stop(Timer.builder(WAIT_FOR_TRANSFER_ARCHIVE_TIMER_NAME)
.publishPercentileHistogram(true)
.tags(Tags.of(
UserAgentTagUtil.getPlatformTag(userAgent),
primaryPlatformTag(accountAndSample.first())))
@@ -60,7 +60,6 @@ public class KeepAliveController {
Timer.builder(CLOSED_CONNECTION_AGE_DISTRIBUTION_NAME)
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(context.getClient().getUserAgent())))
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry)
.record(age);
}
@@ -5,7 +5,6 @@
package org.whispersystems.textsecuregcm.controllers;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.ByteString;
import io.dropwizard.auth.Auth;
import io.grpc.Status;
@@ -29,7 +28,6 @@ import jakarta.ws.rs.ServerErrorException;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.time.Duration;
import java.util.Optional;
import org.glassfish.jersey.server.ManagedAsync;
import org.signal.keytransparency.client.AciMonitorRequest;
@@ -110,10 +108,7 @@ public class KeyTransparencyController {
request.usernameHash().map(ByteString::copyFrom),
maybeE164SearchRequest,
request.lastTreeHeadSize(),
request.distinguishedTreeHeadSize(),
request.aciVersion(),
request.e164Version(),
request.usernameHashVersion())
request.distinguishedTreeHeadSize())
.toByteArray());
} catch (final StatusRuntimeException exception) {
handleKeyTransparencyServiceError(exception);
@@ -147,18 +147,19 @@ public class MessageController {
INDIVIDUAL_MESSAGE_LATENCY_TIMER = Timer.builder(timerName)
.tags(multiRecipientTagName, "false")
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry);
MULTI_RECIPIENT_MESSAGE_LATENCY_TIMER = Timer.builder(timerName)
.tags(multiRecipientTagName, "true")
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry);
}
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.
@@ -584,6 +585,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
@@ -36,6 +36,7 @@ import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
@@ -57,6 +58,7 @@ import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator;
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails;
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
@@ -90,6 +92,7 @@ public class OneTimeDonationController {
private final OneTimeDonationConfiguration oneTimeDonationConfiguration;
private final StripeManager stripeManager;
private final BraintreeManager braintreeManager;
private final PayPalDonationsTranslator payPalDonationsTranslator;
private final ServerZkReceiptOperations zkReceiptOperations;
private final IssuedReceiptsManager issuedReceiptsManager;
private final OneTimeDonationsManager oneTimeDonationsManager;
@@ -99,6 +102,7 @@ public class OneTimeDonationController {
@Nonnull OneTimeDonationConfiguration oneTimeDonationConfiguration,
@Nonnull StripeManager stripeManager,
@Nonnull BraintreeManager braintreeManager,
@Nonnull PayPalDonationsTranslator payPalDonationsTranslator,
@Nonnull ServerZkReceiptOperations zkReceiptOperations,
@Nonnull IssuedReceiptsManager issuedReceiptsManager,
@Nonnull OneTimeDonationsManager oneTimeDonationsManager) {
@@ -106,6 +110,7 @@ public class OneTimeDonationController {
this.oneTimeDonationConfiguration = Objects.requireNonNull(oneTimeDonationConfiguration);
this.stripeManager = Objects.requireNonNull(stripeManager);
this.braintreeManager = Objects.requireNonNull(braintreeManager);
this.payPalDonationsTranslator = Objects.requireNonNull(payPalDonationsTranslator);
this.zkReceiptOperations = Objects.requireNonNull(zkReceiptOperations);
this.issuedReceiptsManager = Objects.requireNonNull(issuedReceiptsManager);
this.oneTimeDonationsManager = Objects.requireNonNull(oneTimeDonationsManager);
@@ -265,14 +270,23 @@ public class OneTimeDonationController {
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), braintreeManager);
})
.thenCompose(unused -> {
final Locale locale = HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext).stream()
final List<Locale> acceptableLanguages =
HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext);
// These two localizations are a best-effort, and it's possible that the first `locale` and the localized line
// item name will not match. We could try to align with the locales PayPal documents <https://developer.paypal.com/reference/locale-codes/#supported-locale-codes>
// but that's a moving target, and we can hopefully have one of them be better for the user by selecting
// independently.
final Locale locale = acceptableLanguages.stream()
.filter(l -> !"*".equals(l.getLanguage()))
.findFirst()
.orElse(Locale.US);
final String localizedLineItemName = payPalDonationsTranslator.translate(acceptableLanguages,
PayPalDonationsTranslator.ONE_TIME_DONATION_LINE_ITEM_KEY);
return braintreeManager.createOneTimePayment(request.currency.toUpperCase(Locale.ROOT), request.amount,
locale.toLanguageTag(),
request.returnUrl, request.cancelUrl);
request.returnUrl, request.cancelUrl, localizedLineItemName);
})
.thenApply(approvalDetails -> Response.ok(
new CreatePayPalBoostResponse(approvalDetails.approvalUrl(), approvalDetails.paymentId())).build());
@@ -56,7 +56,6 @@ public class RegistrationController {
private static final DistributionSummary REREGISTRATION_IDLE_DAYS_DISTRIBUTION = DistributionSummary
.builder(name(RegistrationController.class, "reregistrationIdleDays"))
.publishPercentiles(0.75, 0.95, 0.99, 0.999)
.distributionStatisticExpiry(Duration.ofHours(2))
.register(Metrics.globalRegistry);
@@ -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,21 @@ 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;
import org.whispersystems.textsecuregcm.workers.RemoveExpiredAccountsCommand;
@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 = RemoveExpiredAccountsCommand.MAX_IDLE_DURATION;
public static ExternalServiceCredentialsGenerator credentialsGenerator(final SecureValueRecoveryConfiguration cfg) {
return credentialsGenerator(cfg, Clock.systemUTC());
@@ -101,11 +114,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 +129,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 -> {
@@ -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;
@@ -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,6 +91,7 @@ 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;
@@ -101,6 +104,7 @@ 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")
@@ -123,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;
@@ -229,7 +237,8 @@ public class VerificationController {
throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR, e);
}
VerificationSession verificationSession = new VerificationSession(null,
VerificationSession verificationSession = new VerificationSession(registrationServiceSession.encodedSessionId(),
null,
maybeCarrierData.orElse(null),
new ArrayList<>(),
Collections.emptyList(),
@@ -245,7 +254,7 @@ public class VerificationController {
// 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);
}
@@ -318,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();
}
@@ -354,7 +361,8 @@ public class VerificationController {
requestedInformation.add(VerificationSession.Information.PUSH_CHALLENGE);
requestedInformation.addAll(verificationSession.requestedInformation());
verificationSession = new VerificationSession(generatePushChallenge(),
verificationSession = new VerificationSession(verificationSession.sessionId(),
generatePushChallenge(),
verificationSession.carrierData(),
requestedInformation,
verificationSession.submittedInformation(),
@@ -428,7 +436,8 @@ public class VerificationController {
|| requestedInformation.remove(VerificationSession.Information.PUSH_CHALLENGE))
&& requestedInformation.isEmpty();
verificationSession = new VerificationSession(verificationSession.pushChallenge(),
verificationSession = new VerificationSession(verificationSession.sessionId(),
verificationSession.pushChallenge(),
verificationSession.carrierData(),
requestedInformation,
submittedInformation,
@@ -484,7 +493,7 @@ public class VerificationController {
.increment();
} catch (final IOException e) {
logger.error("error assessing captcha", e);
logger.error("error assessing captcha during registration verification", e);
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE, e);
}
@@ -501,7 +510,8 @@ public class VerificationController {
|| requestedInformation.remove(VerificationSession.Information.CAPTCHA))
&& requestedInformation.isEmpty();
verificationSession = new VerificationSession(verificationSession.pushChallenge(),
verificationSession = new VerificationSession(verificationSession.sessionId(),
verificationSession.pushChallenge(),
verificationSession.carrierData(),
requestedInformation,
submittedInformation,
@@ -770,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);
}
@@ -836,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) {
@@ -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();
@@ -9,8 +9,6 @@ import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import java.util.Optional;
@@ -53,16 +51,7 @@ public record KeyTransparencySearchRequest(
Optional<@Positive Long> lastTreeHeadSize,
@Schema(description = "The distinguished tree head size to prove consistency against.")
@Positive long distinguishedTreeHeadSize,
@Schema(description = "The version of the ACI to look up.")
Optional<@Max(MAX_UINT32) @Min(0) Long> aciVersion,
@Schema(description = "The version of the E164 to look up.")
Optional<@Max(MAX_UINT32) @Min(0) Long> e164Version,
@Schema(description = "The version of the username hash to look up.")
Optional<@Max(MAX_UINT32) @Min(0) Long> usernameHashVersion
@Positive long distinguishedTreeHeadSize
) {
// This is the max value for a protobuf uint32 field
private static final long MAX_UINT32 = 0xFFFFFFFFL;
@@ -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();
@@ -6,26 +6,25 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import java.util.UUID;
import org.signal.chat.account.CheckAccountExistenceRequest;
import org.signal.chat.account.CheckAccountExistenceResponse;
import org.signal.chat.account.LookupUsernameHashRequest;
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.account.SimpleAccountsAnonymousGrpc;
import org.signal.chat.errors.NotFound;
import org.whispersystems.textsecuregcm.controllers.AccountController;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.core.publisher.Mono;
import java.util.Optional;
import java.util.UUID;
public class AccountsAnonymousGrpcService extends ReactorAccountsAnonymousGrpc.AccountsAnonymousImplBase {
public class AccountsAnonymousGrpcService extends SimpleAccountsAnonymousGrpc.AccountsAnonymousImplBase {
private final AccountsManager accountsManager;
private final RateLimiters rateLimiters;
@@ -36,37 +35,41 @@ public class AccountsAnonymousGrpcService extends ReactorAccountsAnonymousGrpc.A
}
@Override
public Mono<CheckAccountExistenceResponse> checkAccountExistence(final CheckAccountExistenceRequest request) {
public CheckAccountExistenceResponse checkAccountExistence(final CheckAccountExistenceRequest request)
throws RateLimitExceededException {
final ServiceIdentifier serviceIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getServiceIdentifier());
return RateLimitUtil.rateLimitByRemoteAddress(rateLimiters.getCheckAccountExistenceLimiter())
.then(Mono.fromFuture(() -> accountsManager.getByServiceIdentifierAsync(serviceIdentifier)))
.map(Optional::isPresent)
.map(accountExists -> CheckAccountExistenceResponse.newBuilder()
.setAccountExists(accountExists)
.build());
RateLimitUtil.rateLimitByRemoteAddress(rateLimiters.getCheckAccountExistenceLimiter());
return CheckAccountExistenceResponse.newBuilder()
.setAccountExists(accountsManager.getByServiceIdentifier(serviceIdentifier).isPresent())
.build();
}
@Override
public Mono<LookupUsernameHashResponse> lookupUsernameHash(final LookupUsernameHashRequest request) {
public LookupUsernameHashResponse lookupUsernameHash(final LookupUsernameHashRequest request)
throws RateLimitExceededException {
if (request.getUsernameHash().size() != AccountController.USERNAME_HASH_LENGTH) {
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
.map(account -> LookupUsernameHashResponse.newBuilder()
.setServiceIdentifier(ServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getUuid())))
.build())
.orElseGet(() -> LookupUsernameHashResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build()));
RateLimitUtil.rateLimitByRemoteAddress(rateLimiters.getUsernameLookupLimiter());
return accountsManager.getByUsernameHash(request.getUsernameHash().toByteArray()).join()
.map(account -> LookupUsernameHashResponse.newBuilder()
.setServiceIdentifier(ServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getUuid())))
.build())
.orElseGet(() -> LookupUsernameHashResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build());
}
@Override
public Mono<LookupUsernameLinkResponse> lookupUsernameLink(final LookupUsernameLinkRequest request) {
public LookupUsernameLinkResponse lookupUsernameLink(final LookupUsernameLinkRequest request)
throws RateLimitExceededException {
final UUID linkHandle;
try {
@@ -75,13 +78,13 @@ public class AccountsAnonymousGrpcService extends ReactorAccountsAnonymousGrpc.A
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)
.map(usernameCiphertext -> LookupUsernameLinkResponse.newBuilder()
.setUsernameCiphertext(ByteString.copyFrom(usernameCiphertext))
.build())
.orElseGet(() -> LookupUsernameLinkResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build()));
RateLimitUtil.rateLimitByRemoteAddress(rateLimiters.getUsernameLinkLookupLimiter());
return accountsManager.getByUsernameLinkHandle(linkHandle).join()
.flatMap(Account::getEncryptedUsername)
.map(usernameCiphertext -> LookupUsernameLinkResponse.newBuilder()
.setUsernameCiphertext(ByteString.copyFrom(usernameCiphertext))
.build())
.orElseGet(() -> LookupUsernameLinkResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build());
}
}
@@ -24,7 +24,6 @@ import org.signal.chat.account.DeleteUsernameLinkRequest;
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.ReserveUsernameHashRequest;
import org.signal.chat.account.ReserveUsernameHashResponse;
import org.signal.chat.account.SetDiscoverableByPhoneNumberRequest;
@@ -35,6 +34,7 @@ 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.SimpleAccountsGrpc;
import org.signal.chat.account.UsernameNotAvailable;
import org.signal.chat.common.AccountIdentifiers;
import org.signal.chat.errors.FailedPrecondition;
@@ -44,6 +44,7 @@ import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.controllers.AccountController;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.entities.EncryptedUsername;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
@@ -56,9 +57,8 @@ import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableExceptio
import org.whispersystems.textsecuregcm.storage.UsernameReservationNotFoundException;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
import reactor.core.publisher.Mono;
public class AccountsGrpcService extends ReactorAccountsGrpc.AccountsImplBase {
public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
private final AccountsManager accountsManager;
private final RateLimiters rateLimiters;
@@ -77,61 +77,59 @@ public class AccountsGrpcService extends ReactorAccountsGrpc.AccountsImplBase {
}
@Override
public Mono<GetAccountIdentityResponse> getAccountIdentity(final GetAccountIdentityRequest request) {
return getAccount()
.map(account -> {
final AccountIdentifiers.Builder accountIdentifiersBuilder = AccountIdentifiers.newBuilder()
.addServiceIdentifiers(ServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getUuid())))
.addServiceIdentifiers(ServiceIdentifierUtil.toGrpcServiceIdentifier(new PniServiceIdentifier(account.getPhoneNumberIdentifier())))
.setE164(account.getNumber());
public GetAccountIdentityResponse getAccountIdentity(final GetAccountIdentityRequest request) {
final Account account = getAuthenticatedAccount();
account.getUsernameHash().ifPresent(usernameHash ->
accountIdentifiersBuilder.setUsernameHash(ByteString.copyFrom(usernameHash)));
final AccountIdentifiers.Builder accountIdentifiersBuilder = AccountIdentifiers.newBuilder()
.addServiceIdentifiers(ServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getUuid())))
.addServiceIdentifiers(ServiceIdentifierUtil.toGrpcServiceIdentifier(new PniServiceIdentifier(account.getPhoneNumberIdentifier())))
.setE164(account.getNumber());
return GetAccountIdentityResponse.newBuilder()
.setAccountIdentifiers(accountIdentifiersBuilder.build())
.build();
});
account.getUsernameHash().ifPresent(usernameHash ->
accountIdentifiersBuilder.setUsernameHash(ByteString.copyFrom(usernameHash)));
return GetAccountIdentityResponse.newBuilder()
.setAccountIdentifiers(accountIdentifiersBuilder)
.build();
}
@Override
public Mono<DeleteAccountResponse> deleteAccount(final DeleteAccountRequest request) {
return getAccount(AuthenticationUtil.requireAuthenticatedPrimaryDevice())
.flatMap(account -> Mono.fromFuture(() -> accountsManager.delete(account, AccountsManager.DeletionReason.USER_REQUEST)))
.thenReturn(DeleteAccountResponse.newBuilder().build());
public DeleteAccountResponse deleteAccount(final DeleteAccountRequest request) {
accountsManager.delete(getAuthenticatedAccount(AuthenticationUtil.requireAuthenticatedPrimaryDevice()),
AccountsManager.DeletionReason.USER_REQUEST)
.join();
return DeleteAccountResponse.getDefaultInstance();
}
@Override
public Mono<SetRegistrationLockResponse> setRegistrationLock(final SetRegistrationLockRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedPrimaryDevice();
public SetRegistrationLockResponse setRegistrationLock(final SetRegistrationLockRequest request) {
if (request.getRegistrationLock().isEmpty()) {
throw GrpcExceptions.fieldViolation("registration_lock", "Registration lock secret must not be empty");
}
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.
final SaltedTokenHash credentials =
SaltedTokenHash.generateFor(HexFormat.of().withLowerCase().formatHex(request.getRegistrationLock().toByteArray()));
// 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.
final SaltedTokenHash credentials =
SaltedTokenHash.generateFor(HexFormat.of().withLowerCase().formatHex(request.getRegistrationLock().toByteArray()));
return Mono.fromFuture(() -> accountsManager.updateAsync(account,
a -> a.setRegistrationLock(credentials.hash(), credentials.salt())));
})
.map(ignored -> SetRegistrationLockResponse.newBuilder().build());
accountsManager.update(getAuthenticatedAccount(AuthenticationUtil.requireAuthenticatedPrimaryDevice()),
account -> account.setRegistrationLock(credentials.hash(), credentials.salt()));
return SetRegistrationLockResponse.getDefaultInstance();
}
@Override
public Mono<ClearRegistrationLockResponse> clearRegistrationLock(final ClearRegistrationLockRequest request) {
return getAccount(AuthenticationUtil.requireAuthenticatedPrimaryDevice())
.flatMap(account -> Mono.fromFuture(() -> accountsManager.updateAsync(account,
a -> a.setRegistrationLock(null, null))))
.map(ignored -> ClearRegistrationLockResponse.newBuilder().build());
public ClearRegistrationLockResponse clearRegistrationLock(final ClearRegistrationLockRequest request) {
accountsManager.update(getAuthenticatedAccount(AuthenticationUtil.requireAuthenticatedPrimaryDevice()),
account -> account.setRegistrationLock(null, null));
return ClearRegistrationLockResponse.getDefaultInstance();
}
@Override
public Mono<ReserveUsernameHashResponse> reserveUsernameHash(final ReserveUsernameHashRequest request) {
public ReserveUsernameHashResponse reserveUsernameHash(final ReserveUsernameHashRequest request)
throws RateLimitExceededException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
if (request.getUsernameHashesCount() == 0) {
@@ -155,19 +153,27 @@ public class AccountsGrpcService extends ReactorAccountsGrpc.AccountsImplBase {
usernameHashes.add(usernameHash.toByteArray());
}
return rateLimiters.getUsernameReserveLimiter().validateReactive(authenticatedDevice.accountIdentifier())
.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()
rateLimiters.getUsernameReserveLimiter().validate(authenticatedDevice.accountIdentifier());
final Account account = getAuthenticatedAccount();
try {
final AccountsManager.UsernameReservation usernameReservation =
accountsManager.reserveUsernameHash(account, usernameHashes);
return ReserveUsernameHashResponse.newBuilder()
.setUsernameHash(ByteString.copyFrom(usernameReservation.reservedUsernameHash()))
.build();
} catch (final UsernameHashNotAvailableException e) {
return ReserveUsernameHashResponse.newBuilder()
.setUsernameNotAvailable(UsernameNotAvailable.getDefaultInstance())
.build());
.build();
}
}
@Override
public Mono<ConfirmUsernameHashResponse> confirmUsernameHash(final ConfirmUsernameHashRequest request) {
public ConfirmUsernameHashResponse confirmUsernameHash(final ConfirmUsernameHashRequest request)
throws RateLimitExceededException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
if (request.getUsernameHash().isEmpty()) {
@@ -200,34 +206,41 @@ public class AccountsGrpcService extends ReactorAccountsGrpc.AccountsImplBase {
throw GrpcExceptions.constraintViolation("Could not verify proof");
}
return rateLimiters.getUsernameSetLimiter().validateReactive(authenticatedDevice.accountIdentifier())
.then(getAccount())
.flatMap(account -> Mono.fromFuture(() -> accountsManager.confirmReservedUsernameHash(account, request.getUsernameHash().toByteArray(), request.getUsernameCiphertext().toByteArray())))
.map(updatedAccount -> ConfirmUsernameHashResponse.newBuilder()
.setConfirmedUsernameHash(ConfirmUsernameHashResponse.ConfirmedUsernameHash.newBuilder()
.setUsernameHash(ByteString.copyFrom(updatedAccount.getUsernameHash().orElseThrow()))
.setUsernameLinkHandle(UUIDUtil.toByteString(updatedAccount.getUsernameLinkHandle()))
.build())
.build())
.onErrorResume(UsernameReservationNotFoundException.class, _ -> Mono.just(ConfirmUsernameHashResponse
.newBuilder()
.setReservationNotFound(FailedPrecondition.getDefaultInstance())
.build()))
.onErrorResume(UsernameHashNotAvailableException.class, _ -> Mono.just(ConfirmUsernameHashResponse
.newBuilder()
.setUsernameNotAvailable(UsernameNotAvailable.getDefaultInstance())
.build()));
rateLimiters.getUsernameSetLimiter().validate(authenticatedDevice.accountIdentifier());
try {
final Account updatedAccount = accountsManager.confirmReservedUsernameHash(getAuthenticatedAccount(),
request.getUsernameHash().toByteArray(),
request.getUsernameCiphertext().toByteArray());
return ConfirmUsernameHashResponse.newBuilder()
.setConfirmedUsernameHash(ConfirmUsernameHashResponse.ConfirmedUsernameHash.newBuilder()
.setUsernameHash(ByteString.copyFrom(updatedAccount.getUsernameHash().orElseThrow()))
.setUsernameLinkHandle(UUIDUtil.toByteString(updatedAccount.getUsernameLinkHandle())))
.build();
} catch (final UsernameHashNotAvailableException e) {
return ConfirmUsernameHashResponse
.newBuilder()
.setUsernameNotAvailable(UsernameNotAvailable.getDefaultInstance())
.build();
} catch (final UsernameReservationNotFoundException e) {
return ConfirmUsernameHashResponse
.newBuilder()
.setReservationNotFound(FailedPrecondition.getDefaultInstance())
.build();
}
}
@Override
public Mono<DeleteUsernameHashResponse> deleteUsernameHash(final DeleteUsernameHashRequest request) {
return getAccount()
.flatMap(account -> Mono.fromFuture(() -> accountsManager.clearUsernameHash(account)))
.thenReturn(DeleteUsernameHashResponse.newBuilder().build());
public DeleteUsernameHashResponse deleteUsernameHash(final DeleteUsernameHashRequest request) {
accountsManager.clearUsernameHash(getAuthenticatedAccount());
return DeleteUsernameHashResponse.getDefaultInstance();
}
@Override
public Mono<SetUsernameLinkResponse> setUsernameLink(final SetUsernameLinkRequest request) {
public SetUsernameLinkResponse setUsernameLink(final SetUsernameLinkRequest request)
throws RateLimitExceededException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
if (request.getUsernameCiphertext().isEmpty() || request.getUsernameCiphertext().size() > EncryptedUsername.MAX_SIZE) {
@@ -235,77 +248,80 @@ public class AccountsGrpcService extends ReactorAccountsGrpc.AccountsImplBase {
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(getAccount())
.flatMap(account -> {
final SetUsernameLinkResponse.Builder responseBuilder = SetUsernameLinkResponse.newBuilder();
if (account.getUsernameHash().isEmpty()) {
return Mono.just(responseBuilder.setNoUsernameSet(FailedPrecondition.getDefaultInstance()).build());
}
rateLimiters.getUsernameLinkOperationLimiter().validate(authenticatedDevice.accountIdentifier());
final UUID linkHandle;
if (request.getKeepLinkHandle() && account.getUsernameLinkHandle() != null) {
linkHandle = account.getUsernameLinkHandle();
} else {
linkHandle = UUID.randomUUID();
}
final Account account = getAuthenticatedAccount();
return Mono.fromFuture(() -> accountsManager.updateAsync(account, a -> a.setUsernameLinkDetails(linkHandle, request.getUsernameCiphertext().toByteArray())))
.thenReturn(responseBuilder.setUsernameLinkHandle(UUIDUtil.toByteString(linkHandle)).build());
});
final SetUsernameLinkResponse.Builder responseBuilder = SetUsernameLinkResponse.newBuilder();
if (account.getUsernameHash().isEmpty()) {
return responseBuilder.setNoUsernameSet(FailedPrecondition.getDefaultInstance()).build();
}
final UUID linkHandle = (request.getKeepLinkHandle() && account.getUsernameLinkHandle() != null)
? account.getUsernameLinkHandle()
: UUID.randomUUID();
accountsManager.update(account, a -> a.setUsernameLinkDetails(linkHandle, request.getUsernameCiphertext().toByteArray()));
return responseBuilder.setUsernameLinkHandle(UUIDUtil.toByteString(linkHandle)).build();
}
@Override
public Mono<DeleteUsernameLinkResponse> deleteUsernameLink(final DeleteUsernameLinkRequest request) {
public DeleteUsernameLinkResponse deleteUsernameLink(final DeleteUsernameLinkRequest request)
throws RateLimitExceededException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
return rateLimiters.getUsernameLinkOperationLimiter().validateReactive(authenticatedDevice.accountIdentifier())
.then(getAccount())
.flatMap(account -> Mono.fromFuture(() -> accountsManager.updateAsync(account, a -> a.setUsernameLinkDetails(null, null))))
.thenReturn(DeleteUsernameLinkResponse.newBuilder().build());
rateLimiters.getUsernameLinkOperationLimiter().validate(authenticatedDevice.accountIdentifier());
accountsManager.update(getAuthenticatedAccount(), a -> a.setUsernameLinkDetails(null, null));
return DeleteUsernameLinkResponse.getDefaultInstance();
}
@Override
public Mono<ConfigureUnidentifiedAccessResponse> configureUnidentifiedAccess(final ConfigureUnidentifiedAccessRequest request) {
public ConfigureUnidentifiedAccessResponse configureUnidentifiedAccess(final ConfigureUnidentifiedAccessRequest request) {
if (!request.getAllowUnrestrictedUnidentifiedAccess() && request.getUnidentifiedAccessKey().size() != UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH) {
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 getAccount()
.flatMap(account -> Mono.fromFuture(() -> accountsManager.updateAsync(account, a -> {
a.setUnrestrictedUnidentifiedAccess(request.getAllowUnrestrictedUnidentifiedAccess());
a.setUnidentifiedAccessKey(request.getAllowUnrestrictedUnidentifiedAccess() ? null : request.getUnidentifiedAccessKey().toByteArray());
})))
.thenReturn(ConfigureUnidentifiedAccessResponse.newBuilder().build());
accountsManager.update(getAuthenticatedAccount(), account -> {
account.setUnrestrictedUnidentifiedAccess(request.getAllowUnrestrictedUnidentifiedAccess());
account.setUnidentifiedAccessKey(request.getAllowUnrestrictedUnidentifiedAccess() ? null : request.getUnidentifiedAccessKey().toByteArray());
});
return ConfigureUnidentifiedAccessResponse.getDefaultInstance();
}
@Override
public Mono<SetDiscoverableByPhoneNumberResponse> setDiscoverableByPhoneNumber(final SetDiscoverableByPhoneNumberRequest request) {
return getAccount()
.flatMap(account -> Mono.fromFuture(() -> accountsManager.updateAsync(account,
a -> a.setDiscoverableByPhoneNumber(request.getDiscoverableByPhoneNumber()))))
.thenReturn(SetDiscoverableByPhoneNumberResponse.newBuilder().build());
public SetDiscoverableByPhoneNumberResponse setDiscoverableByPhoneNumber(final SetDiscoverableByPhoneNumberRequest request) {
accountsManager.update(getAuthenticatedAccount(),
account -> account.setDiscoverableByPhoneNumber(request.getDiscoverableByPhoneNumber()));
return SetDiscoverableByPhoneNumberResponse.getDefaultInstance();
}
@Override
public Mono<SetRegistrationRecoveryPasswordResponse> setRegistrationRecoveryPassword(final SetRegistrationRecoveryPasswordRequest request) {
public SetRegistrationRecoveryPasswordResponse setRegistrationRecoveryPassword(final SetRegistrationRecoveryPasswordRequest request) {
if (request.getRegistrationRecoveryPassword().isEmpty()) {
throw GrpcExceptions.fieldViolation("registration_recovery_password", "Registration recovery password must not be empty");
}
return getAccount()
.flatMap(account -> Mono.fromFuture(() -> registrationRecoveryPasswordsManager.store(account.getIdentifier(IdentityType.PNI), request.getRegistrationRecoveryPassword().toByteArray())))
.thenReturn(SetRegistrationRecoveryPasswordResponse.newBuilder().build());
registrationRecoveryPasswordsManager.store(getAuthenticatedAccount().getIdentifier(IdentityType.PNI),
request.getRegistrationRecoveryPassword().toByteArray())
.join();
return SetRegistrationRecoveryPasswordResponse.getDefaultInstance();
}
private Mono<Account> getAccount() {
return getAccount(AuthenticationUtil.requireAuthenticatedDevice());
private Account getAuthenticatedAccount() {
return getAuthenticatedAccount(AuthenticationUtil.requireAuthenticatedDevice());
}
private Mono<Account> getAccount(AuthenticatedDevice authenticatedDevice) {
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials")));
private Account getAuthenticatedAccount(final AuthenticatedDevice authenticatedDevice) {
return accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
}
}
@@ -5,6 +5,7 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import com.google.protobuf.Empty;
import java.util.Optional;
import java.util.concurrent.Flow;
import org.signal.chat.backup.CopyMediaRequest;
@@ -15,9 +16,10 @@ import org.signal.chat.backup.DeleteMediaItem;
import org.signal.chat.backup.DeleteMediaRequest;
import org.signal.chat.backup.DeleteMediaResponse;
import org.signal.chat.backup.GetBackupInfoRequest;
import org.signal.chat.backup.GetBackupInfoResponse;
import org.signal.chat.backup.GetCdnCredentialsRequest;
import org.signal.chat.backup.GetCdnCredentialsResponse;
import org.signal.chat.backup.GetMediaBackupInfoResponse;
import org.signal.chat.backup.GetMessageBackupInfoResponse;
import org.signal.chat.backup.GetSvrBCredentialsRequest;
import org.signal.chat.backup.GetSvrBCredentialsResponse;
import org.signal.chat.backup.GetUploadFormRequest;
@@ -36,12 +38,12 @@ 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.signal.libsignal.zkgroup.backups.BackupCredentialType;
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;
@@ -99,20 +101,40 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
}
@Override
public GetBackupInfoResponse getBackupInfo(final GetBackupInfoRequest request)
throws BackupNotFoundException, BackupPermissionException {
public GetMessageBackupInfoResponse getMessageBackupInfo(final GetBackupInfoRequest request) throws BackupPermissionException {
try {
final AuthenticatedBackupUser backupUser = authenticateBackupUser(request.getSignedPresentation());
if (backupUser.credentialType() != BackupCredentialType.MESSAGES) {
throw GrpcExceptions.badAuthentication("credential type for message backup info must be 'messages'");
}
final BackupManager.BackupInfo info = backupManager.backupInfo(backupUser);
return GetBackupInfoResponse.newBuilder().setBackupInfo(GetBackupInfoResponse.BackupInfo.newBuilder()
return GetMessageBackupInfoResponse.newBuilder().setBackupInfo(GetMessageBackupInfoResponse.MessageBackupInfo.newBuilder()
.setBackupName(info.messageBackupKey())
.setCdn(info.cdn())
.setBackupDir(info.backupSubdir())
.setMediaDir(info.mediaSubdir())
.setUsedSpace(info.mediaUsedSpace().orElse(0L)))
.build();
.build()).build();
} catch (BackupFailedZkAuthenticationException e) {
return GetBackupInfoResponse.newBuilder()
return GetMessageBackupInfoResponse.newBuilder()
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()).build())
.build();
}
}
@Override
public GetMediaBackupInfoResponse getMediaBackupInfo(final GetBackupInfoRequest request) throws BackupPermissionException {
try {
final AuthenticatedBackupUser backupUser = authenticateBackupUser(request.getSignedPresentation());
if (backupUser.credentialType() != BackupCredentialType.MEDIA) {
throw GrpcExceptions.badAuthentication("credential type for media backup info must be 'media'");
}
final BackupManager.BackupInfo info = backupManager.backupInfo(backupUser);
return GetMediaBackupInfoResponse.newBuilder().setBackupInfo(GetMediaBackupInfoResponse.MediaBackupInfo.newBuilder()
.setBackupDir(info.backupSubdir())
.setMediaDir(info.mediaSubdir())
.setUsedSpace(info.mediaUsedSpace().orElse(0L))
.build()).build();
} catch (BackupFailedZkAuthenticationException e) {
return GetMediaBackupInfoResponse.newBuilder()
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()).build())
.build();
}
@@ -123,7 +145,7 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
try {
final AuthenticatedBackupUser backupUser = authenticateBackupUser(request.getSignedPresentation());
backupManager.ttlRefresh(backupUser);
return RefreshResponse.getDefaultInstance();
return RefreshResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
} catch (BackupFailedZkAuthenticationException e) {
return RefreshResponse.newBuilder()
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()).build())
@@ -141,7 +163,7 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
final byte[] signature = request.getSignedPresentation().getPresentationSignature().toByteArray();
backupManager.setPublicKey(presentation, signature, publicKey);
return SetPublicKeyResponse.getDefaultInstance();
return SetPublicKeyResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
}
@@ -261,7 +283,7 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
try {
final AuthenticatedBackupUser backupUser = authenticateBackupUser(request.getSignedPresentation());
backupManager.deleteEntireBackup(backupUser);
return DeleteAllResponse.getDefaultInstance();
return DeleteAllResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
} catch (BackupFailedZkAuthenticationException e) {
return DeleteAllResponse.newBuilder()
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()))
@@ -11,6 +11,7 @@ import io.micrometer.core.instrument.Tag;
import java.time.Clock;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.signal.chat.backup.GetBackupAuthCredentialsRequest;
@@ -106,19 +107,14 @@ public class BackupsGrpcService extends SimpleBackupsGrpc.BackupsImplBase {
}
final Account account = authenticatedAccount();
try {
final List<BackupAuthManager.Credential> messageCredentials =
backupAuthManager.getBackupAuthCredentials(
account,
BackupCredentialType.MESSAGES,
redemptionRange);
backupMetrics.updateGetCredentialCounter(platformTag, BackupCredentialType.MESSAGES, messageCredentials.size());
final List<BackupAuthManager.Credential> mediaCredentials =
backupAuthManager.getBackupAuthCredentials(
account,
BackupCredentialType.MEDIA,
redemptionRange);
backupMetrics.updateGetCredentialCounter(platformTag, BackupCredentialType.MEDIA, mediaCredentials.size());
final Map<BackupCredentialType, List<BackupAuthManager.Credential>> credentials =
backupAuthManager.getBackupAuthCredentials(account, redemptionRange);
credentials.forEach((type, credentialList) ->
backupMetrics.updateGetCredentialCounter(platformTag, type, credentialList.size()));
final List<BackupAuthManager.Credential> messageCredentials = credentials.get(BackupCredentialType.MESSAGES);
final List<BackupAuthManager.Credential> mediaCredentials = credentials.get(BackupCredentialType.MEDIA);
return GetBackupAuthCredentialsResponse.newBuilder()
.setCredentials(GetBackupAuthCredentialsResponse.Credentials.newBuilder()
@@ -174,7 +170,7 @@ public class BackupsGrpcService extends SimpleBackupsGrpc.BackupsImplBase {
try {
return deserializer.deserialize(bytes);
} catch (InvalidInputException e) {
throw Status.INVALID_ARGUMENT.withDescription("Invalid serialization").asRuntimeException();
throw GrpcExceptions.invalidArguments("invalid serialization");
}
}
@@ -12,6 +12,7 @@ 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 {
@@ -38,8 +39,10 @@ public class CallQualitySurveyGrpcService extends SimpleCallQualityGrpc.CallQual
callQualitySurveyManager.submitCallQualitySurvey(request,
remoteAddress,
RequestAttributesUtil.getUserAgent().orElse(null));
} catch (final IllegalArgumentException e) {
throw Status.INVALID_ARGUMENT.withDescription(e.getMessage()).asRuntimeException();
} catch (final CallQualityInvalidArgumentsException e) {
throw e.getField()
.map(fieldName -> GrpcExceptions.fieldViolation(fieldName, e.getMessage()))
.orElseGet(() -> GrpcExceptions.invalidArguments(e.getMessage()));
}
return SubmitCallQualitySurveyResponse.getDefaultInstance();
@@ -5,7 +5,6 @@
package org.whispersystems.textsecuregcm.grpc;
import io.grpc.Status;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
public class DeviceCapabilityUtil {
@@ -19,7 +18,8 @@ public class DeviceCapabilityUtil {
case DEVICE_CAPABILITY_TRANSFER -> DeviceCapability.TRANSFER;
case DEVICE_CAPABILITY_ATTACHMENT_BACKFILL -> DeviceCapability.ATTACHMENT_BACKFILL;
case DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET -> DeviceCapability.SPARSE_POST_QUANTUM_RATCHET;
case DEVICE_CAPABILITY_UNSPECIFIED, UNRECOGNIZED -> throw Status.INVALID_ARGUMENT.withDescription("Unrecognized device capability").asRuntimeException();
case DEVICE_CAPABILITY_UNSPECIFIED, UNRECOGNIZED ->
throw GrpcExceptions.invalidArguments("unrecognized device capability");
};
}
@@ -16,7 +16,7 @@ public class DeviceIdUtil {
static byte validate(int deviceId) {
if (!isValid(deviceId)) {
throw Status.INVALID_ARGUMENT.withDescription("Device ID is out of range").asRuntimeException();
throw GrpcExceptions.invalidArguments("device ID is out of range");
}
return (byte) deviceId;
@@ -6,7 +6,7 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import io.grpc.Status;
import com.google.protobuf.Empty;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
@@ -16,7 +16,6 @@ import org.signal.chat.device.ClearPushTokenRequest;
import org.signal.chat.device.ClearPushTokenResponse;
import org.signal.chat.device.GetDevicesRequest;
import org.signal.chat.device.GetDevicesResponse;
import org.signal.chat.device.ReactorDevicesGrpc;
import org.signal.chat.device.RemoveDeviceRequest;
import org.signal.chat.device.RemoveDeviceResponse;
import org.signal.chat.device.SetCapabilitiesRequest;
@@ -25,74 +24,71 @@ import org.signal.chat.device.SetDeviceNameRequest;
import org.signal.chat.device.SetDeviceNameResponse;
import org.signal.chat.device.SetPushTokenRequest;
import org.signal.chat.device.SetPushTokenResponse;
import org.signal.chat.device.SimpleDevicesGrpc;
import org.signal.chat.errors.NotFound;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public class DevicesGrpcService extends ReactorDevicesGrpc.DevicesImplBase {
public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase {
private final AccountsManager accountsManager;
private static final int MAX_NAME_LENGTH = 256;
public DevicesGrpcService(final AccountsManager accountsManager) {
this.accountsManager = accountsManager;
}
@Override
public Mono<GetDevicesResponse> getDevices(final GetDevicesRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
public GetDevicesResponse getDevices(final GetDevicesRequest request) {
final Account account = getAuthenticatedAccount();
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
.flatMapMany(account -> Flux.fromIterable(account.getDevices()))
.reduce(GetDevicesResponse.newBuilder(), (builder, device) -> {
final GetDevicesResponse.LinkedDevice.Builder linkedDeviceBuilder = GetDevicesResponse.LinkedDevice.newBuilder();
final GetDevicesResponse.Builder responseBuilder = GetDevicesResponse.newBuilder();
account.getDevices().stream()
.map(device -> {
final GetDevicesResponse.LinkedDevice.Builder linkedDeviceBuilder =
GetDevicesResponse.LinkedDevice.newBuilder()
.setId(device.getId())
.setLastSeen(device.getLastSeen())
.setRegistrationId(device.getRegistrationId(IdentityType.ACI))
.setCreatedAtCiphertext(ByteString.copyFrom(device.getCreatedAtCiphertext()));
if (device.getName() != null) {
linkedDeviceBuilder.setName(ByteString.copyFrom(device.getName()));
}
return builder.addDevices(linkedDeviceBuilder
.setId(device.getId())
.setCreated(device.getCreated())
.setLastSeen(device.getLastSeen())
.setRegistrationId(device.getRegistrationId(IdentityType.ACI))
.setCreatedAtCiphertext(ByteString.copyFrom(device.getCreatedAtCiphertext()))
.build());
return linkedDeviceBuilder.build();
})
.map(GetDevicesResponse.Builder::build);
.forEach(responseBuilder::addDevices);
return responseBuilder.build();
}
@Override
public Mono<RemoveDeviceResponse> removeDevice(final RemoveDeviceRequest request) {
public RemoveDeviceResponse removeDevice(final RemoveDeviceRequest request) {
if (request.getId() == Device.PRIMARY_ID) {
throw Status.INVALID_ARGUMENT.withDescription("Cannot remove primary device").asRuntimeException();
throw GrpcExceptions.invalidArguments("cannot remove primary device");
}
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
if (authenticatedDevice.deviceId() != Device.PRIMARY_ID && request.getId() != authenticatedDevice.deviceId()) {
throw Status.PERMISSION_DENIED
.withDescription("Linked devices cannot remove devices other than themselves")
.asRuntimeException();
throw GrpcExceptions.badAuthentication("linked devices cannot remove devices other than themselves");
}
final byte deviceId = DeviceIdUtil.validate(request.getId());
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
.flatMap(account -> Mono.fromFuture(accountsManager.removeDevice(account, deviceId)))
.thenReturn(RemoveDeviceResponse.newBuilder().build());
accountsManager.removeDevice(getAuthenticatedAccount(), deviceId).join();
return RemoveDeviceResponse.getDefaultInstance();
}
@Override
public Mono<SetDeviceNameResponse> setDeviceName(final SetDeviceNameRequest request) {
public SetDeviceNameResponse setDeviceName(final SetDeviceNameRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final byte deviceId = DeviceIdUtil.validate(request.getId());
@@ -101,34 +97,22 @@ public class DevicesGrpcService extends ReactorDevicesGrpc.DevicesImplBase {
authenticatedDevice.deviceId() == deviceId;
if (!mayChangeName) {
throw Status.PERMISSION_DENIED
.withDescription("Authenticated device is not authorized to change target device name")
.asRuntimeException();
throw GrpcExceptions.badAuthentication("linked device is not authorized to change target device name");
}
if (request.getName().isEmpty()) {
throw Status.INVALID_ARGUMENT.withDescription("Must specify a device name").asRuntimeException();
final Account account = getAuthenticatedAccount();
if (account.getDevice(deviceId).isEmpty()) {
return SetDeviceNameResponse.newBuilder().setTargetDeviceNotFound(NotFound.getDefaultInstance()).build();
}
if (request.getName().size() > MAX_NAME_LENGTH) {
throw Status.INVALID_ARGUMENT.withDescription("Device name must be at most " + MAX_NAME_LENGTH + " bytes")
.asRuntimeException();
}
accountsManager.updateDevice(account, deviceId, device -> device.setName(request.getName().toByteArray()));
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
.doOnNext(account -> {
if (account.getDevice(deviceId).isEmpty()) {
throw Status.NOT_FOUND.withDescription("No device found with given ID").asRuntimeException();
}
})
.flatMap(account -> Mono.fromFuture(() -> accountsManager.updateDeviceAsync(account, deviceId,
device -> device.setName(request.getName().toByteArray()))))
.thenReturn(SetDeviceNameResponse.newBuilder().build());
return SetDeviceNameResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
}
@Override
public Mono<SetPushTokenResponse> setPushToken(final SetPushTokenRequest request) {
public SetPushTokenResponse setPushToken(final SetPushTokenRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
@Nullable final String apnsToken;
@@ -138,83 +122,71 @@ public class DevicesGrpcService extends ReactorDevicesGrpc.DevicesImplBase {
case APNS_TOKEN_REQUEST -> {
final SetPushTokenRequest.ApnsTokenRequest apnsTokenRequest = request.getApnsTokenRequest();
if (StringUtils.isBlank(apnsTokenRequest.getApnsToken())) {
throw Status.INVALID_ARGUMENT.withDescription("APNs token must not be blank").asRuntimeException();
}
apnsToken = StringUtils.stripToNull(apnsTokenRequest.getApnsToken());
fcmToken = null;
}
case FCM_TOKEN_REQUEST -> {
final SetPushTokenRequest.FcmTokenRequest fcmTokenRequest = request.getFcmTokenRequest();
if (StringUtils.isBlank(fcmTokenRequest.getFcmToken())) {
throw Status.INVALID_ARGUMENT.withDescription("FCM token must not be blank").asRuntimeException();
}
apnsToken = null;
fcmToken = StringUtils.stripToNull(fcmTokenRequest.getFcmToken());
}
default -> throw Status.INVALID_ARGUMENT.withDescription("No tokens specified").asRuntimeException();
default -> throw GrpcExceptions.fieldViolation("token_request", "No tokens specified");
}
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
.flatMap(account -> {
final Device device = account.getDevice(authenticatedDevice.deviceId())
.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException);
final Account account = getAuthenticatedAccount();
final boolean tokenUnchanged =
Objects.equals(device.getApnId(), apnsToken) &&
Objects.equals(device.getGcmId(), fcmToken);
final Device device = account.getDevice(authenticatedDevice.deviceId())
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
return tokenUnchanged
? Mono.empty()
: Mono.fromFuture(() -> accountsManager.updateDeviceAsync(account, authenticatedDevice.deviceId(), d -> {
d.setApnId(apnsToken);
d.setGcmId(fcmToken);
d.setFetchesMessages(false);
}));
})
.thenReturn(SetPushTokenResponse.newBuilder().build());
if (!Objects.equals(device.getApnId(), apnsToken) || !Objects.equals(device.getGcmId(), fcmToken)) {
accountsManager.updateDevice(account, authenticatedDevice.deviceId(), d -> {
d.setApnId(apnsToken);
d.setGcmId(fcmToken);
d.setFetchesMessages(false);
});
}
return SetPushTokenResponse.getDefaultInstance();
}
@Override
public Mono<ClearPushTokenResponse> clearPushToken(final ClearPushTokenRequest request) {
public ClearPushTokenResponse clearPushToken(final ClearPushTokenRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final Account account = getAuthenticatedAccount();
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
.flatMap(account -> Mono.fromFuture(() -> accountsManager.updateDeviceAsync(account, authenticatedDevice.deviceId(), device -> {
if (StringUtils.isNotBlank(device.getApnId())) {
device.setUserAgent(device.isPrimary() ? "OWI" : "OWP");
} else if (StringUtils.isNotBlank(device.getGcmId())) {
device.setUserAgent("OWA");
}
accountsManager.updateDevice(account, authenticatedDevice.deviceId(), device -> {
if (StringUtils.isNotBlank(device.getApnId())) {
device.setUserAgent(device.isPrimary() ? "OWI" : "OWP");
} else if (StringUtils.isNotBlank(device.getGcmId())) {
device.setUserAgent("OWA");
}
device.setApnId(null);
device.setGcmId(null);
device.setFetchesMessages(true);
})))
.thenReturn(ClearPushTokenResponse.newBuilder().build());
device.setApnId(null);
device.setGcmId(null);
device.setFetchesMessages(true);
});
return ClearPushTokenResponse.getDefaultInstance();
}
@Override
public Mono<SetCapabilitiesResponse> setCapabilities(final SetCapabilitiesRequest request) {
public SetCapabilitiesResponse setCapabilities(final SetCapabilitiesRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final Set<DeviceCapability> capabilities = request.getCapabilitiesList().stream()
.map(DeviceCapabilityUtil::fromGrpcDeviceCapability)
.collect(Collectors.toSet());
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
.flatMap(account ->
Mono.fromFuture(() -> accountsManager.updateDeviceAsync(account, authenticatedDevice.deviceId(),
d -> d.setCapabilities(capabilities))))
.thenReturn(SetCapabilitiesResponse.newBuilder().build());
accountsManager.updateDevice(getAuthenticatedAccount(), authenticatedDevice.deviceId(),
device -> device.setCapabilities(capabilities));
return SetCapabilitiesResponse.getDefaultInstance();
}
private Account getAuthenticatedAccount() {
return accountsManager.getByAccountIdentifier(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier())
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
}
}
@@ -0,0 +1,54 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import io.grpc.ForwardingServerCall;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ErrorConformanceInterceptor implements ServerInterceptor {
private static final Logger log = LoggerFactory.getLogger(ErrorConformanceInterceptor.class);
private static final Metadata.Key<byte[]> DETAILS_HEADER_KEY =
Metadata.Key.of("grpc-status-details-bin", Metadata.BINARY_BYTE_MARSHALLER);
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
final ServerCall<ReqT, RespT> call,
final Metadata headers,
final ServerCallHandler<ReqT, RespT> next) {
return next.startCall(new ForwardingServerCall.SimpleForwardingServerCall<>(call) {
@Override
public void close(final Status status, final Metadata trailers) {
if (status.getCode() == Status.Code.OK) {
super.close(status, trailers);
return;
}
if (!trailers.containsKey(DETAILS_HEADER_KEY)) {
log.error("Intercepted call {} returned status {} but did not include status details",
call.getMethodDescriptor().getFullMethodName(), status);
assert false;
}
switch (status.getCode()) {
case UNAUTHENTICATED, UNAVAILABLE, INVALID_ARGUMENT, RESOURCE_EXHAUSTED -> {
}
default -> {
log.error("Intercepted call {} returned illegal application status {}: {}",
call.getMethodDescriptor().getFullMethodName(), status, status.getDescription());
assert false;
}
}
super.close(status, trailers);
}
}, 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();
}
}
@@ -29,22 +29,22 @@ public class GroupSendTokenUtil {
this.clock = clock;
}
public void checkGroupSendToken(final ByteString serializedGroupSendToken,
final ServiceIdentifier serviceIdentifier) throws StatusException {
checkGroupSendToken(serializedGroupSendToken, List.of(serviceIdentifier.toLibsignal()));
public boolean checkGroupSendToken(final ByteString groupSendToken, final ServiceIdentifier serviceIdentifier) {
return checkGroupSendToken(groupSendToken, List.of(serviceIdentifier.toLibsignal()));
}
public void checkGroupSendToken(final ByteString serializedGroupSendToken,
final Collection<ServiceId> serviceIds) throws StatusException {
public boolean checkGroupSendToken(final ByteString groupSendToken, final Collection<ServiceId> serviceIds) {
try {
final GroupSendFullToken token = new GroupSendFullToken(serializedGroupSendToken.toByteArray());
token.verify(serviceIds, clock.instant(), GroupSendDerivedKeyPair.forExpiration(token.getExpiration(), serverSecretParams));
final GroupSendFullToken token = new GroupSendFullToken(groupSendToken.toByteArray());
final GroupSendDerivedKeyPair groupSendKeyPair =
GroupSendDerivedKeyPair.forExpiration(token.getExpiration(), serverSecretParams);
token.verify(serviceIds, clock.instant(), groupSendKeyPair);
return true;
} catch (final InvalidInputException e) {
throw Status.INVALID_ARGUMENT.asException();
throw GrpcExceptions.fieldViolation("group_send_token", "malformed group send token");
} catch (VerificationFailedException e) {
throw Status.UNAUTHENTICATED.asException();
return false;
}
}
}
@@ -0,0 +1,39 @@
/*
* 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 org.whispersystems.textsecuregcm.configuration.dynamic.DynamicGrpcAllowListConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
public class GrpcAllowListInterceptor implements ServerInterceptor {
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
public GrpcAllowListInterceptor(
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
this.dynamicConfigurationManager = dynamicConfigurationManager;
}
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> serverCall,
final Metadata metadata, final ServerCallHandler<ReqT, RespT> next) {
final DynamicGrpcAllowListConfiguration allowList = this.dynamicConfigurationManager.getConfiguration().getGrpcAllowList();
final MethodDescriptor<ReqT, RespT> methodDescriptor = serverCall.getMethodDescriptor();
if (!allowList.enableAll() &&
!allowList.enabledServices().contains(methodDescriptor.getServiceName()) &&
!allowList.enabledMethods().contains(methodDescriptor.getFullMethodName())) {
return ServerInterceptorUtil.closeWithStatus(serverCall, Status.UNIMPLEMENTED);
}
return next.startCall(serverCall, metadata);
}
}
@@ -17,7 +17,7 @@ public class IdentityTypeUtil {
return switch (grpcIdentityType) {
case IDENTITY_TYPE_ACI -> IdentityType.ACI;
case IDENTITY_TYPE_PNI -> IdentityType.PNI;
case IDENTITY_TYPE_UNSPECIFIED, UNRECOGNIZED -> throw Status.INVALID_ARGUMENT.asRuntimeException();
case IDENTITY_TYPE_UNSPECIFIED, UNRECOGNIZED -> throw GrpcExceptions.invalidArguments("invalid identity type");
};
}
@@ -6,29 +6,29 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import io.grpc.Status;
import io.grpc.StatusException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Clock;
import java.util.Arrays;
import java.util.concurrent.Flow;
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
import org.signal.chat.errors.NotFound;
import org.signal.chat.keys.CheckIdentityKeyRequest;
import org.signal.chat.keys.CheckIdentityKeyResponse;
import org.signal.chat.keys.GetPreKeysAnonymousRequest;
import org.signal.chat.keys.GetPreKeysResponse;
import org.signal.chat.keys.ReactorKeysAnonymousGrpc;
import org.signal.chat.keys.GetPreKeysAnonymousResponse;
import org.signal.chat.keys.SimpleKeysAnonymousGrpc;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.KeysManager;
import reactor.core.publisher.Flux;
import reactor.adapter.JdkFlowAdapter;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuples;
public class KeysAnonymousGrpcService extends ReactorKeysAnonymousGrpc.KeysAnonymousImplBase {
public class KeysAnonymousGrpcService extends SimpleKeysAnonymousGrpc.KeysAnonymousImplBase {
private final AccountsManager accountsManager;
private final KeysManager keysManager;
@@ -38,11 +38,11 @@ public class KeysAnonymousGrpcService extends ReactorKeysAnonymousGrpc.KeysAnony
final AccountsManager accountsManager, final KeysManager keysManager, final ServerSecretParams serverSecretParams, final Clock clock) {
this.accountsManager = accountsManager;
this.keysManager = keysManager;
this.groupSendTokenUtil = new GroupSendTokenUtil(serverSecretParams, clock);
}
groupSendTokenUtil = new GroupSendTokenUtil(serverSecretParams, clock);
}
@Override
public Mono<GetPreKeysResponse> getPreKeys(final GetPreKeysAnonymousRequest request) {
public GetPreKeysAnonymousResponse getPreKeys(final GetPreKeysAnonymousRequest request) {
final ServiceIdentifier serviceIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getTargetIdentifier());
@@ -52,30 +52,35 @@ public class KeysAnonymousGrpcService extends ReactorKeysAnonymousGrpc.KeysAnony
return switch (request.getAuthorizationCase()) {
case GROUP_SEND_TOKEN -> {
try {
groupSendTokenUtil.checkGroupSendToken(request.getGroupSendToken(), serviceIdentifier);
yield lookUpAccount(serviceIdentifier, Status.NOT_FOUND)
.flatMap(targetAccount -> KeysGrpcHelper.getPreKeys(targetAccount, serviceIdentifier, deviceId, keysManager));
} catch (final StatusException e) {
yield Mono.error(e);
if (!groupSendTokenUtil.checkGroupSendToken(request.getGroupSendToken(), serviceIdentifier)) {
yield GetPreKeysAnonymousResponse.newBuilder()
.setFailedUnidentifiedAuthorization(FailedUnidentifiedAuthorization.getDefaultInstance())
.build();
}
yield accountsManager.getByServiceIdentifier(serviceIdentifier)
.flatMap(targetAccount -> KeysGrpcHelper.getPreKeys(targetAccount, serviceIdentifier, deviceId, keysManager))
.map(accountPreKeyBundles -> GetPreKeysAnonymousResponse.newBuilder().setPreKeys(accountPreKeyBundles).build())
.orElseGet(() -> GetPreKeysAnonymousResponse.newBuilder()
.setTargetNotFound(NotFound.getDefaultInstance())
.build());
}
case UNIDENTIFIED_ACCESS_KEY ->
lookUpAccount(serviceIdentifier, Status.UNAUTHENTICATED)
.flatMap(targetAccount ->
UnidentifiedAccessUtil.checkUnidentifiedAccess(targetAccount, request.getUnidentifiedAccessKey().toByteArray())
? KeysGrpcHelper.getPreKeys(targetAccount, serviceIdentifier, deviceId, keysManager)
: Mono.error(Status.UNAUTHENTICATED.asException()));
case UNIDENTIFIED_ACCESS_KEY -> accountsManager.getByServiceIdentifier(serviceIdentifier)
.filter(targetAccount -> UnidentifiedAccessUtil.checkUnidentifiedAccess(targetAccount, request.getUnidentifiedAccessKey().toByteArray()))
.flatMap(targetAccount -> KeysGrpcHelper.getPreKeys(targetAccount, serviceIdentifier, deviceId, keysManager))
.map(accountPreKeyBundles -> GetPreKeysAnonymousResponse.newBuilder().setPreKeys(accountPreKeyBundles).build())
.orElseGet(() -> GetPreKeysAnonymousResponse.newBuilder()
.setFailedUnidentifiedAuthorization(FailedUnidentifiedAuthorization.getDefaultInstance())
.build());
default -> Mono.error(Status.INVALID_ARGUMENT.asException());
default -> throw GrpcExceptions.fieldViolation("authorization", "invalid authorization type");
};
}
@Override
public Flux<CheckIdentityKeyResponse> checkIdentityKeys(final Flux<CheckIdentityKeyRequest> requests) {
return requests
public Flow.Publisher<CheckIdentityKeyResponse> checkIdentityKeys(final Flow.Publisher<CheckIdentityKeyRequest> requests) {
return JdkFlowAdapter.publisherToFlowPublisher(JdkFlowAdapter.flowPublisherToFlux(requests)
.map(request -> Tuples.of(ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getTargetIdentifier()),
request.getFingerprint().toByteArray()))
.flatMap(serviceIdentifierAndFingerprint -> Mono.fromFuture(
@@ -84,18 +89,11 @@ public class KeysAnonymousGrpcService extends ReactorKeysAnonymousGrpc.KeysAnony
.filter(account -> !fingerprintMatches(account.getIdentityKey(serviceIdentifierAndFingerprint.getT1()
.identityType()), serviceIdentifierAndFingerprint.getT2()))
.map(account -> CheckIdentityKeyResponse.newBuilder()
.setTargetIdentifier(
ServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifierAndFingerprint.getT1()))
.setIdentityKey(ByteString.copyFrom(account.getIdentityKey(serviceIdentifierAndFingerprint.getT1()
.identityType()).serialize()))
.build())
);
}
private Mono<Account> lookUpAccount(final ServiceIdentifier serviceIdentifier, final Status onNotFound) {
return Mono.fromFuture(() -> accountsManager.getByServiceIdentifierAsync(serviceIdentifier))
.flatMap(Mono::justOrEmpty)
.switchIfEmpty(Mono.error(onNotFound.asException()));
.setTargetIdentifier(
ServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifierAndFingerprint.getT1()))
.setIdentityKey(ByteString.copyFrom(account.getIdentityKey(serviceIdentifierAndFingerprint.getT1()
.identityType()).serialize()))
.build())));
}
private static boolean fingerprintMatches(final IdentityKey identityKey, final byte[] fingerprint) {
@@ -6,69 +6,85 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import io.grpc.Status;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.signal.chat.common.EcPreKey;
import org.signal.chat.common.EcSignedPreKey;
import org.signal.chat.common.KemSignedPreKey;
import org.signal.chat.keys.GetPreKeysResponse;
import org.signal.chat.keys.AccountPreKeyBundles;
import org.signal.chat.keys.DevicePreKeyBundle;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.KeysManager;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuples;
class KeysGrpcHelper {
static final byte ALL_DEVICES = 0;
static Mono<GetPreKeysResponse> getPreKeys(final Account targetAccount,
/// Fetch {@link AccountPreKeyBundles} from the targetAccount
///
/// @param targetAccount the account to fetch pre-key bundles from
/// @param targetServiceIdentifier the service identifier for the target Account
/// @param targetDeviceId the device ID to retrieve pre-key bundles for, or [#ALL_DEVICES] if all devices should be
/// retrieved
/// @param keysManager The {@link KeysManager} to lookup pre-keys from
///
/// @return the requested bundles, or empty if the keys for the `targetAccount` do not exist
static Optional<AccountPreKeyBundles> getPreKeys(final Account targetAccount,
final ServiceIdentifier targetServiceIdentifier,
final byte targetDeviceId,
final KeysManager keysManager) {
final Flux<Device> devices = targetDeviceId == ALL_DEVICES
? Flux.fromIterable(targetAccount.getDevices())
: Flux.from(Mono.justOrEmpty(targetAccount.getDevice(targetDeviceId)));
final Stream<Device> devices = targetDeviceId == ALL_DEVICES
? targetAccount.getDevices().stream()
: targetAccount.getDevice(targetDeviceId).stream();
final String userAgent = RequestAttributesUtil.getUserAgent().orElse(null);
return devices
.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)
.map(preKeyBundles -> GetPreKeysResponse.newBuilder()
.setIdentityKey(ByteString
.copyFrom(targetAccount.getIdentityKey(targetServiceIdentifier.identityType())
.serialize()))
.putAllPreKeys(preKeyBundles)
.build());
final Map<Byte, CompletableFuture<Optional<KeysManager.DevicePreKeys>>> takeKeyFuturesByDeviceId =
devices.collect(Collectors.toMap(
Device::getId,
device -> keysManager.takeDevicePreKeys(device.getId(), targetServiceIdentifier, userAgent)));
CompletableFuture.allOf(takeKeyFuturesByDeviceId.values().toArray(CompletableFuture[]::new)).join();
final Map<Byte, KeysManager.DevicePreKeys> preKeysByDeviceId = takeKeyFuturesByDeviceId.entrySet().stream()
.filter(entry -> entry.getValue().resultNow().isPresent())
.collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().resultNow().orElseThrow()));
if (preKeysByDeviceId.isEmpty()) {
// If there were no devices with valid prekey bundles in the account, the account is gone
return Optional.empty();
}
final AccountPreKeyBundles.Builder preKeyBundlesBuilder = AccountPreKeyBundles.newBuilder()
.setIdentityKey(ByteString.copyFrom(targetAccount.getIdentityKey(targetServiceIdentifier.identityType()).serialize()));
preKeysByDeviceId.forEach((deviceId, devicePreKeys) -> {
final Device device = targetAccount.getDevice(deviceId).orElseThrow();
final DevicePreKeyBundle.Builder builder = DevicePreKeyBundle.newBuilder()
.setEcSignedPreKey(EcSignedPreKey.newBuilder()
.setKeyId(devicePreKeys.ecSignedPreKey().keyId())
.setPublicKey(ByteString.copyFrom(devicePreKeys.ecSignedPreKey().serializedPublicKey()))
.setSignature(ByteString.copyFrom(devicePreKeys.ecSignedPreKey().signature())))
.setKemOneTimePreKey(KemSignedPreKey.newBuilder()
.setKeyId(devicePreKeys.kemSignedPreKey().keyId())
.setPublicKey(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().serializedPublicKey()))
.setSignature(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().signature())))
.setRegistrationId(device.getRegistrationId(targetServiceIdentifier.identityType()));
devicePreKeys.ecPreKey().ifPresent(ecPreKey -> builder.setEcOneTimePreKey(EcPreKey.newBuilder()
.setKeyId(ecPreKey.keyId())
.setPublicKey(ByteString.copyFrom(ecPreKey.serializedPublicKey()))));
preKeyBundlesBuilder.putDevicePreKeys(deviceId, builder.build());
});
return Optional.of(preKeyBundlesBuilder.build());
}
}
@@ -5,32 +5,32 @@
package org.whispersystems.textsecuregcm.grpc;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiFunction;
import org.signal.chat.common.EcPreKey;
import org.signal.chat.common.EcSignedPreKey;
import org.signal.chat.common.KemSignedPreKey;
import org.signal.chat.errors.NotFound;
import org.signal.chat.keys.GetPreKeyCountRequest;
import org.signal.chat.keys.GetPreKeyCountResponse;
import org.signal.chat.keys.GetPreKeysRequest;
import org.signal.chat.keys.GetPreKeysResponse;
import org.signal.chat.keys.ReactorKeysGrpc;
import org.signal.chat.keys.SetEcSignedPreKeyRequest;
import org.signal.chat.keys.SetKemLastResortPreKeyRequest;
import org.signal.chat.keys.SetOneTimeEcPreKeysRequest;
import org.signal.chat.keys.SetOneTimeKemSignedPreKeysRequest;
import org.signal.chat.keys.SetPreKeyResponse;
import org.signal.chat.keys.SimpleKeysGrpc;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.InvalidKeyException;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
import org.signal.libsignal.protocol.kem.KEMPublicKey;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.entities.ECPreKey;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
@@ -40,28 +40,18 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.KeysManager;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuples;
public class KeysGrpcService extends ReactorKeysGrpc.KeysImplBase {
public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
private final AccountsManager accountsManager;
private final KeysManager keysManager;
private final RateLimiters rateLimiters;
private static final StatusRuntimeException INVALID_PUBLIC_KEY_EXCEPTION = Status.fromCode(Status.Code.INVALID_ARGUMENT)
.withDescription("Invalid public key")
.asRuntimeException();
private static final StatusRuntimeException INVALID_PUBLIC_KEY_EXCEPTION =
GrpcExceptions.fieldViolation("pre_keys", "invalid public key");
private static final StatusRuntimeException INVALID_SIGNATURE_EXCEPTION = Status.fromCode(Status.Code.INVALID_ARGUMENT)
.withDescription("Invalid signature")
.asRuntimeException();
private enum PreKeyType {
EC,
KEM
}
private static final StatusRuntimeException INVALID_SIGNATURE_EXCEPTION =
GrpcExceptions.fieldViolation("pre_keys", "pre-key signature did not match account identity key");
public KeysGrpcService(final AccountsManager accountsManager,
final KeysManager keysManager,
@@ -73,50 +63,34 @@ public class KeysGrpcService extends ReactorKeysGrpc.KeysImplBase {
}
@Override
public Mono<GetPreKeyCountResponse> getPreKeyCount(final GetPreKeyCountRequest request) {
return Mono.fromSupplier(AuthenticationUtil::requireAuthenticatedDevice)
.flatMap(authenticatedDevice -> Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount
.map(account -> Tuples.of(account, authenticatedDevice.deviceId()))
.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException)))
.flatMapMany(accountAndDeviceId -> Flux.just(
Tuples.of(IdentityType.ACI, accountAndDeviceId.getT1().getUuid(), accountAndDeviceId.getT2()),
Tuples.of(IdentityType.PNI, accountAndDeviceId.getT1().getPhoneNumberIdentifier(), accountAndDeviceId.getT2())
))
.flatMap(identityTypeUuidAndDeviceId -> Flux.merge(
Mono.fromFuture(() -> keysManager.getEcCount(identityTypeUuidAndDeviceId.getT2(), identityTypeUuidAndDeviceId.getT3()))
.map(ecKeyCount -> Tuples.of(identityTypeUuidAndDeviceId.getT1(), PreKeyType.EC, ecKeyCount)),
public GetPreKeyCountResponse getPreKeyCount(final GetPreKeyCountRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final Account account = getAuthenticatedAccount(authenticatedDevice.accountIdentifier());
Mono.fromFuture(() -> keysManager.getPqCount(identityTypeUuidAndDeviceId.getT2(), identityTypeUuidAndDeviceId.getT3()))
.map(ecKeyCount -> Tuples.of(identityTypeUuidAndDeviceId.getT1(), PreKeyType.KEM, ecKeyCount))
))
.reduce(GetPreKeyCountResponse.newBuilder(), (builder, tuple) -> {
final IdentityType identityType = tuple.getT1();
final PreKeyType preKeyType = tuple.getT2();
final int count = tuple.getT3();
final CompletableFuture<Integer> aciEcKeyCountFuture =
keysManager.getEcCount(account.getIdentifier(IdentityType.ACI), authenticatedDevice.deviceId());
switch (identityType) {
case ACI -> {
switch (preKeyType) {
case EC -> builder.setAciEcPreKeyCount(count);
case KEM -> builder.setAciKemPreKeyCount(count);
}
}
case PNI -> {
switch (preKeyType) {
case EC -> builder.setPniEcPreKeyCount(count);
case KEM -> builder.setPniKemPreKeyCount(count);
}
}
}
final CompletableFuture<Integer> pniEcKeyCountFuture =
keysManager.getEcCount(account.getIdentifier(IdentityType.PNI), authenticatedDevice.deviceId());
return builder;
})
.map(GetPreKeyCountResponse.Builder::build);
final CompletableFuture<Integer> aciKemKeyCountFuture =
keysManager.getPqCount(account.getIdentifier(IdentityType.ACI), authenticatedDevice.deviceId());
final CompletableFuture<Integer> pniKemKeyCountFuture =
keysManager.getPqCount(account.getIdentifier(IdentityType.PNI), authenticatedDevice.deviceId());
CompletableFuture.allOf(aciEcKeyCountFuture, pniEcKeyCountFuture, aciKemKeyCountFuture, pniKemKeyCountFuture).join();
return GetPreKeyCountResponse.newBuilder()
.setAciEcPreKeyCount(aciEcKeyCountFuture.resultNow())
.setPniEcPreKeyCount(pniEcKeyCountFuture.resultNow())
.setAciKemPreKeyCount(aciKemKeyCountFuture.resultNow())
.setPniKemPreKeyCount(pniKemKeyCountFuture.resultNow())
.build();
}
@Override
public Mono<GetPreKeysResponse> getPreKeys(final GetPreKeysRequest request) {
public GetPreKeysResponse getPreKeys(final GetPreKeysRequest request) throws RateLimitExceededException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final ServiceIdentifier targetIdentifier =
@@ -131,103 +105,115 @@ public class KeysGrpcService extends ReactorKeysGrpc.KeysImplBase {
targetIdentifier.uuid() + "." +
deviceId;
return rateLimiters.getPreKeysLimiter().validateReactive(rateLimitKey)
.then(Mono.fromFuture(() -> accountsManager.getByServiceIdentifierAsync(targetIdentifier))
.flatMap(Mono::justOrEmpty))
.switchIfEmpty(Mono.error(Status.NOT_FOUND.asException()))
.flatMap(targetAccount ->
KeysGrpcHelper.getPreKeys(targetAccount, targetIdentifier, deviceId, keysManager));
rateLimiters.getPreKeysLimiter().validate(rateLimitKey);
return accountsManager.getByServiceIdentifier(targetIdentifier)
.flatMap(targetAccount -> KeysGrpcHelper.getPreKeys(targetAccount, targetIdentifier, deviceId, keysManager))
.map(accountPreKeyBundles -> GetPreKeysResponse.newBuilder()
.setPreKeys(accountPreKeyBundles)
.build())
.orElseGet(() -> GetPreKeysResponse.newBuilder()
.setTargetNotFound(NotFound.getDefaultInstance())
.build());
}
@Override
public Mono<SetPreKeyResponse> setOneTimeEcPreKeys(final SetOneTimeEcPreKeysRequest request) {
return Mono.fromSupplier(AuthenticationUtil::requireAuthenticatedDevice)
.flatMap(authenticatedDevice -> storeOneTimePreKeys(authenticatedDevice.accountIdentifier(),
request.getPreKeysList(),
IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType()),
(requestPreKey, ignored) -> checkEcPreKey(requestPreKey),
(identifier, preKeys) -> keysManager.storeEcOneTimePreKeys(identifier, authenticatedDevice.deviceId(), preKeys)));
public SetPreKeyResponse setOneTimeEcPreKeys(final SetOneTimeEcPreKeysRequest request) {
if (request.getPreKeysList().isEmpty()) {
throw GrpcExceptions.fieldViolation("pre_keys", "pre_keys must be non-empty");
}
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
storeOneTimePreKeys(authenticatedDevice.accountIdentifier(),
request.getPreKeysList(),
IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType()),
(requestPreKey, _) -> checkEcPreKey(requestPreKey),
(identifier, preKeys) -> keysManager.storeEcOneTimePreKeys(identifier, authenticatedDevice.deviceId(), preKeys));
return SetPreKeyResponse.getDefaultInstance();
}
@Override
public Mono<SetPreKeyResponse> setOneTimeKemSignedPreKeys(final SetOneTimeKemSignedPreKeysRequest request) {
return Mono.fromSupplier(AuthenticationUtil::requireAuthenticatedDevice)
.flatMap(authenticatedDevice -> storeOneTimePreKeys(authenticatedDevice.accountIdentifier(),
request.getPreKeysList(),
IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType()),
KeysGrpcService::checkKemSignedPreKey,
(identifier, preKeys) -> keysManager.storeKemOneTimePreKeys(identifier, authenticatedDevice.deviceId(), preKeys)));
public SetPreKeyResponse setOneTimeKemSignedPreKeys(final SetOneTimeKemSignedPreKeysRequest request) {
if (request.getPreKeysList().isEmpty()) {
throw GrpcExceptions.fieldViolation("pre_keys", "pre_keys must be non-empty");
}
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
storeOneTimePreKeys(authenticatedDevice.accountIdentifier(),
request.getPreKeysList(),
IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType()),
KeysGrpcService::checkKemSignedPreKey,
(identifier, preKeys) -> keysManager.storeKemOneTimePreKeys(identifier, authenticatedDevice.deviceId(), preKeys));
return SetPreKeyResponse.getDefaultInstance();
}
private <K, R> Mono<SetPreKeyResponse> storeOneTimePreKeys(final UUID authenticatedAccountUuid,
private <K, R> void storeOneTimePreKeys(final UUID authenticatedAccountUuid,
final List<R> requestPreKeys,
final IdentityType identityType,
final BiFunction<R, IdentityKey, K> extractPreKeyFunction,
final BiFunction<UUID, List<K>, CompletableFuture<Void>> storeKeysFunction) {
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedAccountUuid))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
.map(account -> {
final List<K> preKeys = requestPreKeys.stream()
.map(requestPreKey -> extractPreKeyFunction.apply(requestPreKey, account.getIdentityKey(identityType)))
.toList();
final Account account = getAuthenticatedAccount(authenticatedAccountUuid);
if (preKeys.isEmpty()) {
throw Status.INVALID_ARGUMENT.asRuntimeException();
}
final List<K> preKeys = requestPreKeys.stream()
.map(requestPreKey -> extractPreKeyFunction.apply(requestPreKey, account.getIdentityKey(identityType)))
.toList();
return Tuples.of(account.getIdentifier(identityType), preKeys);
})
.flatMap(identifierAndPreKeys -> Mono.fromFuture(() -> storeKeysFunction.apply(identifierAndPreKeys.getT1(), identifierAndPreKeys.getT2())))
.thenReturn(SetPreKeyResponse.newBuilder().build());
storeKeysFunction.apply(account.getIdentifier(identityType), preKeys).join();
}
@Override
public Mono<SetPreKeyResponse> setEcSignedPreKey(final SetEcSignedPreKeyRequest request) {
return Mono.fromSupplier(AuthenticationUtil::requireAuthenticatedDevice)
.flatMap(authenticatedDevice -> storeRepeatedUseKey(authenticatedDevice.accountIdentifier(),
request.getIdentityType(),
request.getSignedPreKey(),
KeysGrpcService::checkEcSignedPreKey,
(account, signedPreKey) -> {
final IdentityType identityType = IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType());
final UUID identifier = account.getIdentifier(identityType);
public SetPreKeyResponse setEcSignedPreKey(final SetEcSignedPreKeyRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
return Mono.fromFuture(() -> keysManager.storeEcSignedPreKeys(identifier, authenticatedDevice.deviceId(), signedPreKey));
}));
storeRepeatedUseKey(authenticatedDevice.accountIdentifier(),
request.getIdentityType(),
request.getSignedPreKey(),
KeysGrpcService::checkEcSignedPreKey,
(account, signedPreKey) -> {
final IdentityType identityType = IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType());
final UUID identifier = account.getIdentifier(identityType);
return keysManager.storeEcSignedPreKeys(identifier, authenticatedDevice.deviceId(), signedPreKey);
});
return SetPreKeyResponse.getDefaultInstance();
}
@Override
public Mono<SetPreKeyResponse> setKemLastResortPreKey(final SetKemLastResortPreKeyRequest request) {
return Mono.fromSupplier(AuthenticationUtil::requireAuthenticatedDevice)
.flatMap(authenticatedDevice -> storeRepeatedUseKey(authenticatedDevice.accountIdentifier(),
request.getIdentityType(),
request.getSignedPreKey(),
KeysGrpcService::checkKemSignedPreKey,
(account, lastResortKey) -> {
final UUID identifier =
account.getIdentifier(IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType()));
public SetPreKeyResponse setKemLastResortPreKey(final SetKemLastResortPreKeyRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
return Mono.fromFuture(() -> keysManager.storePqLastResort(identifier, authenticatedDevice.deviceId(), lastResortKey));
}));
storeRepeatedUseKey(authenticatedDevice.accountIdentifier(),
request.getIdentityType(),
request.getSignedPreKey(),
KeysGrpcService::checkKemSignedPreKey,
(account, lastResortKey) -> {
final UUID identifier =
account.getIdentifier(IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType()));
return keysManager.storePqLastResort(identifier, authenticatedDevice.deviceId(), lastResortKey);
});
return SetPreKeyResponse.getDefaultInstance();
}
private <K, R> Mono<SetPreKeyResponse> storeRepeatedUseKey(final UUID authenticatedAccountUuid,
private <K, R> void storeRepeatedUseKey(final UUID authenticatedAccountUuid,
final org.signal.chat.common.IdentityType identityType,
final R storeKeyRequest,
final BiFunction<R, IdentityKey, K> extractKeyFunction,
final BiFunction<Account, K, Mono<?>> storeKeyFunction) {
final BiFunction<Account, K, CompletableFuture<Void>> storeKeyFunction) {
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedAccountUuid))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
.map(account -> {
final IdentityKey identityKey = account.getIdentityKey(IdentityTypeUtil.fromGrpcIdentityType(identityType));
final K key = extractKeyFunction.apply(storeKeyRequest, identityKey);
final Account account = getAuthenticatedAccount(authenticatedAccountUuid);
return Tuples.of(account, key);
})
.flatMap(accountAndKey -> storeKeyFunction.apply(accountAndKey.getT1(), accountAndKey.getT2()))
.thenReturn(SetPreKeyResponse.newBuilder().build());
final IdentityKey identityKey = account.getIdentityKey(IdentityTypeUtil.fromGrpcIdentityType(identityType));
final K key = extractKeyFunction.apply(storeKeyRequest, identityKey);
storeKeyFunction.apply(account, key).join();
}
private static ECPreKey checkEcPreKey(final EcPreKey preKey) {
@@ -269,4 +255,9 @@ public class KeysGrpcService extends ReactorKeysGrpc.KeysImplBase {
throw INVALID_PUBLIC_KEY_EXCEPTION;
}
}
private Account getAuthenticatedAccount(final UUID authenticatedAccountId) {
return accountsManager.getByAccountIdentifier(authenticatedAccountId)
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
}
}
@@ -6,14 +6,16 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import io.grpc.Status;
import io.grpc.StatusException;
import java.time.Clock;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import com.google.protobuf.Empty;
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
import org.signal.chat.errors.NotFound;
import org.signal.chat.messages.IndividualRecipientMessageBundle;
import org.signal.chat.messages.MultiRecipientMismatchedDevices;
import org.signal.chat.messages.MultiRecipientSuccess;
import org.signal.chat.messages.SendMessageResponse;
import org.signal.chat.messages.SendMultiRecipientMessageRequest;
import org.signal.chat.messages.SendMultiRecipientMessageResponse;
@@ -25,6 +27,7 @@ import org.signal.libsignal.protocol.InvalidMessageException;
import org.signal.libsignal.protocol.InvalidVersionException;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.controllers.MultiRecipientMismatchedDevicesException;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
@@ -35,7 +38,7 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.push.MessageSender;
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
import org.whispersystems.textsecuregcm.push.MessageUtil;
import org.whispersystems.textsecuregcm.spam.GrpcResponse;
import org.whispersystems.textsecuregcm.spam.GrpcChallengeResponse;
import org.whispersystems.textsecuregcm.spam.MessageType;
import org.whispersystems.textsecuregcm.spam.SpamCheckResult;
import org.whispersystems.textsecuregcm.spam.SpamChecker;
@@ -52,7 +55,10 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
private final SpamChecker spamChecker;
private final Clock clock;
private static final SendMessageResponse SEND_MESSAGE_SUCCESS_RESPONSE = SendMessageResponse.newBuilder().build();
private static final SendMessageResponse SEND_MESSAGE_SUCCESS_RESPONSE = SendMessageResponse
.newBuilder()
.setSuccess(Empty.getDefaultInstance())
.build();
public MessagesAnonymousGrpcService(final AccountsManager accountsManager,
final RateLimiters rateLimiters,
@@ -65,35 +71,51 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
this.accountsManager = accountsManager;
this.rateLimiters = rateLimiters;
this.messageSender = messageSender;
this.groupSendTokenUtil = groupSendTokenUtil;
this.messageByteLimitEstimator = messageByteLimitEstimator;
this.spamChecker = spamChecker;
this.clock = clock;
this.groupSendTokenUtil = groupSendTokenUtil;
}
@Override
public SendMessageResponse sendSingleRecipientMessage(final SendSealedSenderMessageRequest request)
throws StatusException, RateLimitExceededException {
throws RateLimitExceededException {
final ServiceIdentifier destinationServiceIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getDestination());
final Account destination = accountsManager.getByServiceIdentifier(destinationServiceIdentifier)
.orElseThrow(Status.UNAUTHENTICATED::asException);
final Optional<Account> maybeDestination = accountsManager.getByServiceIdentifier(destinationServiceIdentifier);
switch (request.getAuthorizationCase()) {
final boolean authorized = switch (request.getAuthorizationCase()) {
case UNIDENTIFIED_ACCESS_KEY -> {
if (!UnidentifiedAccessUtil.checkUnidentifiedAccess(destination, request.getUnidentifiedAccessKey().toByteArray())) {
throw Status.UNAUTHENTICATED.asException();
if (destinationServiceIdentifier.identityType() == IdentityType.PNI) {
throw GrpcExceptions.fieldViolation("authorization",
"message for PNI cannot be authenticated with an unidentified access token");
}
final byte[] uak = request.getUnidentifiedAccessKey().toByteArray();
yield maybeDestination
.map(account -> UnidentifiedAccessUtil.checkUnidentifiedAccess(account, uak))
// If the destination is not found, return an authorization error instead of not-found. Otherwise,
// this would provide an unauthenticated existence check.
.orElse(false);
}
case GROUP_SEND_TOKEN ->
groupSendTokenUtil.checkGroupSendToken(request.getGroupSendToken(), destinationServiceIdentifier);
case AUTHORIZATION_NOT_SET ->
throw GrpcExceptions.fieldViolation("authorization", "expected authorization token not provided");
};
case AUTHORIZATION_NOT_SET -> throw Status.UNAUTHENTICATED.asException();
if (!authorized) {
return SendMessageResponse.newBuilder()
.setFailedUnidentifiedAuthorization(FailedUnidentifiedAuthorization.getDefaultInstance())
.build();
}
return sendIndividualMessage(destination,
if (maybeDestination.isEmpty()) {
return SendMessageResponse.newBuilder().setDestinationNotFound(NotFound.getDefaultInstance()).build();
}
return sendIndividualMessage(maybeDestination.get(),
destinationServiceIdentifier,
request.getMessages(),
request.getEphemeral(),
@@ -103,7 +125,7 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
@Override
public SendMessageResponse sendStory(final SendStoryMessageRequest request)
throws StatusException, RateLimitExceededException {
throws RateLimitExceededException {
final ServiceIdentifier destinationServiceIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getDestination());
@@ -132,18 +154,17 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
final IndividualRecipientMessageBundle messages,
final boolean ephemeral,
final boolean urgent,
final boolean story) throws StatusException, RateLimitExceededException {
final boolean story) throws RateLimitExceededException {
final SpamCheckResult<GrpcResponse<SendMessageResponse>> spamCheckResult =
final SpamCheckResult<GrpcChallengeResponse> spamCheckResult =
spamChecker.checkForIndividualRecipientSpamGrpc(
story ? MessageType.INDIVIDUAL_STORY : MessageType.INDIVIDUAL_SEALED_SENDER,
Optional.empty(),
Optional.of(destination),
destinationServiceIdentifier);
if (spamCheckResult.response().isPresent()) {
return spamCheckResult.response().get().getResponseOrThrowStatus();
}
spamCheckResult.response().ifPresent(grpcResponse ->
grpcResponse.throwStatusOr(_ -> GrpcExceptions.rateLimitExceeded(null)));
try {
final int totalPayloadLength = messages.getMessagesMap().values().stream()
@@ -187,22 +208,35 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
entry -> entry.getKey().byteValue(),
entry -> entry.getValue().getRegistrationId()));
return MessagesGrpcHelper.sendMessage(messageSender,
destination,
destinationServiceIdentifier,
messagesByDeviceId,
registrationIdsByDeviceId,
Optional.empty());
try {
messageSender.sendMessages(destination,
destinationServiceIdentifier,
messagesByDeviceId,
registrationIdsByDeviceId,
Optional.empty(),
RequestAttributesUtil.getUserAgent().orElse(null));
return SEND_MESSAGE_SUCCESS_RESPONSE;
} catch (final MismatchedDevicesException e) {
return SendMessageResponse.newBuilder()
.setMismatchedDevices(MessagesGrpcHelper.buildMismatchedDevices(destinationServiceIdentifier, e.getMismatchedDevices()))
.build();
} catch (final MessageTooLargeException e) {
throw GrpcExceptions.invalidArguments("message too large");
}
}
@Override
public SendMultiRecipientMessageResponse sendMultiRecipientMessage(final SendMultiRecipientMessageRequest request)
throws StatusException {
public SendMultiRecipientMessageResponse sendMultiRecipientMessage(final SendMultiRecipientMessageRequest request) {
final SealedSenderMultiRecipientMessage multiRecipientMessage =
parseAndValidateMultiRecipientMessage(request.getMessage().getPayload().toByteArray());
groupSendTokenUtil.checkGroupSendToken(request.getGroupSendToken(), multiRecipientMessage.getRecipients().keySet());
if (!groupSendTokenUtil.checkGroupSendToken(request.getGroupSendToken(), multiRecipientMessage.getRecipients().keySet())) {
return SendMultiRecipientMessageResponse.newBuilder()
.setFailedUnidentifiedAuthorization(FailedUnidentifiedAuthorization.getDefaultInstance())
.build();
}
return sendMultiRecipientMessage(multiRecipientMessage,
request.getMessage().getTimestamp(),
@@ -212,21 +246,26 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
}
@Override
public SendMultiRecipientMessageResponse sendMultiRecipientStory(final SendMultiRecipientStoryRequest request)
throws StatusException {
public SendMultiRecipientMessageResponse sendMultiRecipientStory(final SendMultiRecipientStoryRequest request) {
final SealedSenderMultiRecipientMessage multiRecipientMessage =
parseAndValidateMultiRecipientMessage(request.getMessage().getPayload().toByteArray());
return sendMultiRecipientMessage(multiRecipientMessage,
final SendMultiRecipientMessageResponse sendMultiRecipientMessageResponse = sendMultiRecipientMessage(
multiRecipientMessage,
request.getMessage().getTimestamp(),
false,
request.getUrgent(),
true)
.toBuilder()
// Don't identify unresolved recipients for stories
.clearUnresolvedRecipients()
.build();
true);
if (sendMultiRecipientMessageResponse.hasSuccess()) {
// Clear the unresolved recipients for stories
return sendMultiRecipientMessageResponse.toBuilder()
.setSuccess(MultiRecipientSuccess.getDefaultInstance())
.build();
} else {
return sendMultiRecipientMessageResponse;
}
}
private SendMultiRecipientMessageResponse sendMultiRecipientMessage(
@@ -234,16 +273,15 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
final long timestamp,
final boolean ephemeral,
final boolean urgent,
final boolean story) throws StatusException {
final boolean story) {
final SpamCheckResult<GrpcResponse<SendMultiRecipientMessageResponse>> spamCheckResult =
final SpamCheckResult<GrpcChallengeResponse> spamCheckResult =
spamChecker.checkForMultiRecipientSpamGrpc(story
? MessageType.MULTI_RECIPIENT_STORY
: MessageType.MULTI_RECIPIENT_SEALED_SENDER);
if (spamCheckResult.response().isPresent()) {
return spamCheckResult.response().get().getResponseOrThrowStatus();
}
spamCheckResult.response().ifPresent(response ->
response.throwStatusOr(_ -> GrpcExceptions.rateLimitExceeded(null)));
// At this point, the caller has at least superficially provided the information needed to send a multi-recipient
// message. Attempt to resolve the destination service identifiers to Signal accounts.
@@ -257,20 +295,18 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
story,
ephemeral,
urgent,
RequestAttributesUtil.getUserAgent().orElse(null));
RequestAttributesUtil.getUserAgent().orElse(null))
.join();
final SendMultiRecipientMessageResponse.Builder responseBuilder = SendMultiRecipientMessageResponse.newBuilder();
final MultiRecipientSuccess.Builder responseBuilder = MultiRecipientSuccess.newBuilder();
MessageUtil.getUnresolvedRecipients(multiRecipientMessage, resolvedRecipients).stream()
.map(ServiceIdentifierUtil::toGrpcServiceIdentifier)
.forEach(responseBuilder::addUnresolvedRecipients);
return responseBuilder.build();
return SendMultiRecipientMessageResponse.newBuilder().setSuccess(responseBuilder).build();
} catch (final MessageTooLargeException e) {
throw Status.INVALID_ARGUMENT
.withDescription("Message for an individual recipient was too large")
.withCause(e)
.asRuntimeException();
throw GrpcExceptions.invalidArguments("message for an individual recipient was too large");
} catch (final MultiRecipientMismatchedDevicesException e) {
final MultiRecipientMismatchedDevices.Builder mismatchedDevicesBuilder =
MultiRecipientMismatchedDevices.newBuilder();
@@ -285,22 +321,29 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
}
private SealedSenderMultiRecipientMessage parseAndValidateMultiRecipientMessage(
final byte[] serializedMultiRecipientMessage) throws StatusException {
final byte[] serializedMultiRecipientMessage) {
final SealedSenderMultiRecipientMessage multiRecipientMessage;
try {
multiRecipientMessage = SealedSenderMultiRecipientMessage.parse(serializedMultiRecipientMessage);
} catch (final InvalidMessageException | InvalidVersionException e) {
throw Status.INVALID_ARGUMENT.withCause(e).asException();
} catch (final InvalidMessageException _) {
throw GrpcExceptions.fieldViolation("payload", "invalid multi-recipient message");
} catch (final InvalidVersionException e) {
throw GrpcExceptions.fieldViolation("payload", "unrecognized sealed sender major version");
}
if (multiRecipientMessage.getRecipients().isEmpty()) {
throw GrpcExceptions.fieldViolation("payload", "recipient list is empty");
}
// Check that the request is well-formed and doesn't contain repeated entries for the same device for the same
// recipient
if (MessageUtil.hasDuplicateDevices(multiRecipientMessage)) {
throw Status.INVALID_ARGUMENT.withDescription("Multi-recipient message contains duplicate recipient").asException();
throw GrpcExceptions.fieldViolation("payload", "multi-recipient message contains duplicate recipient");
}
return multiRecipientMessage;
}
}
@@ -5,68 +5,11 @@
package org.whispersystems.textsecuregcm.grpc;
import io.grpc.Status;
import io.grpc.StatusException;
import java.util.Map;
import java.util.Optional;
import org.signal.chat.messages.MismatchedDevices;
import org.signal.chat.messages.SendMessageResponse;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.push.MessageSender;
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
import org.whispersystems.textsecuregcm.storage.Account;
public class MessagesGrpcHelper {
private static final SendMessageResponse SEND_MESSAGE_SUCCESS_RESPONSE = SendMessageResponse.newBuilder().build();
/**
* Sends a "bundle" of messages to an individual destination account, mapping common exceptions to appropriate gRPC
* statuses.
*
* @param messageSender the {@code MessageSender} instance to use to send the messages
* @param destination the destination account for the messages
* @param destinationServiceIdentifier the service identifier for the destination account
* @param messagesByDeviceId a map of device IDs to message payloads
* @param registrationIdsByDeviceId a map of device IDs to device registration IDs
* @param syncMessageSenderDeviceId if the message is a sync message (i.e. a message to other devices linked to the
* caller's own account), contains the ID of the device that sent the message
*
* @return a response object to send to callers
*
* @throws StatusException if the message bundle could not be sent due to an out-of-date device set or an invalid
* message payload
* @throws RateLimitExceededException if the message bundle could not be sent due to a violated rated limit
*/
public static SendMessageResponse sendMessage(final MessageSender messageSender,
final Account destination,
final ServiceIdentifier destinationServiceIdentifier,
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId,
final Map<Byte, Integer> registrationIdsByDeviceId,
@SuppressWarnings("OptionalUsedAsFieldOrParameterType") final Optional<Byte> syncMessageSenderDeviceId)
throws StatusException, RateLimitExceededException {
try {
messageSender.sendMessages(destination,
destinationServiceIdentifier,
messagesByDeviceId,
registrationIdsByDeviceId,
syncMessageSenderDeviceId,
RequestAttributesUtil.getUserAgent().orElse(null));
return SEND_MESSAGE_SUCCESS_RESPONSE;
} catch (final MismatchedDevicesException e) {
return SendMessageResponse.newBuilder()
.setMismatchedDevices(buildMismatchedDevices(destinationServiceIdentifier, e.getMismatchedDevices()))
.build();
} catch (final MessageTooLargeException e) {
throw Status.INVALID_ARGUMENT.withDescription("Message too large").withCause(e).asException();
}
}
/**
* Translates an internal {@link org.whispersystems.textsecuregcm.controllers.MismatchedDevices} entity to a gRPC
* {@link MismatchedDevices} entity.
@@ -6,20 +6,21 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import io.grpc.Status;
import io.grpc.StatusException;
import java.time.Clock;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import com.google.protobuf.Empty;
import org.signal.chat.errors.NotFound;
import org.signal.chat.messages.AuthenticatedSenderMessageType;
import org.signal.chat.messages.IndividualRecipientMessageBundle;
import org.signal.chat.messages.SendAuthenticatedSenderMessageRequest;
import org.signal.chat.messages.SendMessageResponse;
import org.signal.chat.messages.SendMessageAuthenticatedSenderResponse;
import org.signal.chat.messages.SendSyncMessageRequest;
import org.signal.chat.messages.SimpleMessagesGrpc;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
@@ -27,13 +28,16 @@ import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.CardinalityEstimator;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.push.MessageSender;
import org.whispersystems.textsecuregcm.spam.GrpcResponse;
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
import org.whispersystems.textsecuregcm.spam.GrpcChallengeResponse;
import org.whispersystems.textsecuregcm.spam.MessageType;
import org.whispersystems.textsecuregcm.spam.SpamCheckResult;
import org.whispersystems.textsecuregcm.spam.SpamChecker;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import static org.whispersystems.textsecuregcm.grpc.MessagesGrpcHelper.buildMismatchedDevices;
public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
private final AccountsManager accountsManager;
@@ -43,6 +47,9 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
private final SpamChecker spamChecker;
private final Clock clock;
private static final SendMessageAuthenticatedSenderResponse SEND_MESSAGE_SUCCESS_RESPONSE =
SendMessageAuthenticatedSenderResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
public MessagesGrpcService(final AccountsManager accountsManager,
final RateLimiters rateLimiters,
final MessageSender messageSender,
@@ -59,25 +66,28 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
}
@Override
public SendMessageResponse sendMessage(final SendAuthenticatedSenderMessageRequest request)
throws StatusException, RateLimitExceededException {
public SendMessageAuthenticatedSenderResponse sendMessage(final SendAuthenticatedSenderMessageRequest request)
throws RateLimitExceededException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final AciServiceIdentifier senderServiceIdentifier = new AciServiceIdentifier(authenticatedDevice.accountIdentifier());
final Account sender =
accountsManager.getByServiceIdentifier(senderServiceIdentifier).orElseThrow(Status.UNAUTHENTICATED::asException);
final Account sender = accountsManager.getByServiceIdentifier(senderServiceIdentifier)
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
final ServiceIdentifier destinationServiceIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getDestination());
if (sender.isIdentifiedBy(destinationServiceIdentifier)) {
throw Status.INVALID_ARGUMENT
.withDescription("Use `sendSyncMessage` to send messages to own account")
.asException();
throw GrpcExceptions.invalidArguments("use `sendSyncMessage` to send messages to own account");
}
final Account destination = accountsManager.getByServiceIdentifier(destinationServiceIdentifier)
.orElseThrow(Status.NOT_FOUND::asException);
final Optional<Account> maybeDestination = accountsManager.getByServiceIdentifier(destinationServiceIdentifier);
if (maybeDestination.isEmpty()) {
return SendMessageAuthenticatedSenderResponse.newBuilder()
.setDestinationNotFound(NotFound.getDefaultInstance())
.build();
}
final Account destination = maybeDestination.get();
rateLimiters.getMessagesLimiter().validate(authenticatedDevice.accountIdentifier(), destination.getUuid());
@@ -92,13 +102,13 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
}
@Override
public SendMessageResponse sendSyncMessage(final SendSyncMessageRequest request)
throws StatusException, RateLimitExceededException {
public SendMessageAuthenticatedSenderResponse sendSyncMessage(final SendSyncMessageRequest request)
throws RateLimitExceededException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final AciServiceIdentifier senderServiceIdentifier = new AciServiceIdentifier(authenticatedDevice.accountIdentifier());
final Account sender =
accountsManager.getByServiceIdentifier(senderServiceIdentifier).orElseThrow(Status.UNAUTHENTICATED::asException);
final Account sender = accountsManager.getByServiceIdentifier(senderServiceIdentifier)
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
return sendMessage(sender,
senderServiceIdentifier,
@@ -110,14 +120,14 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
request.getUrgent());
}
private SendMessageResponse sendMessage(final Account destination,
private SendMessageAuthenticatedSenderResponse sendMessage(final Account destination,
final ServiceIdentifier destinationServiceIdentifier,
final AuthenticatedDevice sender,
final AuthenticatedSenderMessageType envelopeType,
final MessageType messageType,
final IndividualRecipientMessageBundle messages,
final boolean ephemeral,
final boolean urgent) throws StatusException, RateLimitExceededException {
final boolean urgent) throws RateLimitExceededException {
try {
final int totalPayloadLength = messages.getMessagesMap().values().stream()
@@ -130,14 +140,16 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
throw e;
}
final SpamCheckResult<GrpcResponse<SendMessageResponse>> spamCheckResult =
final SpamCheckResult<GrpcChallengeResponse> spamCheckResult =
spamChecker.checkForIndividualRecipientSpamGrpc(messageType,
Optional.of(sender),
Optional.of(destination),
destinationServiceIdentifier);
if (spamCheckResult.response().isPresent()) {
return spamCheckResult.response().get().getResponseOrThrowStatus();
return SendMessageAuthenticatedSenderResponse.newBuilder()
.setChallengeRequired(spamCheckResult.response().get().getResponseOrThrowStatus())
.build();
}
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId = messages.getMessagesMap().entrySet()
@@ -168,12 +180,22 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
entry -> entry.getKey().byteValue(),
entry -> entry.getValue().getRegistrationId()));
return MessagesGrpcHelper.sendMessage(messageSender,
destination,
destinationServiceIdentifier,
messagesByDeviceId,
registrationIdsByDeviceId,
messageType == MessageType.SYNC ? Optional.of(sender.deviceId()) : Optional.empty());
try {
messageSender.sendMessages(destination,
destinationServiceIdentifier,
messagesByDeviceId,
registrationIdsByDeviceId,
messageType == MessageType.SYNC ? Optional.of(sender.deviceId()) : Optional.empty(),
RequestAttributesUtil.getUserAgent().orElse(null));
return SEND_MESSAGE_SUCCESS_RESPONSE;
} catch (final MismatchedDevicesException e) {
return SendMessageAuthenticatedSenderResponse.newBuilder()
.setMismatchedDevices(buildMismatchedDevices(destinationServiceIdentifier, e.getMismatchedDevices()))
.build();
} catch (final MessageTooLargeException e) {
throw GrpcExceptions.invalidArguments("message too large");
}
}
private static MessageProtos.Envelope.Type getEnvelopeType(final AuthenticatedSenderMessageType type) {
@@ -182,7 +204,7 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
case PREKEY_MESSAGE -> MessageProtos.Envelope.Type.PREKEY_BUNDLE;
case PLAINTEXT_CONTENT -> MessageProtos.Envelope.Type.PLAINTEXT_CONTENT;
case UNSPECIFIED, UNRECOGNIZED ->
throw Status.INVALID_ARGUMENT.withDescription("Unrecognized envelope type").asRuntimeException();
throw GrpcExceptions.invalidArguments("unrecognized envelope type");
};
}
}
@@ -28,7 +28,6 @@ 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;
@@ -81,8 +80,8 @@ public class MetricServerInterceptor implements ServerInterceptor {
tagList.add(Tag.of(TAG_METHOD_TYPE, call.getMethodDescriptor().getType().name()));
RequestAttributesUtil.getUserAgent()
.map(UserAgentTagUtil::getLibsignalAndPlatformTags)
.ifPresent(tagList::addAll);
.map(UserAgentTagUtil::getPlatformTag)
.ifPresent(tagList::add);
userAgentString
.flatMap(ua -> UserAgentTagUtil.getClientVersionTag(ua, clientReleaseManager))
.ifPresent(tagList::add);
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.grpc;
import static java.util.Objects.requireNonNull;
import io.grpc.Status;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
@@ -16,13 +15,12 @@ import javax.annotation.Nonnull;
import org.apache.commons.lang3.tuple.Pair;
import org.signal.chat.payments.GetCurrencyConversionsRequest;
import org.signal.chat.payments.GetCurrencyConversionsResponse;
import org.signal.chat.payments.ReactorPaymentsGrpc;
import org.signal.chat.payments.SimplePaymentsGrpc;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.currency.CurrencyConversionManager;
import org.whispersystems.textsecuregcm.entities.CurrencyConversionEntityList;
import reactor.core.publisher.Mono;
public class PaymentsGrpcService extends ReactorPaymentsGrpc.PaymentsImplBase {
public class PaymentsGrpcService extends SimplePaymentsGrpc.PaymentsImplBase {
private final CurrencyConversionManager currencyManager;
@@ -32,12 +30,12 @@ public class PaymentsGrpcService extends ReactorPaymentsGrpc.PaymentsImplBase {
}
@Override
public Mono<GetCurrencyConversionsResponse> getCurrencyConversions(final GetCurrencyConversionsRequest request) {
public GetCurrencyConversionsResponse getCurrencyConversions(final GetCurrencyConversionsRequest request) {
AuthenticationUtil.requireAuthenticatedDevice();
final CurrencyConversionEntityList currencyConversionEntityList = currencyManager
.getCurrencyConversions()
.orElseThrow(Status.UNAVAILABLE::asRuntimeException);
.orElseThrow(() -> GrpcExceptions.unavailable("currency conversions not available"));
final List<GetCurrencyConversionsResponse.CurrencyConversionEntity> currencyConversionEntities = currencyConversionEntityList
.getCurrencies()
@@ -48,9 +46,9 @@ public class PaymentsGrpcService extends ReactorPaymentsGrpc.PaymentsImplBase {
.build())
.toList();
return Mono.just(GetCurrencyConversionsResponse.newBuilder()
return GetCurrencyConversionsResponse.newBuilder()
.addAllCurrencies(currencyConversionEntities).setTimestamp(currencyConversionEntityList.getTimestamp())
.build());
.build();
}
@Nonnull
@@ -57,8 +57,9 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
final Account account = switch (request.getAuthenticationCase()) {
case GROUP_SEND_TOKEN -> {
groupSendTokenUtil.checkGroupSendToken(request.getGroupSendToken(), targetIdentifier);
if (!groupSendTokenUtil.checkGroupSendToken(request.getGroupSendToken(), targetIdentifier)) {
throw Status.UNAUTHENTICATED.asException();
}
yield accountsManager.getByServiceIdentifier(targetIdentifier)
.orElseThrow(Status.NOT_FOUND::asException);
}
@@ -5,12 +5,12 @@
package org.whispersystems.textsecuregcm.grpc;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import reactor.core.publisher.Mono;
class RateLimitUtil {
static Mono<Void> rateLimitByRemoteAddress(final RateLimiter rateLimiter) {
return rateLimiter.validateReactive(RequestAttributesUtil.getRemoteAddress().getHostAddress());
static void rateLimitByRemoteAddress(final RateLimiter rateLimiter) throws RateLimitExceededException {
rateLimiter.validate(RequestAttributesUtil.getRemoteAddress().getHostAddress());
}
}
@@ -15,8 +15,6 @@ public class ServerInterceptorUtil {
@SuppressWarnings("rawtypes")
private static final ServerCall.Listener NO_OP_LISTENER = new ServerCall.Listener<>() {};
private static final Metadata EMPTY_TRAILERS = new Metadata();
private ServerInterceptorUtil() {
}
@@ -32,7 +30,7 @@ public class ServerInterceptorUtil {
* @param <RespT> the type of response object returned by the server call
*/
public static <ReqT, RespT> ServerCall.Listener<ReqT> closeWithStatus(final ServerCall<ReqT, RespT> call, final Status status) {
call.close(status, EMPTY_TRAILERS);
call.close(status, new Metadata());
//noinspection unchecked
return NO_OP_LISTENER;
@@ -24,7 +24,7 @@ public class ServiceIdentifierUtil {
try {
uuid = UUIDUtil.fromByteString(serviceIdentifier.getUuid());
} catch (final IllegalArgumentException e) {
throw Status.INVALID_ARGUMENT.asRuntimeException();
throw GrpcExceptions.invalidArguments("invalid service identifier");
}
return switch (IdentityTypeUtil.fromGrpcIdentityType(serviceIdentifier.getIdentityType())) {
@@ -5,8 +5,6 @@
package org.whispersystems.textsecuregcm.grpc;
import static org.whispersystems.textsecuregcm.grpc.validators.ValidatorUtils.internalError;
import com.google.protobuf.Descriptors;
import com.google.protobuf.Message;
import io.grpc.ForwardingServerCallListener;
@@ -14,12 +12,15 @@ import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.StatusException;
import io.grpc.StatusRuntimeException;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.grpc.validators.E164FieldValidator;
import org.whispersystems.textsecuregcm.grpc.validators.EnumSpecifiedFieldValidator;
import org.whispersystems.textsecuregcm.grpc.validators.ExactlySizeFieldValidator;
import org.whispersystems.textsecuregcm.grpc.validators.FieldValidationException;
import org.whispersystems.textsecuregcm.grpc.validators.FieldValidator;
import org.whispersystems.textsecuregcm.grpc.validators.NonEmptyFieldValidator;
import org.whispersystems.textsecuregcm.grpc.validators.PresentFieldValidator;
@@ -28,6 +29,7 @@ import org.whispersystems.textsecuregcm.grpc.validators.SizeFieldValidator;
public class ValidatingInterceptor implements ServerInterceptor {
private static final Logger log = LoggerFactory.getLogger(ValidatingInterceptor.class);
private final Map<String, FieldValidator> fieldValidators = Map.of(
"org.signal.chat.require.nonEmpty", new NonEmptyFieldValidator(),
"org.signal.chat.require.present", new PresentFieldValidator(),
@@ -60,8 +62,18 @@ public class ValidatingInterceptor implements ServerInterceptor {
try {
validateMessage(message);
super.onMessage(message);
} catch (final StatusException e) {
call.close(e.getStatus(), new Metadata());
} catch (final StatusRuntimeException e) {
call.close(e.getStatus(), e.getTrailers());
forwardCalls = false;
} catch (RuntimeException runtimeException) {
final StatusRuntimeException grpcException = switch (runtimeException) {
case StatusRuntimeException e -> e;
default -> {
log.error("Failure applying request validation to message {}", call.getMethodDescriptor().getFullMethodName(), runtimeException);
yield GrpcExceptions.unavailable("failure applying request validation");
}
};
call.close(grpcException.getStatus(), grpcException.getTrailers());
forwardCalls = false;
}
}
@@ -75,40 +87,39 @@ public class ValidatingInterceptor implements ServerInterceptor {
};
}
private void validateMessage(final Object message) throws StatusException {
private void validateMessage(final Object message) {
if (message instanceof Message msg) {
try {
for (final Descriptors.FieldDescriptor fd: msg.getDescriptorForType().getFields()) {
for (final Map.Entry<Descriptors.FieldDescriptor, Object> entry: fd.getOptions().getAllFields().entrySet()) {
final Descriptors.FieldDescriptor extensionFieldDescriptor = entry.getKey();
final String extensionName = extensionFieldDescriptor.getFullName();
for (final Descriptors.FieldDescriptor fd : msg.getDescriptorForType().getFields()) {
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) {
// 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) {
try {
validator.validate(entry.getValue(), fd, msg);
} catch (FieldValidationException e) {
throw GrpcExceptions.fieldViolation(fd.getName(),
"extension %s: %s".formatted(extensionName, e.getMessage()));
}
}
// 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;
} catch (final Exception e) {
throw internalError(e);
// 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));
}
}
}
}
@@ -6,14 +6,10 @@
package org.whispersystems.textsecuregcm.grpc.validators;
import static java.util.Objects.requireNonNull;
import static org.whispersystems.textsecuregcm.grpc.validators.ValidatorUtils.internalError;
import static org.whispersystems.textsecuregcm.grpc.validators.ValidatorUtils.invalidArgument;
import com.google.protobuf.ByteString;
import com.google.protobuf.Descriptors;
import com.google.protobuf.Message;
import io.grpc.Status;
import io.grpc.StatusException;
import java.util.Set;
public abstract class BaseFieldValidator<T> implements FieldValidator {
@@ -48,111 +44,100 @@ public abstract class BaseFieldValidator<T> implements FieldValidator {
public void validate(
final Object extensionValue,
final Descriptors.FieldDescriptor fd,
final Message msg) throws StatusException {
try {
final T extensionValueTyped = resolveExtensionValue(extensionValue);
final Message msg) throws FieldValidationException {
final T extensionValueTyped = resolveExtensionValue(extensionValue);
// for the fields with an `optional` modifier, checking if the field was set
// and if not, checking if extension allows missing optional field
if (fd.hasPresence() && !msg.hasField(fd)) {
switch (missingOptionalAction) {
case FAIL -> {
throw invalidArgument("extension requires a value to be set");
}
case SUCCEED -> {
return;
}
case VALIDATE_DEFAULT_VALUE -> {
// just continuing
}
// for the fields with an `optional` modifier, checking if the field was set
// and if not, checking if extension allows missing optional field
if (fd.hasPresence() && !msg.hasField(fd)) {
switch (missingOptionalAction) {
case FAIL -> {
throw new FieldValidationException("extension requires a value to be set");
}
}
// for the `repeated` fields, checking if it's supported by the extension
if (fd.isRepeated()) {
if (applicableToRepeated) {
validateRepeatedField(extensionValueTyped, fd, msg);
case SUCCEED -> {
return;
}
throw internalError("can't apply extension to a `repeated` field");
}
// checking field type against the set of supported types
final Descriptors.FieldDescriptor.Type type = fd.getType();
if (!supportedTypes.contains(type)) {
throw internalError("can't apply extension to a field of type [%s]".formatted(type));
}
switch (type) {
case INT64, UINT64, INT32, FIXED64, FIXED32, UINT32, SFIXED32, SFIXED64, SINT32, SINT64 ->
validateIntegerNumber(extensionValueTyped, ((Number) msg.getField(fd)).longValue(), type);
case STRING ->
validateStringValue(extensionValueTyped, (String) msg.getField(fd));
case BYTES ->
validateBytesValue(extensionValueTyped, (ByteString) msg.getField(fd));
case ENUM ->
validateEnumValue(extensionValueTyped, (Descriptors.EnumValueDescriptor) msg.getField(fd));
case MESSAGE -> {
validateMessageValue(extensionValueTyped, (Message) msg.getField(fd));
}
case FLOAT, DOUBLE, BOOL, GROUP -> {
// at this moment, there are no validations specific to these types of fields
case VALIDATE_DEFAULT_VALUE -> {
// just continuing
}
}
} catch (StatusException e) {
throw new StatusException(e.getStatus().withDescription(
"field [%s], extension [%s]: %s".formatted(fd.getName(), extensionName, e.getStatus().getDescription())
), e.getTrailers());
} catch (RuntimeException e) {
throw Status.INTERNAL
.withDescription("field [%s], extension [%s]: %s".formatted(fd.getName(), extensionName, e.getMessage()))
.withCause(e)
.asException();
}
// for the `repeated` fields, checking if it's supported by the extension
if (fd.isRepeated()) {
if (applicableToRepeated) {
validateRepeatedField(extensionValueTyped, fd, msg);
return;
}
throw new IllegalArgumentException("can't apply extension %s to `repeated` field %s"
.formatted(extensionName, fd.getFullName()));
}
// checking field type against the set of supported types
final Descriptors.FieldDescriptor.Type type = fd.getType();
if (!supportedTypes.contains(type)) {
throw new IllegalArgumentException("can't apply extension %s to field %s of type %s".formatted(
extensionName, fd.getFullName(), type));
}
switch (type) {
case INT64, UINT64, INT32, FIXED64, FIXED32, UINT32, SFIXED32, SFIXED64, SINT32, SINT64 ->
validateIntegerNumber(extensionValueTyped, ((Number) msg.getField(fd)).longValue(), type);
case STRING -> validateStringValue(extensionValueTyped, (String) msg.getField(fd));
case BYTES -> validateBytesValue(extensionValueTyped, (ByteString) msg.getField(fd));
case ENUM -> validateEnumValue(extensionValueTyped, (Descriptors.EnumValueDescriptor) msg.getField(fd));
case MESSAGE -> {
validateMessageValue(extensionValueTyped, (Message) msg.getField(fd));
}
case FLOAT, DOUBLE, BOOL, GROUP -> {
// at this moment, there are no validations specific to these types of fields
}
}
}
protected abstract T resolveExtensionValue(final Object extensionValue) throws StatusException;
protected abstract T resolveExtensionValue(final Object extensionValue) throws FieldValidationException;
protected void validateRepeatedField(
final T extensionValue,
final Descriptors.FieldDescriptor fd,
final Message msg) throws StatusException {
throw internalError("`validateRepeatedField` method needs to be implemented");
final Message msg) throws FieldValidationException {
throw new UnsupportedOperationException("`validateRepeatedField` method needs to be implemented");
}
protected void validateIntegerNumber(
final T extensionValue,
final long fieldValue, final Descriptors.FieldDescriptor.Type type) throws StatusException {
throw internalError("`validateIntegerNumber` method needs to be implemented");
final long fieldValue, final Descriptors.FieldDescriptor.Type type) throws FieldValidationException {
throw new UnsupportedOperationException("`validateIntegerNumber` method needs to be implemented");
}
protected void validateStringValue(
final T extensionValue,
final String fieldValue) throws StatusException {
throw internalError("`validateStringValue` method needs to be implemented");
final String fieldValue) throws FieldValidationException {
throw new UnsupportedOperationException("`validateStringValue` method needs to be implemented");
}
protected void validateBytesValue(
final T extensionValue,
final ByteString fieldValue) throws StatusException {
throw internalError("`validateBytesValue` method needs to be implemented");
final ByteString fieldValue) throws FieldValidationException {
throw new UnsupportedOperationException("`validateBytesValue` method needs to be implemented");
}
protected void validateEnumValue(
final T extensionValue,
final Descriptors.EnumValueDescriptor enumValueDescriptor) throws StatusException {
throw internalError("`validateEnumValue` method needs to be implemented");
final Descriptors.EnumValueDescriptor enumValueDescriptor) throws FieldValidationException {
throw new UnsupportedOperationException("`validateEnumValue` method needs to be implemented");
}
protected void validateMessageValue(
final T extensionValue,
final Message message) throws StatusException {
throw internalError("`validateMessageValue` method needs to be implemented");
final Message message) throws FieldValidationException {
throw new UnsupportedOperationException("`validateMessageValue` method needs to be implemented");
}
protected static boolean requireFlagExtension(final Object extensionValue) throws StatusException {
protected static boolean requireFlagExtension(final Object extensionValue) throws FieldValidationException {
if (extensionValue instanceof Boolean flagIsOn && flagIsOn) {
return true;
}
throw internalError("only value `true` is allowed");
throw new UnsupportedOperationException("only value `true` is allowed");
}
}
@@ -5,10 +5,7 @@
package org.whispersystems.textsecuregcm.grpc.validators;
import static org.whispersystems.textsecuregcm.grpc.validators.ValidatorUtils.invalidArgument;
import com.google.protobuf.Descriptors;
import io.grpc.StatusException;
import java.util.Set;
import org.whispersystems.textsecuregcm.util.ImpossiblePhoneNumberException;
import org.whispersystems.textsecuregcm.util.NonNormalizedPhoneNumberException;
@@ -21,18 +18,18 @@ public class E164FieldValidator extends BaseFieldValidator<Boolean> {
}
@Override
protected Boolean resolveExtensionValue(final Object extensionValue) throws StatusException {
protected Boolean resolveExtensionValue(final Object extensionValue) throws FieldValidationException {
return requireFlagExtension(extensionValue);
}
@Override
protected void validateStringValue(
final Boolean extensionValue,
final String fieldValue) throws StatusException {
final String fieldValue) throws FieldValidationException {
try {
Util.requireNormalizedNumber(fieldValue);
} catch (final ImpossiblePhoneNumberException | NonNormalizedPhoneNumberException e) {
throw invalidArgument("value is not in E164 format");
throw new FieldValidationException("value is not in E164 format");
}
}
}
@@ -5,10 +5,7 @@
package org.whispersystems.textsecuregcm.grpc.validators;
import static org.whispersystems.textsecuregcm.grpc.validators.ValidatorUtils.invalidArgument;
import com.google.protobuf.Descriptors;
import io.grpc.StatusException;
import java.util.Set;
public class EnumSpecifiedFieldValidator extends BaseFieldValidator<Boolean> {
@@ -18,16 +15,16 @@ public class EnumSpecifiedFieldValidator extends BaseFieldValidator<Boolean> {
}
@Override
protected Boolean resolveExtensionValue(final Object extensionValue) throws StatusException {
protected Boolean resolveExtensionValue(final Object extensionValue) throws FieldValidationException {
return requireFlagExtension(extensionValue);
}
@Override
protected void validateEnumValue(
final Boolean extensionValue,
final Descriptors.EnumValueDescriptor enumValueDescriptor) throws StatusException {
final Descriptors.EnumValueDescriptor enumValueDescriptor) throws FieldValidationException {
if (enumValueDescriptor.getIndex() <= 0) {
throw invalidArgument("enum field must be specified");
throw new FieldValidationException("enum field must be specified");
}
}
}
@@ -5,12 +5,9 @@
package org.whispersystems.textsecuregcm.grpc.validators;
import static org.whispersystems.textsecuregcm.grpc.validators.ValidatorUtils.invalidArgument;
import com.google.protobuf.ByteString;
import com.google.protobuf.Descriptors;
import com.google.protobuf.Message;
import io.grpc.StatusException;
import java.util.List;
import java.util.Set;
@@ -24,7 +21,7 @@ public class ExactlySizeFieldValidator extends BaseFieldValidator<Set<Integer>>
}
@Override
protected Set<Integer> resolveExtensionValue(final Object extensionValue) throws StatusException {
protected Set<Integer> resolveExtensionValue(final Object extensionValue) {
//noinspection unchecked
return Set.copyOf((List<Integer>) extensionValue);
}
@@ -32,32 +29,32 @@ public class ExactlySizeFieldValidator extends BaseFieldValidator<Set<Integer>>
@Override
protected void validateBytesValue(
final Set<Integer> permittedSizes,
final ByteString fieldValue) throws StatusException {
final ByteString fieldValue) throws FieldValidationException {
if (permittedSizes.contains(fieldValue.size())) {
return;
}
throw invalidArgument("byte array length is [%d] but expected to be one of %s".formatted(fieldValue.size(), permittedSizes));
throw new FieldValidationException("byte array length is [%d] but expected to be one of %s".formatted(fieldValue.size(), permittedSizes));
}
@Override
protected void validateStringValue(
final Set<Integer> permittedSizes,
final String fieldValue) throws StatusException {
final String fieldValue) throws FieldValidationException {
if (permittedSizes.contains(fieldValue.length())) {
return;
}
throw invalidArgument("string length is [%d] but expected to be one of %s".formatted(fieldValue.length(), permittedSizes));
throw new FieldValidationException("string length is [%d] but expected to be one of %s".formatted(fieldValue.length(), permittedSizes));
}
@Override
protected void validateRepeatedField(
final Set<Integer> permittedSizes,
final Descriptors.FieldDescriptor fd,
final Message msg) throws StatusException {
final Message msg) throws FieldValidationException {
final int size = msg.getRepeatedFieldCount(fd);
if (permittedSizes.contains(size)) {
return;
}
throw invalidArgument("list size is [%d] but expected to be one of %s".formatted(size, permittedSizes));
throw new FieldValidationException("list size is [%d] but expected to be one of %s".formatted(size, permittedSizes));
}
}
@@ -0,0 +1,11 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc.validators;
public class FieldValidationException extends Exception {
public FieldValidationException(String message) {
super(message);
}
}
@@ -7,10 +7,9 @@ package org.whispersystems.textsecuregcm.grpc.validators;
import com.google.protobuf.Descriptors;
import com.google.protobuf.Message;
import io.grpc.StatusException;
public interface FieldValidator {
void validate(Object extensionValue, Descriptors.FieldDescriptor fd, Message msg)
throws StatusException;
throws FieldValidationException;
}
@@ -5,12 +5,9 @@
package org.whispersystems.textsecuregcm.grpc.validators;
import static org.whispersystems.textsecuregcm.grpc.validators.ValidatorUtils.invalidArgument;
import com.google.protobuf.ByteString;
import com.google.protobuf.Descriptors;
import com.google.protobuf.Message;
import io.grpc.StatusException;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
@@ -24,38 +21,38 @@ public class NonEmptyFieldValidator extends BaseFieldValidator<Boolean> {
}
@Override
protected Boolean resolveExtensionValue(final Object extensionValue) throws StatusException {
protected Boolean resolveExtensionValue(final Object extensionValue) throws FieldValidationException {
return requireFlagExtension(extensionValue);
}
@Override
protected void validateBytesValue(
final Boolean extensionValue,
final ByteString fieldValue) throws StatusException {
final ByteString fieldValue) throws FieldValidationException {
if (!fieldValue.isEmpty()) {
return;
}
throw invalidArgument("byte array expected to be non-empty");
throw new FieldValidationException("byte array expected to be non-empty");
}
@Override
protected void validateStringValue(
final Boolean extensionValue,
final String fieldValue) throws StatusException {
final String fieldValue) throws FieldValidationException {
if (StringUtils.isNotEmpty(fieldValue)) {
return;
}
throw invalidArgument("string expected to be non-empty");
throw new FieldValidationException("string expected to be non-empty");
}
@Override
protected void validateRepeatedField(
final Boolean extensionValue,
final Descriptors.FieldDescriptor fd,
final Message msg) throws StatusException {
final Message msg) throws FieldValidationException {
if (msg.getRepeatedFieldCount(fd) > 0) {
return;
}
throw invalidArgument("repeated field is expected to be non-empty");
throw new FieldValidationException("repeated field is expected to be non-empty");
}
}
@@ -5,11 +5,8 @@
package org.whispersystems.textsecuregcm.grpc.validators;
import static org.whispersystems.textsecuregcm.grpc.validators.ValidatorUtils.invalidArgument;
import com.google.protobuf.Descriptors;
import com.google.protobuf.Message;
import io.grpc.StatusException;
import java.util.Set;
public class PresentFieldValidator extends BaseFieldValidator<Boolean> {
@@ -22,14 +19,14 @@ public class PresentFieldValidator extends BaseFieldValidator<Boolean> {
}
@Override
protected Boolean resolveExtensionValue(final Object extensionValue) throws StatusException {
protected Boolean resolveExtensionValue(final Object extensionValue) throws FieldValidationException {
return requireFlagExtension(extensionValue);
}
@Override
protected void validateMessageValue(final Boolean extensionValue, final Message msg) throws StatusException {
protected void validateMessageValue(final Boolean extensionValue, final Message msg) throws FieldValidationException {
if (msg == null) {
throw invalidArgument("message expected to be present");
throw new FieldValidationException("message expected to be present");
}
}
}
@@ -5,10 +5,7 @@
package org.whispersystems.textsecuregcm.grpc.validators;
import static org.whispersystems.textsecuregcm.grpc.validators.ValidatorUtils.invalidArgument;
import com.google.protobuf.Descriptors;
import io.grpc.StatusException;
import java.util.Set;
import org.signal.chat.require.ValueRangeConstraint;
@@ -37,7 +34,7 @@ public class RangeFieldValidator extends BaseFieldValidator<Range> {
}
@Override
protected Range resolveExtensionValue(final Object extensionValue) throws StatusException {
protected Range resolveExtensionValue(final Object extensionValue) {
final ValueRangeConstraint rangeConstraint = (ValueRangeConstraint) extensionValue;
final long min = rangeConstraint.hasMin() ? rangeConstraint.getMin() : Long.MIN_VALUE;
final long max = rangeConstraint.hasMax() ? rangeConstraint.getMax() : Long.MAX_VALUE;
@@ -48,13 +45,13 @@ public class RangeFieldValidator extends BaseFieldValidator<Range> {
protected void validateIntegerNumber(
final Range range,
final long fieldValue,
final Descriptors.FieldDescriptor.Type type) throws StatusException {
final Descriptors.FieldDescriptor.Type type) throws FieldValidationException {
if (fieldValue < 0 && UNSIGNED_TYPES.contains(type)) {
throw invalidArgument("field value is expected to be within the [%d, %d] range".formatted(
throw new FieldValidationException("field value is expected to be within the [%d, %d] range".formatted(
range.min(), range.max()));
}
if (fieldValue < range.min() || fieldValue > range.max()) {
throw invalidArgument("field value is [%d] but expected to be within the [%d, %d] range".formatted(
throw new FieldValidationException("field value is [%d] but expected to be within the [%d, %d] range".formatted(
fieldValue, range.min(), range.max()));
}
}
@@ -5,12 +5,9 @@
package org.whispersystems.textsecuregcm.grpc.validators;
import static org.whispersystems.textsecuregcm.grpc.validators.ValidatorUtils.invalidArgument;
import com.google.protobuf.ByteString;
import com.google.protobuf.Descriptors;
import com.google.protobuf.Message;
import io.grpc.StatusException;
import java.util.Set;
import org.signal.chat.require.SizeConstraint;
@@ -24,7 +21,7 @@ public class SizeFieldValidator extends BaseFieldValidator<Range> {
}
@Override
protected Range resolveExtensionValue(final Object extensionValue) throws StatusException {
protected Range resolveExtensionValue(final Object extensionValue) throws FieldValidationException {
final SizeConstraint sizeConstraint = (SizeConstraint) extensionValue;
final int min = sizeConstraint.hasMin() ? sizeConstraint.getMin() : 0;
final int max = sizeConstraint.hasMax() ? sizeConstraint.getMax() : Integer.MAX_VALUE;
@@ -32,26 +29,26 @@ public class SizeFieldValidator extends BaseFieldValidator<Range> {
}
@Override
protected void validateBytesValue(final Range range, final ByteString fieldValue) throws StatusException {
protected void validateBytesValue(final Range range, final ByteString fieldValue) throws FieldValidationException {
if (fieldValue.size() < range.min() || fieldValue.size() > range.max()) {
throw invalidArgument("field value is [%d] but expected to be within the [%d, %d] range".formatted(
throw new FieldValidationException("field value is [%d] but expected to be within the [%d, %d] range".formatted(
fieldValue.size(), range.min(), range.max()));
}
}
@Override
protected void validateStringValue(final Range range, final String fieldValue) throws StatusException {
protected void validateStringValue(final Range range, final String fieldValue) throws FieldValidationException {
if (fieldValue.length() < range.min() || fieldValue.length() > range.max()) {
throw invalidArgument("field value is [%d] but expected to be within the [%d, %d] range".formatted(
throw new FieldValidationException("field value is [%d] but expected to be within the [%d, %d] range".formatted(
fieldValue.length(), range.min(), range.max()));
}
}
@Override
protected void validateRepeatedField(final Range range, final Descriptors.FieldDescriptor fd, final Message msg) throws StatusException {
protected void validateRepeatedField(final Range range, final Descriptors.FieldDescriptor fd, final Message msg) throws FieldValidationException {
final int size = msg.getRepeatedFieldCount(fd);
if (size < range.min() || size > range.max()) {
throw invalidArgument("field value is [%d] but expected to be within the [%d, %d] range".formatted(
throw new FieldValidationException("field value is [%d] but expected to be within the [%d, %d] range".formatted(
size, range.min(), range.max()));
}
}
@@ -23,18 +23,6 @@ public final class ValidatorUtils {
// noop
}
public static StatusException invalidArgument(final String description) {
return Status.INVALID_ARGUMENT.withDescription(description).asException();
}
public static StatusException internalError(final String description) {
return Status.INTERNAL.withDescription(description).asException();
}
public static StatusException internalError(final Exception cause) {
return Status.INTERNAL.withCause(cause).asException();
}
public static Optional<Auth> serviceAuthExtensionValue(final ServerServiceDefinition serviceDefinition) {
return serviceExtensionValueByName(serviceDefinition, REQUIRE_AUTH_EXTENSION_NAME)
.map(val -> Auth.valueOf((Descriptors.EnumValueDescriptor) val));
@@ -116,10 +116,7 @@ public class KeyTransparencyServiceClient implements Managed {
final Optional<ByteString> usernameHash,
final Optional<E164SearchRequest> e164SearchRequest,
final Optional<Long> lastTreeHeadSize,
final long distinguishedTreeHeadSize,
final Optional<Long> aciVersion,
final Optional<Long> e164Version,
final Optional<Long> usernameHashVersion) {
final long distinguishedTreeHeadSize) {
final SearchRequest.Builder searchRequestBuilder = SearchRequest.newBuilder()
.setAci(aci)
.setAciIdentityKey(aciIdentityKey);
@@ -127,10 +124,6 @@ public class KeyTransparencyServiceClient implements Managed {
usernameHash.ifPresent(searchRequestBuilder::setUsernameHash);
e164SearchRequest.ifPresent(searchRequestBuilder::setE164SearchRequest);
aciVersion.ifPresent(version -> searchRequestBuilder.setAciVersion(version.intValue()));
e164Version.ifPresent(version -> searchRequestBuilder.setE164Version(version.intValue()));
usernameHashVersion.ifPresent(version -> searchRequestBuilder.setUsernameHashVersion(version.intValue()));
final ConsistencyParameters.Builder consistency = ConsistencyParameters.newBuilder()
.setDistinguished(distinguishedTreeHeadSize);
lastTreeHeadSize.ifPresent(consistency::setLast);
@@ -57,7 +57,6 @@ public class BackupMetrics {
final boolean oversize,
final Optional<Long> backupLength) {
DistributionSummary.builder(MESSAGE_BACKUP_SIZE_NAME)
.publishPercentileHistogram(true)
.tags(Tags.of(
UserAgentTagUtil.getPlatformTag(authenticatedBackupUser.userAgent()),
Tag.of("tier", authenticatedBackupUser.backupLevel().name().toLowerCase()),
@@ -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);
}
}
@@ -49,7 +49,9 @@ 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()
@@ -150,21 +152,21 @@ public class CallQualitySurveyManager {
}
@VisibleForTesting
static void validateRequest(final SubmitCallQualitySurveyRequest request) {
static void validateRequest(final SubmitCallQualitySurveyRequest request) throws CallQualityInvalidArgumentsException {
if (request.getStartTimestamp() == 0) {
throw new IllegalArgumentException("Start timestamp not specified");
throw new CallQualityInvalidArgumentsException("Start timestamp not specified", "startTimestamp");
}
if (request.getEndTimestamp() == 0) {
throw new IllegalArgumentException("End timestamp not specified");
throw new CallQualityInvalidArgumentsException("End timestamp not specified", "endTimestamp");
}
if (StringUtils.isBlank(request.getCallType())) {
throw new IllegalArgumentException("Call type not specified");
throw new CallQualityInvalidArgumentsException("Call type not specified", "callType");
}
if (StringUtils.isBlank(request.getCallEndReason())) {
throw new IllegalArgumentException("Call end reason not specified");
throw new CallQualityInvalidArgumentsException("Call end reason not specified", "callEndReason");
}
}
}
@@ -86,7 +86,6 @@ public final class MessageMetrics {
UserAgentTagUtil.getClientVersionTag(userAgent, clientReleaseManager).ifPresent(tags::add);
Timer.builder(DELIVERY_LATENCY_TIMER_NAME)
.publishPercentileHistogram(true)
.tags(tags)
.register(metricRegistry)
.record(Duration.between(Instant.ofEpochMilli(serverTimestamp), Instant.now()));
@@ -31,6 +31,9 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import org.whispersystems.textsecuregcm.util.logging.UriInfoUtil;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
import org.whispersystems.textsecuregcm.util.ua.UserAgent;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
/**
* Gathers and reports HTTP request metrics at the Jetty container level, which sits above Jersey. In order to get
@@ -49,7 +52,6 @@ public class MetricsHttpChannelListener implements HttpChannel.Listener, Contain
private static final Logger logger = LoggerFactory.getLogger(MetricsHttpChannelListener.class);
private record RequestInfo(String path, String method, int statusCode, @Nullable String userAgent) {
}
private final ClientReleaseManager clientReleaseManager;
@@ -136,15 +138,30 @@ public class MetricsHttpChannelListener implements HttpChannel.Listener, Contain
final RequestInfo requestInfo = getRequestInfo(request);
@Nullable final UserAgent userAgent;
{
UserAgent parsedUserAgent;
try {
parsedUserAgent = UserAgentUtil.parseUserAgentString(requestInfo.userAgent());
} catch (final UnrecognizedUserAgentException e) {
parsedUserAgent = null;
}
userAgent = parsedUserAgent;
}
final Tag platformTag = UserAgentTagUtil.getPlatformTag(userAgent);
final List<Tag> tags = new ArrayList<>(5);
tags.add(Tag.of(PATH_TAG, requestInfo.path()));
tags.add(Tag.of(METHOD_TAG, requestInfo.method()));
tags.add(Tag.of(STATUS_CODE_TAG, String.valueOf(requestInfo.statusCode())));
tags.add(Tag.of(TRAFFIC_SOURCE_TAG, TrafficSource.HTTP.name().toLowerCase()));
tags.addAll(UserAgentTagUtil.getLibsignalAndPlatformTags(requestInfo.userAgent()));
tags.add(platformTag);
final Optional<Tag> maybeClientVersionTag =
UserAgentTagUtil.getClientVersionTag(requestInfo.userAgent, clientReleaseManager);
UserAgentTagUtil.getClientVersionTag(userAgent, clientReleaseManager);
maybeClientVersionTag.ifPresent(tags::add);
@@ -154,7 +171,7 @@ public class MetricsHttpChannelListener implements HttpChannel.Listener, Contain
meterRegistry.counter(REQUEST_BYTES_COUNTER_NAME, tags).increment(request.getContentRead());
maybeClientVersionTag.ifPresent(clientVersionTag -> meterRegistry.counter(REQUESTS_BY_VERSION_COUNTER_NAME,
Tags.of(clientVersionTag, UserAgentTagUtil.getPlatformTag(requestInfo.userAgent)))
Tags.of(clientVersionTag, platformTag))
.increment());
}
@@ -17,7 +17,6 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nullable;
import org.eclipse.jetty.io.ArrayByteBufferPool;
import org.glassfish.jersey.server.ContainerResponse;
import org.glassfish.jersey.server.monitoring.RequestEvent;
import org.glassfish.jersey.server.monitoring.RequestEventListener;
@@ -25,6 +24,9 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import org.whispersystems.textsecuregcm.util.logging.UriInfoUtil;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
import org.whispersystems.textsecuregcm.util.ua.UserAgent;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
import org.whispersystems.websocket.WebSocketResourceProvider;
/**
@@ -57,6 +59,9 @@ public class MetricsRequestEventListener implements RequestEventListener {
@VisibleForTesting
static final String AUTHENTICATED_TAG = "authenticated";
@VisibleForTesting
static final String LISTEN_PORT_TAG = "listenPort";
private final TrafficSource trafficSource;
private final MeterRegistry meterRegistry;
@@ -82,7 +87,25 @@ public class MetricsRequestEventListener implements RequestEventListener {
public void onEvent(final RequestEvent event) {
if (event.getType() == RequestEvent.Type.FINISHED) {
if (!event.getUriInfo().getMatchedTemplates().isEmpty()) {
final List<Tag> tags = new ArrayList<>(5);
@Nullable final UserAgent userAgent;
{
final List<String> userAgentValues = event.getContainerRequest().getRequestHeader(HttpHeaders.USER_AGENT);
final String userAgentString = userAgentValues != null && !userAgentValues.isEmpty() ? userAgentValues.getFirst() : null;
UserAgent parsedUserAgent;
try {
parsedUserAgent = UserAgentUtil.parseUserAgentString(userAgentString);
} catch (final UnrecognizedUserAgentException e) {
parsedUserAgent = null;
}
userAgent = parsedUserAgent;
}
final Tag platformTag = UserAgentTagUtil.getPlatformTag(userAgent);
final List<Tag> tags = new ArrayList<>();
tags.add(Tag.of(PATH_TAG, UriInfoUtil.getPathTemplate(event.getUriInfo())));
tags.add(Tag.of(METHOD_TAG, event.getContainerRequest().getMethod()));
tags.add(Tag.of(STATUS_CODE_TAG, String.valueOf(Optional
@@ -96,20 +119,18 @@ public class MetricsRequestEventListener implements RequestEventListener {
.map(Optional::isPresent)
.orElse(false)
.toString()));
@Nullable final String userAgent;
{
final List<String> userAgentValues = event.getContainerRequest().getRequestHeader(HttpHeaders.USER_AGENT);
userAgent = userAgentValues != null && !userAgentValues.isEmpty() ? userAgentValues.getFirst() : null;
}
tags.addAll(UserAgentTagUtil.getLibsignalAndPlatformTags(userAgent));
tags.add(platformTag);
final Optional<Tag> maybeClientVersionTag =
UserAgentTagUtil.getClientVersionTag(userAgent, clientReleaseManager);
maybeClientVersionTag.ifPresent(tags::add);
Optional.ofNullable(event.getContainerRequest().getProperty(WebSocketResourceProvider.LISTEN_PORT_PROPERTY))
.filter(Integer.class::isInstance)
.map(Integer.class::cast)
.ifPresent(port -> tags.add(Tag.of(LISTEN_PORT_TAG, Integer.toString(port))));
meterRegistry.counter(REQUEST_COUNTER_NAME, tags).increment();
Optional.ofNullable(event.getContainerRequest().getProperty(WebSocketResourceProvider.REQUEST_LENGTH_PROPERTY))
@@ -125,7 +146,7 @@ public class MetricsRequestEventListener implements RequestEventListener {
.ifPresent(bytes -> meterRegistry.counter(RESPONSE_BYTES_COUNTER_NAME, tags).increment(bytes));
maybeClientVersionTag.ifPresent(clientVersionTag -> meterRegistry.counter(REQUESTS_BY_VERSION_COUNTER_NAME,
Tags.of(clientVersionTag, UserAgentTagUtil.getPlatformTag(userAgent)))
Tags.of(clientVersionTag, platformTag))
.increment());
}
}
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.metrics;
import com.codahale.metrics.SharedMetricRegistries;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.core.setup.Environment;
import io.dropwizard.lifecycle.Managed;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Metrics;
@@ -30,7 +29,6 @@ import io.opentelemetry.sdk.resources.ResourceBuilder;
import java.time.Duration;
import java.util.Map;
import java.util.Optional;
import org.eclipse.jetty.util.component.LifeCycle;
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
@@ -142,7 +140,7 @@ public class MetricsUtil {
config.meterFilter(new MeterFilter() {
@Override
public DistributionStatisticConfig configure(final Meter.Id id, final DistributionStatisticConfig config) {
return defaultDistributionStatisticConfig.merge(config);
return config.merge(defaultDistributionStatisticConfig);
}
})
// Remove high-cardinality `command` tags from Lettuce metrics and prepend "chat." to meter names
@@ -149,7 +149,6 @@ public class MicrometerAwsSdkMetricPublisher implements MetricPublisher {
DistributionSummary.builder(API_CALL_RETRY_COUNT_DISTRIBUTION_NAME)
.tags(tags)
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry)
.record(retryCount);
@@ -179,21 +178,18 @@ public class MicrometerAwsSdkMetricPublisher implements MetricPublisher {
Optional.ofNullable(httpMetricsByName.get("ConcurrencyAcquireDuration"))
.ifPresent(channelAcquisitionDurationMetricRecord -> Timer.builder(CHANNEL_ACQUISITION_TIMER_NAME)
.tags(attemptTags)
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry)
.record((Duration) channelAcquisitionDurationMetricRecord.value()));
Optional.ofNullable(httpMetricsByName.get("LeasedConcurrency"))
.ifPresent(concurrentRequestsMetricRecord -> DistributionSummary.builder(CONCURRENT_REQUESTS_DISTRIBUTION_NAME)
.tags(attemptTags)
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry)
.record((int) concurrentRequestsMetricRecord.value()));
Optional.ofNullable(httpMetricsByName.get("PendingConcurrencyAcquires"))
.ifPresent(pendingChannelAcquisitionsMetricRecord -> DistributionSummary.builder(PENDING_CHANNEL_ACQUISITIONS_DISTRIBUTION_NAME)
.tags(attemptTags)
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry)
.record((int) pendingChannelAcquisitionsMetricRecord.value()));
});
@@ -3,96 +3,100 @@ package org.whispersystems.textsecuregcm.metrics;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.Timer;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.whispersystems.textsecuregcm.util.EnumMapUtil;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
import org.whispersystems.textsecuregcm.util.ua.UserAgent;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
import org.whispersystems.websocket.session.WebSocketSessionContext;
public class OpenWebSocketCounter {
private static final String WEBSOCKET_CLOSED_COUNTER_NAME = name(OpenWebSocketCounter.class, "websocketClosed");
private final ClientReleaseManager clientReleaseManager;
private final String newConnectionCounterName;
private final String durationTimerName;
private final Tags baseTags;
private final Tags tags;
private final Map<Tags, AtomicInteger> openWebsocketsByTags;
private final AtomicInteger totalConnections;
private final Map<ClientPlatform, AtomicInteger> openWebsocketsByClientPlatform;
private final AtomicInteger openWebsocketsFromUnknownPlatforms;
private static final int MAX_COUNTERS = 4096;
public OpenWebSocketCounter(final String openWebSocketGaugeName,
final String newConnectionCounterName,
final String durationTimerName) {
private static final String OPEN_WEBSOCKET_GAUGE_NAME = name(OpenWebSocketCounter.class, "openWebsockets");
private static final String TOTAL_CONNECTIONS_GAUGE_NAME = name(OpenWebSocketCounter.class, "totalOpenWebsockets");
private static final String NEW_CONNECTION_COUNTER_NAME = name(OpenWebSocketCounter.class, "newConnections");
private static final String WEB_SOCKET_CLOSED_COUNTER_NAME = name(OpenWebSocketCounter.class, "websocketClosed");
private static final String SESSION_DURATION_TIMER_NAME = name(OpenWebSocketCounter.class, "sessionDuration");
private static final String GAUGE_COUNT_GAUGE_NAME = name(OpenWebSocketCounter.class, "gaugeCount");
this(openWebSocketGaugeName, newConnectionCounterName, durationTimerName, Tags.empty());
}
public OpenWebSocketCounter(final String webSocketType,
final ClientReleaseManager clientReleaseManager) {
public OpenWebSocketCounter(final String openWebSocketGaugeName,
final String newConnectionCounterName,
final String durationTimerName,
final Tags tags) {
this.clientReleaseManager = clientReleaseManager;
this.newConnectionCounterName = newConnectionCounterName;
this.durationTimerName = durationTimerName;
this.baseTags = Tags.of("webSocketType", webSocketType);
this.openWebsocketsByTags = Metrics.gaugeMapSize(GAUGE_COUNT_GAUGE_NAME, baseTags, new ConcurrentHashMap<>());
this.tags = tags;
openWebsocketsByClientPlatform = EnumMapUtil.toEnumMap(ClientPlatform.class,
clientPlatform -> buildGauge(openWebSocketGaugeName, clientPlatform.name().toLowerCase(), tags));
openWebsocketsFromUnknownPlatforms = buildGauge(openWebSocketGaugeName, "unknown", tags);
}
private static AtomicInteger buildGauge(final String gaugeName, final String clientPlatformName, final Tags tags) {
return Metrics.gauge(gaugeName,
tags.and(Tag.of(UserAgentTagUtil.PLATFORM_TAG, clientPlatformName)),
new AtomicInteger(0));
this.totalConnections = Metrics.gauge(TOTAL_CONNECTIONS_GAUGE_NAME, baseTags, new AtomicInteger(0));
}
public void countOpenWebSocket(final WebSocketSessionContext context) {
final Timer.Sample sample = Timer.start();
// We have to jump through some hoops here to have something "effectively final" for the close listener, but
// assignable from a `catch` block.
final AtomicInteger openWebSocketCounter;
@Nullable final UserAgent userAgent;
{
AtomicInteger calculatedOpenWebSocketCounter;
UserAgent parsedUserAgent;
try {
final ClientPlatform clientPlatform =
UserAgentUtil.parseUserAgentString(context.getClient().getUserAgent()).platform();
calculatedOpenWebSocketCounter = openWebsocketsByClientPlatform.get(clientPlatform);
parsedUserAgent = UserAgentUtil.parseUserAgentString(context.getClient().getUserAgent());
} catch (final UnrecognizedUserAgentException e) {
calculatedOpenWebSocketCounter = openWebsocketsFromUnknownPlatforms;
parsedUserAgent = null;
}
openWebSocketCounter = calculatedOpenWebSocketCounter;
userAgent = parsedUserAgent;
}
openWebSocketCounter.incrementAndGet();
final Tags tagsWithClientPlatform = baseTags.and(UserAgentTagUtil.getPlatformTag(userAgent));
final Tags tagsWithClientPlatform = tags.and(UserAgentTagUtil.getPlatformTag(context.getClient().getUserAgent()));
final Optional<AtomicInteger> maybeOpenWebSocketCounter;
{
final Tags tagsWithAdditionalSpecifiers = tagsWithClientPlatform
.and(UserAgentTagUtil.getClientVersionTag(userAgent, clientReleaseManager)
.map(Tags::of)
.orElseGet(Tags::empty))
.and(UserAgentTagUtil.getAdditionalSpecifierTags(userAgent));
Metrics.counter(newConnectionCounterName, tagsWithClientPlatform).increment();
maybeOpenWebSocketCounter = getCounter(tagsWithAdditionalSpecifiers);
}
maybeOpenWebSocketCounter.ifPresent(AtomicInteger::incrementAndGet);
totalConnections.incrementAndGet();
Metrics.counter(NEW_CONNECTION_COUNTER_NAME, tagsWithClientPlatform).increment();
context.addWebsocketClosedListener((_, statusCode, _) -> {
sample.stop(Timer.builder(durationTimerName)
.publishPercentileHistogram(true)
sample.stop(Timer.builder(SESSION_DURATION_TIMER_NAME)
.tags(tagsWithClientPlatform)
.register(Metrics.globalRegistry));
openWebSocketCounter.decrementAndGet();
maybeOpenWebSocketCounter.ifPresent(AtomicInteger::decrementAndGet);
totalConnections.decrementAndGet();
Metrics.counter(WEBSOCKET_CLOSED_COUNTER_NAME, tagsWithClientPlatform.and("status", String.valueOf(statusCode)))
Metrics.counter(WEB_SOCKET_CLOSED_COUNTER_NAME, tagsWithClientPlatform.and("status", String.valueOf(statusCode)))
.increment();
});
}
private Optional<AtomicInteger> getCounter(final Tags tags) {
// Make a reasonable effort to avoid creating new counters if we're already full
return openWebsocketsByTags.size() >= MAX_COUNTERS
? Optional.ofNullable(openWebsocketsByTags.get(tags))
: Optional.of(openWebsocketsByTags.computeIfAbsent(tags,
t -> Metrics.gauge(OPEN_WEBSOCKET_GAUGE_NAME, t, new AtomicInteger(0))));
}
}
@@ -6,16 +6,20 @@
package org.whispersystems.textsecuregcm.metrics;
import io.micrometer.core.instrument.Tag;
import java.util.List;
import io.micrometer.core.instrument.Tags;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.HttpHeaders;
import java.util.Optional;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.whispersystems.textsecuregcm.WhisperServerVersion;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
import org.whispersystems.textsecuregcm.util.ua.UserAgent;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
import javax.annotation.Nullable;
/**
* Utility class for extracting platform/version metrics tags from User-Agent strings.
@@ -24,15 +28,24 @@ public class UserAgentTagUtil {
public static final String PLATFORM_TAG = "platform";
public static final String VERSION_TAG = "clientVersion";
public static final String LIBSIGNAL_TAG = "libsignal";
public static final String OPERATING_SYSTEM_TAG = "operatingSystem";
public static final String OPERATING_SYSTEM_VERSION_TAG = "operatingSystemVersion";
public static final String LIBSIGNAL_VERSION_TAG = "libsignalVersion";
public static final String SERVER_UA =
String.format("Signal-Server/%s (%s)", WhisperServerVersion.getServerVersion(), UUID.randomUUID());
private static final Pattern STANDARD_ADDITIONAL_SPECIFIERS_PATTERN =
Pattern.compile("^(Android|iOS|Windows|macOS|Linux)[ /](\\S+) libsignal/([\\d.]+).*$", Pattern.CASE_INSENSITIVE);
private UserAgentTagUtil() {
}
public static Tag getPlatformTag(final String userAgentString) {
public static Tag getPlatformTag(final ContainerRequestContext containerRequestContext) {
return getPlatformTag(containerRequestContext.getHeaderString(HttpHeaders.USER_AGENT));
}
public static Tag getPlatformTag(@Nullable final String userAgentString) {
if (SERVER_UA.equals(userAgentString)) {
return Tag.of(PLATFORM_TAG, "server");
@@ -52,33 +65,51 @@ public class UserAgentTagUtil {
return Tag.of(PLATFORM_TAG, userAgent != null ? userAgent.platform().name().toLowerCase() : "unrecognized");
}
public static Optional<Tag> getClientVersionTag(final String userAgentString, final ClientReleaseManager clientReleaseManager) {
try {
final UserAgent userAgent = UserAgentUtil.parseUserAgentString(userAgentString);
public static Optional<Tag> getClientVersionTag(@Nullable final String userAgentString,
final ClientReleaseManager clientReleaseManager) {
if (clientReleaseManager.isVersionActive(userAgent.platform(), userAgent.version())) {
return Optional.of(Tag.of(VERSION_TAG, userAgent.version().toString()));
}
try {
return getClientVersionTag(UserAgentUtil.parseUserAgentString(userAgentString), clientReleaseManager);
} catch (final UnrecognizedUserAgentException e) {
return Optional.empty();
}
}
public static Optional<Tag> getClientVersionTag(@Nullable final UserAgent userAgent,
final ClientReleaseManager clientReleaseManager) {
if (userAgent == null) {
return Optional.empty();
}
return clientReleaseManager.isVersionActive(userAgent.platform(), userAgent.version())
? Optional.of(Tag.of(VERSION_TAG, userAgent.version().toString()))
: Optional.empty();
}
public static Tags getAdditionalSpecifierTags(@Nullable final String userAgentString) {
UserAgent userAgent = null;
try {
userAgent = UserAgentUtil.parseUserAgentString(userAgentString);
} catch (final UnrecognizedUserAgentException ignored) {
}
return Optional.empty();
return getAdditionalSpecifierTags(userAgent);
}
public static List<Tag> getLibsignalAndPlatformTags(final String userAgentString) {
String platform;
boolean libsignal;
try {
final UserAgent userAgent = UserAgentUtil.parseUserAgentString(userAgentString);
platform = userAgent.platform().name().toLowerCase();
libsignal = StringUtils.contains(userAgent.additionalSpecifiers(), "libsignal");
} catch (final UnrecognizedUserAgentException e) {
platform = "unrecognized";
libsignal = false;
public static Tags getAdditionalSpecifierTags(@Nullable final UserAgent userAgent) {
if (userAgent == null || StringUtils.isBlank(userAgent.additionalSpecifiers())) {
return Tags.empty();
}
return List.of(Tag.of(PLATFORM_TAG, platform), Tag.of(LIBSIGNAL_TAG, String.valueOf(libsignal)));
}
final Matcher matcher = STANDARD_ADDITIONAL_SPECIFIERS_PATTERN.matcher(userAgent.additionalSpecifiers());
return matcher.matches()
? Tags.of(
OPERATING_SYSTEM_TAG, matcher.group(1),
OPERATING_SYSTEM_VERSION_TAG, matcher.group(2),
LIBSIGNAL_VERSION_TAG, matcher.group(3))
: Tags.empty();
}
}
@@ -36,7 +36,6 @@ public class MultiRecipientMessageProvider implements MessageBodyReader<SealedSe
private static final DistributionSummary RECIPIENT_COUNT_DISTRIBUTION = DistributionSummary
.builder(name(MultiRecipientMessageProvider.class, "recipients"))
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry);
@Override
@@ -352,7 +352,6 @@ public class MessageSender {
Tag.of("multiRecipientMessage", String.valueOf(isMultiRecipientMessage)),
Tag.of("syncMessage", String.valueOf(isSyncMessage)),
Tag.of("story", String.valueOf(isStory))))
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry)
.record(contentLength);
@@ -18,6 +18,7 @@ import org.whispersystems.textsecuregcm.telephony.CarrierData;
* 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
@@ -36,6 +37,7 @@ import org.whispersystems.textsecuregcm.telephony.CarrierData;
* @see org.whispersystems.textsecuregcm.entities.VerificationSessionResponse
*/
public record VerificationSession(
String sessionId,
@Nullable String pushChallenge,
@Nullable CarrierData carrierData,
List<Information> requestedInformation,
@@ -44,7 +44,7 @@ public class SchedulingUtil {
final LocalTime preferredTime,
final Clock clock) {
final ZonedDateTime candidateNotificationTime = getZoneId(account, clock)
final ZonedDateTime candidateNotificationTime = getZoneId(account.getNumber(), clock)
.map(zoneId -> {
Metrics.counter(PARSED_TIMEZONE_COUNTER_NAME, HAS_TIMEZONE_TAG_NAME, String.valueOf(true)).increment();
return ZonedDateTime.now(clock.withZone(zoneId)).with(preferredTime);
@@ -64,15 +64,23 @@ public class SchedulingUtil {
}
@VisibleForTesting
static Optional<ZoneId> getZoneId(final Account account, final Clock clock) {
public static Optional<ZoneId> getZoneId(final String e164, final Clock clock) {
try {
final Phonenumber.PhoneNumber phoneNumber = PhoneNumberUtil.getInstance().parse(account.getNumber(), null);
final Phonenumber.PhoneNumber phoneNumber = PhoneNumberUtil.getInstance().parse(e164, null);
final List<String> timeZonesForNumber =
List<String> timeZonesForNumber =
PhoneNumberToTimeZonesMapper.getInstance().getTimeZonesForNumber(phoneNumber);
if (timeZonesForNumber.equals(List.of(PhoneNumberToTimeZonesMapper.getUnknownTimeZone()))) {
return Optional.empty();
if (isUnknownTimeZone(timeZonesForNumber)) {
// The more general getTimeZonesForNumber has a guard on PhoneNumberType.UNKONWN, returning the “unknown”
// time zone for these numbers. In these cases, we'll first fall back to the geographical lookup, which looks up
// a result based on the country code and national significant number.
timeZonesForNumber =
PhoneNumberToTimeZonesMapper.getInstance().getTimeZonesForGeographicalNumber(phoneNumber);
if (isUnknownTimeZone(timeZonesForNumber)) {
return Optional.empty();
}
}
final Instant now = clock.instant();
@@ -91,7 +99,7 @@ public class SchedulingUtil {
.collect(Collectors.toMap(
ZoneId::getRules,
Function.identity(),
(v1, v2) -> v2));
(_, v2) -> v2));
// Sort the ZoneRules by the offsets they produce
final List<ZoneRules> zoneRulesSortedByOffset = byOffset.keySet()
@@ -105,4 +113,8 @@ public class SchedulingUtil {
return Optional.empty();
}
}
static boolean isUnknownTimeZone(final List<String> timeZonesForNumber) {
return timeZonesForNumber.equals(List.of(PhoneNumberToTimeZonesMapper.getUnknownTimeZone()));
}
}
@@ -0,0 +1,72 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.spam;
import io.grpc.StatusRuntimeException;
import java.util.function.Function;
import javax.annotation.Nullable;
import org.signal.chat.messages.ChallengeRequired;
/// A gRPC status or a challenge message to communicate to callers that a message has been flagged as potential spam.
public class GrpcChallengeResponse {
@Nullable
private final StatusRuntimeException statusException;
@Nullable
private final ChallengeRequired response;
private GrpcChallengeResponse(final @Nullable StatusRuntimeException statusException,
@Nullable final ChallengeRequired response) {
this.statusException = statusException;
this.response = response;
if (!((statusException == null) ^ (response == null))) {
throw new IllegalArgumentException("exactly one of statusException and response must be non-null");
}
}
/// Constructs a new response object with the given status and no challenge
///
/// @param status the status to send to callers
/// @return a new response object with the given status and no challenge
public static GrpcChallengeResponse withStatusException(final StatusRuntimeException status) {
return new GrpcChallengeResponse(status, null);
}
/// Constructs a new response object with the given challenge message.
///
/// @param response the challenge message to send to the caller
/// @return a new response object with the given challenge message
public static GrpcChallengeResponse withResponse(final ChallengeRequired response) {
return new GrpcChallengeResponse(null, response);
}
/// Returns the challenge message contained within this response or throws the contained status as a
/// [StatusRuntimeException] if no challenge message is specified.
///
/// @return the [ChallengeRequired] message
/// @throws StatusRuntimeException if no challenge message is specified
public ChallengeRequired getResponseOrThrowStatus() throws StatusRuntimeException {
if (statusException != null) {
throw statusException;
}
return response;
}
/// If this response contains a challenge message, throw a status generated using statusMapper. Otherwise, throw the
/// status.
///
/// @param statusMapper A function that converts a [ChallengeRequired] message into a
/// [StatusRuntimeException]
/// @throws StatusRuntimeException the contained or mapped status exception
public void throwStatusOr(Function<ChallengeRequired, StatusRuntimeException> statusMapper)
throws StatusRuntimeException {
if (statusException != null) {
throw statusException;
}
throw statusMapper.apply(response);
}
}
@@ -1,72 +0,0 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.spam;
import io.grpc.Status;
import io.grpc.StatusException;
import javax.annotation.Nullable;
import java.util.Optional;
/**
* A combination of a gRPC status and response message to communicate to callers that a message has been flagged as
* potential spam.
*
* @param <R> the type of response object
*/
public class GrpcResponse<R> {
private final Status status;
@Nullable
private final R response;
private GrpcResponse(final Status status, @Nullable final R response) {
this.status = status;
this.response = response;
}
/**
* Constructs a new response object with the given status and no response message.
*
* @param status the status to send to callers
*
* @return a new response object with the given status and no response message
*
* @param <R> the type of response object
*/
public static <R> GrpcResponse<R> withStatus(final Status status) {
return new GrpcResponse<>(status, null);
}
/**
* Constructs a new response object with a status of {@link Status#OK} and the given response message.
*
* @param response the response to send to the caller
*
* @return a new response object with a status of {@link Status#OK} and the given response message
*
* @param <R> the type of response object
*/
public static <R> GrpcResponse<R> withResponse(final R response) {
return new GrpcResponse<>(Status.OK, response);
}
/**
* Returns the message body contained within this response or throws the contained status as a {@link StatusException}
* if no message body is specified.
*
* @return the message body contained within this response
*
* @throws StatusException if no message body is specified
*/
public R getResponseOrThrowStatus() throws StatusException {
if (response != null) {
return response;
}
throw status.asException();
}
}
@@ -5,10 +5,8 @@
package org.whispersystems.textsecuregcm.spam;
import jakarta.ws.rs.container.ContainerRequestContext;
import java.util.Optional;
import jakarta.ws.rs.core.Response;
import org.signal.chat.messages.SendMessageResponse;
import org.signal.chat.messages.SendMultiRecipientMessageResponse;
import java.util.Optional;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.Account;
@@ -55,7 +53,7 @@ public interface SpamChecker {
* @return A {@link SpamCheckResult}
*/
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
SpamCheckResult<GrpcResponse<SendMessageResponse>> checkForIndividualRecipientSpamGrpc(
SpamCheckResult<GrpcChallengeResponse> checkForIndividualRecipientSpamGrpc(
final MessageType messageType,
final Optional<org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice> maybeSource,
final Optional<Account> maybeDestination,
@@ -68,7 +66,7 @@ public interface SpamChecker {
*
* @return A {@link SpamCheckResult}
*/
SpamCheckResult<GrpcResponse<SendMultiRecipientMessageResponse>> checkForMultiRecipientSpamGrpc(final MessageType messageType);
SpamCheckResult<GrpcChallengeResponse> checkForMultiRecipientSpamGrpc(final MessageType messageType);
static SpamChecker noop() {
@@ -92,7 +90,7 @@ public interface SpamChecker {
}
@Override
public SpamCheckResult<GrpcResponse<SendMessageResponse>> checkForIndividualRecipientSpamGrpc(final MessageType messageType,
public SpamCheckResult<GrpcChallengeResponse> checkForIndividualRecipientSpamGrpc(final MessageType messageType,
final Optional<org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice> maybeSource,
final Optional<Account> maybeDestination,
final ServiceIdentifier destinationIdentifier) {
@@ -101,7 +99,7 @@ public interface SpamChecker {
}
@Override
public SpamCheckResult<GrpcResponse<SendMultiRecipientMessageResponse>> checkForMultiRecipientSpamGrpc(
public SpamCheckResult<GrpcChallengeResponse> checkForMultiRecipientSpamGrpc(
final MessageType messageType) {
return new SpamCheckResult<>(Optional.empty(), Optional.empty());
@@ -376,7 +376,7 @@ public class Accounts {
writeItems.addAll(additionalWriteItems);
return dynamoDbAsyncClient.transactWriteItems(TransactWriteItemsRequest.builder().transactItems(writeItems).build())
.thenApply(response -> {
.thenApply(_ -> {
accountToCreate.setVersion(accountToCreate.getVersion() + 1);
return (Void) null;
})
@@ -495,18 +495,13 @@ public class Accounts {
});
}
/**
* Reserve a username hash under the account UUID
* @return a future that completes once the username hash has been reserved; may fail with an
* {@link ContestedOptimisticLockException} if the account has been updated or there are concurrent updates to the
* account or constraint records, and with an
* {@link UsernameHashNotAvailableException} if the username was taken by someone else
*/
public CompletableFuture<Void> reserveUsernameHash(
final Account account,
final byte[] reservedUsernameHash,
final Duration ttl) {
/// Reserve a username hash under the account UUID
///
/// @throws ContestedOptimisticLockException if the account has been updated or there are concurrent updates to the
/// account or constraint records, and with an
/// @throws UsernameHashNotAvailableException if the username was taken by someone else
public void reserveUsernameHash(final Account account, final byte[] reservedUsernameHash, final Duration ttl)
throws ContestedOptimisticLockException, UsernameHashNotAvailableException {
final Timer.Sample sample = Timer.start();
@@ -521,19 +516,24 @@ public class Accounts {
// What we'd really like to do is set expirationTime = max(oldExpirationTime, now + ttl), but dynamodb doesn't
// support that. Instead, we'll set expiration if it's greater than the existing expiration, otherwise retry
final long expirationTime = clock.instant().plus(ttl).getEpochSecond();
return tryReserveUsernameHash(account, reservedUsernameHash, expirationTime)
.exceptionallyCompose(ExceptionUtils.exceptionallyHandler(TtlConflictException.class, ttlConflict ->
// retry (once) with the returned expiration time
tryReserveUsernameHash(account, reservedUsernameHash, ttlConflict.getExistingExpirationSeconds())))
.whenComplete((response, throwable) -> {
sample.stop(RESERVE_USERNAME_TIMER);
boolean succeeded = false;
if (throwable == null) {
account.setVersion(account.getVersion() + 1);
} else {
account.setReservedUsernameHash(maybeOriginalReservation.orElse(null));
}
});
try {
tryReserveUsernameHash(account, reservedUsernameHash, expirationTime);
succeeded = true;
} catch (final TtlConflictException e) {
// retry (once) with the returned expiration time
tryReserveUsernameHash(account, reservedUsernameHash, e.getExistingExpirationSeconds());
succeeded = true;
} finally {
sample.stop(RESERVE_USERNAME_TIMER);
if (succeeded) {
account.setVersion(account.getVersion() + 1);
} else {
account.setReservedUsernameHash(maybeOriginalReservation.orElse(null));
}
}
}
private static class TtlConflictException extends ContestedOptimisticLockException {
@@ -548,20 +548,21 @@ public class Accounts {
}
}
/**
* Try to reserve the provided usernameHash
*
* @param updatedAccount The account, already updated to reserve the provided usernameHash
* @param reservedUsernameHash The usernameHash to reserve
* @param expirationTimeSeconds When the reservation should expire
* @return A future that completes successfully if the usernameHash was reserved
* @throws TtlConflictException if the usernameHash was already reserved but with a longer TTL. The operation should
* be retried with the returned {@link TtlConflictException#getExistingExpirationSeconds()}
*/
private CompletableFuture<Void> tryReserveUsernameHash(
/// Try to reserve the provided usernameHash
///
/// @param updatedAccount The account, already updated to reserve the provided usernameHash
/// @param reservedUsernameHash The usernameHash to reserve
/// @param expirationTimeSeconds When the reservation should expire
///
/// @throws ContestedOptimisticLockException in the event of concurrent modifications to the account
/// @throws UsernameHashNotAvailableException if the username hash is already taken
/// @throws TtlConflictException if the usernameHash was already reserved but with a longer TTL. The
/// operation should be retried with the returned
/// {@link TtlConflictException#getExistingExpirationSeconds()}
private void tryReserveUsernameHash(
final Account updatedAccount,
final byte[] reservedUsernameHash,
final long expirationTimeSeconds) {
final long expirationTimeSeconds) throws ContestedOptimisticLockException, TtlConflictException, UsernameHashNotAvailableException {
// Use account UUID as a "reservation token" - by providing this, the client proves ownership of the hash
final UUID uuid = updatedAccount.getUuid();
@@ -597,34 +598,31 @@ public class Accounts {
writeItems.add(UpdateAccountSpec.forAccount(accountsTableName, updatedAccount).transactItem());
return dynamoDbAsyncClient
.transactWriteItems(TransactWriteItemsRequest.builder().transactItems(writeItems).build())
.thenRun(Util.NOOP)
.exceptionally(ExceptionUtils.exceptionallyHandler(TransactionCanceledException.class, e -> {
// If the constraint table update failed the condition check, the username's taken and we should stop
// trying. However,
if (conditionalCheckFailed(e.cancellationReasons().get(0))) {
// The constraint table update failed the condition check. It could be because the username was taken,
// or because we need to retry with a longer TTL
final Map<String, AttributeValue> item = e.cancellationReasons().getFirst().item();
final UUID existingOwner = AttributeValues.getUUID(item, UsernameTable.ATTR_ACCOUNT_UUID, null);
final boolean confirmed = AttributeValues.getBool(item, UsernameTable.ATTR_CONFIRMED, false);
final long existingTtl = AttributeValues.getLong(item, UsernameTable.ATTR_TTL, 0L);
if (uuid.equals(existingOwner) && !confirmed && existingTtl > expirationTimeSeconds) {
// We failed because we provided a shorter TTL than the one that exists on the reservation. The caller
// can retry with updated expiration time.
throw new TtlConflictException(existingTtl);
}
throw ExceptionUtils.wrap(new UsernameHashNotAvailableException());
} else if (conditionalCheckFailed(e.cancellationReasons().get(1)) ||
e.cancellationReasons().stream().anyMatch(Accounts::isTransactionConflict)) {
// The accounts table fails the conditional check or either table was concurrently updated, it's an
// optimistic locking failure and we should try again.
throw new ContestedOptimisticLockException();
} else {
throw ExceptionUtils.wrap(e);
}
}));
try {
dynamoDbClient.transactWriteItems(TransactWriteItemsRequest.builder().transactItems(writeItems).build());
} catch (final TransactionCanceledException e) {
if (conditionalCheckFailed(e.cancellationReasons().get(0))) {
// The constraint table update failed the condition check. It could be because the username was taken,
// or because we need to retry with a longer TTL
final Map<String, AttributeValue> item = e.cancellationReasons().getFirst().item();
final UUID existingOwner = AttributeValues.getUUID(item, UsernameTable.ATTR_ACCOUNT_UUID, null);
final boolean confirmed = AttributeValues.getBool(item, UsernameTable.ATTR_CONFIRMED, false);
final long existingTtl = AttributeValues.getLong(item, UsernameTable.ATTR_TTL, 0L);
if (uuid.equals(existingOwner) && !confirmed && existingTtl > expirationTimeSeconds) {
// We failed because we provided a shorter TTL than the one that exists on the reservation. The caller
// can retry with updated expiration time.
throw new TtlConflictException(existingTtl);
}
throw new UsernameHashNotAvailableException();
} else if (conditionalCheckFailed(e.cancellationReasons().get(1)) ||
e.cancellationReasons().stream().anyMatch(Accounts::isTransactionConflict)) {
// The accounts table fails the conditional check or either table was concurrently updated, it's an
// optimistic locking failure and we should try again.
throw new ContestedOptimisticLockException();
} else {
throw e;
}
}
}
/**
@@ -719,138 +717,133 @@ public class Accounts {
.build()).build();
}
/**
* Confirm (set) a previously reserved username hash
*
* @param account to update
* @param usernameHash believed to be available
* @param encryptedUsername the encrypted form of the previously reserved username; used for the username link
* @return a future that completes once the username hash has been confirmed; may fail with an
* {@link ContestedOptimisticLockException} if the account has been updated or there are concurrent updates to the
* account or constraint records, and with an
* {@link UsernameHashNotAvailableException} if the username was taken by someone else
*/
public CompletableFuture<Void> confirmUsernameHash(final Account account, final byte[] usernameHash, @Nullable final byte[] encryptedUsername) {
/// Confirm (set) a previously reserved username hash
///
/// @param account to update
/// @param usernameHash believed to be available
/// @param encryptedUsername the encrypted form of the previously reserved username; used for the username link
///
/// @throws ContestedOptimisticLockException if the account has been updated or there are concurrent updates to the
/// account or constraint records
/// @throws UsernameHashNotAvailableException if the username was taken by someone else
public void confirmUsernameHash(final Account account, final byte[] usernameHash, @Nullable final byte[] encryptedUsername)
throws ContestedOptimisticLockException, UsernameHashNotAvailableException {
final Timer.Sample sample = Timer.start();
if (usernameHash == null) {
throw new IllegalArgumentException("Cannot confirm a null usernameHash");
}
return pickLinkHandle(account, usernameHash)
.thenCompose(linkHandle -> {
final Optional<byte[]> maybeOriginalUsernameHash = account.getUsernameHash();
final Account updatedAccount = AccountUtil.cloneAccountAsNotStale(account);
updatedAccount.setUsernameHash(usernameHash);
updatedAccount.setReservedUsernameHash(null);
updatedAccount.setUsernameLinkDetails(encryptedUsername == null ? null : linkHandle, encryptedUsername);
final Instant now = clock.instant();
final Optional<byte[]> holdToRemove = maybeOriginalUsernameHash
.flatMap(hold -> addToHolds(updatedAccount, hold, now));
final UUID linkHandle = pickLinkHandle(account, usernameHash);
final List<TransactWriteItem> writeItems = new ArrayList<>();
final Optional<byte[]> maybeOriginalUsernameHash = account.getUsernameHash();
final Account updatedAccount = AccountUtil.cloneAccountAsNotStale(account);
updatedAccount.setUsernameHash(usernameHash);
updatedAccount.setReservedUsernameHash(null);
updatedAccount.setUsernameLinkDetails(encryptedUsername == null ? null : linkHandle, encryptedUsername);
// 0: add the username hash to the constraint table, wiping out the ttl if we had already reserved the hash
writeItems.add(TransactWriteItem.builder().put(Put.builder()
.tableName(usernamesConstraintTableName)
.item(Map.of(
UsernameTable.ATTR_ACCOUNT_UUID, AttributeValues.fromUUID(updatedAccount.getUuid()),
UsernameTable.KEY_USERNAME_HASH, AttributeValues.fromByteArray(usernameHash),
UsernameTable.ATTR_CONFIRMED, AttributeValues.fromBool(true)))
// it's not in the constraint table OR it's expired OR it was reserved by us
.conditionExpression("attribute_not_exists(#username_hash) OR #ttl < :now OR (#aci = :aci AND #confirmed = :confirmed)")
.expressionAttributeNames(Map.of(
"#username_hash", UsernameTable.KEY_USERNAME_HASH,
"#ttl", UsernameTable.ATTR_TTL,
"#aci", UsernameTable.ATTR_ACCOUNT_UUID,
"#confirmed", UsernameTable.ATTR_CONFIRMED))
.expressionAttributeValues(Map.of(
":now", AttributeValues.fromLong(clock.instant().getEpochSecond()),
":aci", AttributeValues.fromUUID(updatedAccount.getUuid()),
":confirmed", AttributeValues.fromBool(false)))
.returnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD)
.build())
.build());
final Instant now = clock.instant();
final Optional<byte[]> holdToRemove =
maybeOriginalUsernameHash.flatMap(hold -> addToHolds(updatedAccount, hold, now));
// 1: update the account object (conditioned on the version increment)
writeItems.add(UpdateAccountSpec.forAccount(accountsTableName, updatedAccount).transactItem());
final List<TransactWriteItem> writeItems = new ArrayList<>();
// 2?: Add a temporary hold for the old username to stop others from claiming it
maybeOriginalUsernameHash.ifPresent(originalUsernameHash ->
writeItems.add(holdUsernameTransactItem(updatedAccount.getUuid(), originalUsernameHash, now)));
// 0: add the username hash to the constraint table, wiping out the ttl if we had already reserved the hash
writeItems.add(TransactWriteItem.builder().put(Put.builder()
.tableName(usernamesConstraintTableName)
.item(Map.of(
UsernameTable.ATTR_ACCOUNT_UUID, AttributeValues.fromUUID(updatedAccount.getUuid()),
UsernameTable.KEY_USERNAME_HASH, AttributeValues.fromByteArray(usernameHash),
UsernameTable.ATTR_CONFIRMED, AttributeValues.fromBool(true)))
// it's not in the constraint table OR it's expired OR it was reserved by us
.conditionExpression("attribute_not_exists(#username_hash) OR #ttl < :now OR (#aci = :aci AND #confirmed = :confirmed)")
.expressionAttributeNames(Map.of(
"#username_hash", UsernameTable.KEY_USERNAME_HASH,
"#ttl", UsernameTable.ATTR_TTL,
"#aci", UsernameTable.ATTR_ACCOUNT_UUID,
"#confirmed", UsernameTable.ATTR_CONFIRMED))
.expressionAttributeValues(Map.of(
":now", AttributeValues.fromLong(clock.instant().getEpochSecond()),
":aci", AttributeValues.fromUUID(updatedAccount.getUuid()),
":confirmed", AttributeValues.fromBool(false)))
.returnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD)
.build())
.build());
// 3?: Adding that hold may have caused our account to exceed our maximum holds. Release an old hold
holdToRemove.ifPresent(oldHold ->
writeItems.add(releaseHoldIfAllowedTransactItem(updatedAccount.getUuid(), oldHold, now)));
// 1: update the account object (conditioned on the version increment)
writeItems.add(UpdateAccountSpec.forAccount(accountsTableName, updatedAccount).transactItem());
return dynamoDbAsyncClient.transactWriteItems(TransactWriteItemsRequest.builder().transactItems(writeItems).build())
.thenApply(ignored -> updatedAccount);
})
.thenApply(updatedAccount -> {
account.setUsernameHash(usernameHash);
account.setReservedUsernameHash(null);
account.setUsernameLinkDetails(updatedAccount.getUsernameLinkHandle(), updatedAccount.getEncryptedUsername().orElse(null));
account.setUsernameHolds(updatedAccount.getUsernameHolds());
account.setVersion(account.getVersion() + 1);
return (Void) null;
})
.exceptionally(ExceptionUtils.exceptionallyHandler(TransactionCanceledException.class, e -> {
// If the constraint table update failed the condition check, the username's taken and we should stop
// trying. However, if the accounts table fails the conditional check or either table was concurrently
// updated, it's an optimistic locking failure and we should try again.
if (conditionalCheckFailed(e.cancellationReasons().get(0))) {
throw ExceptionUtils.wrap(new UsernameHashNotAvailableException());
} else if (conditionalCheckFailed(e.cancellationReasons().get(1)) // Account version conflict
// When we looked at the holds on our account, we thought we still held the corresponding username
// reservation. But it turned out that someone else has taken the reservation since. This means that the
// TTL on the hold must have just expired, so if we retry we should see that our hold is expired, and we
// won't try to remove it again.
|| (e.cancellationReasons().size() > 3 && conditionalCheckFailed(e.cancellationReasons().get(3)))
// concurrent update on any table
|| e.cancellationReasons().stream().anyMatch(Accounts::isTransactionConflict)) {
throw new ContestedOptimisticLockException();
} else {
throw ExceptionUtils.wrap(e);
}
}))
.whenComplete((ignored, throwable) -> sample.stop(SET_USERNAME_TIMER));
// 2?: Add a temporary hold for the old username to stop others from claiming it
maybeOriginalUsernameHash.ifPresent(originalUsernameHash ->
writeItems.add(holdUsernameTransactItem(updatedAccount.getUuid(), originalUsernameHash, now)));
// 3?: Adding that hold may have caused our account to exceed our maximum holds. Release an old hold
holdToRemove.ifPresent(oldHold ->
writeItems.add(releaseHoldIfAllowedTransactItem(updatedAccount.getUuid(), oldHold, now)));
try {
dynamoDbClient.transactWriteItems(TransactWriteItemsRequest.builder().transactItems(writeItems).build());
account.setUsernameHash(usernameHash);
account.setReservedUsernameHash(null);
account.setUsernameLinkDetails(updatedAccount.getUsernameLinkHandle(), updatedAccount.getEncryptedUsername().orElse(null));
account.setUsernameHolds(updatedAccount.getUsernameHolds());
account.setVersion(account.getVersion() + 1);
} catch (final TransactionCanceledException e) {
if (conditionalCheckFailed(e.cancellationReasons().get(0))) {
throw new UsernameHashNotAvailableException();
} else if (conditionalCheckFailed(e.cancellationReasons().get(1)) // Account version conflict
// When we looked at the holds on our account, we thought we still held the corresponding username
// reservation. But it turned out that someone else has taken the reservation since. This means that the
// TTL on the hold must have just expired, so if we retry we should see that our hold is expired, and we
// won't try to remove it again.
|| (e.cancellationReasons().size() > 3 && conditionalCheckFailed(e.cancellationReasons().get(3)))
// concurrent update on any table
|| e.cancellationReasons().stream().anyMatch(Accounts::isTransactionConflict)) {
throw new ContestedOptimisticLockException();
} else {
throw e;
}
} finally {
sample.stop(SET_USERNAME_TIMER);
}
}
private CompletableFuture<UUID> pickLinkHandle(final Account account, final byte[] usernameHash) {
private UUID pickLinkHandle(final Account account, final byte[] usernameHash) {
if (account.getUsernameLinkHandle() == null) {
// There's no old link handle, so we can just use a randomly generated link handle
return CompletableFuture.completedFuture(UUID.randomUUID());
return UUID.randomUUID();
}
// Otherwise, there's an existing link handle. If this is the result of an account being re-registered, we should
// preserve the link handle.
return dynamoDbAsyncClient.getItem(GetItemRequest.builder()
final GetItemResponse response = dynamoDbClient.getItem(GetItemRequest.builder()
.tableName(usernamesConstraintTableName)
.key(Map.of(UsernameTable.KEY_USERNAME_HASH, AttributeValues.b(usernameHash)))
.projectionExpression(UsernameTable.ATTR_RECLAIMABLE).build())
.thenApply(response -> {
if (response.hasItem() && AttributeValues.getBool(response.item(), UsernameTable.ATTR_RECLAIMABLE, false)) {
// this username reservation indicates it's a username waiting to be "reclaimed"
return account.getUsernameLinkHandle();
}
// There was no existing username reservation, or this was a standard "new" username. Either way, we should
// generate a new link handle.
return UUID.randomUUID();
});
.projectionExpression(UsernameTable.ATTR_RECLAIMABLE).build());
if (response.hasItem() && AttributeValues.getBool(response.item(), UsernameTable.ATTR_RECLAIMABLE, false)) {
// this username reservation indicates it's a username waiting to be "reclaimed"
return account.getUsernameLinkHandle();
}
// There was no existing username reservation, or this was a standard "new" username. Either way, we should
// generate a new link handle.
return UUID.randomUUID();
}
/**
* Clear the username hash and link from the given account
*
* @param account to update
* @return a future that completes once the username data has been cleared;
* it can fail with a {@link ContestedOptimisticLockException} if there are concurrent updates
* to the account or username constraint records.
*/
public CompletableFuture<Void> clearUsernameHash(final Account account) {
/// Clear the username hash and link from the given account
///
/// @param account to update
///
/// @throws ContestedOptimisticLockException if there are concurrent updates to the account or username constraint
/// records
public void clearUsernameHash(final Account account) throws ContestedOptimisticLockException {
if (account.getUsernameHash().isEmpty()) {
// no username to clear
return CompletableFuture.completedFuture(null);
return;
}
final byte[] usernameHash = account.getUsernameHash().get();
final Timer.Sample sample = Timer.start();
@@ -872,28 +865,29 @@ public class Accounts {
// 2?: Adding that hold may have caused our account to exceed our maximum holds. Release an old hold
holdToRemove.ifPresent(oldHold -> items.add(releaseHoldIfAllowedTransactItem(updatedAccount.getUuid(), oldHold, now)));
return dynamoDbAsyncClient.transactWriteItems(TransactWriteItemsRequest.builder().transactItems(items).build())
.thenAccept(ignored -> {
account.setUsernameHash(null);
account.setUsernameLinkDetails(null, null);
account.setVersion(account.getVersion() + 1);
account.setUsernameHolds(updatedAccount.getUsernameHolds());
})
.exceptionally(ExceptionUtils.exceptionallyHandler(TransactionCanceledException.class, e -> {
if (conditionalCheckFailed(e.cancellationReasons().get(0)) // Account version conflict
// When we looked at the holds on our account, we thought we still held the corresponding username
// reservation. But it turned out that someone else has taken the reservation since. This means that the
// TTL on the hold must have just expired, so if we retry we should see that our hold is expired, and we
// won't try to remove it again.
|| (e.cancellationReasons().size() > 2 && conditionalCheckFailed(e.cancellationReasons().get(2)))
// concurrent update on any table
|| e.cancellationReasons().stream().anyMatch(Accounts::isTransactionConflict)) {
throw new ContestedOptimisticLockException();
} else {
throw ExceptionUtils.wrap(e);
}
}))
.whenComplete((ignored, throwable) -> sample.stop(CLEAR_USERNAME_HASH_TIMER));
try {
dynamoDbClient.transactWriteItems(TransactWriteItemsRequest.builder().transactItems(items).build());
account.setUsernameHash(null);
account.setUsernameLinkDetails(null, null);
account.setVersion(account.getVersion() + 1);
account.setUsernameHolds(updatedAccount.getUsernameHolds());
} catch (final TransactionCanceledException e) {
if (conditionalCheckFailed(e.cancellationReasons().get(0)) // Account version conflict
// When we looked at the holds on our account, we thought we still held the corresponding username
// reservation. But it turned out that someone else has taken the reservation since. This means that the
// TTL on the hold must have just expired, so if we retry we should see that our hold is expired, and we
// won't try to remove it again.
|| (e.cancellationReasons().size() > 2 && conditionalCheckFailed(e.cancellationReasons().get(2)))
// concurrent update on any table
|| e.cancellationReasons().stream().anyMatch(Accounts::isTransactionConflict)) {
throw new ContestedOptimisticLockException();
} else {
throw e;
}
} finally {
sample.stop(CLEAR_USERNAME_HASH_TIMER);
}
}
/**
@@ -1056,7 +1050,7 @@ public class Accounts {
return dynamoDbAsyncClient.transactWriteItems(TransactWriteItemsRequest.builder()
.transactItems(writeItems)
.build())
.thenApply(response -> {
.thenApply(_ -> {
account.setVersion(account.getVersion() + 1);
return (Void) null;
})
@@ -1142,7 +1136,7 @@ public class Accounts {
return itemByGsiKeyAsync(accountsTableName, USERNAME_LINK_TO_UUID_INDEX, ATTR_USERNAME_LINK_UUID, AttributeValues.fromUUID(usernameLinkHandle))
.thenApply(maybeItem -> maybeItem.map(Accounts::fromItem))
.whenComplete((account, throwable) -> sample.stop(GET_BY_USERNAME_LINK_HANDLE_TIMER));
.whenComplete((_, _) -> sample.stop(GET_BY_USERNAME_LINK_HANDLE_TIMER));
}
@Nonnull
@@ -1253,11 +1247,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();
}
@@ -1288,7 +1278,7 @@ public class Accounts {
final String tableName,
final String keyName,
final AttributeValue keyValue) {
return getByIndirectLookup(timer, tableName, keyName, keyValue, i -> true);
return getByIndirectLookup(timer, tableName, keyName, keyValue, _ -> true);
}
@Nonnull
@@ -1298,7 +1288,7 @@ public class Accounts {
final String keyName,
final AttributeValue keyValue) {
return getByIndirectLookupAsync(timer, tableName, keyName, keyValue, i -> true);
return getByIndirectLookupAsync(timer, tableName, keyName, keyValue, _ -> true);
}
@Nonnull
@@ -1611,7 +1601,7 @@ public class Accounts {
sb.append("???");
sb.append(StringUtils.length(phoneNumber) < 3
? ""
: phoneNumber.substring(phoneNumber.length() - 2, phoneNumber.length()));
: phoneNumber.substring(phoneNumber.length() - 2));
return sb.toString();
}
}
@@ -5,8 +5,8 @@
package org.whispersystems.textsecuregcm.storage;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import static java.util.Objects.requireNonNull;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectWriter;
@@ -66,7 +66,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevices;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
@@ -88,6 +87,7 @@ import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.RegistrationIdValidator;
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.ThrowingConsumer;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Scheduler;
@@ -109,11 +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 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);
@@ -133,12 +134,10 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
private final SecureValueRecoveryClient secureValueRecovery2Client;
private final DisconnectionRequestManager disconnectionRequestManager;
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
private final ClientPublicKeysManager clientPublicKeysManager;
private final Executor accountLockExecutor;
private final ScheduledExecutorService messagesPollExecutor;
private final ScheduledExecutorService retryExecutor;
private final Clock clock;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private final Key verificationTokenKey;
@@ -172,7 +171,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
@@ -218,12 +216,10 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final SecureValueRecoveryClient secureValueRecovery2Client,
final DisconnectionRequestManager disconnectionRequestManager,
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
final ClientPublicKeysManager clientPublicKeysManager,
final Executor accountLockExecutor,
final ScheduledExecutorService messagesPollExecutor, final ScheduledExecutorService retryExecutor,
final Clock clock,
final byte[] linkDeviceSecret,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
final byte[] linkDeviceSecret) {
this.accounts = accounts;
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
this.cacheCluster = cacheCluster;
@@ -236,12 +232,10 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
this.secureValueRecovery2Client = secureValueRecovery2Client;
this.disconnectionRequestManager = disconnectionRequestManager;
this.registrationRecoveryPasswordsManager = requireNonNull(registrationRecoveryPasswordsManager);
this.clientPublicKeysManager = clientPublicKeysManager;
this.accountLockExecutor = accountLockExecutor;
this.messagesPollExecutor = messagesPollExecutor;
this.retryExecutor = retryExecutor;
this.clock = requireNonNull(clock);
this.dynamicConfigurationManager = dynamicConfigurationManager;
this.verificationTokenKey = new SecretKeySpec(linkDeviceSecret, LINK_DEVICE_VERIFICATION_TOKEN_ALGORITHM);
@@ -421,23 +415,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;
}
@@ -658,8 +657,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
account.getIdentifier(IdentityType.PNI),
deviceId));
additionalWriteItems.add(clientPublicKeysManager.buildTransactWriteItemForDeletion(account.getIdentifier(IdentityType.ACI), deviceId));
return accounts.updateTransactionallyAsync(account, additionalWriteItems)
.thenApply(ignored -> account);
})
@@ -762,7 +759,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),
@@ -830,119 +827,116 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
public record UsernameReservation(Account account, byte[] reservedUsernameHash){}
/**
* Reserve a username hash so that no other accounts may take it.
* <p>
* The reserved hash can later be set with {@link #confirmReservedUsernameHash(Account, byte[], byte[])}. The reservation
* will eventually expire, after which point confirmReservedUsernameHash may fail if another account has taken the
* username hash.
*
* @param account the account to update
* @param requestedUsernameHashes the list of username hashes to attempt to reserve
* @return a future that yields the reserved username hash and an updated Account object on success; may fail with a
* {@link UsernameHashNotAvailableException} if none of the given username hashes are available
*/
public CompletableFuture<UsernameReservation> reserveUsernameHash(final Account account, final List<byte[]> requestedUsernameHashes) {
/// Reserve a username hash so that no other accounts may take it.
///
/// The reserved hash can later be set with [#confirmReservedUsernameHash(Account, byte\[\], byte\[\])]. The
/// reservation will eventually expire, after which point confirmReservedUsernameHash may fail if another account has
/// taken the username hash.
///
/// @param account the account to update
/// @param requestedUsernameHashes the list of username hashes to attempt to reserve
///
/// @return the reserved username hash
///
/// @throws UsernameHashNotAvailableException if none of the given username hashes are available
public UsernameReservation reserveUsernameHash(final Account account, final List<byte[]> requestedUsernameHashes)
throws UsernameHashNotAvailableException {
if (account.getUsernameHash().filter(
oldHash -> requestedUsernameHashes.stream().anyMatch(hash -> Arrays.equals(oldHash, hash)))
.isPresent()) {
// if we are trying to reserve our already-confirmed username hash, we don't need to do
// anything, and can give the client a success response (they may try to confirm it again,
// but that's a no-op other than rotaing their username link which they may need to do
// anyway). note this is *not* the case for reserving our already-reserved username hash,
// which should extend the reservation's TTL.
return CompletableFuture.completedFuture(new UsernameReservation(account, account.getUsernameHash().get()));
return new UsernameReservation(account, account.getUsernameHash().get());
}
final AtomicReference<byte[]> reservedUsernameHash = new AtomicReference<>();
return redisDeleteAsync(account)
.thenCompose(ignored -> updateWithRetriesAsync(
account,
a -> true,
a -> checkAndReserveNextUsernameHash(a, new ArrayDeque<>(requestedUsernameHashes))
.thenAccept(reservedUsernameHash::set),
() -> accounts.getByAccountIdentifierAsync(account.getUuid()).thenApply(Optional::orElseThrow),
AccountChangeValidator.USERNAME_CHANGE_VALIDATOR,
MAX_UPDATE_ATTEMPTS))
.whenComplete((updatedAccount, throwable) -> {
if (throwable == null) {
// Make a best effort to clear any stale data that may have been cached while this operation was in progress
redisDeleteAsync(updatedAccount);
}
})
.thenApply(updatedAccount -> new UsernameReservation(updatedAccount, reservedUsernameHash.get()));
redisDelete(account);
final Account updatedAccount = updateWithRetries(
account,
_ -> true,
a -> reservedUsernameHash.set(
checkAndReserveNextUsernameHash(a, new ArrayDeque<>(requestedUsernameHashes))),
() -> accounts.getByAccountIdentifier(account.getUuid()).orElseThrow(),
AccountChangeValidator.USERNAME_CHANGE_VALIDATOR);
redisDelete(updatedAccount);
return new UsernameReservation(updatedAccount, reservedUsernameHash.get());
}
private CompletableFuture<byte[]> checkAndReserveNextUsernameHash(final Account account, final Queue<byte[]> requestedUsernameHashes) {
private byte[] checkAndReserveNextUsernameHash(final Account account, final Queue<byte[]> requestedUsernameHashes)
throws UsernameHashNotAvailableException {
final byte[] usernameHash = requestedUsernameHashes.remove();
return accounts.reserveUsernameHash(account, usernameHash, USERNAME_HASH_RESERVATION_TTL_MINUTES)
.thenApply(ignored -> usernameHash)
.exceptionallyComposeAsync(
throwable -> {
if (ExceptionUtils.unwrap(throwable) instanceof UsernameHashNotAvailableException && !requestedUsernameHashes.isEmpty()) {
return checkAndReserveNextUsernameHash(account, requestedUsernameHashes);
}
return CompletableFuture.failedFuture(throwable);
});
try {
accounts.reserveUsernameHash(account, usernameHash, USERNAME_HASH_RESERVATION_TTL_MINUTES);
return usernameHash;
} catch (final UsernameHashNotAvailableException e) {
if (!requestedUsernameHashes.isEmpty()) {
return checkAndReserveNextUsernameHash(account, requestedUsernameHashes);
}
throw e;
}
}
/**
* Set a username hash previously reserved with {@link #reserveUsernameHash(Account, List)}
*
* @param account the account to update
* @param reservedUsernameHash the previously reserved username hash
* @param encryptedUsername the encrypted form of the previously reserved username for the username link
* @return a future that yields the updated account with the username hash field set; may fail with a
* {@link UsernameHashNotAvailableException} if the reserved username hash has been taken (because the reservation
* expired) or a {@link UsernameReservationNotFoundException} if {@code reservedUsernameHash} was not reserved in the
* account
*/
public CompletableFuture<Account> confirmReservedUsernameHash(final Account account, final byte[] reservedUsernameHash, @Nullable final byte[] encryptedUsername) {
/// Set a username hash previously reserved with {@link #reserveUsernameHash(Account, List)}
///
/// @param account the account to update
/// @param reservedUsernameHash the previously reserved username hash
/// @param encryptedUsername the encrypted form of the previously reserved username for the username link
///
/// @return the updated account with the username hash field set
///
/// @throws UsernameHashNotAvailableException if the reserved username hash has been taken (because the reservation
/// expired)
/// @throws UsernameReservationNotFoundException if `reservedUsernameHash` was not reserved for the account
public Account confirmReservedUsernameHash(final Account account, final byte[] reservedUsernameHash, @Nullable final byte[] encryptedUsername)
throws UsernameReservationNotFoundException, UsernameHashNotAvailableException {
if (account.getUsernameHash().map(currentUsernameHash -> Arrays.equals(currentUsernameHash, reservedUsernameHash)).orElse(false)) {
// the client likely already succeeded and is retrying
return CompletableFuture.completedFuture(account);
return account;
}
if (!account.getReservedUsernameHash().map(oldHash -> Arrays.equals(oldHash, reservedUsernameHash)).orElse(false)) {
// no such reservation existed, either there was no previous call to reserveUsername
// or the reservation changed
return CompletableFuture.failedFuture(new UsernameReservationNotFoundException());
throw new UsernameReservationNotFoundException();
}
return redisDeleteAsync(account)
.thenCompose(ignored -> updateWithRetriesAsync(
account,
a -> true,
a -> accounts.confirmUsernameHash(a, reservedUsernameHash, encryptedUsername),
() -> accounts.getByAccountIdentifierAsync(account.getUuid()).thenApply(Optional::orElseThrow),
AccountChangeValidator.USERNAME_CHANGE_VALIDATOR,
MAX_UPDATE_ATTEMPTS
))
.whenComplete((updatedAccount, throwable) -> {
if (throwable == null) {
// Make a best effort to clear any stale data that may have been cached while this operation was in progress
redisDeleteAsync(updatedAccount);
}
});
redisDelete(account);
final Account updatedAccount = updateWithRetries(account,
_ -> true,
a -> accounts.confirmUsernameHash(a, reservedUsernameHash, encryptedUsername),
() -> accounts.getByAccountIdentifier(account.getUuid()).orElseThrow(),
AccountChangeValidator.USERNAME_CHANGE_VALIDATOR);
redisDelete(updatedAccount);
return updatedAccount;
}
public CompletableFuture<Account> clearUsernameHash(final Account account) {
return redisDeleteAsync(account)
.thenCompose(ignored -> updateWithRetriesAsync(
account,
a -> true,
accounts::clearUsernameHash,
() -> accounts.getByAccountIdentifierAsync(account.getUuid()).thenApply(Optional::orElseThrow),
AccountChangeValidator.USERNAME_CHANGE_VALIDATOR,
MAX_UPDATE_ATTEMPTS))
.whenComplete((updatedAccount, throwable) -> {
if (throwable == null) {
// Make a best effort to clear any stale data that may have been cached while this operation was in progress
redisDeleteAsync(updatedAccount);
}
});
public Account clearUsernameHash(final Account account) {
redisDelete(account);
final Account updatedAccount = updateWithRetries(account,
_ -> true,
accounts::clearUsernameHash,
() -> accounts.getByAccountIdentifier(account.getUuid()).orElseThrow(),
AccountChangeValidator.USERNAME_CHANGE_VALIDATOR);
redisDelete(updatedAccount);
return updatedAccount;
}
public Account update(Account account, Consumer<Account> updater) {
@@ -1028,14 +1022,14 @@ 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,
private <E extends Exception> Account updateWithRetries(Account account,
final Function<Account, Boolean> updater,
final Consumer<Account> persister,
final ThrowingConsumer<Account, E> persister,
final Supplier<Account> retriever,
final AccountChangeValidator changeValidator) {
final AccountChangeValidator changeValidator) throws E {
Account originalAccount = AccountUtil.cloneAccountAsNotStale(account);
@@ -1129,12 +1123,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
return getByNumberTimer.record(() -> accounts.getByE164(number));
}
public CompletableFuture<Optional<Account>> getByE164Async(final String number) {
Timer.Sample sample = Timer.start();
return accounts.getByE164Async(number)
.whenComplete((ignoredResult, ignoredThrowable) -> sample.stop(getByNumberTimer));
}
public Optional<Account> getByPhoneNumberIdentifier(final UUID pni) {
return checkRedisThenAccounts(
getByNumberTimer,
@@ -1209,10 +1197,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
return accounts.getAll(segments, scheduler);
}
public Flux<UUID> streamAccountIdentifiersFromDynamo(final int segments, final Scheduler scheduler) {
return accounts.getAllAccountIdentifiers(segments, scheduler);
}
public CompletableFuture<Void> delete(final Account account, final DeletionReason deletionReason) {
final Timer.Sample sample = Timer.start();
@@ -1233,18 +1217,15 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
private CompletableFuture<Void> delete(final Account account) {
final List<TransactWriteItem> additionalWriteItems = Stream.concat(
account.getDevices().stream()
.flatMap(device -> keysManager.buildWriteItemsForRemovedDevice(
account.getIdentifier(IdentityType.ACI),
account.getIdentifier(IdentityType.PNI),
device.getId())
.stream()),
account.getDevices().stream()
.map(device -> clientPublicKeysManager.buildTransactWriteItemForDeletion(
final List<TransactWriteItem> additionalWriteItems =
account.getDevices().stream()
.flatMap(device -> keysManager.buildWriteItemsForRemovedDevice(
account.getIdentifier(IdentityType.ACI),
device.getId())))
.toList();
account.getIdentifier(IdentityType.PNI),
device.getId())
.stream())
.toList();
return CompletableFuture.allOf(
secureStorageClient.deleteStoredData(account.getUuid()),
secureValueRecovery2Client.removeData(account.getUuid()),
@@ -1329,7 +1310,7 @@ 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)
@@ -1339,7 +1320,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}))
.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) {
@@ -1373,7 +1354,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();
}
@@ -1640,7 +1621,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);
@@ -1,145 +0,0 @@
package org.whispersystems.textsecuregcm.storage;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import org.signal.libsignal.protocol.InvalidKeyException;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.util.Util;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.Delete;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.Put;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
/**
* Stores clients' public keys for transport-level authentication/encryption in a DynamoDB table.
*/
public class ClientPublicKeys {
private final DynamoDbAsyncClient dynamoDbAsyncClient;
private final String tableName;
static final String KEY_ACCOUNT_UUID = "U";
static final String KEY_DEVICE_ID = "D";
static final String ATTR_PUBLIC_KEY = "K";
private static final Logger log = LoggerFactory.getLogger(ClientPublicKeys.class);
public ClientPublicKeys(final DynamoDbAsyncClient dynamoDbAsyncClient, final String tableName) {
this.dynamoDbAsyncClient = dynamoDbAsyncClient;
this.tableName = tableName;
}
/**
* Stores the given public key for the given account/device, overwriting any previously-stored public key. This method
* is intended for use for adding public keys to existing accounts/devices as a migration step. Callers should use
* {@link #buildTransactWriteItemForInsertion(UUID, byte, ECPublicKey)} instead when creating new accounts/devices.
*
* @param accountIdentifier the identifier for the target account
* @param deviceId the identifier for the target device
* @param publicKey the public key to store for the target account/device
* @return a future that completes when the given key has been stored
*/
CompletableFuture<Void> setPublicKey(final UUID accountIdentifier, final byte deviceId, final ECPublicKey publicKey) {
return dynamoDbAsyncClient.putItem(PutItemRequest.builder()
.tableName(tableName)
.item(Map.of(
KEY_ACCOUNT_UUID, getPartitionKey(accountIdentifier),
KEY_DEVICE_ID, getSortKey(deviceId),
ATTR_PUBLIC_KEY, AttributeValues.fromByteArray(publicKey.serialize())))
.build())
.thenRun(Util.NOOP);
}
/**
* Builds a {@link TransactWriteItem} that will store a public key for the given account/device. Intended for use when
* adding devices to accounts or creating new accounts.
*
* @param accountIdentifier the identifier for the target account
* @param deviceId the identifier for the target device
* @param publicKey the public key to store for the target account/device
*
* @return a {@code TransactWriteItem} that will store the given public key for the given account/device
*/
TransactWriteItem buildTransactWriteItemForInsertion(final UUID accountIdentifier,
final byte deviceId,
final ECPublicKey publicKey) {
return TransactWriteItem.builder()
.put(Put.builder()
.tableName(tableName)
.item(Map.of(
KEY_ACCOUNT_UUID, getPartitionKey(accountIdentifier),
KEY_DEVICE_ID, getSortKey(deviceId),
ATTR_PUBLIC_KEY, AttributeValues.fromByteArray(publicKey.serialize())))
.build())
.build();
}
/**
* Builds a {@link TransactWriteItem} that will remove the public key for the given account/device. Intended for
* use when removing devices from accounts or deleting/re-creating accounts.
*
* @param accountIdentifier the identifier for the target account
* @param deviceId the identifier for the target device
*
* @return a {@code TransactWriteItem} that will remove the public key for the given account/device
*/
TransactWriteItem buildTransactWriteItemForDeletion(final UUID accountIdentifier, final byte deviceId) {
return TransactWriteItem.builder()
.delete(Delete.builder()
.tableName(tableName)
.key(getPrimaryKey(accountIdentifier, deviceId))
.build())
.build();
}
/**
* Finds the public key for the given account/device.
*
* @param accountIdentifier the identifier for the target account
* @param deviceId the identifier for the target device
*
* @return a future that yields the Ed25519 public key for the given account/device, or empty if no public key was
* found
*/
CompletableFuture<Optional<ECPublicKey>> findPublicKey(final UUID accountIdentifier, final byte deviceId) {
return dynamoDbAsyncClient.getItem(GetItemRequest.builder()
.tableName(tableName)
.consistentRead(true)
.key(getPrimaryKey(accountIdentifier, deviceId))
.build())
.thenApply(response -> Optional.of(response.item())
.filter(item -> response.hasItem())
.map(item -> {
try {
return new ECPublicKey(item.get(ATTR_PUBLIC_KEY).b().asByteArray());
} catch (final InvalidKeyException e) {
log.warn("Invalid public key for {}:{}", accountIdentifier, deviceId, e);
return null;
}
}));
}
private static Map<String, AttributeValue> getPrimaryKey(final UUID identifier, final byte deviceId) {
return Map.of(
KEY_ACCOUNT_UUID, getPartitionKey(identifier),
KEY_DEVICE_ID, getSortKey(deviceId));
}
private static AttributeValue getPartitionKey(final UUID accountUuid) {
return AttributeValues.fromUUID(accountUuid);
}
private static AttributeValue getSortKey(final byte deviceId) {
return AttributeValues.fromInt(deviceId);
}
}
@@ -1,92 +0,0 @@
package org.whispersystems.textsecuregcm.storage;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
/**
* A client public key manager provides access to clients' public keys for use in transport-level authentication and
* encryption.
*/
public class ClientPublicKeysManager {
private final ClientPublicKeys clientPublicKeys;
private final AccountLockManager accountLockManager;
private final Executor accountLockExecutor;
public ClientPublicKeysManager(final ClientPublicKeys clientPublicKeys,
final AccountLockManager accountLockManager,
final Executor accountLockExecutor) {
this.clientPublicKeys = clientPublicKeys;
this.accountLockManager = accountLockManager;
this.accountLockExecutor = accountLockExecutor;
}
/**
* Stores the given public key for the given account/device, overwriting any previously-stored public key. This method
* is intended for use for adding public keys to existing accounts/devices as a migration step. Callers should use
* {@link #buildTransactWriteItemForInsertion(UUID, byte, ECPublicKey)} instead when creating new accounts/devices.
*
* @param account the target account
* @param deviceId the identifier for the target device
* @param publicKey the public key to store for the target account/device
* @return a future that completes when the given key has been stored
*/
public CompletableFuture<Void> setPublicKey(final Account account, final byte deviceId, final ECPublicKey publicKey) {
return accountLockManager.withLockAsync(Set.of(account.getPhoneNumberIdentifier()),
() -> clientPublicKeys.setPublicKey(account.getIdentifier(IdentityType.ACI), deviceId, publicKey),
accountLockExecutor);
}
/**
* Builds a {@link TransactWriteItem} that will store a public key for the given account/device. Intended for use when
* adding devices to accounts or creating new accounts.
*
* @param accountIdentifier the identifier for the target account
* @param deviceId the identifier for the target device
* @param publicKey the public key to store for the target account/device
*
* @return a {@code TransactWriteItem} that will store the given public key for the given account/device
*/
public TransactWriteItem buildTransactWriteItemForInsertion(final UUID accountIdentifier,
final byte deviceId,
final ECPublicKey publicKey) {
return clientPublicKeys.buildTransactWriteItemForInsertion(accountIdentifier, deviceId, publicKey);
}
/**
* Builds a {@link TransactWriteItem} that will remove the public key for the given account/device. Intended for use
* when removing devices from accounts or deleting/re-creating accounts.
*
* @param accountIdentifier the identifier for the target account
* @param deviceId the identifier for the target device
*
* @return a {@code TransactWriteItem} that will remove the public key for the given account/device
*/
public TransactWriteItem buildTransactWriteItemForDeletion(final UUID accountIdentifier, final byte deviceId) {
return clientPublicKeys.buildTransactWriteItemForDeletion(accountIdentifier, deviceId);
}
/**
* Finds the public key for the given account/device.
*
* @param accountIdentifier the identifier for the target account
* @param deviceId the identifier for the target device
*
* @return a future that yields the Ed25519 public key for the given account/device, or empty if no public key was
* found
*/
public CompletableFuture<Optional<ECPublicKey>> findPublicKey(final UUID accountIdentifier, final byte deviceId) {
return clientPublicKeys.findPublicKey(accountIdentifier, deviceId);
}
}
@@ -236,7 +236,6 @@ public class MessagePersister implements Managed {
DistributionSummary.builder(QUEUE_SIZE_DISTRIBUTION_SUMMARY_NAME)
.tags(Tags.of(platformTag))
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry)
.record(messageCount);
} catch (ItemCollectionSizeLimitExceededException e) {
@@ -73,7 +73,6 @@ public class PagedSingleUseKEMPreKeyStore {
final DistributionSummary availableKeyCountDistributionSummary = DistributionSummary
.builder(name(getClass(), "availableKeyCount"))
.publishPercentileHistogram()
.register(Metrics.globalRegistry);
private final String takeKeyTimerName = name(getClass(), "takeKey");
@@ -22,6 +22,7 @@ import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
public class RegistrationRecoveryPasswords {
@@ -62,26 +63,36 @@ public class RegistrationRecoveryPasswords {
.map(RegistrationRecoveryPasswords::saltedTokenHashFromItem));
}
public CompletableFuture<Void> addOrReplace(final UUID phoneNumberIdentifier, final SaltedTokenHash data) {
/// Add a PNI -> RRP mapping, or replace the current one if it already exists
///
/// @param phoneNumberIdentifier The PNI to associate the salted RRP with
/// @param data The salted registration recovery password
/// @return true if a new mapping was added, false if an existing mapping was updated
public CompletableFuture<Boolean> addOrReplace(final UUID phoneNumberIdentifier, final SaltedTokenHash data) {
final long expirationSeconds = expirationSeconds();
return asyncClient.putItem(PutItemRequest.builder()
.tableName(tableName)
.returnValues(ReturnValue.ALL_OLD)
.item(Map.of(
KEY_PNI, AttributeValues.fromString(phoneNumberIdentifier.toString()),
ATTR_EXP, AttributeValues.fromLong(expirationSeconds),
ATTR_SALT, AttributeValues.fromString(data.salt()),
ATTR_HASH, AttributeValues.fromString(data.hash())))
.build())
.thenRun(Util.NOOP);
.thenApply(response -> response.attributes() == null || response.attributes().isEmpty());
}
public CompletableFuture<Void> removeEntry(final UUID phoneNumberIdentifier) {
/// Remove the entry associated with the provided PNI
///
/// @return true if an entry was removed, false if no entry existed
public CompletableFuture<Boolean> removeEntry(final UUID phoneNumberIdentifier) {
return asyncClient.deleteItem(DeleteItemRequest.builder()
.tableName(tableName)
.returnValues(ReturnValue.ALL_OLD)
.key(Map.of(KEY_PNI, AttributeValues.fromString(phoneNumberIdentifier.toString())))
.build())
.thenRun(Util.NOOP);
.thenApply(response -> response.attributes() != null && !response.attributes().isEmpty());
}
@VisibleForTesting
@@ -30,7 +30,7 @@ public class RegistrationRecoveryPasswordsManager {
public CompletableFuture<Boolean> verify(final UUID phoneNumberIdentifier, final byte[] password) {
return registrationRecoveryPasswords.lookup(phoneNumberIdentifier)
.thenApply(maybeHash -> maybeHash.filter(hash -> hash.verify(bytesToString(password))))
.whenComplete((result, error) -> {
.whenComplete((_, error) -> {
if (error != null) {
logger.warn("Failed to lookup Registration Recovery Password", error);
}
@@ -38,25 +38,22 @@ public class RegistrationRecoveryPasswordsManager {
.thenApply(Optional::isPresent);
}
public CompletableFuture<Void> store(final UUID phoneNumberIdentifier, final byte[] password) {
public CompletableFuture<Boolean> store(final UUID phoneNumberIdentifier, final byte[] password) {
final String token = bytesToString(password);
final SaltedTokenHash tokenHash = SaltedTokenHash.generateFor(token);
return registrationRecoveryPasswords.addOrReplace(phoneNumberIdentifier, tokenHash)
.whenComplete((result, error) -> {
.whenComplete((_, error) -> {
if (error != null) {
logger.warn("Failed to store Registration Recovery Password", error);
}
});
}
public CompletableFuture<Void> remove(final UUID phoneNumberIdentifier) {
public CompletableFuture<Boolean> remove(final UUID phoneNumberIdentifier) {
return registrationRecoveryPasswords.removeEntry(phoneNumberIdentifier)
.whenComplete((ignored, error) -> {
if (error instanceof ResourceNotFoundException) {
// These will naturally happen if a recovery password is already deleted. Since we can remove
// the recovery password through many flows, we avoid creating log messages for these exceptions
} else if (error != null) {
.whenComplete((_, error) -> {
if (error != null) {
logger.warn("Failed to remove Registration Recovery Password", error);
}
});
@@ -30,7 +30,6 @@ public class ReportMessageDynamoDb {
private static final String REMOVED_MESSAGE_COUNTER_NAME = name(ReportMessageDynamoDb.class, "removed");
private static final Timer REMOVED_MESSAGE_AGE_TIMER = Timer
.builder(name(ReportMessageDynamoDb.class, "removedMessageAge"))
.publishPercentiles(0.5, 0.75, 0.95, 0.99)
.distributionStatisticExpiry(Duration.ofDays(1))
.register(Metrics.globalRegistry);
@@ -61,13 +61,11 @@ public class SingleUseECPreKeyStore {
final DistributionSummary keysConsideredForTakeDistributionSummary = DistributionSummary
.builder(name(getClass(), "keysConsideredForTake"))
.publishPercentiles(0.5, 0.75, 0.95, 0.99, 0.999)
.distributionStatisticExpiry(Duration.ofMinutes(10))
.register(Metrics.globalRegistry);
final DistributionSummary availableKeyCountDistributionSummary = DistributionSummary
.builder(name(getClass(), "availableKeyCount"))
.publishPercentiles(0.5, 0.75, 0.95, 0.99, 0.999)
.distributionStatisticExpiry(Duration.ofMinutes(10))
.register(Metrics.globalRegistry);
Loaded 100 of 194 files, more files were not shown because too many files have changed in this diff. Show more