mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 10:26:47 +00:00
Compare commits
73
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
240a406964 | ||
|
|
38d25f9a9b | ||
|
|
7b1b6fa1cf | ||
|
|
a3d9af132f | ||
|
|
5d8b566a27 | ||
|
|
8c30a359e7 | ||
|
|
087c2b61ee | ||
|
|
a9117010f9 | ||
|
|
9d980f36b0 | ||
|
|
93515e5a0f | ||
|
|
d550c69f7f | ||
|
|
087e192fac | ||
|
|
63e45563ec | ||
|
|
961d6d0a5c | ||
|
|
f7aacefc40 | ||
|
|
42e920cd5c | ||
|
|
02ff3f2ff4 | ||
|
|
ca2845bcb0 | ||
|
|
80cd5d9ccc | ||
|
|
0eb7db8de5 | ||
|
|
100955a7db | ||
|
|
68814813c3 | ||
|
|
39590f1b28 | ||
|
|
92698efd39 | ||
|
|
b693cb98d0 | ||
|
|
3ed142d0a9 | ||
|
|
581e61a85b | ||
|
|
764b200289 | ||
|
|
26503dffdf | ||
|
|
b284e95394 | ||
|
|
b2211de8d8 | ||
|
|
1bb0eb0e70 | ||
|
|
0a1161048f | ||
|
|
7a6ce00fed | ||
|
|
c0aa9ced8d | ||
|
|
6b36df3f8f | ||
|
|
df3caeb04a | ||
|
|
0e267509da | ||
|
|
bbe41278ed | ||
|
|
d91a6b0c38 | ||
|
|
694a93db6d | ||
|
|
2f2dec87b1 | ||
|
|
098288c290 | ||
|
|
ab2e6bb9a3 | ||
|
|
513f19370a | ||
|
|
e20a4c1f77 | ||
|
|
946a486c4b | ||
|
|
78b40397f9 | ||
|
|
48e8d1c12f | ||
|
|
b115e95da4 | ||
|
|
ab0892cc41 | ||
|
|
e25291c74c | ||
|
|
0e552bd602 | ||
|
|
e9b3e15556 | ||
|
|
237d0fd4e2 | ||
|
|
50bd30fb1f | ||
|
|
9fb4e2d272 | ||
|
|
3e51366921 | ||
|
|
2d184b1ab6 | ||
|
|
befcdf55fe | ||
|
|
ba12d39121 | ||
|
|
bf0f553ced | ||
|
|
cd68a674bb | ||
|
|
315fc00eac | ||
|
|
6142dcc7e6 | ||
|
|
c47141ffda | ||
|
|
6c8566db60 | ||
|
|
aa60fae3b1 | ||
|
|
8cb9c60a3c | ||
|
|
dd7a20a774 | ||
|
|
374fe087bc | ||
|
|
11691c3122 | ||
|
|
8d129b10ca |
No files matched your search
@@ -10,6 +10,7 @@ import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.signal.integration.config.Config;
|
||||
import org.whispersystems.textsecuregcm.metrics.NoopAwsSdkMetricPublisher;
|
||||
import org.whispersystems.textsecuregcm.registration.VerificationSession;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswords;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
@@ -30,9 +31,11 @@ public class IntegrationTools {
|
||||
public static IntegrationTools create(final Config config) {
|
||||
final AwsCredentialsProvider credentialsProvider = DefaultCredentialsProvider.builder().build();
|
||||
|
||||
final DynamoDbAsyncClient dynamoDbAsyncClient = config.dynamoDbClient().buildAsyncClient(credentialsProvider);
|
||||
final DynamoDbAsyncClient dynamoDbAsyncClient =
|
||||
config.dynamoDbClient().buildAsyncClient(credentialsProvider, new NoopAwsSdkMetricPublisher());
|
||||
|
||||
final DynamoDbClient dynamoDbClient = config.dynamoDbClient().buildSyncClient(credentialsProvider);
|
||||
final DynamoDbClient dynamoDbClient =
|
||||
config.dynamoDbClient().buildSyncClient(credentialsProvider, new NoopAwsSdkMetricPublisher());
|
||||
|
||||
final RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
|
||||
config.dynamoDbTables().registrationRecovery(), Duration.ofDays(1), dynamoDbClient, dynamoDbAsyncClient);
|
||||
|
||||
@@ -126,7 +126,7 @@ public class TestUser {
|
||||
}
|
||||
|
||||
public AccountAttributes accountAttributes() {
|
||||
return new AccountAttributes(true, registrationId, pniRegistrationId, "".getBytes(StandardCharsets.UTF_8), "", true, new Device.DeviceCapabilities(false, false, false, false, false))
|
||||
return new AccountAttributes(true, registrationId, pniRegistrationId, "".getBytes(StandardCharsets.UTF_8), "", true, new Device.DeviceCapabilities(false, false, false, false))
|
||||
.withUnidentifiedAccessKey(unidentifiedAccessKey)
|
||||
.withRecoveryPassword(registrationPassword);
|
||||
}
|
||||
|
||||
@@ -260,7 +260,7 @@ done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties"
|
||||
if [ -n "$wrapperSha256Sum" ]; then
|
||||
wrapperSha256Result=false
|
||||
if command -v sha256sum > /dev/null; then
|
||||
if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c > /dev/null 2>&1; then
|
||||
if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c - > /dev/null 2>&1; then
|
||||
wrapperSha256Result=true
|
||||
fi
|
||||
elif command -v shasum > /dev/null; then
|
||||
|
||||
@@ -63,7 +63,7 @@
|
||||
<luajava.version>3.4.0</luajava.version>
|
||||
<micrometer.version>1.13.2</micrometer.version>
|
||||
<netty.version>4.1.111.Final</netty.version>
|
||||
<protobuf.version>3.25.2</protobuf.version> <!-- should be kept in sync with the value from Google libraries-bom -->
|
||||
<protobuf.version>3.25.5</protobuf.version> <!-- must be greater than or equal to the value from Google libraries-bom, see https://protobuf.dev/support/cross-version-runtime-guarantee/ -->
|
||||
<pushy.version>0.15.4</pushy.version>
|
||||
<reactive.grpc.version>1.2.4</reactive.grpc.version>
|
||||
<reactor-bom.version>2023.0.8</reactor-bom.version> <!-- 3.6.x, see https://github.com/reactor/reactor#bom-versioning-scheme -->
|
||||
|
||||
@@ -8,6 +8,8 @@ braintree.privateKey: unset
|
||||
googlePlayBilling.credentialsJson: |
|
||||
{ "json": true }
|
||||
|
||||
appleAppStore.encodedKey: unset
|
||||
|
||||
directoryV2.client.userAuthenticationTokenSharedSecret: abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG= # base64-encoded secret shared with CDS to generate auth tokens for Signal users
|
||||
directoryV2.client.userIdTokenSharedSecret: bbcdefghijklmnopqrstuvwxyz0123456789ABCDEFG= # base64-encoded secret shared with CDS to generate auth identity tokens for Signal users
|
||||
|
||||
|
||||
@@ -81,6 +81,18 @@ googlePlayBilling:
|
||||
applicationName: test
|
||||
productIdToLevel: {}
|
||||
|
||||
appleAppStore:
|
||||
env: SANDBOX
|
||||
bundleId: bundle.name
|
||||
appAppleId: 12345
|
||||
issuerId: abcdefg
|
||||
keyId: abcdefg
|
||||
encodedKey: secret://appleAppStore.encodedKey
|
||||
subscriptionGroupId: example_subscriptionGroupId
|
||||
productIdToLevel: {}
|
||||
appleRootCerts: []
|
||||
|
||||
|
||||
dynamoDbClient:
|
||||
region: us-west-2 # AWS Region
|
||||
|
||||
@@ -90,6 +102,7 @@ dynamoDbTables:
|
||||
phoneNumberTableName: Example_Accounts_PhoneNumbers
|
||||
phoneNumberIdentifierTableName: Example_Accounts_PhoneNumberIdentifiers
|
||||
usernamesTableName: Example_Accounts_Usernames
|
||||
usedLinkDeviceTokensTableName: Example_Accounts_UsedLinkDeviceTokens
|
||||
backups:
|
||||
tableName: Example_Backups
|
||||
clientReleases:
|
||||
@@ -150,9 +163,8 @@ cacheCluster: # Redis server configuration for cache cluster
|
||||
clientPresenceCluster: # Redis server configuration for client presence cluster
|
||||
configurationUri: redis://redis.example.com:6379/
|
||||
|
||||
provisioning:
|
||||
pubsub: # Redis server configuration for pubsub cluster
|
||||
uri: redis://redis.example.com:6379/
|
||||
pubsub: # Redis server configuration for pubsub cluster
|
||||
uri: redis://redis.example.com:6379/
|
||||
|
||||
pushSchedulerCluster: # Redis server configuration for push scheduler cluster
|
||||
configurationUri: redis://redis.example.com:6379/
|
||||
|
||||
+14
-2
@@ -15,6 +15,7 @@
|
||||
<java-uuid-generator.version>5.1.0</java-uuid-generator.version>
|
||||
<sqlite4java.version>1.0.392</sqlite4java.version>
|
||||
<google-androidpublisher.version>v3-rev20240820-2.0.0</google-androidpublisher.version>
|
||||
<storekit.version>3.1.0</storekit.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
@@ -23,7 +24,18 @@
|
||||
<artifactId>google-api-services-androidpublisher</artifactId>
|
||||
<version>${google-androidpublisher.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.apple.itunes.storekit</groupId>
|
||||
<artifactId>app-store-server-library</artifactId>
|
||||
<version>${storekit.version}</version>
|
||||
<exclusions>
|
||||
<!-- conflicts with okio-jvm from apollo-api-jvm -->
|
||||
<exclusion>
|
||||
<groupId>com.squareup.okio</groupId>
|
||||
<artifactId>okio-jvm</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.swagger.core.v3</groupId>
|
||||
<artifactId>swagger-jaxrs2</artifactId>
|
||||
@@ -506,7 +518,7 @@
|
||||
<dependency>
|
||||
<groupId>com.apollographql.apollo3</groupId>
|
||||
<artifactId>apollo-api-jvm</artifactId>
|
||||
<version>3.8.2</version>
|
||||
<version>3.8.5</version>
|
||||
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
|
||||
+14
-5
@@ -15,6 +15,7 @@ import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import org.whispersystems.textsecuregcm.attachments.TusConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.ApnConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.AppleAppStoreConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.ArtServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.AwsAttachmentsConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.AwsCredentialsProviderFactory;
|
||||
@@ -22,7 +23,6 @@ import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.BraintreeConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.Cdn3StorageManagerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.CdnConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.ClientCdnConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.ClientReleaseConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.DatadogConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.DefaultAwsCredentialsFactory;
|
||||
@@ -33,6 +33,7 @@ import org.whispersystems.textsecuregcm.configuration.DynamoDbClientFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.DynamoDbTables;
|
||||
import org.whispersystems.textsecuregcm.configuration.ExternalRequestFilterConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.FaultTolerantRedisClusterFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.FaultTolerantRedisClientFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.FcmConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.GcpAttachmentsConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.GenericZkConfig;
|
||||
@@ -46,7 +47,6 @@ import org.whispersystems.textsecuregcm.configuration.MessageCacheConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.NoiseWebSocketTunnelConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.PaymentsServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.ProvisioningConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.RegistrationServiceClientFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.RemoteConfigConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.ReportMessageConfiguration;
|
||||
@@ -94,6 +94,11 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private GooglePlayBillingConfiguration googlePlayBilling;
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private AppleAppStoreConfiguration appleAppStore;
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
@@ -137,7 +142,7 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private ProvisioningConfiguration provisioning;
|
||||
private FaultTolerantRedisClientFactory pubsub;
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@@ -368,6 +373,10 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return googlePlayBilling;
|
||||
}
|
||||
|
||||
public AppleAppStoreConfiguration getAppleAppStore() {
|
||||
return appleAppStore;
|
||||
}
|
||||
|
||||
public DynamoDbClientFactory getDynamoDbClientConfiguration() {
|
||||
return dynamoDbClient;
|
||||
}
|
||||
@@ -400,8 +409,8 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return cacheCluster;
|
||||
}
|
||||
|
||||
public ProvisioningConfiguration getProvisioningConfiguration() {
|
||||
return provisioning;
|
||||
public FaultTolerantRedisClientFactory getRedisPubSubConfiguration() {
|
||||
return pubsub;
|
||||
}
|
||||
|
||||
public SecureValueRecovery2Configuration getSvr2Configuration() {
|
||||
|
||||
@@ -113,7 +113,6 @@ import org.whispersystems.textsecuregcm.controllers.ArtController;
|
||||
import org.whispersystems.textsecuregcm.controllers.AttachmentControllerV2;
|
||||
import org.whispersystems.textsecuregcm.controllers.AttachmentControllerV3;
|
||||
import org.whispersystems.textsecuregcm.controllers.AttachmentControllerV4;
|
||||
import org.whispersystems.textsecuregcm.controllers.OneTimeDonationController;
|
||||
import org.whispersystems.textsecuregcm.controllers.CallLinkController;
|
||||
import org.whispersystems.textsecuregcm.controllers.CallRoutingController;
|
||||
import org.whispersystems.textsecuregcm.controllers.CertificateController;
|
||||
@@ -125,6 +124,7 @@ import org.whispersystems.textsecuregcm.controllers.KeepAliveController;
|
||||
import org.whispersystems.textsecuregcm.controllers.KeyTransparencyController;
|
||||
import org.whispersystems.textsecuregcm.controllers.KeysController;
|
||||
import org.whispersystems.textsecuregcm.controllers.MessageController;
|
||||
import org.whispersystems.textsecuregcm.controllers.OneTimeDonationController;
|
||||
import org.whispersystems.textsecuregcm.controllers.PaymentsController;
|
||||
import org.whispersystems.textsecuregcm.controllers.ProfileController;
|
||||
import org.whispersystems.textsecuregcm.controllers.ProvisioningController;
|
||||
@@ -167,6 +167,7 @@ import org.whispersystems.textsecuregcm.keytransparency.KeyTransparencyServiceCl
|
||||
import org.whispersystems.textsecuregcm.limits.CardinalityEstimator;
|
||||
import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor;
|
||||
import org.whispersystems.textsecuregcm.limits.PushChallengeManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitByIpFilter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitChallengeManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper;
|
||||
@@ -181,25 +182,26 @@ import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper
|
||||
import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.ServerRejectedExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.SubscriptionProcessorExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsApplicationEventListener;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsHttpChannelListener;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.MicrometerAwsSdkMetricPublisher;
|
||||
import org.whispersystems.textsecuregcm.metrics.ReportedMessageMetricsListener;
|
||||
import org.whispersystems.textsecuregcm.metrics.TrafficSource;
|
||||
import org.whispersystems.textsecuregcm.providers.MultiRecipientMessageProvider;
|
||||
import org.whispersystems.textsecuregcm.providers.RedisClusterHealthCheck;
|
||||
import org.whispersystems.textsecuregcm.push.APNSender;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.FcmSender;
|
||||
import org.whispersystems.textsecuregcm.push.MessageSender;
|
||||
import org.whispersystems.textsecuregcm.push.ProvisioningManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
import org.whispersystems.textsecuregcm.redis.ConnectionEventLogger;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
|
||||
import org.whispersystems.textsecuregcm.s3.PolicySigner;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
@@ -208,7 +210,6 @@ import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2
|
||||
import org.whispersystems.textsecuregcm.spam.ChallengeConstraintChecker;
|
||||
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
|
||||
import org.whispersystems.textsecuregcm.spam.RegistrationRecoveryChecker;
|
||||
import org.whispersystems.textsecuregcm.spam.ReportSpamTokenProvider;
|
||||
import org.whispersystems.textsecuregcm.spam.SpamChecker;
|
||||
import org.whispersystems.textsecuregcm.spam.SpamFilter;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountLockManager;
|
||||
@@ -242,6 +243,7 @@ import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Subscriptions;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationSessions;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
|
||||
@@ -261,12 +263,9 @@ import org.whispersystems.textsecuregcm.workers.BackupMetricsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CertificateCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CheckDynamicConfigurationCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.DiscardPushNotificationExperimentSamplesCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.FinishPushNotificationExperimentCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.IdleDeviceNotificationSchedulerFactory;
|
||||
import org.whispersystems.textsecuregcm.workers.MessagePersisterServiceCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.NotifyIdleDevicesWithMessagesExperimentFactory;
|
||||
import org.whispersystems.textsecuregcm.workers.NotifyIdleDevicesWithoutMessagesCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.NotifyIdleDevicesCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ProcessScheduledJobsServiceCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.RemoveExpiredAccountsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.RemoveExpiredBackupsCommand;
|
||||
@@ -276,7 +275,6 @@ import org.whispersystems.textsecuregcm.workers.ScheduledApnPushNotificationSend
|
||||
import org.whispersystems.textsecuregcm.workers.ServerVersionCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.SetRequestLoggingEnabledTask;
|
||||
import org.whispersystems.textsecuregcm.workers.SetUserDiscoverabilityCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.StartPushNotificationExperimentCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.UnlinkDeviceCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ZkParamsCommand;
|
||||
import org.whispersystems.websocket.WebSocketResourceProviderFactory;
|
||||
@@ -330,25 +328,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
bootstrap.addCommand(new RemoveExpiredBackupsCommand(Clock.systemUTC()));
|
||||
bootstrap.addCommand(new BackupMetricsCommand(Clock.systemUTC()));
|
||||
bootstrap.addCommand(new RemoveExpiredLinkedDevicesCommand());
|
||||
bootstrap.addCommand(new NotifyIdleDevicesWithoutMessagesCommand());
|
||||
bootstrap.addCommand(new NotifyIdleDevicesCommand());
|
||||
bootstrap.addCommand(new ProcessScheduledJobsServiceCommand("process-idle-device-notification-jobs",
|
||||
"Processes scheduled jobs to send notifications to idle devices",
|
||||
new IdleDeviceNotificationSchedulerFactory()));
|
||||
|
||||
bootstrap.addCommand(
|
||||
new StartPushNotificationExperimentCommand<>("start-notify-idle-devices-with-messages-experiment",
|
||||
"Start an experiment to send push notifications to idle devices with pending messages",
|
||||
new NotifyIdleDevicesWithMessagesExperimentFactory()));
|
||||
|
||||
bootstrap.addCommand(
|
||||
new FinishPushNotificationExperimentCommand<>("finish-notify-idle-devices-with-messages-experiment",
|
||||
"Finish an experiment to send push notifications to idle devices with pending messages",
|
||||
new NotifyIdleDevicesWithMessagesExperimentFactory()));
|
||||
|
||||
bootstrap.addCommand(
|
||||
new DiscardPushNotificationExperimentSamplesCommand("discard-notify-idle-devices-with-messages-samples",
|
||||
"Discard samples from the \"notify idle devices with messages\" experiment",
|
||||
new NotifyIdleDevicesWithMessagesExperimentFactory()));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -394,10 +377,15 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
BankMandateTranslator bankMandateTranslator = new BankMandateTranslator(headerControlledResourceBundleLookup);
|
||||
|
||||
environment.lifecycle().manage(new ManagedAwsCrt());
|
||||
DynamoDbAsyncClient dynamoDbAsyncClient = config.getDynamoDbClientConfiguration()
|
||||
.buildAsyncClient(awsCredentialsProvider);
|
||||
|
||||
DynamoDbClient dynamoDbClient = config.getDynamoDbClientConfiguration().buildSyncClient(awsCredentialsProvider);
|
||||
final ExecutorService awsSdkMetricsExecutor = environment.lifecycle()
|
||||
.virtualExecutorService(name(getClass(), "awsSdkMetrics-%d"));
|
||||
|
||||
final DynamoDbAsyncClient dynamoDbAsyncClient = config.getDynamoDbClientConfiguration()
|
||||
.buildAsyncClient(awsCredentialsProvider, new MicrometerAwsSdkMetricPublisher(awsSdkMetricsExecutor, "dynamoDbAsync"));
|
||||
|
||||
final DynamoDbClient dynamoDbClient = config.getDynamoDbClientConfiguration()
|
||||
.buildSyncClient(awsCredentialsProvider, new MicrometerAwsSdkMetricPublisher(awsSdkMetricsExecutor, "dynamoDbSync"));
|
||||
|
||||
BlockingQueue<Runnable> messageDeletionQueue = new LinkedBlockingQueue<>();
|
||||
Metrics.gaugeCollectionSize(name(getClass(), "messageDeletionQueueSize"), Collections.emptyList(),
|
||||
@@ -416,7 +404,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getDynamoDbTables().getAccounts().getPhoneNumberTableName(),
|
||||
config.getDynamoDbTables().getAccounts().getPhoneNumberIdentifierTableName(),
|
||||
config.getDynamoDbTables().getAccounts().getUsernamesTableName(),
|
||||
config.getDynamoDbTables().getDeletedAccounts().getTableName());
|
||||
config.getDynamoDbTables().getDeletedAccounts().getTableName(),
|
||||
config.getDynamoDbTables().getAccounts().getUsedLinkDeviceTokensTableName());
|
||||
ClientReleases clientReleases = new ClientReleases(dynamoDbAsyncClient,
|
||||
config.getDynamoDbTables().getClientReleases().getTableName());
|
||||
PhoneNumberIdentifiers phoneNumberIdentifiers = new PhoneNumberIdentifiers(dynamoDbClient,
|
||||
@@ -459,18 +448,21 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.build();
|
||||
ConnectionEventLogger.logConnectionEvents(sharedClientResources);
|
||||
|
||||
FaultTolerantRedisCluster cacheCluster = config.getCacheClusterConfiguration()
|
||||
FaultTolerantRedisClusterClient cacheCluster = config.getCacheClusterConfiguration()
|
||||
.build("main_cache", sharedClientResources.mutate());
|
||||
FaultTolerantRedisCluster messagesCluster =
|
||||
FaultTolerantRedisClusterClient messagesCluster =
|
||||
config.getMessageCacheConfiguration().getRedisClusterConfiguration()
|
||||
.build("messages", sharedClientResources.mutate());
|
||||
FaultTolerantRedisCluster clientPresenceCluster = config.getClientPresenceClusterConfiguration()
|
||||
FaultTolerantRedisClusterClient clientPresenceCluster = config.getClientPresenceClusterConfiguration()
|
||||
.build("client_presence", sharedClientResources.mutate());
|
||||
FaultTolerantRedisCluster pushSchedulerCluster = config.getPushSchedulerCluster().build("push_scheduler",
|
||||
FaultTolerantRedisClusterClient pushSchedulerCluster = config.getPushSchedulerCluster().build("push_scheduler",
|
||||
sharedClientResources.mutate());
|
||||
FaultTolerantRedisCluster rateLimitersCluster = config.getRateLimitersCluster().build("rate_limiters",
|
||||
FaultTolerantRedisClusterClient rateLimitersCluster = config.getRateLimitersCluster().build("rate_limiters",
|
||||
sharedClientResources.mutate());
|
||||
|
||||
FaultTolerantRedisClient pubsubClient =
|
||||
config.getRedisPubSubConfiguration().build("pubsub", sharedClientResources);
|
||||
|
||||
final BlockingQueue<Runnable> keyspaceNotificationDispatchQueue = new ArrayBlockingQueue<>(100_000);
|
||||
Metrics.gaugeCollectionSize(name(getClass(), "keyspaceNotificationDispatchQueueSize"), Collections.emptyList(),
|
||||
keyspaceNotificationDispatchQueue);
|
||||
@@ -584,7 +576,11 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.virtualExecutorService(name(getClass(), "keyTransparency-%d"));
|
||||
ExecutorService googlePlayBillingExecutor = environment.lifecycle()
|
||||
.virtualExecutorService(name(getClass(), "googlePlayBilling-%d"));
|
||||
ExecutorService appleAppStoreExecutor = environment.lifecycle()
|
||||
.virtualExecutorService(name(getClass(), "appleAppStore-%d"));
|
||||
|
||||
ScheduledExecutorService appleAppStoreRetryExecutor = environment.lifecycle()
|
||||
.scheduledExecutorService(name(getClass(), "appleAppStoreRetry-%d")).threads(1).build();
|
||||
ScheduledExecutorService subscriptionProcessorRetryExecutor = environment.lifecycle()
|
||||
.scheduledExecutorService(name(getClass(), "subscriptionProcessorRetry-%d")).threads(1).build();
|
||||
ScheduledExecutorService cloudflareTurnRetryExecutor = environment.lifecycle()
|
||||
@@ -646,11 +642,11 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
ClientPublicKeysManager clientPublicKeysManager =
|
||||
new ClientPublicKeysManager(clientPublicKeys, accountLockManager, accountLockExecutor);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
accountLockManager, keysManager, messagesManager, profilesManager,
|
||||
pubsubClient, accountLockManager, keysManager, messagesManager, profilesManager,
|
||||
secureStorageClient, secureValueRecovery2Client,
|
||||
clientPresenceManager,
|
||||
registrationRecoveryPasswordsManager, clientPublicKeysManager, accountLockExecutor, clientPresenceExecutor,
|
||||
clock, dynamicConfigurationManager);
|
||||
clock, config.getLinkDeviceSecretConfiguration().secret().value(), dynamicConfigurationManager);
|
||||
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs);
|
||||
APNSender apnSender = new APNSender(apnSenderExecutor, config.getApnConfiguration());
|
||||
FcmSender fcmSender = new FcmSender(fcmSenderExecutor, config.getFcmConfiguration().credentials().value());
|
||||
@@ -660,9 +656,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new PushNotificationManager(accountsManager, apnSender, fcmSender, pushNotificationScheduler);
|
||||
RateLimiters rateLimiters = RateLimiters.createAndValidate(config.getLimitsConfiguration(),
|
||||
dynamicConfigurationManager, rateLimitersCluster);
|
||||
ProvisioningManager provisioningManager = new ProvisioningManager(
|
||||
config.getProvisioningConfiguration().pubsub().build(sharedClientResources),
|
||||
config.getProvisioningConfiguration().circuitBreaker());
|
||||
ProvisioningManager provisioningManager = new ProvisioningManager(pubsubClient);
|
||||
IssuedReceiptsManager issuedReceiptsManager = new IssuedReceiptsManager(
|
||||
config.getDynamoDbTables().getIssuedReceipts().getTableName(),
|
||||
config.getDynamoDbTables().getIssuedReceipts().getExpiration(),
|
||||
@@ -752,6 +746,13 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getGooglePlayBilling().applicationName(),
|
||||
config.getGooglePlayBilling().productIdToLevel(),
|
||||
googlePlayBillingExecutor);
|
||||
AppleAppStoreManager appleAppStoreManager = new AppleAppStoreManager(
|
||||
config.getAppleAppStore().env(), config.getAppleAppStore().bundleId(), config.getAppleAppStore().appAppleId(),
|
||||
config.getAppleAppStore().issuerId(), config.getAppleAppStore().keyId(),
|
||||
config.getAppleAppStore().encodedKey().value(), config.getAppleAppStore().subscriptionGroupId(),
|
||||
config.getAppleAppStore().productIdToLevel(),
|
||||
config.getAppleAppStore().appleRootCerts(),
|
||||
config.getAppleAppStore().retry(), appleAppStoreExecutor, appleAppStoreRetryExecutor);
|
||||
|
||||
environment.lifecycle().manage(apnSender);
|
||||
environment.lifecycle().manage(pushNotificationScheduler);
|
||||
@@ -763,6 +764,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
environment.lifecycle().manage(keyTransparencyServiceClient);
|
||||
environment.lifecycle().manage(clientReleaseManager);
|
||||
environment.lifecycle().manage(virtualThreadPinEventMonitor);
|
||||
environment.lifecycle().manage(accountsManager);
|
||||
|
||||
final RegistrationCaptchaManager registrationCaptchaManager = new RegistrationCaptchaManager(captchaChecker);
|
||||
|
||||
@@ -973,6 +975,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
final List<Filter> filters = new ArrayList<>();
|
||||
filters.add(remoteDeprecationFilter);
|
||||
filters.add(new RemoteAddressFilter());
|
||||
filters.add(new TimestampResponseFilter());
|
||||
|
||||
for (Filter filter : filters) {
|
||||
environment.servlets()
|
||||
@@ -1003,6 +1006,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
environment.jersey().register(new BufferingInterceptor());
|
||||
environment.jersey().register(new VirtualExecutorServiceProvider("managed-async-virtual-thread-"));
|
||||
environment.jersey().register(new RateLimitByIpFilter(rateLimiters));
|
||||
environment.jersey().register(new RequestStatisticsFilter(TrafficSource.HTTP));
|
||||
environment.jersey().register(MultiRecipientMessageProvider.class);
|
||||
environment.jersey().register(new AuthDynamicFeature(accountAuthFilter));
|
||||
@@ -1021,10 +1025,12 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
clientReleaseManager, messageDeliveryLoopMonitor));
|
||||
webSocketEnvironment.jersey()
|
||||
.register(new WebsocketRefreshApplicationEventListener(accountsManager, clientPresenceManager));
|
||||
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(clientPresenceManager));
|
||||
webSocketEnvironment.jersey().register(new TimestampResponseFilter());
|
||||
|
||||
final List<SpamFilter> spamFilters = ServiceLoader.load(SpamFilter.class)
|
||||
.stream()
|
||||
@@ -1046,12 +1052,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
if (spamFilter.isEmpty()) {
|
||||
log.warn("No spam filters installed");
|
||||
}
|
||||
final ReportSpamTokenProvider reportSpamTokenProvider = spamFilter
|
||||
.map(SpamFilter::getReportSpamTokenProvider)
|
||||
.orElseGet(() -> {
|
||||
log.warn("No spam-reporting token providers found; using default (no-op) provider as a default");
|
||||
return ReportSpamTokenProvider.noop();
|
||||
});
|
||||
final SpamChecker spamChecker = spamFilter
|
||||
.map(SpamFilter::getSpamChecker)
|
||||
.orElseGet(() -> {
|
||||
@@ -1111,8 +1111,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getDeliveryCertificate().ecPrivateKey(), config.getDeliveryCertificate().expiresDays()),
|
||||
zkAuthOperations, callingGenericZkSecretParams, clock),
|
||||
new ChallengeController(rateLimitChallengeManager, challengeConstraintChecker),
|
||||
new DeviceController(config.getLinkDeviceSecretConfiguration().secret().value(), accountsManager,
|
||||
clientPublicKeysManager, rateLimiters, rateLimitersCluster, config.getMaxDevices(), clock),
|
||||
new DeviceController(accountsManager, clientPublicKeysManager, rateLimiters, config.getMaxDevices()),
|
||||
new DirectoryV2Controller(directoryV2CredentialsGenerator),
|
||||
new DonationController(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(),
|
||||
ReceiptCredentialPresentation::new),
|
||||
@@ -1120,7 +1119,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new KeyTransparencyController(keyTransparencyServiceClient),
|
||||
new MessageController(rateLimiters, messageByteLimitCardinalityEstimator, messageSender, receiptSender,
|
||||
accountsManager, messagesManager, pushNotificationManager, pushNotificationScheduler, reportMessageManager,
|
||||
multiRecipientMessageExecutor, messageDeliveryScheduler, reportSpamTokenProvider, clientReleaseManager,
|
||||
multiRecipientMessageExecutor, messageDeliveryScheduler, clientReleaseManager,
|
||||
dynamicConfigurationManager, zkSecretParams, spamChecker, messageMetrics, messageDeliveryLoopMonitor,
|
||||
Clock.systemUTC()),
|
||||
new PaymentsController(currencyManager, paymentsCredentialsGenerator),
|
||||
@@ -1143,10 +1142,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
);
|
||||
if (config.getSubscription() != null && config.getOneTimeDonations() != null) {
|
||||
SubscriptionManager subscriptionManager = new SubscriptionManager(subscriptions,
|
||||
List.of(stripeManager, braintreeManager, googlePlayBillingManager),
|
||||
List.of(stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager),
|
||||
zkReceiptOperations, issuedReceiptsManager);
|
||||
commonControllers.add(new SubscriptionController(clock, config.getSubscription(), config.getOneTimeDonations(),
|
||||
subscriptionManager, stripeManager, braintreeManager, googlePlayBillingManager,
|
||||
subscriptionManager, stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager,
|
||||
profileBadgeConverter, resourceBundleLevelTranslator, bankMandateTranslator));
|
||||
commonControllers.add(new OneTimeDonationController(clock, config.getOneTimeDonations(), stripeManager, braintreeManager,
|
||||
zkReceiptOperations, issuedReceiptsManager, oneTimeDonationsManager));
|
||||
@@ -1163,6 +1162,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
provisioningEnvironment.setConnectListener(new ProvisioningConnectListener(provisioningManager));
|
||||
provisioningEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET, clientReleaseManager));
|
||||
provisioningEnvironment.jersey().register(new KeepAliveController(clientPresenceManager));
|
||||
provisioningEnvironment.jersey().register(new TimestampResponseFilter());
|
||||
|
||||
registerCorsFilter(environment);
|
||||
registerExceptionMappers(environment, webSocketEnvironment, provisioningEnvironment);
|
||||
@@ -1213,7 +1213,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new ImpossiblePhoneNumberExceptionMapper(),
|
||||
new NonNormalizedPhoneNumberExceptionMapper(),
|
||||
new RegistrationServiceSenderExceptionMapper(),
|
||||
new SubscriptionProcessorExceptionMapper(),
|
||||
new SubscriptionExceptionMapper(),
|
||||
new JsonMappingExceptionMapper()
|
||||
).forEach(exceptionMapper -> {
|
||||
|
||||
+26
-15
@@ -8,15 +8,16 @@ package org.whispersystems.textsecuregcm.calls.routing;
|
||||
import com.maxmind.geoip2.DatabaseReader;
|
||||
import com.maxmind.geoip2.exception.GeoIp2Exception;
|
||||
import com.maxmind.geoip2.model.CityResponse;
|
||||
import org.apache.commons.lang3.tuple.Triple;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import javax.annotation.Nonnull;
|
||||
import java.io.IOException;
|
||||
import java.net.Inet6Address;
|
||||
import java.net.InetAddress;
|
||||
import java.util.*;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
@@ -58,6 +59,7 @@ public class TurnCallRouter {
|
||||
* @param aci aci of client
|
||||
* @param clientAddress IP address to base routing on
|
||||
* @param instanceLimit max instances to return options for
|
||||
* @return Up to two * instanceLimit options, half in ipv4, half in ipv6
|
||||
*/
|
||||
public TurnServerOptions getRoutingFor(
|
||||
@Nonnull final UUID aci,
|
||||
@@ -121,8 +123,7 @@ public class TurnCallRouter {
|
||||
List<String> urlsWithIps = getUrlsForInstances(
|
||||
selectInstances(
|
||||
datacenters,
|
||||
instanceLimit,
|
||||
(clientAddress.get() instanceof Inet6Address)
|
||||
instanceLimit
|
||||
));
|
||||
return new TurnServerOptions(hostname, urlsWithIps, minimalRandomUrls());
|
||||
}
|
||||
@@ -134,25 +135,22 @@ public class TurnCallRouter {
|
||||
.toList();
|
||||
}
|
||||
|
||||
private List<String> selectInstances(List<String> datacenters, int limit, boolean preferV6) {
|
||||
if(datacenters.isEmpty() || limit == 0) {
|
||||
// returns balanced number of instances across provided datacenters, prioritizing the datacenters earlier in the list
|
||||
private List<String> selectInstances(List<String> datacenters, int instanceLimit) {
|
||||
if(datacenters.isEmpty() || instanceLimit == 0) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
int numV6 = preferV6 ? (limit - limit / 3) : limit / 3;
|
||||
int numV4 = limit - numV6;
|
||||
|
||||
CallDnsRecords dnsRecords = this.callDnsRecords.get();
|
||||
List<InetAddress> ipv4Selection = datacenters.stream()
|
||||
.flatMap(dc -> randomNOf(dnsRecords.aByRegion().get(dc), limit, stableSelect).stream())
|
||||
List<List<InetAddress>> ipv4Options = datacenters.stream()
|
||||
.map(dc -> randomNOf(dnsRecords.aByRegion().get(dc), instanceLimit, stableSelect))
|
||||
.toList();
|
||||
List<InetAddress> ipv6Selection = datacenters.stream()
|
||||
.flatMap(dc -> randomNOf(dnsRecords.aaaaByRegion().get(dc), limit, stableSelect).stream())
|
||||
List<List<InetAddress>> ipv6Options = datacenters.stream()
|
||||
.map(dc -> randomNOf(dnsRecords.aaaaByRegion().get(dc), instanceLimit, stableSelect))
|
||||
.toList();
|
||||
|
||||
// increase numV4 if not enough v6 options. vice-versa is also true
|
||||
numV4 = Math.max(numV4, limit - ipv6Selection.size());
|
||||
ipv4Selection = ipv4Selection.stream().limit(numV4).toList();
|
||||
ipv6Selection = ipv6Selection.stream().limit(limit - ipv4Selection.size()).toList();
|
||||
List<InetAddress> ipv4Selection = selectFromOptions(ipv4Options, instanceLimit);
|
||||
List<InetAddress> ipv6Selection = selectFromOptions(ipv6Options, instanceLimit);
|
||||
|
||||
return Stream.concat(
|
||||
ipv4Selection.stream().map(InetAddress::getHostAddress),
|
||||
@@ -161,6 +159,19 @@ public class TurnCallRouter {
|
||||
).toList();
|
||||
}
|
||||
|
||||
private static List<InetAddress> selectFromOptions(List<List<InetAddress>> recordsByDc, int instanceLimit) {
|
||||
return IntStream.range(0, recordsByDc.size())
|
||||
.mapToObj(dcIndex -> IntStream.range(0, recordsByDc.get(dcIndex).size())
|
||||
.mapToObj(addressIndex -> Triple.of(addressIndex, dcIndex, recordsByDc.get(dcIndex).get(addressIndex))))
|
||||
.flatMap(i -> i)
|
||||
.sorted(Comparator.comparingInt((Triple<Integer, Integer, InetAddress> t) -> t.getLeft())
|
||||
.thenComparingInt(Triple::getMiddle))
|
||||
.limit(instanceLimit)
|
||||
.sorted(Comparator.comparingInt(Triple::getMiddle))
|
||||
.map(Triple::getRight)
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static <E> List<E> randomNOf(List<E> values, int n, boolean stableSelect) {
|
||||
return stableSelect ? Util.randomNOfStable(values, n) : Util.randomNOfShuffled(values, n);
|
||||
}
|
||||
|
||||
+7
-1
@@ -76,7 +76,13 @@ public class AssessmentResult {
|
||||
if (!solved) {
|
||||
return false;
|
||||
}
|
||||
return this.actualScore >= scoreThreshold.orElse(this.defaultScoreThreshold);
|
||||
// Since HCaptcha scores are truncated to 2 decimal places, we can multiply by 100 and round to the nearest int for
|
||||
// comparison instead of floating point comparisons
|
||||
return normalizedIntScore(this.actualScore) >= normalizedIntScore(scoreThreshold.orElse(this.defaultScoreThreshold));
|
||||
}
|
||||
|
||||
private static int normalizedIntScore(final float score) {
|
||||
return Math.round(score * 100);
|
||||
}
|
||||
|
||||
public String getScoreString() {
|
||||
|
||||
+2
-7
@@ -6,8 +6,7 @@
|
||||
package org.whispersystems.textsecuregcm.captcha;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
@@ -22,14 +21,11 @@ public class HCaptchaResponse {
|
||||
boolean success;
|
||||
|
||||
@JsonProperty(value = "challenge_ts")
|
||||
Duration challengeTs;
|
||||
Instant challengeTs;
|
||||
|
||||
@JsonProperty
|
||||
String hostname;
|
||||
|
||||
@JsonProperty
|
||||
boolean credit;
|
||||
|
||||
@JsonProperty(value = "error-codes")
|
||||
List<String> errorCodes = Collections.emptyList();
|
||||
|
||||
@@ -48,7 +44,6 @@ public class HCaptchaResponse {
|
||||
"success=" + success +
|
||||
", challengeTs=" + challengeTs +
|
||||
", hostname='" + hostname + '\'' +
|
||||
", credit=" + credit +
|
||||
", errorCodes=" + errorCodes +
|
||||
", score=" + score +
|
||||
", scoreReasons=" + scoreReasons +
|
||||
|
||||
+3
-1
@@ -9,9 +9,11 @@ import io.micrometer.core.instrument.Metrics;
|
||||
import org.apache.http.HttpStatus;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.URLEncoder;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
@@ -28,7 +30,7 @@ public class ShortCodeExpander {
|
||||
}
|
||||
|
||||
public Optional<String> retrieve(final String shortCode) throws IOException {
|
||||
final URI uri = shortenerHost.resolve(shortCode);
|
||||
final URI uri = shortenerHost.resolve(URLEncoder.encode(shortCode, StandardCharsets.UTF_8));
|
||||
final HttpRequest request = HttpRequest.newBuilder().uri(uri).GET().build();
|
||||
|
||||
try {
|
||||
|
||||
+9
-1
@@ -10,19 +10,22 @@ public class AccountsTableConfiguration extends Table {
|
||||
private final String phoneNumberTableName;
|
||||
private final String phoneNumberIdentifierTableName;
|
||||
private final String usernamesTableName;
|
||||
private final String usedLinkDeviceTokensTableName;
|
||||
|
||||
@JsonCreator
|
||||
public AccountsTableConfiguration(
|
||||
@JsonProperty("tableName") final String tableName,
|
||||
@JsonProperty("phoneNumberTableName") final String phoneNumberTableName,
|
||||
@JsonProperty("phoneNumberIdentifierTableName") final String phoneNumberIdentifierTableName,
|
||||
@JsonProperty("usernamesTableName") final String usernamesTableName) {
|
||||
@JsonProperty("usernamesTableName") final String usernamesTableName,
|
||||
@JsonProperty("usedLinkDeviceTokensTableName") final String usedLinkDeviceTokensTableName) {
|
||||
|
||||
super(tableName);
|
||||
|
||||
this.phoneNumberTableName = phoneNumberTableName;
|
||||
this.phoneNumberIdentifierTableName = phoneNumberIdentifierTableName;
|
||||
this.usernamesTableName = usernamesTableName;
|
||||
this.usedLinkDeviceTokensTableName = usedLinkDeviceTokensTableName;
|
||||
}
|
||||
|
||||
@NotBlank
|
||||
@@ -39,4 +42,9 @@ public class AccountsTableConfiguration extends Table {
|
||||
public String getUsernamesTableName() {
|
||||
return usernamesTableName;
|
||||
}
|
||||
|
||||
@NotBlank
|
||||
public String getUsedLinkDeviceTokensTableName() {
|
||||
return usedLinkDeviceTokensTableName;
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.apple.itunes.storekit.model.Environment;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
|
||||
|
||||
/**
|
||||
* @param env The ios environment to use, typically SANDBOX or PRODUCTION
|
||||
* @param bundleId The bundleId of the app
|
||||
* @param appAppleId The integer id of the app
|
||||
* @param issuerId The issuerId for the keys:
|
||||
* https://developer.apple.com/documentation/appstoreconnectapi/generating_tokens_for_api_requests
|
||||
* @param keyId The keyId for encodedKey
|
||||
* @param encodedKey A private key with the "In-App Purchase" key type
|
||||
* @param subscriptionGroupId The subscription group for in-app purchases
|
||||
* @param productIdToLevel A map of productIds offered in the product catalog to their corresponding numeric
|
||||
* subscription levels
|
||||
* @param appleRootCerts Apple root certificates to verify signed API responses, encoded as base64 strings:
|
||||
* https://www.apple.com/certificateauthority/
|
||||
*/
|
||||
public record AppleAppStoreConfiguration(
|
||||
@NotNull Environment env,
|
||||
@NotBlank String bundleId,
|
||||
@NotNull Long appAppleId,
|
||||
@NotBlank String issuerId,
|
||||
@NotBlank String keyId,
|
||||
@NotNull SecretString encodedKey,
|
||||
@NotBlank String subscriptionGroupId,
|
||||
@NotNull Map<String, Long> productIdToLevel,
|
||||
@NotNull List<@NotBlank String> appleRootCerts,
|
||||
@NotNull @Valid RetryConfiguration retry) {
|
||||
|
||||
public AppleAppStoreConfiguration {
|
||||
if (retry == null) {
|
||||
retry = new RetryConfiguration();
|
||||
}
|
||||
}
|
||||
}
|
||||
+5
-2
@@ -14,6 +14,7 @@ import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
|
||||
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
|
||||
import software.amazon.awssdk.http.crt.AwsCrtHttpClient;
|
||||
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
|
||||
import software.amazon.awssdk.metrics.MetricPublisher;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
@@ -39,13 +40,14 @@ public record DynamoDbClientConfiguration(@NotBlank String region,
|
||||
}
|
||||
|
||||
@Override
|
||||
public DynamoDbClient buildSyncClient(final AwsCredentialsProvider credentialsProvider) {
|
||||
public DynamoDbClient buildSyncClient(final AwsCredentialsProvider credentialsProvider, final MetricPublisher metricPublisher) {
|
||||
return DynamoDbClient.builder()
|
||||
.region(Region.of(region()))
|
||||
.credentialsProvider(credentialsProvider)
|
||||
.overrideConfiguration(ClientOverrideConfiguration.builder()
|
||||
.apiCallTimeout(clientExecutionTimeout())
|
||||
.apiCallAttemptTimeout(clientRequestTimeout())
|
||||
.addMetricPublisher(metricPublisher)
|
||||
.build())
|
||||
.httpClientBuilder(AwsCrtHttpClient.builder()
|
||||
.maxConcurrency(maxConnections()))
|
||||
@@ -53,13 +55,14 @@ public record DynamoDbClientConfiguration(@NotBlank String region,
|
||||
}
|
||||
|
||||
@Override
|
||||
public DynamoDbAsyncClient buildAsyncClient(final AwsCredentialsProvider credentialsProvider) {
|
||||
public DynamoDbAsyncClient buildAsyncClient(final AwsCredentialsProvider credentialsProvider, final MetricPublisher metricPublisher) {
|
||||
return DynamoDbAsyncClient.builder()
|
||||
.region(Region.of(region()))
|
||||
.credentialsProvider(credentialsProvider)
|
||||
.overrideConfiguration(ClientOverrideConfiguration.builder()
|
||||
.apiCallTimeout(clientExecutionTimeout())
|
||||
.apiCallAttemptTimeout(clientRequestTimeout())
|
||||
.addMetricPublisher(metricPublisher)
|
||||
.build())
|
||||
.httpClientBuilder(NettyNioAsyncHttpClient.builder()
|
||||
.maxConcurrency(maxConnections()))
|
||||
|
||||
+3
-2
@@ -8,13 +8,14 @@ package org.whispersystems.textsecuregcm.configuration;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeInfo;
|
||||
import io.dropwizard.jackson.Discoverable;
|
||||
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
|
||||
import software.amazon.awssdk.metrics.MetricPublisher;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
|
||||
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = DynamoDbClientConfiguration.class)
|
||||
public interface DynamoDbClientFactory extends Discoverable {
|
||||
|
||||
DynamoDbClient buildSyncClient(AwsCredentialsProvider awsCredentialsProvider);
|
||||
DynamoDbClient buildSyncClient(AwsCredentialsProvider awsCredentialsProvider, MetricPublisher metricPublisher);
|
||||
|
||||
DynamoDbAsyncClient buildAsyncClient(AwsCredentialsProvider awsCredentialsProvider);
|
||||
DynamoDbAsyncClient buildAsyncClient(AwsCredentialsProvider awsCredentialsProvider, MetricPublisher metricPublisher);
|
||||
}
|
||||
+3
-3
@@ -7,11 +7,11 @@ package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonTypeInfo;
|
||||
import io.dropwizard.jackson.Discoverable;
|
||||
import io.lettuce.core.RedisClient;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
|
||||
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = RedisConfiguration.class)
|
||||
public interface SingletonRedisClientFactory extends Discoverable {
|
||||
public interface FaultTolerantRedisClientFactory extends Discoverable {
|
||||
|
||||
RedisClient build(ClientResources clientResources);
|
||||
FaultTolerantRedisClient build(String name, ClientResources clientResources);
|
||||
}
|
||||
+2
-2
@@ -8,10 +8,10 @@ package org.whispersystems.textsecuregcm.configuration;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeInfo;
|
||||
import io.dropwizard.jackson.Discoverable;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
|
||||
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = RedisClusterConfiguration.class)
|
||||
public interface FaultTolerantRedisClusterFactory extends Discoverable {
|
||||
|
||||
FaultTolerantRedisCluster build(String name, ClientResources.Builder clientResourcesBuilder);
|
||||
FaultTolerantRedisClusterClient build(String name, ClientResources.Builder clientResourcesBuilder);
|
||||
}
|
||||
-20
@@ -1,20 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
public record ProvisioningConfiguration(@Valid @NotNull SingletonRedisClientFactory pubsub,
|
||||
@Valid @NotNull CircuitBreakerConfiguration circuitBreaker) {
|
||||
|
||||
public ProvisioningConfiguration {
|
||||
if (circuitBreaker == null) {
|
||||
circuitBreaker = new CircuitBreakerConfiguration();
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -13,7 +13,7 @@ import java.time.Duration;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
|
||||
@JsonTypeName("default")
|
||||
public class RedisClusterConfiguration implements FaultTolerantRedisClusterFactory {
|
||||
@@ -58,7 +58,7 @@ public class RedisClusterConfiguration implements FaultTolerantRedisClusterFacto
|
||||
}
|
||||
|
||||
@Override
|
||||
public FaultTolerantRedisCluster build(final String name, final ClientResources.Builder clientResourcesBuilder) {
|
||||
return new FaultTolerantRedisCluster(name, this, clientResourcesBuilder);
|
||||
public FaultTolerantRedisClusterClient build(final String name, final ClientResources.Builder clientResourcesBuilder) {
|
||||
return new FaultTolerantRedisClusterClient(name, this, clientResourcesBuilder);
|
||||
}
|
||||
}
|
||||
+29
-9
@@ -7,15 +7,16 @@ package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeName;
|
||||
import io.lettuce.core.RedisClient;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
import java.time.Duration;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisUriUtil;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
|
||||
@JsonTypeName("default")
|
||||
public class RedisConfiguration implements SingletonRedisClientFactory {
|
||||
public class RedisConfiguration implements FaultTolerantRedisClientFactory {
|
||||
|
||||
@JsonProperty
|
||||
@NotEmpty
|
||||
@@ -25,20 +26,39 @@ public class RedisConfiguration implements SingletonRedisClientFactory {
|
||||
@NotNull
|
||||
private Duration timeout = Duration.ofSeconds(1);
|
||||
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
@Valid
|
||||
private CircuitBreakerConfiguration circuitBreaker = new CircuitBreakerConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
@Valid
|
||||
private RetryConfiguration retry = new RetryConfiguration();
|
||||
|
||||
public String getUri() {
|
||||
return uri;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public void setUri(String uri) {
|
||||
this.uri = uri;
|
||||
}
|
||||
|
||||
public Duration getTimeout() {
|
||||
return timeout;
|
||||
}
|
||||
|
||||
@Override
|
||||
public RedisClient build(final ClientResources clientResources) {
|
||||
final RedisClient redisClient = RedisClient.create(clientResources,
|
||||
RedisUriUtil.createRedisUriWithTimeout(uri, timeout));
|
||||
redisClient.setDefaultTimeout(timeout);
|
||||
public @NotNull @Valid CircuitBreakerConfiguration getCircuitBreakerConfiguration() {
|
||||
return circuitBreaker;
|
||||
}
|
||||
|
||||
return redisClient;
|
||||
public @NotNull @Valid RetryConfiguration getRetryConfiguration() {
|
||||
return retry;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FaultTolerantRedisClient build(final String name, final ClientResources clientResources) {
|
||||
return new FaultTolerantRedisClient(name, this, clientResources.mutate());
|
||||
}
|
||||
}
|
||||
+6
-4
@@ -104,11 +104,13 @@ public class SubscriptionConfiguration {
|
||||
@JsonIgnore
|
||||
@ValidationMethod(message = "has a mismatch between the levels supported currencies")
|
||||
public boolean isCurrencyListSameAcrossAllLevels() {
|
||||
final Map<Long, SubscriptionLevelConfiguration> subscriptionLevels = Stream
|
||||
.concat(donationLevels.entrySet().stream(), backupLevels.entrySet().stream())
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
|
||||
return isCurrencyListSameAccrossLevelConfigurations(donationLevels)
|
||||
&& isCurrencyListSameAccrossLevelConfigurations(backupLevels);
|
||||
}
|
||||
|
||||
Optional<SubscriptionLevelConfiguration> any = subscriptionLevels.values().stream().findAny();
|
||||
private static boolean isCurrencyListSameAccrossLevelConfigurations(
|
||||
Map<Long, ? extends SubscriptionLevelConfiguration> subscriptionLevels) {
|
||||
Optional<? extends SubscriptionLevelConfiguration> any = subscriptionLevels.values().stream().findAny();
|
||||
if (any.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
+15
-2
@@ -26,8 +26,8 @@ public class DynamicExperimentEnrollmentConfiguration {
|
||||
/**
|
||||
* What percentage of enrolled UUIDs should the experiment be enabled for.
|
||||
* <p>
|
||||
* Unlike {@link this#enrollmentPercentage}, this is not stable by UUID. The same UUID may be
|
||||
* enrolled/unenrolled across calls.
|
||||
* Unlike {@link this#enrollmentPercentage}, this is not stable by UUID. The same UUID may be enrolled/unenrolled
|
||||
* across calls.
|
||||
*/
|
||||
@JsonProperty
|
||||
@Valid
|
||||
@@ -49,6 +49,14 @@ public class DynamicExperimentEnrollmentConfiguration {
|
||||
@NotNull
|
||||
private final UuidSelector uuidSelector = new UuidSelector();
|
||||
|
||||
|
||||
/**
|
||||
* UUIDs that the experiment should always be disabled for. This takes precedence over uuidSelector.
|
||||
*/
|
||||
@Valid
|
||||
@NotNull
|
||||
private final Set<UUID> excludedUuids = Collections.emptySet();
|
||||
|
||||
/**
|
||||
* If the UUID is not enrolled via {@link UuidSelector#uuids}, what is the percentage chance it should be enrolled.
|
||||
* <p>
|
||||
@@ -67,4 +75,9 @@ public class DynamicExperimentEnrollmentConfiguration {
|
||||
public UuidSelector getUuidSelector() {
|
||||
return uuidSelector;
|
||||
}
|
||||
|
||||
public Set<UUID> getExcludedUuids() {
|
||||
return excludedUuids;
|
||||
}
|
||||
}
|
||||
|
||||
+1
-3
@@ -120,7 +120,6 @@ public class AccountController {
|
||||
|
||||
accounts.updateDevice(account, device.getId(), d -> {
|
||||
d.setApnId(null);
|
||||
d.setVoipApnId(null);
|
||||
d.setGcmId(registrationId.gcmRegistrationId());
|
||||
d.setFetchesMessages(false);
|
||||
});
|
||||
@@ -153,7 +152,6 @@ public class AccountController {
|
||||
// unconditionally
|
||||
accounts.updateDevice(account, device.getId(), d -> {
|
||||
d.setApnId(registrationId.apnRegistrationId());
|
||||
d.setVoipApnId(registrationId.voipRegistrationId());
|
||||
d.setGcmId(null);
|
||||
d.setFetchesMessages(false);
|
||||
});
|
||||
@@ -167,7 +165,6 @@ public class AccountController {
|
||||
|
||||
accounts.updateDevice(account, device.getId(), d -> {
|
||||
d.setApnId(null);
|
||||
d.setVoipApnId(null);
|
||||
d.setFetchesMessages(false);
|
||||
if (d.getId() == 1) {
|
||||
d.setUserAgent("OWI");
|
||||
@@ -252,6 +249,7 @@ public class AccountController {
|
||||
auth.getAccount().getNumber(),
|
||||
auth.getAccount().getPhoneNumberIdentifier(),
|
||||
auth.getAccount().getUsernameHash().filter(h -> h.length > 0).orElse(null),
|
||||
auth.getAccount().getUsernameLinkHandle(),
|
||||
auth.getAccount().isStorageSupported());
|
||||
}
|
||||
|
||||
|
||||
+2
@@ -150,6 +150,7 @@ public class AccountControllerV2 {
|
||||
updatedAccount.getNumber(),
|
||||
updatedAccount.getPhoneNumberIdentifier(),
|
||||
updatedAccount.getUsernameHash().orElse(null),
|
||||
updatedAccount.getUsernameLinkHandle(),
|
||||
updatedAccount.isStorageSupported());
|
||||
} catch (MismatchedDevicesException e) {
|
||||
throw new WebApplicationException(Response.status(409)
|
||||
@@ -208,6 +209,7 @@ public class AccountControllerV2 {
|
||||
updatedAccount.getNumber(),
|
||||
updatedAccount.getPhoneNumberIdentifier(),
|
||||
updatedAccount.getUsernameHash().orElse(null),
|
||||
updatedAccount.getUsernameLinkHandle(),
|
||||
updatedAccount.isStorageSupported());
|
||||
} catch (MismatchedDevicesException e) {
|
||||
throw new WebApplicationException(Response.status(409)
|
||||
|
||||
+2
-2
@@ -35,7 +35,7 @@ import org.whispersystems.websocket.auth.ReadOnly;
|
||||
@io.swagger.v3.oas.annotations.tags.Tag(name = "Calling")
|
||||
public class CallRoutingController {
|
||||
|
||||
private static final int TURN_INSTANCE_LIMIT = 3;
|
||||
private static final int TURN_INSTANCE_LIMIT = 2;
|
||||
private static final Counter INVALID_IP_COUNTER = Metrics.counter(name(CallRoutingController.class, "invalidIP"));
|
||||
private static final Logger log = LoggerFactory.getLogger(CallRoutingController.class);
|
||||
private final RateLimiters rateLimiters;
|
||||
@@ -79,7 +79,7 @@ public class CallRoutingController {
|
||||
UUID aci = auth.getAccount().getUuid();
|
||||
rateLimiters.getCallEndpointLimiter().validate(aci);
|
||||
|
||||
if (experimentEnrollmentManager.isEnrolled(aci, "cloudflareTurn")) {
|
||||
if (experimentEnrollmentManager.isEnrolled(auth.getAccount().getNumber(), aci, "cloudflareTurn")) {
|
||||
return cloudflareTurnCredentialsManager.retrieveFromCloudflare();
|
||||
}
|
||||
|
||||
|
||||
+187
-157
@@ -7,33 +7,30 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.lettuce.core.SetArgs;
|
||||
import io.lettuce.core.RedisException;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.headers.Header;
|
||||
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 java.nio.charset.StandardCharsets;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.Key;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.LinkedList;
|
||||
import java.util.EnumMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.Max;
|
||||
import javax.validation.constraints.Min;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.validation.constraints.Size;
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.DELETE;
|
||||
import javax.ws.rs.DefaultValue;
|
||||
import javax.ws.rs.ForbiddenException;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.HeaderParam;
|
||||
@@ -41,10 +38,12 @@ import javax.ws.rs.PUT;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.PathParam;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.Context;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import org.glassfish.jersey.server.ContainerRequest;
|
||||
import org.whispersystems.textsecuregcm.auth.LinkedDeviceRefreshRequirementProvider;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
@@ -57,17 +56,25 @@ import org.whispersystems.textsecuregcm.entities.DeviceInfoList;
|
||||
import org.whispersystems.textsecuregcm.entities.DeviceResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.LinkDeviceRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.PreKeySignatureValidator;
|
||||
import org.whispersystems.textsecuregcm.entities.ProvisioningMessage;
|
||||
import org.whispersystems.textsecuregcm.entities.SetPublicKeyRequest;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
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.Device.DeviceCapabilities;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceSpec;
|
||||
import org.whispersystems.textsecuregcm.util.VerificationCode;
|
||||
import org.whispersystems.textsecuregcm.storage.LinkDeviceTokenAlreadyUsedException;
|
||||
import org.whispersystems.textsecuregcm.util.EnumMapUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.LinkDeviceToken;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
|
||||
import org.whispersystems.websocket.auth.Mutable;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
@@ -77,56 +84,54 @@ public class DeviceController {
|
||||
|
||||
static final int MAX_DEVICES = 6;
|
||||
|
||||
private final Key verificationTokenKey;
|
||||
private final AccountsManager accounts;
|
||||
private final ClientPublicKeysManager clientPublicKeysManager;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final FaultTolerantRedisCluster usedTokenCluster;
|
||||
private final Map<String, Integer> maxDeviceConfiguration;
|
||||
|
||||
private final Clock clock;
|
||||
private final EnumMap<ClientPlatform, AtomicInteger> linkedDeviceListenersByPlatform;
|
||||
private final AtomicInteger linkedDeviceListenersForUnrecognizedPlatforms;
|
||||
|
||||
private static final String VERIFICATION_TOKEN_ALGORITHM = "HmacSHA256";
|
||||
private static final String LINKED_DEVICE_LISTENER_GAUGE_NAME =
|
||||
MetricsUtil.name(DeviceController.class, "linkedDeviceListeners");
|
||||
|
||||
private static final String WAIT_FOR_LINKED_DEVICE_TIMER_NAME =
|
||||
MetricsUtil.name(DeviceController.class, "waitForLinkedDeviceDuration");
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration TOKEN_EXPIRATION_DURATION = Duration.ofMinutes(10);
|
||||
static final int MIN_TOKEN_IDENTIFIER_LENGTH = 32;
|
||||
|
||||
@VisibleForTesting
|
||||
static final int MAX_TOKEN_IDENTIFIER_LENGTH = 64;
|
||||
|
||||
public DeviceController(final AccountsManager accounts,
|
||||
final ClientPublicKeysManager clientPublicKeysManager,
|
||||
final RateLimiters rateLimiters,
|
||||
final Map<String, Integer> maxDeviceConfiguration) {
|
||||
|
||||
public DeviceController(byte[] linkDeviceSecret,
|
||||
AccountsManager accounts,
|
||||
ClientPublicKeysManager clientPublicKeysManager,
|
||||
RateLimiters rateLimiters,
|
||||
FaultTolerantRedisCluster usedTokenCluster,
|
||||
Map<String, Integer> maxDeviceConfiguration, final Clock clock) {
|
||||
this.verificationTokenKey = new SecretKeySpec(linkDeviceSecret, VERIFICATION_TOKEN_ALGORITHM);
|
||||
this.accounts = accounts;
|
||||
this.clientPublicKeysManager = clientPublicKeysManager;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.usedTokenCluster = usedTokenCluster;
|
||||
this.maxDeviceConfiguration = maxDeviceConfiguration;
|
||||
this.clock = clock;
|
||||
|
||||
// Fail fast: reject bad keys
|
||||
try {
|
||||
final Mac mac = Mac.getInstance(VERIFICATION_TOKEN_ALGORITHM);
|
||||
mac.init(verificationTokenKey);
|
||||
} catch (final NoSuchAlgorithmException e) {
|
||||
throw new AssertionError("All Java implementations must support HmacSHA256", e);
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw new IllegalArgumentException(e);
|
||||
}
|
||||
linkedDeviceListenersByPlatform =
|
||||
EnumMapUtil.toEnumMap(ClientPlatform.class, clientPlatform -> buildGauge(clientPlatform.name().toLowerCase()));
|
||||
|
||||
linkedDeviceListenersForUnrecognizedPlatforms = buildGauge("unknown");
|
||||
}
|
||||
|
||||
private static AtomicInteger buildGauge(final String clientPlatformName) {
|
||||
return Metrics.gauge(LINKED_DEVICE_LISTENER_GAUGE_NAME,
|
||||
Tags.of(io.micrometer.core.instrument.Tag.of(UserAgentTagUtil.PLATFORM_TAG, clientPlatformName)),
|
||||
new AtomicInteger(0));
|
||||
}
|
||||
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public DeviceInfoList getDevices(@ReadOnly @Auth AuthenticatedDevice auth) {
|
||||
List<DeviceInfo> devices = new LinkedList<>();
|
||||
|
||||
for (Device device : auth.getAccount().getDevices()) {
|
||||
devices.add(new DeviceInfo(device.getId(), device.getName(),
|
||||
device.getLastSeen(), device.getCreated()));
|
||||
}
|
||||
|
||||
return new DeviceInfoList(devices);
|
||||
return new DeviceInfoList(auth.getAccount().getDevices().stream()
|
||||
.map(DeviceInfo::forDevice)
|
||||
.toList());
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@@ -146,10 +151,35 @@ public class DeviceController {
|
||||
accounts.removeDevice(auth.getAccount(), deviceId).join();
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a signed device-linking token. Generally, primary devices will include the signed device-linking token in
|
||||
* a provisioning message to a new device, and then the new device will include the token in its request to
|
||||
* {@link #linkDevice(BasicAuthorizationHeader, String, LinkDeviceRequest, ContainerRequest)}.
|
||||
*
|
||||
* @param auth the authenticated account/device
|
||||
*
|
||||
* @return a signed device-linking token
|
||||
*
|
||||
* @throws RateLimitExceededException if the caller has made too many calls to this method in a set amount of time
|
||||
* @throws DeviceLimitExceededException if the authenticated account has already reached the maximum number of linked
|
||||
* devices
|
||||
*
|
||||
* @see ProvisioningController#sendProvisioningMessage(AuthenticatedDevice, String, ProvisioningMessage, String)
|
||||
*/
|
||||
@GET
|
||||
@Path("/provisioning/code")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public VerificationCode createDeviceToken(@ReadOnly @Auth AuthenticatedDevice auth)
|
||||
@Operation(
|
||||
summary = "Generate a signed device-linking token",
|
||||
description = """
|
||||
Generate a signed device-linking token for transmission to a pending linked device via a provisioning message.
|
||||
""")
|
||||
@ApiResponse(responseCode="200", description="Token was generated successfully", useReturnTypeSchema=true)
|
||||
@ApiResponse(responseCode = "411", description = "The authenticated account already has the maximum allowed number of linked devices")
|
||||
@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 LinkDeviceToken createDeviceToken(@ReadOnly @Auth AuthenticatedDevice auth)
|
||||
throws RateLimitExceededException, DeviceLimitExceededException {
|
||||
|
||||
final Account account = auth.getAccount();
|
||||
@@ -170,7 +200,9 @@ public class DeviceController {
|
||||
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
return new VerificationCode(generateVerificationToken(account.getUuid()));
|
||||
final String token = accounts.generateLinkDeviceToken(account.getUuid());
|
||||
|
||||
return new LinkDeviceToken(token, AccountsManager.getLinkDeviceTokenIdentifier(token));
|
||||
}
|
||||
|
||||
@PUT
|
||||
@@ -196,7 +228,7 @@ public class DeviceController {
|
||||
@Context ContainerRequest containerRequest)
|
||||
throws RateLimitExceededException, DeviceLimitExceededException {
|
||||
|
||||
final Account account = checkVerificationToken(linkDeviceRequest.verificationCode())
|
||||
final Account account = accounts.checkDeviceLinkingToken(linkDeviceRequest.verificationCode())
|
||||
.flatMap(accounts::getByAccountIdentifier)
|
||||
.orElseThrow(ForbiddenException::new);
|
||||
|
||||
@@ -248,27 +280,110 @@ public class DeviceController {
|
||||
signalAgent = "OWD";
|
||||
}
|
||||
|
||||
return accounts.addDevice(account, new DeviceSpec(accountAttributes.getName(),
|
||||
authorizationHeader.getPassword(),
|
||||
signalAgent,
|
||||
capabilities,
|
||||
accountAttributes.getRegistrationId(),
|
||||
accountAttributes.getPhoneNumberIdentityRegistrationId(),
|
||||
accountAttributes.getFetchesMessages(),
|
||||
deviceActivationRequest.apnToken(),
|
||||
deviceActivationRequest.gcmToken(),
|
||||
deviceActivationRequest.aciSignedPreKey(),
|
||||
deviceActivationRequest.pniSignedPreKey(),
|
||||
deviceActivationRequest.aciPqLastResortPreKey(),
|
||||
deviceActivationRequest.pniPqLastResortPreKey()))
|
||||
.thenCompose(a -> usedTokenCluster.withCluster(connection -> connection.async()
|
||||
.set(getUsedTokenKey(linkDeviceRequest.verificationCode()), "", new SetArgs().ex(TOKEN_EXPIRATION_DURATION)))
|
||||
.thenApply(ignored -> a))
|
||||
.thenApply(accountAndDevice -> new DeviceResponse(
|
||||
accountAndDevice.first().getIdentifier(IdentityType.ACI),
|
||||
accountAndDevice.first().getIdentifier(IdentityType.PNI),
|
||||
accountAndDevice.second().getId()))
|
||||
.join();
|
||||
try {
|
||||
return accounts.addDevice(account, new DeviceSpec(accountAttributes.getName(),
|
||||
authorizationHeader.getPassword(),
|
||||
signalAgent,
|
||||
capabilities,
|
||||
accountAttributes.getRegistrationId(),
|
||||
accountAttributes.getPhoneNumberIdentityRegistrationId(),
|
||||
accountAttributes.getFetchesMessages(),
|
||||
deviceActivationRequest.apnToken(),
|
||||
deviceActivationRequest.gcmToken(),
|
||||
deviceActivationRequest.aciSignedPreKey(),
|
||||
deviceActivationRequest.pniSignedPreKey(),
|
||||
deviceActivationRequest.aciPqLastResortPreKey(),
|
||||
deviceActivationRequest.pniPqLastResortPreKey()),
|
||||
linkDeviceRequest.verificationCode())
|
||||
.thenApply(accountAndDevice -> new DeviceResponse(
|
||||
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();
|
||||
}
|
||||
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/wait_for_linked_device/{tokenIdentifier}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(summary = "Wait for a new device to be linked to an account",
|
||||
description = """
|
||||
Waits for a new device to be linked to an account and returns basic information about the new device when
|
||||
available.
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "The specified was linked to an account")
|
||||
@ApiResponse(responseCode = "204", description = "No device was linked to the account before the call completed")
|
||||
@ApiResponse(responseCode = "400", description = "The given token identifier or timeout was invalid")
|
||||
@ApiResponse(responseCode = "429", description = "Rate-limited; try again after the prescribed delay")
|
||||
@Schema(description = "Basic information about the linked device", implementation = DeviceInfo.class)
|
||||
public CompletableFuture<Response> waitForLinkedDevice(
|
||||
@ReadOnly @Auth final AuthenticatedDevice authenticatedDevice,
|
||||
|
||||
@PathParam("tokenIdentifier")
|
||||
@Schema(description = "A 'link device' token identifier provided by the 'create link device token' endpoint")
|
||||
@Size(min = MIN_TOKEN_IDENTIFIER_LENGTH, max = MAX_TOKEN_IDENTIFIER_LENGTH)
|
||||
final String tokenIdentifier,
|
||||
|
||||
@QueryParam("timeout")
|
||||
@DefaultValue("30")
|
||||
@Min(1)
|
||||
@Max(3600)
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED,
|
||||
minimum = "1",
|
||||
maximum = "3600",
|
||||
description = """
|
||||
The amount of time (in seconds) to wait for a response. If the expected device is not linked within the
|
||||
given amount of time, this endpoint will return a status of HTTP/204.
|
||||
""") final int timeoutSeconds,
|
||||
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent) throws RateLimitExceededException {
|
||||
|
||||
rateLimiters.getWaitForLinkedDeviceLimiter().validate(authenticatedDevice.getAccount().getIdentifier(IdentityType.ACI));
|
||||
|
||||
final AtomicInteger linkedDeviceListenerCounter = getCounterForLinkedDeviceListeners(userAgent);
|
||||
linkedDeviceListenerCounter.incrementAndGet();
|
||||
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
try {
|
||||
return accounts.waitForNewLinkedDevice(tokenIdentifier, Duration.ofSeconds(timeoutSeconds))
|
||||
.thenApply(maybeDeviceInfo -> maybeDeviceInfo
|
||||
.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) -> {
|
||||
linkedDeviceListenerCounter.decrementAndGet();
|
||||
|
||||
if (response != null) {
|
||||
sample.stop(Timer.builder(WAIT_FOR_LINKED_DEVICE_TIMER_NAME)
|
||||
.publishPercentileHistogram(true)
|
||||
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
io.micrometer.core.instrument.Tag.of("deviceFound",
|
||||
String.valueOf(response.getStatus() == Response.Status.OK.getStatusCode()))))
|
||||
.register(Metrics.globalRegistry));
|
||||
}
|
||||
});
|
||||
} catch (final RedisException e) {
|
||||
// `waitForNewLinkedDevice` could fail synchronously if the Redis circuit breaker is open; prevent counter drift
|
||||
// if that happens
|
||||
linkedDeviceListenerCounter.decrementAndGet();
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private AtomicInteger getCounterForLinkedDeviceListeners(final String userAgent) {
|
||||
try {
|
||||
return linkedDeviceListenersByPlatform.get(UserAgentUtil.parseUserAgentString(userAgent).getPlatform());
|
||||
} catch (final UnrecognizedUserAgentException ignored) {
|
||||
return linkedDeviceListenersForUnrecognizedPlatforms;
|
||||
}
|
||||
}
|
||||
|
||||
@PUT
|
||||
@@ -310,95 +425,10 @@ public class DeviceController {
|
||||
setPublicKeyRequest.publicKey());
|
||||
}
|
||||
|
||||
private Mac getInitializedMac() {
|
||||
try {
|
||||
final Mac mac = Mac.getInstance(VERIFICATION_TOKEN_ALGORITHM);
|
||||
mac.init(verificationTokenKey);
|
||||
|
||||
return mac;
|
||||
} catch (final NoSuchAlgorithmException | InvalidKeyException e) {
|
||||
// All Java implementations must support HmacSHA256 and we checked the key at construction time, so this can never
|
||||
// happen
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
String generateVerificationToken(final UUID aci) {
|
||||
final String claims = aci + "." + clock.instant().toEpochMilli();
|
||||
final byte[] signature = getInitializedMac().doFinal(claims.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
return claims + ":" + Base64.getUrlEncoder().encodeToString(signature);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
Optional<UUID> checkVerificationToken(final String verificationToken) {
|
||||
final boolean tokenUsed = usedTokenCluster.withCluster(connection ->
|
||||
connection.sync().get(getUsedTokenKey(verificationToken)) != null);
|
||||
|
||||
if (tokenUsed) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
final String[] claimsAndSignature = verificationToken.split(":", 2);
|
||||
|
||||
if (claimsAndSignature.length != 2) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
final byte[] expectedSignature = getInitializedMac().doFinal(
|
||||
claimsAndSignature[0].getBytes(StandardCharsets.UTF_8));
|
||||
final byte[] providedSignature;
|
||||
|
||||
try {
|
||||
providedSignature = Base64.getUrlDecoder().decode(claimsAndSignature[1]);
|
||||
} catch (final IllegalArgumentException e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
if (!MessageDigest.isEqual(expectedSignature, providedSignature)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
final String[] aciAndTimestamp = claimsAndSignature[0].split("\\.", 2);
|
||||
|
||||
if (aciAndTimestamp.length != 2) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
final UUID aci;
|
||||
|
||||
try {
|
||||
aci = UUID.fromString(aciAndTimestamp[0]);
|
||||
} catch (final IllegalArgumentException e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
final Instant timestamp;
|
||||
|
||||
try {
|
||||
timestamp = Instant.ofEpochMilli(Long.parseLong(aciAndTimestamp[1]));
|
||||
} catch (final NumberFormatException e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
final Instant tokenExpiration = timestamp.plus(TOKEN_EXPIRATION_DURATION);
|
||||
|
||||
if (tokenExpiration.isBefore(clock.instant())) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
return Optional.of(aci);
|
||||
}
|
||||
|
||||
private static boolean isCapabilityDowngrade(Account account, DeviceCapabilities capabilities) {
|
||||
boolean isDowngrade = false;
|
||||
isDowngrade |= account.isDeleteSyncSupported() && !capabilities.deleteSync();
|
||||
isDowngrade |= account.isVersionedExpirationTimerSupported() && !capabilities.versionedExpirationTimer();
|
||||
return isDowngrade;
|
||||
}
|
||||
|
||||
private static String getUsedTokenKey(final String token) {
|
||||
return "usedToken::" + token;
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -13,7 +13,7 @@ import io.grpc.StatusRuntimeException;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import katie.MonitorKey;
|
||||
import org.signal.keytransparency.client.MonitorKey;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
|
||||
+36
-43
@@ -55,6 +55,7 @@ import javax.ws.rs.DELETE;
|
||||
import javax.ws.rs.DefaultValue;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.HeaderParam;
|
||||
import javax.ws.rs.InternalServerErrorException;
|
||||
import javax.ws.rs.NotAuthorizedException;
|
||||
import javax.ws.rs.NotFoundException;
|
||||
import javax.ws.rs.POST;
|
||||
@@ -115,7 +116,6 @@ import org.whispersystems.textsecuregcm.push.MessageSender;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
import org.whispersystems.textsecuregcm.spam.ReportSpamTokenProvider;
|
||||
import org.whispersystems.textsecuregcm.spam.SpamChecker;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
@@ -162,7 +162,6 @@ public class MessageController {
|
||||
private final ReportMessageManager reportMessageManager;
|
||||
private final ExecutorService multiRecipientMessageExecutor;
|
||||
private final Scheduler messageDeliveryScheduler;
|
||||
private final ReportSpamTokenProvider reportSpamTokenProvider;
|
||||
private final ClientReleaseManager clientReleaseManager;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
private final ServerSecretParams serverSecretParams;
|
||||
@@ -182,10 +181,7 @@ public class MessageController {
|
||||
private static final String RATE_LIMITED_MESSAGE_COUNTER_NAME = name(MessageController.class, "rateLimitedMessage");
|
||||
|
||||
private static final String REJECT_INVALID_ENVELOPE_TYPE = name(MessageController.class, "rejectInvalidEnvelopeType");
|
||||
private static final Timer SEND_MESSAGE_LATENCY_TIMER =
|
||||
Timer.builder(MetricsUtil.name(MessageController.class, "sendMessageLatency"))
|
||||
.publishPercentileHistogram(true)
|
||||
.register(Metrics.globalRegistry);
|
||||
private static final String SEND_MESSAGE_LATENCY_TIMER_NAME = MetricsUtil.name(MessageController.class, "sendMessageLatency");
|
||||
|
||||
private static final String EPHEMERAL_TAG_NAME = "ephemeral";
|
||||
private static final String SENDER_TYPE_TAG_NAME = "senderType";
|
||||
@@ -225,7 +221,6 @@ public class MessageController {
|
||||
ReportMessageManager reportMessageManager,
|
||||
@Nonnull ExecutorService multiRecipientMessageExecutor,
|
||||
Scheduler messageDeliveryScheduler,
|
||||
@Nonnull ReportSpamTokenProvider reportSpamTokenProvider,
|
||||
final ClientReleaseManager clientReleaseManager,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final ServerSecretParams serverSecretParams,
|
||||
@@ -244,7 +239,6 @@ public class MessageController {
|
||||
this.reportMessageManager = reportMessageManager;
|
||||
this.multiRecipientMessageExecutor = Objects.requireNonNull(multiRecipientMessageExecutor);
|
||||
this.messageDeliveryScheduler = messageDeliveryScheduler;
|
||||
this.reportSpamTokenProvider = reportSpamTokenProvider;
|
||||
this.clientReleaseManager = clientReleaseManager;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
this.serverSecretParams = serverSecretParams;
|
||||
@@ -254,7 +248,6 @@ public class MessageController {
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@Path("/{destination}")
|
||||
@PUT
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -300,25 +293,25 @@ public class MessageController {
|
||||
|
||||
@Context final ContainerRequestContext context) throws RateLimitExceededException {
|
||||
|
||||
if (source.isEmpty() && accessKey.isEmpty() && groupSendToken == null && !isStory) {
|
||||
throw new WebApplicationException(Status.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
if (groupSendToken != null) {
|
||||
if (source.isPresent() || accessKey.isPresent()) {
|
||||
throw new BadRequestException(
|
||||
"Group send endorsement tokens should not be combined with other authentication");
|
||||
} else if (isStory) {
|
||||
throw new BadRequestException("Group send endorsement tokens should not be sent for story messages");
|
||||
}
|
||||
}
|
||||
|
||||
final String senderType = source.map(
|
||||
s -> s.getAccount().isIdentifiedBy(destinationIdentifier) ? SENDER_TYPE_SELF : SENDER_TYPE_IDENTIFIED)
|
||||
.orElse(SENDER_TYPE_UNIDENTIFIED);
|
||||
|
||||
final Sample sample = Timer.start();
|
||||
try {
|
||||
if (source.isEmpty() && accessKey.isEmpty() && groupSendToken == null && !isStory) {
|
||||
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
if (groupSendToken != null) {
|
||||
if (source.isPresent() || accessKey.isPresent()) {
|
||||
throw new BadRequestException(
|
||||
"Group send endorsement tokens should not be combined with other authentication");
|
||||
} else if (isStory) {
|
||||
throw new BadRequestException("Group send endorsement tokens should not be sent for story messages");
|
||||
}
|
||||
}
|
||||
|
||||
final String senderType = source.map(
|
||||
s -> s.getAccount().isIdentifiedBy(destinationIdentifier) ? SENDER_TYPE_SELF : SENDER_TYPE_IDENTIFIED)
|
||||
.orElse(SENDER_TYPE_UNIDENTIFIED);
|
||||
|
||||
final boolean isSyncMessage = senderType.equals(SENDER_TYPE_SELF);
|
||||
|
||||
if (isSyncMessage && destinationIdentifier.identityType() == IdentityType.PNI) {
|
||||
@@ -332,17 +325,14 @@ public class MessageController {
|
||||
destination = source.map(AuthenticatedDevice::getAccount);
|
||||
}
|
||||
|
||||
final Optional<Response> spamCheck = spamChecker.checkForSpam(
|
||||
context, source.map(AuthenticatedDevice::getAccount), destination);
|
||||
if (spamCheck.isPresent()) {
|
||||
return spamCheck.get();
|
||||
final SpamChecker.SpamCheckResult spamCheck = spamChecker.checkForSpam(
|
||||
context, source, destination);
|
||||
final Optional<byte[]> reportSpamToken;
|
||||
switch (spamCheck) {
|
||||
case final SpamChecker.Spam spam: return spam.response();
|
||||
case final SpamChecker.NotSpam notSpam: reportSpamToken = notSpam.token();
|
||||
}
|
||||
|
||||
final Optional<byte[]> spamReportToken = switch (senderType) {
|
||||
case SENDER_TYPE_IDENTIFIED -> reportSpamTokenProvider.makeReportSpamToken(context, source.get(), destination);
|
||||
default -> Optional.empty();
|
||||
};
|
||||
|
||||
int totalContentLength = 0;
|
||||
|
||||
for (final IncomingMessage message : messages.messages()) {
|
||||
@@ -452,7 +442,7 @@ public class MessageController {
|
||||
messages.urgent(),
|
||||
incomingMessage,
|
||||
userAgent,
|
||||
spamReportToken);
|
||||
reportSpamToken);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -470,7 +460,10 @@ public class MessageController {
|
||||
.build());
|
||||
}
|
||||
} finally {
|
||||
sample.stop(SEND_MESSAGE_LATENCY_TIMER);
|
||||
sample.stop(Timer.builder(SEND_MESSAGE_LATENCY_TIMER_NAME)
|
||||
.tags(SENDER_TYPE_TAG_NAME, senderType)
|
||||
.publishPercentileHistogram(true)
|
||||
.register(Metrics.globalRegistry));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -554,9 +547,9 @@ public class MessageController {
|
||||
|
||||
@Context ContainerRequestContext context) throws RateLimitExceededException {
|
||||
|
||||
final Optional<Response> spamCheck = spamChecker.checkForSpam(context, Optional.empty(), Optional.empty());
|
||||
if (spamCheck.isPresent()) {
|
||||
return spamCheck.get();
|
||||
final SpamChecker.SpamCheckResult spamCheck = spamChecker.checkForSpam(context, Optional.empty(), Optional.empty());
|
||||
if (spamCheck instanceof final SpamChecker.Spam spam) {
|
||||
return spam.response();
|
||||
}
|
||||
|
||||
if (groupSendToken == null && accessKeys == null && !isStory) {
|
||||
@@ -697,13 +690,13 @@ public class MessageController {
|
||||
.get();
|
||||
} catch (InterruptedException e) {
|
||||
logger.error("interrupted while delivering multi-recipient messages", e);
|
||||
return Response.serverError().entity("interrupted during delivery").build();
|
||||
throw new InternalServerErrorException("interrupted during delivery");
|
||||
} catch (CancellationException e) {
|
||||
logger.error("cancelled while delivering multi-recipient messages", e);
|
||||
return Response.serverError().entity("delivery cancelled").build();
|
||||
throw new InternalServerErrorException("delivery cancelled");
|
||||
} catch (ExecutionException e) {
|
||||
logger.error("partial failure while delivering multi-recipient messages", e.getCause());
|
||||
return Response.serverError().entity("failure during delivery").build();
|
||||
throw new InternalServerErrorException("failure during delivery");
|
||||
}
|
||||
return Response.ok(new SendMultiRecipientMessageResponse(Collections.emptyList())).build();
|
||||
}
|
||||
|
||||
+8
-6
@@ -54,6 +54,7 @@ import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentStatus;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionCurrencyUtil;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
@@ -319,20 +320,21 @@ public class OneTimeDonationController {
|
||||
case STRIPE -> stripeManager.getPaymentDetails(request.paymentIntentId);
|
||||
case BRAINTREE -> braintreeManager.getPaymentDetails(request.paymentIntentId);
|
||||
case GOOGLE_PLAY_BILLING -> throw new BadRequestException("cannot use play billing for one-time donations");
|
||||
case APPLE_APP_STORE -> throw new BadRequestException("cannot use app store purchases for one-time donations");
|
||||
};
|
||||
|
||||
return paymentDetailsFut.thenCompose(paymentDetails -> {
|
||||
if (paymentDetails == null) {
|
||||
throw new WebApplicationException(Response.Status.NOT_FOUND);
|
||||
}
|
||||
switch (paymentDetails.status()) {
|
||||
case PROCESSING -> throw new WebApplicationException(Response.Status.NO_CONTENT);
|
||||
case SUCCEEDED -> {
|
||||
}
|
||||
default -> throw new WebApplicationException(Response.status(Response.Status.PAYMENT_REQUIRED)
|
||||
} else if (paymentDetails.status() == PaymentStatus.PROCESSING) {
|
||||
return CompletableFuture.completedFuture(Response.noContent().build());
|
||||
} else if (paymentDetails.status() != PaymentStatus.SUCCEEDED) {
|
||||
throw new WebApplicationException(Response.status(Response.Status.PAYMENT_REQUIRED)
|
||||
.entity(new CreateBoostReceiptCredentialsErrorResponse(paymentDetails.chargeFailure())).build());
|
||||
}
|
||||
|
||||
// The payment was successful, try to issue the receipt credential
|
||||
|
||||
long level = oneTimeDonationConfiguration.boost().level();
|
||||
if (paymentDetails.customMetadata() != null) {
|
||||
String levelMetadata = paymentDetails.customMetadata()
|
||||
|
||||
+36
-9
@@ -13,6 +13,9 @@ import io.dropwizard.auth.Auth;
|
||||
import io.dropwizard.util.DataSize;
|
||||
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.Parameter;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import java.util.Base64;
|
||||
import javax.validation.Valid;
|
||||
@@ -31,9 +34,18 @@ import org.whispersystems.textsecuregcm.entities.ProvisioningMessage;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.ProvisioningManager;
|
||||
import org.whispersystems.textsecuregcm.websocket.ProvisioningAddress;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
/**
|
||||
* The provisioning controller facilitates transmission of provisioning messages from the primary device associated with
|
||||
* an existing Signal account to a new device. To send a provisioning message, a primary device generally scans a QR
|
||||
* code displayed by the new device that contains the device's "provisioning address" and a public key. The primary
|
||||
* device then encrypts a use-case-specific provisioning message and posts it to
|
||||
* {@link #sendProvisioningMessage(AuthenticatedDevice, String, ProvisioningMessage, String)}, at which point the server
|
||||
* delivers the message to the new device via an open provisioning WebSocket.
|
||||
*
|
||||
* @see org.whispersystems.textsecuregcm.websocket.ProvisioningConnectListener
|
||||
*/
|
||||
@Path("/v1/provisioning")
|
||||
@Tag(name = "Provisioning")
|
||||
public class ProvisioningController {
|
||||
@@ -56,22 +68,37 @@ public class ProvisioningController {
|
||||
@PUT
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public void sendProvisioningMessage(@ReadOnly @Auth AuthenticatedDevice auth,
|
||||
@PathParam("destination") String destinationName,
|
||||
@NotNull @Valid ProvisioningMessage message,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent)
|
||||
@Operation(
|
||||
summary = "Send a provisioning message to a new device",
|
||||
description = """
|
||||
Send a provisioning message from an authenticated device to a device that (presumably) is not yet associated
|
||||
with a Signal account.
|
||||
""")
|
||||
@ApiResponse(responseCode="204", description="The provisioning message was delivered to the given provisioning address")
|
||||
@ApiResponse(responseCode="400", description="The provisioning message was too large")
|
||||
@ApiResponse(responseCode="404", description="No device with the given provisioning address was connected at the time of the request")
|
||||
public void sendProvisioningMessage(@ReadOnly @Auth final AuthenticatedDevice auth,
|
||||
|
||||
@Parameter(description = "The temporary provisioning address to which to send a provisioning message")
|
||||
@PathParam("destination") final String provisioningAddress,
|
||||
|
||||
@Parameter(description = "The provisioning message to send to the given provisioning address")
|
||||
@NotNull @Valid final ProvisioningMessage message,
|
||||
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent)
|
||||
throws RateLimitExceededException {
|
||||
|
||||
if (message.body().length() > MAX_MESSAGE_SIZE) {
|
||||
Metrics.counter(REJECT_OVERSIZE_MESSAGE_COUNTER, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.increment();
|
||||
Metrics.counter(REJECT_OVERSIZE_MESSAGE_COUNTER, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent))).increment();
|
||||
throw new WebApplicationException(Response.Status.BAD_REQUEST);
|
||||
}
|
||||
|
||||
rateLimiters.getMessagesLimiter().validate(auth.getAccount().getUuid());
|
||||
|
||||
if (!provisioningManager.sendProvisioningMessage(ProvisioningAddress.create(destinationName),
|
||||
Base64.getMimeDecoder().decode(message.body()))) {
|
||||
final boolean subscriberPresent =
|
||||
provisioningManager.sendProvisioningMessage(provisioningAddress, Base64.getMimeDecoder().decode(message.body()));
|
||||
|
||||
if (!subscriberPresent) {
|
||||
throw new WebApplicationException(Response.Status.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
+1
@@ -170,6 +170,7 @@ public class RegistrationController {
|
||||
account.getNumber(),
|
||||
account.getPhoneNumberIdentifier(),
|
||||
account.getUsernameHash().orElse(null),
|
||||
account.getUsernameLinkHandle(),
|
||||
existingAccount.map(Account::isStorageSupported).orElse(false));
|
||||
}
|
||||
|
||||
|
||||
+50
-5
@@ -51,6 +51,7 @@ import javax.ws.rs.Path;
|
||||
import javax.ws.rs.PathParam;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.container.ContainerRequestContext;
|
||||
import javax.ws.rs.core.Context;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
@@ -75,6 +76,7 @@ import org.whispersystems.textsecuregcm.storage.PaymentTime;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriberCredentials;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionException;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BankTransferType;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
|
||||
@@ -105,6 +107,7 @@ public class SubscriptionController {
|
||||
private final StripeManager stripeManager;
|
||||
private final BraintreeManager braintreeManager;
|
||||
private final GooglePlayBillingManager googlePlayBillingManager;
|
||||
private final AppleAppStoreManager appleAppStoreManager;
|
||||
private final BadgeTranslator badgeTranslator;
|
||||
private final LevelTranslator levelTranslator;
|
||||
private final BankMandateTranslator bankMandateTranslator;
|
||||
@@ -121,6 +124,7 @@ public class SubscriptionController {
|
||||
@Nonnull StripeManager stripeManager,
|
||||
@Nonnull BraintreeManager braintreeManager,
|
||||
@Nonnull GooglePlayBillingManager googlePlayBillingManager,
|
||||
@Nonnull AppleAppStoreManager appleAppStoreManager,
|
||||
@Nonnull BadgeTranslator badgeTranslator,
|
||||
@Nonnull LevelTranslator levelTranslator,
|
||||
@Nonnull BankMandateTranslator bankMandateTranslator) {
|
||||
@@ -131,6 +135,7 @@ public class SubscriptionController {
|
||||
this.stripeManager = Objects.requireNonNull(stripeManager);
|
||||
this.braintreeManager = Objects.requireNonNull(braintreeManager);
|
||||
this.googlePlayBillingManager = Objects.requireNonNull(googlePlayBillingManager);
|
||||
this.appleAppStoreManager = appleAppStoreManager;
|
||||
this.badgeTranslator = Objects.requireNonNull(badgeTranslator);
|
||||
this.levelTranslator = Objects.requireNonNull(levelTranslator);
|
||||
this.bankMandateTranslator = Objects.requireNonNull(bankMandateTranslator);
|
||||
@@ -261,8 +266,8 @@ public class SubscriptionController {
|
||||
// Today, we always choose stripe to process non-paypal payment types, however we could use braintree to process
|
||||
// other types (like CARD) in the future.
|
||||
case CARD, SEPA_DEBIT, IDEAL -> stripeManager;
|
||||
case GOOGLE_PLAY_BILLING ->
|
||||
throw new BadRequestException("cannot create payment methods with payment type GOOGLE_PLAY_BILLING");
|
||||
case GOOGLE_PLAY_BILLING, APPLE_APP_STORE ->
|
||||
throw new BadRequestException("cannot create payment methods with payment type " + paymentMethodType);
|
||||
case PAYPAL -> throw new BadRequestException("The PAYPAL payment type must use create_payment_method/paypal");
|
||||
case UNKNOWN -> throw new BadRequestException("Invalid payment method");
|
||||
};
|
||||
@@ -315,7 +320,7 @@ public class SubscriptionController {
|
||||
return switch (processor) {
|
||||
case STRIPE -> stripeManager;
|
||||
case BRAINTREE -> braintreeManager;
|
||||
case GOOGLE_PLAY_BILLING -> throw new BadRequestException("Operation cannot be performed with the GOOGLE_PLAY_BILLING payment provider");
|
||||
case GOOGLE_PLAY_BILLING, APPLE_APP_STORE -> throw new BadRequestException("Operation cannot be performed with the " + processor + " payment provider");
|
||||
};
|
||||
}
|
||||
|
||||
@@ -400,6 +405,39 @@ public class SubscriptionController {
|
||||
== subscriptionConfiguration.getSubscriptionLevel(level2).type();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/{subscriberId}/appstore/{originalTransactionId}")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(summary = "Set app store subscription", description = """
|
||||
Set an originalTransactionId that represents an IAP subscription made with the app store.
|
||||
|
||||
To set up an app store subscription:
|
||||
1. Create a subscriber with `PUT subscriptions/{subscriberId}` (you must regularly refresh this subscriber)
|
||||
2. [Create a subscription](https://developer.apple.com/documentation/storekit/in-app_purchase/) with the App Store
|
||||
directly via StoreKit and obtain a originalTransactionId.
|
||||
3. `POST` the purchaseToken here
|
||||
4. Obtain a receipt at `POST /v1/subscription/{subscriberId}/receipt_credentials` which can then be used to obtain the
|
||||
entitlement
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "The originalTransactionId was successfully validated")
|
||||
@ApiResponse(responseCode = "402", description = "The subscription transaction is incomplete or invalid")
|
||||
@ApiResponse(responseCode = "403", description = "subscriberId authentication failure OR account authentication is present")
|
||||
@ApiResponse(responseCode = "404", description = "No such subscriberId exists or subscriberId is malformed or the specified transaction does not exist")
|
||||
@ApiResponse(responseCode = "409", description = "subscriberId is already linked to a processor that does not support appstore payments. Delete this subscriberId and use a new one.")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limit exceeded.")
|
||||
public CompletableFuture<SetSubscriptionLevelSuccessResponse> setAppStoreSubscription(
|
||||
@ReadOnly @Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@PathParam("subscriberId") String subscriberId,
|
||||
@PathParam("originalTransactionId") String originalTransactionId) throws SubscriptionException {
|
||||
final SubscriberCredentials subscriberCredentials =
|
||||
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
|
||||
|
||||
return subscriptionManager
|
||||
.updateAppStoreTransactionId(subscriberCredentials, appleAppStoreManager, originalTransactionId)
|
||||
.thenApply(SetSubscriptionLevelSuccessResponse::new);
|
||||
}
|
||||
|
||||
|
||||
@POST
|
||||
@Path("/{subscriberId}/playbilling/{purchaseToken}")
|
||||
@@ -419,6 +457,10 @@ public class SubscriptionController {
|
||||
|
||||
After calling this method, the payment is confirmed. Callers must durably store their subscriberId before calling
|
||||
this method to ensure their payment is tracked.
|
||||
|
||||
Once a purchaseToken to is posted to a subscriberId, the same subscriberId must not be used with another payment
|
||||
method. A different playbilling purchaseToken can be posted to the same subscriberId, in this case the subscription
|
||||
associated with the old purchaseToken will be cancelled.
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "The purchaseToken was validated and acknowledged")
|
||||
@ApiResponse(responseCode = "402", description = "The purchaseToken payment is incomplete or invalid")
|
||||
@@ -526,7 +568,7 @@ public class SubscriptionController {
|
||||
long level,
|
||||
|
||||
@Schema(
|
||||
description = "If present, UNIX Epoch Timestamp in seconds, can be used to calculate next billing date. May be absent for IAP subscriptions",
|
||||
description = "If present, UNIX Epoch Timestamp in seconds, can be used to calculate next billing date.",
|
||||
externalDocs = @ExternalDocumentation(description = "Calculate next billing date", url = "https://stripe.com/docs/billing/subscriptions/billing-cycle"))
|
||||
Instant billingCycleAnchor,
|
||||
|
||||
@@ -631,7 +673,10 @@ public class SubscriptionController {
|
||||
UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.increment();
|
||||
return Response.ok(new GetReceiptCredentialsResponse(receiptCredentialResponse.serialize())).build();
|
||||
});
|
||||
})
|
||||
.exceptionally(ExceptionUtils.exceptionallyHandler(
|
||||
SubscriptionException.ReceiptRequestedForOpenPayment.class,
|
||||
e -> Response.noContent().build()));
|
||||
}
|
||||
|
||||
@POST
|
||||
|
||||
+3
-2
@@ -397,8 +397,9 @@ public class VerificationController {
|
||||
Tag.of(SCORE_TAG_NAME, assessmentResult.getScoreString())))
|
||||
.increment();
|
||||
|
||||
} catch (IOException e) {
|
||||
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE);
|
||||
} catch (final IOException e) {
|
||||
logger.error("error assessing captcha", e);
|
||||
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE, e);
|
||||
}
|
||||
|
||||
if (assessmentResult.isValid(captchaScoreThreshold)) {
|
||||
|
||||
+3
-3
@@ -27,7 +27,7 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.CurrencyConversionEntity;
|
||||
import org.whispersystems.textsecuregcm.entities.CurrencyConversionEntityList;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
|
||||
public class CurrencyConversionManager implements Managed {
|
||||
|
||||
@@ -47,7 +47,7 @@ public class CurrencyConversionManager implements Managed {
|
||||
|
||||
private final CoinMarketCapClient coinMarketCapClient;
|
||||
|
||||
private final FaultTolerantRedisCluster cacheCluster;
|
||||
private final FaultTolerantRedisClusterClient cacheCluster;
|
||||
|
||||
private final Clock clock;
|
||||
|
||||
@@ -67,7 +67,7 @@ public class CurrencyConversionManager implements Managed {
|
||||
public CurrencyConversionManager(
|
||||
final FixerClient fixerClient,
|
||||
final CoinMarketCapClient coinMarketCapClient,
|
||||
final FaultTolerantRedisCluster cacheCluster,
|
||||
final FaultTolerantRedisClusterClient cacheCluster,
|
||||
final List<String> currencies,
|
||||
final ScheduledExecutorService executor,
|
||||
final Clock clock) {
|
||||
|
||||
+3
@@ -27,6 +27,9 @@ public record AccountIdentityResponse(
|
||||
@JsonDeserialize(using = ByteArrayBase64UrlAdapter.Deserializing.class)
|
||||
@Nullable byte[] usernameHash,
|
||||
|
||||
@Schema(description="this account's username link handle, if set")
|
||||
@Nullable UUID usernameLinkHandle,
|
||||
|
||||
@Schema(description="whether any of this account's devices support storage")
|
||||
boolean storageCapable) {
|
||||
}
|
||||
+1
-2
@@ -7,6 +7,5 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
|
||||
public record ApnRegistrationId(@NotEmpty String apnRegistrationId,
|
||||
@Nullable String voipRegistrationId) {
|
||||
public record ApnRegistrationId(@NotEmpty String apnRegistrationId) {
|
||||
}
|
||||
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayBase64WithPaddingAdapter;
|
||||
|
||||
public record DeviceInfo(long id,
|
||||
@@ -17,4 +18,8 @@ public record DeviceInfo(long id,
|
||||
|
||||
long lastSeen,
|
||||
long created) {
|
||||
|
||||
public static DeviceInfo forDevice(final Device device) {
|
||||
return new DeviceInfo(device.getId(), device.getName(), device.getLastSeen(), device.getCreated());
|
||||
}
|
||||
}
|
||||
+5
-1
@@ -5,7 +5,11 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
|
||||
public record ProvisioningMessage(@NotEmpty String body) {
|
||||
public record ProvisioningMessage(
|
||||
@Schema(description = "The MIME base64-encoded body of the provisioning message to send to the destination device")
|
||||
@NotEmpty
|
||||
String body) {
|
||||
}
|
||||
+1
-3
@@ -8,13 +8,11 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
|
||||
public record UserCapabilities(
|
||||
// TODO: Remove the paymentActivation capability entirely sometime soon after 2024-10-07
|
||||
boolean paymentActivation,
|
||||
boolean deleteSync,
|
||||
boolean versionedExpirationTimer) {
|
||||
|
||||
public static UserCapabilities createForAccount(final Account account) {
|
||||
return new UserCapabilities(true, account.isDeleteSyncSupported(),
|
||||
return new UserCapabilities(account.isDeleteSyncSupported(),
|
||||
account.isVersionedExpirationTimerSupported());
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import java.util.concurrent.Executor;
|
||||
import java.util.function.Supplier;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/**
|
||||
* An experiment compares the results of two operations and records metrics to assess how frequently they match.
|
||||
@@ -70,6 +71,14 @@ public class Experiment {
|
||||
this.experimentNullMismatchTimer = experimentNullMismatchTimer;
|
||||
}
|
||||
|
||||
public <T> void compareMonoResult(final T expected, final Mono<T> experimentMono) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
experimentMono.subscribe(
|
||||
actual -> recordResult(expected, actual, sample),
|
||||
cause -> recordError(cause, sample));
|
||||
}
|
||||
|
||||
public <T> void compareFutureResult(final T expected, final CompletionStage<T> experimentStage) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
|
||||
+24
-8
@@ -5,11 +5,11 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.experiment;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.util.Optional;
|
||||
import java.util.Random;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicExperimentEnrollmentConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicPreRegistrationExperimentEnrollmentConfiguration;
|
||||
@@ -40,16 +40,32 @@ public class ExperimentEnrollmentManager {
|
||||
final Optional<DynamicExperimentEnrollmentConfiguration> maybeConfiguration = dynamicConfigurationManager
|
||||
.getConfiguration().getExperimentEnrollmentConfiguration(experimentName);
|
||||
|
||||
return maybeConfiguration.map(config -> {
|
||||
return maybeConfiguration
|
||||
.map(config -> isAccountEnrolled(accountUuid, config)
|
||||
.orElse(isEnrolled(accountUuid, config.getEnrollmentPercentage(), experimentName))
|
||||
).orElse(false);
|
||||
}
|
||||
|
||||
if (config.getUuidSelector().getUuids().contains(accountUuid)) {
|
||||
final int r = random.nextInt(100);
|
||||
return r < config.getUuidSelector().getUuidEnrollmentPercentage();
|
||||
}
|
||||
Optional<Boolean> isAccountEnrolled(final UUID accountUuid, DynamicExperimentEnrollmentConfiguration config) {
|
||||
if (config.getExcludedUuids().contains(accountUuid)) {
|
||||
return Optional.of(false);
|
||||
}
|
||||
if (config.getUuidSelector().getUuids().contains(accountUuid)) {
|
||||
final int r = random.nextInt(100);
|
||||
return Optional.of(r < config.getUuidSelector().getUuidEnrollmentPercentage());
|
||||
}
|
||||
|
||||
return isEnrolled(accountUuid, config.getEnrollmentPercentage(), experimentName);
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
}).orElse(false);
|
||||
public boolean isEnrolled(final String e164, final UUID accountUuid, final String experimentName) {
|
||||
|
||||
final Optional<DynamicExperimentEnrollmentConfiguration> maybeConfiguration = dynamicConfigurationManager
|
||||
.getConfiguration().getExperimentEnrollmentConfiguration(experimentName);
|
||||
|
||||
return maybeConfiguration
|
||||
.flatMap(config -> isAccountEnrolled(accountUuid, config))
|
||||
.orElse(isEnrolled(e164, experimentName));
|
||||
}
|
||||
|
||||
public boolean isEnrolled(final String e164, final String experimentName) {
|
||||
|
||||
+1
-2
@@ -54,8 +54,7 @@ abstract class IdleDevicePushNotificationExperiment implements PushNotificationE
|
||||
|
||||
@VisibleForTesting
|
||||
boolean hasPushToken(final Device device) {
|
||||
// Exclude VOIP tokens since they have their own, distinct delivery mechanism
|
||||
return !StringUtils.isAllBlank(device.getApnId(), device.getGcmId()) && StringUtils.isBlank(device.getVoipApnId());
|
||||
return !StringUtils.isAllBlank(device.getApnId(), device.getGcmId());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
-76
@@ -1,76 +0,0 @@
|
||||
package org.whispersystems.textsecuregcm.experiment;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.push.IdleDeviceNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalTime;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public class NotifyIdleDevicesWithMessagesExperiment extends IdleDevicePushNotificationExperiment {
|
||||
|
||||
private final IdleDeviceNotificationScheduler idleDeviceNotificationScheduler;
|
||||
private final MessagesManager messagesManager;
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration MIN_IDLE_DURATION = Duration.ofDays(3);
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration MAX_IDLE_DURATION = Duration.ofDays(14);
|
||||
|
||||
@VisibleForTesting
|
||||
static final LocalTime PREFERRED_NOTIFICATION_TIME = LocalTime.of(14, 0);
|
||||
|
||||
public NotifyIdleDevicesWithMessagesExperiment(final IdleDeviceNotificationScheduler idleDeviceNotificationScheduler,
|
||||
final MessagesManager messagesManager,
|
||||
final Clock clock) {
|
||||
|
||||
super(clock);
|
||||
|
||||
this.idleDeviceNotificationScheduler = idleDeviceNotificationScheduler;
|
||||
this.messagesManager = messagesManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Duration getMinIdleDuration() {
|
||||
return MIN_IDLE_DURATION;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Duration getMaxIdleDuration() {
|
||||
return MAX_IDLE_DURATION;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getExperimentName() {
|
||||
return "notify-idle-devices-with-messages";
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Boolean> isDeviceEligible(final Account account, final Device device) {
|
||||
|
||||
if (!hasPushToken(device)) {
|
||||
return CompletableFuture.completedFuture(false);
|
||||
}
|
||||
|
||||
if (!isIdle(device)) {
|
||||
return CompletableFuture.completedFuture(false);
|
||||
}
|
||||
|
||||
return messagesManager.mayHavePersistedMessages(account.getIdentifier(IdentityType.ACI), device);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<DeviceLastSeenState> getStateClass() {
|
||||
return DeviceLastSeenState.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> applyExperimentTreatment(final Account account, final Device device) {
|
||||
return idleDeviceNotificationScheduler.scheduleNotification(account, device, PREFERRED_NOTIFICATION_TIME);
|
||||
}
|
||||
}
|
||||
+23
-4
@@ -5,18 +5,37 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.filters;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.ws.rs.container.ContainerRequestContext;
|
||||
import javax.ws.rs.container.ContainerResponseContext;
|
||||
import javax.ws.rs.container.ContainerResponseFilter;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Injects a timestamp header into all outbound responses.
|
||||
*/
|
||||
public class TimestampResponseFilter implements ContainerResponseFilter {
|
||||
public class TimestampResponseFilter implements Filter, ContainerResponseFilter {
|
||||
|
||||
@Override
|
||||
public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext) {
|
||||
responseContext.getHeaders().add(HeaderUtils.TIMESTAMP_HEADER, System.currentTimeMillis());
|
||||
@Override
|
||||
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
|
||||
throws ServletException, IOException {
|
||||
|
||||
if (response instanceof HttpServletResponse httpServletResponse) {
|
||||
httpServletResponse.setHeader(HeaderUtils.TIMESTAMP_HEADER, String.valueOf(System.currentTimeMillis()));
|
||||
}
|
||||
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
|
||||
// not using add() - it's ok to overwrite any existing header, and we don't want a multi-value
|
||||
responseContext.getHeaders().putSingle(HeaderUtils.TIMESTAMP_HEADER, System.currentTimeMillis());
|
||||
}
|
||||
}
|
||||
+3
-10
@@ -110,7 +110,6 @@ public class DevicesGrpcService extends ReactorDevicesGrpc.DevicesImplBase {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
@Nullable final String apnsToken;
|
||||
@Nullable final String apnsVoipToken;
|
||||
@Nullable final String fcmToken;
|
||||
|
||||
switch (request.getTokenRequestCase()) {
|
||||
@@ -118,12 +117,11 @@ public class DevicesGrpcService extends ReactorDevicesGrpc.DevicesImplBase {
|
||||
case APNS_TOKEN_REQUEST -> {
|
||||
final SetPushTokenRequest.ApnsTokenRequest apnsTokenRequest = request.getApnsTokenRequest();
|
||||
|
||||
if (StringUtils.isAllBlank(apnsTokenRequest.getApnsToken(), apnsTokenRequest.getApnsVoipToken())) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("APNs tokens may not both be blank").asRuntimeException();
|
||||
if (StringUtils.isBlank(apnsTokenRequest.getApnsToken())) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("APNs token must not be blank").asRuntimeException();
|
||||
}
|
||||
|
||||
apnsToken = StringUtils.stripToNull(apnsTokenRequest.getApnsToken());
|
||||
apnsVoipToken = StringUtils.stripToNull(apnsTokenRequest.getApnsVoipToken());
|
||||
fcmToken = null;
|
||||
}
|
||||
|
||||
@@ -135,7 +133,6 @@ public class DevicesGrpcService extends ReactorDevicesGrpc.DevicesImplBase {
|
||||
}
|
||||
|
||||
apnsToken = null;
|
||||
apnsVoipToken = null;
|
||||
fcmToken = StringUtils.stripToNull(fcmTokenRequest.getFcmToken());
|
||||
}
|
||||
|
||||
@@ -150,14 +147,12 @@ public class DevicesGrpcService extends ReactorDevicesGrpc.DevicesImplBase {
|
||||
|
||||
final boolean tokenUnchanged =
|
||||
Objects.equals(device.getApnId(), apnsToken) &&
|
||||
Objects.equals(device.getVoipApnId(), apnsVoipToken) &&
|
||||
Objects.equals(device.getGcmId(), fcmToken);
|
||||
|
||||
return tokenUnchanged
|
||||
? Mono.empty()
|
||||
: Mono.fromFuture(() -> accountsManager.updateDeviceAsync(account, authenticatedDevice.deviceId(), d -> {
|
||||
d.setApnId(apnsToken);
|
||||
d.setVoipApnId(apnsVoipToken);
|
||||
d.setGcmId(fcmToken);
|
||||
d.setFetchesMessages(false);
|
||||
}));
|
||||
@@ -172,14 +167,13 @@ public class DevicesGrpcService extends ReactorDevicesGrpc.DevicesImplBase {
|
||||
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
|
||||
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
|
||||
.flatMap(account -> Mono.fromFuture(() -> accountsManager.updateDeviceAsync(account, authenticatedDevice.deviceId(), device -> {
|
||||
if (StringUtils.isNotBlank(device.getApnId()) || StringUtils.isNotBlank(device.getVoipApnId())) {
|
||||
if (StringUtils.isNotBlank(device.getApnId())) {
|
||||
device.setUserAgent(device.isPrimary() ? "OWI" : "OWP");
|
||||
} else if (StringUtils.isNotBlank(device.getGcmId())) {
|
||||
device.setUserAgent("OWA");
|
||||
}
|
||||
|
||||
device.setApnId(null);
|
||||
device.setVoipApnId(null);
|
||||
device.setGcmId(null);
|
||||
device.setFetchesMessages(true);
|
||||
})))
|
||||
@@ -197,7 +191,6 @@ public class DevicesGrpcService extends ReactorDevicesGrpc.DevicesImplBase {
|
||||
d -> d.setCapabilities(new Device.DeviceCapabilities(
|
||||
request.getStorage(),
|
||||
request.getTransfer(),
|
||||
request.getPaymentActivation(),
|
||||
request.getDeleteSync(),
|
||||
request.getVersionedExpirationTimer())))))
|
||||
.thenReturn(SetCapabilitiesResponse.newBuilder().build());
|
||||
|
||||
@@ -82,7 +82,6 @@ public class ProfileGrpcHelper {
|
||||
@VisibleForTesting
|
||||
static UserCapabilities buildUserCapabilities(final org.whispersystems.textsecuregcm.entities.UserCapabilities capabilities) {
|
||||
return UserCapabilities.newBuilder()
|
||||
.setPaymentActivation(capabilities.paymentActivation())
|
||||
.setDeleteSync(capabilities.deleteSync())
|
||||
.setVersionedExpirationTimer(capabilities.versionedExpirationTimer())
|
||||
.build();
|
||||
|
||||
+7
-9
@@ -19,13 +19,11 @@ import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import io.grpc.TlsChannelCredentials;
|
||||
import katie.ConsistencyParameters;
|
||||
import katie.KatieGrpc;
|
||||
import katie.MonitorKey;
|
||||
import katie.MonitorRequest;
|
||||
import katie.MonitorResponse;
|
||||
import katie.SearchRequest;
|
||||
import katie.SearchResponse;
|
||||
import org.signal.keytransparency.client.ConsistencyParameters;
|
||||
import org.signal.keytransparency.client.KeyTransparencyQueryServiceGrpc;
|
||||
import org.signal.keytransparency.client.MonitorKey;
|
||||
import org.signal.keytransparency.client.MonitorRequest;
|
||||
import org.signal.keytransparency.client.SearchRequest;
|
||||
import org.whispersystems.textsecuregcm.util.CompletableFutureUtil;
|
||||
|
||||
public class KeyTransparencyServiceClient implements Managed {
|
||||
@@ -35,7 +33,7 @@ public class KeyTransparencyServiceClient implements Managed {
|
||||
private final int port;
|
||||
private final ChannelCredentials tlsChannelCredentials;
|
||||
private ManagedChannel channel;
|
||||
private KatieGrpc.KatieFutureStub stub;
|
||||
private KeyTransparencyQueryServiceGrpc.KeyTransparencyQueryServiceFutureStub stub;
|
||||
|
||||
public KeyTransparencyServiceClient(
|
||||
final String host,
|
||||
@@ -100,7 +98,7 @@ public class KeyTransparencyServiceClient implements Managed {
|
||||
channel = Grpc.newChannelBuilderForAddress(host, port, tlsChannelCredentials)
|
||||
.idleTimeout(1, TimeUnit.MINUTES)
|
||||
.build();
|
||||
stub = KatieGrpc.newFutureStub(channel);
|
||||
stub = KeyTransparencyQueryServiceGrpc.newFutureStub(channel);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -22,7 +22,7 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
|
||||
public abstract class BaseRateLimiters<T extends RateLimiterDescriptor> {
|
||||
@@ -39,7 +39,7 @@ public abstract class BaseRateLimiters<T extends RateLimiterDescriptor> {
|
||||
final Map<String, RateLimiterConfig> configs,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final ClusterLuaScript validateScript,
|
||||
final FaultTolerantRedisCluster cacheCluster,
|
||||
final FaultTolerantRedisClusterClient cacheCluster,
|
||||
final Clock clock) {
|
||||
this.configs = configs;
|
||||
this.rateLimiterByDescriptor = Arrays.stream(values)
|
||||
@@ -69,7 +69,7 @@ public abstract class BaseRateLimiters<T extends RateLimiterDescriptor> {
|
||||
}
|
||||
}
|
||||
|
||||
protected static ClusterLuaScript defaultScript(final FaultTolerantRedisCluster cacheCluster) {
|
||||
protected static ClusterLuaScript defaultScript(final FaultTolerantRedisClusterClient cacheCluster) {
|
||||
try {
|
||||
return ClusterLuaScript.fromResource(
|
||||
cacheCluster, "lua/validate_rate_limit.lua", ScriptOutputType.INTEGER);
|
||||
@@ -83,7 +83,7 @@ public abstract class BaseRateLimiters<T extends RateLimiterDescriptor> {
|
||||
final Map<String, RateLimiterConfig> configs,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final ClusterLuaScript validateScript,
|
||||
final FaultTolerantRedisCluster cacheCluster,
|
||||
final FaultTolerantRedisClusterClient cacheCluster,
|
||||
final Clock clock) {
|
||||
if (descriptor.isDynamic()) {
|
||||
final Supplier<RateLimiterConfig> configResolver = () -> {
|
||||
|
||||
+3
-3
@@ -12,7 +12,7 @@ import java.time.Duration;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
/**
|
||||
@@ -21,11 +21,11 @@ import org.whispersystems.textsecuregcm.util.Util;
|
||||
public class CardinalityEstimator {
|
||||
|
||||
private volatile double uniqueElementCount;
|
||||
private final FaultTolerantRedisCluster redisCluster;
|
||||
private final FaultTolerantRedisClusterClient redisCluster;
|
||||
private final String hllName;
|
||||
private final Duration period;
|
||||
|
||||
public CardinalityEstimator(final FaultTolerantRedisCluster redisCluster, final String name, final Duration period) {
|
||||
public CardinalityEstimator(final FaultTolerantRedisClusterClient redisCluster, final String name, final Duration period) {
|
||||
this.redisCluster = redisCluster;
|
||||
this.hllName = "cardinality_estimator::" + name;
|
||||
this.period = period;
|
||||
|
||||
+3
-3
@@ -15,7 +15,7 @@ import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
|
||||
public class DynamicRateLimiter implements RateLimiter {
|
||||
@@ -26,7 +26,7 @@ public class DynamicRateLimiter implements RateLimiter {
|
||||
|
||||
private final ClusterLuaScript validateScript;
|
||||
|
||||
private final FaultTolerantRedisCluster cluster;
|
||||
private final FaultTolerantRedisClusterClient cluster;
|
||||
|
||||
private final Clock clock;
|
||||
|
||||
@@ -38,7 +38,7 @@ public class DynamicRateLimiter implements RateLimiter {
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final Supplier<RateLimiterConfig> configResolver,
|
||||
final ClusterLuaScript validateScript,
|
||||
final FaultTolerantRedisCluster cluster,
|
||||
final FaultTolerantRedisClusterClient cluster,
|
||||
final Clock clock) {
|
||||
this.name = requireNonNull(name);
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
|
||||
+2
-2
@@ -11,7 +11,7 @@ import java.util.concurrent.CompletableFuture;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
|
||||
public class MessageDeliveryLoopMonitor {
|
||||
|
||||
@@ -22,7 +22,7 @@ public class MessageDeliveryLoopMonitor {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessageDeliveryLoopMonitor.class);
|
||||
|
||||
public MessageDeliveryLoopMonitor(final FaultTolerantRedisCluster rateLimitCluster) {
|
||||
public MessageDeliveryLoopMonitor(final FaultTolerantRedisClusterClient rateLimitCluster) {
|
||||
try {
|
||||
getDeliveryAttemptsScript =
|
||||
ClusterLuaScript.fromResource(rateLimitCluster, "lua/get_delivery_attempt_count.lua", ScriptOutputType.INTEGER);
|
||||
|
||||
+14
-1
@@ -22,6 +22,11 @@ import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
|
||||
public class RateLimitByIpFilter implements ContainerRequestFilter {
|
||||
|
||||
@@ -33,8 +38,9 @@ public class RateLimitByIpFilter implements ContainerRequestFilter {
|
||||
|
||||
private static final ExceptionMapper<RateLimitExceededException> EXCEPTION_MAPPER = new RateLimitExceededExceptionMapper();
|
||||
|
||||
private final RateLimiters rateLimiters;
|
||||
private static final String NO_IP_COUNTER_NAME = MetricsUtil.name(RateLimitByIpFilter.class, "noIpAddress");
|
||||
|
||||
private final RateLimiters rateLimiters;
|
||||
|
||||
public RateLimitByIpFilter(final RateLimiters rateLimiters) {
|
||||
this.rateLimiters = requireNonNull(rateLimiters);
|
||||
@@ -65,6 +71,13 @@ public class RateLimitByIpFilter implements ContainerRequestFilter {
|
||||
|
||||
// checking if we failed to extract the most recent IP for any reason
|
||||
if (remoteAddress.isEmpty()) {
|
||||
Metrics.counter(
|
||||
NO_IP_COUNTER_NAME,
|
||||
Tags.of(
|
||||
Tag.of("limiter", handle.id()),
|
||||
Tag.of("fail", String.valueOf(annotation.failOnUnresolvedIp()))))
|
||||
.increment();
|
||||
|
||||
// checking if annotation is configured to fail when the most recent IP is not resolved
|
||||
if (annotation.failOnUnresolvedIp()) {
|
||||
logger.error("Remote address was null");
|
||||
|
||||
@@ -11,7 +11,7 @@ import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
|
||||
public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
|
||||
@@ -24,8 +24,8 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
|
||||
PRE_KEYS("prekeys", false, new RateLimiterConfig(6, Duration.ofMinutes(10))),
|
||||
MESSAGES("messages", false, new RateLimiterConfig(60, Duration.ofSeconds(1))),
|
||||
STORIES("stories", false, new RateLimiterConfig(5_000, Duration.ofSeconds(8))),
|
||||
ALLOCATE_DEVICE("allocateDevice", false, new RateLimiterConfig(2, Duration.ofMinutes(2))),
|
||||
VERIFY_DEVICE("verifyDevice", false, new RateLimiterConfig(6, Duration.ofMinutes(10))),
|
||||
ALLOCATE_DEVICE("allocateDevice", false, new RateLimiterConfig(6, Duration.ofMinutes(2))),
|
||||
VERIFY_DEVICE("verifyDevice", false, new RateLimiterConfig(6, Duration.ofMinutes(2))),
|
||||
TURN("turnAllocate", false, new RateLimiterConfig(60, Duration.ofSeconds(1))),
|
||||
PROFILE("profile", false, new RateLimiterConfig(4320, Duration.ofSeconds(20))),
|
||||
STICKER_PACK("stickerPack", false, new RateLimiterConfig(50, Duration.ofMinutes(72))),
|
||||
@@ -50,6 +50,7 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
|
||||
EXTERNAL_SERVICE_CREDENTIALS("externalServiceCredentials", true, new RateLimiterConfig(100, Duration.ofMinutes(15))),
|
||||
KEY_TRANSPARENCY_SEARCH_PER_IP("keyTransparencySearch", true, new RateLimiterConfig(100, Duration.ofSeconds(15))),
|
||||
KEY_TRANSPARENCY_MONITOR_PER_IP("keyTransparencyMonitor", true, new RateLimiterConfig(100, Duration.ofSeconds(15))),
|
||||
WAIT_FOR_LINKED_DEVICE("waitForLinkedDevice", true, new RateLimiterConfig(10, Duration.ofSeconds(30))),
|
||||
;
|
||||
|
||||
private final String id;
|
||||
@@ -81,7 +82,7 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
|
||||
public static RateLimiters createAndValidate(
|
||||
final Map<String, RateLimiterConfig> configs,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final FaultTolerantRedisCluster cacheCluster) {
|
||||
final FaultTolerantRedisClusterClient cacheCluster) {
|
||||
final RateLimiters rateLimiters = new RateLimiters(
|
||||
configs, dynamicConfigurationManager, defaultScript(cacheCluster), cacheCluster, Clock.systemUTC());
|
||||
rateLimiters.validateValuesAndConfigs();
|
||||
@@ -93,7 +94,7 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
|
||||
final Map<String, RateLimiterConfig> configs,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final ClusterLuaScript validateScript,
|
||||
final FaultTolerantRedisCluster cacheCluster,
|
||||
final FaultTolerantRedisClusterClient cacheCluster,
|
||||
final Clock clock) {
|
||||
super(For.values(), configs, dynamicConfigurationManager, validateScript, cacheCluster, clock);
|
||||
}
|
||||
@@ -205,4 +206,8 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
|
||||
public RateLimiter getStoriesLimiter() {
|
||||
return forDescriptor(For.STORIES);
|
||||
}
|
||||
|
||||
public RateLimiter getWaitForLinkedDeviceLimiter() {
|
||||
return forDescriptor(For.WAIT_FOR_LINKED_DEVICE);
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -20,7 +20,7 @@ import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfigurati
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
@@ -36,7 +36,7 @@ public class StaticRateLimiter implements RateLimiter {
|
||||
|
||||
private final ClusterLuaScript validateScript;
|
||||
|
||||
private final FaultTolerantRedisCluster cacheCluster;
|
||||
private final FaultTolerantRedisClusterClient cacheCluster;
|
||||
|
||||
private final Clock clock;
|
||||
|
||||
@@ -45,7 +45,7 @@ public class StaticRateLimiter implements RateLimiter {
|
||||
final String name,
|
||||
final RateLimiterConfig config,
|
||||
final ClusterLuaScript validateScript,
|
||||
final FaultTolerantRedisCluster cacheCluster,
|
||||
final FaultTolerantRedisClusterClient cacheCluster,
|
||||
final Clock clock,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
this.name = requireNonNull(name);
|
||||
|
||||
+32
@@ -5,17 +5,48 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.mappers;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.jersey.errors.ErrorMessage;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.ext.ExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionException;
|
||||
import java.util.Map;
|
||||
|
||||
public class SubscriptionExceptionMapper implements ExceptionMapper<SubscriptionException> {
|
||||
@VisibleForTesting
|
||||
public static final int PROCESSOR_ERROR_STATUS_CODE = 440;
|
||||
|
||||
@Override
|
||||
public Response toResponse(final SubscriptionException exception) {
|
||||
|
||||
// Some exceptions have specific error body formats
|
||||
if (exception instanceof SubscriptionException.AmountTooSmall e) {
|
||||
return Response
|
||||
.status(Response.Status.BAD_REQUEST)
|
||||
.entity(Map.of("error", "amount_too_small"))
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
.build();
|
||||
}
|
||||
if (exception instanceof SubscriptionException.ProcessorException e) {
|
||||
return Response.status(PROCESSOR_ERROR_STATUS_CODE)
|
||||
.entity(Map.of(
|
||||
"processor", e.getProcessor().name(),
|
||||
"chargeFailure", e.getChargeFailure()
|
||||
))
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
.build();
|
||||
}
|
||||
if (exception instanceof SubscriptionException.ChargeFailurePaymentRequired e) {
|
||||
return Response
|
||||
.status(Response.Status.PAYMENT_REQUIRED)
|
||||
.entity(Map.of("chargeFailure", e.getChargeFailure()))
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
.build();
|
||||
}
|
||||
|
||||
// Otherwise, we'll return a generic error message WebApplicationException, with a detailed error if one is provided
|
||||
final Response.Status status = (switch (exception) {
|
||||
case SubscriptionException.NotFound e -> Response.Status.NOT_FOUND;
|
||||
case SubscriptionException.Forbidden e -> Response.Status.FORBIDDEN;
|
||||
@@ -36,5 +67,6 @@ public class SubscriptionExceptionMapper implements ExceptionMapper<Subscription
|
||||
.fromResponse(wae.getResponse())
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
.entity(new ErrorMessage(wae.getResponse().getStatus(), wae.getLocalizedMessage())).build();
|
||||
|
||||
}
|
||||
}
|
||||
-26
@@ -1,26 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.mappers;
|
||||
|
||||
import java.util.Map;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.ext.ExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
|
||||
|
||||
public class SubscriptionProcessorExceptionMapper implements ExceptionMapper<SubscriptionProcessorException> {
|
||||
|
||||
public static final int EXTERNAL_SERVICE_ERROR_STATUS_CODE = 440;
|
||||
|
||||
@Override
|
||||
public Response toResponse(final SubscriptionProcessorException exception) {
|
||||
return Response.status(EXTERNAL_SERVICE_ERROR_STATUS_CODE)
|
||||
.entity(Map.of(
|
||||
"processor", exception.getProcessor().name(),
|
||||
"chargeFailure", exception.getChargeFailure()
|
||||
))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
package org.whispersystems.textsecuregcm.metrics;
|
||||
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import software.amazon.awssdk.metrics.MetricCollection;
|
||||
import software.amazon.awssdk.metrics.MetricPublisher;
|
||||
import software.amazon.awssdk.metrics.MetricRecord;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* A Micrometer AWS SDK metric publisher consumes {@link MetricCollection} instances provided by the AWS SDK when it
|
||||
* makes calls to the AWS API and publishes a subset of metrics from each call via the Micrometer metrics facade. A
|
||||
* single {@code MicrometerAwsSdkMetricPublisher} should be bound to a single AWS service client instance; publishers
|
||||
* should not be assigned to multiple service clients.
|
||||
*
|
||||
* @see <a href="https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/metrics-list.html">Service client metrics</a>
|
||||
*/
|
||||
public class MicrometerAwsSdkMetricPublisher implements MetricPublisher {
|
||||
|
||||
private final ExecutorService recordMetricsExecutorService;
|
||||
|
||||
private final String awsClientName;
|
||||
private final AtomicInteger mostRecentMaxConcurrency;
|
||||
|
||||
// Note that these metric collection type names don't seem to appear anywhere in the AWS SDK documentation. The docs
|
||||
// also hint at, but don't explicitly call out, the structure of a `MetricCollection` passed to the `#publish(...)`
|
||||
// method. Empirically, for each AWS SDK operation, the SDK will call `#publish(...)` with a collection structured as
|
||||
// follows:
|
||||
//
|
||||
// MetricCollection { name = "ApiCall" }
|
||||
// +-- MetricRecord { name = "ApiCallDuration" }
|
||||
// +-- MetricRecord { name = "ApiCallSuccessful" }
|
||||
// +-- ...
|
||||
// +-- MetricCollection { name = "ApiCallAttempt" }
|
||||
// +-- MetricRecord { name = "AwsExtendedRequestId" }
|
||||
// +-- MetricRecord { name = "AwsRequestId" }
|
||||
// +-- ...
|
||||
// +-- MetricCollection {name = "HttpClient" }
|
||||
// +-- MetricRecord { name = "AvailableConcurrency" }
|
||||
// +-- MetricRecord { name = "ConcurrencyAcquireDuration" }
|
||||
// +-- ...
|
||||
// +-- MetricCollection { name = "ApiCallAttempt" }
|
||||
// +-- MetricRecord { name = "AwsExtendedRequestId" }
|
||||
// +-- MetricRecord { name = "AwsRequestId" }
|
||||
// +-- ...
|
||||
// +-- MetricCollection {name = "HttpClient" }
|
||||
// +-- MetricRecord { name = "AvailableConcurrency" }
|
||||
// +-- MetricRecord { name = "ConcurrencyAcquireDuration" }
|
||||
// +-- ...
|
||||
// +-- ...
|
||||
//
|
||||
// Every `MetricCollection` passed to `#publish(...)` should have a name of "ApiCall," and the "ApiCall" collection
|
||||
// will have a fixed collection of named metrics (which ARE documented!). The "ApiCall" collection should have one or
|
||||
// more "ApiCallAttempt" `MetricCollection` as children, and each "ApiCallAttempt" collection should have exactly one
|
||||
// "HttpClient" `MetricCollection` as a child.
|
||||
private static final String METRIC_COLLECTION_TYPE_API_CALL = "ApiCall";
|
||||
private static final String METRIC_COLLECTION_TYPE_API_CALL_ATTEMPT = "ApiCallAttempt";
|
||||
private static final String METRIC_COLLECTION_TYPE_HTTP_METRICS = "HttpClient";
|
||||
|
||||
private static final String API_CALL_COUNTER_NAME =
|
||||
MetricsUtil.name(MicrometerAwsSdkMetricPublisher.class, "apiCall");
|
||||
|
||||
private static final String API_CALL_RETRY_COUNT_DISTRIBUTION_NAME =
|
||||
MetricsUtil.name(MicrometerAwsSdkMetricPublisher.class, "apiCallRetries");
|
||||
|
||||
private static final String CHANNEL_ACQUISITION_TIMER_NAME =
|
||||
MetricsUtil.name(MicrometerAwsSdkMetricPublisher.class, "acquireChannelDuration");
|
||||
|
||||
private static final String PENDING_CHANNEL_ACQUISITIONS_DISTRIBUTION_NAME =
|
||||
MetricsUtil.name(MicrometerAwsSdkMetricPublisher.class, "pendingChannelAcquisitions");
|
||||
|
||||
private static final String CONCURRENT_REQUESTS_DISTRIBUTION_NAME =
|
||||
MetricsUtil.name(MicrometerAwsSdkMetricPublisher.class, "concurrentRequests");
|
||||
|
||||
private static final String CLIENT_NAME_TAG = "clientName";
|
||||
|
||||
/**
|
||||
* Constructs a new metric publisher that uses the given executor service to record metrics and tags metrics with the
|
||||
* given client name.
|
||||
*
|
||||
* @param recordMetricsExecutorService the executor service via which to record metrics
|
||||
* @param awsClientName the name of AWS service client to which this publisher is attached
|
||||
*/
|
||||
public MicrometerAwsSdkMetricPublisher(final ExecutorService recordMetricsExecutorService, final String awsClientName) {
|
||||
this.recordMetricsExecutorService = recordMetricsExecutorService;
|
||||
this.awsClientName = awsClientName;
|
||||
|
||||
mostRecentMaxConcurrency = Metrics.gauge("maxConcurrency",
|
||||
Tags.of(CLIENT_NAME_TAG, awsClientName),
|
||||
new AtomicInteger(0));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void publish(final MetricCollection metricCollection) {
|
||||
/* if (METRIC_COLLECTION_TYPE_API_CALL.equals(metricCollection.name())) {
|
||||
try {
|
||||
recordMetricsExecutorService.submit(() -> recordApiCallMetrics(metricCollection));
|
||||
} catch (final RejectedExecutionException ignored) {
|
||||
// This can happen if clients make new calls to an upstream service while the server is shutting down
|
||||
}
|
||||
} */
|
||||
}
|
||||
|
||||
private void recordApiCallMetrics(final MetricCollection apiCallMetricCollection) {
|
||||
if (!apiCallMetricCollection.name().equals(METRIC_COLLECTION_TYPE_API_CALL)) {
|
||||
throw new IllegalArgumentException("Unexpected API call metric collection name: " + apiCallMetricCollection.name());
|
||||
}
|
||||
|
||||
final Map<String, MetricRecord<?>> metricsByName = toMetricMap(apiCallMetricCollection);
|
||||
|
||||
final Optional<String> maybeAwsServiceId = Optional.ofNullable(metricsByName.get("ServiceId"))
|
||||
.map(metricRecord -> (String) metricRecord.value());
|
||||
|
||||
final Optional<String> maybeOperationName = Optional.ofNullable(metricsByName.get("OperationName"))
|
||||
.map(metricRecord -> (String) metricRecord.value());
|
||||
|
||||
// Both the service ID and operation name SHOULD always be present, but since the metric collection is unstructured,
|
||||
// we don't have any compile-time guarantees and so check that they're both present as a pedantic safety check.
|
||||
if (maybeAwsServiceId.isPresent() && maybeOperationName.isPresent()) {
|
||||
final String awsServiceId = maybeAwsServiceId.get();
|
||||
final String operationName = maybeOperationName.get();
|
||||
|
||||
final boolean success = Optional.ofNullable(metricsByName.get("ApiCallSuccessful"))
|
||||
.map(metricRecord -> (boolean) metricRecord.value())
|
||||
.orElse(false);
|
||||
|
||||
final int retryCount = Optional.ofNullable(metricsByName.get("RetryCount"))
|
||||
.map(metricRecord -> (int) metricRecord.value())
|
||||
.orElse(0);
|
||||
|
||||
final Tags tags = Tags.of(
|
||||
CLIENT_NAME_TAG, awsClientName,
|
||||
"awsServiceId", awsServiceId,
|
||||
"operationName", operationName,
|
||||
"callSuccess", String.valueOf(success));
|
||||
|
||||
Metrics.counter(API_CALL_COUNTER_NAME, tags).increment();
|
||||
|
||||
DistributionSummary.builder(API_CALL_RETRY_COUNT_DISTRIBUTION_NAME)
|
||||
.tags(tags)
|
||||
.publishPercentileHistogram(true)
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(retryCount);
|
||||
|
||||
apiCallMetricCollection.childrenWithName(METRIC_COLLECTION_TYPE_API_CALL_ATTEMPT)
|
||||
.forEach(callAttemptMetricCollection -> recordAttemptMetrics(callAttemptMetricCollection, tags));
|
||||
}
|
||||
}
|
||||
|
||||
private void recordAttemptMetrics(final MetricCollection apiCallAttemptMetricCollection, final Tags callTags) {
|
||||
if (!apiCallAttemptMetricCollection.name().equals(METRIC_COLLECTION_TYPE_API_CALL_ATTEMPT)) {
|
||||
throw new IllegalArgumentException("Unexpected API call attempt metric collection name: " + apiCallAttemptMetricCollection.name());
|
||||
}
|
||||
|
||||
// A "call attempt" metric collection should always have exactly one HTTP metrics child collection, but we have no
|
||||
// compiler-level guarantees and so do a pedantic check here just to be safe.
|
||||
apiCallAttemptMetricCollection.childrenWithName(METRIC_COLLECTION_TYPE_HTTP_METRICS).findFirst().ifPresent(httpMetricCollection -> {
|
||||
final Map<String, MetricRecord<?>> callAttemptMetricsByName = toMetricMap(apiCallAttemptMetricCollection);
|
||||
final Map<String, MetricRecord<?>> httpMetricsByName = toMetricMap(httpMetricCollection);
|
||||
|
||||
Optional.ofNullable(httpMetricsByName.get("MaxConcurrency"))
|
||||
.ifPresent(maxConcurrencyMetricRecord -> mostRecentMaxConcurrency.set((int) maxConcurrencyMetricRecord.value()));
|
||||
|
||||
final Tags attemptTags = Optional.ofNullable(callAttemptMetricsByName.get("ErrorType"))
|
||||
.map(errorTypeMetricRecord -> callTags.and("error", errorTypeMetricRecord.value().toString()))
|
||||
.orElse(callTags);
|
||||
|
||||
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()));
|
||||
});
|
||||
}
|
||||
|
||||
private static Map<String, MetricRecord<?>> toMetricMap(final MetricCollection metricCollection) {
|
||||
return metricCollection.stream()
|
||||
.collect(Collectors.toMap(metricRecord -> metricRecord.metric().name(), metricRecord -> metricRecord));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package org.whispersystems.textsecuregcm.metrics;
|
||||
|
||||
import software.amazon.awssdk.metrics.MetricCollection;
|
||||
import software.amazon.awssdk.metrics.MetricPublisher;
|
||||
|
||||
public class NoopAwsSdkMetricPublisher implements MetricPublisher {
|
||||
|
||||
@Override
|
||||
public void publish(final MetricCollection metricCollection) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package org.whispersystems.textsecuregcm.metrics;
|
||||
|
||||
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 org.whispersystems.textsecuregcm.util.EnumMapUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
|
||||
import org.whispersystems.websocket.session.WebSocketSessionContext;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public class OpenWebSocketCounter {
|
||||
|
||||
private final Map<ClientPlatform, AtomicInteger> openWebsocketsByClientPlatform;
|
||||
private final AtomicInteger openWebsocketsFromUnknownPlatforms;
|
||||
|
||||
private final Map<ClientPlatform, Timer> durationTimersByClientPlatform;
|
||||
private final Timer durationTimerForUnknownPlatforms;
|
||||
|
||||
public OpenWebSocketCounter(final String openWebSocketGaugeName, final String durationTimerName) {
|
||||
this(openWebSocketGaugeName, durationTimerName, Tags.empty());
|
||||
}
|
||||
|
||||
public OpenWebSocketCounter(final String openWebSocketGaugeName, final String durationTimerName, final Tags tags) {
|
||||
openWebsocketsByClientPlatform = EnumMapUtil.toEnumMap(ClientPlatform.class,
|
||||
clientPlatform -> buildGauge(openWebSocketGaugeName, clientPlatform.name().toLowerCase(), tags));
|
||||
|
||||
openWebsocketsFromUnknownPlatforms = buildGauge(openWebSocketGaugeName, "unknown", tags);
|
||||
|
||||
durationTimersByClientPlatform = EnumMapUtil.toEnumMap(ClientPlatform.class,
|
||||
clientPlatform -> buildTimer(durationTimerName, clientPlatform.name().toLowerCase(), tags));
|
||||
|
||||
durationTimerForUnknownPlatforms = buildTimer(durationTimerName, "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));
|
||||
}
|
||||
|
||||
private static Timer buildTimer(final String timerName, final String clientPlatformName, final Tags tags) {
|
||||
return Timer.builder(timerName)
|
||||
.publishPercentileHistogram(true)
|
||||
.tags(tags.and(Tag.of(UserAgentTagUtil.PLATFORM_TAG, clientPlatformName)))
|
||||
.register(Metrics.globalRegistry);
|
||||
}
|
||||
|
||||
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 Timer durationTimer;
|
||||
|
||||
{
|
||||
AtomicInteger calculatedOpenWebSocketCounter;
|
||||
Timer calculatedDurationTimer;
|
||||
|
||||
try {
|
||||
final ClientPlatform clientPlatform =
|
||||
UserAgentUtil.parseUserAgentString(context.getClient().getUserAgent()).getPlatform();
|
||||
|
||||
calculatedOpenWebSocketCounter = openWebsocketsByClientPlatform.get(clientPlatform);
|
||||
calculatedDurationTimer = durationTimersByClientPlatform.get(clientPlatform);
|
||||
} catch (final UnrecognizedUserAgentException e) {
|
||||
calculatedOpenWebSocketCounter = openWebsocketsFromUnknownPlatforms;
|
||||
calculatedDurationTimer = durationTimerForUnknownPlatforms;
|
||||
}
|
||||
|
||||
openWebSocketCounter = calculatedOpenWebSocketCounter;
|
||||
durationTimer = calculatedDurationTimer;
|
||||
}
|
||||
|
||||
openWebSocketCounter.incrementAndGet();
|
||||
|
||||
context.addWebsocketClosedListener((context1, statusCode, reason) -> {
|
||||
sample.stop(durationTimer);
|
||||
openWebSocketCounter.decrementAndGet();
|
||||
});
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -6,13 +6,13 @@
|
||||
package org.whispersystems.textsecuregcm.providers;
|
||||
|
||||
import com.codahale.metrics.health.HealthCheck;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
|
||||
public class RedisClusterHealthCheck extends HealthCheck {
|
||||
|
||||
private final FaultTolerantRedisCluster redisCluster;
|
||||
private final FaultTolerantRedisClusterClient redisCluster;
|
||||
|
||||
public RedisClusterHealthCheck(final FaultTolerantRedisCluster redisCluster) {
|
||||
public RedisClusterHealthCheck(final FaultTolerantRedisClusterClient redisCluster) {
|
||||
this.redisCluster = redisCluster;
|
||||
}
|
||||
|
||||
|
||||
@@ -34,12 +34,6 @@ public class APNSender implements Managed, PushNotificationSender {
|
||||
private final String bundleId;
|
||||
private final ApnsClient apnsClient;
|
||||
|
||||
@VisibleForTesting
|
||||
static final String APN_VOIP_NOTIFICATION_PAYLOAD = new SimpleApnsPayloadBuilder()
|
||||
.setSound("default")
|
||||
.setLocalizedAlertMessage("APN_Message")
|
||||
.build();
|
||||
|
||||
@VisibleForTesting
|
||||
static final String APN_NSE_NOTIFICATION_PAYLOAD = new SimpleApnsPayloadBuilder()
|
||||
.setMutableContent(true)
|
||||
@@ -80,22 +74,8 @@ public class APNSender implements Managed, PushNotificationSender {
|
||||
|
||||
@Override
|
||||
public CompletableFuture<SendPushNotificationResult> sendNotification(final PushNotification notification) {
|
||||
final String topic = switch (notification.tokenType()) {
|
||||
case APN -> bundleId;
|
||||
case APN_VOIP -> bundleId + ".voip";
|
||||
default -> throw new IllegalArgumentException("Unsupported token type: " + notification.tokenType());
|
||||
};
|
||||
|
||||
final boolean isVoip = notification.tokenType() == PushNotification.TokenType.APN_VOIP;
|
||||
|
||||
final String payload = switch (notification.notificationType()) {
|
||||
case NOTIFICATION -> {
|
||||
if (isVoip) {
|
||||
yield APN_VOIP_NOTIFICATION_PAYLOAD;
|
||||
} else {
|
||||
yield notification.urgent() ? APN_NSE_NOTIFICATION_PAYLOAD : APN_BACKGROUND_PAYLOAD;
|
||||
}
|
||||
}
|
||||
case NOTIFICATION -> notification.urgent() ? APN_NSE_NOTIFICATION_PAYLOAD : APN_BACKGROUND_PAYLOAD;
|
||||
|
||||
case ATTEMPT_LOGIN_NOTIFICATION_HIGH_PRIORITY -> new SimpleApnsPayloadBuilder()
|
||||
.setMutableContent(true)
|
||||
@@ -115,13 +95,7 @@ public class APNSender implements Managed, PushNotificationSender {
|
||||
};
|
||||
|
||||
final PushType pushType = switch (notification.notificationType()) {
|
||||
case NOTIFICATION -> {
|
||||
if (isVoip) {
|
||||
yield PushType.VOIP;
|
||||
} else {
|
||||
yield notification.urgent() ? PushType.ALERT : PushType.BACKGROUND;
|
||||
}
|
||||
}
|
||||
case NOTIFICATION -> notification.urgent() ? PushType.ALERT : PushType.BACKGROUND;
|
||||
case ATTEMPT_LOGIN_NOTIFICATION_HIGH_PRIORITY -> PushType.ALERT;
|
||||
case CHALLENGE, RATE_LIMIT_CHALLENGE -> PushType.BACKGROUND;
|
||||
};
|
||||
@@ -131,19 +105,17 @@ public class APNSender implements Managed, PushNotificationSender {
|
||||
if (pushType == PushType.BACKGROUND) {
|
||||
deliveryPriority = DeliveryPriority.CONSERVE_POWER;
|
||||
} else {
|
||||
deliveryPriority = (notification.urgent() || isVoip)
|
||||
? DeliveryPriority.IMMEDIATE
|
||||
: DeliveryPriority.CONSERVE_POWER;
|
||||
deliveryPriority = notification.urgent() ? DeliveryPriority.IMMEDIATE : DeliveryPriority.CONSERVE_POWER;
|
||||
}
|
||||
|
||||
final String collapseId =
|
||||
(notification.notificationType() == PushNotification.NotificationType.NOTIFICATION && notification.urgent() && !isVoip)
|
||||
(notification.notificationType() == PushNotification.NotificationType.NOTIFICATION && notification.urgent())
|
||||
? "incoming-message" : null;
|
||||
|
||||
final Instant start = Instant.now();
|
||||
|
||||
return apnsClient.sendNotification(new SimpleApnsPushNotification(notification.deviceToken(),
|
||||
topic,
|
||||
bundleId,
|
||||
payload,
|
||||
MAX_EXPIRATION,
|
||||
deliveryPriority,
|
||||
|
||||
+6
-6
@@ -35,8 +35,8 @@ import java.util.concurrent.TimeUnit;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubConnection;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubClusterConnection;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
|
||||
/**
|
||||
@@ -52,8 +52,8 @@ public class ClientPresenceManager extends RedisClusterPubSubAdapter<String, Str
|
||||
private final String managerId = UUID.randomUUID().toString();
|
||||
private final String connectedClientSetKey = getConnectedClientSetKey(managerId);
|
||||
|
||||
private final FaultTolerantRedisCluster presenceCluster;
|
||||
private final FaultTolerantPubSubConnection<String, String> pubSubConnection;
|
||||
private final FaultTolerantRedisClusterClient presenceCluster;
|
||||
private final FaultTolerantPubSubClusterConnection<String, String> pubSubConnection;
|
||||
|
||||
private final ClusterLuaScript clearPresenceScript;
|
||||
private final ClusterLuaScript renewPresenceScript;
|
||||
@@ -80,7 +80,7 @@ public class ClientPresenceManager extends RedisClusterPubSubAdapter<String, Str
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ClientPresenceManager.class);
|
||||
|
||||
public ClientPresenceManager(final FaultTolerantRedisCluster presenceCluster,
|
||||
public ClientPresenceManager(final FaultTolerantRedisClusterClient presenceCluster,
|
||||
final ScheduledExecutorService scheduledExecutorService,
|
||||
final ExecutorService keyspaceNotificationExecutorService) throws IOException {
|
||||
this.presenceCluster = presenceCluster;
|
||||
@@ -106,7 +106,7 @@ public class ClientPresenceManager extends RedisClusterPubSubAdapter<String, Str
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
FaultTolerantPubSubConnection<String, String> getPubSubConnection() {
|
||||
FaultTolerantPubSubClusterConnection<String, String> getPubSubConnection() {
|
||||
return pubSubConnection;
|
||||
}
|
||||
|
||||
|
||||
@@ -70,7 +70,7 @@ public class MessageSender {
|
||||
if (clientPresent) {
|
||||
messagesManager.insert(account.getUuid(), device.getId(), message.toBuilder().setEphemeral(true).build());
|
||||
} else {
|
||||
messagesManager.removeRecipientViewFromMrmData(account.getUuid(), device.getId(), message);
|
||||
messagesManager.removeRecipientViewFromMrmData(device.getId(), message);
|
||||
}
|
||||
} else {
|
||||
messagesManager.insert(account.getUuid(), device.getId(), message);
|
||||
|
||||
+20
-52
@@ -10,12 +10,7 @@ import static com.codahale.metrics.MetricRegistry.name;
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
|
||||
import io.lettuce.core.RedisClient;
|
||||
import io.lettuce.core.api.StatefulRedisConnection;
|
||||
import io.lettuce.core.codec.ByteArrayCodec;
|
||||
import io.lettuce.core.pubsub.RedisPubSubAdapter;
|
||||
import io.lettuce.core.pubsub.StatefulRedisPubSubConnection;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
@@ -24,22 +19,17 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Consumer;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubConnection;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisOperation;
|
||||
import org.whispersystems.textsecuregcm.storage.PubSubProtos;
|
||||
import org.whispersystems.textsecuregcm.util.CircuitBreakerUtil;
|
||||
import org.whispersystems.textsecuregcm.websocket.InvalidWebsocketAddressException;
|
||||
import org.whispersystems.textsecuregcm.websocket.ProvisioningAddress;
|
||||
|
||||
public class ProvisioningManager extends RedisPubSubAdapter<byte[], byte[]> implements Managed {
|
||||
|
||||
private final RedisClient redisClient;
|
||||
private final StatefulRedisPubSubConnection<byte[], byte[]> subscriptionConnection;
|
||||
private final StatefulRedisConnection<byte[], byte[]> publicationConnection;
|
||||
private final FaultTolerantRedisClient pubSubClient;
|
||||
private final FaultTolerantPubSubConnection<byte[], byte[]> pubSubConnection;
|
||||
|
||||
private final CircuitBreaker circuitBreaker;
|
||||
|
||||
private final Map<ProvisioningAddress, Consumer<PubSubProtos.PubSubMessage>> listenersByProvisioningAddress =
|
||||
private final Map<String, Consumer<PubSubProtos.PubSubMessage>> listenersByProvisioningAddress =
|
||||
new ConcurrentHashMap<>();
|
||||
|
||||
private static final String ACTIVE_LISTENERS_GAUGE_NAME = name(ProvisioningManager.class, "activeListeners");
|
||||
@@ -52,59 +42,43 @@ public class ProvisioningManager extends RedisPubSubAdapter<byte[], byte[]> impl
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ProvisioningManager.class);
|
||||
|
||||
public ProvisioningManager(final RedisClient redisClient,
|
||||
final CircuitBreakerConfiguration circuitBreakerConfiguration) {
|
||||
|
||||
this.redisClient = redisClient;
|
||||
|
||||
this.subscriptionConnection = redisClient.connectPubSub(new ByteArrayCodec());
|
||||
this.publicationConnection = redisClient.connect(new ByteArrayCodec());
|
||||
|
||||
this.circuitBreaker = CircuitBreaker.of("pubsub-breaker", circuitBreakerConfiguration.toCircuitBreakerConfig());
|
||||
|
||||
CircuitBreakerUtil.registerMetrics(circuitBreaker, ProvisioningManager.class, Tags.empty());
|
||||
public ProvisioningManager(final FaultTolerantRedisClient pubSubClient) {
|
||||
this.pubSubClient = pubSubClient;
|
||||
this.pubSubConnection = pubSubClient.createBinaryPubSubConnection();
|
||||
|
||||
Metrics.gaugeMapSize(ACTIVE_LISTENERS_GAUGE_NAME, Tags.empty(), listenersByProvisioningAddress);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() throws Exception {
|
||||
subscriptionConnection.addListener(this);
|
||||
pubSubConnection.usePubSubConnection(connection -> connection.addListener(this));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() throws Exception {
|
||||
subscriptionConnection.removeListener(this);
|
||||
|
||||
subscriptionConnection.close();
|
||||
publicationConnection.close();
|
||||
|
||||
redisClient.shutdown();
|
||||
pubSubConnection.usePubSubConnection(connection -> connection.removeListener(this));
|
||||
}
|
||||
|
||||
public void addListener(final ProvisioningAddress address, final Consumer<PubSubProtos.PubSubMessage> listener) {
|
||||
public void addListener(final String address, final Consumer<PubSubProtos.PubSubMessage> listener) {
|
||||
listenersByProvisioningAddress.put(address, listener);
|
||||
|
||||
circuitBreaker.executeRunnable(
|
||||
() -> subscriptionConnection.sync().subscribe(address.serialize().getBytes(StandardCharsets.UTF_8)));
|
||||
pubSubConnection.usePubSubConnection(connection -> connection.sync().subscribe(address.getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
|
||||
public void removeListener(final ProvisioningAddress address) {
|
||||
RedisOperation.unchecked(() -> circuitBreaker.executeRunnable(
|
||||
() -> subscriptionConnection.sync().unsubscribe(address.serialize().getBytes(StandardCharsets.UTF_8))));
|
||||
public void removeListener(final String address) {
|
||||
RedisOperation.unchecked(() ->
|
||||
pubSubConnection.usePubSubConnection(connection -> connection.sync().unsubscribe(address.getBytes(StandardCharsets.UTF_8))));
|
||||
|
||||
listenersByProvisioningAddress.remove(address);
|
||||
}
|
||||
|
||||
public boolean sendProvisioningMessage(final ProvisioningAddress address, final byte[] body) {
|
||||
public boolean sendProvisioningMessage(final String address, final byte[] body) {
|
||||
final PubSubProtos.PubSubMessage pubSubMessage = PubSubProtos.PubSubMessage.newBuilder()
|
||||
.setType(PubSubProtos.PubSubMessage.Type.DELIVER)
|
||||
.setContent(ByteString.copyFrom(body))
|
||||
.build();
|
||||
|
||||
final boolean receiverPresent = circuitBreaker.executeSupplier(
|
||||
() -> publicationConnection.sync()
|
||||
.publish(address.serialize().getBytes(StandardCharsets.UTF_8), pubSubMessage.toByteArray()) > 0);
|
||||
final boolean receiverPresent = pubSubClient.withBinaryConnection(connection ->
|
||||
connection.sync().publish(address.getBytes(StandardCharsets.UTF_8), pubSubMessage.toByteArray()) > 0);
|
||||
|
||||
Metrics.counter(SEND_PROVISIONING_MESSAGE_COUNTER_NAME, "online", String.valueOf(receiverPresent)).increment();
|
||||
|
||||
@@ -114,7 +88,7 @@ public class ProvisioningManager extends RedisPubSubAdapter<byte[], byte[]> impl
|
||||
@Override
|
||||
public void message(final byte[] channel, final byte[] message) {
|
||||
try {
|
||||
final ProvisioningAddress address = new ProvisioningAddress(new String(channel, StandardCharsets.UTF_8));
|
||||
final String address = new String(channel, StandardCharsets.UTF_8);
|
||||
final PubSubProtos.PubSubMessage pubSubMessage = PubSubProtos.PubSubMessage.parseFrom(message);
|
||||
|
||||
if (pubSubMessage.getType() == PubSubProtos.PubSubMessage.Type.DELIVER) {
|
||||
@@ -129,8 +103,6 @@ public class ProvisioningManager extends RedisPubSubAdapter<byte[], byte[]> impl
|
||||
|
||||
Metrics.counter(RECEIVE_PROVISIONING_MESSAGE_COUNTER_NAME, "listenerPresent", String.valueOf(listenerPresent)).increment();
|
||||
}
|
||||
} catch (final InvalidWebsocketAddressException e) {
|
||||
logger.warn("Failed to parse provisioning address", e);
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
logger.warn("Failed to parse pub/sub message", e);
|
||||
}
|
||||
@@ -138,10 +110,6 @@ public class ProvisioningManager extends RedisPubSubAdapter<byte[], byte[]> impl
|
||||
|
||||
@Override
|
||||
public void unsubscribed(final byte[] channel, final long count) {
|
||||
try {
|
||||
listenersByProvisioningAddress.remove(new ProvisioningAddress(new String(channel)));
|
||||
} catch (final InvalidWebsocketAddressException e) {
|
||||
logger.warn("Failed to parse provisioning address for `unsubscribe` event", e);
|
||||
}
|
||||
listenersByProvisioningAddress.remove(new String(channel, StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,6 @@ public record PushNotification(String deviceToken,
|
||||
|
||||
public enum TokenType {
|
||||
FCM,
|
||||
APN,
|
||||
APN_VOIP,
|
||||
APN
|
||||
}
|
||||
}
|
||||
+2
-18
@@ -90,8 +90,6 @@ public class PushNotificationManager {
|
||||
|
||||
if (StringUtils.isNotBlank(device.getGcmId())) {
|
||||
tokenAndType = new Pair<>(device.getGcmId(), PushNotification.TokenType.FCM);
|
||||
} else if (StringUtils.isNotBlank(device.getVoipApnId())) {
|
||||
tokenAndType = new Pair<>(device.getVoipApnId(), PushNotification.TokenType.APN_VOIP);
|
||||
} else if (StringUtils.isNotBlank(device.getApnId())) {
|
||||
tokenAndType = new Pair<>(device.getApnId(), PushNotification.TokenType.APN);
|
||||
} else {
|
||||
@@ -115,7 +113,7 @@ public class PushNotificationManager {
|
||||
|
||||
final PushNotificationSender sender = switch (pushNotification.tokenType()) {
|
||||
case FCM -> fcmSender;
|
||||
case APN, APN_VOIP -> apnSender;
|
||||
case APN -> apnSender;
|
||||
};
|
||||
|
||||
return sender.sendNotification(pushNotification).whenComplete((result, throwable) -> {
|
||||
@@ -141,18 +139,6 @@ public class PushNotificationManager {
|
||||
result.errorCode(),
|
||||
result.unregisteredTimestamp());
|
||||
}
|
||||
|
||||
if (result.accepted() &&
|
||||
pushNotification.tokenType() == PushNotification.TokenType.APN_VOIP &&
|
||||
pushNotification.notificationType() == PushNotification.NotificationType.NOTIFICATION &&
|
||||
pushNotification.destination() != null &&
|
||||
pushNotification.destinationDevice() != null) {
|
||||
|
||||
pushNotificationScheduler.scheduleRecurringApnsVoipNotification(
|
||||
pushNotification.destination(),
|
||||
pushNotification.destinationDevice())
|
||||
.whenComplete(logErrors());
|
||||
}
|
||||
} else {
|
||||
logger.debug("Failed to deliver {} push notification to {} ({})",
|
||||
pushNotification.notificationType(), pushNotification.deviceToken(), pushNotification.tokenType(),
|
||||
@@ -183,7 +169,7 @@ public class PushNotificationManager {
|
||||
tokenInvalidationTimestamp.isAfter(Instant.ofEpochMilli(device.getPushTimestamp()))).orElse(true);
|
||||
|
||||
if (tokenExpired) {
|
||||
if (tokenType == PushNotification.TokenType.APN || tokenType == PushNotification.TokenType.APN_VOIP) {
|
||||
if (tokenType == PushNotification.TokenType.APN) {
|
||||
pushNotificationScheduler.cancelScheduledNotifications(account, device).whenComplete(logErrors());
|
||||
}
|
||||
|
||||
@@ -215,7 +201,6 @@ public class PushNotificationManager {
|
||||
switch (tokenType) {
|
||||
case FCM -> d.setGcmId(null);
|
||||
case APN -> d.setApnId(null);
|
||||
case APN_VOIP -> d.setVoipApnId(null);
|
||||
}
|
||||
}
|
||||
})));
|
||||
@@ -225,7 +210,6 @@ public class PushNotificationManager {
|
||||
return switch (tokenType) {
|
||||
case FCM -> device.getGcmId();
|
||||
case APN -> device.getApnId();
|
||||
case APN_VOIP -> device.getVoipApnId();
|
||||
};
|
||||
}
|
||||
}
|
||||
+7
-142
@@ -19,36 +19,31 @@ import java.io.IOException;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.function.BiFunction;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.RedisClusterUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
public class PushNotificationScheduler implements Managed {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(PushNotificationScheduler.class);
|
||||
|
||||
private static final String PENDING_RECURRING_VOIP_NOTIFICATIONS_KEY_PREFIX = "PENDING_APN";
|
||||
private static final String PENDING_BACKGROUND_NOTIFICATIONS_KEY_PREFIX = "PENDING_BACKGROUND_APN";
|
||||
private static final String LAST_BACKGROUND_NOTIFICATION_TIMESTAMP_KEY_PREFIX = "LAST_BACKGROUND_NOTIFICATION";
|
||||
private static final String PENDING_DELAYED_NOTIFICATIONS_KEY_PREFIX = "DELAYED";
|
||||
@@ -56,11 +51,6 @@ public class PushNotificationScheduler implements Managed {
|
||||
@VisibleForTesting
|
||||
static final String NEXT_SLOT_TO_PROCESS_KEY = "pending_notification_next_slot";
|
||||
|
||||
private static final Counter delivered = Metrics.counter("chat.ApnPushNotificationScheduler.voip_delivered");
|
||||
private static final Counter sent = Metrics.counter("chat.ApnPushNotificationScheduler.voip_sent");
|
||||
private static final Counter retry = Metrics.counter("chat.ApnPushNotificationScheduler.voip_retry");
|
||||
private static final Counter evicted = Metrics.counter("chat.ApnPushNotificationScheduler.voip_evicted");
|
||||
|
||||
private static final Counter BACKGROUND_NOTIFICATION_SCHEDULED_COUNTER = Metrics.counter(name(PushNotificationScheduler.class, "backgroundNotification", "scheduled"));
|
||||
private static final String BACKGROUND_NOTIFICATION_SENT_COUNTER_NAME = name(PushNotificationScheduler.class, "backgroundNotification", "sent");
|
||||
|
||||
@@ -72,13 +62,9 @@ public class PushNotificationScheduler implements Managed {
|
||||
private final APNSender apnSender;
|
||||
private final FcmSender fcmSender;
|
||||
private final AccountsManager accountsManager;
|
||||
private final FaultTolerantRedisCluster pushSchedulingCluster;
|
||||
private final FaultTolerantRedisClusterClient pushSchedulingCluster;
|
||||
private final Clock clock;
|
||||
|
||||
private final ClusterLuaScript getPendingVoipDestinationsScript;
|
||||
private final ClusterLuaScript insertPendingVoipDestinationScript;
|
||||
private final ClusterLuaScript removePendingVoipDestinationScript;
|
||||
|
||||
private final ClusterLuaScript scheduleBackgroundApnsNotificationScript;
|
||||
|
||||
private final Thread[] workerThreads;
|
||||
@@ -117,37 +103,7 @@ public class PushNotificationScheduler implements Managed {
|
||||
final int slot = (int) (pushSchedulingCluster.withCluster(connection ->
|
||||
connection.sync().incr(NEXT_SLOT_TO_PROCESS_KEY)) % SlotHash.SLOT_COUNT);
|
||||
|
||||
return processRecurringApnsVoipNotifications(slot) +
|
||||
processScheduledBackgroundApnsNotifications(slot) +
|
||||
processScheduledDelayedNotifications(slot);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
long processRecurringApnsVoipNotifications(final int slot) {
|
||||
List<String> pendingDestinations;
|
||||
long entriesProcessed = 0;
|
||||
|
||||
do {
|
||||
pendingDestinations = getPendingDestinationsForRecurringApnsVoipNotifications(slot, PAGE_SIZE);
|
||||
entriesProcessed += pendingDestinations.size();
|
||||
|
||||
Flux.fromIterable(pendingDestinations)
|
||||
.flatMap(destination -> Mono.fromFuture(() -> getAccountAndDeviceFromPairString(destination))
|
||||
.flatMap(maybeAccountAndDevice -> {
|
||||
if (maybeAccountAndDevice.isPresent()) {
|
||||
final Pair<Account, Device> accountAndDevice = maybeAccountAndDevice.get();
|
||||
return Mono.fromFuture(() -> sendRecurringApnsVoipNotification(accountAndDevice.first(), accountAndDevice.second()));
|
||||
} else {
|
||||
final Pair<UUID, Byte> aciAndDeviceId = decodeAciAndDeviceId(destination);
|
||||
return Mono.fromFuture(() -> removeRecurringApnsVoipNotificationEntry(aciAndDeviceId.first(), aciAndDeviceId.second()))
|
||||
.then();
|
||||
}
|
||||
}), maxConcurrency)
|
||||
.then()
|
||||
.block();
|
||||
} while (!pendingDestinations.isEmpty());
|
||||
|
||||
return entriesProcessed;
|
||||
return processScheduledBackgroundApnsNotifications(slot) + processScheduledDelayedNotifications(slot);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -185,7 +141,7 @@ public class PushNotificationScheduler implements Managed {
|
||||
}
|
||||
}
|
||||
|
||||
public PushNotificationScheduler(final FaultTolerantRedisCluster pushSchedulingCluster,
|
||||
public PushNotificationScheduler(final FaultTolerantRedisClusterClient pushSchedulingCluster,
|
||||
final APNSender apnSender,
|
||||
final FcmSender fcmSender,
|
||||
final AccountsManager accountsManager,
|
||||
@@ -202,7 +158,7 @@ public class PushNotificationScheduler implements Managed {
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
PushNotificationScheduler(final FaultTolerantRedisCluster pushSchedulingCluster,
|
||||
PushNotificationScheduler(final FaultTolerantRedisClusterClient pushSchedulingCluster,
|
||||
final APNSender apnSender,
|
||||
final FcmSender fcmSender,
|
||||
final AccountsManager accountsManager,
|
||||
@@ -216,13 +172,6 @@ public class PushNotificationScheduler implements Managed {
|
||||
this.pushSchedulingCluster = pushSchedulingCluster;
|
||||
this.clock = clock;
|
||||
|
||||
this.getPendingVoipDestinationsScript = ClusterLuaScript.fromResource(pushSchedulingCluster, "lua/apn/get.lua",
|
||||
ScriptOutputType.MULTI);
|
||||
this.insertPendingVoipDestinationScript = ClusterLuaScript.fromResource(pushSchedulingCluster, "lua/apn/insert.lua",
|
||||
ScriptOutputType.VALUE);
|
||||
this.removePendingVoipDestinationScript = ClusterLuaScript.fromResource(pushSchedulingCluster, "lua/apn/remove.lua",
|
||||
ScriptOutputType.INTEGER);
|
||||
|
||||
this.scheduleBackgroundApnsNotificationScript = ClusterLuaScript.fromResource(pushSchedulingCluster,
|
||||
"lua/apn/schedule_background_notification.lua", ScriptOutputType.VALUE);
|
||||
|
||||
@@ -233,17 +182,6 @@ public class PushNotificationScheduler implements Managed {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedule a recurring VOIP notification until {@link this#cancelScheduledNotifications} is called or the device is
|
||||
* removed
|
||||
*
|
||||
* @return A CompletionStage that completes when the recurring notification has successfully been scheduled
|
||||
*/
|
||||
public CompletionStage<Void> scheduleRecurringApnsVoipNotification(Account account, Device device) {
|
||||
sent.increment();
|
||||
return insertRecurringApnsVoipNotificationEntry(account.getIdentifier(IdentityType.ACI), device.getId(), clock.millis() + (15 * 1000), (15 * 1000));
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedule a background APNs notification to be sent some time in the future.
|
||||
*
|
||||
@@ -292,32 +230,16 @@ public class PushNotificationScheduler implements Managed {
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel a scheduled recurring VOIP notification
|
||||
* Cancel scheduled notifications for the given account and device.
|
||||
*
|
||||
* @return A CompletionStage that completes when the scheduled task has been cancelled.
|
||||
* @return A CompletionStage that completes when the scheduled notification has been cancelled.
|
||||
*/
|
||||
public CompletionStage<Void> cancelScheduledNotifications(Account account, Device device) {
|
||||
return CompletableFuture.allOf(
|
||||
cancelRecurringApnsVoipNotifications(account, device),
|
||||
cancelBackgroundApnsNotifications(account, device),
|
||||
cancelDelayedNotifications(account, device));
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> cancelRecurringApnsVoipNotifications(final Account account, final Device device) {
|
||||
return removeRecurringApnsVoipNotificationEntry(account.getIdentifier(IdentityType.ACI), device.getId())
|
||||
.thenCompose(removed -> {
|
||||
if (removed) {
|
||||
delivered.increment();
|
||||
}
|
||||
return pushSchedulingCluster.withCluster(connection ->
|
||||
connection.async().zrem(
|
||||
getPendingBackgroundApnsNotificationQueueKey(account, device),
|
||||
encodeAciAndDeviceId(account, device)));
|
||||
})
|
||||
.thenRun(Util.NOOP)
|
||||
.toCompletableFuture();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
CompletableFuture<Void> cancelBackgroundApnsNotifications(final Account account, final Device device) {
|
||||
return pushSchedulingCluster.withCluster(connection -> connection.async()
|
||||
@@ -353,21 +275,6 @@ public class PushNotificationScheduler implements Managed {
|
||||
}
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> sendRecurringApnsVoipNotification(final Account account, final Device device) {
|
||||
if (StringUtils.isBlank(device.getVoipApnId())) {
|
||||
return removeRecurringApnsVoipNotificationEntry(account.getIdentifier(IdentityType.ACI), device.getId())
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
|
||||
if (device.getLastSeen() < clock.millis() - TimeUnit.DAYS.toMillis(7)) {
|
||||
return removeRecurringApnsVoipNotificationEntry(account.getIdentifier(IdentityType.ACI), device.getId())
|
||||
.thenRun(evicted::increment);
|
||||
}
|
||||
|
||||
return apnSender.sendNotification(new PushNotification(device.getVoipApnId(), PushNotification.TokenType.APN_VOIP, PushNotification.NotificationType.NOTIFICATION, null, account, device, true))
|
||||
.thenRun(retry::increment);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
CompletableFuture<Void> sendBackgroundApnsNotification(final Account account, final Device device) {
|
||||
if (StringUtils.isBlank(device.getApnId())) {
|
||||
@@ -443,48 +350,6 @@ public class PushNotificationScheduler implements Managed {
|
||||
.flatMap(account -> account.getDevice(aciAndDeviceId.second()).map(device -> new Pair<>(account, device))));
|
||||
}
|
||||
|
||||
private CompletableFuture<Boolean> removeRecurringApnsVoipNotificationEntry(final UUID aci, final byte deviceId) {
|
||||
final String endpoint = getVoipEndpointKey(aci, deviceId);
|
||||
|
||||
return removePendingVoipDestinationScript.executeAsync(
|
||||
List.of(getPendingRecurringApnsVoipNotificationQueueKey(endpoint), endpoint), Collections.emptyList())
|
||||
.thenApply(result -> ((long) result) > 0);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@VisibleForTesting
|
||||
List<String> getPendingDestinationsForRecurringApnsVoipNotifications(final int slot, final int limit) {
|
||||
return (List<String>) getPendingVoipDestinationsScript.execute(
|
||||
List.of(getPendingRecurringApnsVoipNotificationQueueKey(slot)),
|
||||
List.of(String.valueOf(clock.millis()), String.valueOf(limit)));
|
||||
}
|
||||
|
||||
@SuppressWarnings("SameParameterValue")
|
||||
private CompletionStage<Void> insertRecurringApnsVoipNotificationEntry(final UUID aci, final byte deviceId, final long timestamp, final long interval) {
|
||||
final String endpoint = getVoipEndpointKey(aci, deviceId);
|
||||
|
||||
return insertPendingVoipDestinationScript.executeAsync(
|
||||
List.of(getPendingRecurringApnsVoipNotificationQueueKey(endpoint), endpoint),
|
||||
List.of(String.valueOf(timestamp),
|
||||
String.valueOf(interval),
|
||||
aci.toString(),
|
||||
String.valueOf(deviceId)))
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static String getVoipEndpointKey(final UUID aci, final byte deviceId) {
|
||||
return "apn_device::{" + aci + "::" + deviceId + "}";
|
||||
}
|
||||
|
||||
private static String getPendingRecurringApnsVoipNotificationQueueKey(final String endpoint) {
|
||||
return getPendingRecurringApnsVoipNotificationQueueKey(SlotHash.getSlot(endpoint));
|
||||
}
|
||||
|
||||
private static String getPendingRecurringApnsVoipNotificationQueueKey(final int slot) {
|
||||
return PENDING_RECURRING_VOIP_NOTIFICATIONS_KEY_PREFIX + "::{" + RedisClusterUtil.getMinimalHashTag(slot) + "}";
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static String getPendingBackgroundApnsNotificationQueueKey(final Account account, final Device device) {
|
||||
return getPendingBackgroundApnsNotificationQueueKey(SlotHash.getSlot(encodeAciAndDeviceId(account, device)));
|
||||
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.redis;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.github.resilience4j.retry.Retry;
|
||||
import io.lettuce.core.RedisException;
|
||||
import io.lettuce.core.pubsub.StatefulRedisPubSubConnection;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
|
||||
abstract class AbstractFaultTolerantPubSubConnection<K, V, C extends StatefulRedisPubSubConnection<K, V>> {
|
||||
|
||||
private final String name;
|
||||
private final C pubSubConnection;
|
||||
|
||||
private final Retry retry;
|
||||
|
||||
private final Timer executeTimer;
|
||||
|
||||
protected AbstractFaultTolerantPubSubConnection(final String name,
|
||||
final C pubSubConnection,
|
||||
final Retry retry) {
|
||||
|
||||
this.name = name;
|
||||
this.pubSubConnection = pubSubConnection;
|
||||
this.retry = retry;
|
||||
|
||||
this.executeTimer = Metrics.timer(name(getClass(), "execute"), "clusterName", name + "-pubsub");
|
||||
}
|
||||
|
||||
protected String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void usePubSubConnection(final Consumer<C> consumer) {
|
||||
try {
|
||||
retry.executeRunnable(() -> executeTimer.record(() -> consumer.accept(pubSubConnection)));
|
||||
} catch (final Throwable t) {
|
||||
if (t instanceof RedisException) {
|
||||
throw (RedisException) t;
|
||||
} else {
|
||||
throw new RedisException(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public <T> T withPubSubConnection(final Function<C, T> function) {
|
||||
try {
|
||||
return retry.executeCallable(() -> executeTimer.record(() -> function.apply(pubSubConnection)));
|
||||
} catch (final Throwable t) {
|
||||
if (t instanceof RedisException) {
|
||||
throw (RedisException) t;
|
||||
} else {
|
||||
throw new RedisException(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@ import reactor.core.publisher.Mono;
|
||||
|
||||
public class ClusterLuaScript {
|
||||
|
||||
private final FaultTolerantRedisCluster redisCluster;
|
||||
private final FaultTolerantRedisClusterClient redisCluster;
|
||||
private final ScriptOutputType scriptOutputType;
|
||||
private final String script;
|
||||
private final String sha;
|
||||
@@ -35,7 +35,7 @@ public class ClusterLuaScript {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ClusterLuaScript.class);
|
||||
|
||||
public static ClusterLuaScript fromResource(final FaultTolerantRedisCluster redisCluster,
|
||||
public static ClusterLuaScript fromResource(final FaultTolerantRedisClusterClient redisCluster,
|
||||
final String resource,
|
||||
final ScriptOutputType scriptOutputType) throws IOException {
|
||||
|
||||
@@ -51,7 +51,7 @@ public class ClusterLuaScript {
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
ClusterLuaScript(final FaultTolerantRedisCluster redisCluster,
|
||||
ClusterLuaScript(final FaultTolerantRedisClusterClient redisCluster,
|
||||
final String script,
|
||||
final ScriptOutputType scriptOutputType) {
|
||||
|
||||
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.redis;
|
||||
|
||||
import io.github.resilience4j.retry.Retry;
|
||||
import io.lettuce.core.cluster.event.ClusterTopologyChangedEvent;
|
||||
import io.lettuce.core.cluster.pubsub.StatefulRedisClusterPubSubConnection;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
|
||||
public class FaultTolerantPubSubClusterConnection<K, V> extends AbstractFaultTolerantPubSubConnection<K, V, StatefulRedisClusterPubSubConnection<K, V>> {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(FaultTolerantPubSubClusterConnection.class);
|
||||
|
||||
private final Retry resubscribeRetry;
|
||||
private final Scheduler topologyChangedEventScheduler;
|
||||
|
||||
protected FaultTolerantPubSubClusterConnection(final String name,
|
||||
final StatefulRedisClusterPubSubConnection<K, V> pubSubConnection,
|
||||
final Retry retry,
|
||||
final Retry resubscribeRetry,
|
||||
final Scheduler topologyChangedEventScheduler) {
|
||||
|
||||
super(name, pubSubConnection, retry);
|
||||
|
||||
pubSubConnection.setNodeMessagePropagation(true);
|
||||
|
||||
this.resubscribeRetry = resubscribeRetry;
|
||||
this.topologyChangedEventScheduler = topologyChangedEventScheduler;
|
||||
}
|
||||
|
||||
public void subscribeToClusterTopologyChangedEvents(final Runnable eventHandler) {
|
||||
|
||||
usePubSubConnection(connection -> connection.getResources().eventBus().get()
|
||||
.filter(event -> event instanceof ClusterTopologyChangedEvent)
|
||||
.subscribeOn(topologyChangedEventScheduler)
|
||||
.subscribe(event -> {
|
||||
logger.info("Got topology change event for {}, resubscribing all keyspace notifications", getName());
|
||||
|
||||
resubscribeRetry.executeRunnable(() -> {
|
||||
try {
|
||||
eventHandler.run();
|
||||
} catch (final RuntimeException e) {
|
||||
logger.warn("Resubscribe for {} failed", getName(), e);
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
}));
|
||||
}
|
||||
}
|
||||
+6
-81
@@ -5,90 +5,15 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.redis;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.github.resilience4j.retry.Retry;
|
||||
import io.lettuce.core.RedisException;
|
||||
import io.lettuce.core.cluster.event.ClusterTopologyChangedEvent;
|
||||
import io.lettuce.core.cluster.pubsub.StatefulRedisClusterPubSubConnection;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import io.lettuce.core.pubsub.StatefulRedisPubSubConnection;
|
||||
|
||||
public class FaultTolerantPubSubConnection<K, V> {
|
||||
public class FaultTolerantPubSubConnection<K, V> extends AbstractFaultTolerantPubSubConnection<K, V, StatefulRedisPubSubConnection<K, V>> {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(FaultTolerantPubSubConnection.class);
|
||||
protected FaultTolerantPubSubConnection(final String name,
|
||||
final StatefulRedisPubSubConnection<K, V> pubSubConnection,
|
||||
final Retry retry) {
|
||||
|
||||
|
||||
private final String name;
|
||||
private final StatefulRedisClusterPubSubConnection<K, V> pubSubConnection;
|
||||
|
||||
private final Retry retry;
|
||||
private final Retry resubscribeRetry;
|
||||
private final Scheduler topologyChangedEventScheduler;
|
||||
|
||||
private final Timer executeTimer;
|
||||
|
||||
public FaultTolerantPubSubConnection(final String name,
|
||||
final StatefulRedisClusterPubSubConnection<K, V> pubSubConnection,
|
||||
final Retry retry, final Retry resubscribeRetry, final Scheduler topologyChangedEventScheduler) {
|
||||
this.name = name;
|
||||
this.pubSubConnection = pubSubConnection;
|
||||
this.retry = retry;
|
||||
this.resubscribeRetry = resubscribeRetry;
|
||||
this.topologyChangedEventScheduler = topologyChangedEventScheduler;
|
||||
|
||||
this.pubSubConnection.setNodeMessagePropagation(true);
|
||||
|
||||
this.executeTimer = Metrics.timer(name(getClass(), "execute"), "clusterName", name + "-pubsub");
|
||||
super(name, pubSubConnection, retry);
|
||||
}
|
||||
|
||||
public void usePubSubConnection(final Consumer<StatefulRedisClusterPubSubConnection<K, V>> consumer) {
|
||||
try {
|
||||
retry.executeRunnable(() -> executeTimer.record(() -> consumer.accept(pubSubConnection)));
|
||||
} catch (final Throwable t) {
|
||||
if (t instanceof RedisException) {
|
||||
throw (RedisException) t;
|
||||
} else {
|
||||
throw new RedisException(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public <T> T withPubSubConnection(final Function<StatefulRedisClusterPubSubConnection<K, V>, T> function) {
|
||||
try {
|
||||
return retry.executeCallable(() -> executeTimer.record(() -> function.apply(pubSubConnection)));
|
||||
} catch (final Throwable t) {
|
||||
if (t instanceof RedisException) {
|
||||
throw (RedisException) t;
|
||||
} else {
|
||||
throw new RedisException(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void subscribeToClusterTopologyChangedEvents(final Runnable eventHandler) {
|
||||
|
||||
usePubSubConnection(connection -> connection.getResources().eventBus().get()
|
||||
.filter(event -> event instanceof ClusterTopologyChangedEvent)
|
||||
.subscribeOn(topologyChangedEventScheduler)
|
||||
.subscribe(event -> {
|
||||
logger.info("Got topology change event for {}, resubscribing all keyspace notifications", name);
|
||||
|
||||
resubscribeRetry.executeRunnable(() -> {
|
||||
try {
|
||||
eventHandler.run();
|
||||
} catch (final RuntimeException e) {
|
||||
logger.warn("Resubscribe for {} failed", name, e);
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
}
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
package org.whispersystems.textsecuregcm.redis;
|
||||
|
||||
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
|
||||
import io.github.resilience4j.retry.Retry;
|
||||
import io.lettuce.core.ClientOptions;
|
||||
import io.lettuce.core.RedisClient;
|
||||
import io.lettuce.core.RedisCommandTimeoutException;
|
||||
import io.lettuce.core.RedisException;
|
||||
import io.lettuce.core.RedisURI;
|
||||
import io.lettuce.core.TimeoutOptions;
|
||||
import io.lettuce.core.api.StatefulRedisConnection;
|
||||
import io.lettuce.core.cluster.ClusterClientOptions;
|
||||
import io.lettuce.core.cluster.ClusterTopologyRefreshOptions;
|
||||
import io.lettuce.core.codec.ByteArrayCodec;
|
||||
import io.lettuce.core.pubsub.StatefulRedisPubSubConnection;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.RedisConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.util.CircuitBreakerUtil;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class FaultTolerantRedisClient {
|
||||
|
||||
private final String name;
|
||||
|
||||
private final RedisClient redisClient;
|
||||
|
||||
private final StatefulRedisConnection<String, String> stringConnection;
|
||||
private final StatefulRedisConnection<byte[], byte[]> binaryConnection;
|
||||
|
||||
private final List<StatefulRedisPubSubConnection<?, ?>> pubSubConnections = new ArrayList<>();
|
||||
|
||||
private final CircuitBreaker circuitBreaker;
|
||||
private final Retry retry;
|
||||
|
||||
public FaultTolerantRedisClient(final String name,
|
||||
final RedisConfiguration redisConfiguration,
|
||||
final ClientResources.Builder clientResourcesBuilder) {
|
||||
|
||||
this(name, clientResourcesBuilder,
|
||||
RedisUriUtil.createRedisUriWithTimeout(redisConfiguration.getUri(), redisConfiguration.getTimeout()),
|
||||
redisConfiguration.getTimeout(),
|
||||
redisConfiguration.getCircuitBreakerConfiguration(),
|
||||
redisConfiguration.getRetryConfiguration());
|
||||
}
|
||||
|
||||
FaultTolerantRedisClient(String name,
|
||||
final ClientResources.Builder clientResourcesBuilder,
|
||||
final RedisURI redisUri,
|
||||
final Duration commandTimeout,
|
||||
final CircuitBreakerConfiguration circuitBreakerConfiguration,
|
||||
final RetryConfiguration retryConfiguration) {
|
||||
|
||||
this.name = name;
|
||||
|
||||
final LettuceShardCircuitBreaker lettuceShardCircuitBreaker = new LettuceShardCircuitBreaker(name,
|
||||
circuitBreakerConfiguration.toCircuitBreakerConfig(), Schedulers.newSingle("topology-changed-" + name, true));
|
||||
this.redisClient = RedisClient.create(clientResourcesBuilder.build(), redisUri);
|
||||
this.redisClient.setOptions(ClusterClientOptions.builder()
|
||||
.disconnectedBehavior(ClientOptions.DisconnectedBehavior.REJECT_COMMANDS)
|
||||
.validateClusterNodeMembership(false)
|
||||
.topologyRefreshOptions(ClusterTopologyRefreshOptions.builder()
|
||||
.enableAllAdaptiveRefreshTriggers()
|
||||
.build())
|
||||
// for asynchronous commands
|
||||
.timeoutOptions(TimeoutOptions.builder()
|
||||
.fixedTimeout(commandTimeout)
|
||||
.build())
|
||||
.publishOnScheduler(true)
|
||||
.build());
|
||||
|
||||
lettuceShardCircuitBreaker.setEventBus(redisClient.getResources().eventBus());
|
||||
|
||||
this.stringConnection = redisClient.connect();
|
||||
this.binaryConnection = redisClient.connect(ByteArrayCodec.INSTANCE);
|
||||
|
||||
this.circuitBreaker = CircuitBreaker.of(name + "-breaker", circuitBreakerConfiguration.toCircuitBreakerConfig());
|
||||
this.retry = Retry.of(name + "-retry", retryConfiguration.toRetryConfigBuilder()
|
||||
.retryOnException(exception -> exception instanceof RedisCommandTimeoutException).build());
|
||||
|
||||
CircuitBreakerUtil.registerMetrics(retry, FaultTolerantRedisClusterClient.class);
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
stringConnection.close();
|
||||
|
||||
for (final StatefulRedisPubSubConnection<?, ?> pubSubConnection : pubSubConnections) {
|
||||
pubSubConnection.close();
|
||||
}
|
||||
|
||||
redisClient.shutdown();
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void useConnection(final Consumer<StatefulRedisConnection<String, String>> consumer) {
|
||||
useConnection(stringConnection, consumer);
|
||||
}
|
||||
|
||||
public <T> T withConnection(final Function<StatefulRedisConnection<String, String>, T> function) {
|
||||
return withConnection(stringConnection, function);
|
||||
}
|
||||
|
||||
public void useBinaryConnection(final Consumer<StatefulRedisConnection<byte[], byte[]>> consumer) {
|
||||
useConnection(binaryConnection, consumer);
|
||||
}
|
||||
|
||||
public <T> T withBinaryConnection(final Function<StatefulRedisConnection<byte[], byte[]>, T> function) {
|
||||
return withConnection(binaryConnection, function);
|
||||
}
|
||||
|
||||
public <K, V> void useConnection(final StatefulRedisConnection<K, V> connection,
|
||||
final Consumer<StatefulRedisConnection<K, V>> consumer) {
|
||||
try {
|
||||
circuitBreaker.executeRunnable(() -> retry.executeRunnable(() -> consumer.accept(connection)));
|
||||
} catch (final Throwable t) {
|
||||
if (t instanceof RedisException) {
|
||||
throw (RedisException) t;
|
||||
} else {
|
||||
throw new RedisException(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public <T, K, V> T withConnection(final StatefulRedisConnection<K, V> connection,
|
||||
final Function<StatefulRedisConnection<K, V>, T> function) {
|
||||
try {
|
||||
return circuitBreaker.executeCallable(() -> retry.executeCallable(() -> function.apply(connection)));
|
||||
} catch (final Throwable t) {
|
||||
if (t instanceof RedisException) {
|
||||
throw (RedisException) t;
|
||||
} else {
|
||||
throw new RedisException(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public FaultTolerantPubSubConnection<String, String> createPubSubConnection() {
|
||||
final StatefulRedisPubSubConnection<String, String> pubSubConnection = redisClient.connectPubSub();
|
||||
pubSubConnections.add(pubSubConnection);
|
||||
|
||||
return new FaultTolerantPubSubConnection<>(name, pubSubConnection, retry);
|
||||
}
|
||||
|
||||
public FaultTolerantPubSubConnection<byte[], byte[]> createBinaryPubSubConnection() {
|
||||
final StatefulRedisPubSubConnection<byte[], byte[]> pubSubConnection = redisClient.connectPubSub(ByteArrayCodec.INSTANCE);
|
||||
pubSubConnections.add(pubSubConnection);
|
||||
|
||||
return new FaultTolerantPubSubConnection<>(name, pubSubConnection, retry);
|
||||
}
|
||||
}
|
||||
+22
-12
@@ -34,6 +34,7 @@ import org.whispersystems.textsecuregcm.configuration.RedisClusterConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.util.CircuitBreakerUtil;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
|
||||
/**
|
||||
@@ -41,7 +42,7 @@ import reactor.core.scheduler.Schedulers;
|
||||
*
|
||||
* @see LettuceShardCircuitBreaker
|
||||
*/
|
||||
public class FaultTolerantRedisCluster {
|
||||
public class FaultTolerantRedisClusterClient {
|
||||
|
||||
private final String name;
|
||||
|
||||
@@ -56,8 +57,8 @@ public class FaultTolerantRedisCluster {
|
||||
private final Retry topologyChangedEventRetry;
|
||||
|
||||
|
||||
public FaultTolerantRedisCluster(final String name, final RedisClusterConfiguration clusterConfiguration,
|
||||
final ClientResources.Builder clientResourcesBuilder) {
|
||||
public FaultTolerantRedisClusterClient(final String name, final RedisClusterConfiguration clusterConfiguration,
|
||||
final ClientResources.Builder clientResourcesBuilder) {
|
||||
|
||||
this(name, clientResourcesBuilder,
|
||||
Collections.singleton(RedisUriUtil.createRedisUriWithTimeout(clusterConfiguration.getConfigurationUri(),
|
||||
@@ -68,9 +69,9 @@ public class FaultTolerantRedisCluster {
|
||||
|
||||
}
|
||||
|
||||
FaultTolerantRedisCluster(String name, final ClientResources.Builder clientResourcesBuilder,
|
||||
Iterable<RedisURI> redisUris, Duration commandTimeout, CircuitBreakerConfiguration circuitBreakerConfig,
|
||||
RetryConfiguration retryConfiguration) {
|
||||
FaultTolerantRedisClusterClient(String name, final ClientResources.Builder clientResourcesBuilder,
|
||||
Iterable<RedisURI> redisUris, Duration commandTimeout, CircuitBreakerConfiguration circuitBreakerConfig,
|
||||
RetryConfiguration retryConfiguration) {
|
||||
|
||||
this.name = name;
|
||||
|
||||
@@ -112,7 +113,7 @@ public class FaultTolerantRedisCluster {
|
||||
|
||||
this.topologyChangedEventRetry = Retry.of(name + "-topologyChangedRetry", topologyChangedEventRetryConfig);
|
||||
|
||||
CircuitBreakerUtil.registerMetrics(retry, FaultTolerantRedisCluster.class);
|
||||
CircuitBreakerUtil.registerMetrics(retry, FaultTolerantRedisClusterClient.class);
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
@@ -177,18 +178,27 @@ public class FaultTolerantRedisCluster {
|
||||
}
|
||||
}
|
||||
|
||||
public <T, K, V> Publisher<T> withConnectionReactive(final StatefulRedisClusterConnection<K, V> connection,
|
||||
public <T, K, V> Publisher<T> withConnectionReactive(
|
||||
final StatefulRedisClusterConnection<K, V> connection,
|
||||
final Function<StatefulRedisClusterConnection<K, V>, Publisher<T>> function) {
|
||||
|
||||
return Flux.from(function.apply(connection))
|
||||
.transformDeferred(RetryOperator.of(retry));
|
||||
final Publisher<T> publisher = function.apply(connection);
|
||||
|
||||
if (publisher instanceof Mono<T> m) {
|
||||
return m.transformDeferred(RetryOperator.of(retry));
|
||||
}
|
||||
if (publisher instanceof Flux<T> f) {
|
||||
return f.transformDeferred(RetryOperator.of(retry));
|
||||
}
|
||||
|
||||
return Flux.from(publisher).transformDeferred(RetryOperator.of(retry));
|
||||
}
|
||||
|
||||
public FaultTolerantPubSubConnection<String, String> createPubSubConnection() {
|
||||
public FaultTolerantPubSubClusterConnection<String, String> createPubSubConnection() {
|
||||
final StatefulRedisClusterPubSubConnection<String, String> pubSubConnection = clusterClient.connectPubSub();
|
||||
pubSubConnections.add(pubSubConnection);
|
||||
|
||||
return new FaultTolerantPubSubConnection<>(name, pubSubConnection, retry, topologyChangedEventRetry,
|
||||
return new FaultTolerantPubSubClusterConnection<>(name, pubSubConnection, retry, topologyChangedEventRetry,
|
||||
Schedulers.newSingle(name + "-redisPubSubEvents", true));
|
||||
}
|
||||
|
||||
@@ -136,7 +136,7 @@ public abstract class JobScheduler {
|
||||
*
|
||||
* @see #processJob(byte[])
|
||||
*/
|
||||
public CompletableFuture<Void> processAvailableJobs() {
|
||||
public Mono<Void> processAvailableJobs() {
|
||||
return Flux.from(dynamoDbAsyncClient.queryPaginator(QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.keyConditionExpression("#schedulerName = :schedulerName AND #runAt <= :maxRunAt")
|
||||
@@ -153,7 +153,7 @@ public abstract class JobScheduler {
|
||||
? item.get(ATTR_JOB_DATA).b().asByteArray()
|
||||
: null;
|
||||
|
||||
return Mono.fromFuture(processJob(jobData))
|
||||
return Mono.fromFuture(() -> processJob(jobData))
|
||||
.doOnNext(outcome -> Metrics.counter(PROCESS_JOB_COUNTER_NAME,
|
||||
SCHEDULER_NAME_TAG, getSchedulerName(),
|
||||
OUTCOME_TAG, outcome)
|
||||
@@ -164,8 +164,7 @@ public abstract class JobScheduler {
|
||||
return Mono.empty();
|
||||
});
|
||||
}, MAX_CONCURRENCY)
|
||||
.then()
|
||||
.toFuture();
|
||||
.then();
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> deleteJob(final AttributeValue schedulerName, final AttributeValue runAt) {
|
||||
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
package org.whispersystems.textsecuregcm.spam;
|
||||
|
||||
import org.whispersystems.textsecuregcm.auth.AccountAndAuthenticatedDeviceHolder;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import javax.ws.rs.container.ContainerRequestContext;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Generates ReportSpamTokens to be used for spam reports.
|
||||
*/
|
||||
public interface ReportSpamTokenProvider {
|
||||
|
||||
/**
|
||||
* Generate a new ReportSpamToken
|
||||
*
|
||||
* @param context the message request context
|
||||
* @param sender the account that sent the unsealed sender message
|
||||
* @param maybeDestination the intended recepient of the message if available
|
||||
* @return either a generated token or nothing
|
||||
*/
|
||||
Optional<byte[]> makeReportSpamToken(ContainerRequestContext context, final AccountAndAuthenticatedDeviceHolder sender,
|
||||
final Optional<Account> maybeDestination);
|
||||
|
||||
/**
|
||||
* Provider which generates nothing
|
||||
*
|
||||
* @return the provider
|
||||
*/
|
||||
static ReportSpamTokenProvider noop() {
|
||||
return (ignoredContext, ignoredSender, ignoredDest) -> Optional.empty();
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.spam;
|
||||
|
||||
import org.whispersystems.textsecuregcm.auth.AccountAndAuthenticatedDeviceHolder;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import javax.ws.rs.container.ContainerRequestContext;
|
||||
import javax.ws.rs.core.Response;
|
||||
@@ -11,6 +12,25 @@ import java.util.Optional;
|
||||
|
||||
public interface SpamChecker {
|
||||
|
||||
/**
|
||||
* A result from the spam checker that is one of:
|
||||
* <ul>
|
||||
* <li>
|
||||
* Message is determined to be spam, and a response is returned
|
||||
* </li>
|
||||
* <li>
|
||||
* Message is not spam, and an optional spam token is returned
|
||||
* </li>
|
||||
* </ul>
|
||||
*/
|
||||
sealed interface SpamCheckResult {}
|
||||
|
||||
record Spam(Response response) implements SpamCheckResult {}
|
||||
|
||||
record NotSpam(Optional<byte[]> token) implements SpamCheckResult {
|
||||
public static final NotSpam EMPTY_TOKEN = new NotSpam(Optional.empty());
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if a message may be spam
|
||||
*
|
||||
@@ -18,14 +38,14 @@ public interface SpamChecker {
|
||||
* @param maybeSource The sender of the message, could be empty if this as message sent with sealed sender
|
||||
* @param maybeDestination The destination of the message, could be empty if the destination does not exist or could
|
||||
* not be retrieved
|
||||
* @return A response to return if the request is determined to be spam, otherwise empty if the message should be sent
|
||||
* @return A {@link SpamCheckResult}
|
||||
*/
|
||||
Optional<Response> checkForSpam(
|
||||
SpamCheckResult checkForSpam(
|
||||
final ContainerRequestContext requestContext,
|
||||
final Optional<Account> maybeSource,
|
||||
final Optional<? extends AccountAndAuthenticatedDeviceHolder> maybeSource,
|
||||
final Optional<Account> maybeDestination);
|
||||
|
||||
static SpamChecker noop() {
|
||||
return (ignoredContext, ignoredSource, ignoredDestination) -> Optional.empty();
|
||||
return (ignoredContext, ignoredSource, ignoredDestination) -> NotSpam.EMPTY_TOKEN;
|
||||
}
|
||||
}
|
||||
@@ -33,13 +33,6 @@ public interface SpamFilter extends Managed {
|
||||
*/
|
||||
void configure(String environmentName, Validator validator) throws IOException, ConfigurationValidationException;
|
||||
|
||||
/**
|
||||
* Builds a spam report token provider. This will generate tokens used by the spam reporting system.
|
||||
*
|
||||
* @return the configured spam report token provider.
|
||||
*/
|
||||
ReportSpamTokenProvider getReportSpamTokenProvider();
|
||||
|
||||
/**
|
||||
* Return a reported message listener controlled by the spam filter. Listeners will be registered with the
|
||||
* {@link org.whispersystems.textsecuregcm.storage.ReportMessageManager}.
|
||||
|
||||
@@ -288,10 +288,6 @@ public class Account {
|
||||
.orElse(false);
|
||||
}
|
||||
|
||||
public boolean isPaymentActivationSupported() {
|
||||
return allDevicesHaveCapability(DeviceCapabilities::paymentActivation);
|
||||
}
|
||||
|
||||
public boolean isDeleteSyncSupported() {
|
||||
return allDevicesHaveCapability(DeviceCapabilities::deleteSync);
|
||||
}
|
||||
|
||||
@@ -14,6 +14,9 @@ import com.google.common.base.Throwables;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
@@ -43,6 +46,7 @@ import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import software.amazon.awssdk.core.SdkBytes;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
@@ -122,6 +126,12 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
// username hash; byte[] or null
|
||||
static final String ATTR_USERNAME_HASH = "N";
|
||||
|
||||
// bytes, primary key
|
||||
static final String KEY_LINK_DEVICE_TOKEN_HASH = "H";
|
||||
|
||||
// integer, seconds
|
||||
static final String ATTR_LINK_DEVICE_TOKEN_TTL = "E";
|
||||
|
||||
// unidentified access key; byte[] or null
|
||||
static final String ATTR_UAK = "UAK";
|
||||
|
||||
@@ -154,6 +164,7 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
private final String phoneNumberIdentifierConstraintTableName;
|
||||
private final String usernamesConstraintTableName;
|
||||
private final String deletedAccountsTableName;
|
||||
private final String usedLinkDeviceTokenTableName;
|
||||
private final String accountsTableName;
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -165,7 +176,8 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
final String phoneNumberConstraintTableName,
|
||||
final String phoneNumberIdentifierConstraintTableName,
|
||||
final String usernamesConstraintTableName,
|
||||
final String deletedAccountsTableName) {
|
||||
final String deletedAccountsTableName,
|
||||
final String usedLinkDeviceTokenTableName) {
|
||||
|
||||
super(client);
|
||||
this.clock = clock;
|
||||
@@ -175,6 +187,7 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
this.accountsTableName = accountsTableName;
|
||||
this.usernamesConstraintTableName = usernamesConstraintTableName;
|
||||
this.deletedAccountsTableName = deletedAccountsTableName;
|
||||
this.usedLinkDeviceTokenTableName = usedLinkDeviceTokenTableName;
|
||||
}
|
||||
|
||||
public Accounts(
|
||||
@@ -184,11 +197,12 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
final String phoneNumberConstraintTableName,
|
||||
final String phoneNumberIdentifierConstraintTableName,
|
||||
final String usernamesConstraintTableName,
|
||||
final String deletedAccountsTableName) {
|
||||
final String deletedAccountsTableName,
|
||||
final String usedLinkDeviceTokenTableName) {
|
||||
|
||||
this(Clock.systemUTC(), client, asyncClient, accountsTableName,
|
||||
phoneNumberConstraintTableName, phoneNumberIdentifierConstraintTableName, usernamesConstraintTableName,
|
||||
deletedAccountsTableName);
|
||||
deletedAccountsTableName, usedLinkDeviceTokenTableName);
|
||||
}
|
||||
|
||||
static class UsernameTable {
|
||||
@@ -1065,6 +1079,28 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
});
|
||||
}
|
||||
|
||||
public TransactWriteItem buildTransactWriteItemForLinkDevice(final String linkDeviceToken, final Duration tokenTtl) {
|
||||
final byte[] linkDeviceTokenHash;
|
||||
|
||||
try {
|
||||
linkDeviceTokenHash = MessageDigest.getInstance("SHA-256").digest(linkDeviceToken.getBytes(StandardCharsets.UTF_8));
|
||||
} catch (final NoSuchAlgorithmException e) {
|
||||
throw new AssertionError("Every implementation of the Java platform is required to support the SHA-256 MessageDigest algorithm", e);
|
||||
}
|
||||
|
||||
return TransactWriteItem.builder()
|
||||
.put(Put.builder()
|
||||
.tableName(usedLinkDeviceTokenTableName)
|
||||
.item(Map.of(
|
||||
KEY_LINK_DEVICE_TOKEN_HASH, AttributeValue.fromB(SdkBytes.fromByteArray(linkDeviceTokenHash)),
|
||||
ATTR_LINK_DEVICE_TOKEN_TTL, AttributeValue.fromN(String.valueOf(clock.instant().plus(tokenTtl).getEpochSecond()))
|
||||
))
|
||||
.conditionExpression("attribute_not_exists(#linkDeviceTokenHash)")
|
||||
.expressionAttributeNames(Map.of("#linkDeviceTokenHash", KEY_LINK_DEVICE_TOKEN_HASH))
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
public Optional<Account> getByE164(final String number) {
|
||||
return getByIndirectLookup(
|
||||
|
||||
+294
-18
@@ -12,19 +12,29 @@ import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectWriter;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.base.Preconditions;
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import io.lettuce.core.RedisException;
|
||||
import io.lettuce.core.SetArgs;
|
||||
import io.lettuce.core.cluster.api.sync.RedisAdvancedClusterCommands;
|
||||
import io.lettuce.core.pubsub.RedisPubSubAdapter;
|
||||
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.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.Key;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
@@ -35,7 +45,9 @@ import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Consumer;
|
||||
@@ -43,6 +55,8 @@ import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import org.apache.commons.lang3.ObjectUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
@@ -52,13 +66,16 @@ import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.DeviceInfo;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubConnection;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisOperation;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
|
||||
@@ -71,15 +88,15 @@ import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledException;
|
||||
|
||||
public class AccountsManager {
|
||||
public class AccountsManager extends RedisPubSubAdapter<String, String> implements Managed {
|
||||
|
||||
private static final Timer createTimer = Metrics.timer(name(AccountsManager.class, "create"));
|
||||
private static final Timer updateTimer = Metrics.timer(name(AccountsManager.class, "update"));
|
||||
private static final Timer getByNumberTimer = Metrics.timer(name(AccountsManager.class, "getByNumber"));
|
||||
private static final Timer getByUsernameHashTimer = Metrics.timer(name(AccountsManager.class, "getByUsernameHash"));
|
||||
private static final Timer getByUsernameLinkHandleTimer = Metrics.timer(
|
||||
name(AccountsManager.class, "getByUsernameLinkHandle"));
|
||||
private static final Timer getByUsernameLinkHandleTimer = Metrics.timer(name(AccountsManager.class, "getByUsernameLinkHandle"));
|
||||
private static final Timer getByUuidTimer = Metrics.timer(name(AccountsManager.class, "getByUuid"));
|
||||
private static final Timer deleteTimer = Metrics.timer(name(AccountsManager.class, "delete"));
|
||||
|
||||
@@ -97,7 +114,8 @@ public class AccountsManager {
|
||||
|
||||
private final Accounts accounts;
|
||||
private final PhoneNumberIdentifiers phoneNumberIdentifiers;
|
||||
private final FaultTolerantRedisCluster cacheCluster;
|
||||
private final FaultTolerantRedisClusterClient cacheCluster;
|
||||
private final FaultTolerantRedisClient pubSubRedisSingleton;
|
||||
private final AccountLockManager accountLockManager;
|
||||
private final KeysManager keysManager;
|
||||
private final MessagesManager messagesManager;
|
||||
@@ -112,6 +130,18 @@ public class AccountsManager {
|
||||
private final Clock clock;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
|
||||
private final Key verificationTokenKey;
|
||||
|
||||
private final FaultTolerantPubSubConnection<String, String> pubSubConnection;
|
||||
|
||||
private final Map<String, CompletableFuture<Optional<DeviceInfo>>> waitForDeviceFuturesByTokenIdentifier =
|
||||
new ConcurrentHashMap<>();
|
||||
|
||||
private static final int SHA256_HASH_LENGTH = getSha256MessageDigest().getDigestLength();
|
||||
private static final Duration RECENTLY_ADDED_DEVICE_TTL = Duration.ofHours(1);
|
||||
private static final String LINKED_DEVICE_PREFIX = "linked_device::";
|
||||
private static final String LINKED_DEVICE_KEYSPACE_PATTERN = "__keyspace@0__:" + LINKED_DEVICE_PREFIX + "*";
|
||||
|
||||
private static final ObjectWriter ACCOUNT_REDIS_JSON_WRITER = SystemMapper.jsonMapper()
|
||||
.writer(SystemMapper.excludingField(Account.class, List.of("uuid")));
|
||||
|
||||
@@ -125,6 +155,12 @@ public class AccountsManager {
|
||||
|
||||
private static final int MAX_UPDATE_ATTEMPTS = 10;
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration LINK_DEVICE_TOKEN_EXPIRATION_DURATION = Duration.ofMinutes(10);
|
||||
|
||||
@VisibleForTesting
|
||||
static final String LINK_DEVICE_VERIFICATION_TOKEN_ALGORITHM = "HmacSHA256";
|
||||
|
||||
public enum DeletionReason {
|
||||
ADMIN_DELETED("admin"),
|
||||
EXPIRED ("expired"),
|
||||
@@ -139,7 +175,8 @@ public class AccountsManager {
|
||||
|
||||
public AccountsManager(final Accounts accounts,
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers,
|
||||
final FaultTolerantRedisCluster cacheCluster,
|
||||
final FaultTolerantRedisClusterClient cacheCluster,
|
||||
final FaultTolerantRedisClient pubSubRedisSingleton,
|
||||
final AccountLockManager accountLockManager,
|
||||
final KeysManager keysManager,
|
||||
final MessagesManager messagesManager,
|
||||
@@ -152,10 +189,12 @@ public class AccountsManager {
|
||||
final Executor accountLockExecutor,
|
||||
final Executor clientPresenceExecutor,
|
||||
final Clock clock,
|
||||
final byte[] linkDeviceSecret,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
this.accounts = accounts;
|
||||
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
|
||||
this.cacheCluster = cacheCluster;
|
||||
this.pubSubRedisSingleton = pubSubRedisSingleton;
|
||||
this.accountLockManager = accountLockManager;
|
||||
this.keysManager = keysManager;
|
||||
this.messagesManager = messagesManager;
|
||||
@@ -169,6 +208,29 @@ public class AccountsManager {
|
||||
this.clientPresenceExecutor = clientPresenceExecutor;
|
||||
this.clock = requireNonNull(clock);
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
|
||||
this.verificationTokenKey = new SecretKeySpec(linkDeviceSecret, LINK_DEVICE_VERIFICATION_TOKEN_ALGORITHM);
|
||||
|
||||
// Fail fast: reject bad keys
|
||||
try {
|
||||
getInitializedMac(verificationTokenKey);
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw new IllegalArgumentException(e);
|
||||
}
|
||||
|
||||
this.pubSubConnection = pubSubRedisSingleton.createPubSubConnection();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
pubSubConnection.usePubSubConnection(connection -> connection.addListener(this));
|
||||
pubSubConnection.usePubSubConnection(connection -> connection.sync().psubscribe(LINKED_DEVICE_KEYSPACE_PATTERN));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
pubSubConnection.usePubSubConnection(connection -> connection.sync().punsubscribe());
|
||||
pubSubConnection.usePubSubConnection(connection -> connection.removeListener(this));
|
||||
}
|
||||
|
||||
public Account create(final String number,
|
||||
@@ -275,46 +337,190 @@ public class AccountsManager {
|
||||
});
|
||||
}
|
||||
|
||||
public CompletableFuture<Pair<Account, Device>> addDevice(final Account account, final DeviceSpec deviceSpec) {
|
||||
public CompletableFuture<Pair<Account, Device>> addDevice(final Account account, final DeviceSpec deviceSpec, final String linkDeviceToken) {
|
||||
return accountLockManager.withLockAsync(List.of(account.getNumber()),
|
||||
() -> addDevice(account.getIdentifier(IdentityType.ACI), deviceSpec, MAX_UPDATE_ATTEMPTS),
|
||||
() -> addDevice(account.getIdentifier(IdentityType.ACI), deviceSpec, linkDeviceToken, MAX_UPDATE_ATTEMPTS),
|
||||
accountLockExecutor);
|
||||
}
|
||||
|
||||
private CompletableFuture<Pair<Account, Device>> addDevice(final UUID accountIdentifier, final DeviceSpec deviceSpec, final int retries) {
|
||||
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();
|
||||
|
||||
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();
|
||||
|
||||
account.addDevice(deviceSpec.toDevice(nextDeviceId, clock));
|
||||
|
||||
final List<TransactWriteItem> additionalWriteItems = keysManager.buildWriteItemsForNewDevice(
|
||||
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());
|
||||
deviceSpec.pniPqLastResortPreKey()));
|
||||
|
||||
return CompletableFuture.allOf(
|
||||
keysManager.deleteSingleUsePreKeys(account.getUuid(), nextDeviceId),
|
||||
keysManager.deleteSingleUsePreKeys(account.getPhoneNumberIdentifier(), nextDeviceId),
|
||||
messagesManager.clear(account.getUuid(), nextDeviceId))
|
||||
.thenCompose(ignored -> accounts.updateTransactionallyAsync(account, additionalWriteItems))
|
||||
additionalWriteItems.add(accounts.buildTransactWriteItemForLinkDevice(linkDeviceToken, LINK_DEVICE_TOKEN_EXPIRATION_DURATION));
|
||||
|
||||
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, retries - 1);
|
||||
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();
|
||||
|
||||
final boolean tokenReuseConditionFailed =
|
||||
"ConditionalCheckFailed".equals(transactionCanceledException.cancellationReasons().getLast().code());
|
||||
|
||||
if (cancelledTransactions == 1 && tokenReuseConditionFailed) {
|
||||
return CompletableFuture.failedFuture(new LinkDeviceTokenAlreadyUsedException());
|
||||
}
|
||||
}
|
||||
|
||||
return CompletableFuture.failedFuture(throwable);
|
||||
})
|
||||
.whenComplete((updatedAccountAndDevice, throwable) -> {
|
||||
if (updatedAccountAndDevice != null) {
|
||||
final String key = getLinkedDeviceKey(getLinkDeviceTokenIdentifier(linkDeviceToken));
|
||||
final String deviceInfoJson;
|
||||
|
||||
try {
|
||||
deviceInfoJson = SystemMapper.jsonMapper().writeValueAsString(DeviceInfo.forDevice(updatedAccountAndDevice.second()));
|
||||
} catch (final JsonProcessingException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
|
||||
pubSubRedisSingleton.withConnection(connection ->
|
||||
connection.async().set(key, deviceInfoJson, SetArgs.Builder.ex(RECENTLY_ADDED_DEVICE_TTL)))
|
||||
.whenComplete((ignored, pubSubThrowable) -> {
|
||||
if (pubSubThrowable != null) {
|
||||
logger.warn("Failed to record recently-created device", pubSubThrowable);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private Mac getInitializedMac() {
|
||||
try {
|
||||
return getInitializedMac(verificationTokenKey);
|
||||
} catch (final InvalidKeyException e) {
|
||||
// We checked the key at construction time, so this can never happen
|
||||
throw new AssertionError("Previously valid key now invalid", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static Mac getInitializedMac(final Key linkDeviceTokenKey) throws InvalidKeyException {
|
||||
try {
|
||||
final Mac mac = Mac.getInstance(LINK_DEVICE_VERIFICATION_TOKEN_ALGORITHM);
|
||||
mac.init(linkDeviceTokenKey);
|
||||
|
||||
return mac;
|
||||
} catch (final NoSuchAlgorithmException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
public String generateLinkDeviceToken(final UUID aci) {
|
||||
final String claims = aci + "." + clock.instant().toEpochMilli();
|
||||
final byte[] signature = getInitializedMac().doFinal(claims.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
return claims + ":" + Base64.getUrlEncoder().encodeToString(signature);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static String generateLinkDeviceToken(final UUID aci, final Key linkDeviceTokenKey, final Clock clock)
|
||||
throws InvalidKeyException {
|
||||
|
||||
final String claims = aci + "." + clock.instant().toEpochMilli();
|
||||
final byte[] signature = getInitializedMac(linkDeviceTokenKey).doFinal(claims.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
return claims + ":" + Base64.getUrlEncoder().encodeToString(signature);
|
||||
}
|
||||
|
||||
public static String getLinkDeviceTokenIdentifier(final String linkDeviceToken) {
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(
|
||||
getSha256MessageDigest().digest(linkDeviceToken.getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks that a device-linking token is valid and returns the account identifier from the token if so, or empty if
|
||||
* the token was invalid
|
||||
*
|
||||
* @param token the device-linking token to check
|
||||
*
|
||||
* @return the account identifier from a valid token or empty if the token was invalid
|
||||
*/
|
||||
public Optional<UUID> checkDeviceLinkingToken(final String token) {
|
||||
final String[] claimsAndSignature = token.split(":", 2);
|
||||
|
||||
if (claimsAndSignature.length != 2) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
final byte[] expectedSignature = getInitializedMac().doFinal(claimsAndSignature[0].getBytes(StandardCharsets.UTF_8));
|
||||
final byte[] providedSignature;
|
||||
|
||||
try {
|
||||
providedSignature = Base64.getUrlDecoder().decode(claimsAndSignature[1]);
|
||||
} catch (final IllegalArgumentException e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
if (!MessageDigest.isEqual(expectedSignature, providedSignature)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
final String[] aciAndTimestamp = claimsAndSignature[0].split("\\.", 2);
|
||||
|
||||
if (aciAndTimestamp.length != 2) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
final UUID aci;
|
||||
|
||||
try {
|
||||
aci = UUID.fromString(aciAndTimestamp[0]);
|
||||
} catch (final IllegalArgumentException e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
final Instant timestamp;
|
||||
|
||||
try {
|
||||
timestamp = Instant.ofEpochMilli(Long.parseLong(aciAndTimestamp[1]));
|
||||
} catch (final NumberFormatException e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
final Instant tokenExpiration = timestamp.plus(LINK_DEVICE_TOKEN_EXPIRATION_DURATION);
|
||||
|
||||
if (tokenExpiration.isBefore(clock.instant())) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
return Optional.of(aci);
|
||||
}
|
||||
|
||||
public CompletableFuture<Account> removeDevice(final Account account, final byte deviceId) {
|
||||
if (deviceId == Device.PRIMARY_ID) {
|
||||
throw new IllegalArgumentException("Cannot remove primary device");
|
||||
@@ -1004,7 +1210,6 @@ public class AccountsManager {
|
||||
keysManager.deleteSingleUsePreKeys(account.getUuid()),
|
||||
keysManager.deleteSingleUsePreKeys(account.getPhoneNumberIdentifier()),
|
||||
messagesManager.clear(account.getUuid()),
|
||||
messagesManager.clear(account.getPhoneNumberIdentifier()),
|
||||
profilesManager.deleteAll(account.getUuid()),
|
||||
registrationRecoveryPasswordsManager.removeForNumber(account.getNumber()))
|
||||
.thenCompose(ignored -> accounts.delete(account.getUuid(), additionalWriteItems))
|
||||
@@ -1193,4 +1398,75 @@ public class AccountsManager {
|
||||
.whenComplete((ignoredResult, ignoredException) -> sample.stop(redisDeleteTimer))
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<DeviceInfo>> waitForNewLinkedDevice(final String linkDeviceTokenIdentifier, final Duration timeout) {
|
||||
// Unbeknownst to callers but beknownst to us, the "link device token identifier" is the base64/url-encoded SHA256
|
||||
// hash of a device-linking token. Before we use the string anywhere, make sure it's the right "shape" for a hash.
|
||||
if (Base64.getUrlDecoder().decode(linkDeviceTokenIdentifier).length != SHA256_HASH_LENGTH) {
|
||||
return CompletableFuture.failedFuture(new IllegalArgumentException("Invalid token identifier"));
|
||||
}
|
||||
|
||||
final CompletableFuture<Optional<DeviceInfo>> waitForDeviceFuture = new CompletableFuture<>();
|
||||
|
||||
waitForDeviceFuture
|
||||
.completeOnTimeout(Optional.empty(), TimeUnit.MILLISECONDS.convert(timeout), TimeUnit.MILLISECONDS)
|
||||
.whenComplete((maybeDevice, throwable) -> waitForDeviceFuturesByTokenIdentifier.compute(linkDeviceTokenIdentifier,
|
||||
(ignored, existingFuture) -> {
|
||||
// Only remove the future from the map if it's THIS future, and not one that later displaced this one
|
||||
return existingFuture == waitForDeviceFuture ? null : existingFuture;
|
||||
}));
|
||||
|
||||
{
|
||||
final CompletableFuture<Optional<DeviceInfo>> displacedFuture =
|
||||
waitForDeviceFuturesByTokenIdentifier.put(linkDeviceTokenIdentifier, waitForDeviceFuture);
|
||||
|
||||
if (displacedFuture != null) {
|
||||
displacedFuture.complete(Optional.empty());
|
||||
}
|
||||
}
|
||||
|
||||
// The device may already have been linked by the time the caller started watching for it; perform an immediate
|
||||
// check to see if the device is already there.
|
||||
pubSubRedisSingleton.withConnection(connection -> connection.async().get(getLinkedDeviceKey(linkDeviceTokenIdentifier)))
|
||||
.thenAccept(response -> {
|
||||
if (StringUtils.isNotBlank(response)) {
|
||||
handleDeviceAdded(waitForDeviceFuture, response);
|
||||
}
|
||||
});
|
||||
|
||||
return waitForDeviceFuture;
|
||||
}
|
||||
|
||||
private static String getLinkedDeviceKey(final String linkDeviceTokenIdentifier) {
|
||||
return LINKED_DEVICE_PREFIX + linkDeviceTokenIdentifier;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void message(final String pattern, final String channel, final String message) {
|
||||
if (LINKED_DEVICE_KEYSPACE_PATTERN.equals(pattern) && "set".equalsIgnoreCase(message)) {
|
||||
// The `- 1` here compensates for the '*' in the pattern
|
||||
final String tokenIdentifier = channel.substring(LINKED_DEVICE_KEYSPACE_PATTERN.length() - 1);
|
||||
|
||||
Optional.ofNullable(waitForDeviceFuturesByTokenIdentifier.remove(tokenIdentifier))
|
||||
.ifPresent(future -> pubSubRedisSingleton.withConnection(connection -> connection.async().get(getLinkedDeviceKey(tokenIdentifier)))
|
||||
.thenAccept(deviceInfoJson -> handleDeviceAdded(future, deviceInfoJson)));
|
||||
}
|
||||
}
|
||||
|
||||
private void handleDeviceAdded(final CompletableFuture<Optional<DeviceInfo>> future, final String deviceInfoJson) {
|
||||
try {
|
||||
future.complete(Optional.of(SystemMapper.jsonMapper().readValue(deviceInfoJson, DeviceInfo.class)));
|
||||
} catch (final JsonProcessingException e) {
|
||||
logger.error("Could not parse device json", e);
|
||||
future.completeExceptionally(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static MessageDigest getSha256MessageDigest() {
|
||||
try {
|
||||
return MessageDigest.getInstance("SHA-256");
|
||||
} catch (final NoSuchAlgorithmException e) {
|
||||
throw new AssertionError("Every implementation of the Java platform is required to support the SHA-256 MessageDigest algorithm", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@ public class Device {
|
||||
public static final List<Byte> ALL_POSSIBLE_DEVICE_IDS = IntStream.range(Device.PRIMARY_ID, MAXIMUM_DEVICE_ID).boxed()
|
||||
.map(Integer::byteValue).collect(Collectors.toList());
|
||||
|
||||
private static final long ALLOWED_LINKED_IDLE_MILLIS = Duration.ofDays(30).toMillis();
|
||||
private static final long ALLOWED_LINKED_IDLE_MILLIS = Duration.ofDays(45).toMillis();
|
||||
private static final long ALLOWED_PRIMARY_IDLE_MILLIS = Duration.ofDays(180).toMillis();
|
||||
|
||||
@JsonDeserialize(using = DeviceIdDeserializer.class)
|
||||
@@ -49,9 +49,6 @@ public class Device {
|
||||
@JsonProperty
|
||||
private String apnId;
|
||||
|
||||
@JsonProperty
|
||||
private String voipApnId;
|
||||
|
||||
@JsonProperty
|
||||
private long pushTimestamp;
|
||||
|
||||
@@ -89,14 +86,6 @@ public class Device {
|
||||
}
|
||||
}
|
||||
|
||||
public String getVoipApnId() {
|
||||
return voipApnId;
|
||||
}
|
||||
|
||||
public void setVoipApnId(String voipApnId) {
|
||||
this.voipApnId = voipApnId;
|
||||
}
|
||||
|
||||
public void setLastSeen(long lastSeen) {
|
||||
this.lastSeen = lastSeen;
|
||||
}
|
||||
@@ -232,7 +221,7 @@ public class Device {
|
||||
return this.userAgent;
|
||||
}
|
||||
|
||||
public record DeviceCapabilities(boolean storage, boolean transfer, boolean paymentActivation, boolean deleteSync,
|
||||
public record DeviceCapabilities(boolean storage, boolean transfer, boolean deleteSync,
|
||||
boolean versionedExpirationTimer) {
|
||||
}
|
||||
}
|
||||
@@ -39,13 +39,8 @@ public record DeviceSpec(
|
||||
device.setLastSeen(Util.todayInMillis());
|
||||
device.setUserAgent(signalAgent());
|
||||
|
||||
apnRegistrationId().ifPresent(apnRegistrationId -> {
|
||||
device.setApnId(apnRegistrationId.apnRegistrationId());
|
||||
device.setVoipApnId(apnRegistrationId.voipRegistrationId());
|
||||
});
|
||||
|
||||
gcmRegistrationId().ifPresent(gcmRegistrationId ->
|
||||
device.setGcmId(gcmRegistrationId.gcmRegistrationId()));
|
||||
apnRegistrationId().ifPresent(apnRegistrationId -> device.setApnId(apnRegistrationId.apnRegistrationId()));
|
||||
gcmRegistrationId().ifPresent(gcmRegistrationId -> device.setGcmId(gcmRegistrationId.gcmRegistrationId()));
|
||||
|
||||
return device;
|
||||
}
|
||||
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
public class LinkDeviceTokenAlreadyUsedException extends Exception {
|
||||
}
|
||||
@@ -48,11 +48,10 @@ import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfigurati
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicMessagesConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.experiment.Experiment;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubConnection;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubClusterConnection;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.RedisClusterUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
@@ -120,8 +119,8 @@ import reactor.core.scheduler.Schedulers;
|
||||
*/
|
||||
public class MessagesCache extends RedisClusterPubSubAdapter<String, String> implements Managed {
|
||||
|
||||
private final FaultTolerantRedisCluster redisCluster;
|
||||
private final FaultTolerantPubSubConnection<String, String> pubSubConnection;
|
||||
private final FaultTolerantRedisClusterClient redisCluster;
|
||||
private final FaultTolerantPubSubClusterConnection<String, String> pubSubConnection;
|
||||
private final Clock clock;
|
||||
|
||||
private final ExecutorService notificationExecutorService;
|
||||
@@ -184,9 +183,9 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessagesCache.class);
|
||||
|
||||
public MessagesCache(final FaultTolerantRedisCluster redisCluster, final ExecutorService notificationExecutorService,
|
||||
final Scheduler messageDeliveryScheduler, final ExecutorService messageDeletionExecutorService, final Clock clock,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager)
|
||||
public MessagesCache(final FaultTolerantRedisClusterClient redisCluster, final ExecutorService notificationExecutorService,
|
||||
final Scheduler messageDeliveryScheduler, final ExecutorService messageDeletionExecutorService, final Clock clock,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager)
|
||||
throws IOException {
|
||||
this(
|
||||
redisCluster,
|
||||
@@ -206,15 +205,15 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
MessagesCache(final FaultTolerantRedisCluster redisCluster, final ExecutorService notificationExecutorService,
|
||||
final Scheduler messageDeliveryScheduler, final ExecutorService messageDeletionExecutorService, final Clock clock,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final MessagesCacheInsertScript insertScript,
|
||||
final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript,
|
||||
final MessagesCacheGetItemsScript getItemsScript, final MessagesCacheRemoveByGuidScript removeByGuidScript,
|
||||
final MessagesCacheRemoveQueueScript removeQueueScript,
|
||||
final MessagesCacheGetQueuesToPersistScript getQueuesToPersistScript,
|
||||
final MessagesCacheRemoveRecipientViewFromMrmDataScript removeRecipientViewFromMrmDataScript)
|
||||
MessagesCache(final FaultTolerantRedisClusterClient redisCluster, final ExecutorService notificationExecutorService,
|
||||
final Scheduler messageDeliveryScheduler, final ExecutorService messageDeletionExecutorService, final Clock clock,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final MessagesCacheInsertScript insertScript,
|
||||
final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript,
|
||||
final MessagesCacheGetItemsScript getItemsScript, final MessagesCacheRemoveByGuidScript removeByGuidScript,
|
||||
final MessagesCacheRemoveQueueScript removeQueueScript,
|
||||
final MessagesCacheGetQueuesToPersistScript getQueuesToPersistScript,
|
||||
final MessagesCacheRemoveRecipientViewFromMrmDataScript removeRecipientViewFromMrmDataScript)
|
||||
throws IOException {
|
||||
|
||||
this.redisCluster = redisCluster;
|
||||
@@ -296,21 +295,25 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
.thenApplyAsync(serialized -> {
|
||||
|
||||
final List<RemovedMessage> removedMessages = new ArrayList<>(serialized.size());
|
||||
final List<byte[]> sharedMrmKeysToUpdate = new ArrayList<>();
|
||||
final Map<ServiceIdentifier, List<byte[]>> serviceIdentifierToMrmKeys = new HashMap<>();
|
||||
|
||||
for (final byte[] bytes : serialized) {
|
||||
try {
|
||||
final MessageProtos.Envelope envelope = MessageProtos.Envelope.parseFrom(bytes);
|
||||
removedMessages.add(RemovedMessage.fromEnvelope(envelope));
|
||||
if (envelope.hasSharedMrmKey()) {
|
||||
sharedMrmKeysToUpdate.add(envelope.getSharedMrmKey().toByteArray());
|
||||
serviceIdentifierToMrmKeys.computeIfAbsent(
|
||||
ServiceIdentifier.valueOf(envelope.getDestinationServiceId()), ignored -> new ArrayList<>())
|
||||
.add(envelope.getSharedMrmKey().toByteArray());
|
||||
}
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
logger.warn("Failed to parse envelope", e);
|
||||
}
|
||||
}
|
||||
|
||||
removeRecipientViewFromMrmData(sharedMrmKeysToUpdate, destinationUuid, destinationDevice);
|
||||
serviceIdentifierToMrmKeys.forEach(
|
||||
(serviceId, keysToUpdate) -> removeRecipientViewFromMrmData(keysToUpdate, serviceId, destinationDevice));
|
||||
|
||||
return removedMessages;
|
||||
}, messageDeletionExecutorService).whenComplete((ignored, throwable) -> sample.stop(removeByGuidTimer));
|
||||
|
||||
@@ -438,30 +441,30 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
ServiceIdentifier.valueOf(mrmMessage.getDestinationServiceId()), destinationDevice);
|
||||
|
||||
final Mono<MessageProtos.Envelope> mrmMessageMono = Mono.from(redisCluster.withBinaryClusterReactive(
|
||||
conn -> conn.reactive().hmget(key, "data".getBytes(StandardCharsets.UTF_8), sharedMrmViewKey)
|
||||
.collectList()
|
||||
.publishOn(messageDeliveryScheduler)
|
||||
.handle((mrmDataAndView, sink) -> {
|
||||
try {
|
||||
assert mrmDataAndView.size() == 2;
|
||||
conn -> conn.reactive().hmget(key, "data".getBytes(StandardCharsets.UTF_8), sharedMrmViewKey)
|
||||
.collectList()
|
||||
.publishOn(messageDeliveryScheduler)))
|
||||
.<MessageProtos.Envelope>handle((mrmDataAndView, sink) -> {
|
||||
try {
|
||||
assert mrmDataAndView.size() == 2;
|
||||
|
||||
final byte[] content = SealedSenderMultiRecipientMessage.messageForRecipient(
|
||||
mrmDataAndView.getFirst().getValue(),
|
||||
mrmDataAndView.getLast().getValue());
|
||||
final byte[] content = SealedSenderMultiRecipientMessage.messageForRecipient(
|
||||
mrmDataAndView.getFirst().getValue(),
|
||||
mrmDataAndView.getLast().getValue());
|
||||
|
||||
sink.next(mrmMessage.toBuilder()
|
||||
.clearSharedMrmKey()
|
||||
.setContent(ByteString.copyFrom(content))
|
||||
.build());
|
||||
sink.next(mrmMessage.toBuilder()
|
||||
.clearSharedMrmKey()
|
||||
.setContent(ByteString.copyFrom(content))
|
||||
.build());
|
||||
|
||||
mrmContentRetrievedCounter.increment();
|
||||
} catch (Exception e) {
|
||||
sink.error(e);
|
||||
}
|
||||
})));
|
||||
mrmContentRetrievedCounter.increment();
|
||||
} catch (Exception e) {
|
||||
sink.error(e);
|
||||
}
|
||||
})
|
||||
.share();
|
||||
|
||||
experiment.compareFutureResult(mrmMessage.toBuilder().clearSharedMrmKey().build(),
|
||||
mrmMessageMono.toFuture());
|
||||
experiment.compareMonoResult(mrmMessage.toBuilder().clearSharedMrmKey().build(), mrmMessageMono);
|
||||
|
||||
return mrmMessageMono;
|
||||
} else {
|
||||
@@ -472,7 +475,8 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
/**
|
||||
* Makes a best-effort attempt at asynchronously updating (and removing when empty) the MRM data structure
|
||||
*/
|
||||
void removeRecipientViewFromMrmData(final List<byte[]> sharedMrmKeys, final UUID accountUuid, final byte deviceId) {
|
||||
void removeRecipientViewFromMrmData(final List<byte[]> sharedMrmKeys, final ServiceIdentifier serviceIdentifier,
|
||||
final byte deviceId) {
|
||||
|
||||
if (sharedMrmKeys.isEmpty()) {
|
||||
return;
|
||||
@@ -483,7 +487,7 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
.collectMultimap(SlotHash::getSlot)
|
||||
.flatMapMany(slotsAndKeys -> Flux.fromIterable(slotsAndKeys.values()))
|
||||
.flatMap(
|
||||
keys -> removeRecipientViewFromMrmDataScript.execute(keys, new AciServiceIdentifier(accountUuid), deviceId),
|
||||
keys -> removeRecipientViewFromMrmDataScript.execute(keys, serviceIdentifier, deviceId),
|
||||
REMOVE_MRM_RECIPIENT_VIEW_CONCURRENCY)
|
||||
.doOnNext(sharedMrmDataKeyRemovedCounter::increment)
|
||||
.onErrorResume(e -> {
|
||||
@@ -575,7 +579,7 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
return Mono.empty();
|
||||
}
|
||||
|
||||
final List<byte[]> mrmKeys = new ArrayList<>(messagesToProcess.size());
|
||||
final Map<ServiceIdentifier, List<byte[]>> serviceIdentifierToMrmKeys = new HashMap<>();
|
||||
final List<String> processedMessages = new ArrayList<>(messagesToProcess.size());
|
||||
for (byte[] serialized : messagesToProcess) {
|
||||
try {
|
||||
@@ -584,14 +588,17 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
processedMessages.add(message.getServerGuid());
|
||||
|
||||
if (message.hasSharedMrmKey()) {
|
||||
mrmKeys.add(message.getSharedMrmKey().toByteArray());
|
||||
serviceIdentifierToMrmKeys.computeIfAbsent(ServiceIdentifier.valueOf(message.getDestinationServiceId()),
|
||||
ignored -> new ArrayList<>())
|
||||
.add(message.getSharedMrmKey().toByteArray());
|
||||
}
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
logger.warn("Failed to parse envelope", e);
|
||||
}
|
||||
}
|
||||
|
||||
removeRecipientViewFromMrmData(mrmKeys, destinationUuid, deviceId);
|
||||
serviceIdentifierToMrmKeys.forEach((serviceId, keysToUpdate) ->
|
||||
removeRecipientViewFromMrmData(keysToUpdate, serviceId, deviceId));
|
||||
|
||||
return removeQueueScript.execute(destinationUuid, deviceId, processedMessages);
|
||||
})
|
||||
|
||||
+2
-2
@@ -11,7 +11,7 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/**
|
||||
@@ -22,7 +22,7 @@ class MessagesCacheGetItemsScript {
|
||||
|
||||
private final ClusterLuaScript getItemsScript;
|
||||
|
||||
MessagesCacheGetItemsScript(FaultTolerantRedisCluster redisCluster) throws IOException {
|
||||
MessagesCacheGetItemsScript(FaultTolerantRedisClusterClient redisCluster) throws IOException {
|
||||
this.getItemsScript = ClusterLuaScript.fromResource(redisCluster, "lua/get_items.lua", ScriptOutputType.OBJECT);
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -11,7 +11,7 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
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
|
||||
@@ -23,7 +23,7 @@ class MessagesCacheGetQueuesToPersistScript {
|
||||
|
||||
private final ClusterLuaScript getQueuesToPersistScript;
|
||||
|
||||
MessagesCacheGetQueuesToPersistScript(final FaultTolerantRedisCluster redisCluster) throws IOException {
|
||||
MessagesCacheGetQueuesToPersistScript(final FaultTolerantRedisClusterClient redisCluster) throws IOException {
|
||||
this.getQueuesToPersistScript = ClusterLuaScript.fromResource(redisCluster, "lua/get_queues_to_persist.lua",
|
||||
ScriptOutputType.MULTI);
|
||||
}
|
||||
|
||||
+2
-2
@@ -14,7 +14,7 @@ import java.util.List;
|
||||
import java.util.UUID;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
|
||||
/**
|
||||
* Inserts an envelope into the message queue for a destination device.
|
||||
@@ -23,7 +23,7 @@ class MessagesCacheInsertScript {
|
||||
|
||||
private final ClusterLuaScript insertScript;
|
||||
|
||||
MessagesCacheInsertScript(FaultTolerantRedisCluster redisCluster) throws IOException {
|
||||
MessagesCacheInsertScript(FaultTolerantRedisClusterClient redisCluster) throws IOException {
|
||||
this.insertScript = ClusterLuaScript.fromResource(redisCluster, "lua/insert_item.lua", ScriptOutputType.INTEGER);
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -11,7 +11,7 @@ import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
|
||||
/**
|
||||
* Inserts the shared multi-recipient message payload into the cache. The list of recipients and views will be set as
|
||||
@@ -25,7 +25,7 @@ class MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript {
|
||||
|
||||
static final String ERROR_KEY_EXISTS = "ERR key exists";
|
||||
|
||||
MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript(FaultTolerantRedisCluster redisCluster)
|
||||
MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript(FaultTolerantRedisClusterClient redisCluster)
|
||||
throws IOException {
|
||||
this.script = ClusterLuaScript.fromResource(redisCluster, "lua/insert_shared_multirecipient_message_data.lua",
|
||||
ScriptOutputType.INTEGER);
|
||||
|
||||
+2
-2
@@ -12,7 +12,7 @@ import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
|
||||
/**
|
||||
* Removes a list of message GUIDs from the queue of a destination device.
|
||||
@@ -21,7 +21,7 @@ class MessagesCacheRemoveByGuidScript {
|
||||
|
||||
private final ClusterLuaScript removeByGuidScript;
|
||||
|
||||
MessagesCacheRemoveByGuidScript(final FaultTolerantRedisCluster redisCluster) throws IOException {
|
||||
MessagesCacheRemoveByGuidScript(final FaultTolerantRedisClusterClient redisCluster) throws IOException {
|
||||
this.removeByGuidScript = ClusterLuaScript.fromResource(redisCluster, "lua/remove_item_by_guid.lua",
|
||||
ScriptOutputType.OBJECT);
|
||||
}
|
||||
|
||||
+2
-2
@@ -12,7 +12,7 @@ import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/**
|
||||
@@ -29,7 +29,7 @@ class MessagesCacheRemoveQueueScript {
|
||||
|
||||
private final ClusterLuaScript removeQueueScript;
|
||||
|
||||
MessagesCacheRemoveQueueScript(FaultTolerantRedisCluster redisCluster) throws IOException {
|
||||
MessagesCacheRemoveQueueScript(FaultTolerantRedisClusterClient redisCluster) throws IOException {
|
||||
this.removeQueueScript = ClusterLuaScript.fromResource(redisCluster, "lua/remove_queue.lua",
|
||||
ScriptOutputType.MULTI);
|
||||
}
|
||||
|
||||
+5
-4
@@ -10,9 +10,9 @@ import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/**
|
||||
@@ -25,13 +25,14 @@ class MessagesCacheRemoveRecipientViewFromMrmDataScript {
|
||||
|
||||
private final ClusterLuaScript removeRecipientViewFromMrmDataScript;
|
||||
|
||||
MessagesCacheRemoveRecipientViewFromMrmDataScript(final FaultTolerantRedisCluster redisCluster) throws IOException {
|
||||
MessagesCacheRemoveRecipientViewFromMrmDataScript(final FaultTolerantRedisClusterClient redisCluster) throws IOException {
|
||||
this.removeRecipientViewFromMrmDataScript = ClusterLuaScript.fromResource(redisCluster,
|
||||
"lua/remove_recipient_view_from_mrm_data.lua", ScriptOutputType.INTEGER);
|
||||
}
|
||||
|
||||
Mono<Long> execute(final Collection<byte[]> keysCollection, final AciServiceIdentifier serviceIdentifier,
|
||||
Mono<Long> execute(final Collection<byte[]> keysCollection, final ServiceIdentifier serviceIdentifier,
|
||||
final byte deviceId) {
|
||||
|
||||
final List<byte[]> keys = keysCollection instanceof List<byte[]>
|
||||
? (List<byte[]>) keysCollection
|
||||
: new ArrayList<>(keysCollection);
|
||||
|
||||
+7
-3
@@ -24,7 +24,6 @@ import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.reactivestreams.Publisher;
|
||||
import org.slf4j.Logger;
|
||||
@@ -118,8 +117,7 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> mayHaveMessages(final UUID accountIdentifier, final Device device) {
|
||||
return
|
||||
dbAsyncClient.query(QueryRequest.builder()
|
||||
return dbAsyncClient.query(QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.consistentRead(false)
|
||||
.limit(1)
|
||||
@@ -129,6 +127,12 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
.thenApply(queryResponse -> queryResponse.count() > 0);
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> mayHaveUrgentMessages(final UUID accountIdentifier, final Device device) {
|
||||
return Flux.from(load(accountIdentifier, device, null))
|
||||
.any(MessageProtos.Envelope::getUrgent)
|
||||
.toFuture();
|
||||
}
|
||||
|
||||
public Publisher<MessageProtos.Envelope> load(final UUID destinationAccountUuid, final Device device, final Integer limit) {
|
||||
QueryRequest.Builder queryRequestBuilder = QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
|
||||
@@ -24,6 +24,7 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import reactor.core.observability.micrometer.Micrometer;
|
||||
@@ -95,8 +96,8 @@ public class MessagesManager {
|
||||
});
|
||||
}
|
||||
|
||||
public boolean hasCachedMessages(final UUID destinationUuid, final byte destinationDevice) {
|
||||
return messagesCache.hasMessages(destinationUuid, destinationDevice);
|
||||
public CompletableFuture<Boolean> mayHaveUrgentPersistedMessages(final UUID destinationUuid, final Device destinationDevice) {
|
||||
return messagesDynamoDb.mayHaveUrgentMessages(destinationUuid, destinationDevice);
|
||||
}
|
||||
|
||||
public Mono<Pair<List<Envelope>, Boolean>> getMessagesForDevice(UUID destinationUuid, Device destinationDevice,
|
||||
@@ -214,10 +215,10 @@ public class MessagesManager {
|
||||
/**
|
||||
* Removes the recipient's view from shared MRM data if necessary
|
||||
*/
|
||||
public void removeRecipientViewFromMrmData(final UUID destinationUuid, final byte destinationDeviceId,
|
||||
final Envelope message) {
|
||||
public void removeRecipientViewFromMrmData(final byte destinationDeviceId, final Envelope message) {
|
||||
if (message.hasSharedMrmKey()) {
|
||||
messagesCache.removeRecipientViewFromMrmData(List.of(message.getSharedMrmKey().toByteArray()), destinationUuid,
|
||||
messagesCache.removeRecipientViewFromMrmData(List.of(message.getSharedMrmKey().toByteArray()),
|
||||
ServiceIdentifier.valueOf(message.getDestinationServiceId()),
|
||||
destinationDeviceId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import javax.annotation.Nullable;
|
||||
@@ -26,12 +26,12 @@ public class ProfilesManager {
|
||||
private static final String CACHE_PREFIX = "profiles::";
|
||||
|
||||
private final Profiles profiles;
|
||||
private final FaultTolerantRedisCluster cacheCluster;
|
||||
private final FaultTolerantRedisClusterClient cacheCluster;
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
|
||||
public ProfilesManager(final Profiles profiles,
|
||||
final FaultTolerantRedisCluster cacheCluster) {
|
||||
final FaultTolerantRedisClusterClient cacheCluster) {
|
||||
this.profiles = profiles;
|
||||
this.cacheCluster = cacheCluster;
|
||||
this.mapper = SystemMapper.jsonMapper();
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
public interface PubSubAddress {
|
||||
|
||||
String serialize();
|
||||
}
|
||||
+3
-3
@@ -21,13 +21,13 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
|
||||
public class ReportMessageManager {
|
||||
|
||||
private final ReportMessageDynamoDb reportMessageDynamoDb;
|
||||
private final FaultTolerantRedisCluster rateLimitCluster;
|
||||
private final FaultTolerantRedisClusterClient rateLimitCluster;
|
||||
|
||||
private final Duration counterTtl;
|
||||
|
||||
@@ -40,7 +40,7 @@ public class ReportMessageManager {
|
||||
private static final Logger logger = LoggerFactory.getLogger(ReportMessageManager.class);
|
||||
|
||||
public ReportMessageManager(final ReportMessageDynamoDb reportMessageDynamoDb,
|
||||
final FaultTolerantRedisCluster rateLimitCluster,
|
||||
final FaultTolerantRedisClusterClient rateLimitCluster,
|
||||
final Duration counterTtl) {
|
||||
|
||||
this.reportMessageDynamoDb = reportMessageDynamoDb;
|
||||
|
||||
+67
@@ -6,6 +6,8 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import java.util.Optional;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
|
||||
public class SubscriptionException extends Exception {
|
||||
|
||||
@@ -50,33 +52,98 @@ public class SubscriptionException extends Exception {
|
||||
public InvalidArguments(final String message, final Exception cause) {
|
||||
super(cause, message);
|
||||
}
|
||||
|
||||
public InvalidArguments(final String message) {
|
||||
this(message, null);
|
||||
}
|
||||
}
|
||||
|
||||
public static class InvalidLevel extends InvalidArguments {
|
||||
|
||||
public InvalidLevel() {
|
||||
super(null, null);
|
||||
}
|
||||
}
|
||||
|
||||
public static class AmountTooSmall extends InvalidArguments {
|
||||
|
||||
public AmountTooSmall() {
|
||||
super(null, null);
|
||||
}
|
||||
}
|
||||
|
||||
public static class PaymentRequiresAction extends InvalidArguments {
|
||||
|
||||
public PaymentRequiresAction(String message) {
|
||||
super(message, null);
|
||||
}
|
||||
|
||||
public PaymentRequiresAction() {
|
||||
super(null, null);
|
||||
}
|
||||
}
|
||||
|
||||
public static class PaymentRequired extends SubscriptionException {
|
||||
|
||||
public PaymentRequired() {
|
||||
super(null, null);
|
||||
}
|
||||
|
||||
public PaymentRequired(String message) {
|
||||
super(null, message);
|
||||
}
|
||||
}
|
||||
|
||||
public static class ChargeFailurePaymentRequired extends SubscriptionException {
|
||||
|
||||
private final ChargeFailure chargeFailure;
|
||||
|
||||
public ChargeFailurePaymentRequired(final ChargeFailure chargeFailure) {
|
||||
super(null, null);
|
||||
this.chargeFailure = chargeFailure;
|
||||
}
|
||||
|
||||
public ChargeFailure getChargeFailure() {
|
||||
return chargeFailure;
|
||||
}
|
||||
}
|
||||
|
||||
public static class ProcessorException extends SubscriptionException {
|
||||
|
||||
private final PaymentProvider processor;
|
||||
private final ChargeFailure chargeFailure;
|
||||
|
||||
public ProcessorException(final PaymentProvider processor, final ChargeFailure chargeFailure) {
|
||||
super(null, null);
|
||||
this.processor = processor;
|
||||
this.chargeFailure = chargeFailure;
|
||||
}
|
||||
|
||||
public PaymentProvider getProcessor() {
|
||||
return processor;
|
||||
}
|
||||
|
||||
public ChargeFailure getChargeFailure() {
|
||||
return chargeFailure;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempted to retrieve a receipt for a subscription that hasn't yet been charged or the invoice is in the open
|
||||
* state
|
||||
*/
|
||||
public static class ReceiptRequestedForOpenPayment extends SubscriptionException {
|
||||
|
||||
public ReceiptRequestedForOpenPayment() {
|
||||
super(null, null);
|
||||
}
|
||||
}
|
||||
|
||||
public static class ProcessorConflict extends SubscriptionException {
|
||||
public ProcessorConflict() {
|
||||
super(null, null);
|
||||
}
|
||||
|
||||
public ProcessorConflict(final String message) {
|
||||
super(null, message);
|
||||
}
|
||||
|
||||
+70
-19
@@ -22,6 +22,7 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.whispersystems.textsecuregcm.controllers.SubscriptionController;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
@@ -116,7 +117,8 @@ public class SubscriptionManager {
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<SubscriptionInformation>> getSubscriptionInformation(final SubscriberCredentials subscriberCredentials) {
|
||||
public CompletableFuture<Optional<SubscriptionInformation>> getSubscriptionInformation(
|
||||
final SubscriberCredentials subscriberCredentials) {
|
||||
return getSubscriber(subscriberCredentials).thenCompose(record -> {
|
||||
if (record.subscriptionId == null) {
|
||||
return CompletableFuture.completedFuture(Optional.empty());
|
||||
@@ -155,8 +157,8 @@ public class SubscriptionManager {
|
||||
*
|
||||
* @param subscriberCredentials Subscriber credentials derived from the subscriberId
|
||||
* @param request The ZK Receipt credential request
|
||||
* @param expiration A function that takes a {@link CustomerAwareSubscriptionPaymentProcessor.ReceiptItem} and returns
|
||||
* the expiration time of the receipt
|
||||
* @param expiration A function that takes a {@link CustomerAwareSubscriptionPaymentProcessor.ReceiptItem}
|
||||
* and returns the expiration time of the receipt
|
||||
* @return If the subscription had a valid payment, the requested ZK receipt credential
|
||||
*/
|
||||
public CompletableFuture<ReceiptResult> createReceiptCredentials(
|
||||
@@ -300,8 +302,9 @@ public class SubscriptionManager {
|
||||
.getSubscription(subId)
|
||||
.thenCompose(subscription -> processor.getLevelAndCurrencyForSubscription(subscription)
|
||||
.thenCompose(existingLevelAndCurrency -> {
|
||||
if (existingLevelAndCurrency.equals(new CustomerAwareSubscriptionPaymentProcessor.LevelAndCurrency(level,
|
||||
currency.toLowerCase(Locale.ROOT)))) {
|
||||
if (existingLevelAndCurrency.equals(
|
||||
new CustomerAwareSubscriptionPaymentProcessor.LevelAndCurrency(level,
|
||||
currency.toLowerCase(Locale.ROOT)))) {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
if (!transitionValidator.isTransitionValid(existingLevelAndCurrency.level(), level)) {
|
||||
@@ -349,27 +352,75 @@ public class SubscriptionManager {
|
||||
final GooglePlayBillingManager googlePlayBillingManager,
|
||||
final String purchaseToken) {
|
||||
|
||||
// For IAP providers, the subscriptionId and the customerId are both just the purchaseToken. Changes to the
|
||||
// subscription always just result in a new purchaseToken
|
||||
final ProcessorCustomer pc = new ProcessorCustomer(purchaseToken, PaymentProvider.GOOGLE_PLAY_BILLING);
|
||||
|
||||
return getSubscriber(subscriberCredentials)
|
||||
|
||||
// Check the record for an existing subscription
|
||||
.thenCompose(record -> {
|
||||
if (record.processorCustomer != null
|
||||
&& record.processorCustomer.processor() != PaymentProvider.GOOGLE_PLAY_BILLING) {
|
||||
return CompletableFuture.failedFuture(
|
||||
new SubscriptionException.ProcessorConflict("existing processor does not match"));
|
||||
}
|
||||
|
||||
// If we're replacing an existing purchaseToken, cancel it first
|
||||
return Optional.ofNullable(record.processorCustomer)
|
||||
.map(ProcessorCustomer::customerId)
|
||||
.filter(existingToken -> !purchaseToken.equals(existingToken))
|
||||
.map(googlePlayBillingManager::cancelAllActiveSubscriptions)
|
||||
.orElseGet(() -> CompletableFuture.completedFuture(null))
|
||||
.thenApply(ignored -> record);
|
||||
})
|
||||
|
||||
// Validate and set the purchaseToken
|
||||
.thenCompose(record -> googlePlayBillingManager
|
||||
|
||||
// Validating ensures we don't allow a user-determined token that's totally bunk into the subscription manager,
|
||||
// but we don't want to acknowledge it until it's successfully persisted.
|
||||
.validateToken(purchaseToken)
|
||||
|
||||
// Store the purchaseToken with the subscriber
|
||||
.thenCompose(validatedToken -> subscriptions.setIapPurchase(
|
||||
record, pc, purchaseToken, validatedToken.getLevel(), subscriberCredentials.now())
|
||||
// Now that the purchaseToken is durable, we can acknowledge it
|
||||
.thenCompose(ignore -> validatedToken.acknowledgePurchase())
|
||||
.thenApply(ignore -> validatedToken.getLevel())));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check the provided app store transactionId and write it the subscriptions table if is valid.
|
||||
*
|
||||
* @param subscriberCredentials Subscriber credentials derived from the subscriberId
|
||||
* @param appleAppStoreManager Performs app store API operations
|
||||
* @param originalTransactionId The client provided originalTransactionId that represents a purchased subscription in
|
||||
* the app store
|
||||
* @return A stage that completes with the subscription level for the accepted subscription
|
||||
*/
|
||||
public CompletableFuture<Long> updateAppStoreTransactionId(
|
||||
final SubscriberCredentials subscriberCredentials,
|
||||
final AppleAppStoreManager appleAppStoreManager,
|
||||
final String originalTransactionId) {
|
||||
|
||||
return getSubscriber(subscriberCredentials).thenCompose(record -> {
|
||||
if (record.processorCustomer != null
|
||||
&& record.processorCustomer.processor() != PaymentProvider.GOOGLE_PLAY_BILLING) {
|
||||
&& record.processorCustomer.processor() != PaymentProvider.APPLE_APP_STORE) {
|
||||
return CompletableFuture.failedFuture(
|
||||
new SubscriptionException.ProcessorConflict("existing processor does not match"));
|
||||
}
|
||||
|
||||
// For IAP providers, the subscriptionId and the customerId are both just the purchaseToken. Changes to the
|
||||
// subscription always just result in a new purchaseToken
|
||||
final ProcessorCustomer pc = new ProcessorCustomer(purchaseToken, PaymentProvider.GOOGLE_PLAY_BILLING);
|
||||
// For IAP providers, the subscriptionId and the customerId are both just the identifier for the subscription in
|
||||
// the provider (in this case, the originalTransactionId). Changes to the subscription always just result in a new
|
||||
// originalTransactionId
|
||||
final ProcessorCustomer pc = new ProcessorCustomer(originalTransactionId, PaymentProvider.APPLE_APP_STORE);
|
||||
|
||||
return googlePlayBillingManager
|
||||
// Validating ensures we don't allow a user-determined token that's totally bunk into the subscription manager,
|
||||
// but we don't want to acknowledge it until it's successfully persisted.
|
||||
.validateToken(purchaseToken)
|
||||
// Store the purchaseToken with the subscriber
|
||||
.thenCompose(validatedToken -> subscriptions.setIapPurchase(
|
||||
record, pc, purchaseToken, validatedToken.getLevel(), subscriberCredentials.now())
|
||||
// Now that the purchaseToken is durable, we can acknowledge it
|
||||
.thenCompose(ignore -> validatedToken.acknowledgePurchase())
|
||||
.thenApply(ignore -> validatedToken.getLevel()));
|
||||
return appleAppStoreManager
|
||||
.validateTransaction(originalTransactionId)
|
||||
.thenCompose(level -> subscriptions
|
||||
.setIapPurchase(record, pc, originalTransactionId, level, subscriberCredentials.now())
|
||||
.thenApply(ignore -> level));
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
Loaded 100 of 194 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user