Compare commits

..
Author SHA1 Message Date
Jon Chambers 69d9fc12ca Simplify MessagesCache#getEarliestUndeliveredTimestamp 2026-03-17 14:19:22 -04:00
Ravi Khadiwala 81f2499889 Port AttachmentController to gRPC 2026-03-17 13:18:18 -05:00
Jon Chambers 82a3bba7ec Clean up last vestiges of "total queue index" system 2026-03-17 14:17:11 -04:00
Jon Chambers ee09d6b334 Make sure the client connection process has completed before persisting messages 2026-03-16 12:35:49 -04:00
Jon Chambers dc215cab54 Add a command to discard now-unsued message cache queue indices 2026-03-16 11:43:03 -04:00
Jon Chambers 99bbbbe1ac Retire "total queue index" from message management scripts 2026-03-16 11:43:03 -04:00
Jon Chambers 38121bcbfa Use a shorter default node claim TTL 2026-03-16 10:07:38 -04:00
Jon Chambers 5e7a50a36d Simplify and use a shorter delay in MessagePersisterIntegrationTest 2026-03-16 10:07:38 -04:00
Jon Chambers 17531c5927 Remove a spurious rate limit response annotation 2026-03-16 09:35:37 -04:00
Jon Chambers e7df1aeb5b Add a configurable pause between persisted nodes 2026-03-16 09:35:19 -04:00
Jon Chambers dc8e03bd40 Fetch messages to persist via the same pathway as messages to deliver 2026-03-16 09:34:59 -04:00
Jon Chambers 4578150e5a Add a test for fetching messages when a queue is locked for persistence 2026-03-16 09:34:59 -04:00
Jon Chambers bd97e70a56 Add a test for fetching messages with a "discardable" first page 2026-03-16 09:34:59 -04:00
Jon Chambers 206f114b34 Add a (failing!) test for persisting messages when the entire first page is discardable 2026-03-16 09:34:59 -04:00
Ameya Lokare 2dc4db3918 Revert "Update to Java 25"
Back to Java 24 for now
2026-03-13 18:32:36 -07:00
Jon Chambers 98dc758bb7 Update to the latest version of the spam filter 2026-03-13 19:24:10 -04:00
Jon Chambers b4c594c657 Add scan COUNT arguments and rate limits for queue scans 2026-03-13 18:20:51 -04:00
Chris Eager b55afdd704 Update to Java 25 2026-03-13 18:20:30 -04:00
Chris Eager 136cddf6e2 Add Profiles OpenAPI annotations 2026-03-13 18:20:18 -04:00
ravi-signal b7d455ed11 Validate pre-key key-id ranges 2026-03-12 16:37:28 -05:00
Chris Eager ac23b8e79e Add additional null check for app store's APIException#getApiError 2026-03-12 16:36:32 -05:00
Jon Chambers af2d276f37 Log dropped persistence errors via a hook 2026-03-12 17:32:33 -04:00
Jon Chambers 8154bb1047 Add a dedicated counter for "persist node" events 2026-03-12 12:12:07 -04:00
Jon Chambers b647853983 Add better logging for unhandled persister errors 2026-03-12 12:11:38 -04:00
Jon Chambers 3350922456 Don't destroy persister schedulers/executors while the persister is still running 2026-03-12 11:15:49 -04:00
Jon Chambers 69af979bfa Use a SCAN-based strategy for message persisters 2026-03-12 10:04:04 -04:00
Jon Chambers a142916fef Resolve minor warnings/suggestions throughout MessagePersister and MessagePersisterTest 2026-03-12 10:04:04 -04:00
Ameya Lokare 9ff1431488 Update to the latest version of the spam filter 2026-03-11 11:11:09 -07:00
Ameya Lokare cf2d3369cb Change ChallengeRequired token type to string 2026-03-11 10:57:32 -07:00
Chris Eager c41ae57871 Cancel a subscription immediately if the currency is no longer supported 2026-03-11 12:54:41 -05:00
Ameya Lokare 6d351aad7b Update to the latest version of the spam filter 2026-03-09 14:01:00 -07:00
Ameya Lokare a320504fdc Include raw "Accept-Language" header value in RequestAttributes 2026-03-09 13:46:46 -07:00
Jon Chambers 11df65b8d8 Keep a count of open WebSockets by ASN region 2026-03-09 16:29:20 -04:00
Katherine e96149ecf5 Add null check for app store's APIException#getApiError 2026-03-09 16:28:57 -04:00
Ravi Khadiwala db66d4ef18 Add size annotations to AccountAttributes 2026-03-06 15:05:39 -06:00
Ravi Khadiwala 610782b8c3 Add annotation-based validations to a number of services 2026-03-06 15:05:39 -06:00
Jon Chambers aae1541e88 Include required device capabilities when creating users in integration tests 2026-03-06 15:53:18 -05:00
Ravi Khadiwala 1cf3bf5ecf Add a oneof case for the unrestricted access path in gRPC services 2026-03-06 14:49:26 -06:00
Ravi Khadiwala a90fa5db02 Fix oneof field validation 2026-03-06 14:49:26 -06:00
Jon Chambers f5f217f3de Prevent capability downgrades for SPARSE_POST_QUANTUM_RATCHET 2026-03-06 12:18:04 -05:00
Graeme Connell c93aa7a9b9 Require SPARSE_POST_QUANTUM_RATCHET at registration time 2026-03-06 12:18:04 -05:00
Jon Chambers d519a80f90 Remove AccountLockManager#withLockAsync 2026-03-05 09:54:05 -05:00
Jon Chambers ec2cb8581c Make account deletion a blocking operation 2026-03-05 09:54:05 -05:00
Jon Chambers 405b04f07b Make adding/removing devices blocking and remove async update plumbing 2026-03-05 09:54:05 -05:00
Jon Chambers 31de1fc1a3 Remove asynchronous account update plumbing 2026-03-05 09:54:05 -05:00
Jon Chambers de458c3e6a Remove AccountsManager#updateDeviceAsync 2026-03-05 09:54:05 -05:00
Jon Chambers 8df3f3c150 Update version number in a comment 2026-03-04 18:05:10 -05:00
dependabot[bot] 8800b79f97 Bump aws-actions/configure-aws-credentials from 5.1.1 to 6.0.0
Bumps [aws-actions/configure-aws-credentials](https://github.com/aws-actions/configure-aws-credentials) from 5.1.1 to 6.0.0.
- [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/61815dcd50bd041e203e49132bacad1fd04d2708...8df5847569e6427dd6c4fb1cf565c83acfa8afa7)

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

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-04 13:03:27 -05:00
Ravi Khadiwala a66b8b278e Register implemented gRPC services 2026-03-03 12:34:48 -06:00
Ravi Khadiwala 9e2d8125f0 Move the envelope type down to the device level 2026-03-03 12:34:16 -06:00
Chris Eager 865ecc0005 Update to the latest version of the spam filter 2026-03-02 10:29:14 -06:00
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
180 changed files with 4724 additions and 4150 deletions

No files matched your search

+1 -1
View File
@@ -24,7 +24,7 @@ jobs:
distribution: 'temurin'
java-version-file: .java-version
cache: 'maven'
- uses: aws-actions/configure-aws-credentials@61815dcd50bd041e203e49132bacad1fd04d2708 # v5.0.0
- uses: aws-actions/configure-aws-credentials@8df5847569e6427dd6c4fb1cf565c83acfa8afa7 # v6.0.0
name: Configure AWS credentials from Test account
with:
role-to-assume: ${{ vars.AWS_ROLE }}
@@ -26,6 +26,7 @@ import org.signal.libsignal.protocol.util.KeyHelper;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
public class TestUser {
@@ -128,7 +129,8 @@ public class TestUser {
}
public AccountAttributes accountAttributes() {
return new AccountAttributes(true, registrationId, pniRegistrationId, "".getBytes(StandardCharsets.UTF_8), "", true, Set.of())
return new AccountAttributes(true, registrationId, pniRegistrationId, "".getBytes(StandardCharsets.UTF_8), "", true,
DeviceCapability.CAPABILITIES_REQUIRED_FOR_REGISTRATION)
.withUnidentifiedAccessKey(unidentifiedAccessKey)
.withRecoveryPassword(registrationPassword);
}
-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>
-5
View File
@@ -361,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>
@@ -31,7 +31,7 @@ import org.whispersystems.textsecuregcm.configuration.DeviceCheckConfiguration;
import org.whispersystems.textsecuregcm.configuration.DirectoryV2Configuration;
import org.whispersystems.textsecuregcm.configuration.DynamoDbClientFactory;
import org.whispersystems.textsecuregcm.configuration.DynamoDbTables;
import org.whispersystems.textsecuregcm.configuration.GrpcAllowListConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicGrpcAllowListConfiguration;
import org.whispersystems.textsecuregcm.configuration.ExternalRequestFilterConfiguration;
import org.whispersystems.textsecuregcm.configuration.FaultTolerantRedisClientFactory;
import org.whispersystems.textsecuregcm.configuration.FaultTolerantRedisClusterFactory;
@@ -352,7 +352,7 @@ public class WhisperServerConfiguration extends Configuration {
@NotNull
@Valid
@JsonProperty
private GrpcAllowListConfiguration grpcAllowList = new GrpcAllowListConfiguration();
private DynamicGrpcAllowListConfiguration grpcAllowList = new DynamicGrpcAllowListConfiguration();
@Valid
@NotNull
@@ -595,7 +595,7 @@ public class WhisperServerConfiguration extends Configuration {
return grpc;
}
public GrpcAllowListConfiguration getGrpcAllowList() {
public DynamicGrpcAllowListConfiguration getGrpcAllowList() {
return grpcAllowList;
}
@@ -142,18 +142,23 @@ import org.whispersystems.textsecuregcm.filters.RestDeprecationFilter;
import org.whispersystems.textsecuregcm.filters.TimestampResponseFilter;
import org.whispersystems.textsecuregcm.grpc.AccountsAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.AccountsGrpcService;
import org.whispersystems.textsecuregcm.grpc.AttachmentsGrpcService;
import org.whispersystems.textsecuregcm.grpc.BackupsAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.BackupsGrpcService;
import org.whispersystems.textsecuregcm.grpc.CallQualitySurveyGrpcService;
import org.whispersystems.textsecuregcm.grpc.DevicesGrpcService;
import org.whispersystems.textsecuregcm.grpc.ErrorConformanceInterceptor;
import org.whispersystems.textsecuregcm.grpc.GrpcAllowListInterceptor;
import org.whispersystems.textsecuregcm.grpc.ErrorMappingInterceptor;
import org.whispersystems.textsecuregcm.grpc.ExternalServiceCredentialsAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.ExternalServiceCredentialsGrpcService;
import org.whispersystems.textsecuregcm.grpc.GroupSendTokenUtil;
import org.whispersystems.textsecuregcm.grpc.GrpcAllowListInterceptor;
import org.whispersystems.textsecuregcm.grpc.KeysAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.KeysGrpcService;
import org.whispersystems.textsecuregcm.grpc.MessagesAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.MessagesGrpcService;
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;
@@ -219,8 +224,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,8 +260,8 @@ import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreClient;
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator;
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator;
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;
@@ -499,8 +502,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);
@@ -693,13 +694,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());
@@ -807,6 +806,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
environment.lifecycle().manage(asnInfoProviderSupplier);
environment.lifecycle().manage(dnsResolutionEventLoopGroup);
environment.lifecycle().manage(apnSender);
environment.lifecycle().manage(pushNotificationScheduler);
environment.lifecycle().manage(provisioningManager);
@@ -862,6 +862,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
secureValueRecoveryBClient,
clock,
dynamicConfigurationManager);
final BackupMetrics backupMetrics = new BackupMetrics();
final AppleDeviceChecks appleDeviceChecks = new AppleDeviceChecks(
dynamoDbClient,
@@ -877,139 +878,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getAppleDeviceCheck().teamId(),
config.getAppleDeviceCheck().bundleId());
final RemoteDeprecationFilter remoteDeprecationFilter = new RemoteDeprecationFilter(dynamicConfigurationManager);
final MetricServerInterceptor metricServerInterceptor = new MetricServerInterceptor(Metrics.globalRegistry, clientReleaseManager);
final ErrorMappingInterceptor errorMappingInterceptor = new ErrorMappingInterceptor();
final ErrorConformanceInterceptor errorConformanceInterceptor = new ErrorConformanceInterceptor();
final GrpcAllowListInterceptor grpcAllowListInterceptor =
new GrpcAllowListInterceptor(config.getGrpcAllowList().enableAll(), config.getGrpcAllowList().enabledServices(), config.getGrpcAllowList().enabledMethods());
final RequestAttributesInterceptor requestAttributesInterceptor = new RequestAttributesInterceptor();
final ValidatingInterceptor validatingInterceptor = new ValidatingInterceptor();
final ExternalRequestFilter grpcExternalRequestFilter = new ExternalRequestFilter(
config.getExternalRequestFilterConfiguration().permittedInternalRanges(),
config.getExternalRequestFilterConfiguration().grpcMethods());
final RequireAuthenticationInterceptor requireAuthenticationInterceptor = new RequireAuthenticationInterceptor(accountAuthenticator);
final ProhibitAuthenticationInterceptor prohibitAuthenticationInterceptor = new ProhibitAuthenticationInterceptor();
final List<ServerServiceDefinition> authenticatedServices = Stream.of(
new AccountsGrpcService(accountsManager, rateLimiters, usernameHashZkProofVerifier, registrationRecoveryPasswordsManager),
ExternalServiceCredentialsGrpcService.createForAllExternalServices(config, rateLimiters),
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,
grpcAllowListInterceptor,
metricServerInterceptor,
errorMappingInterceptor,
errorConformanceInterceptor,
remoteDeprecationFilter,
requestAttributesInterceptor,
requireAuthenticationInterceptor))
.toList();
final List<ServerServiceDefinition> unauthenticatedServices = Stream.of(
new AccountsAnonymousGrpcService(accountsManager, rateLimiters),
new CallQualitySurveyGrpcService(callQualitySurveyManager, rateLimiters),
new KeysAnonymousGrpcService(accountsManager, keysManager, zkSecretParams, Clock.systemUTC()),
new PaymentsGrpcService(currencyManager),
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,
grpcAllowListInterceptor,
metricServerInterceptor,
errorMappingInterceptor,
errorConformanceInterceptor,
remoteDeprecationFilter,
requestAttributesInterceptor,
prohibitAuthenticationInterceptor))
.toList();
final ServerBuilder<?> serverBuilder =
NettyServerBuilder.forAddress(new InetSocketAddress(config.getGrpc().bindAddress(), config.getGrpc().port()));
authenticatedServices.forEach(serverBuilder::addService);
unauthenticatedServices.forEach(serverBuilder::addService);
final ManagedGrpcServer exposedGrpcServer = new ManagedGrpcServer(serverBuilder.build());
environment.lifecycle().manage(dnsResolutionEventLoopGroup);
environment.lifecycle().manage(exposedGrpcServer);
final List<Filter> filters = new ArrayList<>();
filters.add(remoteDeprecationFilter);
filters.add(new RemoteAddressFilter());
filters.add(new TimestampResponseFilter());
for (Filter filter : filters) {
environment.servlets()
.addFilter(filter.getClass().getSimpleName(), filter)
.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");
}
if (!config.getExternalRequestFilterConfiguration().paths().isEmpty()) {
environment.servlets().addFilter(ExternalRequestFilter.class.getSimpleName(),
new ExternalRequestFilter(config.getExternalRequestFilterConfiguration().permittedInternalRanges(),
config.getExternalRequestFilterConfiguration().grpcMethods()))
.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true,
config.getExternalRequestFilterConfiguration().paths().toArray(new String[]{}));
}
final AuthFilter<BasicCredentials, AuthenticatedDevice> accountAuthFilter =
new BasicCredentialAuthFilter.Builder<AuthenticatedDevice>()
.setAuthenticator(accountAuthenticator)
.buildAuthFilter();
final String websocketServletPath = "/v1/websocket/";
final String provisioningWebsocketServletPath = "/v1/websocket/provisioning/";
final MetricsHttpChannelListener metricsHttpChannelListener = new MetricsHttpChannelListener(clientReleaseManager,
Set.of(websocketServletPath, provisioningWebsocketServletPath, "/health-check"));
metricsHttpChannelListener.configure(environment);
final MessageMetrics messageMetrics = new MessageMetrics();
final BackupMetrics backupMetrics = new BackupMetrics();
// BufferingInterceptor is needed on the base environment but not the WebSocketEnvironment,
// because we handle serialization of http responses on the websocket on our own and can
// compute content lengths without it
environment.jersey().register(new BufferingInterceptor());
environment.jersey().register(new RestDeprecationFilter(dynamicConfigurationManager, experimentEnrollmentManager));
environment.jersey().register(new VirtualExecutorServiceProvider(
"managed-async-virtual-thread",
config.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor()));
environment.jersey().register(new RateLimitByIpFilter(rateLimiters));
environment.jersey().register(new RequestStatisticsFilter(TrafficSource.HTTP));
environment.jersey().register(MultiRecipientMessageProvider.class);
environment.jersey().register(new AuthDynamicFeature(accountAuthFilter));
environment.jersey().register(new AuthValueFactoryProvider.Binder<>(AuthenticatedDevice.class));
environment.jersey().register(new TimestampResponseFilter());
///
WebSocketEnvironment<AuthenticatedDevice> webSocketEnvironment = new WebSocketEnvironment<>(environment,
config.getWebSocketConfiguration(), Duration.ofMillis(90000));
webSocketEnvironment.jersey().register(new VirtualExecutorServiceProvider(
"managed-async-websocket-virtual-thread",
config.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor()));
webSocketEnvironment.setAuthenticator(new WebSocketAccountAuthenticator(accountAuthenticator));
webSocketEnvironment.setAuthenticatedWebSocketUpgradeFilter(new IdlePrimaryDeviceAuthenticatedWebSocketUpgradeFilter(
config.idlePrimaryDeviceReminderConfiguration().minIdleDuration(), Clock.systemUTC()));
webSocketEnvironment.setConnectListener(
new AuthenticatedConnectListener(accountsManager, receiptSender, messagesManager, messageMetrics, pushNotificationManager,
pushNotificationScheduler, disconnectionRequestManager,
messageDeliveryScheduler, clientReleaseManager, messageDeliveryLoopMonitor, experimentEnrollmentManager
));
webSocketEnvironment.jersey().register(new RateLimitByIpFilter(rateLimiters));
webSocketEnvironment.jersey().register(new RequestStatisticsFilter(TrafficSource.WEBSOCKET));
webSocketEnvironment.jersey().register(MultiRecipientMessageProvider.class);
webSocketEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET, clientReleaseManager));
webSocketEnvironment.jersey().register(new KeepAliveController(redisMessageAvailabilityManager));
webSocketEnvironment.jersey().register(new TimestampResponseFilter());
final List<SpamFilter> spamFilters = ServiceLoader.load(SpamFilter.class)
.stream()
.map(ServiceLoader.Provider::get)
@@ -1079,6 +947,142 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
log.info("Registered spam filter: {}", filter.getClass().getName());
});
final RemoteDeprecationFilter remoteDeprecationFilter = new RemoteDeprecationFilter(dynamicConfigurationManager);
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();
final ExternalRequestFilter grpcExternalRequestFilter = new ExternalRequestFilter(
config.getExternalRequestFilterConfiguration().permittedInternalRanges(),
config.getExternalRequestFilterConfiguration().grpcMethods());
final RequireAuthenticationInterceptor requireAuthenticationInterceptor = new RequireAuthenticationInterceptor(accountAuthenticator);
final ProhibitAuthenticationInterceptor prohibitAuthenticationInterceptor = new ProhibitAuthenticationInterceptor();
final GroupSendTokenUtil groupSendTokenUtil = new GroupSendTokenUtil(zkSecretParams, Clock.systemUTC());
final List<ServerServiceDefinition> authenticatedServices = Stream.of(
new AccountsGrpcService(accountsManager, rateLimiters, usernameHashZkProofVerifier, registrationRecoveryPasswordsManager),
ExternalServiceCredentialsGrpcService.createForAllExternalServices(config, rateLimiters),
new KeysGrpcService(accountsManager, keysManager, rateLimiters),
new MessagesGrpcService(accountsManager, rateLimiters, messageSender, messageByteLimitCardinalityEstimator, spamChecker, Clock.systemUTC()),
new BackupsGrpcService(accountsManager, backupAuthManager, backupMetrics),
new DevicesGrpcService(accountsManager),
new AttachmentsGrpcService(experimentEnrollmentManager, rateLimiters, gcsAttachmentGenerator, tusAttachmentGenerator))
.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,
errorMappingInterceptor,
errorConformanceInterceptor,
grpcAllowListInterceptor,
remoteDeprecationFilter,
metricServerInterceptor,
requestAttributesInterceptor,
requireAuthenticationInterceptor))
.toList();
final List<ServerServiceDefinition> unauthenticatedServices = Stream.of(
new AccountsAnonymousGrpcService(accountsManager, rateLimiters),
new CallQualitySurveyGrpcService(callQualitySurveyManager, rateLimiters),
new KeysAnonymousGrpcService(accountsManager, keysManager, zkSecretParams, Clock.systemUTC()),
new PaymentsGrpcService(currencyManager),
new MessagesAnonymousGrpcService(accountsManager, rateLimiters, messageSender, groupSendTokenUtil, messageByteLimitCardinalityEstimator, spamChecker, Clock.systemUTC()),
new BackupsAnonymousGrpcService(backupManager, backupMetrics),
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,
errorMappingInterceptor,
errorConformanceInterceptor,
grpcAllowListInterceptor,
remoteDeprecationFilter,
metricServerInterceptor,
requestAttributesInterceptor,
prohibitAuthenticationInterceptor))
.toList();
final ServerBuilder<?> serverBuilder =
NettyServerBuilder.forAddress(new InetSocketAddress(config.getGrpc().bindAddress(), config.getGrpc().port()));
authenticatedServices.forEach(serverBuilder::addService);
unauthenticatedServices.forEach(serverBuilder::addService);
final ManagedGrpcServer exposedGrpcServer = new ManagedGrpcServer(serverBuilder.build());
environment.lifecycle().manage(exposedGrpcServer);
final List<Filter> filters = new ArrayList<>();
filters.add(remoteDeprecationFilter);
filters.add(new RemoteAddressFilter());
filters.add(new TimestampResponseFilter());
for (Filter filter : filters) {
environment.servlets()
.addFilter(filter.getClass().getSimpleName(), filter)
.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");
}
if (!config.getExternalRequestFilterConfiguration().paths().isEmpty()) {
environment.servlets().addFilter(ExternalRequestFilter.class.getSimpleName(),
new ExternalRequestFilter(config.getExternalRequestFilterConfiguration().permittedInternalRanges(),
config.getExternalRequestFilterConfiguration().grpcMethods()))
.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true,
config.getExternalRequestFilterConfiguration().paths().toArray(new String[]{}));
}
final AuthFilter<BasicCredentials, AuthenticatedDevice> accountAuthFilter =
new BasicCredentialAuthFilter.Builder<AuthenticatedDevice>()
.setAuthenticator(accountAuthenticator)
.buildAuthFilter();
final String websocketServletPath = "/v1/websocket/";
final String provisioningWebsocketServletPath = "/v1/websocket/provisioning/";
final MetricsHttpChannelListener metricsHttpChannelListener = new MetricsHttpChannelListener(clientReleaseManager,
Set.of(websocketServletPath, provisioningWebsocketServletPath, "/health-check"));
metricsHttpChannelListener.configure(environment);
final MessageMetrics messageMetrics = new MessageMetrics();
// BufferingInterceptor is needed on the base environment but not the WebSocketEnvironment,
// because we handle serialization of http responses on the websocket on our own and can
// compute content lengths without it
environment.jersey().register(new BufferingInterceptor());
environment.jersey().register(new RestDeprecationFilter(dynamicConfigurationManager, experimentEnrollmentManager));
environment.jersey().register(new VirtualExecutorServiceProvider(
"managed-async-virtual-thread",
config.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor()));
environment.jersey().register(new RateLimitByIpFilter(rateLimiters));
environment.jersey().register(new RequestStatisticsFilter(TrafficSource.HTTP));
environment.jersey().register(MultiRecipientMessageProvider.class);
environment.jersey().register(new AuthDynamicFeature(accountAuthFilter));
environment.jersey().register(new AuthValueFactoryProvider.Binder<>(AuthenticatedDevice.class));
environment.jersey().register(new TimestampResponseFilter());
///
WebSocketEnvironment<AuthenticatedDevice> webSocketEnvironment = new WebSocketEnvironment<>(environment,
config.getWebSocketConfiguration(), Duration.ofMillis(90000));
webSocketEnvironment.jersey().register(new VirtualExecutorServiceProvider(
"managed-async-websocket-virtual-thread",
config.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor()));
webSocketEnvironment.setAuthenticator(new WebSocketAccountAuthenticator(accountAuthenticator));
webSocketEnvironment.setAuthenticatedWebSocketUpgradeFilter(new IdlePrimaryDeviceAuthenticatedWebSocketUpgradeFilter(
config.idlePrimaryDeviceReminderConfiguration().minIdleDuration(), Clock.systemUTC()));
webSocketEnvironment.setConnectListener(
new AuthenticatedConnectListener(accountsManager, receiptSender, messagesManager, messageMetrics, pushNotificationManager,
pushNotificationScheduler, disconnectionRequestManager,
messageDeliveryScheduler, asnInfoProviderSupplier, clientReleaseManager, messageDeliveryLoopMonitor, experimentEnrollmentManager
));
webSocketEnvironment.jersey().register(new RateLimitByIpFilter(rateLimiters));
webSocketEnvironment.jersey().register(new RequestStatisticsFilter(TrafficSource.WEBSOCKET));
webSocketEnvironment.jersey().register(MultiRecipientMessageProvider.class);
webSocketEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET, clientReleaseManager));
webSocketEnvironment.jersey().register(new KeepAliveController(redisMessageAvailabilityManager));
webSocketEnvironment.jersey().register(new TimestampResponseFilter());
final PersistentTimer persistentTimer = new PersistentTimer(rateLimitersCluster, clock);
final PhoneVerificationTokenManager phoneVerificationTokenManager = new PhoneVerificationTokenManager(
@@ -1098,7 +1102,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()),
@@ -1148,7 +1152,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, asnInfoProviderSupplier, clientReleaseManager, provisioningWebsocketTimeoutExecutor, Duration.ofSeconds(90)));
provisioningEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET, clientReleaseManager));
provisioningEnvironment.jersey().register(new KeepAliveController(redisMessageAvailabilityManager));
provisioningEnvironment.jersey().register(new TimestampResponseFilter());
@@ -0,0 +1,20 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.attachments;
import java.security.SecureRandom;
import java.util.Base64;
public class AttachmentUtil {
public static final String CDN3_EXPERIMENT_NAME = "cdn3";
private AttachmentUtil() {}
public static String generateAttachmentKey(final SecureRandom secureRandom) {
final byte[] bytes = new byte[15];
secureRandom.nextBytes(bytes);
return Base64.getUrlEncoder().encodeToString(bytes);
}
}
@@ -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);
@@ -46,6 +46,7 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient;
import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.Pair;
@@ -177,9 +178,7 @@ public class BackupManager {
checkBackupCredentialType(backupUser, BackupCredentialType.MEDIA);
rateLimiters.forDescriptor(RateLimiters.For.BACKUP_ATTACHMENT).validate(rateLimitKey(backupUser));
final byte[] bytes = new byte[15];
secureRandom.nextBytes(bytes);
final String attachmentKey = Base64.getUrlEncoder().encodeToString(bytes);
final String attachmentKey = AttachmentUtil.generateAttachmentKey(secureRandom);
final AttachmentGenerator.Descriptor descriptor = tusAttachmentGenerator.generateAttachment(attachmentKey);
return new BackupUploadDescriptor(3, attachmentKey, descriptor.headers(), descriptor.signedUploadLocation());
}
@@ -210,12 +209,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());
}
@@ -729,7 +726,6 @@ public class BackupManager {
concurrentDeletes)
.count()
.doOnSuccess(itemsRemoved -> DistributionSummary.builder(DELETE_COUNT_DISTRIBUTION_NAME)
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry)
.record(itemsRemoved))
.then()
@@ -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;
}
}
@@ -2,10 +2,11 @@
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
package org.whispersystems.textsecuregcm.configuration.dynamic;
import java.util.Collections;
import java.util.List;
import java.util.Set;
/// Configure which gRPC methods are enabled
///
@@ -16,22 +17,22 @@ import java.util.List;
/// @param enabledMethods A list of fully qualified method names of RPCs that should be enabled. For example,
/// `org.signal.chat.account.AccountsAnonymous/LookupUsernameHash` would enable the
/// `LookupUsernameHash` RPC method
public record GrpcAllowListConfiguration(
public record DynamicGrpcAllowListConfiguration(
boolean enableAll,
List<String> enabledServices,
List<String> enabledMethods) {
Set<String> enabledServices,
Set<String> enabledMethods) {
public GrpcAllowListConfiguration {
public DynamicGrpcAllowListConfiguration {
if (enabledServices == null) {
enabledServices = Collections.emptyList();
enabledServices = Collections.emptySet();
}
if (enabledMethods == null) {
enabledMethods = Collections.emptyList();
enabledMethods = Collections.emptySet();
}
}
public GrpcAllowListConfiguration() {
public DynamicGrpcAllowListConfiguration() {
// By default, no GRPC methods are accessible
this(false, Collections.emptyList(), Collections.emptyList());
this(false, Collections.emptySet(), Collections.emptySet());
}
}
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.configuration.dynamic;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.annotations.VisibleForTesting;
import java.time.Duration;
public class DynamicMessagePersisterConfiguration {
@@ -19,12 +20,24 @@ public class DynamicMessagePersisterConfiguration {
@JsonProperty
private double trimOversizedQueueExtraRoomRatio = 1.5;
@JsonProperty
private Duration nodeClaimTtl = Duration.ofMinutes(5);
@JsonProperty
private Duration sleepBetweenNodes = Duration.ofSeconds(5);
public DynamicMessagePersisterConfiguration() {}
@VisibleForTesting
public DynamicMessagePersisterConfiguration(final boolean persistenceEnabled, final double trimOversizedQueueExtraRoomRatio) {
public DynamicMessagePersisterConfiguration(final boolean persistenceEnabled,
final double trimOversizedQueueExtraRoomRatio,
final Duration nodeClaimTtl,
final Duration sleepBetweenNodes) {
this.persistenceEnabled = persistenceEnabled;
this.trimOversizedQueueExtraRoomRatio = trimOversizedQueueExtraRoomRatio;
this.nodeClaimTtl = nodeClaimTtl;
this.sleepBetweenNodes = sleepBetweenNodes;
}
public boolean isPersistenceEnabled() {
@@ -35,4 +48,11 @@ public class DynamicMessagePersisterConfiguration {
return trimOversizedQueueExtraRoomRatio;
}
public Duration getNodeClaimTtl() {
return nodeClaimTtl;
}
public Duration getSleepBetweenNodes() {
return sleepBetweenNodes;
}
}
@@ -4,6 +4,8 @@
*/
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;
@@ -67,13 +69,10 @@ 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;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@Path("/v1/accounts")
@io.swagger.v3.oas.annotations.tags.Tag(name = "Account")
@@ -306,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
@@ -330,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 {
@@ -345,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
@@ -373,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));
@@ -386,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
@@ -565,11 +558,11 @@ public class AccountController {
@DELETE
@Path("/me")
public CompletableFuture<Response> deleteAccount(@Auth AuthenticatedDevice auth) {
public void deleteAccount(@Auth AuthenticatedDevice auth) {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
return accounts.delete(account, AccountsManager.DeletionReason.USER_REQUEST).thenApply(Util.ASYNC_EMPTY_RESPONSE);
accounts.delete(account, AccountsManager.DeletionReason.USER_REQUEST);
}
private void clearUsernameLink(final Account account) {
@@ -15,7 +15,6 @@ import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Map;
import javax.annotation.Nonnull;
import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
@@ -26,6 +25,7 @@ import org.whispersystems.textsecuregcm.entities.AttachmentDescriptorV3;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
/**
@@ -36,8 +36,6 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
@Tag(name = "Attachments")
public class AttachmentControllerV4 {
public static final String CDN3_EXPERIMENT_NAME = "cdn3";
private final ExperimentEnrollmentManager experimentEnrollmentManager;
private final RateLimiter rateLimiter;
@@ -71,25 +69,17 @@ public class AttachmentControllerV4 {
"""
)
@ApiResponse(responseCode = "200", description = "Success, response body includes upload form", useReturnTypeSchema = true)
@ApiResponse(responseCode = "413", description = "Too many attempts", headers = @Header(
name = "Retry-After",
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
name = "Retry-After",
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
public AttachmentDescriptorV3 getAttachmentUploadForm(@Auth AuthenticatedDevice auth)
throws RateLimitExceededException {
rateLimiter.validate(auth.accountIdentifier());
final String key = generateAttachmentKey();
final boolean useCdn3 = this.experimentEnrollmentManager.isEnrolled(auth.accountIdentifier(), CDN3_EXPERIMENT_NAME);
final String key = AttachmentUtil.generateAttachmentKey(secureRandom);
final boolean useCdn3 = this.experimentEnrollmentManager.isEnrolled(auth.accountIdentifier(), AttachmentUtil.CDN3_EXPERIMENT_NAME);
int cdn = useCdn3 ? 3 : 2;
final AttachmentGenerator.Descriptor descriptor = this.attachmentGenerators.get(cdn).generateAttachment(key);
return new AttachmentDescriptorV3(cdn, key, descriptor.headers(), descriptor.signedUploadLocation());
}
private String generateAttachmentKey() {
final byte[] bytes = new byte[15];
secureRandom.nextBytes(bytes);
return Base64.getUrlEncoder().encodeToString(bytes);
}
}
@@ -37,15 +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;
import java.util.stream.Collectors;
@@ -64,7 +61,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 +70,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 +91,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 +116,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;
@@ -173,7 +165,7 @@ public class DeviceController {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
accounts.removeDevice(account, deviceId).join();
accounts.removeDevice(account, deviceId);
}
/**
@@ -301,7 +293,7 @@ public class DeviceController {
}
try {
return accounts.addDevice(account, new DeviceSpec(accountAttributes.getName(),
final Pair<Account, Device> accountAndDevice = accounts.addDevice(account, new DeviceSpec(accountAttributes.getName(),
authorizationHeader.getPassword(),
signalAgent,
capabilities,
@@ -314,18 +306,14 @@ public class DeviceController {
deviceActivationRequest.pniSignedPreKey(),
deviceActivationRequest.aciPqLastResortPreKey(),
deviceActivationRequest.pniPqLastResortPreKey()),
linkDeviceRequest.verificationCode())
.thenApply(accountAndDevice -> new LinkDeviceResponse(
accountAndDevice.first().getIdentifier(IdentityType.ACI),
accountAndDevice.first().getIdentifier(IdentityType.PNI),
accountAndDevice.second().getId()))
.join();
} catch (final CompletionException e) {
if (e.getCause() instanceof LinkDeviceTokenAlreadyUsedException) {
throw new ForbiddenException();
}
linkDeviceRequest.verificationCode());
throw e;
return new LinkDeviceResponse(
accountAndDevice.first().getIdentifier(IdentityType.ACI),
accountAndDevice.first().getIdentifier(IdentityType.PNI),
accountAndDevice.second().getId());
} catch (final LinkDeviceTokenAlreadyUsedException e) {
throw new ForbiddenException();
}
}
@@ -384,13 +372,12 @@ public class DeviceController {
.map(deviceInfo -> Response.status(Response.Status.OK).entity(deviceInfo).build())
.orElseGet(() -> Response.status(Response.Status.NO_CONTENT).build()))
.exceptionally(ExceptionUtils.exceptionallyHandler(IllegalArgumentException.class,
e -> Response.status(Response.Status.BAD_REQUEST).build()))
.whenComplete((response, throwable) -> {
_ -> Response.status(Response.Status.BAD_REQUEST).build()))
.whenComplete((response, _) -> {
linkedDeviceListenerCounter.decrementAndGet();
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 +407,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
@@ -599,10 +563,9 @@ public class DeviceController {
.thenApply(maybeTransferArchive -> maybeTransferArchive
.map(transferArchive -> Response.status(Response.Status.OK).entity(transferArchive).build())
.orElseGet(() -> Response.status(Response.Status.NO_CONTENT).build()))
.whenComplete((response, throwable) -> {
.whenComplete((response, _) -> {
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,12 +147,10 @@ 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);
}
@@ -11,6 +11,10 @@ import com.google.common.base.Preconditions;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
@@ -72,7 +76,6 @@ import org.whispersystems.textsecuregcm.entities.BaseProfileResponse;
import org.whispersystems.textsecuregcm.entities.BatchIdentityCheckRequest;
import org.whispersystems.textsecuregcm.entities.BatchIdentityCheckResponse;
import org.whispersystems.textsecuregcm.entities.CreateProfileRequest;
import org.whispersystems.textsecuregcm.entities.CredentialProfileResponse;
import org.whispersystems.textsecuregcm.entities.ExpiringProfileKeyCredentialProfileResponse;
import org.whispersystems.textsecuregcm.entities.ProfileAvatarUploadAttributes;
import org.whispersystems.textsecuregcm.entities.VersionedProfileResponse;
@@ -151,6 +154,18 @@ public class ProfileController {
@PUT
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Operation(
summary = "Update profile",
description = "Updates an account’s profile. Must be authenticated.")
@ApiResponse(responseCode = "200", description = "The profile was updated successfully.",
content = @Content(schema = @Schema(
implementation = ProfileAvatarUploadAttributes.class,
description = "If the request changed the avatar, the response body contains an upload form.")))
@ApiResponse(responseCode = "400", description = "Invalid create profile request.")
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
@ApiResponse(responseCode = "403", description = "The request contained a payment address, but payments are not supported in the region of the account’s phone number.")
@ApiResponse(responseCode = "412", description = "The requesting account has the profiles_v2 capability")
@ApiResponse(responseCode = "422", description = "Invalid request format")
public Response setProfile(@Auth AuthenticatedDevice auth, @NotNull @Valid CreateProfileRequest request) {
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
@@ -214,8 +229,16 @@ public class ProfileController {
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{identifier}/{version}")
@Produces(MediaType.APPLICATION_JSON)
@Operation(
summary = "Get versioned profile",
description = "Retrieves a specific version of an account's profile. Requires either authentication or an unidentified access key.")
@ApiResponse(responseCode = "200", description = "Profile retrieved successfully.", useReturnTypeSchema = true)
@ApiResponse(responseCode = "400", description = "Malformed identifier")
@ApiResponse(responseCode = "401", description = "Not authorized to access this profile.")
@ApiResponse(responseCode = "404", description = "Profile or account not found.")
@ApiResponse(responseCode = "429", description = "Rate limit exceeded.")
@ManagedAsync
public VersionedProfileResponse getProfile(
@Auth Optional<AuthenticatedDevice> maybeAuthenticatedDevice,
@@ -241,9 +264,21 @@ public class ProfileController {
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{identifier}/{version}/{credentialRequest}")
public CredentialProfileResponse getProfile(
@Produces(MediaType.APPLICATION_JSON)
@Operation(
summary = "Get profile with credential",
description = "Retrieves a specific version of an account's profile along with an expiring profile key credential. Requires either authentication or an unidentified access key."
)
@ApiResponse(
responseCode = "200",
description = "Account found. Profile information will be limited and credential will be null if the version was not found",
useReturnTypeSchema = true)
@ApiResponse(responseCode = "400", description = "Invalid credential type or credential request.")
@ApiResponse(responseCode = "401", description = "Not authorized to access this profile.")
@ApiResponse(responseCode = "404", description = "Profile or account not found.")
@ApiResponse(responseCode = "429", description = "Rate limit exceeded.")
public ExpiringProfileKeyCredentialProfileResponse getProfile(
@Auth Optional<AuthenticatedDevice> maybeAuthenticatedDevice,
@HeaderParam(HeaderUtils.UNIDENTIFIED_ACCESS_KEY) Optional<Anonymous> accessKey,
@Context ContainerRequestContext containerRequestContext,
@@ -276,8 +311,16 @@ public class ProfileController {
// Although clients should generally be using versioned profiles wherever possible, there are still a few lingering
// use cases for getting profiles without a version (e.g. getting a contact's unidentified access key checksum).
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{identifier}")
@Produces(MediaType.APPLICATION_JSON)
@Operation(
summary = "Get unversioned profile",
description = "Retrieves basic profile information without a specific version. Supports ACI and PNI identifiers. Requires authentication, an unidentified access key, or a group send token.")
@ApiResponse(responseCode = "200", description = "Unversioned profile retrieved successfully.", useReturnTypeSchema = true)
@ApiResponse(responseCode = "400", description = "Invalid request (e.g., multiple authorization types provided).")
@ApiResponse(responseCode = "401", description = "Not authorized to access this profile.")
@ApiResponse(responseCode = "404", description = "Account not found.")
@ApiResponse(responseCode = "429", description = "Rate limit exceeded.")
@ManagedAsync
public BaseProfileResponse getUnversionedProfile(
@Auth Optional<AuthenticatedDevice> maybeAuthenticatedDevice,
@@ -318,9 +361,17 @@ public class ProfileController {
}
@POST
@Path("/identity_check/batch")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/identity_check/batch")
@Operation(
summary = "Batch identity key check",
description = "Checks identity key fingerprints for multiple accounts. Returns accounts where the fingerprint does not match. Should not be authenticated.")
@ApiResponse(
responseCode = "200",
description = "Batch check completed successfully. Response may contain accounts with mismatched fingerprints.",
content = @Content(schema = @Schema(implementation = BatchIdentityCheckResponse.class)))
@ApiResponse(responseCode = "400", description = "Invalid request format or validation failed.")
public CompletableFuture<BatchIdentityCheckResponse> runBatchIdentityCheck(@NotNull @Valid BatchIdentityCheckRequest request) {
return CompletableFuture.supplyAsync(() -> {
List<BatchIdentityCheckResponse.Element> responseElements = Collections.synchronizedList(new ArrayList<>());
@@ -410,7 +461,7 @@ public class ProfileController {
final Optional<VersionedProfile> maybeProfile = profilesManager.get(account.getUuid(), version);
if (maybeProfile.isEmpty()) {
// Hypothesis: this should basically never happen since clients can't delete versions
// this can happen if an account re-registers, which includes some device-transfer scenarios
Metrics.counter(
VERSION_NOT_FOUND_COUNTER_NAME,
Tags.of(
@@ -32,6 +32,7 @@ import jakarta.ws.rs.core.Response;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Optional;
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
@@ -56,7 +57,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);
@@ -101,6 +101,7 @@ public class RegistrationController {
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
name = "Retry-After",
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
@ApiResponse(responseCode = "499", description = "Client must support post-quantum ratchet")
public AccountCreationResponse register(
@HeaderParam(HttpHeaders.AUTHORIZATION) @NotNull final BasicAuthorizationHeader authorizationHeader,
@HeaderParam(HeaderUtils.X_SIGNAL_AGENT) final String signalAgent,
@@ -115,6 +116,13 @@ public class RegistrationController {
throw new WebApplicationException("Invalid signature", 422);
}
if (!(registrationRequest.accountAttributes().getCapabilities() != null
? registrationRequest.accountAttributes().getCapabilities()
: Collections.<DeviceCapability>emptySet()).containsAll(DeviceCapability.CAPABILITIES_REQUIRED_FOR_REGISTRATION)) {
throw new WebApplicationException("Missing required device capability", 499);
}
rateLimiters.getRegistrationLimiter().validate(number);
final PhoneVerificationRequest.VerificationType verificationType = phoneVerificationTokenManager.verify(
@@ -44,6 +44,7 @@ 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}")
@io.swagger.v3.oas.annotations.tags.Tag(name = "Secure Value Recovery")
@@ -53,7 +54,7 @@ public class SecureValueRecovery2Controller {
MetricsUtil.name(SecureValueRecovery2Controller.class, "credentialAge");
public static final Duration MAX_AGE = Duration.ofDays(30);
public static final Duration MAX_AGE = RemoveExpiredAccountsCommand.MAX_IDLE_DURATION;
public static ExternalServiceCredentialsGenerator credentialsGenerator(final SecureValueRecoveryConfiguration cfg) {
return credentialsGenerator(cfg, Clock.systemUTC());
@@ -40,6 +40,7 @@ public class AccountAttributes {
private byte[] name;
@JsonProperty
@ExactlySize({0, 64})
private String registrationLock;
@JsonProperty
@@ -61,6 +62,7 @@ public class AccountAttributes {
@JsonProperty
@Nullable
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
@ExactlySize({0, 32})
private byte[] recoveryPassword = null;
public AccountAttributes() {
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import io.swagger.v3.oas.annotations.media.Schema;
import org.signal.libsignal.protocol.IdentityKey;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.util.ByteArrayBase64WithPaddingAdapter;
@@ -17,27 +18,34 @@ import org.whispersystems.textsecuregcm.util.IdentityKeyAdapter;
import java.util.List;
import java.util.Map;
@Schema(description = "Unversioned profile containing basic information")
public class BaseProfileResponse {
@Schema(description = "The account's public identity key (unpadded base64)")
@JsonProperty
@JsonSerialize(using = IdentityKeyAdapter.Serializer.class)
@JsonDeserialize(using = IdentityKeyAdapter.Deserializer.class)
private IdentityKey identityKey;
@Schema(description = "Checksum for unidentified access authentication (padded base64)")
@JsonProperty
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
private byte[] unidentifiedAccess;
@Schema(description = "Whether unidentified access is unrestricted for this account")
@JsonProperty
private boolean unrestrictedUnidentifiedAccess;
@Schema(description = "Device capabilities and whether they are enabled")
@JsonProperty
private Map<String, Boolean> capabilities;
@Schema(description = "List of badges displayed on the profile")
@JsonProperty
private List<Badge> badges;
@Schema(description = "Service identifier (ACI or PNI)")
@JsonProperty
@JsonSerialize(using = ServiceIdentifierAdapter.ServiceIdentifierSerializer.class)
@JsonDeserialize(using = ServiceIdentifierAdapter.ServiceIdentifierDeserializer.class)
@@ -7,29 +7,36 @@ package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.util.List;
import javax.annotation.Nullable;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import java.util.List;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.util.ExactlySize;
import org.whispersystems.textsecuregcm.util.ServiceIdentifierAdapter;
public record BatchIdentityCheckRequest(@Valid @NotNull @Size(max = 1000) List<Element> elements) {
@Schema(description = "Request to check identity key fingerprints for multiple accounts")
public record BatchIdentityCheckRequest(
@Schema(description = "List of accounts to check")
@Valid @NotNull @Size(max = 1000) List<Element> elements) {
/**
* @param uuid account id or phone number id
* @param fingerprint most significant 4 bytes of SHA-256 of the 33-byte identity key field (32-byte curve25519 public
* key prefixed with 0x05)
*/
public record Element(@NotNull
@JsonSerialize(using = ServiceIdentifierAdapter.ServiceIdentifierSerializer.class)
@JsonDeserialize(using = ServiceIdentifierAdapter.ServiceIdentifierDeserializer.class)
ServiceIdentifier uuid,
@Schema(description = "A service identifier and expected identity key fingerprint")
public record Element(
@Schema(description = "Identifier (ACI or PNI)")
@NotNull
@JsonSerialize(using = ServiceIdentifierAdapter.ServiceIdentifierSerializer.class)
@JsonDeserialize(using = ServiceIdentifierAdapter.ServiceIdentifierDeserializer.class)
ServiceIdentifier uuid,
@NotNull
@ExactlySize(4)
byte[] fingerprint) {
}
@Schema(description = "Expected identity key fingerprint (4 bytes, most significant bytes of SHA-256 hash of 33-byte identity key field)")
@NotNull
@ExactlySize(4)
byte[] fingerprint) {
}
}
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.List;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
@@ -16,17 +17,24 @@ import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.util.IdentityKeyAdapter;
import org.whispersystems.textsecuregcm.util.ServiceIdentifierAdapter;
public record BatchIdentityCheckResponse(@Valid List<Element> elements) {
@Schema(description = "Response containing accounts with mismatched identity key fingerprints")
public record BatchIdentityCheckResponse(
@Schema(description = "List of accounts where fingerprint did not match (empty if all matched)")
@Valid List<Element> elements) {
public record Element(@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonSerialize(using = ServiceIdentifierAdapter.ServiceIdentifierSerializer.class)
@JsonDeserialize(using = ServiceIdentifierAdapter.ServiceIdentifierDeserializer.class)
@NotNull
ServiceIdentifier uuid,
@Schema(description = "An account with a mismatched identity key fingerprint")
public record Element(
@Schema(description = "Service identifier (ACI or PNI)")
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonSerialize(using = ServiceIdentifierAdapter.ServiceIdentifierSerializer.class)
@JsonDeserialize(using = ServiceIdentifierAdapter.ServiceIdentifierDeserializer.class)
@NotNull
ServiceIdentifier uuid,
@NotNull
@JsonSerialize(using = IdentityKeyAdapter.Serializer.class)
@JsonDeserialize(using = IdentityKeyAdapter.Deserializer.class)
IdentityKey identityKey) {
@Schema(description = "The actual identity key for this account")
@NotNull
@JsonSerialize(using = IdentityKeyAdapter.Serializer.class)
@JsonDeserialize(using = IdentityKeyAdapter.Deserializer.class)
IdentityKey identityKey) {
}
}
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.List;
import java.util.Optional;
import jakarta.validation.constraints.NotEmpty;
@@ -17,52 +18,63 @@ import org.whispersystems.textsecuregcm.util.ByteArrayBase64WithPaddingAdapter;
import org.whispersystems.textsecuregcm.util.ExactlySize;
import org.whispersystems.textsecuregcm.util.ValidHexString;
@Schema(description = "Request to create or update a versioned profile")
public record CreateProfileRequest(
@Schema(description = "Profile key commitment")
@JsonProperty
@NotNull
@JsonDeserialize(using = ProfileKeyCommitmentAdapter.Deserializing.class)
@JsonSerialize(using = ProfileKeyCommitmentAdapter.Serializing.class)
ProfileKeyCommitment commitment,
@Schema(description = "Profile version identifier (hex-encoding of the public key)")
@JsonProperty
@NotEmpty
@ValidHexString
@ExactlySize({64})
String version,
@Schema(description = "Encrypted profile name. Padded base64.")
@JsonProperty
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
@ExactlySize({81, 285})
byte[] name,
@Schema(description = "Encrypted about emoji. Padded base64.")
@JsonProperty
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
@ExactlySize({0, 60})
byte[] aboutEmoji,
@Schema(description = "Encrypted about text. Padded base64.")
@JsonProperty
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
@ExactlySize({0, 156, 282, 540})
byte[] about,
@Schema(description = "Encrypted payment address. Padded base64.")
@JsonProperty
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
@ExactlySize({0, 582})
byte[] paymentAddress,
@Schema(description = "Whether the profile has an avatar")
@JsonProperty("avatar")
boolean hasAvatar,
@Schema(description = "Whether the avatar is unchanged from the previous version")
@JsonProperty
boolean sameAvatar,
@Schema(description = "List of badge IDs to display on the profile")
@JsonProperty("badgeIds")
Optional<List<String>> badges,
@Schema(description = "Encrypted phone number sharing preference. Padded base64.")
@JsonProperty
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
@@ -1,25 +0,0 @@
/*
* Copyright 2013-2021 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
public abstract class CredentialProfileResponse {
@JsonUnwrapped
private VersionedProfileResponse versionedProfileResponse;
protected CredentialProfileResponse() {
}
protected CredentialProfileResponse(final VersionedProfileResponse versionedProfileResponse) {
this.versionedProfileResponse = versionedProfileResponse;
}
public VersionedProfileResponse getVersionedProfileResponse() {
return versionedProfileResponse;
}
}
@@ -8,7 +8,10 @@ package org.whispersystems.textsecuregcm.entities;
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.Max;
import jakarta.validation.constraints.Min;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
import org.whispersystems.textsecuregcm.storage.KeyIdUtil;
import org.whispersystems.textsecuregcm.util.ECPublicKeyAdapter;
public record ECPreKey(
@@ -16,6 +19,8 @@ public record ECPreKey(
An arbitrary ID for this key, which will be provided by peers using this key to encrypt messages so the private key can be looked up.
Should not be zero. Should be less than 2^24.
""")
@Max(KeyIdUtil.MAX_KEY_ID)
@Min(KeyIdUtil.MIN_KEY_ID)
long keyId,
@JsonSerialize(using = ECPublicKeyAdapter.Serializer.class)
@@ -8,7 +8,10 @@ package org.whispersystems.textsecuregcm.entities;
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.Max;
import jakarta.validation.constraints.Min;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
import org.whispersystems.textsecuregcm.storage.KeyIdUtil;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import org.whispersystems.textsecuregcm.util.ECPublicKeyAdapter;
import java.util.Arrays;
@@ -19,6 +22,8 @@ public record ECSignedPreKey(
An arbitrary ID for this key, which will be provided by peers using this key to encrypt messages so the private key can be looked up.
Should not be zero. Should be less than 2^24.
""")
@Max(KeyIdUtil.MAX_KEY_ID)
@Min(KeyIdUtil.MIN_KEY_ID)
long keyId,
@JsonSerialize(using = ECPublicKeyAdapter.Serializer.class)
@@ -6,13 +6,20 @@
package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import io.swagger.v3.oas.annotations.media.Schema;
import javax.annotation.Nullable;
import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialResponse;
public class ExpiringProfileKeyCredentialProfileResponse extends CredentialProfileResponse {
@Schema(description = "Profile response with an expiring profile key credential")
public class ExpiringProfileKeyCredentialProfileResponse {
@JsonUnwrapped
private VersionedProfileResponse versionedProfileResponse;
@Schema(description = "Expiring profile key credential response. Null if profile version was not found")
@JsonProperty
@JsonSerialize(using = ExpiringProfileKeyCredentialResponseAdapter.Serializing.class)
@JsonDeserialize(using = ExpiringProfileKeyCredentialResponseAdapter.Deserializing.class)
@@ -25,7 +32,7 @@ public class ExpiringProfileKeyCredentialProfileResponse extends CredentialProfi
public ExpiringProfileKeyCredentialProfileResponse(final VersionedProfileResponse versionedProfileResponse,
@Nullable final ExpiringProfileKeyCredentialResponse credential) {
super(versionedProfileResponse);
this.versionedProfileResponse = versionedProfileResponse;
this.credential = credential;
}
@@ -33,4 +40,8 @@ public class ExpiringProfileKeyCredentialProfileResponse extends CredentialProfi
public ExpiringProfileKeyCredentialResponse getCredential() {
return credential;
}
public VersionedProfileResponse getVersionedProfileResponse() {
return versionedProfileResponse;
}
}
@@ -8,7 +8,10 @@ package org.whispersystems.textsecuregcm.entities;
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.Max;
import jakarta.validation.constraints.Min;
import org.signal.libsignal.protocol.kem.KEMPublicKey;
import org.whispersystems.textsecuregcm.storage.KeyIdUtil;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import org.whispersystems.textsecuregcm.util.KEMPublicKeyAdapter;
import java.util.Arrays;
@@ -20,6 +23,8 @@ public record KEMSignedPreKey(
Should not be zero. Should be less than 2^24. The owner of this key must be able to determine from the key ID whether this represents
a single-use or last-resort key, but another party should *not* be able to tell.
""")
@Max(KeyIdUtil.MAX_KEY_ID)
@Min(KeyIdUtil.MIN_KEY_ID)
long keyId,
@JsonSerialize(using = KEMPublicKeyAdapter.Serializer.class)
@@ -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;
@@ -6,44 +6,51 @@
package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema;
@Schema(description = "Profile avatar upload form (S3 Post Policy, AWS Signature version 4)")
public class ProfileAvatarUploadAttributes {
@Schema(description = "Object key for the avatar")
@JsonProperty
private String key;
@Schema(description = "Credential for the upload")
@JsonProperty
private String credential;
@Schema(description = "Access control list setting")
@JsonProperty
private String acl;
@Schema(description = "Signing algorithm")
@JsonProperty
private String algorithm;
@Schema(description = "Date in AWS format")
@JsonProperty
private String date;
@Schema(description = "Base64-encoded upload policy")
@JsonProperty
private String policy;
@Schema(description = "Signature calculated over the policy")
@JsonProperty
private String signature;
public ProfileAvatarUploadAttributes() {}
public ProfileAvatarUploadAttributes(String key, String credential,
String acl, String algorithm,
String date, String policy,
String signature)
{
this.key = key;
public ProfileAvatarUploadAttributes(String key, String credential, String acl, String algorithm, String date,
String policy, String signature) {
this.key = key;
this.credential = credential;
this.acl = acl;
this.algorithm = algorithm;
this.date = date;
this.policy = policy;
this.signature = signature;
this.acl = acl;
this.algorithm = algorithm;
this.date = date;
this.policy = policy;
this.signature = signature;
}
public String getKey() {
@@ -9,36 +9,45 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import io.swagger.v3.oas.annotations.media.Schema;
import org.whispersystems.textsecuregcm.util.ByteArrayBase64WithPaddingAdapter;
@Schema(description = "Versioned profile containing encrypted fields. Versioned fields may be empty if the version was not found.")
public record VersionedProfileResponse(
@Schema(description = "Base profile information")
@JsonUnwrapped
BaseProfileResponse baseProfileResponse,
@Schema(description = "Encrypted profile name. Padded base64.")
@JsonProperty
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] name,
@Schema(description = "Encrypted about text. Padded base64.")
@JsonProperty
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] about,
@Schema(description = "Encrypted about emoji. Padded base64.")
@JsonProperty
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] aboutEmoji,
@Schema(description = "Avatar CDN path")
@JsonProperty
String avatar,
@Schema(description = "Encrypted payment address. Padded base64.")
@JsonProperty
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] paymentAddress,
@Schema(description = "Encrypted phone number sharing preference. Padded base64.")
@JsonProperty
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
@@ -6,26 +6,24 @@
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 +34,35 @@ 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) {
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()));
}
public LookupUsernameHashResponse lookupUsernameHash(final LookupUsernameHashRequest request)
throws RateLimitExceededException {
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 +71,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,7 +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.entities.EncryptedUsername;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
@@ -56,9 +56,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,73 +76,56 @@ 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);
return DeleteAccountResponse.getDefaultInstance();
}
@Override
public Mono<SetRegistrationLockResponse> setRegistrationLock(final SetRegistrationLockRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedPrimaryDevice();
public SetRegistrationLockResponse setRegistrationLock(final SetRegistrationLockRequest request) {
// 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()));
if (request.getRegistrationLock().isEmpty()) {
throw GrpcExceptions.fieldViolation("registration_lock", "Registration lock secret must not be empty");
}
accountsManager.update(getAuthenticatedAccount(AuthenticationUtil.requireAuthenticatedPrimaryDevice()),
account -> account.setRegistrationLock(credentials.hash(), credentials.salt()));
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()));
return Mono.fromFuture(() -> accountsManager.updateAsync(account,
a -> a.setRegistrationLock(credentials.hash(), credentials.salt())));
})
.map(ignored -> SetRegistrationLockResponse.newBuilder().build());
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) {
throw GrpcExceptions.fieldViolation("username_hashes", "List of username hashes must not be empty");
}
if (request.getUsernameHashesCount() > AccountController.MAXIMUM_USERNAME_HASHES_LIST_LENGTH) {
throw GrpcExceptions.fieldViolation("username_hashes",
String.format("List of username hashes may have at most %d elements, but actually had %d",
AccountController.MAXIMUM_USERNAME_HASHES_LIST_LENGTH, request.getUsernameHashesCount()));
}
final List<byte[]> usernameHashes = new ArrayList<>(request.getUsernameHashesCount());
for (final ByteString usernameHash : request.getUsernameHashesList()) {
@@ -155,157 +137,142 @@ 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()) {
throw GrpcExceptions.fieldViolation("username_hash", "Username hash must not be empty");
}
if (request.getUsernameHash().size() != AccountController.USERNAME_HASH_LENGTH) {
throw GrpcExceptions.fieldViolation("username_hash",
String.format("Username hash length must be %d bytes, but was actually %d",
AccountController.USERNAME_HASH_LENGTH, request.getUsernameHash().size()));
}
if (request.getZkProof().isEmpty()) {
throw GrpcExceptions.fieldViolation("zk_proof", "Zero-knowledge proof must not be empty");
}
if (request.getUsernameCiphertext().isEmpty()) {
throw GrpcExceptions.fieldViolation("username_ciphertext", "Username ciphertext must not be empty");
}
if (request.getUsernameCiphertext().size() > AccountController.MAXIMUM_USERNAME_CIPHERTEXT_LENGTH) {
throw GrpcExceptions.fieldViolation("username_ciphertext",
String.format("Username ciphertext length must at most %d bytes, but was actually %d",
AccountController.MAXIMUM_USERNAME_CIPHERTEXT_LENGTH, request.getUsernameCiphertext().size()));
}
try {
usernameHashZkProofVerifier.verifyProof(request.getZkProof().toByteArray(), request.getUsernameHash().toByteArray());
} catch (final BaseUsernameException e) {
throw 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) {
throw GrpcExceptions.fieldViolation("username_ciphertext",
String.format("Username ciphertext must not be empty and must be shorter than %d bytes", EncryptedUsername.MAX_SIZE));
rateLimiters.getUsernameLinkOperationLimiter().validate(authenticatedDevice.accountIdentifier());
final Account account = getAuthenticatedAccount();
final SetUsernameLinkResponse.Builder responseBuilder = SetUsernameLinkResponse.newBuilder();
if (account.getUsernameHash().isEmpty()) {
return responseBuilder.setNoUsernameSet(FailedPrecondition.getDefaultInstance()).build();
}
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());
}
final UUID linkHandle = (request.getKeepLinkHandle() && account.getUsernameLinkHandle() != null)
? account.getUsernameLinkHandle()
: UUID.randomUUID();
final UUID linkHandle;
if (request.getKeepLinkHandle() && account.getUsernameLinkHandle() != null) {
linkHandle = account.getUsernameLinkHandle();
} else {
linkHandle = UUID.randomUUID();
}
accountsManager.update(account, a -> a.setUsernameLinkDetails(linkHandle, request.getUsernameCiphertext().toByteArray()));
return Mono.fromFuture(() -> accountsManager.updateAsync(account, a -> a.setUsernameLinkDetails(linkHandle, request.getUsernameCiphertext().toByteArray())))
.thenReturn(responseBuilder.setUsernameLinkHandle(UUIDUtil.toByteString(linkHandle)).build());
});
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) {
if (request.getRegistrationRecoveryPassword().isEmpty()) {
throw GrpcExceptions.fieldViolation("registration_recovery_password", "Registration recovery password must not be empty");
}
public SetRegistrationRecoveryPasswordResponse setRegistrationRecoveryPassword(final SetRegistrationRecoveryPasswordRequest request) {
registrationRecoveryPasswordsManager.store(getAuthenticatedAccount().getIdentifier(IdentityType.PNI),
request.getRegistrationRecoveryPassword().toByteArray())
.join();
return getAccount()
.flatMap(account -> Mono.fromFuture(() -> registrationRecoveryPasswordsManager.store(account.getIdentifier(IdentityType.PNI), request.getRegistrationRecoveryPassword().toByteArray())))
.thenReturn(SetRegistrationRecoveryPasswordResponse.newBuilder().build());
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"));
}
}
@@ -0,0 +1,61 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import java.security.SecureRandom;
import java.util.Map;
import org.signal.chat.attachments.GetUploadFormRequest;
import org.signal.chat.attachments.GetUploadFormResponse;
import org.signal.chat.attachments.SimpleAttachmentsGrpc;
import org.signal.chat.common.UploadForm;
import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
import org.whispersystems.textsecuregcm.attachments.GcsAttachmentGenerator;
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
public class AttachmentsGrpcService extends SimpleAttachmentsGrpc.AttachmentsImplBase {
private final ExperimentEnrollmentManager experimentEnrollmentManager;
private final RateLimiter rateLimiter;
private final Map<Integer, AttachmentGenerator> attachmentGenerators;
private final SecureRandom secureRandom;
public AttachmentsGrpcService(
final ExperimentEnrollmentManager experimentEnrollmentManager,
final RateLimiters rateLimiters,
final GcsAttachmentGenerator gcsAttachmentGenerator,
final TusAttachmentGenerator tusAttachmentGenerator) {
this.experimentEnrollmentManager = experimentEnrollmentManager;
this.rateLimiter = rateLimiters.getAttachmentLimiter();
this.secureRandom = new SecureRandom();
this.attachmentGenerators = Map.of(
2, gcsAttachmentGenerator,
3, tusAttachmentGenerator);
}
@Override
public GetUploadFormResponse getUploadForm(final GetUploadFormRequest request) throws RateLimitExceededException {
final AuthenticatedDevice auth = AuthenticationUtil.requireAuthenticatedDevice();
rateLimiter.validate(auth.accountIdentifier());
final String key = AttachmentUtil.generateAttachmentKey(secureRandom);
final boolean useCdn3 = this.experimentEnrollmentManager.isEnrolled(auth.accountIdentifier(),
AttachmentUtil.CDN3_EXPERIMENT_NAME);
final int cdn = useCdn3 ? 3 : 2;
final AttachmentGenerator.Descriptor descriptor = this.attachmentGenerators.get(cdn).generateAttachment(key);
return GetUploadFormResponse.newBuilder().setUploadForm(UploadForm.newBuilder()
.setCdn(cdn)
.setKey(key)
.putAllHeaders(descriptor.headers())
.setSignedUploadLocation(descriptor.signedUploadLocation()))
.build();
}
}
@@ -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,19 +101,40 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
}
@Override
public GetBackupInfoResponse getBackupInfo(final GetBackupInfoRequest request) throws 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();
}
@@ -122,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())
@@ -140,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();
}
@@ -260,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()))
@@ -9,7 +9,6 @@ import com.google.protobuf.ByteString;
import com.google.protobuf.Empty;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
@@ -17,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;
@@ -26,6 +24,7 @@ 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;
@@ -34,10 +33,8 @@ 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;
@@ -46,31 +43,33 @@ public class DevicesGrpcService extends ReactorDevicesGrpc.DevicesImplBase {
}
@Override
public Mono<GetDevicesResponse> getDevices(final GetDevicesRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
public GetDevicesResponse getDevices(final GetDevicesRequest request) {
final Account account = getAuthenticatedAccount();
return getAccount(authenticatedDevice.accountIdentifier())
.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 GrpcExceptions.invalidArguments("cannot remove primary device");
}
@@ -83,13 +82,13 @@ public class DevicesGrpcService extends ReactorDevicesGrpc.DevicesImplBase {
final byte deviceId = DeviceIdUtil.validate(request.getId());
return getAccount(authenticatedDevice.accountIdentifier())
.flatMap(account -> Mono.fromFuture(accountsManager.removeDevice(account, deviceId)))
.thenReturn(RemoveDeviceResponse.newBuilder().build());
accountsManager.removeDevice(getAuthenticatedAccount(), deviceId);
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,19 +100,19 @@ public class DevicesGrpcService extends ReactorDevicesGrpc.DevicesImplBase {
throw GrpcExceptions.badAuthentication("linked device is not authorized to change target device name");
}
return getAccount(authenticatedDevice.accountIdentifier())
.flatMap(account -> {
if (account.getDevice(deviceId).isEmpty()) {
return Mono.just(SetDeviceNameResponse.newBuilder().setTargetDeviceNotFound(NotFound.getDefaultInstance()).build());
}
return Mono.fromFuture(() -> accountsManager.updateDeviceAsync(account, deviceId, device ->
device.setName(request.getName().toByteArray())))
.thenReturn(SetDeviceNameResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build());
});
final Account account = getAuthenticatedAccount();
if (account.getDevice(deviceId).isEmpty()) {
return SetDeviceNameResponse.newBuilder().setTargetDeviceNotFound(NotFound.getDefaultInstance()).build();
}
accountsManager.updateDevice(account, deviceId, device -> device.setName(request.getName().toByteArray()));
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;
@@ -136,62 +135,58 @@ public class DevicesGrpcService extends ReactorDevicesGrpc.DevicesImplBase {
default -> throw GrpcExceptions.fieldViolation("token_request", "No tokens specified");
}
return getAccount(authenticatedDevice.accountIdentifier())
.flatMap(account -> {
final Device device = account.getDevice(authenticatedDevice.deviceId())
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
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 getAccount(authenticatedDevice.accountIdentifier())
.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 getAccount(authenticatedDevice.accountIdentifier())
.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 Mono<Account> getAccount(final UUID accountIdentifier) {
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(accountIdentifier))
.map(maybeAccount -> maybeAccount.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials")));
private Account getAuthenticatedAccount() {
return accountsManager.getByAccountIdentifier(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier())
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
}
}
@@ -53,9 +53,6 @@ public class ExternalServiceCredentialsAnonymousGrpcService extends
@Override
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,
@@ -10,31 +10,28 @@ import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.Status;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
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 boolean enableAll;
private final Set<String> enabledServices;
private final Set<String> enabledMethods;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
public GrpcAllowListInterceptor(
final boolean enableAll,
final List<String> enabledServices,
final List<String> enabledMethods) {
this.enableAll = enableAll;
this.enabledServices = new HashSet<>(enabledServices);
this.enabledMethods = new HashSet<>(enabledMethods);
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 (!enableAll && !enabledServices.contains(methodDescriptor.getServiceName()) && !enabledMethods.contains(methodDescriptor.getFullMethodName())) {
if (!allowList.enableAll() &&
!allowList.enabledServices().contains(methodDescriptor.getServiceName()) &&
!allowList.enabledMethods().contains(methodDescriptor.getFullMethodName())) {
return ServerInterceptorUtil.closeWithStatus(serverCall, Status.UNIMPLEMENTED);
}
return next.startCall(serverCall, metadata);
@@ -10,13 +10,15 @@ 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.AccountPreKeyBundles;
import org.signal.chat.keys.CheckIdentityKeyRequest;
import org.signal.chat.keys.CheckIdentityKeyResponse;
import org.signal.chat.keys.GetPreKeysAnonymousRequest;
import org.signal.chat.keys.GetPreKeysAnonymousResponse;
import org.signal.chat.keys.ReactorKeysAnonymousGrpc;
import org.signal.chat.keys.SimpleKeysAnonymousGrpc;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
@@ -24,11 +26,11 @@ 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;
@@ -42,7 +44,7 @@ public class KeysAnonymousGrpcService extends ReactorKeysAnonymousGrpc.KeysAnony
}
@Override
public Mono<GetPreKeysAnonymousResponse> getPreKeys(final GetPreKeysAnonymousRequest request) {
public GetPreKeysAnonymousResponse getPreKeys(final GetPreKeysAnonymousRequest request) {
final ServiceIdentifier serviceIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getTargetIdentifier());
@@ -53,34 +55,42 @@ public class KeysAnonymousGrpcService extends ReactorKeysAnonymousGrpc.KeysAnony
return switch (request.getAuthorizationCase()) {
case GROUP_SEND_TOKEN -> {
if (!groupSendTokenUtil.checkGroupSendToken(request.getGroupSendToken(), serviceIdentifier)) {
yield Mono.fromSupplier(() -> GetPreKeysAnonymousResponse.newBuilder()
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 -> 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());
}
yield lookUpAccount(serviceIdentifier)
.flatMap(targetAccount -> KeysGrpcHelper
.getPreKeys(targetAccount, serviceIdentifier, deviceId, keysManager))
.map(preKeys -> GetPreKeysAnonymousResponse.newBuilder().setPreKeys(preKeys).build())
.switchIfEmpty(Mono.fromSupplier(() -> GetPreKeysAnonymousResponse.newBuilder()
.setTargetNotFound(NotFound.getDefaultInstance())
.build()));
}
case UNIDENTIFIED_ACCESS_KEY -> lookUpAccount(serviceIdentifier)
.filter(targetAccount ->
UnidentifiedAccessUtil.checkUnidentifiedAccess(targetAccount, request.getUnidentifiedAccessKey().toByteArray()))
.flatMap(targetAccount -> KeysGrpcHelper.getPreKeys(targetAccount, serviceIdentifier, deviceId, keysManager))
.map(preKeys -> GetPreKeysAnonymousResponse.newBuilder().setPreKeys(preKeys).build())
.switchIfEmpty(Mono.fromSupplier(() -> GetPreKeysAnonymousResponse.newBuilder()
.setFailedUnidentifiedAuthorization(FailedUnidentifiedAuthorization.getDefaultInstance())
.build()));
default -> Mono.error(GrpcExceptions.fieldViolation("authorization", "invalid authorization type"));
case UNRESTRICTED_ACCESS -> accountsManager.getByServiceIdentifier(serviceIdentifier)
.filter(Account::isUnrestrictedUnidentifiedAccess)
.flatMap(targetAccount -> KeysGrpcHelper.getPreKeys(targetAccount, serviceIdentifier, deviceId, keysManager))
.map(accountPreKeyBundles -> GetPreKeysAnonymousResponse.newBuilder().setPreKeys(accountPreKeyBundles).build())
.orElseGet(() -> GetPreKeysAnonymousResponse.newBuilder()
.setFailedUnidentifiedAuthorization(FailedUnidentifiedAuthorization.getDefaultInstance())
.build());
case AUTHORIZATION_NOT_SET -> 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(
@@ -89,17 +99,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) {
return Mono.fromFuture(() -> accountsManager.getByServiceIdentifierAsync(serviceIdentifier))
.flatMap(Mono::justOrEmpty);
.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,84 +6,87 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
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.AccountPreKeyBundles;
import org.signal.chat.keys.DevicePreKeyBundle;
import org.signal.libsignal.protocol.IdentityKey;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.KeyIdUtil;
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;
import java.util.Optional;
class KeysGrpcHelper {
static final byte ALL_DEVICES = 0;
/**
* Fetch {@link AccountPreKeyBundles} from the targetAccount
*
* @param targetAccount The targetAccount to fetch pre-key bundles from
* @param targetServiceIdentifier The serviceIdentifier used to lookup the targetAccount
* @param targetDeviceId The deviceId 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 an empty Mono if the keys for the targetAccount do not exist
*/
static Mono<AccountPreKeyBundles> 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 DevicePreKeyBundle.Builder builder = DevicePreKeyBundle.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());
});
})
.collectMap(Tuple2::getT1, Tuple2::getT2)
.flatMap(preKeyBundles -> {
if (preKeyBundles.isEmpty()) {
// If there were no devices with valid prekey bundles in the account, the account is gone
return Mono.empty();
}
final IdentityKey targetIdentityKey = targetAccount.getIdentityKey(targetServiceIdentifier.identityType());
return Mono.just(AccountPreKeyBundles.newBuilder()
.setIdentityKey(ByteString.copyFrom(targetIdentityKey.serialize()))
.putAllDevicePreKeys(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(KeyIdUtil.toUnsignedInt(devicePreKeys.ecSignedPreKey().keyId()))
.setPublicKey(ByteString.copyFrom(devicePreKeys.ecSignedPreKey().serializedPublicKey()))
.setSignature(ByteString.copyFrom(devicePreKeys.ecSignedPreKey().signature())))
.setKemOneTimePreKey(KemSignedPreKey.newBuilder()
.setKeyId(KeyIdUtil.toUnsignedInt(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(KeyIdUtil.toUnsignedInt(ecPreKey.keyId()))
.setPublicKey(ByteString.copyFrom(ecPreKey.serializedPublicKey()))));
preKeyBundlesBuilder.putDevicePreKeys(deviceId, builder.build());
});
return Optional.of(preKeyBundlesBuilder.build());
}
}
@@ -18,18 +18,19 @@ 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;
@@ -39,11 +40,8 @@ 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;
@@ -55,11 +53,6 @@ public class KeysGrpcService extends ReactorKeysGrpc.KeysImplBase {
private static final StatusRuntimeException INVALID_SIGNATURE_EXCEPTION =
GrpcExceptions.fieldViolation("pre_keys", "pre-key signature did not match account identity key");
private enum PreKeyType {
EC,
KEM
}
public KeysGrpcService(final AccountsManager accountsManager,
final KeysManager keysManager,
final RateLimiters rateLimiters) {
@@ -70,48 +63,34 @@ public class KeysGrpcService extends ReactorKeysGrpc.KeysImplBase {
}
@Override
public Mono<GetPreKeyCountResponse> getPreKeyCount(final GetPreKeyCountRequest request) {
return Mono.fromSupplier(AuthenticationUtil::requireAuthenticatedDevice)
.flatMap(authenticatedDevice -> getAuthenticatedAccount(authenticatedDevice.accountIdentifier())
.zipWith(Mono.just(authenticatedDevice.deviceId())))
.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 =
@@ -126,107 +105,107 @@ public class KeysGrpcService extends ReactorKeysGrpc.KeysImplBase {
targetIdentifier.uuid() + "." +
deviceId;
return rateLimiters.getPreKeysLimiter().validateReactive(rateLimitKey)
.then(Mono.fromFuture(() -> accountsManager.getByServiceIdentifierAsync(targetIdentifier)))
.flatMap(Mono::justOrEmpty)
rateLimiters.getPreKeysLimiter().validate(rateLimitKey);
return accountsManager.getByServiceIdentifier(targetIdentifier)
.flatMap(targetAccount -> KeysGrpcHelper.getPreKeys(targetAccount, targetIdentifier, deviceId, keysManager))
.map(bundles -> GetPreKeysResponse.newBuilder()
.setPreKeys(bundles)
.map(accountPreKeyBundles -> GetPreKeysResponse.newBuilder()
.setPreKeys(accountPreKeyBundles)
.build())
.switchIfEmpty(Mono.fromSupplier(() -> GetPreKeysResponse.newBuilder()
.orElseGet(() -> GetPreKeysResponse.newBuilder()
.setTargetNotFound(NotFound.getDefaultInstance())
.build()));
.build());
}
@Override
public Mono<SetPreKeyResponse> setOneTimeEcPreKeys(final SetOneTimeEcPreKeysRequest request) {
if (request.getPreKeysList().isEmpty()) {
throw GrpcExceptions.fieldViolation("pre_keys", "pre_keys must be non-empty");
}
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) {
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) {
if (request.getPreKeysList().isEmpty()) {
throw GrpcExceptions.fieldViolation("pre_keys", "pre_keys must be non-empty");
}
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) {
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 getAuthenticatedAccount(authenticatedAccountUuid)
.map(account -> {
final List<K> preKeys = requestPreKeys.stream()
.map(requestPreKey -> extractPreKeyFunction.apply(requestPreKey, account.getIdentityKey(identityType)))
.toList();
final Account account = getAuthenticatedAccount(authenticatedAccountUuid);
return Tuples.of(account.getIdentifier(identityType), preKeys);
})
.flatMap(identifierAndPreKeys -> Mono.fromFuture(() -> storeKeysFunction.apply(identifierAndPreKeys.getT1(), identifierAndPreKeys.getT2())))
.thenReturn(SetPreKeyResponse.newBuilder().build());
final List<K> preKeys = requestPreKeys.stream()
.map(requestPreKey -> extractPreKeyFunction.apply(requestPreKey, account.getIdentityKey(identityType)))
.toList();
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 getAuthenticatedAccount(authenticatedAccountUuid)
.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,8 +248,8 @@ public class KeysGrpcService extends ReactorKeysGrpc.KeysImplBase {
}
}
private Mono<Account> getAuthenticatedAccount(final UUID authenticatedAccountId) {
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedAccountId))
.map(maybeAccount -> maybeAccount.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials")));
private Account getAuthenticatedAccount(final UUID authenticatedAccountId) {
return accountsManager.getByAccountIdentifier(authenticatedAccountId)
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
}
}
@@ -14,6 +14,7 @@ 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.SendMessageType;
import org.signal.chat.messages.MultiRecipientMismatchedDevices;
import org.signal.chat.messages.MultiRecipientSuccess;
import org.signal.chat.messages.SendMessageResponse;
@@ -27,6 +28,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;
@@ -37,7 +39,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;
@@ -100,6 +102,8 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
}
case GROUP_SEND_TOKEN ->
groupSendTokenUtil.checkGroupSendToken(request.getGroupSendToken(), destinationServiceIdentifier);
case UNRESTRICTED_ACCESS ->
maybeDestination.map(account -> account.isUnrestrictedUnidentifiedAccess()).orElse(false);
case AUTHORIZATION_NOT_SET ->
throw GrpcExceptions.fieldViolation("authorization", "expected authorization token not provided");
};
@@ -155,16 +159,15 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
final boolean urgent,
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()
@@ -182,6 +185,9 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
.collect(Collectors.toMap(
entry -> DeviceIdUtil.validate(entry.getKey()),
entry -> {
if (entry.getValue().getType() != SendMessageType.UNIDENTIFIED_SENDER) {
throw GrpcExceptions.invalidArguments("sealed sender messages must have a type of UNIDENTIFIED_SENDER");
}
final MessageProtos.Envelope.Builder envelopeBuilder = MessageProtos.Envelope.newBuilder()
.setType(MessageProtos.Envelope.Type.UNIDENTIFIED_SENDER)
.setClientTimestamp(messages.getTimestamp())
@@ -208,12 +214,22 @@ 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
@@ -265,14 +281,13 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
final boolean urgent,
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.
@@ -5,71 +5,11 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.Empty;
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()
.setSuccess(Empty.getDefaultInstance())
.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 RateLimitExceededException if the message bundle could not be sent due to a violated rated limit
* @throws io.grpc.StatusRuntimeException for invalid arguments if the message is too large to send
*/
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 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 GrpcExceptions.invalidArguments("message too large");
}
}
/**
* Translates an internal {@link org.whispersystems.textsecuregcm.controllers.MismatchedDevices} entity to a gRPC
* {@link MismatchedDevices} entity.
@@ -10,15 +10,17 @@ 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.SendMessageType;
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;
@@ -26,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;
@@ -42,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,
@@ -58,7 +66,7 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
}
@Override
public SendMessageResponse sendMessage(final SendAuthenticatedSenderMessageRequest request)
public SendMessageAuthenticatedSenderResponse sendMessage(final SendAuthenticatedSenderMessageRequest request)
throws RateLimitExceededException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
@@ -75,7 +83,9 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
final Optional<Account> maybeDestination = accountsManager.getByServiceIdentifier(destinationServiceIdentifier);
if (maybeDestination.isEmpty()) {
return SendMessageResponse.newBuilder().setDestinationNotFound(NotFound.getDefaultInstance()).build();
return SendMessageAuthenticatedSenderResponse.newBuilder()
.setDestinationNotFound(NotFound.getDefaultInstance())
.build();
}
final Account destination = maybeDestination.get();
@@ -84,7 +94,6 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
return sendMessage(destination,
destinationServiceIdentifier,
authenticatedDevice,
request.getType(),
MessageType.INDIVIDUAL_IDENTIFIED_SENDER,
request.getMessages(),
request.getEphemeral(),
@@ -92,7 +101,7 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
}
@Override
public SendMessageResponse sendSyncMessage(final SendSyncMessageRequest request)
public SendMessageAuthenticatedSenderResponse sendSyncMessage(final SendSyncMessageRequest request)
throws RateLimitExceededException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
@@ -103,17 +112,15 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
return sendMessage(sender,
senderServiceIdentifier,
authenticatedDevice,
request.getType(),
MessageType.SYNC,
request.getMessages(),
false,
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,
@@ -130,14 +137,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()
@@ -146,7 +155,7 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
entry -> DeviceIdUtil.validate(entry.getKey()),
entry -> {
final MessageProtos.Envelope.Builder envelopeBuilder = MessageProtos.Envelope.newBuilder()
.setType(getEnvelopeType(envelopeType))
.setType(getEnvelopeType(entry.getValue().getType()))
.setClientTimestamp(messages.getTimestamp())
.setServerTimestamp(clock.millis())
.setDestinationServiceId(destinationServiceIdentifier.toServiceIdentifierString())
@@ -168,19 +177,31 @@ 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) {
private static MessageProtos.Envelope.Type getEnvelopeType(final SendMessageType type) {
return switch (type) {
case DOUBLE_RATCHET -> MessageProtos.Envelope.Type.CIPHERTEXT;
case PREKEY_MESSAGE -> MessageProtos.Envelope.Type.PREKEY_BUNDLE;
case PLAINTEXT_CONTENT -> MessageProtos.Envelope.Type.PLAINTEXT_CONTENT;
case UNIDENTIFIED_SENDER ->
throw GrpcExceptions.invalidArguments("illegal envelope type for identified sends");
case UNSPECIFIED, UNRECOGNIZED ->
throw GrpcExceptions.invalidArguments("unrecognized envelope type");
};
@@ -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,7 +30,7 @@ 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
@@ -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
@@ -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());
}
}
@@ -5,12 +5,37 @@
package org.whispersystems.textsecuregcm.grpc;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import javax.annotation.Nullable;
public record RequestAttributes(InetAddress remoteAddress,
@Nullable String userAgent,
@Nullable String acceptLanguageRaw,
List<Locale.LanguageRange> acceptLanguage) {
private static final Logger LOGGER = LoggerFactory.getLogger(RequestAttributes.class);
public RequestAttributes(InetAddress remoteAddress,
@Nullable String userAgent,
@Nullable String acceptLanguageRaw) {
this(remoteAddress, userAgent, acceptLanguageRaw, parseAcceptLanguage(acceptLanguageRaw, userAgent));
}
private static List<Locale.LanguageRange> parseAcceptLanguage(final String acceptLanguageRaw, final String userAgent) {
List<Locale.LanguageRange> acceptLanguages = Collections.emptyList();
if (StringUtils.isNotBlank(acceptLanguageRaw)) {
try {
acceptLanguages = Locale.LanguageRange.parse(acceptLanguageRaw);
} catch (final IllegalArgumentException e) {
LOGGER.debug("Invalid Accept-Language header from User-Agent {}: {}", userAgent, acceptLanguageRaw, e);
}
}
return acceptLanguages;
}
}
@@ -70,17 +70,8 @@ public class RequestAttributesInterceptor implements ServerInterceptor {
return ServerInterceptorUtil.closeWithStatus(call, Status.UNAVAILABLE);
}
@Nullable List<Locale.LanguageRange> acceptLanguages = Collections.emptyList();
if (StringUtils.isNotBlank(acceptLanguageHeader)) {
try {
acceptLanguages = Locale.LanguageRange.parse(acceptLanguageHeader);
} catch (final IllegalArgumentException e) {
log.debug("Invalid Accept-Language header from User-Agent {}: {}", userAgentHeader, acceptLanguageHeader, e);
}
}
final RequestAttributes requestAttributes =
new RequestAttributes(remoteAddress.get(), userAgentHeader, acceptLanguages);
new RequestAttributes(remoteAddress.get(), userAgentHeader, acceptLanguageHeader);
return Contexts.interceptCall(
Context.current().withValue(RequestAttributesUtil.REQUEST_ATTRIBUTES_CONTEXT_KEY, requestAttributes),
call, headers, next);
@@ -1,6 +1,7 @@
package org.whispersystems.textsecuregcm.grpc;
import io.grpc.Context;
import javax.annotation.Nullable;
import java.net.InetAddress;
import java.util.Arrays;
import java.util.List;
@@ -22,6 +23,15 @@ public class RequestAttributesUtil {
return REQUEST_ATTRIBUTES_CONTEXT_KEY.get().acceptLanguage();
}
/**
* Returns the raw "Accept-Language" header string from the remote client in the current gRPC request context
*
* @return the raw "Accept-Language" header listed by the remote client; may be null if not specified
*/
public static @Nullable String getAcceptLanguageRaw() {
return REQUEST_ATTRIBUTES_CONTEXT_KEY.get().acceptLanguageRaw();
}
/**
* Returns a list of distinct locales supported by the JVM and accepted by the remote client in the current gRPC
* context. May be empty if the client did not supply a list of acceptable languages, if the list of acceptable
@@ -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;
@@ -19,8 +19,11 @@ public class ServiceIdentifierUtil {
}
public static ServiceIdentifier fromGrpcServiceIdentifier(final org.signal.chat.common.ServiceIdentifier serviceIdentifier) {
final UUID uuid;
if (serviceIdentifier == null) {
throw GrpcExceptions.invalidArguments("invalid service identifier");
}
final UUID uuid;
try {
uuid = UUIDUtil.fromByteString(serviceIdentifier.getUuid());
} catch (final IllegalArgumentException e) {
@@ -94,6 +94,12 @@ public class ValidatingInterceptor implements ServerInterceptor {
final Descriptors.FieldDescriptor extensionFieldDescriptor = entry.getKey();
final String extensionName = extensionFieldDescriptor.getFullName();
// If this is a oneof, but this field isn't set, we shouldn't validate it. We assume if you have a validator
// that requires presence, you don't actually want presence enforcement on a oneof case.
if (fd.getRealContainingOneof() != null && !msg.hasField(fd)) {
continue;
}
// first validate the field
final FieldValidator validator = fieldValidators.get(extensionName);
// not all extensions are validators, so `validator` value here could legitimately be `null`
@@ -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()),
@@ -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()));
@@ -171,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, platformTag).and(UserAgentTagUtil.getAdditionalSpecifierTags(userAgent)))
Tags.of(clientVersionTag, platformTag))
.increment());
}
@@ -146,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, platformTag).and(UserAgentTagUtil.getAdditionalSpecifierTags(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()));
});
@@ -2,97 +2,127 @@ package org.whispersystems.textsecuregcm.metrics;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.net.InetAddresses;
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.net.InetSocketAddress;
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 java.util.function.Supplier;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.asn.AsnInfo;
import org.whispersystems.textsecuregcm.asn.AsnInfoProvider;
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 Supplier<AsnInfoProvider> asnInfoProviderSupplier;
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 Map<String, AtomicInteger> openWebsocketsByAsnRegion = new ConcurrentHashMap<>();
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");
private static final String OPEN_WEBSOCKET_BY_ASN_REGION_GAUGE_NAME = name(OpenWebSocketCounter.class, "openWebsocketsByAsnRegion");
this(openWebSocketGaugeName, newConnectionCounterName, durationTimerName, Tags.empty());
}
public OpenWebSocketCounter(final String webSocketType,
final Supplier<AsnInfoProvider> asnInfoProviderSupplier,
final ClientReleaseManager clientReleaseManager) {
public OpenWebSocketCounter(final String openWebSocketGaugeName,
final String newConnectionCounterName,
final String durationTimerName,
final Tags tags) {
this.asnInfoProviderSupplier = asnInfoProviderSupplier;
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;
final Optional<AtomicInteger> maybeOpenWebSocketsByAsnRegion;
{
AtomicInteger calculatedOpenWebSocketCounter;
try {
final ClientPlatform clientPlatform =
UserAgentUtil.parseUserAgentString(context.getClient().getUserAgent()).platform();
calculatedOpenWebSocketCounter = openWebsocketsByClientPlatform.get(clientPlatform);
} catch (final UnrecognizedUserAgentException e) {
calculatedOpenWebSocketCounter = openWebsocketsFromUnknownPlatforms;
}
openWebSocketCounter = calculatedOpenWebSocketCounter;
if (context.getClient().getRemoteAddress() instanceof InetSocketAddress inetSocketAddress) {
maybeOpenWebSocketsByAsnRegion =
asnInfoProviderSupplier.get().lookup(InetAddresses.toAddrString(inetSocketAddress.getAddress()))
.map(AsnInfo::regionCode)
.map(asnRegion -> openWebsocketsByAsnRegion.computeIfAbsent(asnRegion, region ->
Metrics.gauge(OPEN_WEBSOCKET_BY_ASN_REGION_GAUGE_NAME, Tags.of("asnRegion", region),
new AtomicInteger(0))));
} else {
maybeOpenWebSocketsByAsnRegion = Optional.empty();
}
openWebSocketCounter.incrementAndGet();
maybeOpenWebSocketsByAsnRegion.ifPresent(AtomicInteger::incrementAndGet);
final Tags tagsWithClientPlatform = tags.and(UserAgentTagUtil.getPlatformTag(context.getClient().getUserAgent()));
@Nullable final UserAgent userAgent;
{
UserAgent parsedUserAgent;
Metrics.counter(newConnectionCounterName, tagsWithClientPlatform).increment();
try {
parsedUserAgent = UserAgentUtil.parseUserAgentString(context.getClient().getUserAgent());
} catch (final UnrecognizedUserAgentException e) {
parsedUserAgent = null;
}
userAgent = parsedUserAgent;
}
final Tags tagsWithClientPlatform = baseTags.and(UserAgentTagUtil.getPlatformTag(userAgent));
final Optional<AtomicInteger> maybeOpenWebSocketCounter;
{
final Tags tagsWithAdditionalSpecifiers = tagsWithClientPlatform
.and(UserAgentTagUtil.getClientVersionTag(userAgent, clientReleaseManager)
.map(Tags::of)
.orElseGet(Tags::empty))
.and(UserAgentTagUtil.getAdditionalSpecifierTags(userAgent));
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);
maybeOpenWebSocketsByAsnRegion.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))));
}
}
@@ -36,7 +36,7 @@ public class UserAgentTagUtil {
String.format("Signal-Server/%s (%s)", WhisperServerVersion.getServerVersion(), UUID.randomUUID());
private static final Pattern STANDARD_ADDITIONAL_SPECIFIERS_PATTERN =
Pattern.compile("^(Windows|macOS|Linux) (\\S+) libsignal/([\\d.]+).*$", Pattern.CASE_INSENSITIVE);
Pattern.compile("^(Android|iOS|Windows|macOS|Linux)[ /](\\S+) libsignal/([\\d.]+).*$", Pattern.CASE_INSENSITIVE);
private UserAgentTagUtil() {
}
@@ -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);
@@ -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,76 +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 io.grpc.StatusRuntimeException;
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> {
@Nullable
private final StatusRuntimeException statusException;
@Nullable
private final R response;
private GrpcResponse(final @Nullable StatusRuntimeException statusException, @Nullable final R 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 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> withStatusException(final StatusRuntimeException 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<>(null, 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 StatusRuntimeException {
if (statusException != null) {
throw statusException;
}
return response;
}
}
@@ -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());
@@ -10,12 +10,11 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import org.whispersystems.textsecuregcm.util.ThrowingSupplier;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
public class AccountLockManager {
@@ -54,11 +53,11 @@ public class AccountLockManager {
*
* @return the value returned by the given {@code task}
*
* @throws Exception if an exception is thrown by the given {@code task}
* @throws E if an exception is thrown by the given {@code task}
*/
public <V> V withLock(final Set<UUID> phoneNumberIdentifiers,
final Callable<V> task,
final Executor lockAcquisitionExecutor) throws Exception {
public <V, E extends Exception> V withLock(final Set<UUID> phoneNumberIdentifiers,
final ThrowingSupplier<V, E> task,
final Executor lockAcquisitionExecutor) throws E {
if (phoneNumberIdentifiers.isEmpty()) {
throw new IllegalArgumentException("List of PNIs to lock must not be empty");
@@ -82,7 +81,7 @@ public class AccountLockManager {
}
}, lockAcquisitionExecutor).join();
return task.call();
return task.get();
} finally {
CompletableFuture.runAsync(() -> {
for (final LockItem lockItem : lockItems) {
@@ -93,43 +92,4 @@ public class AccountLockManager {
}, lockAcquisitionExecutor).join();
}
}
/**
* Acquires a distributed, pessimistic lock for the accounts identified by the given phone number identifiers. By
* design, the accounts need not actually exist in order to acquire a lock; this allows lock acquisition for
* operations that span account lifecycle changes (like deleting an account or changing a phone number). The given
* task runs once locks for all given identifiers have been acquired, and the locks are released as soon as the task
* completes by any means.
*
* @param phoneNumberIdentifiers the phone number identifiers for which to acquire a distributed, pessimistic lock
* @param taskSupplier a supplier for the task to execute once locks have been acquired
* @param executor the executor on which to acquire and release locks
* @return a future that completes normally when the given task has executed successfully and all locks have been
* released; the returned future may fail with an {@link InterruptedException} if interrupted while acquiring a lock
*/
public <T> CompletableFuture<T> withLockAsync(final Set<UUID> phoneNumberIdentifiers,
final Supplier<CompletableFuture<T>> taskSupplier, final Executor executor) {
if (phoneNumberIdentifiers.isEmpty()) {
throw new IllegalArgumentException("List of PNIs to lock must not be empty");
}
final List<LockItem> lockItems = new ArrayList<>(phoneNumberIdentifiers.size());
return CompletableFuture.runAsync(() -> {
for (final UUID pni : phoneNumberIdentifiers) {
try {
lockItems.add(lockClient.acquireLock(AcquireLockOptions.builder(pni.toString())
.withAcquireReleasedLocksConsistently(true)
.build()));
} catch (final InterruptedException e) {
throw new CompletionException(e);
}
}
}, executor)
.thenCompose(ignored -> taskSupplier.get())
.whenCompleteAsync((ignored, throwable) -> lockItems.forEach(lockItem -> lockClient.releaseLock(ReleaseLockOptions.builder(lockItem)
.withBestEffort(true)
.build())), executor);
}
}
@@ -4,13 +4,12 @@
*/
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;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Throwables;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;
import java.io.IOException;
@@ -30,7 +29,6 @@ import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.function.Predicate;
import java.util.stream.Collectors;
@@ -70,6 +68,7 @@ import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledExcepti
import software.amazon.awssdk.services.dynamodb.model.TransactionConflictException;
import software.amazon.awssdk.services.dynamodb.model.Update;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;
import software.amazon.awssdk.services.dynamodb.paginators.ScanPublisher;
import software.amazon.awssdk.utils.CompletableFutureUtils;
@@ -376,7 +375,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 +494,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 +515,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 +547,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 +597,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 +716,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 +864,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);
}
}
/**
@@ -996,89 +989,61 @@ public class Accounts {
}
}
@Nonnull
public CompletionStage<Void> updateAsync(final Account account) {
return AsyncTimerUtil.record(UPDATE_TIMER, () -> {
final UpdateItemRequest updateItemRequest = UpdateAccountSpec
.forAccount(accountsTableName, account)
.updateItemRequest();
public void update(final Account account) throws ContestedOptimisticLockException {
final Timer.Sample sample = Timer.start();
return dynamoDbAsyncClient.updateItem(updateItemRequest)
.thenApply(response -> {
account.setVersion(AttributeValues.getInt(response.attributes(), "V", account.getVersion() + 1));
return (Void) null;
})
.exceptionallyCompose(throwable -> {
final Throwable unwrapped = ExceptionUtils.unwrap(throwable);
if (unwrapped instanceof TransactionConflictException) {
throw new ContestedOptimisticLockException();
} else if (unwrapped instanceof ConditionalCheckFailedException e) {
// the exception doesn't give details about which condition failed,
// but we can infer it was an optimistic locking failure if the UUID is known
return getByAccountIdentifierAsync(account.getUuid())
.thenAccept(refreshedAccount -> {
throw refreshedAccount.isPresent() ? new ContestedOptimisticLockException() : e;
});
} else {
// rethrow
throw CompletableFutureUtils.errorAsCompletionException(throwable);
}
});
});
}
private static void joinAndUnwrapUpdateFuture(CompletionStage<Void> future) {
try {
future.toCompletableFuture().join();
} catch (final CompletionException e) {
// unwrap CompletionExceptions, throw as long is it's unchecked
Throwables.throwIfUnchecked(ExceptionUtils.unwrap(e));
final UpdateItemResponse response = dynamoDbClient.updateItem(UpdateAccountSpec
.forAccount(accountsTableName, account)
.updateItemRequest());
// if we otherwise somehow got a wrapped checked exception,
// rethrow the checked exception wrapped by the original CompletionException
log.error("Unexpected checked exception thrown from dynamo update", e);
throw e;
account.setVersion(AttributeValues.getInt(response.attributes(), "V", account.getVersion() + 1));
} catch (final TransactionConflictException _) {
throw new ContestedOptimisticLockException();
} catch (final ConditionalCheckFailedException e) {
// the exception doesn't give details about which condition failed,
// but we can infer it was an optimistic locking failure if the UUID is known
if (getByAccountIdentifier(account.getUuid()).isPresent()) {
throw new ContestedOptimisticLockException();
} else {
throw e;
}
} finally {
sample.stop(UPDATE_TIMER);
}
}
public void update(final Account account) throws ContestedOptimisticLockException {
joinAndUnwrapUpdateFuture(updateAsync(account));
}
public void updateTransactionally(final Account account, final Collection<TransactWriteItem> additionalWriteItems)
throws ContestedOptimisticLockException {
public CompletionStage<Void> updateTransactionallyAsync(final Account account,
final Collection<TransactWriteItem> additionalWriteItems) {
final Timer.Sample sample = Timer.start();
return AsyncTimerUtil.record(UPDATE_TRANSACTIONALLY_TIMER, () -> {
try {
final List<TransactWriteItem> writeItems = new ArrayList<>(additionalWriteItems.size() + 1);
writeItems.add(UpdateAccountSpec.forAccount(accountsTableName, account).transactItem());
writeItems.addAll(additionalWriteItems);
return dynamoDbAsyncClient.transactWriteItems(TransactWriteItemsRequest.builder()
.transactItems(writeItems)
.build())
.thenApply(response -> {
account.setVersion(account.getVersion() + 1);
return (Void) null;
})
.exceptionally(throwable -> {
final Throwable unwrapped = ExceptionUtils.unwrap(throwable);
dynamoDbClient.transactWriteItems(TransactWriteItemsRequest.builder()
.transactItems(writeItems)
.build());
if (unwrapped instanceof TransactionCanceledException transactionCanceledException) {
if (CONDITIONAL_CHECK_FAILED.equals(transactionCanceledException.cancellationReasons().getFirst().code())) {
throw new ContestedOptimisticLockException();
}
account.setVersion(account.getVersion() + 1);
} catch (final TransactionCanceledException transactionCanceledException) {
if (CONDITIONAL_CHECK_FAILED.equals(transactionCanceledException.cancellationReasons().getFirst().code())) {
throw new ContestedOptimisticLockException();
}
if (transactionCanceledException.cancellationReasons()
.stream()
.anyMatch(reason -> TRANSACTION_CONFLICT.equals(reason.code()))) {
if (transactionCanceledException.cancellationReasons()
.stream()
.anyMatch(reason -> TRANSACTION_CONFLICT.equals(reason.code()))) {
throw new ContestedOptimisticLockException();
}
}
throw new ContestedOptimisticLockException();
}
throw CompletableFutureUtils.errorAsCompletionException(throwable);
});
});
throw transactionCanceledException;
} finally {
sample.stop(UPDATE_TRANSACTIONALLY_TIMER);
}
}
public TransactWriteItem buildTransactWriteItemForLinkDevice(final String linkDeviceToken, final Duration tokenTtl) {
@@ -1142,7 +1107,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
@@ -1211,30 +1176,39 @@ public class Accounts {
.map(UUID::fromString);
}
public CompletableFuture<Void> delete(final UUID uuid, final List<TransactWriteItem> additionalWriteItems) {
public void delete(final UUID uuid, final List<TransactWriteItem> additionalWriteItems) {
final Timer.Sample sample = Timer.start();
return getByAccountIdentifierAsync(uuid)
.thenCompose(maybeAccount -> maybeAccount.map(account -> {
final List<TransactWriteItem> transactWriteItems = new ArrayList<>(List.of(
buildDelete(phoneNumberConstraintTableName, ATTR_ACCOUNT_E164, account.getNumber()),
buildDelete(accountsTableName, KEY_ACCOUNT_UUID, uuid),
buildDelete(phoneNumberIdentifierConstraintTableName, ATTR_PNI_UUID, account.getPhoneNumberIdentifier()),
buildPutDeletedAccount(uuid, account.getPhoneNumberIdentifier())
));
try {
final Account account;
{
final Optional<Account> maybeAccount = getByAccountIdentifier(uuid);
account.getUsernameHash().ifPresent(usernameHash -> transactWriteItems.add(
buildDelete(usernamesConstraintTableName, UsernameTable.KEY_USERNAME_HASH, usernameHash)));
if (maybeAccount.isEmpty()) {
return;
}
transactWriteItems.addAll(additionalWriteItems);
account = maybeAccount.get();
}
return dynamoDbAsyncClient.transactWriteItems(TransactWriteItemsRequest.builder()
.transactItems(transactWriteItems)
.build())
.thenRun(Util.NOOP);
})
.orElseGet(() -> CompletableFuture.completedFuture(null)))
.thenRun(() -> sample.stop(DELETE_TIMER));
final List<TransactWriteItem> transactWriteItems = new ArrayList<>(List.of(
buildDelete(phoneNumberConstraintTableName, ATTR_ACCOUNT_E164, account.getNumber()),
buildDelete(accountsTableName, KEY_ACCOUNT_UUID, uuid),
buildDelete(phoneNumberIdentifierConstraintTableName, ATTR_PNI_UUID, account.getPhoneNumberIdentifier()),
buildPutDeletedAccount(uuid, account.getPhoneNumberIdentifier())
));
account.getUsernameHash().ifPresent(usernameHash -> transactWriteItems.add(
buildDelete(usernamesConstraintTableName, UsernameTable.KEY_USERNAME_HASH, usernameHash)));
transactWriteItems.addAll(additionalWriteItems);
dynamoDbClient.transactWriteItems(TransactWriteItemsRequest.builder()
.transactItems(transactWriteItems)
.build());
} finally {
sample.stop(DELETE_TIMER);
}
}
Flux<Account> getAll(final int segments, final Scheduler scheduler) {
@@ -1284,7 +1258,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
@@ -1294,7 +1268,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
@@ -1607,7 +1581,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;
@@ -45,7 +45,6 @@ import java.util.Queue;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
@@ -66,7 +65,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 +86,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;
@@ -134,12 +133,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;
@@ -218,12 +215,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 +231,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);
@@ -305,13 +298,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
try {
return accountLockManager.withLock(Set.of(pni),
() -> create(number, pni, accountAttributes, accountBadges, aciIdentityKey, pniIdentityKey, primaryDeviceSpec, userAgent), accountLockExecutor);
} catch (final Exception e) {
if (e instanceof RuntimeException runtimeException) {
throw runtimeException;
}
} catch (final RuntimeException e) {
logger.error("Unexpected exception while creating account", e);
throw new RuntimeException(e);
throw e;
}
});
}
@@ -446,88 +435,86 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
return account;
}
public CompletableFuture<Pair<Account, Device>> addDevice(final Account account, final DeviceSpec deviceSpec, final String linkDeviceToken) {
return accountLockManager.withLockAsync(Set.of(account.getPhoneNumberIdentifier()),
public Pair<Account, Device> addDevice(final Account account, final DeviceSpec deviceSpec, final String linkDeviceToken)
throws LinkDeviceTokenAlreadyUsedException {
return accountLockManager.withLock(Set.of(account.getPhoneNumberIdentifier()),
() -> addDevice(account.getIdentifier(IdentityType.ACI), deviceSpec, linkDeviceToken, MAX_UPDATE_ATTEMPTS),
accountLockExecutor);
}
private CompletableFuture<Pair<Account, Device>> addDevice(final UUID accountIdentifier, final DeviceSpec deviceSpec, final String linkDeviceToken, final int retries) {
return accounts.getByAccountIdentifierAsync(accountIdentifier)
.thenApply(maybeAccount -> maybeAccount.orElseThrow(ContestedOptimisticLockException::new))
.thenCompose(account -> {
final byte nextDeviceId = account.getNextDeviceId();
private Pair<Account, Device> addDevice(final UUID accountIdentifier, final DeviceSpec deviceSpec, final String linkDeviceToken, final int retries)
throws LinkDeviceTokenAlreadyUsedException {
final Account account = accounts.getByAccountIdentifier(accountIdentifier)
.orElseThrow(ContestedOptimisticLockException::new);
return CompletableFuture.allOf(
keysManager.deleteSingleUsePreKeys(account.getUuid(), nextDeviceId),
keysManager.deleteSingleUsePreKeys(account.getPhoneNumberIdentifier(), nextDeviceId),
messagesManager.clear(account.getUuid(), nextDeviceId))
.thenApply(ignored -> new Pair<>(account, nextDeviceId));
})
.thenCompose(accountAndNextDeviceId -> {
final Account account = accountAndNextDeviceId.first();
final byte nextDeviceId = accountAndNextDeviceId.second();
final byte nextDeviceId = account.getNextDeviceId();
account.addDevice(deviceSpec.toDevice(nextDeviceId, clock, account.getIdentityKey(IdentityType.ACI)));
CompletableFuture.allOf(
keysManager.deleteSingleUsePreKeys(account.getUuid(), nextDeviceId),
keysManager.deleteSingleUsePreKeys(account.getPhoneNumberIdentifier(), nextDeviceId),
messagesManager.clear(account.getUuid(), nextDeviceId))
.join();
final List<TransactWriteItem> additionalWriteItems = new ArrayList<>(keysManager.buildWriteItemsForNewDevice(
account.getIdentifier(IdentityType.ACI),
account.getIdentifier(IdentityType.PNI),
nextDeviceId,
deviceSpec.aciSignedPreKey(),
deviceSpec.pniSignedPreKey(),
deviceSpec.aciPqLastResortPreKey(),
deviceSpec.pniPqLastResortPreKey()));
account.addDevice(deviceSpec.toDevice(nextDeviceId, clock, account.getIdentityKey(IdentityType.ACI)));
additionalWriteItems.add(accounts.buildTransactWriteItemForLinkDevice(linkDeviceToken, LINK_DEVICE_TOKEN_EXPIRATION_DURATION));
final List<TransactWriteItem> additionalWriteItems = new ArrayList<>(keysManager.buildWriteItemsForNewDevice(
account.getIdentifier(IdentityType.ACI),
account.getIdentifier(IdentityType.PNI),
nextDeviceId,
deviceSpec.aciSignedPreKey(),
deviceSpec.pniSignedPreKey(),
deviceSpec.aciPqLastResortPreKey(),
deviceSpec.pniPqLastResortPreKey()));
return accounts.updateTransactionallyAsync(account, additionalWriteItems)
.thenApply(ignored -> new Pair<>(account, account.getDevice(nextDeviceId).orElseThrow()));
})
.thenCompose(updatedAccountAndDevice -> redisDeleteAsync(updatedAccountAndDevice.first())
.thenApply(ignored -> updatedAccountAndDevice))
.exceptionallyCompose(throwable -> {
if (ExceptionUtils.unwrap(throwable) instanceof ContestedOptimisticLockException && retries > 0) {
return addDevice(accountIdentifier, deviceSpec, linkDeviceToken, retries - 1);
} else if (ExceptionUtils.unwrap(throwable) instanceof TransactionCanceledException transactionCanceledException) {
// We can be confident the transaction was canceled because the linked device token was already used if the
// "check token" transaction write item is the only one that failed. That SHOULD be the last one in the
// list.
final long cancelledTransactions = transactionCanceledException.cancellationReasons().stream()
.filter(cancellationReason -> !"None".equals(cancellationReason.code()))
.count();
additionalWriteItems.add(accounts.buildTransactWriteItemForLinkDevice(linkDeviceToken, LINK_DEVICE_TOKEN_EXPIRATION_DURATION));
final boolean tokenReuseConditionFailed =
"ConditionalCheckFailed".equals(transactionCanceledException.cancellationReasons().getLast().code());
try {
accounts.updateTransactionally(account, additionalWriteItems);
redisDelete(account);
if (cancelledTransactions == 1 && tokenReuseConditionFailed) {
return CompletableFuture.failedFuture(new LinkDeviceTokenAlreadyUsedException());
final String key = getLinkedDeviceKey(getLinkDeviceTokenIdentifier(linkDeviceToken));
final String deviceInfoJson;
try {
deviceInfoJson = SystemMapper.jsonMapper().writeValueAsString(DeviceInfo.forDevice(account.getDevice(nextDeviceId).orElseThrow()));
} catch (final JsonProcessingException e) {
throw new UncheckedIOException(e);
}
ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
.executeCompletionStage(retryExecutor, () -> pubSubRedisClient.withConnection(connection ->
connection.async().set(key, deviceInfoJson, SetArgs.Builder.ex(RECENTLY_ADDED_DEVICE_TTL))))
.whenComplete((_, pubSubThrowable) -> {
if (pubSubThrowable != null) {
logger.warn("Failed to record recently-created device", pubSubThrowable);
}
}
});
return CompletableFuture.failedFuture(throwable);
})
.whenComplete((updatedAccountAndDevice, _) -> {
if (updatedAccountAndDevice != null) {
final String key = getLinkedDeviceKey(getLinkDeviceTokenIdentifier(linkDeviceToken));
final String deviceInfoJson;
return new Pair<>(account, account.getDevice(nextDeviceId).orElseThrow());
} catch (final ContestedOptimisticLockException e) {
if (retries > 0) {
return addDevice(accountIdentifier, deviceSpec, linkDeviceToken, retries - 1);
}
try {
deviceInfoJson = SystemMapper.jsonMapper().writeValueAsString(DeviceInfo.forDevice(updatedAccountAndDevice.second()));
} catch (final JsonProcessingException e) {
throw new UncheckedIOException(e);
}
throw e;
} catch (final TransactionCanceledException transactionCanceledException) {
// We can be confident the transaction was canceled because the linked device token was already used if the
// "check token" transaction write item is the only one that failed. That SHOULD be the last one in the
// list.
final long cancelledTransactions = transactionCanceledException.cancellationReasons().stream()
.filter(cancellationReason -> !"None".equals(cancellationReason.code()))
.count();
ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
.executeCompletionStage(retryExecutor, () -> pubSubRedisClient.withConnection(connection ->
connection.async().set(key, deviceInfoJson, SetArgs.Builder.ex(RECENTLY_ADDED_DEVICE_TTL))))
.whenComplete((_, pubSubThrowable) -> {
if (pubSubThrowable != null) {
logger.warn("Failed to record recently-created device", pubSubThrowable);
}
});
}
});
final boolean tokenReuseConditionFailed =
"ConditionalCheckFailed".equals(transactionCanceledException.cancellationReasons().getLast().code());
if (cancelledTransactions == 1 && tokenReuseConditionFailed) {
throw new LinkDeviceTokenAlreadyUsedException();
}
throw transactionCanceledException;
}
}
private Mac getInitializedMac() {
@@ -637,55 +624,54 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
*
* @return the updated Account
*/
public CompletableFuture<Account> removeDevice(final Account account, final byte deviceId) {
public Account removeDevice(final Account account, final byte deviceId) {
if (deviceId == Device.PRIMARY_ID) {
throw new IllegalArgumentException("Cannot remove primary device");
}
return accountLockManager.withLockAsync(Set.of(account.getPhoneNumberIdentifier()),
return accountLockManager.withLock(Set.of(account.getPhoneNumberIdentifier()),
() -> removeDevice(account.getIdentifier(IdentityType.ACI), deviceId, MAX_UPDATE_ATTEMPTS),
accountLockExecutor);
}
private CompletableFuture<Account> removeDevice(final UUID accountIdentifier, final byte deviceId, final int retries) {
return accounts.getByAccountIdentifierAsync(accountIdentifier)
.thenApply(maybeAccount -> maybeAccount.orElseThrow(ContestedOptimisticLockException::new))
.thenCompose(account -> CompletableFuture.allOf(
private Account removeDevice(final UUID accountIdentifier, final byte deviceId, final int retries) {
final Account account = accounts.getByAccountIdentifier(accountIdentifier)
.orElseThrow(ContestedOptimisticLockException::new);
CompletableFuture.allOf(
keysManager.deleteSingleUsePreKeys(account.getUuid(), deviceId),
messagesManager.clear(account.getUuid(), deviceId))
.thenApply(ignored -> account))
.thenCompose(account -> {
account.removeDevice(deviceId);
.join();
final List<TransactWriteItem> additionalWriteItems = new ArrayList<>(
keysManager.buildWriteItemsForRemovedDevice(
account.getIdentifier(IdentityType.ACI),
account.getIdentifier(IdentityType.PNI),
deviceId));
account.removeDevice(deviceId);
additionalWriteItems.add(clientPublicKeysManager.buildTransactWriteItemForDeletion(account.getIdentifier(IdentityType.ACI), deviceId));
final List<TransactWriteItem> additionalWriteItems = new ArrayList<>(
keysManager.buildWriteItemsForRemovedDevice(
account.getIdentifier(IdentityType.ACI),
account.getIdentifier(IdentityType.PNI),
deviceId));
return accounts.updateTransactionallyAsync(account, additionalWriteItems)
.thenApply(ignored -> account);
})
.thenCompose(updatedAccount -> redisDeleteAsync(updatedAccount).thenApply(ignored -> updatedAccount))
// Ensure any messages/single-use pre-keys that came in while we were working are also removed
.thenCompose(account -> CompletableFuture.allOf(
keysManager.deleteSingleUsePreKeys(account.getUuid(), deviceId),
messagesManager.clear(account.getUuid(), deviceId))
.thenApply(ignored -> account))
.exceptionallyCompose(throwable -> {
if (ExceptionUtils.unwrap(throwable) instanceof ContestedOptimisticLockException && retries > 0) {
return removeDevice(accountIdentifier, deviceId, retries - 1);
}
try {
accounts.updateTransactionally(account, additionalWriteItems);
return CompletableFuture.failedFuture(throwable);
})
.whenComplete((ignored, throwable) -> {
if (throwable == null) {
disconnectionRequestManager.requestDisconnection(accountIdentifier, List.of(deviceId));
}
});
redisDelete(account);
// Ensure any messages/single-use pre-keys that came in while we were working are also removed
CompletableFuture.allOf(
keysManager.deleteSingleUsePreKeys(account.getUuid(), deviceId),
messagesManager.clear(account.getUuid(), deviceId))
.join();
disconnectionRequestManager.requestDisconnection(accountIdentifier, List.of(deviceId));
return account;
} catch (final ContestedOptimisticLockException e) {
if (retries > 0) {
return removeDevice(accountIdentifier, deviceId, retries - 1);
}
throw e;
}
}
public Account changeNumber(final Account account,
@@ -700,15 +686,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
try {
return accountLockManager.withLock(new HashSet<>(List.of(account.getPhoneNumberIdentifier(), targetPhoneNumberIdentifier)),
() -> changeNumber(account, targetNumber, targetPhoneNumberIdentifier, pniIdentityKey, pniSignedPreKeys, pniPqLastResortPreKeys, pniRegistrationIds), accountLockExecutor);
} catch (final Exception e) {
if (e instanceof MismatchedDevicesException mismatchedDevicesException) {
throw mismatchedDevicesException;
} if (e instanceof RuntimeException runtimeException) {
throw runtimeException;
}
} catch (final RuntimeException e) {
logger.error("Unexpected exception when changing phone number", e);
throw new RuntimeException(e);
throw e;
}
}
@@ -747,7 +727,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
if (maybeExistingAccount.get().getIdentifier(IdentityType.ACI).equals(account.getIdentifier(IdentityType.ACI))) {
maybeDisplacedUuid = Optional.empty();
} else {
delete(maybeExistingAccount.get()).join();
delete(maybeExistingAccount.get());
maybeDisplacedUuid = maybeExistingAccount.map(Account::getUuid);
}
} else {
@@ -835,119 +815,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) {
@@ -958,14 +935,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
});
}
public CompletableFuture<Account> updateAsync(Account account, Consumer<Account> updater) {
return updateAsync(account, a -> {
updater.accept(a);
// assume that all updaters passed to the public method actually modify the account
return true;
});
}
/**
* Specialized version of {@link #updateDevice(Account, byte, Consumer)} that minimizes potentially contentious and
* redundant updates of {@code device.lastSeen}
@@ -1017,30 +986,11 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
});
}
private CompletableFuture<Account> updateAsync(final Account account, final Function<Account, Boolean> updater) {
final Timer.Sample timerSample = Timer.start();
return redisDeleteAsync(account)
.thenCompose(ignored -> {
final UUID uuid = account.getUuid();
return updateWithRetriesAsync(account,
updater,
a -> accounts.updateAsync(a).toCompletableFuture(),
() -> accounts.getByAccountIdentifierAsync(uuid).thenApply(Optional::orElseThrow),
AccountChangeValidator.GENERAL_CHANGE_VALIDATOR,
MAX_UPDATE_ATTEMPTS);
})
.thenCompose(updatedAccount -> redisSetAsync(updatedAccount).thenApply(ignored -> updatedAccount))
.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);
@@ -1077,42 +1027,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
throw new OptimisticLockRetryLimitExceededException();
}
private CompletionStage<Account> updateWithRetriesAsync(Account account,
final Function<Account, Boolean> updater,
final Function<Account, CompletionStage<Void>> persister,
final Supplier<CompletionStage<Account>> retriever,
final AccountChangeValidator changeValidator,
final int remainingTries) {
final Account originalAccount = AccountUtil.cloneAccountAsNotStale(account);
if (!updater.apply(account)) {
return CompletableFuture.completedFuture(account);
}
if (remainingTries > 0) {
return persister.apply(account)
.thenApply(ignored -> {
final Account updatedAccount = AccountUtil.cloneAccountAsNotStale(account);
account.markStale();
changeValidator.validateChange(originalAccount, updatedAccount);
return updatedAccount;
})
.exceptionallyCompose(throwable -> {
if (ExceptionUtils.unwrap(throwable) instanceof ContestedOptimisticLockException) {
return retriever.get().thenCompose(refreshedAccount ->
updateWithRetriesAsync(refreshedAccount, updater, persister, retriever, changeValidator, remainingTries - 1));
} else {
throw ExceptionUtils.wrap(throwable);
}
});
}
return CompletableFuture.failedFuture(new OptimisticLockRetryLimitExceededException());
}
public Account updateDevice(Account account, byte deviceId, Consumer<Device> deviceUpdater) {
return update(account, a -> {
a.getDevice(deviceId).ifPresent(deviceUpdater);
@@ -1121,25 +1035,10 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
});
}
public CompletableFuture<Account> updateDeviceAsync(final Account account, final byte deviceId,
final Consumer<Device> deviceUpdater) {
return updateAsync(account, a -> {
a.getDevice(deviceId).ifPresent(deviceUpdater);
// assume that all updaters passed to the public method actually modify the device
return true;
});
}
public Optional<Account> getByE164(final String number) {
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,
@@ -1214,43 +1113,37 @@ 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) {
public void delete(final Account account, final DeletionReason deletionReason) {
final Timer.Sample sample = Timer.start();
return accountLockManager.withLockAsync(Set.of(account.getPhoneNumberIdentifier()), () -> delete(account),
accountLockExecutor)
.whenComplete((ignored, throwable) -> {
sample.stop(deleteTimer);
try {
accountLockManager.withLock(Set.of(account.getPhoneNumberIdentifier()), () -> {
delete(account);
return null;
}, accountLockExecutor);
if (throwable == null) {
Metrics.counter(DELETE_COUNTER_NAME,
COUNTRY_CODE_TAG_NAME, Util.getCountryCode(account.getNumber()),
DELETION_REASON_TAG_NAME, deletionReason.tagValue)
.increment();
} else {
logger.warn("Failed to delete account", throwable);
}
});
Metrics.counter(DELETE_COUNTER_NAME,
COUNTRY_CODE_TAG_NAME, Util.getCountryCode(account.getNumber()),
DELETION_REASON_TAG_NAME, deletionReason.tagValue)
.increment();
} catch (final RuntimeException e) {
logger.warn("Failed to delete account", e);
throw e;
} finally {
sample.stop(deleteTimer);
}
}
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(
account.getIdentifier(IdentityType.ACI),
device.getId())))
private void delete(final Account account) {
final List<TransactWriteItem> additionalWriteItems = account.getDevices().stream()
.flatMap(device -> keysManager.buildWriteItemsForRemovedDevice(
account.getIdentifier(IdentityType.ACI),
account.getIdentifier(IdentityType.PNI),
device.getId())
.stream())
.toList();
return CompletableFuture.allOf(
CompletableFuture.allOf(
secureStorageClient.deleteStoredData(account.getUuid()),
secureValueRecovery2Client.removeData(account.getUuid()),
keysManager.deleteSingleUsePreKeys(account.getUuid()),
@@ -1258,9 +1151,12 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
messagesManager.clear(account.getUuid()),
profilesManager.deleteAll(account.getUuid(), true),
registrationRecoveryPasswordsManager.remove(account.getIdentifier(IdentityType.PNI)))
.thenCompose(ignored -> accounts.delete(account.getUuid(), additionalWriteItems))
.thenCompose(ignored -> redisDeleteAsync(account))
.thenRun(() -> disconnectionRequestManager.requestDisconnection(account));
.join();
accounts.delete(account.getUuid(), additionalWriteItems);
redisDelete(account);
disconnectionRequestManager.requestDisconnection(account);
}
private String getAccountMapKey(String key) {
@@ -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);
}
}
@@ -5,13 +5,16 @@
package org.whispersystems.textsecuregcm.storage;
import java.util.Arrays;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
public enum DeviceCapability {
STORAGE("storage", AccountCapabilityMode.ANY_DEVICE, false, false),
TRANSFER("transfer", AccountCapabilityMode.PRIMARY_DEVICE, false, false),
ATTACHMENT_BACKFILL("attachmentBackfill", AccountCapabilityMode.PRIMARY_DEVICE, false, true),
SPARSE_POST_QUANTUM_RATCHET("spqr", AccountCapabilityMode.ALL_DEVICES, false, true);
STORAGE("storage", AccountCapabilityMode.ANY_DEVICE, false, false, false),
TRANSFER("transfer", AccountCapabilityMode.PRIMARY_DEVICE, false, false, false),
ATTACHMENT_BACKFILL("attachmentBackfill", AccountCapabilityMode.PRIMARY_DEVICE, false, true, false),
SPARSE_POST_QUANTUM_RATCHET("spqr", AccountCapabilityMode.ALL_DEVICES, true, true, true);
public enum AccountCapabilityMode {
/**
@@ -33,32 +36,42 @@ public enum DeviceCapability {
ALWAYS_CAPABLE,
}
public static final Set<DeviceCapability> CAPABILITIES_REQUIRED_FOR_REGISTRATION =
Arrays.stream(DeviceCapability.values())
.filter(DeviceCapability::requireForRegistration)
.collect(Collectors.toSet());
private final String name;
private final AccountCapabilityMode accountCapabilityMode;
private final boolean preventDowngrade;
private final boolean includeInProfile;
private final boolean requireForRegistration;
/**
* Create a DeviceCapability
*
* @param name The name of the device capability that clients will see
* @param accountCapabilityMode How to combine the constituent device's capabilities in the account to an overall
* account capability
* @param preventDowngrade If true, don't let linked devices join that don't have a device capability if the
* overall account has the capability. Most of the time this should only be used in
* conjunction with AccountCapabilityMode.ALL_DEVICES
* @param includeInProfile Whether to return this capability on the account's profile. If false, the capability
* is only visible to the server
* @param name The name of the device capability that clients will see
* @param accountCapabilityMode How to combine the constituent device's capabilities in the account to an overall
* account capability
* @param preventDowngrade If true, don't let linked devices join that don't have a device capability if the
* overall account has the capability. Most of the time this should only be used in
* conjunction with AccountCapabilityMode.ALL_DEVICES.
* @param includeInProfile Whether to return this capability on the account's profile. If false, the capability
* is only visible to the server.
* @param requireForRegistration If true, prevent account creation if the account's initial device does not have this
* capability
*/
DeviceCapability(final String name,
final AccountCapabilityMode accountCapabilityMode,
final boolean preventDowngrade,
final boolean includeInProfile) {
final boolean includeInProfile,
final boolean requireForRegistration) {
this.name = name;
this.accountCapabilityMode = accountCapabilityMode;
this.preventDowngrade = preventDowngrade;
this.includeInProfile = includeInProfile;
this.requireForRegistration = requireForRegistration;
}
public String getName() {
@@ -77,6 +90,10 @@ public enum DeviceCapability {
return includeInProfile;
}
public boolean requireForRegistration() {
return requireForRegistration;
}
public static Optional<DeviceCapability> forName(final String name) {
for (final DeviceCapability capability : DeviceCapability.values()) {
if (capability.getName().equals(name)) {
@@ -0,0 +1,29 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
public class KeyIdUtil {
public static final long MAX_KEY_ID = (1L << 32) - 1;
public static final long MIN_KEY_ID = 0;
private KeyIdUtil(){}
public static boolean keyIdValid(final long keyId) {
return keyId <= MAX_KEY_ID && keyId >= MIN_KEY_ID;
}
/// Convert a long keyId (a 32-bit unsigned int) into an int representation.
///
/// The inverse of [Integer#toUnsignedLong].
///
/// @param keyId A key ID which must be in the range [0, 2^32)
/// @throws IllegalArgumentException If `keyId` is not within the range
/// @return A 32-bit unsigned integer where the top bit is stored in the sign bit
public static int toUnsignedInt(final long keyId) {
if (!keyIdValid(keyId)) {
throw new IllegalArgumentException("Invalid keyId " + keyId);
}
return (int) keyId;
}
}
@@ -9,20 +9,22 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.lifecycle.Managed;
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.LongTaskTimer;
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.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.IntStream;
import javax.annotation.Nullable;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -33,7 +35,10 @@ import org.whispersystems.textsecuregcm.metrics.DevicePlatformUtil;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
import reactor.util.function.Tuples;
import reactor.util.retry.Retry;
import reactor.util.retry.RetryBackoffSpec;
import software.amazon.awssdk.services.dynamodb.model.ItemCollectionSizeLimitExceededException;
public class MessagePersister implements Managed {
@@ -42,153 +47,228 @@ public class MessagePersister implements Managed {
private final MessagesManager messagesManager;
private final AccountsManager accountsManager;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private final Scheduler persistQueueScheduler;
private final Clock clock;
private final Duration persistDelay;
private final int maxConcurrency;
private final int scanCount;
private final RetryBackoffSpec retryBackoffSpec;
private final String persisterId = UUID.randomUUID().toString();
private final Thread[] workerThreads;
private volatile boolean running;
@Nullable
private Thread workerThread;
private static final String INSPECTED_QUEUE_COUNTER_NAME = name(MessagePersister.class, "inspectedQueue");
private static final String OVERSIZED_QUEUE_COUNTER_NAME = name(MessagePersister.class, "persistQueueOversized");
private static final String PERSISTED_MESSAGE_COUNTER_NAME = name(MessagePersister.class, "persistMessage");
private static final String PERSISTED_BYTES_COUNTER_NAME = name(MessagePersister.class, "persistBytes");
private static final Timer GET_QUEUES_TIMER = Metrics.timer(name(MessagePersister.class, "getQueues"));
private static final Timer PERSIST_QUEUE_TIMER = Metrics.timer(name(MessagePersister.class, "persistQueue"));
private static final Counter PERSIST_QUEUE_EXCEPTION_METER =
Metrics.counter(name(MessagePersister.class, "persistQueueException"));
private static final Counter TRIMMED_MESSAGE_COUNTER = Metrics.counter(name(MessagePersister.class, "trimmedMessage"));
private static final Counter TRIMMED_MESSAGE_BYTES_COUNTER = Metrics.counter(name(MessagePersister.class, "trimmedMessageBytes"));
private static final Counter PERSIST_NODE_COUNTER = Metrics.counter(name(MessagePersister.class, "persistNodeCount"));
private static final LongTaskTimer PERSIST_NODE_TIMER = Metrics.more().longTaskTimer(name(MessagePersister.class, "persistNode"));
private static final String QUEUE_SIZE_DISTRIBUTION_SUMMARY_NAME = name(MessagePersister.class, "queueSize");
static final int QUEUE_BATCH_LIMIT = 100;
static final int MESSAGE_BATCH_LIMIT = 100;
private static final DistributionSummary QUEUE_COUNT_DISTRIBUTION_SUMMARY = DistributionSummary.builder(
name(MessagePersister.class, "queueCount"))
.register(Metrics.globalRegistry);
private static final DistributionSummary QUEUE_COUNT_DISTRIBUTION_SUMMARY =
DistributionSummary.builder(name(MessagePersister.class, "queueCount"))
.register(Metrics.globalRegistry);
private static final long EXCEPTION_PAUSE_MILLIS = Duration.ofSeconds(3).toMillis();
private static final int CONSECUTIVE_EMPTY_CACHE_REMOVAL_LIMIT = 3;
private static final Logger logger = LoggerFactory.getLogger(MessagePersister.class);
public MessagePersister(final MessagesCache messagesCache,
final MessagesManager messagesManager,
final AccountsManager accountsManager,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final Scheduler persistQueueScheduler,
final Clock clock,
final Duration persistDelay,
final int dedicatedProcessWorkerThreadCount) {
final int maxConcurrency,
final int scanCount) {
this(messagesCache,
messagesManager,
accountsManager,
dynamicConfigurationManager,
persistQueueScheduler,
clock,
persistDelay,
maxConcurrency,
scanCount,
Retry.backoff(3, Duration.ofSeconds(1)));
}
@VisibleForTesting
MessagePersister(final MessagesCache messagesCache,
final MessagesManager messagesManager,
final AccountsManager accountsManager,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final Scheduler persistQueueScheduler,
final Clock clock,
final Duration persistDelay,
final int maxConcurrency,
final int scanCount,
final RetryBackoffSpec retryBackoffSpec) {
this.messagesCache = messagesCache;
this.messagesManager = messagesManager;
this.accountsManager = accountsManager;
this.dynamicConfigurationManager = dynamicConfigurationManager;
this.clock = clock;
this.persistDelay = persistDelay;
this.workerThreads = new Thread[dedicatedProcessWorkerThreadCount];
for (int i = 0; i < workerThreads.length; i++) {
workerThreads[i] = new Thread(() -> {
while (running) {
if (dynamicConfigurationManager.getConfiguration().getMessagePersisterConfiguration()
.isPersistenceEnabled()) {
try {
final int queuesPersisted = persistNextQueues(Instant.now());
QUEUE_COUNT_DISTRIBUTION_SUMMARY.record(queuesPersisted);
if (queuesPersisted == 0) {
Util.sleep(100);
}
} catch (final Throwable t) {
logger.warn("Failed to persist queues", t);
Util.sleep(EXCEPTION_PAUSE_MILLIS);
}
} else {
Util.sleep(1000);
}
}
}, "MessagePersisterWorker-" + i);
}
}
@VisibleForTesting
Duration getPersistDelay() {
return persistDelay;
this.maxConcurrency = maxConcurrency;
this.scanCount = scanCount;
this.retryBackoffSpec = retryBackoffSpec;
this.persistQueueScheduler = persistQueueScheduler;
}
@Override
public void start() {
public synchronized void start() {
running = true;
for (final Thread workerThread : workerThreads) {
workerThread.start();
}
workerThread = new Thread(() -> {
while (running) {
if (dynamicConfigurationManager.getConfiguration().getMessagePersisterConfiguration().isPersistenceEnabled()) {
try {
final int queuesPersisted = persistNextNode();
QUEUE_COUNT_DISTRIBUTION_SUMMARY.record(queuesPersisted);
if (queuesPersisted == 0) {
Util.sleep(100);
}
} catch (final Throwable t) {
logger.warn("Failed to persist queues", t);
Util.sleep(EXCEPTION_PAUSE_MILLIS);
}
}
try {
// Persisters work through nodes quickly, and running in a hot loop taxes Redis nodes unnecessarily
Thread.sleep(dynamicConfigurationManager.getConfiguration().getMessagePersisterConfiguration().getSleepBetweenNodes());
} catch (final InterruptedException _) {
}
}
}, "MessagePersister");
workerThread.start();
}
@Override
public void stop() {
public synchronized void stop() {
running = false;
for (final Thread workerThread : workerThreads) {
if (workerThread != null) {
try {
workerThread.join();
} catch (final InterruptedException e) {
logger.warn("Interrupted while waiting for worker thread to complete current operation");
}
workerThread = null;
}
}
@VisibleForTesting
int persistNextQueues(final Instant currentTime) {
final int slot = messagesCache.getNextSlotToPersist();
final String shard = messagesCache.shardForSlot(slot);
int persistNextNode() {
final RedisClusterNode node;
{
final Duration nodeClaimTtl =
dynamicConfigurationManager.getConfiguration().getMessagePersisterConfiguration().getNodeClaimTtl();
List<String> queuesToPersist;
int queuesPersisted = 0;
final Optional<RedisClusterNode> maybeNode = messagesCache.claimNextNodeToPersist(persisterId, nodeClaimTtl);
do {
queuesToPersist = GET_QUEUES_TIMER.record(
() -> messagesCache.getQueuesToPersist(slot, currentTime.minus(persistDelay), QUEUE_BATCH_LIMIT));
for (final String queue : queuesToPersist) {
final UUID accountUuid = MessagesCache.getAccountUuidFromQueueName(queue);
final byte deviceId = MessagesCache.getDeviceIdFromQueueName(queue);
final Optional<Account> maybeAccount = accountsManager.getByAccountIdentifier(accountUuid);
if (maybeAccount.isEmpty()) {
logger.error("No account record found for account {}", accountUuid);
continue;
}
final Optional<Device> maybeDevice = maybeAccount.flatMap(account -> account.getDevice(deviceId));
if (maybeDevice.isEmpty()) {
logger.error("Account {} does not have a device with id {}", accountUuid, deviceId);
continue;
}
try {
persistQueue(maybeAccount.get(), maybeDevice.get(), shard);
} catch (final Exception e) {
PERSIST_QUEUE_EXCEPTION_METER.increment();
logger.warn("Failed to persist queue {}::{} (slot {}, shard {}); will schedule for retry",
accountUuid, deviceId, slot, shard, e);
messagesCache.addQueueToPersist(accountUuid, deviceId);
if (!(e instanceof MessagePersistenceException)) {
// Pause after unexpected exceptions
Util.sleep(EXCEPTION_PAUSE_MILLIS);
}
}
if (maybeNode.isEmpty()) {
return 0;
}
queuesPersisted += queuesToPersist.size();
} while (queuesToPersist.size() >= QUEUE_BATCH_LIMIT);
node = maybeNode.get();
}
return queuesPersisted;
try {
return persistNode(node);
} finally {
messagesCache.releaseNodeClaim(node, persisterId);
}
}
int persistNode(final RedisClusterNode node) {
final LongTaskTimer.Sample sample = PERSIST_NODE_TIMER.start();
try {
final Tags tags = Tags.of("node", node.getUri().getHost());
return messagesCache.getQueues(node, scanCount)
.filter(_ -> dynamicConfigurationManager.getConfiguration().getMessagePersisterConfiguration()
.isPersistenceEnabled())
.flatMap(queueKey -> Mono.defer(() -> shouldPersistQueue(queueKey))
.retryWhen(retryBackoffSpec)
.onErrorResume(e -> {
logger.warn("Failed to determine whether queue {} should be persisted", queueKey, e);
return Mono.empty();
})
.mapNotNull(shouldPersist -> shouldPersist ? queueKey : null)
.doOnTerminate(() -> Metrics.counter(INSPECTED_QUEUE_COUNTER_NAME, tags).increment()), maxConcurrency)
.distinct()
.flatMap(queueKey -> {
final UUID accountIdentifier = MessagesCache.getAccountUuidFromQueueName(queueKey);
final byte deviceId = MessagesCache.getDeviceIdFromQueueName(queueKey);
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(accountIdentifier))
.map(maybeAccount -> maybeAccount
.flatMap(account -> account.getDevice(deviceId))
.map(device -> Tuples.of(maybeAccount.get(), device)))
.flatMap(Mono::justOrEmpty)
.retryWhen(retryBackoffSpec)
.onErrorResume(e -> {
logger.warn("Failed to fetch account/device for queue: {}", queueKey, e);
return Mono.empty();
});
}, maxConcurrency)
.flatMap(accountAndDevice -> {
final Account account = accountAndDevice.getT1();
final Device device = accountAndDevice.getT2();
return persistQueue(account, device, tags)
.thenReturn(1)
.retryWhen(retryBackoffSpec
// Don't retry with backoff for persistence exceptions
.filter(e -> !(e instanceof MessagePersistenceException)))
.onErrorResume(e -> {
logger.warn("Failed to persist queue {}::{} ({}); will schedule for retry",
account.getIdentifier(IdentityType.ACI), device.getId(), node.getUri().getHost(), e);
return Mono.empty();
});
}, maxConcurrency)
.onErrorResume(e -> {
logger.warn("Unhandled error while persisting messages", e);
return Mono.empty();
})
.count()
.blockOptional()
.map(Math::toIntExact)
.orElse(0);
} finally {
sample.stop();
PERSIST_NODE_COUNTER.increment();
}
}
@VisibleForTesting
void persistQueue(final Account account, final Device device, final String shard) throws MessagePersistenceException {
Mono<Void> persistQueue(final Account account, final Device device, final Tags baseTags) {
final UUID accountUuid = account.getUuid();
final byte deviceId = device.getId();
@@ -197,120 +277,128 @@ public class MessagePersister implements Managed {
.orElse("unknown"));
final Timer.Sample sample = Timer.start();
final Tags tags = baseTags.and(platformTag);
messagesCache.lockQueueForPersistence(accountUuid, deviceId);
return Flux.usingWhen(
messagesCache.lockQueueForPersistence(accountUuid, deviceId)
.thenReturn(true),
_ -> Flux.from(messagesCache.getMessagesToPersist(accountUuid, deviceId))
.buffer(MESSAGE_BATCH_LIMIT)
.flatMap(messages -> {
final int urgentMessageCount = (int) messages.stream().filter(MessageProtos.Envelope::getUrgent).count();
final int nonUrgentMessageCount = messages.size() - urgentMessageCount;
try {
int messageCount = 0;
List<MessageProtos.Envelope> messages;
Metrics.counter(PERSISTED_MESSAGE_COUNTER_NAME, tags.and("urgent", "true")).increment(urgentMessageCount);
Metrics.counter(PERSISTED_MESSAGE_COUNTER_NAME, tags.and("urgent", "false")).increment(nonUrgentMessageCount);
Metrics.counter(PERSISTED_BYTES_COUNTER_NAME, tags)
.increment(messages.stream().mapToInt(MessageProtos.Envelope::getSerializedSize).sum());
int consecutiveEmptyCacheRemovals = 0;
return Mono.fromRunnable(() -> messagesManager.persistMessages(accountUuid, device, messages))
.subscribeOn(persistQueueScheduler)
.thenReturn(messages.size());
}, 1)
.reduce(0, Integer::sum)
.onErrorResume(ItemCollectionSizeLimitExceededException.class, _ -> {
final boolean isPrimary = deviceId == Device.PRIMARY_ID;
Metrics.counter(OVERSIZED_QUEUE_COUNTER_NAME, "primary", String.valueOf(isPrimary)).increment();
// may throw, in which case we'll retry later by the usual mechanism
if (isPrimary) {
logger.warn("Failed to persist queue {}::{} due to overfull queue; will trim oldest messages",
account.getUuid(), deviceId);
do {
messages = messagesCache.getMessagesToPersist(accountUuid, deviceId, MESSAGE_BATCH_LIMIT);
return trimQueue(account, device)
.then(Mono.error(new MessagePersistenceException("Could not persist due to an overfull queue. Trimmed primary queue, a subsequent retry may succeed")));
} else {
logger.warn("Failed to persist queue {}::{} due to overfull queue; will unlink device", accountUuid, deviceId);
final int urgentMessageCount = (int) messages.stream().filter(MessageProtos.Envelope::getUrgent).count();
final int nonUrgentMessageCount = messages.size() - urgentMessageCount;
final Tags tags = Tags.of(platformTag, Tag.of("shard", shard));
Metrics.counter(PERSISTED_MESSAGE_COUNTER_NAME, tags.and("urgent", "true")).increment(urgentMessageCount);
Metrics.counter(PERSISTED_MESSAGE_COUNTER_NAME, tags.and("urgent", "false")).increment(nonUrgentMessageCount);
Metrics.counter(PERSISTED_BYTES_COUNTER_NAME, tags)
.increment(messages.stream().mapToInt(MessageProtos.Envelope::getSerializedSize).sum());
int messagesRemovedFromCache = messagesManager.persistMessages(accountUuid, device, messages);
messageCount += messages.size();
if (messagesRemovedFromCache == 0) {
consecutiveEmptyCacheRemovals += 1;
} else {
consecutiveEmptyCacheRemovals = 0;
}
if (consecutiveEmptyCacheRemovals > CONSECUTIVE_EMPTY_CACHE_REMOVAL_LIMIT) {
throw new MessagePersistenceException("persistence failure loop detected");
}
} while (!messages.isEmpty());
DistributionSummary.builder(QUEUE_SIZE_DISTRIBUTION_SUMMARY_NAME)
.tags(Tags.of(platformTag))
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry)
.record(messageCount);
} catch (ItemCollectionSizeLimitExceededException e) {
final boolean isPrimary = deviceId == Device.PRIMARY_ID;
Metrics.counter(OVERSIZED_QUEUE_COUNTER_NAME, "primary", String.valueOf(isPrimary)).increment();
// may throw, in which case we'll retry later by the usual mechanism
if (isPrimary) {
logger.warn("Failed to persist queue {}::{} due to overfull queue; will trim oldest messages",
account.getUuid(), deviceId);
trimQueue(account, deviceId);
throw new MessagePersistenceException("Could not persist due to an overfull queue. Trimmed primary queue, a subsequent retry may succeed");
} else {
logger.warn("Failed to persist queue {}::{} due to overfull queue; will unlink device", accountUuid, deviceId);
accountsManager.removeDevice(account, deviceId).join();
}
} finally {
messagesCache.unlockQueueForPersistence(accountUuid, deviceId);
sample.stop(PERSIST_QUEUE_TIMER);
}
return Mono.fromRunnable(() -> accountsManager.removeDevice(account, deviceId))
.subscribeOn(persistQueueScheduler)
.then(Mono.empty());
}
})
.doOnSuccess(messagesPersisted -> {
if (messagesPersisted != null) {
DistributionSummary.builder(QUEUE_SIZE_DISTRIBUTION_SUMMARY_NAME)
.tags(Tags.of(platformTag))
.register(Metrics.globalRegistry)
.record(messagesPersisted);
}
})
.doOnTerminate(() -> sample.stop(PERSIST_QUEUE_TIMER)),
_ -> messagesCache.unlockQueueForPersistence(accountUuid, deviceId))
.then();
}
private void trimQueue(final Account account, byte deviceId) {
private Mono<Void> trimQueue(final Account account, final Device device) {
final UUID aci = account.getIdentifier(IdentityType.ACI);
final byte deviceId = device.getId();
final Optional<Device> maybeDevice = account.getDevice(deviceId);
if (maybeDevice.isEmpty()) {
logger.warn("Not deleting messages for overfull queue {}::{}, deviceId {} does not exist",
aci, deviceId, deviceId);
return;
}
final Device device = maybeDevice.get();
// Calculate how many bytes we should trim
final long cachedMessageBytes = messagesCache.estimatePersistedQueueSizeBytes(aci, deviceId).join();
final double extraRoomRatio = this.dynamicConfigurationManager.getConfiguration()
.getMessagePersisterConfiguration()
.getTrimOversizedQueueExtraRoomRatio();
final long targetDeleteBytes = Math.round(cachedMessageBytes * extraRoomRatio);
final AtomicLong oldestMessage = new AtomicLong(0L);
final AtomicLong newestMessage = new AtomicLong(0L);
final AtomicLong bytesDeleted = new AtomicLong(0L);
// Iterate from the oldest message until we've removed targetDeleteBytes
final Pair<Long, Long> outcomes = Flux.from(messagesManager.getMessagesForDeviceReactive(aci, device, false))
.concatMap(envelope -> {
if (bytesDeleted.getAndAdd(envelope.getSerializedSize()) >= targetDeleteBytes) {
return Mono.just(Optional.<MessageProtos.Envelope>empty());
}
oldestMessage.compareAndSet(0L, envelope.getServerTimestamp());
newestMessage.set(envelope.getServerTimestamp());
return Mono.just(Optional.of(envelope));
})
.takeWhile(Optional::isPresent)
.flatMap(maybeEnvelope -> {
final MessageProtos.Envelope envelope = maybeEnvelope.get();
TRIMMED_MESSAGE_COUNTER.increment();
TRIMMED_MESSAGE_BYTES_COUNTER.increment(envelope.getSerializedSize());
return Mono
.fromCompletionStage(() -> messagesManager
.delete(aci, device, UUID.fromString(envelope.getServerGuid()), envelope.getServerTimestamp()))
.retryWhen(Retry.backoff(5, Duration.ofSeconds(1)))
.map(Optional::isPresent);
})
.reduce(Pair.of(0L, 0L), (acc, deleted) -> deleted
? Pair.of(acc.getLeft() + 1, acc.getRight())
: Pair.of(acc.getLeft(), acc.getRight() + 1))
.block();
final AtomicLong cachedMessageBytes = new AtomicLong(0L);
final AtomicLong targetDeleteBytes = new AtomicLong(0L);
logger.warn(
"Finished trimming {}:{}. Oldest message = {}, newest message = {}. Attempted to delete {} persisted bytes to make room for {} cached message bytes. Delete outcomes: {} present, {} missing.",
aci, deviceId,
Instant.ofEpochMilli(oldestMessage.get()), Instant.ofEpochMilli(newestMessage.get()),
targetDeleteBytes, cachedMessageBytes,
outcomes.getLeft(), outcomes.getRight());
return Mono.fromFuture(() -> messagesCache.estimatePersistedQueueSizeBytes(aci, deviceId))
.flatMap(estimatedPersistedQueueSize -> {
cachedMessageBytes.set(estimatedPersistedQueueSize);
targetDeleteBytes.set(Math.round(estimatedPersistedQueueSize * extraRoomRatio));
return Flux.from(messagesManager.getMessagesForDeviceReactive(aci, device, false))
.concatMap(envelope -> {
if (bytesDeleted.getAndAdd(envelope.getSerializedSize()) >= targetDeleteBytes.get()) {
return Mono.just(Optional.<MessageProtos.Envelope>empty());
}
oldestMessage.compareAndSet(0L, envelope.getServerTimestamp());
newestMessage.set(envelope.getServerTimestamp());
return Mono.just(Optional.of(envelope));
})
.takeWhile(Optional::isPresent)
.flatMap(maybeEnvelope -> {
// We know this must be present because we `takeWhile` values are present
final MessageProtos.Envelope envelope = maybeEnvelope.orElseThrow(AssertionError::new);
TRIMMED_MESSAGE_COUNTER.increment();
TRIMMED_MESSAGE_BYTES_COUNTER.increment(envelope.getSerializedSize());
return Mono
.fromCompletionStage(() -> messagesManager
.delete(aci, device, UUID.fromString(envelope.getServerGuid()), envelope.getServerTimestamp()))
.retryWhen(retryBackoffSpec)
.map(Optional::isPresent);
})
.reduce(Pair.of(0L, 0L), (acc, deleted) -> deleted
? Pair.of(acc.getLeft() + 1, acc.getRight())
: Pair.of(acc.getLeft(), acc.getRight() + 1));
})
.doOnSuccess(outcomes -> {
if (outcomes != null) {
logger.warn(
"Finished trimming {}:{}. Oldest message = {}, newest message = {}. Attempted to delete {} persisted bytes to make room for {} cached message bytes. Delete outcomes: {} present, {} missing.",
aci, deviceId,
Instant.ofEpochMilli(oldestMessage.get()), Instant.ofEpochMilli(newestMessage.get()),
targetDeleteBytes, cachedMessageBytes,
outcomes.getLeft(), outcomes.getRight());
}
})
.then();
}
@VisibleForTesting
Mono<Boolean> shouldPersistQueue(final String queueKey) {
return messagesCache.getEarliestUndeliveredTimestamp(
MessagesCache.getAccountUuidFromQueueName(queueKey),
MessagesCache.getDeviceIdFromQueueName(queueKey))
.map(oldestMessageTimestamp ->
Duration.between(Instant.ofEpochMilli(oldestMessageTimestamp), clock.instant()).compareTo(persistDelay) > 0)
.switchIfEmpty(Mono.just(false));
}
@VisibleForTesting
String getPersisterId() {
return persisterId;
}
}
@@ -13,9 +13,12 @@ import com.google.protobuf.InvalidProtocolBufferException;
import io.github.resilience4j.reactor.retry.RetryOperator;
import io.lettuce.core.Limit;
import io.lettuce.core.Range;
import io.lettuce.core.ScanArgs;
import io.lettuce.core.ScanStream;
import io.lettuce.core.ScoredValue;
import io.lettuce.core.ZAddArgs;
import io.lettuce.core.SetArgs;
import io.lettuce.core.cluster.SlotHash;
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
@@ -38,6 +41,7 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.reactivestreams.Publisher;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
import org.signal.libsignal.protocol.ServiceId;
@@ -48,9 +52,8 @@ import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.RedisClusterUtil;
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
import reactor.core.observability.micrometer.Micrometer;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@@ -85,9 +88,6 @@ import reactor.core.scheduler.Schedulers;
* <dt>{@code queueLockKey}</dt>
* <dd>Used to indicate that a queue is being modified by the {@link MessagePersister} and that {@code get_items} should
* return an empty list.</dd>
* <dt>{@code queueTotalIndexKey}</dt>
* <dd>A sorted set of all queues in a shard. A queue’s score is the timestamp of its oldest message, which is used by
* the {@link MessagePersister} to prioritize queues to persist.</dd>
* </dl>
* <p>
* At a high level, the process is:
@@ -127,15 +127,15 @@ public class MessagesCache {
private final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript;
private final MessagesCacheRemoveByGuidScript removeByGuidScript;
private final MessagesCacheGetItemsScript getItemsScript;
private final MessagesCacheReleaseNodeClaimScript releaseNodeClaimScript;
private final MessagesCacheRemoveQueueScript removeQueueScript;
private final MessagesCacheGetQueuesToPersistScript getQueuesToPersistScript;
private final MessagesCacheRemoveRecipientViewFromMrmDataScript removeRecipientViewFromMrmDataScript;
private final MessagesCacheUnlockQueueScript unlockQueueScript;
private int nextNodeRotateDistance = 0;
private final Timer insertTimer = Metrics.timer(name(MessagesCache.class, "insert"));
private final Timer insertSharedMrmPayloadTimer = Metrics.timer(name(MessagesCache.class, "insertSharedMrmPayload"));
private final Timer getMessagesTimer = Metrics.timer(name(MessagesCache.class, "get"));
private final Timer getQueuesToPersistTimer = Metrics.timer(name(MessagesCache.class, "getQueuesToPersist"));
private final Timer removeByGuidTimer = Metrics.timer(name(MessagesCache.class, "removeByGuid"));
private final Timer removeRecipientViewTimer = Metrics.timer(name(MessagesCache.class, "removeRecipientView"));
private final Timer clearQueueTimer = Metrics.timer(name(MessagesCache.class, "clear"));
@@ -154,7 +154,6 @@ public class MessagesCache {
static final String RETRY_NAME = ResilienceUtil.name(MessagesCache.class);
static final String NEXT_SLOT_TO_PERSIST_KEY = "user_queue_persist_slot";
private static final byte[] LOCK_VALUE = "1".getBytes(StandardCharsets.UTF_8);
@VisibleForTesting
@@ -164,7 +163,9 @@ public class MessagesCache {
static final Duration MAX_EPHEMERAL_MESSAGE_DELAY = Duration.ofSeconds(10);
private static final String GET_FLUX_NAME = MetricsUtil.name(MessagesCache.class, "get");
private static final int PAGE_SIZE = 100;
@VisibleForTesting
static final int PAGE_SIZE = 100;
private static final int REMOVE_MRM_RECIPIENT_VIEW_CONCURRENCY = 8;
@@ -187,9 +188,9 @@ public class MessagesCache {
new MessagesCacheInsertScript(redisCluster, retryExecutor),
new MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript(redisCluster, retryExecutor),
new MessagesCacheGetItemsScript(redisCluster),
new MessagesCacheReleaseNodeClaimScript(redisCluster),
new MessagesCacheRemoveByGuidScript(redisCluster, retryExecutor),
new MessagesCacheRemoveQueueScript(redisCluster),
new MessagesCacheGetQueuesToPersistScript(redisCluster),
new MessagesCacheRemoveRecipientViewFromMrmDataScript(redisCluster),
new MessagesCacheUnlockQueueScript(redisCluster)
);
@@ -202,9 +203,10 @@ public class MessagesCache {
final ExperimentEnrollmentManager experimentEnrollmentManager,
final MessagesCacheInsertScript insertScript,
final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript,
final MessagesCacheGetItemsScript getItemsScript, final MessagesCacheRemoveByGuidScript removeByGuidScript,
final MessagesCacheGetItemsScript getItemsScript,
final MessagesCacheReleaseNodeClaimScript releaseNodeClaimScript,
final MessagesCacheRemoveByGuidScript removeByGuidScript,
final MessagesCacheRemoveQueueScript removeQueueScript,
final MessagesCacheGetQueuesToPersistScript getQueuesToPersistScript,
final MessagesCacheRemoveRecipientViewFromMrmDataScript removeRecipientViewFromMrmDataScript,
final MessagesCacheUnlockQueueScript unlockQueueScript) throws IOException {
@@ -220,8 +222,8 @@ public class MessagesCache {
this.insertMrmScript = insertMrmScript;
this.removeByGuidScript = removeByGuidScript;
this.getItemsScript = getItemsScript;
this.releaseNodeClaimScript = releaseNodeClaimScript;
this.removeQueueScript = removeQueueScript;
this.getQueuesToPersistScript = getQueuesToPersistScript;
this.removeRecipientViewFromMrmDataScript = removeRecipientViewFromMrmDataScript;
this.unlockQueueScript = unlockQueueScript;
}
@@ -307,13 +309,30 @@ public class MessagesCache {
.toCompletableFuture();
}
public Publisher<MessageProtos.Envelope> get(final UUID destinationUuid, final byte destinationDevice) {
public Publisher<MessageProtos.Envelope> get(final UUID destinationUuid, final byte destinationDeviceId) {
return get(destinationUuid,
destinationDeviceId,
clock.instant().minus(MAX_EPHEMERAL_MESSAGE_DELAY),
false);
}
final long earliestAllowableEphemeralTimestamp =
clock.millis() - MAX_EPHEMERAL_MESSAGE_DELAY.toMillis();
Publisher<MessageProtos.Envelope> getMessagesToPersist(final UUID accountUuid, final byte destinationDeviceId) {
return Flux.from(get(accountUuid,
destinationDeviceId,
// Discard all ephemeral messages when persisting
Instant.ofEpochMilli(Long.MAX_VALUE),
true));
}
final Flux<MessageProtos.Envelope> allMessages = getAllMessages(destinationUuid, destinationDevice,
earliestAllowableEphemeralTimestamp, PAGE_SIZE)
private Publisher<MessageProtos.Envelope> get(final UUID destinationUuid,
final byte destinationDeviceId,
final Instant earliestAllowableEphemeralTimestamp,
final boolean bypassLock) {
final long earliestAllowableEphemeralTimestampMillis = earliestAllowableEphemeralTimestamp.toEpochMilli();
final Flux<MessageProtos.Envelope> allMessages = getAllMessages(destinationUuid, destinationDeviceId,
earliestAllowableEphemeralTimestampMillis, PAGE_SIZE, bypassLock)
.publish()
// We expect exactly three subscribers to this base flux:
// 1. the websocket that delivers messages to clients
@@ -325,25 +344,41 @@ public class MessagesCache {
final Flux<MessageProtos.Envelope> messagesToPublish = allMessages
.filter(Predicate.not(envelope ->
isStaleEphemeralMessage(envelope, earliestAllowableEphemeralTimestamp) || isStaleMrmMessage(envelope)));
isStaleEphemeralMessage(envelope, earliestAllowableEphemeralTimestampMillis) || isStaleMrmMessage(envelope)));
final Flux<MessageProtos.Envelope> staleEphemeralMessages = allMessages
.filter(envelope -> isStaleEphemeralMessage(envelope, earliestAllowableEphemeralTimestamp));
discardStaleMessages(destinationUuid, destinationDevice, staleEphemeralMessages, staleEphemeralMessagesCounter, "ephemeral");
.filter(envelope -> isStaleEphemeralMessage(envelope, earliestAllowableEphemeralTimestampMillis));
discardStaleMessages(destinationUuid, destinationDeviceId, staleEphemeralMessages, staleEphemeralMessagesCounter, "ephemeral");
final Flux<MessageProtos.Envelope> staleMrmMessages = allMessages.filter(MessagesCache::isStaleMrmMessage)
// clearing the sharedMrmKey prevents unnecessary calls to update the shared MRM data
.map(envelope -> envelope.toBuilder().clearSharedMrmKey().build());
discardStaleMessages(destinationUuid, destinationDevice, staleMrmMessages, staleMrmMessagesCounter, "mrm");
discardStaleMessages(destinationUuid, destinationDeviceId, staleMrmMessages, staleMrmMessagesCounter, "mrm");
return messagesToPublish.name(GET_FLUX_NAME)
.tap(Micrometer.metrics(Metrics.globalRegistry));
}
public Mono<Long> getEarliestUndeliveredTimestamp(final UUID destinationUuid, final byte destinationDevice) {
return getAllMessages(destinationUuid, destinationDevice, -1, 1)
/// Returns the server-issued timestamp of the earliest message in the queue for the given account/device, regardless
/// of the type of message. Note that this method may return a timestamp for a message that would ultimately be
/// discarded were a caller to actually fetch messages (i.e. an expired ephemeral message).
///
/// @param destinationUuid the account identifier for the queue for which to get a timestamp
/// @param destinationDeviceId the device identifier for the queue for which to get a timestamp
///
/// @return a `Mono` that publishes the timestamp (in milliseconds since the epoch) of the earliest message in the
/// given queue or yields no value if the queue is empty or does not exist
public Mono<Long> getEarliestUndeliveredTimestamp(final UUID destinationUuid, final byte destinationDeviceId) {
return redisCluster.withBinaryCluster(connection ->
connection.reactive().zrange(getMessageQueueKey(destinationUuid, destinationDeviceId), 0, 0))
.next()
.map(MessageProtos.Envelope::getServerTimestamp);
.flatMap(serializedEnvelope -> {
try {
return Mono.just(parseEnvelope(serializedEnvelope).getServerTimestamp());
} catch (final InvalidProtocolBufferException e) {
return Mono.error(e);
}
});
}
private static boolean isStaleEphemeralMessage(final MessageProtos.Envelope message,
@@ -373,18 +408,21 @@ public class MessagesCache {
}
@VisibleForTesting
Flux<MessageProtos.Envelope> getAllMessages(final UUID destinationUuid, final byte destinationDevice,
final long earliestAllowableEphemeralTimestamp, final int pageSize) {
Flux<MessageProtos.Envelope> getAllMessages(final UUID destinationUuid,
final byte destinationDevice,
final long earliestAllowableEphemeralTimestamp,
final int pageSize,
final boolean bypassLock) {
// fetch messages by page
return getNextMessagePage(destinationUuid, destinationDevice, -1, pageSize)
return getNextMessagePage(destinationUuid, destinationDevice, -1, pageSize, bypassLock)
.expand(queueItemsAndLastMessageId -> {
// expand() is breadth-first, so each page will be published in order
if (queueItemsAndLastMessageId.first().isEmpty()) {
return Mono.empty();
}
return getNextMessagePage(destinationUuid, destinationDevice, queueItemsAndLastMessageId.second(), pageSize);
return getNextMessagePage(destinationUuid, destinationDevice, queueItemsAndLastMessageId.second(), pageSize, bypassLock);
})
.limitRate(1)
// we want to ensure we don’t accidentally block the Lettuce/netty i/o executors
@@ -529,10 +567,13 @@ public class MessagesCache {
.subscribe();
}
private Mono<Pair<List<byte[]>, Long>> getNextMessagePage(final UUID destinationUuid, final byte destinationDevice,
long messageId, int pageSize) {
private Mono<Pair<List<byte[]>, Long>> getNextMessagePage(final UUID destinationUuid,
final byte destinationDevice,
final long messageId,
final int pageSize,
final boolean bypassLock) {
return getItemsScript.execute(destinationUuid, destinationDevice, pageSize, messageId)
return getItemsScript.execute(destinationUuid, destinationDevice, pageSize, messageId, bypassLock)
.map(queueItems -> {
logger.trace("Processing page: {}", messageId);
@@ -583,35 +624,6 @@ public class MessagesCache {
.toFuture();
}
List<MessageProtos.Envelope> getMessagesToPersist(final UUID accountUuid, final byte destinationDevice,
final int limit) {
final Timer.Sample sample = Timer.start();
final List<byte[]> messages = redisCluster.withBinaryCluster(connection ->
connection.sync().zrange(getMessageQueueKey(accountUuid, destinationDevice), 0, limit));
final Flux<MessageProtos.Envelope> allMessages = parseAndFetchMrms(Flux.fromIterable(messages), destinationDevice);
final Flux<MessageProtos.Envelope> messagesToPersist = allMessages
.filter(Predicate.not(envelope ->
envelope.getEphemeral() || isStaleMrmMessage(envelope)));
final Flux<MessageProtos.Envelope> ephemeralMessages = allMessages
.filter(MessageProtos.Envelope::getEphemeral);
discardStaleMessages(accountUuid, destinationDevice, ephemeralMessages, staleEphemeralMessagesCounter, "ephemeral");
final Flux<MessageProtos.Envelope> staleMrmMessages = allMessages.filter(MessagesCache::isStaleMrmMessage)
// clearing the sharedMrmKey prevents unnecessary calls to update the shared MRM data
.map(envelope -> envelope.toBuilder().clearSharedMrmKey().build());
discardStaleMessages(accountUuid, destinationDevice, staleMrmMessages, staleMrmMessagesCounter, "mrm");
return messagesToPersist
.collectList()
.doOnTerminate(() -> sample.stop(getMessagesTimer))
.block(Duration.ofSeconds(5));
}
private Flux<MessageProtos.Envelope> parseAndFetchMrms(final Flux<byte[]> serializedMessages, final byte destinationDevice) {
return serializedMessages
.mapNotNull(message -> {
@@ -680,37 +692,47 @@ public class MessagesCache {
.thenRun(() -> sample.stop(clearQueueTimer));
}
public String shardForSlot(int slot) {
try {
return redisCluster.withBinaryCluster(
connection -> connection.getPartitions().getPartitionBySlot(slot).getUri().getHost());
} catch (final Throwable _) {
return "unknown";
}
Optional<RedisClusterNode> claimNextNodeToPersist(final String persisterId, final Duration ttl) {
final List<RedisClusterNode> primaryNodes = redisCluster.withCluster(connection -> connection.getPartitions().stream()
.filter(node -> node.is(RedisClusterNode.NodeFlag.UPSTREAM))
.collect(Collectors.toCollection(ArrayList::new)));
Collections.rotate(primaryNodes, Math.abs(nextNodeRotateDistance++) % primaryNodes.size());
return primaryNodes.stream()
.filter(node -> claimNode(node, persisterId, ttl))
.findFirst();
}
int getNextSlotToPersist() {
return (int) (redisCluster.withCluster(connection -> connection.sync().incr(NEXT_SLOT_TO_PERSIST_KEY))
% SlotHash.SLOT_COUNT);
@VisibleForTesting
boolean claimNode(final RedisClusterNode node, final String persisterId, final Duration claimTtl) {
return redisCluster.withCluster(connection ->
"OK".equals(connection.sync().set(getPersisterNodeClaimKey(node), persisterId, SetArgs.Builder.nx().ex(claimTtl))));
}
List<String> getQueuesToPersist(final int slot, final Instant maxTime, final int limit) {
return getQueuesToPersistTimer.record(() -> getQueuesToPersistScript.execute(slot, maxTime, limit));
void releaseNodeClaim(final RedisClusterNode node, final String persisterId) {
releaseNodeClaimScript.execute(node, persisterId);
}
void addQueueToPersist(final UUID accountUuid, final byte deviceId) {
redisCluster.useBinaryCluster(connection -> connection.sync()
.zadd(getQueueIndexKey(accountUuid, deviceId), ZAddArgs.Builder.nx(), System.currentTimeMillis(),
getMessageQueueKey(accountUuid, deviceId)));
@VisibleForTesting
static String getPersisterNodeClaimKey(final RedisClusterNode node) {
return "persister_node_claim::" + node.getNodeId();
}
void lockQueueForPersistence(final UUID accountUuid, final byte deviceId) {
redisCluster.useBinaryCluster(
connection -> connection.sync().setex(getPersistInProgressKey(accountUuid, deviceId), 30, LOCK_VALUE));
Flux<String> getQueues(final RedisClusterNode node, final int scanCount) {
return redisCluster.withCluster(connection ->
ScanStream.scan(connection.getConnection(node.getNodeId()).reactive(),
ScanArgs.Builder.matches("user_queue::*").limit(scanCount)));
}
void unlockQueueForPersistence(final UUID accountUuid, final byte deviceId) {
unlockQueueScript.execute(accountUuid, deviceId);
Mono<Void> lockQueueForPersistence(final UUID accountUuid, final byte deviceId) {
return redisCluster.withBinaryCluster(
connection -> connection.reactive().setex(getPersistInProgressKey(accountUuid, deviceId), 30, LOCK_VALUE))
.then();
}
Mono<Void> unlockQueueForPersistence(final UUID accountUuid, final byte deviceId) {
return unlockQueueScript.execute(accountUuid, deviceId);
}
static byte[] getMessageQueueKey(final UUID accountUuid, final byte deviceId) {
@@ -721,14 +743,6 @@ public class MessagesCache {
return ("user_queue_metadata::{" + accountUuid.toString() + "::" + deviceId + "}").getBytes(StandardCharsets.UTF_8);
}
static byte[] getQueueIndexKey(final UUID accountUuid, final byte deviceId) {
return getQueueIndexKey(SlotHash.getSlot(accountUuid.toString() + "::" + deviceId));
}
static byte[] getQueueIndexKey(final int slot) {
return ("user_queue_index::{" + RedisClusterUtil.getMinimalHashTag(slot) + "}").getBytes(StandardCharsets.UTF_8);
}
static byte[] getSharedMrmKey(final UUID mrmGuid) {
return ("mrm::{" + mrmGuid.toString() + "}").getBytes(StandardCharsets.UTF_8);
}
@@ -28,15 +28,20 @@ class MessagesCacheGetItemsScript {
this.getItemsScript = ClusterLuaScript.fromResource(redisCluster, "lua/get_items.lua", ScriptOutputType.OBJECT);
}
Mono<List<byte[]>> execute(final UUID destinationUuid, final byte destinationDevice,
int limit, long afterMessageId) {
Mono<List<byte[]>> execute(final UUID destinationUuid,
final byte destinationDevice,
final int limit,
final long afterMessageId,
final boolean bypassLock) {
final List<byte[]> keys = List.of(
MessagesCache.getMessageQueueKey(destinationUuid, destinationDevice), // queueKey
MessagesCache.getPersistInProgressKey(destinationUuid, destinationDevice) // queueLockKey
);
final List<byte[]> args = List.of(
String.valueOf(limit).getBytes(StandardCharsets.UTF_8), // limit
String.valueOf(afterMessageId).getBytes(StandardCharsets.UTF_8) // afterMessageId
String.valueOf(afterMessageId).getBytes(StandardCharsets.UTF_8), // afterMessageId
String.valueOf(bypassLock).getBytes(StandardCharsets.UTF_8) // bypassLock
);
//noinspection unchecked
return getItemsScript.executeBinaryReactive(keys, args)
@@ -1,43 +0,0 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import io.lettuce.core.ScriptOutputType;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.List;
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
/**
* Returns a list of queues that may be persisted. They will be sorted from oldest to more recent, limited by the
* {@code maxTime} argument.
*
* @see MessagePersister
*/
class MessagesCacheGetQueuesToPersistScript {
private final ClusterLuaScript getQueuesToPersistScript;
MessagesCacheGetQueuesToPersistScript(final FaultTolerantRedisClusterClient redisCluster) throws IOException {
this.getQueuesToPersistScript = ClusterLuaScript.fromResource(redisCluster, "lua/get_queues_to_persist.lua",
ScriptOutputType.MULTI);
}
List<String> execute(final int slot, final Instant maxTime, final int limit) {
final List<String> keys = List.of(
new String(MessagesCache.getQueueIndexKey(slot), StandardCharsets.UTF_8) // queueTotalIndexKey
);
final List<String> args = List.of(
String.valueOf(maxTime.toEpochMilli()), // maxTime
String.valueOf(limit) // limit
);
//noinspection unchecked
return (List<String>) getQueuesToPersistScript.execute(keys, args);
}
}
@@ -58,13 +58,11 @@ class MessagesCacheInsertScript {
final List<byte[]> keys = List.of(
MessagesCache.getMessageQueueKey(destinationUuid, destinationDevice), // queueKey
MessagesCache.getMessageQueueMetadataKey(destinationUuid, destinationDevice), // queueMetadataKey
MessagesCache.getQueueIndexKey(destinationUuid, destinationDevice), // queueTotalIndexKey
RedisMessageAvailabilityManager.getClientEventChannel(destinationUuid, destinationDevice) // eventChannelKey
);
final List<byte[]> args = new ArrayList<>(Arrays.asList(
EnvelopeUtil.compress(envelope).toByteArray(), // message
String.valueOf(envelope.getServerTimestamp()).getBytes(StandardCharsets.UTF_8), // currentTime
envelope.getServerGuid().getBytes(StandardCharsets.UTF_8), // guid
NEW_MESSAGE_EVENT_BYTES // eventPayload
));
@@ -0,0 +1,32 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import io.lettuce.core.ScriptOutputType;
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
import java.io.IOException;
import java.util.List;
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
class MessagesCacheReleaseNodeClaimScript {
private final ClusterLuaScript releaseNodeClaimScript;
MessagesCacheReleaseNodeClaimScript(final FaultTolerantRedisClusterClient redisCluster) throws IOException {
this.releaseNodeClaimScript =
ClusterLuaScript.fromResource(redisCluster, "lua/release_node_claim.lua", ScriptOutputType.STATUS);
}
void execute(final RedisClusterNode node, final String persisterId) {
final List<String> keys = List.of(MessagesCache.getPersisterNodeClaimKey(node));
final List<String> arguments = List.of(persisterId);
ResilienceUtil.getGeneralRedisRetry(getClass().getSimpleName())
.executeRunnable(() -> releaseNodeClaimScript.execute(keys, arguments));
}
}
@@ -37,8 +37,7 @@ class MessagesCacheRemoveByGuidScript {
final List<byte[]> keys = List.of(
MessagesCache.getMessageQueueKey(destinationUuid, destinationDevice), // queueKey
MessagesCache.getMessageQueueMetadataKey(destinationUuid, destinationDevice), // queueMetadataKey
MessagesCache.getQueueIndexKey(destinationUuid, destinationDevice) // queueTotalIndexKey
MessagesCache.getMessageQueueMetadataKey(destinationUuid, destinationDevice) // queueMetadataKey
);
final List<byte[]> args = messageGuids.stream().map(guid -> guid.toString().getBytes(StandardCharsets.UTF_8))
.toList();
@@ -39,8 +39,7 @@ class MessagesCacheRemoveQueueScript {
final List<byte[]> keys = List.of(
MessagesCache.getMessageQueueKey(destinationUuid, destinationDevice), // queueKey
MessagesCache.getMessageQueueMetadataKey(destinationUuid, destinationDevice), // queueMetadataKey
MessagesCache.getQueueIndexKey(destinationUuid, destinationDevice) // queueTotalIndexKey
MessagesCache.getMessageQueueMetadataKey(destinationUuid, destinationDevice) // queueMetadataKey
);
final List<byte[]> args = new ArrayList<>();
@@ -6,15 +6,17 @@
package org.whispersystems.textsecuregcm.storage;
import io.lettuce.core.ScriptOutputType;
import java.io.IOException;
import java.time.Duration;
import java.util.List;
import java.util.UUID;
import org.whispersystems.textsecuregcm.push.ClientEvent;
import org.whispersystems.textsecuregcm.push.MessagesPersistedEvent;
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import reactor.core.publisher.Mono;
import reactor.util.retry.Retry;
/**
* Unlocks a message queue for persistence/message retrieval.
@@ -33,13 +35,14 @@ class MessagesCacheUnlockQueueScript {
ClusterLuaScript.fromResource(redisCluster, "lua/unlock_queue.lua", ScriptOutputType.STATUS);
}
void execute(final UUID accountIdentifier, final byte deviceId) {
Mono<Void> execute(final UUID accountIdentifier, final byte deviceId) {
final List<byte[]> keys = List.of(
MessagesCache.getPersistInProgressKey(accountIdentifier, deviceId), // persistInProgressKey
RedisMessageAvailabilityManager.getClientEventChannel(accountIdentifier, deviceId) // eventChannelKey
);
ResilienceUtil.getGeneralRedisRetry(MessagesCache.RETRY_NAME)
.executeRunnable(() -> unlockQueueScript.executeBinary(keys, MESSAGES_PERSISTED_EVENT_ARGS));
return unlockQueueScript.executeBinaryReactive(keys, MESSAGES_PERSISTED_EVENT_ARGS)
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1)))
.then();
}
}
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.storage;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;
@@ -71,9 +72,9 @@ public class PagedSingleUseKEMPreKeyStore {
private final Timer deleteForDeviceTimer = Metrics.timer(name(getClass(), "deleteForDevice"));
private final Timer deleteForAccountTimer = Metrics.timer(name(getClass(), "deleteForAccount"));
private final Counter outOfRangeKeysDiscarded = Metrics.counter(name(getClass(), "outOfRangeKeysDiscarded"));
final DistributionSummary availableKeyCountDistributionSummary = DistributionSummary
.builder(name(getClass(), "availableKeyCount"))
.publishPercentileHistogram()
.register(Metrics.globalRegistry);
private final String takeKeyTimerName = name(getClass(), "takeKey");
@@ -160,7 +161,14 @@ public class PagedSingleUseKEMPreKeyStore {
*/
public CompletableFuture<Optional<KEMSignedPreKey>> take(final UUID identifier, final byte deviceId) {
final Timer.Sample sample = Timer.start();
return takeHelper(identifier, deviceId)
.whenComplete((maybeKey, throwable) ->
sample.stop(Metrics.timer(
takeKeyTimerName,
KEY_PRESENT_TAG_NAME, String.valueOf(maybeKey != null && maybeKey.isPresent()))));
}
private CompletableFuture<Optional<KEMSignedPreKey>> takeHelper(final UUID identifier, final byte deviceId) {
return dynamoDbAsyncClient.updateItem(UpdateItemRequest.builder()
.tableName(tableName)
.key(Map.of(
@@ -197,10 +205,15 @@ public class PagedSingleUseKEMPreKeyStore {
.exceptionally(ExceptionUtils.exceptionallyHandler(
ConditionalCheckFailedException.class,
e -> Optional.empty()))
.whenComplete((maybeKey, throwable) ->
sample.stop(Metrics.timer(
takeKeyTimerName,
KEY_PRESENT_TAG_NAME, String.valueOf(maybeKey != null && maybeKey.isPresent()))));
.thenCompose(maybeKey -> {
if (!maybeKey.map(KEMSignedPreKey::keyId).map(KeyIdUtil::keyIdValid).orElse(true)) {
// At some point we did not validate that keyIds fit in an unsigned 32-bit integer, which clients require.
// This keyId was invalid, so just recursively fetch the next key
outOfRangeKeysDiscarded.increment();
return takeHelper(identifier, deviceId);
}
return CompletableFuture.completedFuture(maybeKey);
});
}
/**
@@ -107,11 +107,14 @@ public abstract class RepeatedUseSignedPreKeyStore<K extends SignedPreKey<?>> {
.build())
.thenApply(response -> response.hasItem() ? Optional.of(getPreKeyFromItem(response.item())) : Optional.empty());
findFuture.whenComplete((maybeSignedPreKey, throwable) ->
sample.stop(Metrics.timer(findKeyTimerName,
"keyPresent", String.valueOf(maybeSignedPreKey != null && maybeSignedPreKey.isPresent()))));
return findFuture.whenComplete((maybeSignedPreKey, throwable) -> {
if (throwable == null && maybeSignedPreKey.map(k -> !KeyIdUtil.keyIdValid(k.keyId())).orElse(false)) {
throw new IllegalStateException("Encountered an impossible invalid repeated use pre-key id of " + maybeSignedPreKey.get().keyId());
}
return findFuture;
sample.stop(Metrics.timer(findKeyTimerName,
"keyPresent", String.valueOf(maybeSignedPreKey != null && maybeSignedPreKey.isPresent())));
});
}
protected static Map<String, AttributeValue> getPrimaryKey(final UUID identifier, final byte deviceId) {
@@ -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);
@@ -47,7 +47,6 @@ import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
* may fall back to using the device's repeated-use ("last-resort") signed pre-key instead.
*/
public class SingleUseECPreKeyStore {
private final DynamoDbAsyncClient dynamoDbAsyncClient;
private final String tableName;
@@ -58,16 +57,16 @@ public class SingleUseECPreKeyStore {
private final Timer deleteForAccountTimer = Metrics.timer(name(getClass(), "deleteForAccount"));
private final Counter noKeyCountAvailableCounter = Metrics.counter(name(getClass(), "noKeyCountAvailable"));
private final Counter outOfRangeKeysDiscarded =
Metrics.counter(name(getClass(), "outOfRangeKeysDiscarded"));
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);
@@ -137,7 +136,7 @@ public class SingleUseECPreKeyStore {
public CompletableFuture<Optional<ECPreKey>> take(final UUID identifier, final byte deviceId) {
final Timer.Sample sample = Timer.start();
final AttributeValue partitionKey = getPartitionKey(identifier);
final AtomicInteger keysConsidered = new AtomicInteger(0);
final AtomicInteger deletionAttempts = new AtomicInteger(0);
return Flux.from(dynamoDbAsyncClient.queryPaginator(QueryRequest.builder()
.tableName(tableName)
@@ -158,16 +157,26 @@ public class SingleUseECPreKeyStore {
KEY_DEVICE_ID_KEY_ID, item.get(KEY_DEVICE_ID_KEY_ID)))
.returnValues(ReturnValue.ALL_OLD)
.build())
.flatMap(deleteItemRequest -> Mono.fromFuture(() -> dynamoDbAsyncClient.deleteItem(deleteItemRequest)), 1)
.doOnNext(deleteItemResponse -> keysConsidered.incrementAndGet())
.concatMap(deleteItemRequest -> Mono.fromFuture(() -> dynamoDbAsyncClient.deleteItem(deleteItemRequest)))
.doOnNext(_ -> deletionAttempts.incrementAndGet())
.filter(DeleteItemResponse::hasAttributes)
.filter(item -> {
final long keyId = getKeyIdFromItem(item.attributes());
final boolean keyIdValid = KeyIdUtil.keyIdValid(keyId);
if (!keyIdValid) {
outOfRangeKeysDiscarded.increment();
}
// At some point we did not validate that keyIds fit in an unsigned 32-bit integer, which clients require.
// If this keyId is invalid, we'll skip it and fetch the next key
return keyIdValid;
})
.next()
.map(deleteItemResponse -> getPreKeyFromItem(deleteItemResponse.attributes()))
.toFuture()
.thenApply(Optional::ofNullable)
.whenComplete((maybeKey, throwable) -> {
sample.stop(Metrics.timer(takeKeyTimerName, KEY_PRESENT_TAG_NAME, String.valueOf(maybeKey != null && maybeKey.isPresent())));
keysConsideredForTakeDistributionSummary.record(keysConsidered.get());
keysConsideredForTakeDistributionSummary.record(deletionAttempts.get());
});
}
@@ -312,7 +321,7 @@ public class SingleUseECPreKeyStore {
}
private ECPreKey getPreKeyFromItem(final Map<String, AttributeValue> item) {
final long keyId = item.get(KEY_DEVICE_ID_KEY_ID).b().asByteBuffer().getLong(8);
final long keyId = getKeyIdFromItem(item);
final byte[] publicKey = AttributeValues.extractByteArray(item.get(ATTR_PUBLIC_KEY), PARSE_BYTE_ARRAY_COUNTER_NAME);
try {
@@ -322,4 +331,8 @@ public class SingleUseECPreKeyStore {
throw new IllegalArgumentException(e);
}
}
private static long getKeyIdFromItem(final Map<String, AttributeValue> item) {
return item.get(KEY_DEVICE_ID_KEY_ID).b().asByteBuffer().getLong(8);
}
}
@@ -130,12 +130,13 @@ public class AppleAppStoreClient {
try {
return getAllSubscriptionsHelper(defaultEnvironment, originalTransactionId);
} catch (final APIException e) {
Metrics.counter(GET_SUBSCRIPTION_ERROR_COUNTER_NAME, errorTags.and("reason", e.getApiError().name())).increment();
final APIError apiError = e.getApiError();
Metrics.counter(GET_SUBSCRIPTION_ERROR_COUNTER_NAME, errorTags.and("reason", apiError != null ? apiError.name() : "http_" + e.getHttpStatusCode())).increment();
throw switch (e.getApiError()) {
case TRANSACTION_ID_NOT_FOUND, ORIGINAL_TRANSACTION_ID_NOT_FOUND -> new SubscriptionNotFoundException();
case RATE_LIMIT_EXCEEDED -> new RateLimitExceededException(null);
case INVALID_ORIGINAL_TRANSACTION_ID -> new SubscriptionInvalidArgumentsException(e.getApiErrorMessage());
default -> throw e;
case null, default -> throw e;
};
} catch (final IOException e) {
Metrics.counter(GET_SUBSCRIPTION_ERROR_COUNTER_NAME, "reason", "io_error").increment();
@@ -183,7 +184,7 @@ public class AppleAppStoreClient {
private static boolean shouldRetry(Throwable e) {
return e instanceof APIException apiException && switch (apiException.getApiError()) {
case ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE, GENERAL_INTERNAL_RETRYABLE, APP_NOT_FOUND_RETRYABLE -> true;
default -> false;
case null, default -> false;
};
}
@@ -9,14 +9,18 @@ import com.apple.itunes.storekit.model.AutoRenewStatus;
import com.apple.itunes.storekit.model.Status;
import com.apple.itunes.storekit.model.StatusResponse;
import com.apple.itunes.storekit.model.SubscriptionGroupIdentifierItem;
import io.micrometer.core.instrument.Tags;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.Base64;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import io.micrometer.core.instrument.Tags;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
@@ -165,23 +169,20 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
final List<AppleAppStoreDecodedTransaction> txs = item.getLastTransactions().stream()
.map(txItem -> appleAppStoreClient.verify(statuses.getEnvironment(), txItem))
.filter(tx -> tx.signedTransaction().getOriginalTransactionId().equals(originalTransactionId))
.filter(decoded -> productIdToLevel.containsKey(decoded.transaction().getProductId()))
.toList();
if (txs.isEmpty()) {
throw new SubscriptionInvalidArgumentsException("transactionId did not include a paid subscription", null);
}
if (txs.size() > 1) {
logger.warn("Multiple matching product transactions found for transactionId {}, only considering first",
originalTransactionId);
}
if (!originalTransactionId.equals(txs.getFirst().signedTransaction().getOriginalTransactionId())) {
// Get All Subscriptions only requires that the transaction be some transaction associated with the
// subscription. This is too flexible, since we'd like to key on the originalTransactionId in the
// SubscriptionManager.
throw new SubscriptionInvalidArgumentsException("transactionId was not the transaction's originalTransactionId", null);
throw new SubscriptionInvalidArgumentsException("transactionId did not include a paid subscription or the provided transactionId was not an originalTransactionId", null);
}
if (txs.size() > 1) {
logger.warn("Multiple matching product transactions found with a sha256(originalTransactionId)={}, only considering first",
sha256(originalTransactionId));
}
return txs.getFirst();
}
@@ -210,4 +211,14 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|| tx.signedTransaction().getStatus() == Status.BILLING_GRACE_PERIOD;
}
private static String sha256(final String input) {
final MessageDigest sha256;
try {
sha256 = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new AssertionError("Every implementation of the Java platform is required to support SHA-256", e);
}
return Base64.getEncoder().encodeToString(sha256.digest(input.getBytes(StandardCharsets.UTF_8)));
}
}
@@ -433,33 +433,48 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
}
}
private Subscription endSubscription(Subscription subscription) {
@VisibleForTesting
void endSubscription(Subscription subscription) {
final SubscriptionStatus status = SubscriptionStatus.forApiValue(subscription.getStatus());
return switch (status) {
switch (status) {
// The payment for this period has not processed yet, we should immediately cancel to prevent any payment from
// going through.
case UNPAID, PAST_DUE, INCOMPLETE -> cancelSubscriptionImmediately(subscription);
// Otherwise, set the subscription to cancel at the current period end. If the subscription is active, it may
// continue to be used until the end of the period.
default -> cancelSubscriptionAtEndOfCurrentPeriod(subscription);
default -> {
final Price price = getPriceForSubscription(subscription);
if (supportedCurrenciesByPaymentMethod.values().stream()
.noneMatch(supported -> supported.contains(price.getCurrency()))) {
// This currency is no longer supported. Cancel-at-period-end will fail, so we must cancel immediately.
cancelSubscriptionImmediately(subscription);
} else {
cancelSubscriptionAtEndOfCurrentPeriod(subscription);
}
}
};
}
private Subscription cancelSubscriptionImmediately(Subscription subscription) {
private void cancelSubscriptionImmediately(Subscription subscription) {
SubscriptionCancelParams params = SubscriptionCancelParams.builder().build();
try {
return stripeClient.v1().subscriptions().cancel(subscription.getId(), params, commonOptions());
stripeClient.v1().subscriptions().cancel(subscription.getId(), params, commonOptions());
} catch (StripeException e) {
throw new UncheckedIOException(new IOException(e));
}
}
private Subscription cancelSubscriptionAtEndOfCurrentPeriod(Subscription subscription) {
private void cancelSubscriptionAtEndOfCurrentPeriod(Subscription subscription) {
SubscriptionUpdateParams params = SubscriptionUpdateParams.builder()
.setCancelAtPeriodEnd(true)
.build();
try {
return stripeClient.v1().subscriptions().update(subscription.getId(), params, commonOptions());
stripeClient.v1().subscriptions().update(subscription.getId(), params, commonOptions());
} catch (StripeException e) {
throw new UncheckedIOException(new IOException(e));
}
@@ -171,7 +171,7 @@ public class HlrLookupCarrierDataProvider implements CarrierDataProvider {
static Optional<String> mncFromMccMnc(@Nullable final String mccMnc) {
// MNCs may be 2 or 3 digits, but always come after a 3-digit MCC
return Optional.ofNullable(StringUtils.stripToNull(mccMnc))
.map(trimmedMccMnc -> trimmedMccMnc.substring(3));
.map(trimmedMccMnc -> StringUtils.stripToNull(trimmedMccMnc.substring(3)));
}
@VisibleForTesting
@@ -32,8 +32,6 @@ public final class HeaderUtils {
public static final String X_SIGNAL_AGENT = "X-Signal-Agent";
public static final String X_SIGNAL_KEY = "X-Signal-Key";
public static final String TIMESTAMP_HEADER = "X-Signal-Timestamp";
public static final String UNIDENTIFIED_ACCESS_KEY = "Unidentified-Access-Key";
@@ -0,0 +1,19 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.util;
/// Represents an operation that accepts a single input argument and returns no result, but may throw a checked
/// exception. Unlike most other functional interfaces, `ThrowingConsumer` is expected to operate via side-effects.
@FunctionalInterface
public interface ThrowingConsumer<T, E extends Exception> {
/// Performs this operation on the given argument.
///
/// @param t the input argument
///
/// @throws E at the implementation's discretion
void accept(T t) throws E;
}
@@ -0,0 +1,20 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.util;
/// Represents a supplier of results that may throw an exception.
///
/// There is no requirement that a new or distinct result be returned each time the supplier is invoked.
@FunctionalInterface
public interface ThrowingSupplier<T, E extends Exception> {
/// Gets a result, potentially throwing an exception.
///
/// @return a result
///
/// @throws E at the discretion of the implementation
T get() throws E;
}
@@ -5,14 +5,12 @@
package org.whispersystems.textsecuregcm.websocket;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Tags;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.asn.AsnInfoProvider;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
@@ -35,13 +33,6 @@ import reactor.core.scheduler.Scheduler;
public class AuthenticatedConnectListener implements WebSocketConnectListener {
private static final String OPEN_WEBSOCKET_GAUGE_NAME = name(AuthenticatedConnectListener.class, "openWebsockets");
private static final String NEW_CONNECTION_COUNTER_NAME = name(AuthenticatedConnectListener.class, "newConnections");
private static final String CONNECTED_DURATION_TIMER_NAME =
name(AuthenticatedConnectListener.class, "connectedDuration");
private static final String AUTHENTICATED_TAG_NAME = "authenticated";
private static final Logger log = LoggerFactory.getLogger(AuthenticatedConnectListener.class);
private final AccountsManager accountsManager;
@@ -66,12 +57,15 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
final PushNotificationScheduler pushNotificationScheduler,
final DisconnectionRequestManager disconnectionRequestManager,
final Scheduler messageDeliveryScheduler,
final Supplier<AsnInfoProvider> asnInfoProviderSupplier,
final ClientReleaseManager clientReleaseManager,
final MessageDeliveryLoopMonitor messageDeliveryLoopMonitor,
final ExperimentEnrollmentManager experimentEnrollmentManager) {
this(accountsManager,
disconnectionRequestManager,
asnInfoProviderSupplier,
clientReleaseManager,
(account, device, client) -> new WebSocketConnection(receiptSender,
messagesManager,
messageMetrics,
@@ -83,26 +77,23 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
messageDeliveryScheduler,
clientReleaseManager,
messageDeliveryLoopMonitor,
experimentEnrollmentManager),
authenticated -> new OpenWebSocketCounter(OPEN_WEBSOCKET_GAUGE_NAME,
NEW_CONNECTION_COUNTER_NAME,
CONNECTED_DURATION_TIMER_NAME,
Tags.of(AUTHENTICATED_TAG_NAME, String.valueOf(authenticated)))
experimentEnrollmentManager)
);
}
@VisibleForTesting AuthenticatedConnectListener(
final AccountsManager accountsManager,
final DisconnectionRequestManager disconnectionRequestManager,
final WebSocketConnectionBuilder webSocketConnectionBuilder,
final Function<Boolean, OpenWebSocketCounter> openWebSocketCounterBuilder) {
final Supplier<AsnInfoProvider> asnInfoProviderSupplier,
final ClientReleaseManager clientReleaseManager,
final WebSocketConnectionBuilder webSocketConnectionBuilder) {
this.accountsManager = accountsManager;
this.disconnectionRequestManager = disconnectionRequestManager;
this.webSocketConnectionBuilder = webSocketConnectionBuilder;
openAuthenticatedWebSocketCounter = openWebSocketCounterBuilder.apply(true);
openUnauthenticatedWebSocketCounter = openWebSocketCounterBuilder.apply(false);
this.openAuthenticatedWebSocketCounter = new OpenWebSocketCounter("rpc-authenticated", asnInfoProviderSupplier, clientReleaseManager);
this.openUnauthenticatedWebSocketCounter = new OpenWebSocketCounter("rpc-unauthenticated", asnInfoProviderSupplier, clientReleaseManager);
}
@Override
@@ -14,13 +14,15 @@ import java.util.Optional;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import org.whispersystems.textsecuregcm.asn.AsnInfoProvider;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.controllers.ProvisioningController;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.entities.ProvisioningMessage;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.OpenWebSocketCounter;
import org.whispersystems.textsecuregcm.push.ProvisioningManager;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import org.whispersystems.textsecuregcm.storage.PubSubProtos;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.websocket.session.WebSocketSessionContext;
@@ -48,14 +50,14 @@ public class ProvisioningConnectListener implements WebSocketConnectListener {
private final Duration timeout;
public ProvisioningConnectListener(final ProvisioningManager provisioningManager,
final Supplier<AsnInfoProvider> asnInfoProviderSupplier,
final ClientReleaseManager clientReleaseManager,
final ScheduledExecutorService timeoutExecutor,
final Duration timeout) {
this.provisioningManager = provisioningManager;
this.timeoutExecutor = timeoutExecutor;
this.timeout = timeout;
this.openWebSocketCounter = new OpenWebSocketCounter(MetricsUtil.name(getClass(), "openWebsockets"),
MetricsUtil.name(getClass(), "newConnections"),
MetricsUtil.name(getClass(), "sessionDuration"));
this.openWebSocketCounter = new OpenWebSocketCounter("provisioning", asnInfoProviderSupplier, clientReleaseManager);
}
@Override
@@ -67,7 +69,7 @@ public class ProvisioningConnectListener implements WebSocketConnectListener {
final String provisioningAddress = generateProvisioningAddress();
context.addWebsocketClosedListener((context1, statusCode, reason) -> {
context.addWebsocketClosedListener((_, _, _) -> {
provisioningManager.removeListener(provisioningAddress);
timeoutFuture.cancel(false);
});
@@ -78,7 +80,7 @@ public class ProvisioningConnectListener implements WebSocketConnectListener {
final Optional<byte[]> body = Optional.of(message.getContent().toByteArray());
context.getClient().sendRequest("PUT", "/v1/message", List.of(HeaderUtils.getTimestampHeader()), body)
.whenComplete((ignored, throwable) -> context.getClient().close(1000, "Closed"));
.whenComplete((_, _) -> context.getClient().close(1000, "Closed"));
});
context.getClient().sendRequest("PUT", "/v1/address", List.of(HeaderUtils.getTimestampHeader()),
@@ -247,9 +247,8 @@ public class WebSocketConnection implements DisconnectionRequestListener {
final Timer.Sample sample = Timer.start();
// X-Signal-Key: false must be sent until Android stops assuming it missing means true
return client.sendRequest("PUT", "/api/v1/message",
List.of(HeaderUtils.X_SIGNAL_KEY + ": false", HeaderUtils.getTimestampHeader()), body)
List.of(HeaderUtils.getTimestampHeader()), body)
.whenComplete((ignored, throwable) -> {
if (throwable != null) {
sendFailuresCounter.increment();
@@ -287,7 +286,6 @@ public class WebSocketConnection implements DisconnectionRequestListener {
return result;
})
.thenRun(() -> sample.stop(Timer.builder(SEND_MESSAGE_DURATION_TIMER_NAME)
.publishPercentileHistogram(true)
.tags(platformTag)
.register(Metrics.globalRegistry)));
}
@@ -52,8 +52,6 @@ import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryC
import org.whispersystems.textsecuregcm.storage.AccountLockManager;
import org.whispersystems.textsecuregcm.storage.Accounts;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.ClientPublicKeys;
import org.whispersystems.textsecuregcm.storage.ClientPublicKeysManager;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.DynamoDbRecoveryManager;
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
@@ -210,9 +208,6 @@ public record CommandDependencies(
dynamoDbAsyncClient,
clock);
ClientPublicKeys clientPublicKeys =
new ClientPublicKeys(dynamoDbAsyncClient, configuration.getDynamoDbTables().getClientPublicKeys().getTableName());
Accounts accounts = new Accounts(
clock,
dynamoDbClient,
@@ -281,16 +276,13 @@ public record CommandDependencies(
reportMessageManager, messageDeletionExecutor, Clock.systemUTC());
AccountLockManager accountLockManager = new AccountLockManager(dynamoDbClient,
configuration.getDynamoDbTables().getDeletedAccountsLock().getTableName());
ClientPublicKeysManager clientPublicKeysManager =
new ClientPublicKeysManager(clientPublicKeys, accountLockManager, accountLockExecutor);
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager =
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords);
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
pubsubClient, accountLockManager, keys, messagesManager, profilesManager,
secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
registrationRecoveryPasswordsManager, clientPublicKeysManager, accountLockExecutor, messagePollExecutor,
retryExecutor, clock, configuration.getLinkDeviceSecretConfiguration().secret().value(),
dynamicConfigurationManager);
registrationRecoveryPasswordsManager, accountLockExecutor, messagePollExecutor,
retryExecutor, clock, configuration.getLinkDeviceSecretConfiguration().secret().value());
RateLimiters rateLimiters = RateLimiters.create(dynamicConfigurationManager, rateLimitersCluster, retryExecutor);
final BackupsDb backupsDb =
new BackupsDb(dynamoDbAsyncClient, configuration.getDynamoDbTables().getBackups().getTableName(), clock);
Loaded 100 of 180 files, more files were not shown because too many files have changed in this diff. Show more