mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 06:56:47 +00:00
Compare commits
33
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 |
No files matched your search
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
@@ -192,15 +192,16 @@ 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;
|
||||
@@ -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;
|
||||
@@ -402,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,
|
||||
@@ -445,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);
|
||||
@@ -570,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()
|
||||
@@ -632,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());
|
||||
@@ -646,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(),
|
||||
@@ -738,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);
|
||||
@@ -749,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);
|
||||
|
||||
@@ -959,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()
|
||||
@@ -989,7 +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, true));
|
||||
environment.jersey().register(new RateLimitByIpFilter(rateLimiters));
|
||||
environment.jersey().register(new RequestStatisticsFilter(TrafficSource.HTTP));
|
||||
environment.jersey().register(MultiRecipientMessageProvider.class);
|
||||
environment.jersey().register(new AuthDynamicFeature(accountAuthFilter));
|
||||
@@ -1008,12 +1025,12 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
clientReleaseManager, messageDeliveryLoopMonitor));
|
||||
webSocketEnvironment.jersey()
|
||||
.register(new WebsocketRefreshApplicationEventListener(accountsManager, clientPresenceManager));
|
||||
webSocketEnvironment.jersey().register(new RateLimitByIpFilter(rateLimiters, true));
|
||||
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()
|
||||
@@ -1094,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),
|
||||
@@ -1126,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));
|
||||
@@ -1146,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);
|
||||
|
||||
+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() {
|
||||
|
||||
+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();
|
||||
}
|
||||
}
|
||||
}
|
||||
+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());
|
||||
}
|
||||
}
|
||||
+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;
|
||||
}
|
||||
}
|
||||
|
||||
-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");
|
||||
|
||||
+1
-1
@@ -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;
|
||||
|
||||
+1
@@ -320,6 +320,7 @@ 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 -> {
|
||||
|
||||
+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);
|
||||
}
|
||||
}
|
||||
|
||||
+40
-3
@@ -76,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;
|
||||
@@ -106,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;
|
||||
@@ -122,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) {
|
||||
@@ -132,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);
|
||||
@@ -262,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");
|
||||
};
|
||||
@@ -316,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");
|
||||
};
|
||||
}
|
||||
|
||||
@@ -401,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}")
|
||||
|
||||
+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) {
|
||||
|
||||
+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());
|
||||
}
|
||||
}
|
||||
+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
|
||||
|
||||
+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);
|
||||
|
||||
+3
-13
@@ -41,15 +41,9 @@ public class RateLimitByIpFilter implements ContainerRequestFilter {
|
||||
private static final String NO_IP_COUNTER_NAME = MetricsUtil.name(RateLimitByIpFilter.class, "noIpAddress");
|
||||
|
||||
private final RateLimiters rateLimiters;
|
||||
private final boolean softEnforcement;
|
||||
|
||||
public RateLimitByIpFilter(final RateLimiters rateLimiters, final boolean softEnforcement) {
|
||||
this.rateLimiters = requireNonNull(rateLimiters);
|
||||
this.softEnforcement = softEnforcement;
|
||||
}
|
||||
|
||||
public RateLimitByIpFilter(final RateLimiters rateLimiters) {
|
||||
this(rateLimiters, false);
|
||||
this.rateLimiters = requireNonNull(rateLimiters);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -87,9 +81,7 @@ public class RateLimitByIpFilter implements ContainerRequestFilter {
|
||||
// checking if annotation is configured to fail when the most recent IP is not resolved
|
||||
if (annotation.failOnUnresolvedIp()) {
|
||||
logger.error("Remote address was null");
|
||||
if (!softEnforcement) {
|
||||
throw INVALID_HEADER_EXCEPTION;
|
||||
}
|
||||
throw INVALID_HEADER_EXCEPTION;
|
||||
}
|
||||
// otherwise, allow request
|
||||
return;
|
||||
@@ -99,9 +91,7 @@ public class RateLimitByIpFilter implements ContainerRequestFilter {
|
||||
rateLimiter.validate(remoteAddress.get());
|
||||
} catch (RateLimitExceededException e) {
|
||||
final Response response = EXCEPTION_MAPPER.toResponse(e);
|
||||
if (!softEnforcement) {
|
||||
throw new ClientErrorException(response);
|
||||
}
|
||||
throw new ClientErrorException(response);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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> {
|
||||
@@ -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);
|
||||
|
||||
+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;
|
||||
}
|
||||
|
||||
|
||||
+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));
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
}
|
||||
@@ -50,8 +50,8 @@ import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.experiment.Experiment;
|
||||
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;
|
||||
@@ -119,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;
|
||||
@@ -183,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,
|
||||
@@ -205,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;
|
||||
|
||||
+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);
|
||||
}
|
||||
|
||||
+2
-2
@@ -12,7 +12,7 @@ import java.util.Collection;
|
||||
import java.util.List;
|
||||
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,7 +25,7 @@ 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);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
+4
@@ -52,6 +52,10 @@ 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 {
|
||||
|
||||
+43
-5
@@ -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)) {
|
||||
@@ -387,6 +390,41 @@ public class SubscriptionManager {
|
||||
.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.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 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 appleAppStoreManager
|
||||
.validateTransaction(originalTransactionId)
|
||||
.thenCompose(level -> subscriptions
|
||||
.setIapPurchase(record, pc, originalTransactionId, level, subscriberCredentials.now())
|
||||
.thenApply(ignore -> level));
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
private SubscriptionPaymentProcessor getProcessor(PaymentProvider provider) {
|
||||
return processors.get(provider);
|
||||
}
|
||||
|
||||
+319
@@ -0,0 +1,319 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
import com.apple.itunes.storekit.client.APIException;
|
||||
import com.apple.itunes.storekit.client.AppStoreServerAPIClient;
|
||||
import com.apple.itunes.storekit.model.AutoRenewStatus;
|
||||
import com.apple.itunes.storekit.model.Environment;
|
||||
import com.apple.itunes.storekit.model.JWSRenewalInfoDecodedPayload;
|
||||
import com.apple.itunes.storekit.model.JWSTransactionDecodedPayload;
|
||||
import com.apple.itunes.storekit.model.LastTransactionsItem;
|
||||
import com.apple.itunes.storekit.model.Status;
|
||||
import com.apple.itunes.storekit.model.StatusResponse;
|
||||
import com.apple.itunes.storekit.model.SubscriptionGroupIdentifierItem;
|
||||
import com.apple.itunes.storekit.verification.SignedDataVerifier;
|
||||
import com.apple.itunes.storekit.verification.VerificationException;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.github.resilience4j.retry.Retry;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.PaymentTime;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionException;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
|
||||
/**
|
||||
* Manages subscriptions made with the Apple App Store
|
||||
* <p>
|
||||
* Clients create a subscription using storekit directly, and then notify us about their subscription with their
|
||||
* subscription's <a
|
||||
* href="https://developer.apple.com/documentation/appstoreserverapi/originaltransactionid">originalTransactionId</a>.
|
||||
*/
|
||||
public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(AppleAppStoreManager.class);
|
||||
|
||||
private final AppStoreServerAPIClient apiClient;
|
||||
private final SignedDataVerifier signedDataVerifier;
|
||||
private final ExecutorService executor;
|
||||
private final ScheduledExecutorService retryExecutor;
|
||||
private final Map<String, Long> productIdToLevel;
|
||||
|
||||
private static final Status[] EMPTY_STATUSES = new Status[0];
|
||||
|
||||
private static final String GET_SUBSCRIPTION_ERROR_COUNTER_NAME =
|
||||
MetricsUtil.name(AppleAppStoreManager.class, "getSubscriptionsError");
|
||||
|
||||
private final String subscriptionGroupId;
|
||||
private final Retry retry;
|
||||
|
||||
|
||||
public AppleAppStoreManager(
|
||||
final Environment env,
|
||||
final String bundleId,
|
||||
final long appAppleId,
|
||||
final String issuerId,
|
||||
final String keyId,
|
||||
final String encodedKey,
|
||||
final String subscriptionGroupId,
|
||||
final Map<String, Long> productIdToLevel,
|
||||
final List<String> base64AppleRootCerts,
|
||||
final RetryConfiguration retryConfiguration,
|
||||
final ExecutorService executor,
|
||||
final ScheduledExecutorService retryExecutor) {
|
||||
this(new AppStoreServerAPIClient(encodedKey, keyId, issuerId, bundleId, env),
|
||||
new SignedDataVerifier(decodeRootCerts(base64AppleRootCerts), bundleId, appAppleId, env, true),
|
||||
subscriptionGroupId, productIdToLevel, retryConfiguration, executor, retryExecutor);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
AppleAppStoreManager(
|
||||
final AppStoreServerAPIClient apiClient,
|
||||
final SignedDataVerifier signedDataVerifier,
|
||||
final String subscriptionGroupId,
|
||||
final Map<String, Long> productIdToLevel,
|
||||
final RetryConfiguration retryConfiguration,
|
||||
final ExecutorService executor,
|
||||
final ScheduledExecutorService retryExecutor) {
|
||||
this.apiClient = apiClient;
|
||||
this.signedDataVerifier = signedDataVerifier;
|
||||
this.subscriptionGroupId = subscriptionGroupId;
|
||||
this.productIdToLevel = productIdToLevel;
|
||||
this.retry = Retry.of("appstore-retry", retryConfiguration
|
||||
.toRetryConfigBuilder()
|
||||
.retryOnException(AppleAppStoreManager::shouldRetry).build());
|
||||
this.executor = Objects.requireNonNull(executor);
|
||||
this.retryExecutor = Objects.requireNonNull(retryExecutor);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PaymentProvider getProvider() {
|
||||
return PaymentProvider.APPLE_APP_STORE;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Check if the subscription with the provided originalTransactionId is valid.
|
||||
*
|
||||
* @param originalTransactionId The originalTransactionId associated with the subscription
|
||||
* @return A stage that completes successfully when the transaction has been validated, or fails if the token does not
|
||||
* represent an active subscription.
|
||||
*/
|
||||
public CompletableFuture<Long> validateTransaction(final String originalTransactionId) {
|
||||
return lookup(originalTransactionId).thenApplyAsync(tx -> {
|
||||
if (!isSubscriptionActive(tx)) {
|
||||
throw ExceptionUtils.wrap(new SubscriptionException.PaymentRequired());
|
||||
}
|
||||
return getLevel(tx);
|
||||
}, executor);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Cancel the subscription
|
||||
* <p>
|
||||
* The App Store does not support backend cancellation, so this does not actually cancel, but it does verify that the
|
||||
* user has no active subscriptions. End-users must cancel their subscription directly through storekit before calling
|
||||
* this method.
|
||||
*
|
||||
* @param originalTransactionId The originalTransactionId associated with the subscription
|
||||
* @return A stage that completes when the subscription has successfully been cancelled
|
||||
*/
|
||||
@Override
|
||||
public CompletableFuture<Void> cancelAllActiveSubscriptions(String originalTransactionId) {
|
||||
return lookup(originalTransactionId).thenApplyAsync(tx -> {
|
||||
if (tx.signedTransaction.getStatus() != Status.EXPIRED &&
|
||||
tx.signedTransaction.getStatus() != Status.REVOKED &&
|
||||
tx.renewalInfo.getAutoRenewStatus() != AutoRenewStatus.OFF) {
|
||||
throw ExceptionUtils.wrap(
|
||||
new SubscriptionException.InvalidArguments("must cancel subscription with storekit before deleting"));
|
||||
}
|
||||
// The subscription will not auto-renew, so we can stop tracking it
|
||||
return null;
|
||||
}, executor);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<SubscriptionInformation> getSubscriptionInformation(final String originalTransactionId) {
|
||||
return lookup(originalTransactionId).thenApplyAsync(tx -> {
|
||||
|
||||
final SubscriptionStatus status = switch (tx.signedTransaction.getStatus()) {
|
||||
case ACTIVE -> SubscriptionStatus.ACTIVE;
|
||||
case BILLING_RETRY -> SubscriptionStatus.PAST_DUE;
|
||||
case BILLING_GRACE_PERIOD -> SubscriptionStatus.UNPAID;
|
||||
case EXPIRED, REVOKED -> SubscriptionStatus.CANCELED;
|
||||
};
|
||||
|
||||
return new SubscriptionInformation(
|
||||
getSubscriptionPrice(tx),
|
||||
getLevel(tx),
|
||||
Instant.ofEpochMilli(tx.transaction.getOriginalPurchaseDate()),
|
||||
Instant.ofEpochMilli(tx.transaction.getExpiresDate()),
|
||||
isSubscriptionActive(tx),
|
||||
tx.renewalInfo.getAutoRenewStatus() == AutoRenewStatus.OFF,
|
||||
status,
|
||||
PaymentProvider.APPLE_APP_STORE,
|
||||
PaymentMethod.APPLE_APP_STORE,
|
||||
false,
|
||||
null);
|
||||
}, executor);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public CompletableFuture<ReceiptItem> getReceiptItem(String originalTransactionId) {
|
||||
return lookup(originalTransactionId).thenApplyAsync(tx -> {
|
||||
if (!isSubscriptionActive(tx)) {
|
||||
throw ExceptionUtils.wrap(new SubscriptionException.PaymentRequired());
|
||||
}
|
||||
|
||||
// A new transactionId might be generated if you restore a subscription on a new device. webOrderLineItemId is
|
||||
// guaranteed not to change for a specific renewal purchase.
|
||||
// See: https://developer.apple.com/documentation/appstoreservernotifications/weborderlineitemid
|
||||
final String itemId = tx.transaction.getWebOrderLineItemId();
|
||||
final PaymentTime paymentTime = PaymentTime.periodEnds(Instant.ofEpochMilli(tx.transaction.getExpiresDate()));
|
||||
|
||||
return new ReceiptItem(itemId, paymentTime, getLevel(tx));
|
||||
|
||||
}, executor);
|
||||
}
|
||||
|
||||
private CompletableFuture<DecodedTransaction> lookup(final String originalTransactionId) {
|
||||
return getAllSubscriptions(originalTransactionId).thenApplyAsync(statuses -> {
|
||||
|
||||
final SubscriptionGroupIdentifierItem item = statuses.getData().stream()
|
||||
.filter(s -> subscriptionGroupId.equals(s.getSubscriptionGroupIdentifier())).findFirst()
|
||||
.orElseThrow(() -> ExceptionUtils.wrap(
|
||||
new SubscriptionException.InvalidArguments("transaction did not contain a backup subscription", null)));
|
||||
|
||||
final List<DecodedTransaction> txs = item.getLastTransactions().stream()
|
||||
.map(this::decode)
|
||||
.filter(decoded -> productIdToLevel.containsKey(decoded.transaction.getProductId()))
|
||||
.toList();
|
||||
|
||||
if (txs.isEmpty()) {
|
||||
throw ExceptionUtils.wrap(
|
||||
new SubscriptionException.InvalidArguments("transactionId did not include a paid subscription", null));
|
||||
}
|
||||
|
||||
if (txs.size() > 1) {
|
||||
logger.warn("Multiple matching product transactions found for transactionId {}, only considering first",
|
||||
originalTransactionId);
|
||||
}
|
||||
|
||||
if (!originalTransactionId.equals(txs.getFirst().signedTransaction.getOriginalTransactionId())) {
|
||||
// Get All Subscriptions only requires that the transaction be some transaction associated with the
|
||||
// subscription. This is too flexible, since we'd like to key on the originalTransactionId in the
|
||||
// SubscriptionManager.
|
||||
throw ExceptionUtils.wrap(
|
||||
new SubscriptionException.InvalidArguments(
|
||||
"transactionId was not the transaction's originalTransactionId", null));
|
||||
}
|
||||
|
||||
return txs.getFirst();
|
||||
}, executor).toCompletableFuture();
|
||||
}
|
||||
|
||||
private CompletionStage<StatusResponse> getAllSubscriptions(final String originalTransactionId) {
|
||||
Supplier<CompletionStage<StatusResponse>> supplier = () -> CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
return apiClient.getAllSubscriptionStatuses(originalTransactionId, EMPTY_STATUSES);
|
||||
} catch (final APIException e) {
|
||||
Metrics.counter(GET_SUBSCRIPTION_ERROR_COUNTER_NAME, "reason", e.getApiError().name()).increment();
|
||||
throw ExceptionUtils.wrap(switch (e.getApiError()) {
|
||||
case ORIGINAL_TRANSACTION_ID_NOT_FOUND, TRANSACTION_ID_NOT_FOUND -> new SubscriptionException.NotFound();
|
||||
case RATE_LIMIT_EXCEEDED -> new RateLimitExceededException(null);
|
||||
case INVALID_ORIGINAL_TRANSACTION_ID -> new SubscriptionException.InvalidArguments(e.getApiErrorMessage());
|
||||
default -> e;
|
||||
});
|
||||
} catch (final IOException e) {
|
||||
Metrics.counter(GET_SUBSCRIPTION_ERROR_COUNTER_NAME, "reason", "io_error").increment();
|
||||
throw ExceptionUtils.wrap(e);
|
||||
}
|
||||
}, executor);
|
||||
return retry.executeCompletionStage(retryExecutor, supplier);
|
||||
}
|
||||
|
||||
private static boolean shouldRetry(Throwable e) {
|
||||
return ExceptionUtils.unwrap(e) instanceof APIException apiException && switch (apiException.getApiError()) {
|
||||
case ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE, GENERAL_INTERNAL_RETRYABLE, APP_NOT_FOUND_RETRYABLE -> true;
|
||||
default -> false;
|
||||
};
|
||||
}
|
||||
|
||||
private record DecodedTransaction(
|
||||
LastTransactionsItem signedTransaction,
|
||||
JWSTransactionDecodedPayload transaction,
|
||||
JWSRenewalInfoDecodedPayload renewalInfo) {}
|
||||
|
||||
/**
|
||||
* Verify signature and decode transaction payloads
|
||||
*/
|
||||
private DecodedTransaction decode(final LastTransactionsItem tx) {
|
||||
try {
|
||||
return new DecodedTransaction(
|
||||
tx,
|
||||
signedDataVerifier.verifyAndDecodeTransaction(tx.getSignedTransactionInfo()),
|
||||
signedDataVerifier.verifyAndDecodeRenewalInfo(tx.getSignedRenewalInfo()));
|
||||
} catch (VerificationException e) {
|
||||
throw ExceptionUtils.wrap(new IOException("Failed to verify payload from App Store Server", e));
|
||||
}
|
||||
}
|
||||
|
||||
private SubscriptionPrice getSubscriptionPrice(final DecodedTransaction tx) {
|
||||
final BigDecimal amount = new BigDecimal(tx.transaction.getPrice()).scaleByPowerOfTen(-3);
|
||||
return new SubscriptionPrice(
|
||||
tx.transaction.getCurrency().toUpperCase(Locale.ROOT),
|
||||
SubscriptionCurrencyUtil.convertConfiguredAmountToApiAmount(tx.transaction.getCurrency(), amount));
|
||||
}
|
||||
|
||||
private long getLevel(final DecodedTransaction tx) {
|
||||
final Long level = productIdToLevel.get(tx.transaction.getProductId());
|
||||
if (level == null) {
|
||||
throw ExceptionUtils.wrap(
|
||||
new SubscriptionException.InvalidArguments(
|
||||
"Transaction for unknown productId " + tx.transaction.getProductId()));
|
||||
}
|
||||
return level;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if the subscription's entitlement can currently be granted
|
||||
*/
|
||||
private boolean isSubscriptionActive(final DecodedTransaction tx) {
|
||||
return tx.signedTransaction.getStatus() == Status.ACTIVE
|
||||
|| tx.signedTransaction.getStatus() == Status.BILLING_GRACE_PERIOD;
|
||||
}
|
||||
|
||||
private static Set<InputStream> decodeRootCerts(final List<String> rootCerts) {
|
||||
return rootCerts.stream()
|
||||
.map(Base64.getDecoder()::decode)
|
||||
.map(ByteArrayInputStream::new)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
}
|
||||
-1
@@ -412,7 +412,6 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// https://developers.google.com/android-publisher/api-ref/rest/v3/purchases.subscriptionsv2#SubscriptionState
|
||||
@VisibleForTesting
|
||||
enum SubscriptionState {
|
||||
|
||||
+2
-1
@@ -23,5 +23,6 @@ public enum PaymentMethod {
|
||||
* An iDEAL account
|
||||
*/
|
||||
IDEAL,
|
||||
GOOGLE_PLAY_BILLING
|
||||
GOOGLE_PLAY_BILLING,
|
||||
APPLE_APP_STORE
|
||||
}
|
||||
+1
-1
@@ -18,7 +18,7 @@ public enum PaymentProvider {
|
||||
STRIPE(1),
|
||||
BRAINTREE(2),
|
||||
GOOGLE_PLAY_BILLING(3),
|
||||
;
|
||||
APPLE_APP_STORE(4);
|
||||
|
||||
private static final Map<Integer, PaymentProvider> IDS_TO_PROCESSORS = new HashMap<>();
|
||||
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.EnumMap;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class EnumMapUtil {
|
||||
|
||||
private EnumMapUtil() {}
|
||||
|
||||
public static <E extends Enum<E>, V> EnumMap<E, V> toEnumMap(final Class<E> enumClass, final Function<E, V> valueMapper) {
|
||||
return Arrays.stream(enumClass.getEnumConstants())
|
||||
.collect(Collectors.toMap(Function.identity(), valueMapper, (a, b) -> {
|
||||
throw new AssertionError("Duplicate enumeration key");
|
||||
},
|
||||
() -> new EnumMap<>(enumClass)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
public record LinkDeviceToken(
|
||||
@Schema(description = """
|
||||
An opaque token to send to a new linked device that authorizes the new device to link itself to the account that
|
||||
requested this token.
|
||||
""")
|
||||
@JsonProperty("verificationCode") String token,
|
||||
|
||||
@Schema(description = """
|
||||
An opaque identifier for the generated token that the caller may use to watch for a new device to complete the
|
||||
linking process.
|
||||
""")
|
||||
String tokenIdentifier) {
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
public record VerificationCode(String verificationCode) {
|
||||
}
|
||||
+14
-105
@@ -7,22 +7,17 @@ package org.whispersystems.textsecuregcm.websocket;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.util.EnumMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor;
|
||||
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.OpenWebSocketCounter;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
@@ -30,19 +25,15 @@ import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisOperation;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
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 org.whispersystems.websocket.setup.WebSocketConnectListener;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
|
||||
public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
|
||||
private static final String OPEN_WEBSOCKET_COUNTER_NAME =
|
||||
name(WebSocketConnection.class, "openWebsockets");
|
||||
private static final String CONNECTED_DURATION_TIMER_NAME = name(AuthenticatedConnectListener.class,
|
||||
"connectedDuration");
|
||||
private static final String OPEN_WEBSOCKET_GAUGE_NAME = name(WebSocketConnection.class, "openWebsockets");
|
||||
private static final String CONNECTED_DURATION_TIMER_NAME =
|
||||
name(AuthenticatedConnectListener.class, "connectedDuration");
|
||||
|
||||
private static final String AUTHENTICATED_TAG_NAME = "authenticated";
|
||||
|
||||
@@ -61,15 +52,8 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
private final ClientReleaseManager clientReleaseManager;
|
||||
private final MessageDeliveryLoopMonitor messageDeliveryLoopMonitor;
|
||||
|
||||
private final Map<ClientPlatform, AtomicInteger> openAuthenticatedWebsocketsByClientPlatform;
|
||||
private final Map<ClientPlatform, AtomicInteger> openUnauthenticatedWebsocketsByClientPlatform;
|
||||
private final Map<ClientPlatform, Timer> durationTimersByClientPlatform;
|
||||
private final Map<ClientPlatform, Timer> unauthenticatedDurationTimersByClientPlatform;
|
||||
|
||||
private final AtomicInteger openAuthenticatedWebsocketsFromUnknownPlatforms;
|
||||
private final AtomicInteger openUnauthenticatedWebsocketsFromUnknownPlatforms;
|
||||
private final Timer durationTimerForUnknownPlatforms;
|
||||
private final Timer unauthenticatedDurationTimerForUnknownPlatforms;
|
||||
private final OpenWebSocketCounter openAuthenticatedWebSocketCounter;
|
||||
private final OpenWebSocketCounter openUnauthenticatedWebSocketCounter;
|
||||
|
||||
public AuthenticatedConnectListener(ReceiptSender receiptSender,
|
||||
MessagesManager messagesManager,
|
||||
@@ -92,60 +76,24 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
this.clientReleaseManager = clientReleaseManager;
|
||||
this.messageDeliveryLoopMonitor = messageDeliveryLoopMonitor;
|
||||
|
||||
openAuthenticatedWebsocketsByClientPlatform = new EnumMap<>(ClientPlatform.class);
|
||||
openUnauthenticatedWebsocketsByClientPlatform = new EnumMap<>(ClientPlatform.class);
|
||||
durationTimersByClientPlatform = new EnumMap<>(ClientPlatform.class);
|
||||
unauthenticatedDurationTimersByClientPlatform = new EnumMap<>(ClientPlatform.class);
|
||||
openAuthenticatedWebSocketCounter =
|
||||
new OpenWebSocketCounter(OPEN_WEBSOCKET_GAUGE_NAME, CONNECTED_DURATION_TIMER_NAME, Tags.of(AUTHENTICATED_TAG_NAME, "true"));
|
||||
|
||||
final Tags authenticatedTag = Tags.of(AUTHENTICATED_TAG_NAME, "true");
|
||||
final Tags unauthenticatedTag = Tags.of(AUTHENTICATED_TAG_NAME, "false");
|
||||
|
||||
for (final ClientPlatform clientPlatform : ClientPlatform.values()) {
|
||||
openAuthenticatedWebsocketsByClientPlatform.put(clientPlatform, new AtomicInteger(0));
|
||||
openUnauthenticatedWebsocketsByClientPlatform.put(clientPlatform, new AtomicInteger(0));
|
||||
|
||||
final Tags clientPlatformTag = Tags.of(UserAgentTagUtil.PLATFORM_TAG, clientPlatform.name().toLowerCase());
|
||||
Metrics.gauge(OPEN_WEBSOCKET_COUNTER_NAME, clientPlatformTag.and(authenticatedTag),
|
||||
openAuthenticatedWebsocketsByClientPlatform.get(clientPlatform));
|
||||
|
||||
Metrics.gauge(OPEN_WEBSOCKET_COUNTER_NAME, clientPlatformTag.and(unauthenticatedTag),
|
||||
openUnauthenticatedWebsocketsByClientPlatform.get(clientPlatform));
|
||||
|
||||
durationTimersByClientPlatform.put(clientPlatform,
|
||||
Metrics.timer(CONNECTED_DURATION_TIMER_NAME, clientPlatformTag.and(authenticatedTag)));
|
||||
|
||||
unauthenticatedDurationTimersByClientPlatform.put(clientPlatform,
|
||||
Metrics.timer(CONNECTED_DURATION_TIMER_NAME, clientPlatformTag.and(unauthenticatedTag)));
|
||||
}
|
||||
|
||||
openAuthenticatedWebsocketsFromUnknownPlatforms = new AtomicInteger(0);
|
||||
openUnauthenticatedWebsocketsFromUnknownPlatforms = new AtomicInteger(0);
|
||||
|
||||
final Tags unrecognizedPlatform = Tags.of(UserAgentTagUtil.PLATFORM_TAG, "unrecognized");
|
||||
Metrics.gauge(OPEN_WEBSOCKET_COUNTER_NAME, unrecognizedPlatform.and(authenticatedTag),
|
||||
openAuthenticatedWebsocketsFromUnknownPlatforms);
|
||||
|
||||
Metrics.gauge(OPEN_WEBSOCKET_COUNTER_NAME, unrecognizedPlatform.and(unauthenticatedTag),
|
||||
openUnauthenticatedWebsocketsFromUnknownPlatforms);
|
||||
|
||||
durationTimerForUnknownPlatforms = Metrics.timer(CONNECTED_DURATION_TIMER_NAME,
|
||||
unrecognizedPlatform.and(authenticatedTag));
|
||||
|
||||
unauthenticatedDurationTimerForUnknownPlatforms = Metrics.timer(CONNECTED_DURATION_TIMER_NAME,
|
||||
unrecognizedPlatform.and(unauthenticatedTag));
|
||||
openUnauthenticatedWebSocketCounter =
|
||||
new OpenWebSocketCounter(OPEN_WEBSOCKET_GAUGE_NAME, CONNECTED_DURATION_TIMER_NAME, Tags.of(AUTHENTICATED_TAG_NAME, "false"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onWebSocketConnect(WebSocketSessionContext context) {
|
||||
|
||||
final boolean authenticated = (context.getAuthenticated() != null);
|
||||
final String userAgent = context.getClient().getUserAgent();
|
||||
final AtomicInteger openWebsocketAtomicInteger = getOpenWebsocketCounter(userAgent, authenticated);
|
||||
final Timer connectionTimer = getConnectionTimer(userAgent, authenticated);
|
||||
final OpenWebSocketCounter openWebSocketCounter =
|
||||
authenticated ? openAuthenticatedWebSocketCounter : openUnauthenticatedWebSocketCounter;
|
||||
|
||||
openWebSocketCounter.countOpenWebSocket(context);
|
||||
|
||||
if (authenticated) {
|
||||
final AuthenticatedDevice auth = context.getAuthenticated(AuthenticatedDevice.class);
|
||||
final Timer.Sample sample = Timer.start();
|
||||
final WebSocketConnection connection = new WebSocketConnection(receiptSender,
|
||||
messagesManager,
|
||||
messageMetrics,
|
||||
@@ -158,14 +106,9 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
clientReleaseManager,
|
||||
messageDeliveryLoopMonitor);
|
||||
|
||||
openWebsocketAtomicInteger.incrementAndGet();
|
||||
|
||||
final AtomicReference<ScheduledFuture<?>> renewPresenceFutureReference = new AtomicReference<>();
|
||||
|
||||
context.addWebsocketClosedListener((closingContext, statusCode, reason) -> {
|
||||
openWebsocketAtomicInteger.decrementAndGet();
|
||||
sample.stop(connectionTimer);
|
||||
|
||||
final ScheduledFuture<?> renewPresenceFuture = renewPresenceFutureReference.get();
|
||||
|
||||
if (renewPresenceFuture != null) {
|
||||
@@ -214,40 +157,6 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
log.warn("Failed to initialize websocket", e);
|
||||
context.getClient().close(1011, "Unexpected error initializing connection");
|
||||
}
|
||||
} else {
|
||||
openWebsocketAtomicInteger.incrementAndGet();
|
||||
final Timer.Sample sample = Timer.start();
|
||||
context.addWebsocketClosedListener((context1, statusCode, reason) -> {
|
||||
openWebsocketAtomicInteger.decrementAndGet();
|
||||
sample.stop(connectionTimer);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private AtomicInteger getOpenWebsocketCounter(final String userAgentString, final boolean authenticated) {
|
||||
try {
|
||||
final ClientPlatform platform = UserAgentUtil.parseUserAgentString(userAgentString).getPlatform();
|
||||
return authenticated
|
||||
? openAuthenticatedWebsocketsByClientPlatform.get(platform)
|
||||
: openUnauthenticatedWebsocketsByClientPlatform.get(platform);
|
||||
} catch (final UnrecognizedUserAgentException e) {
|
||||
return authenticated
|
||||
? openAuthenticatedWebsocketsFromUnknownPlatforms
|
||||
: openUnauthenticatedWebsocketsFromUnknownPlatforms;
|
||||
}
|
||||
}
|
||||
|
||||
private Timer getConnectionTimer(final String userAgentString,
|
||||
final boolean authenticated) {
|
||||
try {
|
||||
final ClientPlatform platform = UserAgentUtil.parseUserAgentString(userAgentString).getPlatform();
|
||||
return authenticated
|
||||
? durationTimersByClientPlatform.get(platform)
|
||||
: unauthenticatedDurationTimersByClientPlatform.get(platform);
|
||||
} catch (final UnrecognizedUserAgentException e) {
|
||||
return authenticated
|
||||
? durationTimerForUnknownPlatforms
|
||||
: unauthenticatedDurationTimerForUnknownPlatforms;
|
||||
}
|
||||
}
|
||||
}
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.websocket;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
|
||||
public class ProvisioningAddress extends WebsocketAddress {
|
||||
|
||||
public static byte DEVICE_ID = 0;
|
||||
|
||||
public static ProvisioningAddress create(String address) {
|
||||
return new ProvisioningAddress(address, DEVICE_ID);
|
||||
}
|
||||
|
||||
private ProvisioningAddress(String address, byte deviceId) {
|
||||
super(address, deviceId);
|
||||
}
|
||||
|
||||
public ProvisioningAddress(String serialized) throws InvalidWebsocketAddressException {
|
||||
super(serialized);
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return getNumber();
|
||||
}
|
||||
|
||||
public static ProvisioningAddress generate() {
|
||||
byte[] random = new byte[16];
|
||||
new SecureRandom().nextBytes(random);
|
||||
|
||||
return create(Base64.getUrlEncoder().withoutPadding().encodeToString(random));
|
||||
}
|
||||
}
|
||||
+40
-7
@@ -5,26 +5,52 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.websocket;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.entities.ProvisioningMessage;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.OpenWebSocketCounter;
|
||||
import org.whispersystems.textsecuregcm.push.ProvisioningManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PubSubProtos;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.websocket.session.WebSocketSessionContext;
|
||||
import org.whispersystems.websocket.setup.WebSocketConnectListener;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* A "provisioning WebSocket" provides a mechanism for sending a caller-defined provisioning message from the primary
|
||||
* device associated with a Signal account to a new device that is not yet associated with a Signal account. Generally,
|
||||
* the message contains key material and credentials the new device needs to associate itself with the primary device's
|
||||
* Signal account.
|
||||
* <p>
|
||||
* New devices initiate the provisioning process by opening a provisioning WebSocket. The server assigns the new device
|
||||
* a random, temporary "provisioning address," which it transmits via the newly-opened WebSocket. From there, the new
|
||||
* device generally displays the provisioning address (and a public key) as a QR code. After that, the primary device
|
||||
* will scan the QR code and send an encrypted provisioning message to the new device via
|
||||
* {@link org.whispersystems.textsecuregcm.controllers.ProvisioningController#sendProvisioningMessage(AuthenticatedDevice, String, ProvisioningMessage, String)}.
|
||||
* Once the server receives the message from the primary device, it sends the message to the new device via the open
|
||||
* WebSocket, then closes the WebSocket connection.
|
||||
*/
|
||||
public class ProvisioningConnectListener implements WebSocketConnectListener {
|
||||
|
||||
private final ProvisioningManager provisioningManager;
|
||||
private final OpenWebSocketCounter openWebSocketCounter;
|
||||
|
||||
public ProvisioningConnectListener(final ProvisioningManager provisioningManager) {
|
||||
this.provisioningManager = provisioningManager;
|
||||
this.openWebSocketCounter = new OpenWebSocketCounter(MetricsUtil.name(getClass(), "openWebsockets"),
|
||||
MetricsUtil.name(getClass(), "sessionDuration"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onWebSocketConnect(WebSocketSessionContext context) {
|
||||
final ProvisioningAddress provisioningAddress = ProvisioningAddress.generate();
|
||||
openWebSocketCounter.countOpenWebSocket(context);
|
||||
|
||||
final String provisioningAddress = generateProvisioningAddress();
|
||||
context.addWebsocketClosedListener((context1, statusCode, reason) -> provisioningManager.removeListener(provisioningAddress));
|
||||
|
||||
provisioningManager.addListener(provisioningAddress, message -> {
|
||||
@@ -37,9 +63,16 @@ public class ProvisioningConnectListener implements WebSocketConnectListener {
|
||||
});
|
||||
|
||||
context.getClient().sendRequest("PUT", "/v1/address", List.of(HeaderUtils.getTimestampHeader()),
|
||||
Optional.of(MessageProtos.ProvisioningUuid.newBuilder()
|
||||
.setUuid(provisioningAddress.getAddress())
|
||||
.build()
|
||||
.toByteArray()));
|
||||
Optional.of(MessageProtos.ProvisioningAddress.newBuilder()
|
||||
.setAddress(provisioningAddress)
|
||||
.build().toByteArray()));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public static String generateProvisioningAddress() {
|
||||
final byte[] provisioningAddress = new byte[16];
|
||||
new SecureRandom().nextBytes(provisioningAddress);
|
||||
|
||||
return Base64.getUrlEncoder().encodeToString(provisioningAddress);
|
||||
}
|
||||
}
|
||||
-68
@@ -1,68 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.websocket;
|
||||
|
||||
import org.whispersystems.textsecuregcm.storage.PubSubAddress;
|
||||
|
||||
public class WebsocketAddress implements PubSubAddress {
|
||||
|
||||
private final String number;
|
||||
private final byte deviceId;
|
||||
|
||||
public WebsocketAddress(String number, byte deviceId) {
|
||||
this.number = number;
|
||||
this.deviceId = deviceId;
|
||||
}
|
||||
|
||||
public WebsocketAddress(String serialized) throws InvalidWebsocketAddressException {
|
||||
try {
|
||||
String[] parts = serialized.split(":", 2);
|
||||
|
||||
if (parts.length != 2) {
|
||||
throw new InvalidWebsocketAddressException("Bad address: " + serialized);
|
||||
}
|
||||
|
||||
this.number = parts[0];
|
||||
this.deviceId = Byte.parseByte(parts[1]);
|
||||
} catch (NumberFormatException e) {
|
||||
throw new InvalidWebsocketAddressException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public String getNumber() {
|
||||
return number;
|
||||
}
|
||||
|
||||
public byte getDeviceId() {
|
||||
return deviceId;
|
||||
}
|
||||
|
||||
public String serialize() {
|
||||
return number + ":" + deviceId;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return serialize();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
if (other == null) return false;
|
||||
if (!(other instanceof WebsocketAddress)) return false;
|
||||
|
||||
WebsocketAddress that = (WebsocketAddress)other;
|
||||
|
||||
return
|
||||
this.number.equals(that.number) &&
|
||||
this.deviceId == that.deviceId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return number.hashCode() ^ (int)deviceId;
|
||||
}
|
||||
|
||||
}
|
||||
+15
-12
@@ -34,13 +34,13 @@ import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery2Controll
|
||||
import org.whispersystems.textsecuregcm.experiment.PushNotificationExperimentSamples;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.MicrometerAwsSdkMetricPublisher;
|
||||
import org.whispersystems.textsecuregcm.metrics.NoopAwsSdkMetricPublisher;
|
||||
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.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountLockManager;
|
||||
@@ -82,8 +82,8 @@ record CommandDependencies(
|
||||
FcmSender fcmSender,
|
||||
PushNotificationManager pushNotificationManager,
|
||||
PushNotificationExperimentSamples pushNotificationExperimentSamples,
|
||||
FaultTolerantRedisCluster cacheCluster,
|
||||
FaultTolerantRedisCluster pushSchedulerCluster,
|
||||
FaultTolerantRedisClusterClient cacheCluster,
|
||||
FaultTolerantRedisClusterClient pushSchedulerCluster,
|
||||
ClientResources.Builder redisClusterClientResourcesBuilder,
|
||||
BackupManager backupManager,
|
||||
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
@@ -109,10 +109,12 @@ record CommandDependencies(
|
||||
|
||||
final ClientResources.Builder redisClientResourcesBuilder = ClientResources.builder();
|
||||
|
||||
FaultTolerantRedisCluster cacheCluster = configuration.getCacheClusterConfiguration()
|
||||
FaultTolerantRedisClusterClient cacheCluster = configuration.getCacheClusterConfiguration()
|
||||
.build("main_cache", redisClientResourcesBuilder);
|
||||
FaultTolerantRedisCluster pushSchedulerCluster = configuration.getPushSchedulerCluster()
|
||||
FaultTolerantRedisClusterClient pushSchedulerCluster = configuration.getPushSchedulerCluster()
|
||||
.build("push_scheduler", redisClientResourcesBuilder);
|
||||
FaultTolerantRedisClient pubsubClient =
|
||||
configuration.getRedisPubSubConfiguration().build("pubsub", redisClientResourcesBuilder.build());
|
||||
|
||||
ScheduledExecutorService recurringJobExecutor = environment.lifecycle()
|
||||
.scheduledExecutorService(name(name, "recurringJob-%d")).threads(2).build();
|
||||
@@ -180,7 +182,8 @@ record CommandDependencies(
|
||||
configuration.getDynamoDbTables().getAccounts().getPhoneNumberTableName(),
|
||||
configuration.getDynamoDbTables().getAccounts().getPhoneNumberIdentifierTableName(),
|
||||
configuration.getDynamoDbTables().getAccounts().getUsernamesTableName(),
|
||||
configuration.getDynamoDbTables().getDeletedAccounts().getTableName());
|
||||
configuration.getDynamoDbTables().getDeletedAccounts().getTableName(),
|
||||
configuration.getDynamoDbTables().getAccounts().getUsedLinkDeviceTokensTableName());
|
||||
PhoneNumberIdentifiers phoneNumberIdentifiers = new PhoneNumberIdentifiers(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getPhoneNumberIdentifiers().getTableName());
|
||||
Profiles profiles = new Profiles(dynamoDbClient, dynamoDbAsyncClient,
|
||||
@@ -196,11 +199,11 @@ record CommandDependencies(
|
||||
configuration.getDynamoDbTables().getMessages().getTableName(),
|
||||
configuration.getDynamoDbTables().getMessages().getExpiration(),
|
||||
messageDeletionExecutor);
|
||||
FaultTolerantRedisCluster messagesCluster = configuration.getMessageCacheConfiguration()
|
||||
FaultTolerantRedisClusterClient messagesCluster = configuration.getMessageCacheConfiguration()
|
||||
.getRedisClusterConfiguration().build("messages", redisClientResourcesBuilder);
|
||||
FaultTolerantRedisCluster clientPresenceCluster = configuration.getClientPresenceClusterConfiguration()
|
||||
FaultTolerantRedisClusterClient clientPresenceCluster = configuration.getClientPresenceClusterConfiguration()
|
||||
.build("client_presence", redisClientResourcesBuilder);
|
||||
FaultTolerantRedisCluster rateLimitersCluster = configuration.getRateLimitersCluster().build("rate_limiters",
|
||||
FaultTolerantRedisClusterClient rateLimitersCluster = configuration.getRateLimitersCluster().build("rate_limiters",
|
||||
redisClientResourcesBuilder);
|
||||
SecureValueRecovery2Client secureValueRecovery2Client = new SecureValueRecovery2Client(
|
||||
secureValueRecoveryCredentialsGenerator, secureValueRecoveryServiceExecutor,
|
||||
@@ -225,10 +228,10 @@ record CommandDependencies(
|
||||
ClientPublicKeysManager clientPublicKeysManager =
|
||||
new ClientPublicKeysManager(clientPublicKeys, accountLockManager, accountLockExecutor);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
accountLockManager, keys, messagesManager, profilesManager,
|
||||
pubsubClient, accountLockManager, keys, messagesManager, profilesManager,
|
||||
secureStorageClient, secureValueRecovery2Client, clientPresenceManager,
|
||||
registrationRecoveryPasswordsManager, clientPublicKeysManager, accountLockExecutor, clientPresenceExecutor,
|
||||
clock, dynamicConfigurationManager);
|
||||
clock, configuration.getLinkDeviceSecretConfiguration().secret().value(), dynamicConfigurationManager);
|
||||
RateLimiters rateLimiters = RateLimiters.createAndValidate(configuration.getLimitsConfiguration(),
|
||||
dynamicConfigurationManager, rateLimitersCluster);
|
||||
final BackupsDb backupsDb =
|
||||
|
||||
+1
-2
@@ -182,7 +182,6 @@ public class NotifyIdleDevicesCommand extends AbstractSinglePassCrawlAccountsCom
|
||||
|
||||
@VisibleForTesting
|
||||
static boolean hasPushToken(final Device device) {
|
||||
// Exclude VOIP tokens since they have their own, distinct delivery mechanism
|
||||
return !StringUtils.isAllBlank(device.getApnId(), device.getGcmId()) && StringUtils.isBlank(device.getVoipApnId());
|
||||
return !StringUtils.isAllBlank(device.getApnId(), device.getGcmId());
|
||||
}
|
||||
}
|
||||
@@ -6,17 +6,23 @@
|
||||
syntax = "proto3";
|
||||
|
||||
option java_multiple_files = true;
|
||||
option java_package = "org.signal.keytransparency.client";
|
||||
|
||||
package katie;
|
||||
package kt_query;
|
||||
|
||||
service Katie {
|
||||
/**
|
||||
* An external-facing, read-only key transparency service used by Signal's chat server
|
||||
* to look up and monitor search keys.
|
||||
*/
|
||||
service KeyTransparencyQueryService {
|
||||
/**
|
||||
* Provides proof that a specific version of the search key exists in the log tree.
|
||||
* An endpoint used by clients to search for a given key in the transparency log.
|
||||
* The server returns proof that the search key exists in the log.
|
||||
*/
|
||||
rpc Search(SearchRequest) returns (SearchResponse) {}
|
||||
/**
|
||||
* Allows users to monitor a set of search keys by providing proof that the log tree continues to be
|
||||
* constructed correctly in later entries for those search keys.
|
||||
* An endpoint that allows users to monitor a set of search keys by returning proof that the log continues to be
|
||||
* constructed correctly in later entries for those search keys.
|
||||
*/
|
||||
rpc Monitor(MonitorRequest) returns (MonitorResponse) {}
|
||||
}
|
||||
@@ -37,7 +43,7 @@ message ConsistencyParameters {
|
||||
/**
|
||||
* The distinguished tree head size to prove consistency against.
|
||||
* This field may be omitted when the client is looking up the
|
||||
* "distinguished" key for the very first time.
|
||||
* "distinguished" key for the very first time.
|
||||
*/
|
||||
optional uint64 distinguished = 2;
|
||||
}
|
||||
@@ -211,6 +217,11 @@ message MonitorKey {
|
||||
* in the corresponding MonitorProof.
|
||||
*/
|
||||
repeated uint64 entries = 2;
|
||||
/**
|
||||
* The commitment index for the search key. This is derived from vrf_proof in
|
||||
* the SearchResponse.
|
||||
*/
|
||||
bytes commitment_index = 3;
|
||||
}
|
||||
|
||||
|
||||
@@ -263,4 +274,3 @@ message MonitorResponse {
|
||||
*/
|
||||
repeated bytes inclusion = 4;
|
||||
}
|
||||
|
||||
@@ -38,8 +38,8 @@ message Envelope {
|
||||
// next: 19
|
||||
}
|
||||
|
||||
message ProvisioningUuid {
|
||||
optional string uuid = 1;
|
||||
message ProvisioningAddress {
|
||||
optional string address = 1;
|
||||
}
|
||||
|
||||
message ServerCertificate {
|
||||
|
||||
@@ -107,13 +107,6 @@ message SetPushTokenRequest {
|
||||
* A "standard" APNs device token.
|
||||
*/
|
||||
string apns_token = 1;
|
||||
|
||||
/**
|
||||
* A VoIP APNs device token. If present, the server will prefer to send
|
||||
* message notifications to the device using this token on a VOIP APNs
|
||||
* topic.
|
||||
*/
|
||||
string apns_voip_token = 2;
|
||||
}
|
||||
|
||||
message FcmTokenRequest {
|
||||
@@ -147,9 +140,8 @@ message ClearPushTokenResponse {}
|
||||
message SetCapabilitiesRequest {
|
||||
bool storage = 1;
|
||||
bool transfer = 2;
|
||||
bool paymentActivation = 3;
|
||||
bool deleteSync = 4;
|
||||
bool versionedExpirationTimer = 5;
|
||||
bool deleteSync = 3;
|
||||
bool versionedExpirationTimer = 4;
|
||||
}
|
||||
|
||||
message SetCapabilitiesResponse {}
|
||||
@@ -318,18 +318,14 @@ message ProfileAvatarUploadAttributes {
|
||||
}
|
||||
|
||||
message UserCapabilities {
|
||||
/**
|
||||
* Whether all devices linked to the account support MobileCoin payments.
|
||||
*/
|
||||
bool payment_activation = 1;
|
||||
/**
|
||||
* Whether all devices linked to the account support delete syncing
|
||||
*/
|
||||
bool delete_sync = 2;
|
||||
bool delete_sync = 1;
|
||||
/**
|
||||
* Whether all devices linked to the account support a versioned expiration timer
|
||||
*/
|
||||
bool versioned_expiration_timer = 3;
|
||||
bool versioned_expiration_timer = 2;
|
||||
}
|
||||
|
||||
message Badge {
|
||||
|
||||
@@ -4,8 +4,8 @@ org.whispersystems.textsecuregcm.configuration.DynamicConfigurationManagerFactor
|
||||
org.whispersystems.textsecuregcm.configuration.DynamoDbClientFactory
|
||||
org.whispersystems.textsecuregcm.configuration.HCaptchaClientFactory
|
||||
org.whispersystems.textsecuregcm.configuration.FaultTolerantRedisClusterFactory
|
||||
org.whispersystems.textsecuregcm.configuration.FaultTolerantRedisClientFactory
|
||||
org.whispersystems.textsecuregcm.configuration.PaymentsServiceClientsFactory
|
||||
org.whispersystems.textsecuregcm.configuration.PubSubPublisherFactory
|
||||
org.whispersystems.textsecuregcm.configuration.RegistrationServiceClientFactory
|
||||
org.whispersystems.textsecuregcm.configuration.S3ObjectMonitorFactory
|
||||
org.whispersystems.textsecuregcm.configuration.SingletonRedisClientFactory
|
||||
@@ -1,70 +0,0 @@
|
||||
local pendingNotificationQueue = KEYS[1]
|
||||
|
||||
local maxTime = ARGV[1]
|
||||
local limit = ARGV[2]
|
||||
|
||||
local hgetall = function (key)
|
||||
local bulk = redis.call('HGETALL', key)
|
||||
local result = {}
|
||||
local nextkey
|
||||
for i, v in ipairs(bulk) do
|
||||
if i % 2 == 1 then
|
||||
nextkey = v
|
||||
else
|
||||
result[nextkey] = v
|
||||
end
|
||||
end
|
||||
return result
|
||||
end
|
||||
|
||||
local getNextInterval = function(interval)
|
||||
if interval < 20000 then
|
||||
return 20000
|
||||
end
|
||||
|
||||
if interval < 40000 then
|
||||
return 40000
|
||||
end
|
||||
|
||||
if interval < 80000 then
|
||||
return 80000
|
||||
end
|
||||
|
||||
if interval < 160000 then
|
||||
return 160000
|
||||
end
|
||||
|
||||
if interval < 600000 then
|
||||
return 600000
|
||||
end
|
||||
|
||||
if interval < 1800000 then
|
||||
return 1800000
|
||||
end
|
||||
|
||||
return 3600000
|
||||
end
|
||||
|
||||
|
||||
local results = redis.call("ZRANGE", pendingNotificationQueue, 0, maxTime, "BYSCORE", "LIMIT", 0, limit)
|
||||
local collated = {}
|
||||
|
||||
if results and next(results) then
|
||||
for i, name in ipairs(results) do
|
||||
local pending = hgetall(name)
|
||||
local lastInterval = pending["interval"]
|
||||
|
||||
if lastInterval == nil then
|
||||
lastInterval = 0
|
||||
end
|
||||
|
||||
local nextInterval = getNextInterval(tonumber(lastInterval))
|
||||
|
||||
redis.call("HSET", name, "interval", nextInterval)
|
||||
redis.call("ZADD", pendingNotificationQueue, tonumber(maxTime) + nextInterval, name)
|
||||
|
||||
collated[i] = pending["account"] .. ":" .. pending["device"]
|
||||
end
|
||||
end
|
||||
|
||||
return collated
|
||||
@@ -1,14 +0,0 @@
|
||||
local pendingNotificationQueue = KEYS[1]
|
||||
local endpoint = KEYS[2]
|
||||
|
||||
local timestamp = ARGV[1]
|
||||
local interval = ARGV[2]
|
||||
local account = ARGV[3]
|
||||
local deviceId = ARGV[4]
|
||||
|
||||
redis.call("HSET", endpoint, "created", timestamp)
|
||||
redis.call("HSET", endpoint, "interval", interval)
|
||||
redis.call("HSET", endpoint, "account", account)
|
||||
redis.call("HSET", endpoint, "device", deviceId)
|
||||
|
||||
redis.call("ZADD", pendingNotificationQueue, timestamp, endpoint)
|
||||
@@ -1,5 +0,0 @@
|
||||
local pendingNotificationQueue = KEYS[1]
|
||||
local endpoint = KEYS[2]
|
||||
|
||||
redis.call("DEL", endpoint)
|
||||
return redis.call("ZREM", pendingNotificationQueue, endpoint)
|
||||
@@ -17,8 +17,8 @@ local messageId = redis.call("HINCRBY", queueMetadataKey, "counter", 1)
|
||||
redis.call("ZADD", queueKey, "NX", messageId, message)
|
||||
|
||||
redis.call("HSET", queueMetadataKey, guid, messageId)
|
||||
redis.call("EXPIRE", queueKey, 2678400) -- 31 days
|
||||
redis.call("EXPIRE", queueMetadataKey, 2678400) -- 31 days
|
||||
redis.call("EXPIRE", queueKey, 3974400) -- 46 days
|
||||
redis.call("EXPIRE", queueMetadataKey, 3974400) -- 46 days
|
||||
|
||||
redis.call("ZADD", queueTotalIndexKey, "NX", currentTime, queueKey)
|
||||
return messageId
|
||||
+32
-3
@@ -13,9 +13,11 @@ import io.dropwizard.testing.junit5.DropwizardAppExtension;
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import io.dropwizard.util.Resources;
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import javax.ws.rs.client.Client;
|
||||
import javax.ws.rs.core.Response;
|
||||
import org.eclipse.jetty.websocket.api.Session;
|
||||
import org.eclipse.jetty.websocket.client.WebSocketClient;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
@@ -27,6 +29,7 @@ import org.whispersystems.textsecuregcm.storage.DynamoDbExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema;
|
||||
import org.whispersystems.textsecuregcm.tests.util.TestWebsocketListener;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.websocket.messages.WebSocketResponseMessage;
|
||||
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
@@ -92,15 +95,42 @@ class WhisperServerServiceTest {
|
||||
@Test
|
||||
void websocket() throws Exception {
|
||||
// test unauthenticated websocket
|
||||
final long start = System.currentTimeMillis();
|
||||
|
||||
final TestWebsocketListener testWebsocketListener = new TestWebsocketListener();
|
||||
webSocketClient.connect(testWebsocketListener,
|
||||
|
||||
final Session session = webSocketClient.connect(testWebsocketListener,
|
||||
URI.create(String.format("ws://localhost:%d/v1/websocket/", EXTENSION.getLocalPort())))
|
||||
.join();
|
||||
final long sessionTimestamp = Long.parseLong(session.getUpgradeResponse().getHeader(HeaderUtils.TIMESTAMP_HEADER));
|
||||
assertTrue(sessionTimestamp >= start);
|
||||
|
||||
final WebSocketResponseMessage keepAlive = testWebsocketListener.doGet("/v1/keepalive").join();
|
||||
|
||||
assertEquals(200, keepAlive.getStatus());
|
||||
final long keepAliveTimestamp = Long.parseLong(
|
||||
keepAlive.getHeaders().get(HeaderUtils.TIMESTAMP_HEADER.toLowerCase()));
|
||||
assertTrue(keepAliveTimestamp >= start);
|
||||
|
||||
final WebSocketResponseMessage whoami = testWebsocketListener.doGet("/v1/accounts/whoami").join();
|
||||
assertEquals(401, whoami.getStatus());
|
||||
final long whoamiTimestamp = Long.parseLong(whoami.getHeaders().get(HeaderUtils.TIMESTAMP_HEADER.toLowerCase()));
|
||||
assertTrue(whoamiTimestamp >= start);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rest() throws Exception {
|
||||
// test unauthenticated rest
|
||||
final long start = System.currentTimeMillis();
|
||||
|
||||
final Response whoami = EXTENSION.client().target(
|
||||
"http://localhost:%d/v1/accounts/whoami".formatted(EXTENSION.getLocalPort())).request().get();
|
||||
|
||||
assertEquals(401, whoami.getStatus());
|
||||
final List<Object> timestampValues = whoami.getHeaders().get(HeaderUtils.TIMESTAMP_HEADER.toLowerCase());
|
||||
assertEquals(1, timestampValues.size());
|
||||
|
||||
final long whoamiTimestamp = Long.parseLong(timestampValues.getFirst().toString());
|
||||
assertTrue(whoamiTimestamp >= start);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -140,7 +170,6 @@ class WhisperServerServiceTest {
|
||||
.key(Map.of(numbers.hashKeyName(), numberAV))
|
||||
.build());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+11
-7
@@ -35,16 +35,20 @@ public class HCaptchaClientTest {
|
||||
|
||||
static Stream<Arguments> captchaProcessed() {
|
||||
return Stream.of(
|
||||
Arguments.of(true, 0.6f, true),
|
||||
Arguments.of(false, 0.6f, false),
|
||||
Arguments.of(true, 0.4f, false),
|
||||
Arguments.of(false, 0.4f, false)
|
||||
// hCaptcha scores are inverted compared to recaptcha scores. (low score is good)
|
||||
Arguments.of(true, 0.4f, 0.5f, true),
|
||||
Arguments.of(false, 0.4f, 0.5f, false),
|
||||
Arguments.of(true, 0.6f, 0.5f, false),
|
||||
Arguments.of(false, 0.6f, 0.5f, false),
|
||||
Arguments.of(true, 0.6f, 0.4f, true),
|
||||
Arguments.of(true, 0.61f, 0.4f, false),
|
||||
Arguments.of(true, 0.7f, 0.3f, true)
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
public void captchaProcessed(final boolean success, final float score, final boolean expectedResult)
|
||||
public void captchaProcessed(final boolean success, final float hCaptchaScore, final float scoreFloor, final boolean expectedResult)
|
||||
throws IOException, InterruptedException {
|
||||
|
||||
final FaultTolerantHttpClient client = mockResponder(200, String.format("""
|
||||
@@ -54,9 +58,9 @@ public class HCaptchaClientTest {
|
||||
"score-reasons": ["great job doing this captcha"]
|
||||
}
|
||||
""",
|
||||
success, 1 - score)); // hCaptcha scores are inverted compared to recaptcha scores. (low score is good)
|
||||
success, hCaptchaScore));
|
||||
|
||||
final AssessmentResult result = new HCaptchaClient("fake", client, mockConfig(true, 0.5))
|
||||
final AssessmentResult result = new HCaptchaClient("fake", client, mockConfig(true, scoreFloor))
|
||||
.verify(SITE_KEY, Action.CHALLENGE, TOKEN, null, USER_AGENT);
|
||||
if (!success) {
|
||||
assertThat(result).isEqualTo(AssessmentResult.invalid());
|
||||
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonTypeName;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisServerExtension;
|
||||
|
||||
@JsonTypeName("local")
|
||||
public class LocalFaultTolerantRedisClientFactory implements FaultTolerantRedisClientFactory {
|
||||
|
||||
private static final RedisServerExtension REDIS_SERVER_EXTENSION = RedisServerExtension.builder().build();
|
||||
|
||||
private final AtomicBoolean shutdownHookConfigured = new AtomicBoolean();
|
||||
|
||||
private LocalFaultTolerantRedisClientFactory() {
|
||||
try {
|
||||
REDIS_SERVER_EXTENSION.beforeAll(null);
|
||||
REDIS_SERVER_EXTENSION.beforeEach(null);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public FaultTolerantRedisClient build(final String name, final ClientResources clientResources) {
|
||||
|
||||
if (shutdownHookConfigured.compareAndSet(false, true)) {
|
||||
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
|
||||
try {
|
||||
REDIS_SERVER_EXTENSION.afterEach(null);
|
||||
REDIS_SERVER_EXTENSION.afterAll(null);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
final RedisConfiguration config = new RedisConfiguration();
|
||||
config.setUri(RedisServerExtension.getRedisURI().toString());
|
||||
|
||||
return new FaultTolerantRedisClient(name, config, clientResources.mutate());
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -8,7 +8,7 @@ package org.whispersystems.textsecuregcm.configuration;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeName;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
|
||||
@JsonTypeName("local")
|
||||
@@ -31,7 +31,7 @@ public class LocalFaultTolerantRedisClusterFactory implements FaultTolerantRedis
|
||||
}
|
||||
|
||||
@Override
|
||||
public FaultTolerantRedisCluster build(final String name, final ClientResources.Builder clientResourcesBuilder) {
|
||||
public FaultTolerantRedisClusterClient build(final String name, final ClientResources.Builder clientResourcesBuilder) {
|
||||
|
||||
if (shutdownHookConfigured.compareAndSet(false, true)) {
|
||||
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
|
||||
@@ -47,7 +47,7 @@ public class LocalFaultTolerantRedisClusterFactory implements FaultTolerantRedis
|
||||
final RedisClusterConfiguration config = new RedisClusterConfiguration();
|
||||
config.setConfigurationUri(RedisClusterExtension.getRedisURIs().getFirst().toString());
|
||||
|
||||
return new FaultTolerantRedisCluster(name, config, clientResourcesBuilder);
|
||||
return new FaultTolerantRedisClusterClient(name, config, clientResourcesBuilder);
|
||||
}
|
||||
|
||||
}
|
||||
-52
@@ -1,52 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonTypeName;
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import io.lettuce.core.RedisClient;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisSingletonExtension;
|
||||
|
||||
@JsonTypeName("local")
|
||||
public class LocalSingletonRedisClientFactory implements SingletonRedisClientFactory, Managed {
|
||||
|
||||
private static final RedisSingletonExtension redisSingletonExtension = RedisSingletonExtension.builder().build();
|
||||
|
||||
private final AtomicBoolean shutdownHookConfigured = new AtomicBoolean();
|
||||
|
||||
private LocalSingletonRedisClientFactory() {
|
||||
try {
|
||||
redisSingletonExtension.beforeAll(null);
|
||||
redisSingletonExtension.beforeEach(null);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public RedisClient build(final ClientResources clientResources) {
|
||||
|
||||
if (shutdownHookConfigured.compareAndSet(false, true)) {
|
||||
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
|
||||
try {
|
||||
this.stop();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
return RedisClient.create(clientResources, redisSingletonExtension.getRedisUri());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() throws Exception {
|
||||
redisSingletonExtension.afterEach(null);
|
||||
redisSingletonExtension.afterAll(null);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 150 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user