Compare commits

..
Author SHA1 Message Date
Jon Chambers 9d19fc9ecc Shift authority to the new pub/sub client presence system 2024-11-06 12:10:44 -05:00
Jon Chambers aad12670b2 Register WebSocket connections as pub/sub event listeners 2024-11-06 09:37:06 -05:00
Jon Chambers 7ca7fe7c13 Handle batches of commands in sharded circuit breakers 2024-11-06 09:36:08 -05:00
Jon Chambers ca7e7c288e Format pub/sub hash tags consistently with message-related hash tags 2024-11-06 09:35:45 -05:00
Chris Eager 3a604464b5 Mark LevelConfiguration#name as deprecated 2024-11-06 09:35:19 -05:00
Jon Chambers e277281d18 Update to the latest version of the spam filter 2024-11-06 09:32:57 -05:00
Ameya Lokare 3d339696dc Update to the latest version of the spam filter 2024-11-05 16:17:22 -08:00
Jon Chambers 3e36a49142 Reframe "connection ID" as "server ID" to avoid double-removing clients 2024-11-05 18:43:31 -05:00
Jon Chambers d8f53954d0 Don't send CLIENT SETINFO commands when connecting to Redis instances 2024-11-05 17:29:31 -05:00
Jon Chambers 8c984cbf42 Introduce and evaluate a client presence manager based on sharded pub/sub 2024-11-05 15:51:29 -05:00
Jon Chambers 60cdcf5f0c Only respond to cluster toplogy events from the same cluster to which we're subscribed 2024-11-05 11:42:51 -05:00
Jon Chambers 5afcd634b6 Extend "long idle" device range to 60–75 days 2024-11-05 11:33:22 -05:00
Katherine Yen 00ca58ec13 Align FullTreeHead proto with KT's 2024-11-05 11:33:11 -05:00
Katherine Yen bbb6d448db Standardize KT response field name to serializedResponse 2024-11-05 11:32:58 -05:00
adel-signal 45fad7a6a9 update e164 experiments to use account enrollment percentage 2024-11-04 15:00:25 -06:00
Katherine 7633a9b07a Replace TreeSearchResponse with CondensedTreeSearchResponse 2024-11-04 10:36:15 -05:00
Jon Chambers 00d0dba62c Don't retry pub/sub commands 2024-11-04 10:35:50 -05:00
Jon Chambers c9a396b9e3 Deserialize null capabilities in Device entities as empty sets 2024-11-01 16:48:56 -04:00
Ravi Khadiwala fc0a7b7657 401 instead of 403 on wrong backup auth credential type 2024-11-01 16:46:44 -04:00
Ameya Lokare c1e870d8f5 Update to the latest version of the spam filter 2024-10-31 14:55:33 -07:00
Ameya Lokare 190f2a7fc2 Pass ACI to captcha checker 2024-10-31 14:24:43 -07:00
Jonathan Klabunde Tomer ce0ccf4fd0 Update to the latest version of the spam filter 2024-10-31 11:27:38 -07:00
Jonathan Klabunde Tomer 0018e0bec6 remove appconfig in favor of S3ObjectMonitor 2024-10-31 11:25:45 -07:00
Jonathan Klabunde Tomer 63021e0ca3 Avoid annotation-driven parsing of device capabilities in DeviceController 2024-10-31 10:58:38 -04:00
Katherine Yen bf741df38e Remove unnecessary NotNull annotation 2024-10-31 10:56:19 -04:00
Katherine e627d4e2c4 Require some tree head sizes in key transparency search and monitor requests 2024-10-31 10:54:55 -04:00
Katherine 9b5a62e60f Remove FullTreeHead from TreeSearchResponse 2024-10-31 10:51:22 -04:00
Ravi Khadiwala 3bb1eab48c Fix casing in GET /v1/archives/auth 2024-10-30 17:07:43 -04:00
Jon Chambers 4af576668c Fix incorrect substitution of enumeration key names for capability names 2024-10-30 17:06:09 -04:00
Jon Chambers f5a93574f6 Simplify capabilities representation in gRPC profile responses 2024-10-30 17:06:09 -04:00
Jon Chambers 74f8889bfa Simplify capability set serialization 2024-10-30 17:06:09 -04:00
Jon Chambers a8da0f64ac Extract device capability enumeration translation to a utility class 2024-10-30 17:06:09 -04:00
Jon Chambers 44c3b046dd Add a new capability for storage service record key rotation 2024-10-30 13:04:10 -04:00
Ravi Khadiwala f2cb04817b Let server generate copyToMedia IVs
We include the IV in the encrypted payload, so we can let the server
choose them instead of the client
2024-10-30 13:03:48 -04:00
Katherine a5f60b1522 Use standard, unpadded base64 serialization/deserialization for commitmentIndex 2024-10-30 12:50:45 -04:00
Jon Chambers 0e3dccd9f6 Replace DeviceCapabilities entity with Set<DeviceCapability> 2024-10-30 12:46:20 -04:00
Jon ChambersandRavi Khadiwala b21b50873f Add support for distinct media backup credentials
Co-authored-by: Ravi Khadiwala <ravi@signal.org>
2024-10-29 16:03:10 -04:00
Katherine d335b7a033 Align KeyTransparencySearchResponse with distinguished counterpart and update DistinguishedResponse field names 2024-10-29 15:55:45 -04:00
Jon Chambers f3b22e04e8 Allow primary devices to change names of linked devices 2024-10-29 09:52:38 -04:00
Katherine 712f3affd9 Update chat to send three search keys in one request to KT 2024-10-29 09:52:26 -04:00
Ameya Lokare 89292e238b Update to the latest version of the spam filter 2024-10-28 12:20:54 -07:00
Katherine 3287085ef9 Remove test references to legacy ratelimit HTTP status code 2024-10-28 15:20:08 -04:00
Ameya Lokare 17dfd914d5 Add maybe to optional argument name 2024-10-28 12:19:19 -07:00
Chris Eager c65fe49983 Add commitment index to key transparency monitor requests 2024-10-28 14:18:41 -05:00
Chris Eager 6552d90dc9 Refactor request JSON creation in KeyTransparencyControllerTest 2024-10-28 14:18:41 -05:00
Chris Eager d925e8af9e Update shape of KeyTransparencyMonitorRequest 2024-10-28 14:18:41 -05:00
Jon Chambers 2c0fc43137 Require that accounts be non-stale when getting/setting backup vouchers 2024-10-28 15:18:19 -04:00
Ameya Lokare ccdbec088f Document that sendMessage can return 428 2024-10-28 12:18:02 -07:00
Jon Chambers 9822d17ab9 Fail "wait for X" futures if a Redis operation fails 2024-10-28 15:17:49 -04:00
Chris Eager 9573d9e385 Skip fetching MRM content for stale ephemeral messages 2024-10-24 11:49:33 -05:00
Chris Eager 155f3d6231 key transparency: add distinguished key endpoint 2024-10-24 11:49:20 -05:00
Chris Eager 1959ca2d96 Add client identity to key and certificate to KeyTransparencyServiceClient 2024-10-24 11:36:57 -05:00
Jon Chambers 324913d2da Add API endpoints for waiting for account restoration requests 2024-10-24 12:25:40 -04:00
Ameya Lokare 5c4cafcb6f Update to the latest version of the spam filter 2024-10-23 13:21:05 -07:00
Ameya Lokare 1ea8d69b40 Update captcha string in local testing doc 2024-10-23 09:56:41 -07:00
Katherine 013e45596e Update KT search requests to include a value and maybe an unidentified access key 2024-10-23 10:21:38 -04:00
Ameya Lokare 3fdb691702 Update to the latest version of the spam filter 2024-10-22 10:29:01 -07:00
Ameya Lokare 997129871c Lazily get captcha clients to avoid initialization issues 2024-10-22 09:13:00 -07:00
Ameya Lokare 39b1935350 Update to the latest version of the spam filter 2024-10-21 14:09:19 -07:00
Ameya Lokare dbb9a8dcf6 Get captcha clients from spam-filter module 2024-10-21 13:32:32 -07:00
157 changed files with 4615 additions and 2595 deletions

No files matched your search

+1 -1
View File
@@ -20,7 +20,7 @@ goal with the `test-server` profile activated:
This runs [`LocalWhisperServerService`][lwss] with [test configuration][test.yml] and [secrets][test secrets]. External
registration clients are stubbed so that:
- a captcha requirement can be satisfied with `test.test.registration.test`
- a captcha requirement can be satisfied with `noop.noop.registration.noop`
- any string will be accepted for a phone verification code
[lwss]: service/src/test/java/org/whispersystems/textsecuregcm/LocalWhisperServerService.java
@@ -14,10 +14,12 @@ import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.IdentityKeyPair;
import org.signal.libsignal.protocol.InvalidKeyException;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
import org.signal.libsignal.protocol.state.SignedPreKeyRecord;
import org.signal.libsignal.protocol.util.KeyHelper;
@@ -126,7 +128,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))
return new AccountAttributes(true, registrationId, pniRegistrationId, "".getBytes(StandardCharsets.UTF_8), "", true, Set.of())
.withUnidentifiedAccessKey(unidentifiedAccessKey)
.withRecoveryPassword(registrationPassword);
}
@@ -161,15 +163,19 @@ public class TestUser {
: aciIdentityKey;
final TestDevice device = requireNonNull(devices.get(deviceId));
final SignedPreKeyRecord signedPreKeyRecord = device.latestSignedPreKey(identity);
return new PreKeySetPublicView(
Collections.emptyList(),
identity.getPublicKey(),
new SignedPreKeyPublicView(
signedPreKeyRecord.getId(),
signedPreKeyRecord.getKeyPair().getPublicKey(),
signedPreKeyRecord.getSignature()
)
);
try {
return new PreKeySetPublicView(
Collections.emptyList(),
identity.getPublicKey(),
new SignedPreKeyPublicView(
signedPreKeyRecord.getId(),
signedPreKeyRecord.getKeyPair().getPublicKey(),
signedPreKeyRecord.getSignature()
)
);
} catch (InvalidKeyException e) {
throw new RuntimeException(e);
}
}
public record SignedPreKeyPublicView(
+2 -2
View File
@@ -56,7 +56,7 @@
<jsr305.version>3.0.2</jsr305.version>
<kotlin.version>1.9.24</kotlin.version>
<kotlinx-serialization.version>1.5.1</kotlinx-serialization.version>
<lettuce.version>6.3.2.RELEASE</lettuce.version>
<lettuce.version>6.4.1.RELEASE</lettuce.version>
<libphonenumber.version>8.13.40</libphonenumber.version>
<logstash.logback.version>7.3</logstash.logback.version>
<log4j-bom.version>2.23.1</log4j-bom.version>
@@ -272,7 +272,7 @@
<dependency>
<groupId>org.signal</groupId>
<artifactId>libsignal-server</artifactId>
<version>0.54.2</version>
<version>0.60.0</version>
</dependency>
<dependency>
<groupId>org.signal.forks</groupId>
+7 -1
View File
@@ -72,7 +72,13 @@ cdn3StorageManager.clientSecret: test
unidentifiedDelivery.certificate: ABCD1234
unidentifiedDelivery.privateKey: ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789AAAAAAA
hCaptcha.apiKey: unset
keyTransparencyService.clientPrivateKey: |
-----BEGIN PRIVATE KEY-----
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
AAAAAAAA
-----END PRIVATE KEY-----
storageService.userAuthenticationTokenSharedSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
+29 -7
View File
@@ -284,9 +284,6 @@ unidentifiedDelivery:
privateKey: secret://unidentifiedDelivery.privateKey
expiresDays: 7
hCaptcha:
apiKey: secret://hCaptcha.apiKey
shortCode:
baseUrl: https://example.com/shortcodes/
@@ -327,10 +324,12 @@ callingZkConfig:
backupsZkConfig:
serverSecret: secret://backupsZkConfig.serverSecret
appConfig:
application: example
environment: example
configuration: example
dynamicConfig:
s3Region: a-region
s3Bucket: a-bucket
objectKey: dynamic-config.yaml
maxSize: 100000
refreshInterval: PT10S
remoteConfig:
globalConfig: # keys and values that are given to clients on GET /v1/config
@@ -467,6 +466,29 @@ keyTransparencyService:
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
AAAAAAAAAAAAAAAAAAAA
-----END CERTIFICATE-----
clientCertificate: |
-----BEGIN CERTIFICATE-----
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
AAAAAAAAAAAAAAAAAAAA
-----END CERTIFICATE-----
clientPrivateKey: secret://keyTransparencyService.clientPrivateKey
turn:
secret: secret://turn.secret
-8
View File
@@ -364,14 +364,6 @@
<groupId>software.amazon.awssdk</groupId>
<artifactId>dynamodb</artifactId>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>appconfig</artifactId>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>appconfigdata</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>dynamodb-lock-client</artifactId>
@@ -27,7 +27,6 @@ import org.whispersystems.textsecuregcm.configuration.DatadogConfiguration;
import org.whispersystems.textsecuregcm.configuration.DefaultAwsCredentialsFactory;
import org.whispersystems.textsecuregcm.configuration.DirectoryV2Configuration;
import org.whispersystems.textsecuregcm.configuration.DogstatsdConfiguration;
import org.whispersystems.textsecuregcm.configuration.DynamicConfigurationManagerFactory;
import org.whispersystems.textsecuregcm.configuration.DynamoDbClientFactory;
import org.whispersystems.textsecuregcm.configuration.DynamoDbTables;
import org.whispersystems.textsecuregcm.configuration.ExternalRequestFilterConfiguration;
@@ -37,7 +36,6 @@ import org.whispersystems.textsecuregcm.configuration.FcmConfiguration;
import org.whispersystems.textsecuregcm.configuration.GcpAttachmentsConfiguration;
import org.whispersystems.textsecuregcm.configuration.GenericZkConfig;
import org.whispersystems.textsecuregcm.configuration.GooglePlayBillingConfiguration;
import org.whispersystems.textsecuregcm.configuration.HCaptchaClientFactory;
import org.whispersystems.textsecuregcm.configuration.KeyTransparencyServiceConfiguration;
import org.whispersystems.textsecuregcm.configuration.LinkDeviceSecretConfiguration;
import org.whispersystems.textsecuregcm.configuration.MaxDeviceConfiguration;
@@ -202,11 +200,6 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private UnidentifiedDeliveryConfiguration unidentifiedDelivery;
@Valid
@NotNull
@JsonProperty
private HCaptchaClientFactory hCaptcha;
@Valid
@NotNull
@JsonProperty
@@ -250,7 +243,7 @@ public class WhisperServerConfiguration extends Configuration {
@Valid
@NotNull
@JsonProperty
private DynamicConfigurationManagerFactory appConfig;
private S3ObjectMonitorFactory dynamicConfig;
@Valid
@NotNull
@@ -379,10 +372,6 @@ public class WhisperServerConfiguration extends Configuration {
return dynamoDbTables;
}
public HCaptchaClientFactory getHCaptchaConfiguration() {
return hCaptcha;
}
public ShortCodeExpanderConfiguration getShortCodeRetrieverConfiguration() {
return shortCode;
}
@@ -497,8 +486,8 @@ public class WhisperServerConfiguration extends Configuration {
return remoteConfig;
}
public DynamicConfigurationManagerFactory getAppConfig() {
return appConfig;
public S3ObjectMonitorFactory getDynamicConfig() {
return dynamicConfig;
}
public BadgesConfiguration getBadges() {
@@ -57,6 +57,7 @@ import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.function.Function;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import javax.servlet.DispatcherType;
@@ -94,13 +95,12 @@ import org.whispersystems.textsecuregcm.backup.BackupsDb;
import org.whispersystems.textsecuregcm.backup.Cdn3BackupCredentialGenerator;
import org.whispersystems.textsecuregcm.backup.Cdn3RemoteStorageManager;
import org.whispersystems.textsecuregcm.badges.ConfiguredProfileBadgeConverter;
import org.whispersystems.textsecuregcm.badges.ResourceBundleLevelTranslator;
import org.whispersystems.textsecuregcm.calls.routing.CallDnsRecordsManager;
import org.whispersystems.textsecuregcm.calls.routing.CallRoutingTableManager;
import org.whispersystems.textsecuregcm.calls.routing.DynamicConfigTurnRouter;
import org.whispersystems.textsecuregcm.calls.routing.TurnCallRouter;
import org.whispersystems.textsecuregcm.captcha.CaptchaChecker;
import org.whispersystems.textsecuregcm.captcha.HCaptchaClient;
import org.whispersystems.textsecuregcm.captcha.CaptchaClient;
import org.whispersystems.textsecuregcm.captcha.RegistrationCaptchaManager;
import org.whispersystems.textsecuregcm.captcha.ShortCodeExpander;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
@@ -195,6 +195,7 @@ 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.PubSubClientEventManager;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
import org.whispersystems.textsecuregcm.push.ReceiptSender;
@@ -350,8 +351,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
ScheduledExecutorService dynamicConfigurationExecutor = environment.lifecycle()
.scheduledExecutorService(name(getClass(), "dynamicConfiguration-%d")).threads(1).build();
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = config.getAppConfig()
.build(DynamicConfiguration.class, dynamicConfigurationExecutor, awsCredentialsProvider);
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
new DynamicConfigurationManager<>(
config.getDynamicConfig().build(awsCredentialsProvider, dynamicConfigurationExecutor), DynamicConfiguration.class);
dynamicConfigurationManager.start();
MetricsUtil.configureRegistries(config, environment, dynamicConfigurationManager);
@@ -371,8 +373,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new HeaderControlledResourceBundleLookup();
ConfiguredProfileBadgeConverter profileBadgeConverter = new ConfiguredProfileBadgeConverter(
clock, config.getBadges(), headerControlledResourceBundleLookup);
ResourceBundleLevelTranslator resourceBundleLevelTranslator = new ResourceBundleLevelTranslator(
headerControlledResourceBundleLookup);
BankMandateTranslator bankMandateTranslator = new BankMandateTranslator(headerControlledResourceBundleLookup);
environment.lifecycle().manage(new ManagedAwsCrt());
@@ -499,8 +499,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
.scheduledExecutorService(name(getClass(), "secureValueRecoveryServiceRetry-%d")).threads(1).build();
ScheduledExecutorService storageServiceRetryExecutor = environment.lifecycle()
.scheduledExecutorService(name(getClass(), "storageServiceRetry-%d")).threads(1).build();
ScheduledExecutorService hcaptchaRetryExecutor = environment.lifecycle()
.scheduledExecutorService(name(getClass(), "hCaptchaRetry-%d")).threads(1).build();
ScheduledExecutorService remoteStorageRetryExecutor = environment.lifecycle()
.scheduledExecutorService(name(getClass(), "remoteStorageRetry-%d")).threads(1).build();
ScheduledExecutorService registrationIdentityTokenRefreshExecutor = environment.lifecycle()
@@ -551,14 +549,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
.maxThreads(8)
.build();
// unbounded executor (same as cachedThreadPool)
ExecutorService hcaptchaHttpExecutor = environment.lifecycle()
.executorService(name(getClass(), "hcaptcha-%d"))
.minThreads(0)
.maxThreads(Integer.MAX_VALUE)
.workQueue(new SynchronousQueue<>())
.keepAliveTime(io.dropwizard.util.Duration.seconds(60L))
.build();
// unbounded executor (same as cachedThreadPool)
ExecutorService remoteStorageHttpExecutor = environment.lifecycle()
.executorService(name(getClass(), "remoteStorage-%d"))
.minThreads(0)
@@ -577,6 +567,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
.virtualExecutorService(name(getClass(), "googlePlayBilling-%d"));
ExecutorService appleAppStoreExecutor = environment.lifecycle()
.virtualExecutorService(name(getClass(), "appleAppStore-%d"));
ExecutorService clientEventExecutor = environment.lifecycle()
.virtualExecutorService(name(getClass(), "clientEvent-%d"));
ScheduledExecutorService appleAppStoreRetryExecutor = environment.lifecycle()
.scheduledExecutorService(name(getClass(), "appleAppStoreRetry-%d")).threads(1).build();
@@ -618,6 +610,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getKeyTransparencyServiceConfiguration().host(),
config.getKeyTransparencyServiceConfiguration().port(),
config.getKeyTransparencyServiceConfiguration().tlsCertificate(),
config.getKeyTransparencyServiceConfiguration().clientCertificate(),
config.getKeyTransparencyServiceConfiguration().clientPrivateKey().value(),
keyTransparencyCallbackExecutor);
SecureValueRecovery2Client secureValueRecovery2Client = new SecureValueRecovery2Client(svr2CredentialsGenerator,
secureValueRecoveryServiceExecutor, secureValueRecoveryServiceRetryExecutor, config.getSvr2Configuration());
@@ -625,6 +619,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
storageServiceExecutor, storageServiceRetryExecutor, config.getSecureStorageServiceConfiguration());
ClientPresenceManager clientPresenceManager = new ClientPresenceManager(clientPresenceCluster, recurringJobExecutor,
keyspaceNotificationDispatchExecutor);
PubSubClientEventManager pubSubClientEventManager = new PubSubClientEventManager(messagesCluster, clientEventExecutor);
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster);
MessagesCache messagesCache = new MessagesCache(messagesCluster, keyspaceNotificationDispatchExecutor,
messageDeliveryScheduler, messageDeletionAsyncExecutor, clock, dynamicConfigurationManager);
@@ -643,7 +638,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
pubsubClient, accountLockManager, keysManager, messagesManager, profilesManager,
secureStorageClient, secureValueRecovery2Client,
clientPresenceManager,
clientPresenceManager, pubSubClientEventManager,
registrationRecoveryPasswordsManager, clientPublicKeysManager, accountLockExecutor, clientPresenceExecutor,
clock, config.getLinkDeviceSecretConfiguration().secret().value(), dynamicConfigurationManager);
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs);
@@ -673,7 +668,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new MessageDeliveryLoopMonitor(rateLimitersCluster);
final RegistrationLockVerificationManager registrationLockVerificationManager = new RegistrationLockVerificationManager(
accountsManager, clientPresenceManager, svr2CredentialsGenerator, svr3CredentialsGenerator,
accountsManager, clientPresenceManager, pubSubClientEventManager, svr2CredentialsGenerator, svr3CredentialsGenerator,
registrationRecoveryPasswordsManager, pushNotificationManager, rateLimiters);
final ReportedMessageMetricsListener reportedMessageMetricsListener = new ReportedMessageMetricsListener(
@@ -683,7 +678,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final AccountAuthenticator accountAuthenticator = new AccountAuthenticator(accountsManager);
final MessageSender messageSender =
new MessageSender(clientPresenceManager, messagesManager, pushNotificationManager);
new MessageSender(pubSubClientEventManager, messagesManager, pushNotificationManager);
final ReceiptSender receiptSender = new ReceiptSender(accountsManager, messageSender, receiptSenderExecutor);
final TurnTokenGenerator turnTokenGenerator = new TurnTokenGenerator(dynamicConfigurationManager,
config.getTurnConfiguration().secret().value());
@@ -706,13 +701,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
"message_byte_limit",
config.getMessageByteLimitCardinalityEstimator().period());
HCaptchaClient hCaptchaClient = config.getHCaptchaConfiguration()
.build(hcaptchaRetryExecutor, hcaptchaHttpExecutor, dynamicConfigurationManager);
HttpClient shortCodeRetrieverHttpClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2)
.connectTimeout(Duration.ofSeconds(10)).build();
ShortCodeExpander shortCodeRetriever = new ShortCodeExpander(shortCodeRetrieverHttpClient, config.getShortCodeRetrieverConfiguration().baseUrl());
CaptchaChecker captchaChecker = new CaptchaChecker(shortCodeRetriever, List.of(hCaptchaClient));
PushChallengeManager pushChallengeManager = new PushChallengeManager(pushNotificationManager,
pushChallengeDynamoDb);
@@ -758,6 +746,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
environment.lifecycle().manage(provisioningManager);
environment.lifecycle().manage(messagesCache);
environment.lifecycle().manage(clientPresenceManager);
environment.lifecycle().manage(pubSubClientEventManager);
environment.lifecycle().manage(currencyManager);
environment.lifecycle().manage(registrationServiceClient);
environment.lifecycle().manage(keyTransparencyServiceClient);
@@ -765,7 +754,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
environment.lifecycle().manage(virtualThreadPinEventMonitor);
environment.lifecycle().manage(accountsManager);
final RegistrationCaptchaManager registrationCaptchaManager = new RegistrationCaptchaManager(captchaChecker);
AwsCredentialsProvider cdnCredentialsProvider = config.getCdnConfiguration().credentials().build();
S3Client cdnS3Client = S3Client.builder()
@@ -1010,7 +998,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
environment.jersey().register(MultiRecipientMessageProvider.class);
environment.jersey().register(new AuthDynamicFeature(accountAuthFilter));
environment.jersey().register(new AuthValueFactoryProvider.Binder<>(AuthenticatedDevice.class));
environment.jersey().register(new WebsocketRefreshApplicationEventListener(accountsManager, clientPresenceManager));
environment.jersey().register(new WebsocketRefreshApplicationEventListener(accountsManager, clientPresenceManager,
pubSubClientEventManager));
environment.jersey().register(new TimestampResponseFilter());
///
@@ -1020,15 +1009,16 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
webSocketEnvironment.setAuthenticator(new WebSocketAccountAuthenticator(accountAuthenticator, new AccountPrincipalSupplier(accountsManager)));
webSocketEnvironment.setConnectListener(
new AuthenticatedConnectListener(receiptSender, messagesManager, messageMetrics, pushNotificationManager,
pushNotificationScheduler, clientPresenceManager, websocketScheduledExecutor, messageDeliveryScheduler,
clientReleaseManager, messageDeliveryLoopMonitor));
pushNotificationScheduler, clientPresenceManager, pubSubClientEventManager, websocketScheduledExecutor,
messageDeliveryScheduler, clientReleaseManager, messageDeliveryLoopMonitor));
webSocketEnvironment.jersey()
.register(new WebsocketRefreshApplicationEventListener(accountsManager, clientPresenceManager));
.register(new WebsocketRefreshApplicationEventListener(accountsManager, clientPresenceManager,
pubSubClientEventManager));
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 KeepAliveController(pubSubClientEventManager));
webSocketEnvironment.jersey().register(new TimestampResponseFilter());
final List<SpamFilter> spamFilters = ServiceLoader.load(SpamFilter.class)
@@ -1075,10 +1065,22 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
log.warn("No registration-recovery-checkers found; using default (no-op) provider as a default");
return RegistrationRecoveryChecker.noop();
});
final Function<String, CaptchaClient> captchaClientSupplier = spamFilter
.map(SpamFilter::getCaptchaClientSupplier)
.orElseGet(() -> {
log.warn("No captcha clients found; using default (no-op) client as default");
return ignored -> CaptchaClient.noop();
});
spamFilter.map(SpamFilter::getReportedMessageListener).ifPresent(reportMessageManager::addListener);
final HttpClient shortCodeRetrieverHttpClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2)
.connectTimeout(Duration.ofSeconds(10)).build();
final ShortCodeExpander shortCodeRetriever = new ShortCodeExpander(shortCodeRetrieverHttpClient, config.getShortCodeRetrieverConfiguration().baseUrl());
final CaptchaChecker captchaChecker = new CaptchaChecker(shortCodeRetriever, captchaClientSupplier);
final RegistrationCaptchaManager registrationCaptchaManager = new RegistrationCaptchaManager(captchaChecker);
final RateLimitChallengeManager rateLimitChallengeManager = new RateLimitChallengeManager(pushChallengeManager,
captchaChecker, rateLimiters, spamFilter.map(SpamFilter::getRateLimitChallengeListener).stream().toList());
@@ -1141,7 +1143,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
zkReceiptOperations, issuedReceiptsManager);
commonControllers.add(new SubscriptionController(clock, config.getSubscription(), config.getOneTimeDonations(),
subscriptionManager, stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager,
profileBadgeConverter, resourceBundleLevelTranslator, bankMandateTranslator));
profileBadgeConverter, bankMandateTranslator));
commonControllers.add(new OneTimeDonationController(clock, config.getOneTimeDonations(), stripeManager, braintreeManager,
zkReceiptOperations, issuedReceiptsManager, oneTimeDonationsManager));
}
@@ -1153,10 +1155,11 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
WebSocketEnvironment<AuthenticatedDevice> provisioningEnvironment = new WebSocketEnvironment<>(environment,
webSocketEnvironment.getRequestLog(), Duration.ofMillis(60000));
provisioningEnvironment.jersey().register(new WebsocketRefreshApplicationEventListener(accountsManager, clientPresenceManager));
provisioningEnvironment.jersey().register(new WebsocketRefreshApplicationEventListener(accountsManager, clientPresenceManager,
pubSubClientEventManager));
provisioningEnvironment.setConnectListener(new ProvisioningConnectListener(provisioningManager));
provisioningEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET, clientReleaseManager));
provisioningEnvironment.jersey().register(new KeepAliveController(clientPresenceManager));
provisioningEnvironment.jersey().register(new KeepAliveController(pubSubClientEventManager));
provisioningEnvironment.jersey().register(new TimestampResponseFilter());
registerCorsFilter(environment);
@@ -5,6 +5,12 @@
package org.whispersystems.textsecuregcm.auth;
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
import org.signal.libsignal.zkgroup.backups.BackupLevel;
public record AuthenticatedBackupUser(byte[] backupId, BackupLevel backupLevel, String backupDir, String mediaDir) {}
public record AuthenticatedBackupUser(byte[] backupId,
BackupCredentialType credentialType,
BackupLevel backupLevel,
String backupDir,
String mediaDir) {
}
@@ -27,6 +27,7 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
@@ -55,6 +56,7 @@ public class RegistrationLockVerificationManager {
private final AccountsManager accounts;
private final ClientPresenceManager clientPresenceManager;
private final PubSubClientEventManager pubSubClientEventManager;
private final ExternalServiceCredentialsGenerator svr2CredentialGenerator;
private final ExternalServiceCredentialsGenerator svr3CredentialGenerator;
private final RateLimiters rateLimiters;
@@ -62,7 +64,9 @@ public class RegistrationLockVerificationManager {
private final PushNotificationManager pushNotificationManager;
public RegistrationLockVerificationManager(
final AccountsManager accounts, final ClientPresenceManager clientPresenceManager,
final AccountsManager accounts,
final ClientPresenceManager clientPresenceManager,
final PubSubClientEventManager pubSubClientEventManager,
final ExternalServiceCredentialsGenerator svr2CredentialGenerator,
final ExternalServiceCredentialsGenerator svr3CredentialGenerator,
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
@@ -70,6 +74,7 @@ public class RegistrationLockVerificationManager {
final RateLimiters rateLimiters) {
this.accounts = accounts;
this.clientPresenceManager = clientPresenceManager;
this.pubSubClientEventManager = pubSubClientEventManager;
this.svr2CredentialGenerator = svr2CredentialGenerator;
this.svr3CredentialGenerator = svr3CredentialGenerator;
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
@@ -161,6 +166,7 @@ public class RegistrationLockVerificationManager {
final List<Byte> deviceIds = updatedAccount.getDevices().stream().map(Device::getId).toList();
clientPresenceManager.disconnectAllPresences(updatedAccount.getUuid(), deviceIds);
pubSubClientEventManager.requestDisconnection(updatedAccount.getUuid(), deviceIds);
try {
// Send a push notification that prompts the client to attempt login and fail due to locked credentials
@@ -10,6 +10,7 @@ import org.glassfish.jersey.server.monitoring.ApplicationEventListener;
import org.glassfish.jersey.server.monitoring.RequestEvent;
import org.glassfish.jersey.server.monitoring.RequestEventListener;
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
/**
@@ -20,9 +21,11 @@ public class WebsocketRefreshApplicationEventListener implements ApplicationEven
private final WebsocketRefreshRequestEventListener websocketRefreshRequestEventListener;
public WebsocketRefreshApplicationEventListener(final AccountsManager accountsManager,
final ClientPresenceManager clientPresenceManager) {
final ClientPresenceManager clientPresenceManager,
final PubSubClientEventManager pubSubClientEventManager) {
this.websocketRefreshRequestEventListener = new WebsocketRefreshRequestEventListener(clientPresenceManager,
pubSubClientEventManager,
new LinkedDeviceRefreshRequirementProvider(accountsManager),
new PhoneNumberChangeRefreshRequirementProvider(accountsManager));
}
@@ -10,6 +10,7 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.core.Context;
@@ -19,10 +20,12 @@ import org.glassfish.jersey.server.monitoring.RequestEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
public class WebsocketRefreshRequestEventListener implements RequestEventListener {
private final ClientPresenceManager clientPresenceManager;
private final PubSubClientEventManager pubSubClientEventManager;
private final WebsocketRefreshRequirementProvider[] providers;
private static final Counter DISPLACED_ACCOUNTS = Metrics.counter(
@@ -35,9 +38,11 @@ public class WebsocketRefreshRequestEventListener implements RequestEventListene
public WebsocketRefreshRequestEventListener(
final ClientPresenceManager clientPresenceManager,
final PubSubClientEventManager pubSubClientEventManager,
final WebsocketRefreshRequirementProvider... providers) {
this.clientPresenceManager = clientPresenceManager;
this.pubSubClientEventManager = pubSubClientEventManager;
this.providers = providers;
}
@@ -60,6 +65,7 @@ public class WebsocketRefreshRequestEventListener implements RequestEventListene
try {
displacedDevices.incrementAndGet();
clientPresenceManager.disconnectPresence(pair.first(), pair.second());
pubSubClientEventManager.requestDisconnection(pair.first(), List.of(pair.second()));
} catch (final Exception e) {
logger.error("Could not displace device presence", e);
}
@@ -21,6 +21,7 @@ import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialRequest;
import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialResponse;
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
import org.signal.libsignal.zkgroup.backups.BackupLevel;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
@@ -29,7 +30,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
@@ -81,22 +81,34 @@ public class BackupAuthManager {
}
/**
* Store a credential request containing a blinded backup-id for future use.
* Store credential requests containing blinded backup-ids for future use.
*
* @param account The account using the backup-id
* @param backupAuthCredentialRequest A request containing the blinded backup-id
* @param account The account using the backup-id
* @param messagesBackupCredentialRequest A request containing the blinded backup-id the client will use to upload
* message backups
* @param mediaBackupCredentialRequest A request containing the blinded backup-id the client will use to upload
* media backups
* @return A future that completes when the credentialRequest has been stored
* @throws RateLimitExceededException If too many backup-ids have been committed
*/
public CompletableFuture<Void> commitBackupId(final Account account,
final BackupAuthCredentialRequest backupAuthCredentialRequest) {
final BackupAuthCredentialRequest messagesBackupCredentialRequest,
final BackupAuthCredentialRequest mediaBackupCredentialRequest) {
if (configuredBackupLevel(account).isEmpty()) {
throw Status.PERMISSION_DENIED.withDescription("Backups not allowed on account").asRuntimeException();
}
final byte[] serializedMessageCredentialRequest = messagesBackupCredentialRequest.serialize();
final byte[] serializedMediaCredentialRequest = mediaBackupCredentialRequest.serialize();
byte[] serializedRequest = backupAuthCredentialRequest.serialize();
byte[] existingRequest = account.getBackupCredentialRequest();
if (existingRequest != null && MessageDigest.isEqual(serializedRequest, existingRequest)) {
final boolean messageCredentialRequestMatches = account.getBackupCredentialRequest(BackupCredentialType.MESSAGES)
.map(storedCredentialRequest -> MessageDigest.isEqual(storedCredentialRequest, serializedMessageCredentialRequest))
.orElse(false);
final boolean mediaCredentialRequestMatches = account.getBackupCredentialRequest(BackupCredentialType.MEDIA)
.map(storedCredentialRequest -> MessageDigest.isEqual(storedCredentialRequest, serializedMediaCredentialRequest))
.orElse(false);
if (messageCredentialRequestMatches && mediaCredentialRequestMatches) {
// No need to update or enforce rate limits, this is the credential that the user has already
// committed to.
return CompletableFuture.completedFuture(null);
@@ -105,7 +117,7 @@ public class BackupAuthManager {
return rateLimiters.forDescriptor(RateLimiters.For.SET_BACKUP_ID)
.validateAsync(account.getUuid())
.thenCompose(ignored -> this.accountsManager
.updateAsync(account, acc -> acc.setBackupCredentialRequest(serializedRequest))
.updateAsync(account, a -> a.setBackupCredentialRequests(serializedMessageCredentialRequest, serializedMediaCredentialRequest))
.thenRun(Util.NOOP))
.toCompletableFuture();
}
@@ -123,12 +135,14 @@ public class BackupAuthManager {
* method will also remove the expired voucher from the account.
*
* @param account The account to create the credentials for
* @param credentialType The type of backup credentials to create
* @param redemptionStart The day (must be truncated to a day boundary) the first credential should be valid
* @param redemptionEnd The day (must be truncated to a day boundary) the last credential should be valid
* @return Credentials and the day on which they may be redeemed
*/
public CompletableFuture<List<Credential>> getBackupAuthCredentials(
final Account account,
final BackupCredentialType credentialType,
final Instant redemptionStart,
final Instant redemptionEnd) {
@@ -139,7 +153,7 @@ public class BackupAuthManager {
if (hasExpiredVoucher(a)) {
a.setBackupVoucher(null);
}
}).thenCompose(updated -> getBackupAuthCredentials(updated, redemptionStart, redemptionEnd));
}).thenCompose(updated -> getBackupAuthCredentials(updated, credentialType, redemptionStart, redemptionEnd));
}
// If this account isn't allowed some level of backup access via configuration, don't continue
@@ -157,23 +171,20 @@ public class BackupAuthManager {
}
// fetch the blinded backup-id the account should have previously committed to
final byte[] committedBytes = account.getBackupCredentialRequest();
if (committedBytes == null) {
throw Status.NOT_FOUND.withDescription("No blinded backup-id has been added to the account").asRuntimeException();
}
final byte[] committedBytes = account.getBackupCredentialRequest(credentialType)
.orElseThrow(() -> Status.NOT_FOUND.withDescription("No blinded backup-id has been added to the account").asRuntimeException());
try {
// create a credential for every day in the requested period
final BackupAuthCredentialRequest credentialReq = new BackupAuthCredentialRequest(committedBytes);
return CompletableFuture.completedFuture(Stream
.iterate(redemptionStart, curr -> curr.plus(Duration.ofDays(1)))
.takeWhile(redemptionTime -> !redemptionTime.isAfter(redemptionEnd))
.iterate(redemptionStart, redemptionTime -> !redemptionTime.isAfter(redemptionEnd), curr -> curr.plus(Duration.ofDays(1)))
.map(redemptionTime -> {
// Check if the account has a voucher that's good for a certain receiptLevel at redemption time, otherwise
// use the default receipt level
final BackupLevel backupLevel = storedBackupLevel(account, redemptionTime).orElse(configuredBackupLevel);
return new Credential(
credentialReq.issueCredential(redemptionTime, backupLevel, serverSecretParams),
credentialReq.issueCredential(redemptionTime, backupLevel, credentialType, serverSecretParams),
redemptionTime);
})
.toList());
@@ -210,7 +221,7 @@ public class BackupAuthManager {
final long receiptLevel = receiptCredentialPresentation.getReceiptLevel();
if (BackupLevelUtil.fromReceiptLevel(receiptLevel) != BackupLevel.MEDIA) {
if (BackupLevelUtil.fromReceiptLevel(receiptLevel) != BackupLevel.PAID) {
throw Status.INVALID_ARGUMENT
.withDescription("server does not recognize the requested receipt level")
.asRuntimeException();
@@ -281,10 +292,10 @@ public class BackupAuthManager {
*/
private Optional<BackupLevel> configuredBackupLevel(final Account account) {
if (inExperiment(BACKUP_MEDIA_EXPERIMENT_NAME, account)) {
return Optional.of(BackupLevel.MEDIA);
return Optional.of(BackupLevel.PAID);
}
if (inExperiment(BACKUP_EXPERIMENT_NAME, account)) {
return Optional.of(BackupLevel.MESSAGES);
return Optional.of(BackupLevel.FREE);
}
return Optional.empty();
}
@@ -28,25 +28,22 @@ import org.signal.libsignal.protocol.ecc.ECPublicKey;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialPresentation;
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
import org.signal.libsignal.zkgroup.backups.BackupLevel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.util.AsyncTimerUtil;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.Pair;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
public class BackupManager {
private static final Logger logger = LoggerFactory.getLogger(BackupManager.class);
static final String MESSAGE_BACKUP_NAME = "messageBackup";
public static final long MAX_TOTAL_BACKUP_MEDIA_BYTES = DataSize.gibibytes(100).toBytes();
static final long MAX_MEDIA_OBJECT_SIZE = DataSize.mebibytes(101).toBytes();
@@ -120,8 +117,10 @@ public class BackupManager {
// Note: this is a special case where we can't validate the presentation signature against the stored public key
// because we are currently setting it. We check against the provided public key, but we must also verify that
// there isn't an existing, different stored public key for the backup-id (verified with a condition expression)
final BackupLevel backupLevel = verifyPresentation(presentation).verifySignature(signature, publicKey);
return backupsDb.setPublicKey(presentation.getBackupId(), backupLevel, publicKey)
final Pair<BackupCredentialType, BackupLevel> credentialTypeAndBackupLevel =
verifyPresentation(presentation).verifySignature(signature, publicKey);
return backupsDb.setPublicKey(presentation.getBackupId(), credentialTypeAndBackupLevel.second(), publicKey)
.exceptionally(ExceptionUtils.exceptionallyHandler(PublicKeyConflictException.class, ex -> {
Metrics.counter(ZK_AUTHN_COUNTER_NAME,
SUCCESS_TAG_NAME, String.valueOf(false),
@@ -144,7 +143,8 @@ public class BackupManager {
*/
public CompletableFuture<BackupUploadDescriptor> createMessageBackupUploadDescriptor(
final AuthenticatedBackupUser backupUser) {
checkBackupLevel(backupUser, BackupLevel.MESSAGES);
checkBackupLevel(backupUser, BackupLevel.FREE);
checkBackupCredentialType(backupUser, BackupCredentialType.MESSAGES);
// this could race with concurrent updates, but the only effect would be last-writer-wins on the timestamp
return backupsDb
@@ -154,7 +154,8 @@ public class BackupManager {
public CompletableFuture<BackupUploadDescriptor> createTemporaryAttachmentUploadDescriptor(
final AuthenticatedBackupUser backupUser) {
checkBackupLevel(backupUser, BackupLevel.MEDIA);
checkBackupLevel(backupUser, BackupLevel.PAID);
checkBackupCredentialType(backupUser, BackupCredentialType.MEDIA);
return rateLimiters.forDescriptor(RateLimiters.For.BACKUP_ATTACHMENT)
.validateAsync(rateLimitKey(backupUser)).thenApply(ignored -> {
@@ -172,7 +173,7 @@ public class BackupManager {
* @param backupUser an already ZK authenticated backup user
*/
public CompletableFuture<Void> ttlRefresh(final AuthenticatedBackupUser backupUser) {
checkBackupLevel(backupUser, BackupLevel.MESSAGES);
checkBackupLevel(backupUser, BackupLevel.FREE);
// update message backup TTL
return backupsDb.ttlRefresh(backupUser);
}
@@ -187,7 +188,7 @@ public class BackupManager {
* @return Information about the existing backup
*/
public CompletableFuture<BackupInfo> backupInfo(final AuthenticatedBackupUser backupUser) {
checkBackupLevel(backupUser, BackupLevel.MESSAGES);
checkBackupLevel(backupUser, BackupLevel.FREE);
return backupsDb.describeBackup(backupUser)
.thenApply(backupDescription -> new BackupInfo(
backupDescription.cdn(),
@@ -210,7 +211,8 @@ public class BackupManager {
* detailing why the object could not be copied.
*/
public Flux<CopyResult> copyToBackup(final AuthenticatedBackupUser backupUser, List<CopyParameters> toCopy) {
checkBackupLevel(backupUser, BackupLevel.MEDIA);
checkBackupLevel(backupUser, BackupLevel.PAID);
checkBackupCredentialType(backupUser, BackupCredentialType.MEDIA);
return Mono
// Figure out how many objects we're allowed to copy, updating the quota usage for the amount we are allowed
@@ -349,7 +351,7 @@ public class BackupManager {
* @return A map of headers to include with CDN requests
*/
public Map<String, String> generateReadAuth(final AuthenticatedBackupUser backupUser, final int cdnNumber) {
checkBackupLevel(backupUser, BackupLevel.MESSAGES);
checkBackupLevel(backupUser, BackupLevel.FREE);
if (cdnNumber != 3) {
throw Status.INVALID_ARGUMENT.withDescription("unknown cdn").asRuntimeException();
}
@@ -377,7 +379,7 @@ public class BackupManager {
final AuthenticatedBackupUser backupUser,
final Optional<String> cursor,
final int limit) {
checkBackupLevel(backupUser, BackupLevel.MESSAGES);
checkBackupLevel(backupUser, BackupLevel.FREE);
return remoteStorageManager.list(cdnMediaDirectory(backupUser), cursor, limit)
.thenApply(result ->
new ListMediaResult(
@@ -395,7 +397,7 @@ public class BackupManager {
}
public CompletableFuture<Void> deleteEntireBackup(final AuthenticatedBackupUser backupUser) {
checkBackupLevel(backupUser, BackupLevel.MESSAGES);
checkBackupLevel(backupUser, BackupLevel.FREE);
return backupsDb
// Try to swap out the backupDir for the user
.scheduleBackupDeletion(backupUser)
@@ -408,7 +410,8 @@ public class BackupManager {
public Flux<StorageDescriptor> deleteMedia(final AuthenticatedBackupUser backupUser,
final List<StorageDescriptor> storageDescriptors) {
checkBackupLevel(backupUser, BackupLevel.MESSAGES);
checkBackupLevel(backupUser, BackupLevel.FREE);
checkBackupCredentialType(backupUser, BackupCredentialType.MEDIA);
// Check for a cdn we don't know how to process
if (storageDescriptors.stream().anyMatch(sd -> sd.cdn() != remoteStorageManager.cdnNumber())) {
@@ -492,10 +495,16 @@ public class BackupManager {
// There was no stored public key, use a bunk public key so that validation will fail
return new BackupsDb.AuthenticationData(INVALID_PUBLIC_KEY, null, null);
});
final Pair<BackupCredentialType, BackupLevel> credentialTypeAndBackupLevel =
signatureVerifier.verifySignature(signature, authenticationData.publicKey());
return new AuthenticatedBackupUser(
presentation.getBackupId(),
signatureVerifier.verifySignature(signature, authenticationData.publicKey()),
authenticationData.backupDir(), authenticationData.mediaDir());
credentialTypeAndBackupLevel.first(),
credentialTypeAndBackupLevel.second(),
authenticationData.backupDir(),
authenticationData.mediaDir());
})
.thenApply(result -> {
Metrics.counter(ZK_AUTHN_COUNTER_NAME, SUCCESS_TAG_NAME, String.valueOf(true)).increment();
@@ -579,7 +588,7 @@ public class BackupManager {
interface PresentationSignatureVerifier {
BackupLevel verifySignature(byte[] signature, ECPublicKey publicKey);
Pair<BackupCredentialType, BackupLevel> verifySignature(byte[] signature, ECPublicKey publicKey);
}
/**
@@ -611,7 +620,7 @@ public class BackupManager {
.withDescription("backup auth credential presentation signature verification failed")
.asRuntimeException();
}
return presentation.getBackupLevel();
return new Pair<>(presentation.getType(), presentation.getBackupLevel());
};
}
@@ -622,15 +631,40 @@ public class BackupManager {
* @param backupLevel The authorization level to verify the backupUser has access to
* @throws {@link Status#PERMISSION_DENIED} error if the backup user is not authorized to access {@code backupLevel}
*/
private static void checkBackupLevel(final AuthenticatedBackupUser backupUser, final BackupLevel backupLevel) {
@VisibleForTesting
static void checkBackupLevel(final AuthenticatedBackupUser backupUser, final BackupLevel backupLevel) {
if (backupUser.backupLevel().compareTo(backupLevel) < 0) {
Metrics.counter(ZK_AUTHZ_FAILURE_COUNTER_NAME).increment();
Metrics.counter(ZK_AUTHZ_FAILURE_COUNTER_NAME,
FAILURE_REASON_TAG_NAME, "level")
.increment();
throw Status.PERMISSION_DENIED
.withDescription("credential does not support the requested operation")
.asRuntimeException();
}
}
/**
* Check that the authenticated backup user is authenticated with the given credential type
*
* @param backupUser The backup user to check
* @param credentialType The credential type to require
* @throws {@link Status#UNAUTHENTICATED} error if the backup user is not authenticated with the given
* {@code credentialType}
*/
@VisibleForTesting
static void checkBackupCredentialType(final AuthenticatedBackupUser backupUser, final BackupCredentialType credentialType) {
if (backupUser.credentialType() != credentialType) {
Metrics.counter(ZK_AUTHZ_FAILURE_COUNTER_NAME,
FAILURE_REASON_TAG_NAME, "credential_type")
.increment();
throw Status.UNAUTHENTICATED
.withDescription("wrong credential type for the requested operation")
.asRuntimeException();
}
}
@VisibleForTesting
static String encodeMediaIdForCdn(final byte[] bytes) {
return Base64.getUrlEncoder().encodeToString(bytes);
@@ -87,7 +87,7 @@ public class BackupsDb {
// garbage collection of archive objects.
public static final String ATTR_LAST_REFRESH = "R";
// N: Time in seconds since epoch of the last backup media refresh. This timestamp can only be updated if the client
// has BackupLevel.MEDIA, and must be periodically updated to avoid garbage collection of media objects.
// has BackupLevel.PAID, and must be periodically updated to avoid garbage collection of media objects.
public static final String ATTR_LAST_MEDIA_REFRESH = "MR";
// B: A 32 byte public key that should be used to sign the presentation used to authenticate requests against the
// backup-id
@@ -265,7 +265,7 @@ public class BackupsDb {
* Indicates that we couldn't schedule a deletion because one was already scheduled. The caller may want to delete the
* objects directly.
*/
class PendingDeletionException extends IOException {}
static class PendingDeletionException extends IOException {}
/**
* Attempt to mark a backup as expired and swap in a new empty backupDir for the user.
@@ -285,7 +285,7 @@ public class BackupsDb {
final byte[] hashedBackupId = hashedBackupId(backupUser);
// Clear usage metadata, swap names of things we intend to delete, and record our intent to delete in attr_expired_prefix
return dynamoClient.updateItem(new UpdateBuilder(backupTableName, BackupLevel.MEDIA, hashedBackupId)
return dynamoClient.updateItem(new UpdateBuilder(backupTableName, BackupLevel.PAID, hashedBackupId)
.clearMediaUsage(clock)
.expireDirectoryNames(secureRandom, ExpiredBackup.ExpirationType.ALL)
.setRefreshTimes(Instant.ofEpochSecond(0))
@@ -300,7 +300,7 @@ public class BackupsDb {
// is toggling backups on and off. In this case, it should be pretty cheap to directly delete the backup.
// Instead of changing the backupDir, just make sure the row has expired/ timestamps and tell the caller we
// couldn't schedule the deletion.
dynamoClient.updateItem(new UpdateBuilder(backupTableName, BackupLevel.MEDIA, hashedBackupId)
dynamoClient.updateItem(new UpdateBuilder(backupTableName, BackupLevel.PAID, hashedBackupId)
.setRefreshTimes(Instant.ofEpochSecond(0))
.updateItemBuilder()
.build())
@@ -399,7 +399,7 @@ public class BackupsDb {
}
// Clear usage metadata, swap names of things we intend to delete, and record our intent to delete in attr_expired_prefix
return dynamoClient.updateItem(new UpdateBuilder(backupTableName, BackupLevel.MEDIA, expiredBackup.hashedBackupId())
return dynamoClient.updateItem(new UpdateBuilder(backupTableName, BackupLevel.PAID, expiredBackup.hashedBackupId())
.clearMediaUsage(clock)
.expireDirectoryNames(secureRandom, expiredBackup.expirationType())
.addRemoveExpression(Map.entry("#mediaRefresh", ATTR_LAST_MEDIA_REFRESH))
@@ -433,7 +433,7 @@ public class BackupsDb {
.build())
.thenRun(Util.NOOP);
} else {
return dynamoClient.updateItem(new UpdateBuilder(backupTableName, BackupLevel.MEDIA, hashedBackupId)
return dynamoClient.updateItem(new UpdateBuilder(backupTableName, BackupLevel.PAID, hashedBackupId)
.addRemoveExpression(Map.entry("#expiredPrefixes", ATTR_EXPIRED_PREFIX))
.updateItemBuilder()
.build())
@@ -722,7 +722,7 @@ public class BackupsDb {
Map.entry("#lastRefreshTime", ATTR_LAST_REFRESH),
Map.entry(":lastRefreshTime", AttributeValues.n(refreshTime.getEpochSecond())));
if (backupLevel.compareTo(BackupLevel.MEDIA) >= 0) {
if (backupLevel.compareTo(BackupLevel.PAID) >= 0) {
// update the media time if we have the appropriate level
addSetExpression("#lastMediaRefreshTime = :lastMediaRefreshTime",
Map.entry("#lastMediaRefreshTime", ATTR_LAST_MEDIA_REFRESH),
@@ -19,7 +19,6 @@ import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import javax.annotation.Nullable;
import javax.validation.constraints.NotNull;
@@ -129,7 +128,7 @@ public class Cdn3RemoteStorageManager implements RemoteStorageManager {
* Serialized copy request for cdn3 storage manager
*/
record Cdn3CopyRequest(
String encryptionKey, String hmacKey, String iv,
String encryptionKey, String hmacKey,
SourceDescriptor source, int expectedSourceLength,
String dst) {
@@ -137,7 +136,6 @@ public class Cdn3RemoteStorageManager implements RemoteStorageManager {
String dst) {
this(Base64.getEncoder().encodeToString(parameters.aesEncryptionKey().getEncoded()),
Base64.getEncoder().encodeToString(parameters.hmacSHA256Key().getEncoded()),
Base64.getEncoder().encodeToString(parameters.iv().getIV()),
source, expectedSourceLength, dst);
}
@@ -1,24 +1,22 @@
package org.whispersystems.textsecuregcm.backup;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public record MediaEncryptionParameters(
SecretKeySpec aesEncryptionKey,
SecretKeySpec hmacSHA256Key,
IvParameterSpec iv) {
SecretKeySpec hmacSHA256Key) {
public MediaEncryptionParameters(byte[] encryptionKey, byte[] macKey, byte[] iv) {
public MediaEncryptionParameters(byte[] encryptionKey, byte[] macKey) {
this(
new SecretKeySpec(encryptionKey, "AES"),
new SecretKeySpec(macKey, "HmacSHA256"),
new IvParameterSpec(iv));
new SecretKeySpec(macKey, "HmacSHA256"));
}
public int outputSize(final int inputSize) {
// AES-256 has 16-byte block size, and always adds a block if the plaintext is a multiple of the block size
final int numBlocks = (inputSize + 16) / 16;
// 16-byte IV will be generated and prepended to the ciphertext
// IV + AES-256 encrypted data + HmacSHA256
return this.iv().getIV().length + (numBlocks * 16) + 32;
return 16 + (numBlocks * 16) + 32;
}
}
@@ -1,32 +0,0 @@
/*
* Copyright 2021 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.badges;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.ResourceBundle;
import javax.annotation.Nonnull;
import org.signal.i18n.HeaderControlledResourceBundleLookup;
public class ResourceBundleLevelTranslator implements LevelTranslator {
private static final String BASE_NAME = "org.signal.subscriptions.Subscriptions";
private final HeaderControlledResourceBundleLookup headerControlledResourceBundleLookup;
public ResourceBundleLevelTranslator(
@Nonnull final HeaderControlledResourceBundleLookup headerControlledResourceBundleLookup) {
this.headerControlledResourceBundleLookup = Objects.requireNonNull(headerControlledResourceBundleLookup);
}
@Override
public String translate(final List<Locale> acceptableLanguages, final String badgeId) {
final ResourceBundle resourceBundle = headerControlledResourceBundleLookup.getResourceBundle(BASE_NAME,
acceptableLanguages);
return resourceBundle.getString(badgeId);
}
}
@@ -10,12 +10,11 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Metrics;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.ws.rs.BadRequestException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -32,20 +31,20 @@ public class CaptchaChecker {
private static final String SHORT_SUFFIX = "-short";
private final ShortCodeExpander shortCodeExpander;
private final Map<String, CaptchaClient> captchaClientMap;
private final Function<String, CaptchaClient> captchaClientSupplier;
public CaptchaChecker(
final ShortCodeExpander shortCodeRetriever,
final List<CaptchaClient> captchaClients) {
final Function<String, CaptchaClient> captchaClientSupplier) {
this.shortCodeExpander = shortCodeRetriever;
this.captchaClientMap = captchaClients.stream()
.collect(Collectors.toMap(CaptchaClient::scheme, Function.identity()));
this.captchaClientSupplier = captchaClientSupplier;
}
/**
* Check if a solved captcha should be accepted
*
* @param maybeAci optional account UUID of the user solving the captcha
* @param expectedAction the {@link Action} for which this captcha solution is intended
* @param input expected to contain a prefix indicating the captcha scheme, sitekey, token, and action. The
* expected format is {@code version-prefix.sitekey.action.token}
@@ -57,6 +56,7 @@ public class CaptchaChecker {
* @throws BadRequestException if input is not in the expected format
*/
public AssessmentResult verify(
final Optional<UUID> maybeAci,
final Action expectedAction,
final String input,
final String ip,
@@ -81,7 +81,7 @@ public class CaptchaChecker {
token = shortCodeExpander.retrieve(token).orElseThrow(() -> new BadRequestException("invalid shortcode"));
}
final CaptchaClient client = this.captchaClientMap.get(provider);
final CaptchaClient client = this.captchaClientSupplier.apply(provider);
if (client == null) {
throw new BadRequestException("invalid captcha scheme");
}
@@ -104,7 +104,7 @@ public class CaptchaChecker {
throw new BadRequestException("invalid captcha site-key");
}
final AssessmentResult result = client.verify(siteKey, parsedAction, token, ip, userAgent);
final AssessmentResult result = client.verify(maybeAci, siteKey, parsedAction, token, ip, userAgent);
Metrics.counter(ASSESSMENTS_COUNTER_NAME,
"action", action,
"score", result.getScoreString(),
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.captcha;
import java.io.IOException;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
public interface CaptchaClient {
@@ -26,6 +27,7 @@ public interface CaptchaClient {
/**
* Verify a provided captcha solution
*
* @param maybeAci optional account service identifier of the user
* @param siteKey identifying string for the captcha service
* @param action an action indicating the purpose of the captcha
* @param token the captcha solution that will be verified
@@ -35,9 +37,30 @@ public interface CaptchaClient {
* @throws IOException if the underlying captcha provider returns an error
*/
AssessmentResult verify(
final Optional<UUID> maybeAci,
final String siteKey,
final Action action,
final String token,
final String ip,
final String userAgent) throws IOException;
static CaptchaClient noop() {
return new CaptchaClient() {
@Override
public String scheme() {
return "noop";
}
@Override
public Set<String> validSiteKeys(final Action action) {
return Set.of("noop");
}
@Override
public AssessmentResult verify(final Optional<UUID> maybeAci, final String siteKey, final Action action, final String token, final String ip,
final String userAgent) throws IOException {
return AssessmentResult.alwaysValid();
}
};
}
}
@@ -1,167 +0,0 @@
/*
* Copyright 2021 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.captcha;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Metrics;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import javax.ws.rs.core.Response;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicCaptchaConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.SystemMapper;
public class HCaptchaClient implements CaptchaClient {
private static final Logger logger = LoggerFactory.getLogger(HCaptchaClient.class);
private static final String PREFIX = "signal-hcaptcha";
private static final String ASSESSMENT_REASON_COUNTER_NAME = name(HCaptchaClient.class, "assessmentReason");
private static final String INVALID_REASON_COUNTER_NAME = name(HCaptchaClient.class, "invalidReason");
private final String apiKey;
private final FaultTolerantHttpClient client;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
@VisibleForTesting
HCaptchaClient(final String apiKey,
final FaultTolerantHttpClient faultTolerantHttpClient,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
this.apiKey = apiKey;
this.client = faultTolerantHttpClient;
this.dynamicConfigurationManager = dynamicConfigurationManager;
}
public HCaptchaClient(
final String apiKey,
final ScheduledExecutorService retryExecutor,
final ExecutorService httpExecutor,
final CircuitBreakerConfiguration circuitBreakerConfiguration,
final RetryConfiguration retryConfiguration,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
this(apiKey,
FaultTolerantHttpClient.newBuilder()
.withName("hcaptcha")
.withCircuitBreaker(circuitBreakerConfiguration)
.withExecutor(httpExecutor)
.withRetryExecutor(retryExecutor)
.withRetry(retryConfiguration)
.withRetryOnException(ex -> ex instanceof IOException)
.withConnectTimeout(Duration.ofSeconds(10))
.withVersion(HttpClient.Version.HTTP_2)
.build(),
dynamicConfigurationManager);
}
@Override
public String scheme() {
return PREFIX;
}
@Override
public Set<String> validSiteKeys(final Action action) {
final DynamicCaptchaConfiguration config = dynamicConfigurationManager.getConfiguration().getCaptchaConfiguration();
if (!config.isAllowHCaptcha()) {
logger.warn("Received request to verify an hCaptcha, but hCaptcha is not enabled");
return Collections.emptySet();
}
return Optional
.ofNullable(config.getHCaptchaSiteKeys().get(action))
.orElse(Collections.emptySet());
}
@Override
public AssessmentResult verify(
final String siteKey,
final Action action,
final String token,
final String ip,
final String userAgent)
throws IOException {
final DynamicCaptchaConfiguration config = dynamicConfigurationManager.getConfiguration().getCaptchaConfiguration();
final String body = String.format("response=%s&secret=%s&remoteip=%s",
URLEncoder.encode(token, StandardCharsets.UTF_8),
URLEncoder.encode(this.apiKey, StandardCharsets.UTF_8),
ip);
final HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://hcaptcha.com/siteverify"))
.header("Content-Type", "application/x-www-form-urlencoded")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
final HttpResponse<String> response;
try {
response = this.client.sendAsync(request, HttpResponse.BodyHandlers.ofString()).join();
} catch (CompletionException e) {
logger.warn("failed to make http request to hCaptcha: {}", e.getMessage());
throw new IOException(ExceptionUtils.unwrap(e));
}
if (response.statusCode() != Response.Status.OK.getStatusCode()) {
logger.warn("failure submitting token to hCaptcha (code={}): {}", response.statusCode(), response);
throw new IOException("hCaptcha http failure : " + response.statusCode());
}
final HCaptchaResponse hCaptchaResponse = SystemMapper.jsonMapper()
.readValue(response.body(), HCaptchaResponse.class);
logger.debug("received hCaptcha response: {}", hCaptchaResponse);
if (!hCaptchaResponse.success) {
for (String errorCode : hCaptchaResponse.errorCodes) {
Metrics.counter(INVALID_REASON_COUNTER_NAME, Tags.of(
Tag.of("action", action.getActionName()),
Tag.of("reason", errorCode),
UserAgentTagUtil.getPlatformTag(userAgent)
)).increment();
}
return AssessmentResult.invalid();
}
// hcaptcha uses the inverse scheme of recaptcha (for hcaptcha, a low score is less risky)
final float score = 1.0f - hCaptchaResponse.score;
if (score < 0.0f || score > 1.0f) {
logger.error("Invalid score {} from hcaptcha response {}", hCaptchaResponse.score, hCaptchaResponse);
return AssessmentResult.invalid();
}
final BigDecimal threshold = config.getScoreFloorByAction().getOrDefault(action, config.getScoreFloor());
final AssessmentResult assessmentResult = AssessmentResult.fromScore(score, threshold.floatValue());
for (String reason : hCaptchaResponse.scoreReasons) {
Metrics.counter(ASSESSMENT_REASON_COUNTER_NAME,
"action", action.getActionName(),
"reason", reason,
"score", assessmentResult.getScoreString()).increment();
}
return assessmentResult;
}
}
@@ -1,52 +0,0 @@
/*
* Copyright 2022 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.captcha;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.Instant;
import java.util.Collections;
import java.util.List;
/**
* Verify response returned by hcaptcha
* <p>
* see <a href="https://docs.hcaptcha.com/#verify-the-user-response-server-side">...</a>
*/
public class HCaptchaResponse {
@JsonProperty
boolean success;
@JsonProperty(value = "challenge_ts")
Instant challengeTs;
@JsonProperty
String hostname;
@JsonProperty(value = "error-codes")
List<String> errorCodes = Collections.emptyList();
@JsonProperty
float score;
@JsonProperty(value = "score_reason")
List<String> scoreReasons = Collections.emptyList();
public HCaptchaResponse() {
}
@Override
public String toString() {
return "HCaptchaResponse{" +
"success=" + success +
", challengeTs=" + challengeTs +
", hostname='" + hostname + '\'' +
", errorCodes=" + errorCodes +
", score=" + score +
", scoreReasons=" + scoreReasons +
'}';
}
}
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.captcha;
import java.io.IOException;
import java.util.Optional;
import java.util.UUID;
public class RegistrationCaptchaManager {
@@ -17,10 +18,10 @@ public class RegistrationCaptchaManager {
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public Optional<AssessmentResult> assessCaptcha(final Optional<String> captcha, final String sourceHost, final String userAgent)
public Optional<AssessmentResult> assessCaptcha(final Optional<UUID> aci, final Optional<String> captcha, final String sourceHost, final String userAgent)
throws IOException {
return captcha.isPresent()
? Optional.of(captchaChecker.verify(Action.REGISTRATION, captcha.get(), sourceHost, userAgent))
? Optional.of(captchaChecker.verify(aci, Action.REGISTRATION, captcha.get(), sourceHost, userAgent))
: Optional.empty();
}
}
@@ -1,43 +0,0 @@
package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.concurrent.ScheduledExecutorService;
import javax.validation.constraints.NotEmpty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
@JsonTypeName("default")
public class AppConfigConfiguration implements DynamicConfigurationManagerFactory {
@JsonProperty
@NotEmpty
private String application;
@JsonProperty
@NotEmpty
private String environment;
@JsonProperty
@NotEmpty
private String configuration;
public String getApplication() {
return application;
}
public String getEnvironment() {
return environment;
}
public String getConfigurationName() {
return configuration;
}
@Override
public <T> DynamicConfigurationManager<T> build(Class<T> klazz, ScheduledExecutorService scheduledExecutorService,
AwsCredentialsProvider awsCredentialsProvider) {
return new DynamicConfigurationManager<>(application, environment, configuration, awsCredentialsProvider, klazz,
scheduledExecutorService);
}
}
@@ -1,19 +0,0 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import io.dropwizard.jackson.Discoverable;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import java.util.concurrent.ScheduledExecutorService;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = AppConfigConfiguration.class)
public interface DynamicConfigurationManagerFactory extends Discoverable {
<T> DynamicConfigurationManager<T> build(Class<T> configurationClass,
ScheduledExecutorService scheduledExecutorService, AwsCredentialsProvider awsCredentialsProvider);
}
@@ -1,21 +0,0 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import io.dropwizard.jackson.Discoverable;
import org.whispersystems.textsecuregcm.captcha.HCaptchaClient;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = HCaptchaConfiguration.class)
public interface HCaptchaClientFactory extends Discoverable {
HCaptchaClient build(ScheduledExecutorService retryExecutor, ExecutorService httpExecutor,
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager);
}
@@ -1,62 +0,0 @@
/*
* Copyright 2021 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import com.fasterxml.jackson.annotation.JsonTypeName;
import org.whispersystems.textsecuregcm.captcha.HCaptchaClient;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
@JsonTypeName("default")
public class HCaptchaConfiguration implements HCaptchaClientFactory {
@JsonProperty
@NotNull
SecretString apiKey;
@JsonProperty
@NotNull
@Valid
CircuitBreakerConfiguration circuitBreaker = new CircuitBreakerConfiguration();
@JsonProperty
@NotNull
@Valid
RetryConfiguration retry = new RetryConfiguration();
public SecretString getApiKey() {
return apiKey;
}
public CircuitBreakerConfiguration getCircuitBreaker() {
return circuitBreaker;
}
public RetryConfiguration getRetry() {
return retry;
}
@Override
public HCaptchaClient build(
final ScheduledExecutorService retryExecutor,
final ExecutorService httpExecutor,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
return new HCaptchaClient(
apiKey.value(),
retryExecutor,
httpExecutor,
circuitBreaker,
retry,
dynamicConfigurationManager);
}
}
@@ -5,9 +5,13 @@
package org.whispersystems.textsecuregcm.configuration;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Positive;
public record KeyTransparencyServiceConfiguration(@NotBlank String host,
@Positive int port,
@NotBlank String tlsCertificate) {}
@NotBlank String tlsCertificate,
@NotBlank String clientCertificate,
@NotNull SecretString clientPrivateKey) {}
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.controllers;
import io.dropwizard.auth.Auth;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import java.util.Base64;
import java.util.Objects;
@@ -19,6 +20,7 @@ import javax.validation.constraints.NotNull;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.ForbiddenException;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.HeaderParam;
@@ -27,6 +29,7 @@ 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.MediaType;
import javax.ws.rs.core.Response;
@@ -57,6 +60,7 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableException;
import org.whispersystems.textsecuregcm.storage.UsernameReservationNotFoundException;
@@ -192,10 +196,39 @@ public class AccountController {
@PUT
@Path("/name/")
public void setName(@Mutable @Auth AuthenticatedDevice auth, @NotNull @Valid DeviceName deviceName) {
Account account = auth.getAccount();
Device device = auth.getAuthenticatedDevice();
accounts.updateDevice(account, device.getId(), d -> d.setName(deviceName.getDeviceName()));
@Operation(summary = "Set a device's encrypted name",
description = """
Sets the encrypted name for the specified device. Primary devices may change the name of any device associated
with their account, but linked devices may only change their own name. If no device ID is specified, then the
authenticated device's ID will be used.
""")
@ApiResponse(responseCode = "204", description = "Device name changed successfully")
@ApiResponse(responseCode = "404", description = "No device found with the given ID")
@ApiResponse(responseCode = "403", description = "Not authorized to change the name of the device with the given ID")
public void setName(@Mutable @Auth final AuthenticatedDevice auth,
@NotNull @Valid final DeviceName deviceName,
@Nullable
@QueryParam("deviceId")
@Schema(description = "The ID of the device for which to set a name; if omitted, the authenticated device will be targeted for a name change",
requiredMode = Schema.RequiredMode.NOT_REQUIRED)
final Byte deviceId) {
final Account account = auth.getAccount();
final byte targetDeviceId = deviceId == null ? auth.getAuthenticatedDevice().getId() : deviceId;
if (account.getDevice(targetDeviceId).isEmpty()) {
throw new NotFoundException();
}
final boolean mayChangeName = auth.getAuthenticatedDevice().isPrimary() ||
auth.getAuthenticatedDevice().getId() == targetDeviceId;
if (!mayChangeName) {
throw new ForbiddenException();
}
accounts.updateDevice(account, targetDeviceId, d -> d.setName(deviceName.deviceName()));
}
@PUT
@@ -250,7 +283,7 @@ public class AccountController {
auth.getAccount().getPhoneNumberIdentifier(),
auth.getAccount().getUsernameHash().filter(h -> h.length > 0).orElse(null),
auth.getAccount().getUsernameLinkHandle(),
auth.getAccount().isStorageSupported());
auth.getAccount().hasCapability(DeviceCapability.STORAGE));
}
@DELETE
@@ -54,6 +54,7 @@ import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.websocket.auth.Mutable;
import org.whispersystems.websocket.auth.ReadOnly;
@@ -151,7 +152,7 @@ public class AccountControllerV2 {
updatedAccount.getPhoneNumberIdentifier(),
updatedAccount.getUsernameHash().orElse(null),
updatedAccount.getUsernameLinkHandle(),
updatedAccount.isStorageSupported());
updatedAccount.hasCapability(DeviceCapability.STORAGE));
} catch (MismatchedDevicesException e) {
throw new WebApplicationException(Response.status(409)
.type(MediaType.APPLICATION_JSON_TYPE)
@@ -210,7 +211,7 @@ public class AccountControllerV2 {
updatedAccount.getPhoneNumberIdentifier(),
updatedAccount.getUsernameHash().orElse(null),
updatedAccount.getUsernameLinkHandle(),
updatedAccount.isStorageSupported());
updatedAccount.hasCapability(DeviceCapability.STORAGE));
} catch (MismatchedDevicesException e) {
throw new WebApplicationException(Response.status(409)
.type(MediaType.APPLICATION_JSON_TYPE)
@@ -5,11 +5,14 @@
package org.whispersystems.textsecuregcm.controllers;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.auth.Auth;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
@@ -23,11 +26,16 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.validation.Valid;
import javax.validation.constraints.Max;
@@ -52,6 +60,7 @@ import org.signal.libsignal.protocol.ecc.ECPublicKey;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialPresentation;
import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialRequest;
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
@@ -89,11 +98,21 @@ public class ArchiveController {
public record SetBackupIdRequest(
@Schema(description = """
A BackupAuthCredentialRequest containing a blinded encrypted backup-id, encoded in standard padded base64
A BackupAuthCredentialRequest containing a blinded encrypted backup-id, encoded in standard padded base64.
This backup-id should be used for message backups only, and must have the message backup type set on the
credential.
""", implementation = String.class)
@JsonDeserialize(using = BackupAuthCredentialAdapter.CredentialRequestDeserializer.class)
@JsonSerialize(using = BackupAuthCredentialAdapter.CredentialRequestSerializer.class)
@NotNull BackupAuthCredentialRequest backupAuthCredentialRequest) {}
@NotNull BackupAuthCredentialRequest messagesBackupAuthCredentialRequest,
@Schema(description = """
A BackupAuthCredentialRequest containing a blinded encrypted backup-id, encoded in standard padded base64.
This backup-id should be used for media only, and must have the media type set on the credential.
""", implementation = String.class)
@JsonDeserialize(using = BackupAuthCredentialAdapter.CredentialRequestDeserializer.class)
@JsonSerialize(using = BackupAuthCredentialAdapter.CredentialRequestSerializer.class)
@NotNull BackupAuthCredentialRequest mediaBackupAuthCredentialRequest) {}
@PUT
@@ -115,8 +134,10 @@ public class ArchiveController {
public CompletionStage<Response> setBackupId(
@Mutable @Auth final AuthenticatedDevice account,
@Valid @NotNull final SetBackupIdRequest setBackupIdRequest) throws RateLimitExceededException {
return this.backupAuthManager
.commitBackupId(account.getAccount(), setBackupIdRequest.backupAuthCredentialRequest)
.commitBackupId(account.getAccount(), setBackupIdRequest.messagesBackupAuthCredentialRequest,
setBackupIdRequest.mediaBackupAuthCredentialRequest)
.thenApply(Util.ASYNC_EMPTY_RESPONSE);
}
@@ -166,8 +187,31 @@ public class ArchiveController {
}
public record BackupAuthCredentialsResponse(
@Schema(description = "A list of BackupAuthCredentials and their validity periods")
List<BackupAuthCredential> credentials) {
@Schema(description = "A map of credential types to lists of BackupAuthCredentials and their validity periods")
Map<CredentialType, List<BackupAuthCredential>> credentials) {
public enum CredentialType {
MESSAGES,
MEDIA;
@JsonValue
public String toValue() {
return this.name().toLowerCase(Locale.ROOT);
}
@JsonCreator
public static CredentialType fromValue(String v) {
return v == null ? null : CredentialType.valueOf(v.toUpperCase(Locale.ROOT));
}
@VisibleForTesting
static CredentialType fromLibsignalType(BackupCredentialType backupCredentialType) {
return switch (backupCredentialType) {
case MESSAGES -> BackupAuthCredentialsResponse.CredentialType.MESSAGES;
case MEDIA -> BackupAuthCredentialsResponse.CredentialType.MEDIA;
};
}
}
public record BackupAuthCredential(
@Schema(description = "A BackupAuthCredential, encoded in standard padded base64")
@@ -202,14 +246,24 @@ public class ArchiveController {
@NotNull @QueryParam("redemptionStartSeconds") Long startSeconds,
@NotNull @QueryParam("redemptionEndSeconds") Long endSeconds) {
return this.backupAuthManager.getBackupAuthCredentials(
auth.getAccount(),
Instant.ofEpochSecond(startSeconds), Instant.ofEpochSecond(endSeconds))
.thenApply(creds -> new BackupAuthCredentialsResponse(creds.stream()
.map(cred -> new BackupAuthCredentialsResponse.BackupAuthCredential(
cred.credential().serialize(),
cred.redemptionTime().getEpochSecond()))
.toList()));
final Map<BackupCredentialType, List<BackupAuthCredentialsResponse.BackupAuthCredential>> credentialsByType =
new ConcurrentHashMap<>();
return CompletableFuture.allOf(Arrays.stream(BackupCredentialType.values())
.map(credentialType -> this.backupAuthManager.getBackupAuthCredentials(
auth.getAccount(),
credentialType,
Instant.ofEpochSecond(startSeconds), Instant.ofEpochSecond(endSeconds))
.thenAccept(credentials -> credentialsByType.put(credentialType, credentials.stream()
.map(credential -> new BackupAuthCredentialsResponse.BackupAuthCredential(
credential.credential().serialize(),
credential.redemptionTime().getEpochSecond()))
.toList())))
.toArray(CompletableFuture[]::new))
.thenApply(ignored -> new BackupAuthCredentialsResponse(credentialsByType.entrySet().stream()
.collect(Collectors.toMap(
e -> BackupAuthCredentialsResponse.CredentialType.fromLibsignalType(e.getKey()),
Map.Entry::getValue))));
}
@@ -227,7 +281,8 @@ public class ArchiveController {
@ApiResponse(responseCode = "401", description = """
The provided backup auth credential presentation could not be verified or
The public key signature was invalid or
There is no backup associated with the backup-id in the presentation""")
There is no backup associated with the backup-id in the presentation or
The credential was of the wrong type (messages/media)""")
@ApiResponse(responseCode = "400", description = "Bad arguments. The request may have been made on an authenticated channel")
@interface ApiResponseZkAuth {}
@@ -453,7 +508,7 @@ public class ArchiveController {
throw new BadRequestException("must not use authenticated connection for anonymous operations");
}
return backupManager.authenticateBackupUser(presentation.presentation, signature.signature)
.thenCompose(backupUser -> backupManager.createTemporaryAttachmentUploadDescriptor(backupUser))
.thenCompose(backupManager::createTemporaryAttachmentUploadDescriptor)
.thenApply(result -> new UploadDescriptorResponse(
result.cdn(),
result.key(),
@@ -489,19 +544,13 @@ public class ArchiveController {
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
@NotNull
@ExactlySize(32)
byte[] encryptionKey,
@Schema(description = "A 16-byte IV for AES, encoded in standard padded base64", implementation = String.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
@NotNull
@ExactlySize(16)
byte[] iv) {
byte[] encryptionKey) {
CopyParameters toCopyParameters() {
return new CopyParameters(
sourceAttachment.cdn(), sourceAttachment.key(),
objectLength,
new MediaEncryptionParameters(encryptionKey, hmacKey, iv),
new MediaEncryptionParameters(encryptionKey, hmacKey),
mediaId);
}
}
@@ -16,19 +16,24 @@ import io.swagger.v3.oas.annotations.headers.Header;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.ws.rs.Consumes;
@@ -46,24 +51,25 @@ 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;
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
import org.whispersystems.textsecuregcm.auth.ChangesLinkedDevices;
import org.whispersystems.textsecuregcm.auth.LinkedDeviceRefreshRequirementProvider;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.entities.DeviceActivationRequest;
import org.whispersystems.textsecuregcm.entities.DeviceInfo;
import org.whispersystems.textsecuregcm.entities.DeviceInfoList;
import org.whispersystems.textsecuregcm.entities.LinkDeviceResponse;
import org.whispersystems.textsecuregcm.entities.LinkDeviceRequest;
import org.whispersystems.textsecuregcm.entities.LinkDeviceResponse;
import org.whispersystems.textsecuregcm.entities.PreKeySignatureValidator;
import org.whispersystems.textsecuregcm.entities.ProvisioningMessage;
import org.whispersystems.textsecuregcm.entities.RemoteAttachment;
import org.whispersystems.textsecuregcm.entities.RestoreAccountRequest;
import org.whispersystems.textsecuregcm.entities.SetPublicKeyRequest;
import org.whispersystems.textsecuregcm.entities.TransferArchiveUploadedRequest;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
@@ -71,9 +77,10 @@ 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.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.DeviceSpec;
import org.whispersystems.textsecuregcm.storage.LinkDeviceTokenAlreadyUsedException;
import org.whispersystems.textsecuregcm.util.DeviceCapabilityAdapter;
import org.whispersystems.textsecuregcm.util.EnumMapUtil;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.LinkDeviceToken;
@@ -267,7 +274,7 @@ public class DeviceController {
throw new DeviceLimitExceededException(account.getDevices().size(), maxDeviceLimit);
}
final DeviceCapabilities capabilities = accountAttributes.getCapabilities();
final Set<DeviceCapability> capabilities = accountAttributes.getCapabilities();
if (capabilities == null) {
throw new WebApplicationException(Response.status(422, "Missing device capabilities").build());
@@ -402,10 +409,15 @@ public class DeviceController {
@PUT
@Produces(MediaType.APPLICATION_JSON)
@Path("/capabilities")
public void setCapabilities(@Mutable @Auth AuthenticatedDevice auth, @NotNull @Valid DeviceCapabilities capabilities) {
public void setCapabilities(@Mutable @Auth final AuthenticatedDevice auth,
@NotNull
final Map<String, Boolean> capabilities) {
assert (auth.getAuthenticatedDevice() != null);
final byte deviceId = auth.getAuthenticatedDevice().getId();
accounts.updateDevice(auth.getAccount(), deviceId, d -> d.setCapabilities(capabilities));
accounts.updateDevice(auth.getAccount(), deviceId,
d -> d.setCapabilities(DeviceCapabilityAdapter.mapToSet(capabilities)));
}
@PUT
@@ -430,11 +442,77 @@ public class DeviceController {
setPublicKeyRequest.publicKey());
}
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 boolean isCapabilityDowngrade(final Account account, final Set<DeviceCapability> capabilities) {
final Set<DeviceCapability> requiredCapabilities = Arrays.stream(DeviceCapability.values())
.filter(DeviceCapability::preventDowngrade)
.filter(account::hasCapability)
.collect(Collectors.toSet());
return !capabilities.containsAll(requiredCapabilities);
}
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/restore_account/{token}")
@Operation(
summary = "Signals that a new device is requesting restoration of account data by some method",
description = """
Signals that a new device is requesting restoration of account data by some method. Devices waiting via the
"wait for 'restore account' request" endpoint will be notified that the request has been issued.
""")
@ApiResponse(responseCode = "204", description = "Success")
@ApiResponse(responseCode = "422", description = "The request object could not be parsed or was otherwise invalid")
@ApiResponse(responseCode = "429", description = "Rate-limited; try again after the prescribed delay")
@RateLimitedByIp(RateLimiters.For.RECORD_DEVICE_TRANSFER_REQUEST)
public CompletionStage<Void> recordRestoreAccountRequest(
@PathParam("token")
@NotBlank
@Size(max = 64)
@Schema(description = "A randomly-generated token identifying the request for device-to-device transfer.",
requiredMode = Schema.RequiredMode.REQUIRED,
maximum = "64") final String token,
@Valid
final RestoreAccountRequest restoreAccountRequest) {
return accounts.recordRestoreAccountRequest(token, restoreAccountRequest);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/restore_account/{token}")
@Operation(summary = "Wait for 'restore account' request")
@ApiResponse(responseCode = "200", description = "A 'restore account' request was received for the given token",
content = @Content(schema = @Schema(implementation = RestoreAccountRequest.class)))
@ApiResponse(responseCode = "204", description = "No 'restore account' request for the given token was received before the call completed; clients may repeat the call to continue waiting")
@ApiResponse(responseCode = "400", description = "The given token or timeout was invalid")
@ApiResponse(responseCode = "429", description = "Rate-limited; try again after the prescribed delay")
@RateLimitedByIp(RateLimiters.For.WAIT_FOR_DEVICE_TRANSFER_REQUEST)
public CompletionStage<Response> waitForDeviceTransferRequest(
@PathParam("token")
@NotBlank
@Size(max = 64)
@Schema(description = "A randomly-generated token identifying the request for device-to-device transfer.",
requiredMode = Schema.RequiredMode.REQUIRED,
maximum = "64") final String token,
@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 a transfer archive for the authenticated
device is not available within the given amount of time, this endpoint will return a status of HTTP/204.
""") final int timeoutSeconds) {
return accounts.waitForRestoreAccountRequest(token, Duration.ofSeconds(timeoutSeconds))
.thenApply(maybeRequestReceived -> maybeRequestReceived
.map(restoreAccountRequest -> Response.status(Response.Status.OK).entity(restoreAccountRequest).build())
.orElseGet(() -> Response.status(Response.Status.NO_CONTENT).build()));
}
@PUT
@@ -23,6 +23,7 @@ import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
import org.whispersystems.websocket.auth.ReadOnly;
import org.whispersystems.websocket.session.WebSocketSession;
import org.whispersystems.websocket.session.WebSocketSessionContext;
@@ -34,14 +35,14 @@ public class KeepAliveController {
private final Logger logger = LoggerFactory.getLogger(KeepAliveController.class);
private final ClientPresenceManager clientPresenceManager;
private final PubSubClientEventManager pubSubClientEventManager;
private static final String CLOSED_CONNECTION_AGE_DISTRIBUTION_NAME = name(KeepAliveController.class,
"closedConnectionAge");
public KeepAliveController(final ClientPresenceManager clientPresenceManager) {
this.clientPresenceManager = clientPresenceManager;
public KeepAliveController(final PubSubClientEventManager pubSubClientEventManager) {
this.pubSubClientEventManager = pubSubClientEventManager;
}
@GET
@@ -49,7 +50,7 @@ public class KeepAliveController {
@WebSocketSession WebSocketSessionContext context) {
maybeAuth.ifPresent(auth -> {
if (!clientPresenceManager.isLocallyPresent(auth.getAccount().getUuid(), auth.getAuthenticatedDevice().getId())) {
if (!pubSubClientEventManager.isLocallyPresent(auth.getAccount().getUuid(), auth.getAuthenticatedDevice().getId())) {
final Duration age = Duration.between(context.getClient().getCreated(), Instant.now());
@@ -11,12 +11,38 @@ import io.dropwizard.auth.Auth;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
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.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletionException;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Positive;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.ForbiddenException;
import javax.ws.rs.GET;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.ServerErrorException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.signal.keytransparency.client.E164SearchRequest;
import org.signal.keytransparency.client.MonitorKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.entities.KeyTransparencyDistinguishedKeyResponse;
import org.whispersystems.textsecuregcm.entities.KeyTransparencyMonitorRequest;
import org.whispersystems.textsecuregcm.entities.KeyTransparencyMonitorResponse;
import org.whispersystems.textsecuregcm.entities.KeyTransparencySearchRequest;
@@ -27,28 +53,6 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.websocket.auth.ReadOnly;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.ForbiddenException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.ServerErrorException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
@Path("/v1/key-transparency")
@Tag(name = "KeyTransparency")
public class KeyTransparencyController {
@@ -56,8 +60,10 @@ public class KeyTransparencyController {
private static final Logger LOGGER = LoggerFactory.getLogger(KeyTransparencyController.class);
@VisibleForTesting
static final Duration KEY_TRANSPARENCY_RPC_TIMEOUT = Duration.ofSeconds(15);
private static final byte USERNAME_PREFIX = (byte) 'u';
private static final byte E164_PREFIX = (byte) 'n';
@VisibleForTesting
static final byte USERNAME_PREFIX = (byte) 'u';
@VisibleForTesting
static final byte E164_PREFIX = (byte) 'n';
@VisibleForTesting
static final byte ACI_PREFIX = (byte) 'a';
private final KeyTransparencyServiceClient keyTransparencyServiceClient;
@@ -68,16 +74,25 @@ public class KeyTransparencyController {
}
@Operation(
summary = "Search for the given search keys in the key transparency log",
summary = "Search for the given identifiers in the key transparency log",
description = """
Enforced unauthenticated endpoint. Returns a response if all search keys exist in the key transparency log.
Returns a response if the ACI exists in the transparency log and its mapped value matches the provided
ACI identity key.
The username hash search response field is populated if it is found in the log and its mapped value matches
the provided ACI. The E164 search response is populated similarly, with some additional requirements:
- The account associated with the provided ACI must be discoverable by phone number.
- The provided unidentified access key must match the one on the account.
Enforced unauthenticated endpoint.
"""
)
@ApiResponse(responseCode = "200", description = "All search key lookups were successful", useReturnTypeSchema = true)
@ApiResponse(responseCode = "403", description = "At least one search key lookup to value mapping was invalid")
@ApiResponse(responseCode = "404", description = "At least one search key lookup did not find the key")
@ApiResponse(responseCode = "413", description = "Ratelimited")
@ApiResponse(responseCode = "200", description = "The ACI was found and its mapped value matched the provided ACI identity key", useReturnTypeSchema = true)
@ApiResponse(responseCode = "400", description = "Invalid request. See response for any available details.")
@ApiResponse(responseCode = "403", description = "The ACI was found but its mapped value did not match the provided ACI identity key")
@ApiResponse(responseCode = "404", description = "The ACI was not found in the log")
@ApiResponse(responseCode = "422", description = "Invalid request format")
@ApiResponse(responseCode = "429", description = "Rate-limited")
@POST
@Path("/search")
@RateLimitedByIp(RateLimiters.For.KEY_TRANSPARENCY_SEARCH_PER_IP)
@@ -90,35 +105,23 @@ public class KeyTransparencyController {
requireNotAuthenticated(authenticatedAccount);
try {
final CompletableFuture<byte[]> aciSearchKeyResponseFuture = keyTransparencyServiceClient.search(
getFullSearchKeyByteString(ACI_PREFIX, request.aci().toCompactByteArray()),
request.lastTreeHeadSize(),
request.distinguishedTreeHeadSize(),
KEY_TRANSPARENCY_RPC_TIMEOUT);
final Optional<E164SearchRequest> maybeE164SearchRequest =
request.e164().flatMap(e164 -> request.unidentifiedAccessKey().map(uak ->
E164SearchRequest.newBuilder()
.setE164(e164)
.setUnidentifiedAccessKey(ByteString.copyFrom(request.unidentifiedAccessKey().get()))
.build()
));
final CompletableFuture<byte[]> e164SearchKeyResponseFuture = request.e164()
.map(e164 -> keyTransparencyServiceClient.search(
getFullSearchKeyByteString(E164_PREFIX, e164.getBytes(StandardCharsets.UTF_8)),
return keyTransparencyServiceClient.search(
ByteString.copyFrom(request.aci().toCompactByteArray()),
ByteString.copyFrom(request.aciIdentityKey().serialize()),
request.usernameHash().map(ByteString::copyFrom),
maybeE164SearchRequest,
request.lastTreeHeadSize(),
request.distinguishedTreeHeadSize(),
KEY_TRANSPARENCY_RPC_TIMEOUT))
.orElse(CompletableFuture.completedFuture(null));
final CompletableFuture<byte[]> usernameHashSearchKeyResponseFuture = request.usernameHash()
.map(usernameHash -> keyTransparencyServiceClient.search(
getFullSearchKeyByteString(USERNAME_PREFIX, request.usernameHash().get()),
request.lastTreeHeadSize(),
request.distinguishedTreeHeadSize(),
KEY_TRANSPARENCY_RPC_TIMEOUT))
.orElse(CompletableFuture.completedFuture(null));
return CompletableFuture.allOf(aciSearchKeyResponseFuture, e164SearchKeyResponseFuture,
usernameHashSearchKeyResponseFuture)
.thenApply(ignored ->
new KeyTransparencySearchResponse(aciSearchKeyResponseFuture.join(),
Optional.ofNullable(e164SearchKeyResponseFuture.join()),
Optional.ofNullable(usernameHashSearchKeyResponseFuture.join())))
.join();
KEY_TRANSPARENCY_RPC_TIMEOUT)
.thenApply(KeyTransparencySearchResponse::new).join();
} catch (final CancellationException exception) {
LOGGER.error("Unexpected cancellation from key transparency service", exception);
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE, exception);
@@ -130,15 +133,16 @@ public class KeyTransparencyController {
}
@Operation(
summary = "Monitor the given search keys in the key transparency log",
summary = "Monitor the given identifiers in the key transparency log",
description = """
Enforced unauthenticated endpoint. Return proofs proving that the log tree
has been constructed correctly in later entries for each of the given search keys .
Return proofs proving that the log tree has been constructed correctly in later entries for each of the given
identifiers. Enforced unauthenticated endpoint.
"""
)
@ApiResponse(responseCode = "200", description = "All search keys exist in the log", useReturnTypeSchema = true)
@ApiResponse(responseCode = "400", description = "Invalid request. See response for any available details.")
@ApiResponse(responseCode = "404", description = "At least one search key lookup did not find the key")
@ApiResponse(responseCode = "413", description = "Ratelimited")
@ApiResponse(responseCode = "429", description = "Rate-limited")
@ApiResponse(responseCode = "422", description = "Invalid request format")
@POST
@Path("/monitor")
@@ -153,20 +157,19 @@ public class KeyTransparencyController {
try {
final List<MonitorKey> monitorKeys = new ArrayList<>(List.of(
createMonitorKey(getFullSearchKeyByteString(ACI_PREFIX, request.aci().toCompactByteArray()),
request.aciPositions())
createMonitorKey(getFullSearchKeyByteString(ACI_PREFIX, request.aci().value().toCompactByteArray()),
request.aci().positions(),
ByteString.copyFrom(request.aci().commitmentIndex()))
));
request.usernameHash().ifPresent(usernameHash ->
monitorKeys.add(createMonitorKey(getFullSearchKeyByteString(USERNAME_PREFIX, usernameHash),
request.usernameHashPositions().get()))
);
monitorKeys.add(createMonitorKey(getFullSearchKeyByteString(USERNAME_PREFIX, usernameHash.value()),
usernameHash.positions(), ByteString.copyFrom(usernameHash.commitmentIndex()))));
request.e164().ifPresent(e164 ->
monitorKeys.add(
createMonitorKey(getFullSearchKeyByteString(E164_PREFIX, e164.getBytes(StandardCharsets.UTF_8)),
request.e164Positions().get()))
);
createMonitorKey(getFullSearchKeyByteString(E164_PREFIX, e164.value().getBytes(StandardCharsets.UTF_8)),
e164.positions(), ByteString.copyFrom(e164.commitmentIndex()))));
return new KeyTransparencyMonitorResponse(keyTransparencyServiceClient.monitor(
monitorKeys,
@@ -183,6 +186,45 @@ public class KeyTransparencyController {
return null;
}
@Operation(
summary = "Get the current value of the distinguished key",
description = """
The response contains the distinguished tree head to prove consistency
against for future calls to `/search`, `/monitor`, and `/distinguished`.
Enforced unauthenticated endpoint.
"""
)
@ApiResponse(responseCode = "200", description = "The `distinguished` search key exists in the log", useReturnTypeSchema = true)
@ApiResponse(responseCode = "400", description = "Invalid request. See response for any available details.")
@ApiResponse(responseCode = "422", description = "Invalid request format")
@ApiResponse(responseCode = "429", description = "Rate-limited")
@GET
@Path("/distinguished")
@RateLimitedByIp(RateLimiters.For.KEY_TRANSPARENCY_DISTINGUISHED_PER_IP)
@Produces(MediaType.APPLICATION_JSON)
public KeyTransparencyDistinguishedKeyResponse getDistinguishedKey(
@ReadOnly @Auth final Optional<AuthenticatedDevice> authenticatedAccount,
@Parameter(description = "The distinguished tree head size returned by a previously verified call")
@QueryParam("lastTreeHeadSize") @Valid final Optional<@Positive Long> lastTreeHeadSize) {
// Disallow clients from making authenticated requests to this endpoint
requireNotAuthenticated(authenticatedAccount);
try {
return keyTransparencyServiceClient.getDistinguishedKey(lastTreeHeadSize, KEY_TRANSPARENCY_RPC_TIMEOUT)
.thenApply(KeyTransparencyDistinguishedKeyResponse::new)
.join();
} catch (final CancellationException exception) {
LOGGER.error("Unexpected cancellation from key transparency service", exception);
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE, exception);
} catch (final CompletionException exception) {
handleKeyTransparencyServiceError(exception);
}
// This is unreachable
return null;
}
private void handleKeyTransparencyServiceError(final CompletionException exception) {
final Throwable unwrapped = ExceptionUtils.unwrap(exception);
@@ -200,10 +242,12 @@ public class KeyTransparencyController {
throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR, unwrapped);
}
private static MonitorKey createMonitorKey(final ByteString fullSearchKey, final List<Long> positions) {
private static MonitorKey createMonitorKey(final ByteString fullSearchKey, final List<Long> positions,
final ByteString commitmentIndex) {
return MonitorKey.newBuilder()
.setSearchKey(fullSearchKey)
.addAllEntries(positions)
.setCommitmentIndex(commitmentIndex)
.build();
}
@@ -272,6 +272,9 @@ public class MessageController {
@ApiResponse(
responseCode = "410", description = "Mismatched registration ids supplied for some recipient devices",
content = @Content(schema = @Schema(implementation = AccountStaleDevices[].class)))
@ApiResponse(
responseCode="428",
description="The sender should complete a challenge before proceeding")
public Response sendMessage(@ReadOnly @Auth final Optional<AuthenticatedDevice> source,
@Parameter(description="The recipient's unidentified access key")
@HeaderParam(HeaderUtils.UNIDENTIFIED_ACCESS_KEY) final Optional<Anonymous> accessKey,
@@ -73,7 +73,6 @@ import org.whispersystems.textsecuregcm.entities.CreateProfileRequest;
import org.whispersystems.textsecuregcm.entities.CredentialProfileResponse;
import org.whispersystems.textsecuregcm.entities.ExpiringProfileKeyCredentialProfileResponse;
import org.whispersystems.textsecuregcm.entities.ProfileAvatarUploadAttributes;
import org.whispersystems.textsecuregcm.entities.UserCapabilities;
import org.whispersystems.textsecuregcm.entities.VersionedProfileResponse;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
@@ -85,6 +84,7 @@ import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountBadge;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
@@ -431,7 +431,7 @@ public class ProfileController {
return new BaseProfileResponse(account.getIdentityKey(IdentityType.ACI),
account.getUnidentifiedAccessKey().map(UnidentifiedAccessChecksum::generateFor).orElse(null),
account.isUnrestrictedUnidentifiedAccess(),
UserCapabilities.createForAccount(account),
getAccountCapabilities(account),
profileBadgeConverter.convert(
HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext),
account.getBadges(),
@@ -443,7 +443,7 @@ public class ProfileController {
return new BaseProfileResponse(account.getIdentityKey(IdentityType.PNI),
null,
false,
UserCapabilities.createForAccount(account),
getAccountCapabilities(account),
Collections.emptyList(),
new PniServiceIdentifier(account.getPhoneNumberIdentifier()));
}
@@ -489,4 +489,9 @@ public class ProfileController {
now.format(PostPolicyGenerator.AWS_DATE_TIME), policy.second(), signature);
}
private static Map<String, Boolean> getAccountCapabilities(final Account account) {
return Arrays.stream(DeviceCapability.values())
.filter(DeviceCapability::includeInProfile)
.collect(Collectors.toMap(DeviceCapability::getName, account::hasCapability));
}
}
@@ -40,11 +40,11 @@ import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
import org.whispersystems.textsecuregcm.entities.RegistrationRequest;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.DeviceSpec;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.Util;
@@ -127,7 +127,7 @@ public class RegistrationController {
REREGISTRATION_IDLE_DAYS_DISTRIBUTION.record(timeSinceLastSeen.toDays());
});
if (!registrationRequest.skipDeviceTransfer() && existingAccount.map(Account::isTransferSupported).orElse(false)) {
if (!registrationRequest.skipDeviceTransfer() && existingAccount.map(account -> account.hasCapability(DeviceCapability.TRANSFER)).orElse(false)) {
// If a device transfer is possible, clients must explicitly opt out of a transfer (i.e. after prompting the user)
// before we'll let them create a new account "from scratch"
throw new WebApplicationException(Response.status(409, "device transfer available").build());
@@ -171,7 +171,7 @@ public class RegistrationController {
account.getPhoneNumberIdentifier(),
account.getUsernameHash().orElse(null),
account.getUsernameLinkHandle(),
existingAccount.map(Account::isStorageSupported).orElse(false));
existingAccount.map(a -> a.hasCapability(DeviceCapability.STORAGE)).orElse(false));
}
}
@@ -60,7 +60,6 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.backup.BackupManager;
import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
import org.whispersystems.textsecuregcm.badges.LevelTranslator;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationCurrencyConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
@@ -104,7 +103,6 @@ public class SubscriptionController {
private final GooglePlayBillingManager googlePlayBillingManager;
private final AppleAppStoreManager appleAppStoreManager;
private final BadgeTranslator badgeTranslator;
private final LevelTranslator levelTranslator;
private final BankMandateTranslator bankMandateTranslator;
static final String RECEIPT_ISSUED_COUNTER_NAME = MetricsUtil.name(SubscriptionController.class, "receiptIssued");
static final String PROCESSOR_TAG_NAME = "processor";
@@ -121,7 +119,6 @@ public class SubscriptionController {
@Nonnull GooglePlayBillingManager googlePlayBillingManager,
@Nonnull AppleAppStoreManager appleAppStoreManager,
@Nonnull BadgeTranslator badgeTranslator,
@Nonnull LevelTranslator levelTranslator,
@Nonnull BankMandateTranslator bankMandateTranslator) {
this.subscriptionManager = subscriptionManager;
this.clock = Objects.requireNonNull(clock);
@@ -132,7 +129,6 @@ public class SubscriptionController {
this.googlePlayBillingManager = Objects.requireNonNull(googlePlayBillingManager);
this.appleAppStoreManager = appleAppStoreManager;
this.badgeTranslator = Objects.requireNonNull(badgeTranslator);
this.levelTranslator = Objects.requireNonNull(levelTranslator);
this.bankMandateTranslator = Objects.requireNonNull(bankMandateTranslator);
}
@@ -183,7 +179,7 @@ public class SubscriptionController {
subscriptionConfiguration.getDonationLevels().forEach((levelId, levelConfig) -> {
final LevelConfiguration levelConfiguration = new LevelConfiguration(
levelTranslator.translate(acceptableLanguages, levelConfig.badge()),
"" /* deprecated and unused */,
badgeTranslator.translate(acceptableLanguages, levelConfig.badge()));
donationLevels.put(String.valueOf(levelId), levelConfiguration);
});
@@ -192,7 +188,7 @@ public class SubscriptionController {
oneTimeDonationConfiguration.boost().badge());
donationLevels.put(String.valueOf(oneTimeDonationConfiguration.boost().level()),
new LevelConfiguration(
boostBadge.getName(),
"" /* deprecated and unused */,
// NB: the one-time badges are PurchasableBadge, which has a `duration` field
new PurchasableBadge(
boostBadge,
@@ -201,7 +197,7 @@ public class SubscriptionController {
final Badge giftBadge = badgeTranslator.translate(acceptableLanguages, oneTimeDonationConfiguration.gift().badge());
donationLevels.put(String.valueOf(oneTimeDonationConfiguration.gift().level()),
new LevelConfiguration(
giftBadge.getName(),
"" /* deprecated and unused */,
new PurchasableBadge(
giftBadge,
oneTimeDonationConfiguration.gift().expiration())));
@@ -504,6 +500,7 @@ public class SubscriptionController {
@Schema(description = "Configuration for a donation level - use to present appropriate client interfaces")
public record LevelConfiguration(
@Deprecated(forRemoval = true) // may be removed after 2025-01-28
@Schema(description = "The localized name for the level")
String name,
@Schema(description = "The displayable badge associated with the level")
@@ -386,6 +386,7 @@ public class VerificationController {
try {
assessmentResult = registrationCaptchaManager.assessCaptcha(
Optional.empty(),
Optional.of(updateVerificationSessionRequest.captcha()), sourceHost, userAgent)
.orElseThrow(() -> new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR));
@@ -11,12 +11,14 @@ import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.google.common.annotations.VisibleForTesting;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.Size;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.storage.Device.DeviceCapabilities;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import org.whispersystems.textsecuregcm.util.DeviceCapabilityAdapter;
import org.whispersystems.textsecuregcm.util.ExactlySize;
public class AccountAttributes {
@@ -47,7 +49,10 @@ public class AccountAttributes {
private boolean unrestrictedUnidentifiedAccess;
@JsonProperty
private DeviceCapabilities capabilities;
@JsonSerialize(using = DeviceCapabilityAdapter.Serializer.class)
@JsonDeserialize(using = DeviceCapabilityAdapter.Deserializer.class)
@Nullable
private Set<DeviceCapability> capabilities;
@JsonProperty
private boolean discoverableByPhoneNumber = true;
@@ -68,7 +73,7 @@ public class AccountAttributes {
final byte[] name,
final String registrationLock,
final boolean discoverableByPhoneNumber,
final DeviceCapabilities capabilities) {
final Set<DeviceCapability> capabilities) {
this.fetchesMessages = fetchesMessages;
this.registrationId = registrationId;
this.phoneNumberIdentityRegistrationId = phoneNumberIdentifierRegistrationId;
@@ -106,7 +111,8 @@ public class AccountAttributes {
return unrestrictedUnidentifiedAccess;
}
public DeviceCapabilities getCapabilities() {
@Nullable
public Set<DeviceCapability> getCapabilities() {
return capabilities;
}
@@ -130,11 +136,6 @@ public class AccountAttributes {
return this;
}
@VisibleForTesting
public void setPhoneNumberIdentityRegistrationId(final Integer phoneNumberIdentityRegistrationId) {
this.phoneNumberIdentityRegistrationId = phoneNumberIdentityRegistrationId;
}
@AssertTrue
public boolean isEachRegistrationIdValid() {
return validRegistrationId(registrationId) && validRegistrationId(phoneNumberIdentityRegistrationId);
@@ -15,6 +15,7 @@ import org.whispersystems.textsecuregcm.util.ServiceIdentifierAdapter;
import org.whispersystems.textsecuregcm.util.IdentityKeyAdapter;
import java.util.List;
import java.util.Map;
public class BaseProfileResponse {
@@ -32,7 +33,7 @@ public class BaseProfileResponse {
private boolean unrestrictedUnidentifiedAccess;
@JsonProperty
private UserCapabilities capabilities;
private Map<String, Boolean> capabilities;
@JsonProperty
private List<Badge> badges;
@@ -48,7 +49,7 @@ public class BaseProfileResponse {
public BaseProfileResponse(final IdentityKey identityKey,
final byte[] unidentifiedAccess,
final boolean unrestrictedUnidentifiedAccess,
final UserCapabilities capabilities,
final Map<String, Boolean> capabilities,
final List<Badge> badges,
final ServiceIdentifier uuid) {
@@ -72,7 +73,7 @@ public class BaseProfileResponse {
return unrestrictedUnidentifiedAccess;
}
public UserCapabilities getCapabilities() {
public Map<String, Boolean> getCapabilities() {
return capabilities;
}
@@ -5,25 +5,15 @@
package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
public class DeviceName {
@JsonProperty
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
@NotEmpty
@Size(max = 225)
private byte[] deviceName;
public DeviceName() {}
public byte[] getDeviceName() {
return deviceName;
}
public record DeviceName(@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
@NotEmpty
@Size(max = 225)
byte[] deviceName) {
}
@@ -0,0 +1,20 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import io.swagger.v3.oas.annotations.media.Schema;
import javax.validation.constraints.NotNull;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
public record KeyTransparencyDistinguishedKeyResponse(
@NotNull
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
@Schema(description = "The serialized `DistinguishedResponse` encoded in standard un-padded base64")
byte[] serializedResponse
) {}
@@ -8,58 +8,99 @@ package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import io.swagger.v3.oas.annotations.media.Schema;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.util.ByteArrayBase64UrlAdapter;
import org.whispersystems.textsecuregcm.util.ServiceIdentifierAdapter;
import javax.validation.constraints.AssertTrue;
import java.util.List;
import java.util.Optional;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Positive;
import java.util.List;
import java.util.Optional;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import org.whispersystems.textsecuregcm.util.ByteArrayBase64UrlAdapter;
import org.whispersystems.textsecuregcm.util.ExactlySize;
import org.whispersystems.textsecuregcm.util.ServiceIdentifierAdapter;
public record KeyTransparencyMonitorRequest(
@Valid
@NotNull
@JsonSerialize(using = ServiceIdentifierAdapter.ServiceIdentifierSerializer.class)
@JsonDeserialize(using = ServiceIdentifierAdapter.AciServiceIdentifierDeserializer.class)
@Schema(description = "The aci identifier to monitor")
AciServiceIdentifier aci,
AciMonitor aci,
@NotEmpty
@Schema(description = "A list of log tree positions maintained by the client for the aci search key.")
List<@Positive Long> aciPositions,
@Valid
@NotNull
Optional<@Valid E164Monitor> e164,
@Schema(description = "The e164-formatted phone number to monitor")
Optional<String> e164,
@Schema(description = "A list of log tree positions maintained by the client for the e164 search key.")
Optional<List<@Positive Long>> e164Positions,
@JsonSerialize(contentUsing = ByteArrayBase64UrlAdapter.Serializing.class)
@JsonDeserialize(contentUsing = ByteArrayBase64UrlAdapter.Deserializing.class)
@Schema(description = "The username hash to monitor, encoded in url-safe unpadded base64.")
Optional<byte[]> usernameHash,
@Schema(description = "A list of log tree positions maintained by the client for the username hash search key.")
Optional<List<@Positive Long>> usernameHashPositions,
@Valid
@NotNull
Optional<@Valid UsernameHashMonitor> usernameHash,
@Schema(description = "The tree head size to prove consistency against.")
Optional<@Positive Long> lastNonDistinguishedTreeHeadSize,
@Positive long lastNonDistinguishedTreeHeadSize,
@Schema(description = "The distinguished tree head size to prove consistency against.")
Optional<@Positive Long> lastDistinguishedTreeHeadSize
@Positive long lastDistinguishedTreeHeadSize
) {
@AssertTrue
public boolean isUsernameHashFieldsValid() {
return (usernameHash.isEmpty() && usernameHashPositions.isEmpty()) ||
(usernameHash.isPresent() && usernameHashPositions.isPresent() && !usernameHashPositions.get().isEmpty());
}
public record AciMonitor(
@NotNull
@JsonSerialize(using = ServiceIdentifierAdapter.ServiceIdentifierSerializer.class)
@JsonDeserialize(using = ServiceIdentifierAdapter.AciServiceIdentifierDeserializer.class)
@Schema(description = "The aci identifier to monitor")
AciServiceIdentifier value,
@AssertTrue
public boolean isE164VFieldsValid() {
return (e164.isEmpty() && e164Positions.isEmpty()) ||
(e164.isPresent() && e164Positions.isPresent() && !e164Positions.get().isEmpty());
}
@Schema(description = "A list of log tree positions maintained by the client for the aci search key.")
@Valid
@NotNull
@NotEmpty
List<@Positive Long> positions,
@Schema(description = "The commitment index derived from a previous search request, encoded in standard unpadded base64")
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
@NotNull
@ExactlySize(32)
byte[] commitmentIndex
) {}
public record E164Monitor(
@Schema(description = "The e164-formatted phone number to monitor")
@NotBlank
String value,
@Schema(description = "A list of log tree positions maintained by the client for the e164 search key.")
@NotNull
@NotEmpty
@Valid
List<@Positive Long> positions,
@Schema(description = "The commitment index derived from a previous search request, encoded in standard unpadded base64")
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
@NotNull
@ExactlySize(32)
byte[] commitmentIndex
) {}
public record UsernameHashMonitor(
@Schema(description = "The username hash to monitor, encoded in url-safe unpadded base64.")
@JsonSerialize(using = ByteArrayBase64UrlAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64UrlAdapter.Deserializing.class)
@NotNull
@NotEmpty
byte[] value,
@Schema(description = "A list of log tree positions maintained by the client for the username hash search key.")
@NotNull
@NotEmpty
@Valid List<@Positive Long> positions,
@Schema(description = "The commitment index derived from a previous search request, encoded in standard unpadded base64")
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
@NotNull
@ExactlySize(32)
byte[] commitmentIndex
) {}
}
@@ -16,6 +16,6 @@ public record KeyTransparencyMonitorResponse(
@NotNull
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
@Schema(description = "The monitor response encoded in standard un-padded base64")
byte[] monitorResponse
@Schema(description = "The serialized `MonitorResponse` encoded in standard un-padded base64")
byte[] serializedResponse
) {}
@@ -8,11 +8,15 @@ package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import io.swagger.v3.oas.annotations.media.Schema;
import org.signal.libsignal.protocol.IdentityKey;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.util.ByteArrayBase64UrlAdapter;
import org.whispersystems.textsecuregcm.util.ByteArrayBase64WithPaddingAdapter;
import org.whispersystems.textsecuregcm.util.E164;
import org.whispersystems.textsecuregcm.util.IdentityKeyAdapter;
import org.whispersystems.textsecuregcm.util.ServiceIdentifierAdapter;
import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Positive;
import java.util.Optional;
@@ -21,11 +25,11 @@ public record KeyTransparencySearchRequest(
@NotNull
@JsonSerialize(using = ServiceIdentifierAdapter.ServiceIdentifierSerializer.class)
@JsonDeserialize(using = ServiceIdentifierAdapter.AciServiceIdentifierDeserializer.class)
@Schema(description = "The aci identifier to look up")
@Schema(description = "The ACI to look up")
AciServiceIdentifier aci,
@E164
@Schema(description = "The e164-formatted phone number to look up")
@Schema(description = "The E164-formatted phone number to look up")
Optional<String> e164,
@JsonSerialize(contentUsing = ByteArrayBase64UrlAdapter.Serializing.class)
@@ -33,9 +37,25 @@ public record KeyTransparencySearchRequest(
@Schema(description = "The username hash to look up, encoded in web-safe unpadded base64.")
Optional<byte[]> usernameHash,
@NotNull
@JsonSerialize(using = IdentityKeyAdapter.Serializer.class)
@JsonDeserialize(using = IdentityKeyAdapter.Deserializer.class)
@Schema(description="The public ACI identity key associated with the provided ACI")
IdentityKey aciIdentityKey,
@JsonSerialize(contentUsing = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(contentUsing = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
@Schema(description="The unidentified access key associated with the account")
Optional<byte[]> unidentifiedAccessKey,
@Schema(description = "The non-distinguished tree head size to prove consistency against.")
Optional<@Positive Long> lastTreeHeadSize,
@Schema(description = "The distinguished tree head size to prove consistency against.")
Optional<@Positive Long> distinguishedTreeHeadSize
) {}
@Positive long distinguishedTreeHeadSize
) {
@AssertTrue
public boolean isUnidentifiedAccessKeyProvidedWithE164() {
return unidentifiedAccessKey.isPresent() == e164.isPresent();
}
}
@@ -17,16 +17,6 @@ public record KeyTransparencySearchResponse(
@NotNull
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
@Schema(description = "The search response for the aci search key encoded in standard un-padded base64")
byte[] aciSearchResponse,
@JsonSerialize(contentUsing = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(contentUsing = ByteArrayAdapter.Deserializing.class)
@Schema(description = "The search response for the e164 search key encoded in standard un-padded base64")
Optional<byte[]> e164SearchResponse,
@JsonSerialize(contentUsing = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(contentUsing = ByteArrayAdapter.Deserializing.class)
@Schema(description = "The search response for the username hash search key encoded in standard un-padded base64")
Optional<byte[]> usernameHashSearchResponse
@Schema(description = "The serialized `SearchResponse` encoded in standard un-padded base64.")
byte[] serializedResponse
) {}
@@ -0,0 +1,32 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.entities;
import io.swagger.v3.oas.annotations.media.Schema;
import javax.validation.constraints.NotNull;
@Schema(description = """
Represents a request from a new device to restore account data by some method.
""")
public record RestoreAccountRequest(
@NotNull
@Schema(description = "The method by which the new device has requested account data restoration")
Method method) {
public enum Method {
@Schema(description = "Restore account data from a remote message history backup")
REMOTE_BACKUP,
@Schema(description = "Restore account data from a local backup archive")
LOCAL_BACKUP,
@Schema(description = "Restore account data via direct device-to-device transfer")
DEVICE_TRANSFER,
@Schema(description = "Do not restore account data")
DECLINE,
}
}
@@ -1,18 +0,0 @@
/*
* Copyright 2013-2022 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.entities;
import org.whispersystems.textsecuregcm.storage.Account;
public record UserCapabilities(
boolean deleteSync,
boolean versionedExpirationTimer) {
public static UserCapabilities createForAccount(final Account account) {
return new UserCapabilities(account.isDeleteSyncSupported(),
account.isVersionedExpirationTimerSupported());
}
}
@@ -41,12 +41,11 @@ public class ExperimentEnrollmentManager {
.getConfiguration().getExperimentEnrollmentConfiguration(experimentName);
return maybeConfiguration
.map(config -> isAccountEnrolled(accountUuid, config)
.orElse(isEnrolled(accountUuid, config.getEnrollmentPercentage(), experimentName))
).orElse(false);
.map(config -> isAccountEnrolled(accountUuid, config, experimentName).orElse(false))
.orElse(false);
}
Optional<Boolean> isAccountEnrolled(final UUID accountUuid, DynamicExperimentEnrollmentConfiguration config) {
private Optional<Boolean> isAccountEnrolled(final UUID accountUuid, DynamicExperimentEnrollmentConfiguration config, String experimentName) {
if (config.getExcludedUuids().contains(accountUuid)) {
return Optional.of(false);
}
@@ -55,6 +54,10 @@ public class ExperimentEnrollmentManager {
return Optional.of(r < config.getUuidSelector().getUuidEnrollmentPercentage());
}
if (isEnrolled(accountUuid, config.getEnrollmentPercentage(), experimentName)) {
return Optional.of(true);
}
return Optional.empty();
}
@@ -64,7 +67,7 @@ public class ExperimentEnrollmentManager {
.getConfiguration().getExperimentEnrollmentConfiguration(experimentName);
return maybeConfiguration
.flatMap(config -> isAccountEnrolled(accountUuid, config))
.flatMap(config -> isAccountEnrolled(accountUuid, config, experimentName))
.orElse(isEnrolled(e164, experimentName));
}
@@ -0,0 +1,36 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import io.grpc.Status;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
public class DeviceCapabilityUtil {
private DeviceCapabilityUtil() {
}
public static DeviceCapability fromGrpcDeviceCapability(final org.signal.chat.common.DeviceCapability grpcDeviceCapability) {
return switch (grpcDeviceCapability) {
case DEVICE_CAPABILITY_STORAGE -> DeviceCapability.STORAGE;
case DEVICE_CAPABILITY_TRANSFER -> DeviceCapability.TRANSFER;
case DEVICE_CAPABILITY_DELETE_SYNC -> DeviceCapability.DELETE_SYNC;
case DEVICE_CAPABILITY_VERSIONED_EXPIRATION_TIMER -> DeviceCapability.VERSIONED_EXPIRATION_TIMER;
case DEVICE_CAPABILITY_STORAGE_SERVICE_RECORD_KEY_ROTATION -> DeviceCapability.STORAGE_SERVICE_RECORD_KEY_ROTATION;
case DEVICE_CAPABILITY_UNSPECIFIED, UNRECOGNIZED -> throw Status.INVALID_ARGUMENT.withDescription("Unrecognized device capability").asRuntimeException();
};
}
public static org.signal.chat.common.DeviceCapability toGrpcDeviceCapability(final DeviceCapability deviceCapability) {
return switch (deviceCapability) {
case STORAGE -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_STORAGE;
case TRANSFER -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_TRANSFER;
case DELETE_SYNC -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_DELETE_SYNC;
case VERSIONED_EXPIRATION_TIMER -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_VERSIONED_EXPIRATION_TIMER;
case STORAGE_SERVICE_RECORD_KEY_ROTATION -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_STORAGE_SERVICE_RECORD_KEY_ROTATION;
};
}
}
@@ -6,13 +6,15 @@
package org.whispersystems.textsecuregcm.grpc;
import io.grpc.Status;
import org.whispersystems.textsecuregcm.storage.Device;
public class DeviceIdUtil {
static byte validate(int deviceId) {
if (deviceId > Byte.MAX_VALUE) {
if (deviceId < Device.PRIMARY_ID || deviceId > Byte.MAX_VALUE) {
throw Status.INVALID_ARGUMENT.withDescription("Device ID is out of range").asRuntimeException();
}
return (byte) deviceId;
}
}
@@ -8,6 +8,8 @@ package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import io.grpc.Status;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.signal.chat.device.ClearPushTokenRequest;
@@ -27,6 +29,7 @@ import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@@ -89,6 +92,17 @@ public class DevicesGrpcService extends ReactorDevicesGrpc.DevicesImplBase {
public Mono<SetDeviceNameResponse> setDeviceName(final SetDeviceNameRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final byte deviceId = DeviceIdUtil.validate(request.getId());
final boolean mayChangeName = authenticatedDevice.deviceId() == Device.PRIMARY_ID ||
authenticatedDevice.deviceId() == deviceId;
if (!mayChangeName) {
throw Status.PERMISSION_DENIED
.withDescription("Authenticated device is not authorized to change target device name")
.asRuntimeException();
}
if (request.getName().isEmpty()) {
throw Status.INVALID_ARGUMENT.withDescription("Must specify a device name").asRuntimeException();
}
@@ -100,7 +114,12 @@ 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(),
.doOnNext(account -> {
if (account.getDevice(deviceId).isEmpty()) {
throw Status.NOT_FOUND.withDescription("No device found with given ID").asRuntimeException();
}
})
.flatMap(account -> Mono.fromFuture(() -> accountsManager.updateDeviceAsync(account, deviceId,
device -> device.setName(request.getName().toByteArray()))))
.thenReturn(SetDeviceNameResponse.newBuilder().build());
}
@@ -184,15 +203,15 @@ public class DevicesGrpcService extends ReactorDevicesGrpc.DevicesImplBase {
public Mono<SetCapabilitiesResponse> setCapabilities(final SetCapabilitiesRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final Set<DeviceCapability> capabilities = request.getCapabilitiesList().stream()
.map(DeviceCapabilityUtil::fromGrpcDeviceCapability)
.collect(Collectors.toSet());
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
.flatMap(account ->
Mono.fromFuture(() -> accountsManager.updateDeviceAsync(account, authenticatedDevice.deviceId(),
d -> d.setCapabilities(new Device.DeviceCapabilities(
request.getStorage(),
request.getTransfer(),
request.getDeleteSync(),
request.getVersionedExpirationTimer())))))
d -> d.setCapabilities(capabilities))))
.thenReturn(SetCapabilitiesResponse.newBuilder().build());
}
}
@@ -47,7 +47,9 @@ public class KeysAnonymousGrpcService extends ReactorKeysAnonymousGrpc.KeysAnony
final ServiceIdentifier serviceIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getTargetIdentifier());
final byte deviceId = DeviceIdUtil.validate(request.getRequest().getDeviceId());
final byte deviceId = request.getRequest().hasDeviceId()
? DeviceIdUtil.validate(request.getRequest().getDeviceId())
: KeysGrpcHelper.ALL_DEVICES;
return switch (request.getAuthorizationCase()) {
case GROUP_SEND_TOKEN ->
@@ -5,7 +5,6 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.ByteString;
import io.grpc.Status;
import org.signal.chat.common.EcPreKey;
@@ -26,7 +25,6 @@ import reactor.util.function.Tuples;
class KeysGrpcHelper {
@VisibleForTesting
static final byte ALL_DEVICES = 0;
static Mono<GetPreKeysResponse> getPreKeys(final Account targetAccount,
@@ -122,7 +122,9 @@ public class KeysGrpcService extends ReactorKeysGrpc.KeysImplBase {
final ServiceIdentifier targetIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getTargetIdentifier());
final byte deviceId = DeviceIdUtil.validate(request.getDeviceId());
final byte deviceId = request.hasDeviceId()
? DeviceIdUtil.validate(request.getDeviceId())
: KeysGrpcHelper.ALL_DEVICES;
final String rateLimitKey = authenticatedDevice.accountIdentifier() + "." +
authenticatedDevice.deviceId() + "__" +
@@ -9,6 +9,7 @@ import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.ByteString;
import io.grpc.Status;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import org.signal.chat.profile.Badge;
@@ -16,7 +17,6 @@ import org.signal.chat.profile.BadgeSvg;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResponse;
import org.signal.chat.profile.GetUnversionedProfileResponse;
import org.signal.chat.profile.GetVersionedProfileResponse;
import org.signal.chat.profile.UserCapabilities;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
@@ -24,9 +24,9 @@ import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialRespons
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
import org.whispersystems.textsecuregcm.util.ProfileHelper;
@@ -80,11 +80,12 @@ public class ProfileGrpcHelper {
}
@VisibleForTesting
static UserCapabilities buildUserCapabilities(final org.whispersystems.textsecuregcm.entities.UserCapabilities capabilities) {
return UserCapabilities.newBuilder()
.setDeleteSync(capabilities.deleteSync())
.setVersionedExpirationTimer(capabilities.versionedExpirationTimer())
.build();
static List<org.signal.chat.common.DeviceCapability> buildAccountCapabilities(final Account account) {
return Arrays.stream(DeviceCapability.values())
.filter(DeviceCapability::includeInProfile)
.filter(account::hasCapability)
.map(DeviceCapabilityUtil::toGrpcDeviceCapability)
.toList();
}
private static List<BadgeSvg> buildBadgeSvgs(final List<org.whispersystems.textsecuregcm.entities.BadgeSvg> badgeSvgs) {
@@ -105,7 +106,7 @@ public class ProfileGrpcHelper {
final ProfileBadgeConverter profileBadgeConverter) {
final GetUnversionedProfileResponse.Builder responseBuilder = GetUnversionedProfileResponse.newBuilder()
.setIdentityKey(ByteString.copyFrom(targetAccount.getIdentityKey(targetIdentifier.identityType()).serialize()))
.setCapabilities(buildUserCapabilities(org.whispersystems.textsecuregcm.entities.UserCapabilities.createForAccount(targetAccount)));
.addAllCapabilities(buildAccountCapabilities(targetAccount));
switch (targetIdentifier.identityType()) {
case ACI -> {
@@ -113,7 +114,7 @@ public class ProfileGrpcHelper {
.addAllBadges(buildBadges(profileBadgeConverter.convert(
RequestAttributesUtil.getAvailableAcceptedLocales(),
targetAccount.getBadges(),
ProfileHelper.isSelfProfileRequest(requesterUuid, (AciServiceIdentifier) targetIdentifier))));
ProfileHelper.isSelfProfileRequest(requesterUuid, targetIdentifier))));
targetAccount.getUnidentifiedAccessKey()
.map(UnidentifiedAccessChecksum::generateFor)
@@ -7,27 +7,42 @@ import io.grpc.ChannelCredentials;
import io.grpc.Deadline;
import io.grpc.Grpc;
import io.grpc.ManagedChannel;
import io.grpc.TlsChannelCredentials;
import io.micrometer.core.instrument.Metrics;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.time.Instant;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import io.grpc.TlsChannelCredentials;
import org.signal.keytransparency.client.ConsistencyParameters;
import org.signal.keytransparency.client.DistinguishedRequest;
import org.signal.keytransparency.client.E164SearchRequest;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.util.CompletableFutureUtil;
public class KeyTransparencyServiceClient implements Managed {
private static final String DAYS_UNTIL_CLIENT_CERTIFICATE_EXPIRATION_GAUGE_NAME =
MetricsUtil.name(KeyTransparencyServiceClient.class, "daysUntilClientCertificateExpiration");
private static final Logger logger = LoggerFactory.getLogger(KeyTransparencyServiceClient.class);
private final Executor callbackExecutor;
private final String host;
private final int port;
@@ -39,32 +54,84 @@ public class KeyTransparencyServiceClient implements Managed {
final String host,
final int port,
final String tlsCertificate,
final String clientCertificate,
final String clientPrivateKey,
final Executor callbackExecutor
) throws IOException {
this.host = host;
this.port = port;
try (final ByteArrayInputStream certificateInputStream = new ByteArrayInputStream(
tlsCertificate.getBytes(StandardCharsets.UTF_8))) {
tlsCertificate.getBytes(StandardCharsets.UTF_8));
final ByteArrayInputStream clientCertificateInputStream = new ByteArrayInputStream(
clientCertificate.getBytes(StandardCharsets.UTF_8));
final ByteArrayInputStream clientPrivateKeyInputStream = new ByteArrayInputStream(
clientPrivateKey.getBytes(StandardCharsets.UTF_8))
) {
tlsChannelCredentials = TlsChannelCredentials.newBuilder()
.trustManager(certificateInputStream)
.keyManager(clientCertificateInputStream, clientPrivateKeyInputStream)
.build();
configureClientCertificateMetrics(clientCertificate);
}
this.callbackExecutor = callbackExecutor;
}
private void configureClientCertificateMetrics(String clientCertificate) {
try {
final CertificateFactory cf = CertificateFactory.getInstance("X.509");
final Collection<? extends Certificate> certificates = cf.generateCertificates(
new ByteArrayInputStream(clientCertificate.getBytes(StandardCharsets.UTF_8)));
if (certificates.isEmpty()) {
logger.warn("No client certificate found");
return;
}
if (certificates.size() > 1) {
throw new IllegalArgumentException("Unexpected number of client certificates: " + certificates.size());
}
final Certificate certificate = certificates.iterator().next();
if (certificate instanceof X509Certificate x509Cert) {
final Instant expiration = Instant.ofEpochMilli(x509Cert.getNotAfter().getTime());
Metrics.gauge(DAYS_UNTIL_CLIENT_CERTIFICATE_EXPIRATION_GAUGE_NAME,
this,
(ignored) -> Duration.between(Instant.now(), expiration).toDays());
} else {
logger.error("Certificate was of unexpected type: {}", certificate.getClass().getName());
}
} catch (CertificateException e) {
throw new AssertionError("JDKs are required to support X.509 algorithms", e);
}
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public CompletableFuture<byte[]> search(
final ByteString searchKey,
final ByteString aci,
final ByteString aciIdentityKey,
final Optional<ByteString> usernameHash,
final Optional<E164SearchRequest> e164SearchRequest,
final Optional<Long> lastTreeHeadSize,
final Optional<Long> distinguishedTreeHeadSize,
final long distinguishedTreeHeadSize,
final Duration timeout) {
final SearchRequest.Builder searchRequestBuilder = SearchRequest.newBuilder()
.setSearchKey(searchKey);
.setAci(aci)
.setAciIdentityKey(aciIdentityKey);
final ConsistencyParameters.Builder consistency = ConsistencyParameters.newBuilder();
usernameHash.ifPresent(searchRequestBuilder::setUsernameHash);
e164SearchRequest.ifPresent(searchRequestBuilder::setE164SearchRequest);
final ConsistencyParameters.Builder consistency = ConsistencyParameters.newBuilder()
.setDistinguished(distinguishedTreeHeadSize);
lastTreeHeadSize.ifPresent(consistency::setLast);
distinguishedTreeHeadSize.ifPresent(consistency::setDistinguished);
searchRequestBuilder.setConsistency(consistency);
searchRequestBuilder.setConsistency(consistency.build());
return CompletableFutureUtil.toCompletableFuture(stub.withDeadline(toDeadline(timeout))
.search(searchRequestBuilder.build()), callbackExecutor)
@@ -72,15 +139,16 @@ public class KeyTransparencyServiceClient implements Managed {
}
public CompletableFuture<byte[]> monitor(final List<MonitorKey> monitorKeys,
final Optional<Long> lastTreeHeadSize,
final Optional<Long> distinguishedTreeHeadSize,
final long lastTreeHeadSize,
final long distinguishedTreeHeadSize,
final Duration timeout) {
final MonitorRequest.Builder monitorRequestBuilder = MonitorRequest.newBuilder()
.addAllContactKeys(monitorKeys);
final ConsistencyParameters.Builder consistency = ConsistencyParameters.newBuilder();
lastTreeHeadSize.ifPresent(consistency::setLast);
distinguishedTreeHeadSize.ifPresent(consistency::setDistinguished);
final ConsistencyParameters consistency = ConsistencyParameters.newBuilder()
.setLast(lastTreeHeadSize)
.setDistinguished(distinguishedTreeHeadSize)
.build();
monitorRequestBuilder.setConsistency(consistency);
@@ -89,6 +157,16 @@ public class KeyTransparencyServiceClient implements Managed {
.thenApply(AbstractMessageLite::toByteArray);
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public CompletableFuture<byte[]> getDistinguishedKey(final Optional<Long> lastTreeHeadSize, final Duration timeout) {
final DistinguishedRequest request = lastTreeHeadSize.map(
last -> DistinguishedRequest.newBuilder().setLast(last).build())
.orElseGet(DistinguishedRequest::getDefaultInstance);
return CompletableFutureUtil.toCompletableFuture(stub.withDeadline(toDeadline(timeout)).distinguished(request),
callbackExecutor)
.thenApply(AbstractMessageLite::toByteArray);
}
private static Deadline toDeadline(final Duration timeout) {
return Deadline.after(timeout.toMillis(), TimeUnit.MILLISECONDS);
}
@@ -7,6 +7,9 @@ package org.whispersystems.textsecuregcm.limits;
import static com.codahale.metrics.MetricRegistry.name;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
@@ -16,12 +19,15 @@ import java.util.Optional;
import org.whispersystems.textsecuregcm.captcha.Action;
import org.whispersystems.textsecuregcm.captcha.CaptchaChecker;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
import org.whispersystems.textsecuregcm.spam.ChallengeType;
import org.whispersystems.textsecuregcm.spam.RateLimitChallengeListener;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.util.Util;
import javax.ws.rs.ServerErrorException;
import javax.ws.rs.core.Response;
public class RateLimitChallengeManager {
@@ -67,7 +73,7 @@ public class RateLimitChallengeManager {
rateLimiters.getCaptchaChallengeAttemptLimiter().validate(account.getUuid());
final boolean challengeSuccess = captchaChecker.verify(Action.CHALLENGE, captcha, mostRecentProxyIp, userAgent).isValid(scoreThreshold);
final boolean challengeSuccess = captchaChecker.verify(Optional.of(account.getUuid()), Action.CHALLENGE, captcha, mostRecentProxyIp, userAgent).isValid(scoreThreshold);
final Tags tags = Tags.of(
Tag.of(SOURCE_COUNTRY_TAG_NAME, Util.getCountryCode(account.getNumber())),
@@ -48,11 +48,15 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
CREATE_CALL_LINK("createCallLink", false, new RateLimiterConfig(100, Duration.ofMinutes(15))),
INBOUND_MESSAGE_BYTES("inboundMessageBytes", true, new RateLimiterConfig(128 * 1024 * 1024, Duration.ofNanos(500_000))),
EXTERNAL_SERVICE_CREDENTIALS("externalServiceCredentials", true, new RateLimiterConfig(100, Duration.ofMinutes(15))),
KEY_TRANSPARENCY_DISTINGUISHED_PER_IP("keyTransparencyDistinguished", true,
new RateLimiterConfig(100, Duration.ofSeconds(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))),
UPLOAD_TRANSFER_ARCHIVE("uploadTransferArchive", true, new RateLimiterConfig(10, Duration.ofMinutes(1))),
WAIT_FOR_TRANSFER_ARCHIVE("waitForTransferArchive", true, new RateLimiterConfig(10, Duration.ofSeconds(30))),
RECORD_DEVICE_TRANSFER_REQUEST("recordDeviceTransferRequest", true, new RateLimiterConfig(10, Duration.ofMillis(100))),
WAIT_FOR_DEVICE_TRANSFER_REQUEST("waitForDeviceTransferRequest", true, new RateLimiterConfig(10, Duration.ofMillis(100))),
;
private final String id;
@@ -0,0 +1,27 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.push;
/**
* A client event listener handles events related to a client's message-retrieval presence. Handler methods are run on
* dedicated threads and may safely perform blocking operations.
*/
public interface ClientEventListener {
/**
* Indicates that a new message is available in the connected client's message queue.
*/
void handleNewMessageAvailable();
/**
* Indicates that the client's presence has been displaced and the listener should close the client's underlying
* network connection.
*
* @param connectedElsewhere if {@code true}, indicates that the client's presence has been displaced by another
* connection from the same client
*/
void handleConnectionDisplaced(boolean connectedElsewhere);
}
@@ -14,6 +14,7 @@ import io.lettuce.core.RedisFuture;
import io.lettuce.core.ScriptOutputType;
import io.lettuce.core.cluster.SlotHash;
import io.lettuce.core.cluster.api.async.RedisAdvancedClusterAsyncCommands;
import io.lettuce.core.cluster.event.ClusterTopologyChangedEvent;
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
import io.lettuce.core.cluster.pubsub.RedisClusterPubSubAdapter;
import io.micrometer.core.instrument.Counter;
@@ -277,7 +278,7 @@ public class ClientPresenceManager extends RedisClusterPubSubAdapter<String, Str
.subscribe(getKeyspaceNotificationChannel(presenceKey)));
}
private void resubscribeAll() {
private void resubscribeAll(final ClusterTopologyChangedEvent event) {
for (final String presenceKey : displacementListenersByPresenceKey.keySet()) {
subscribeForRemotePresenceChanges(presenceKey);
}
@@ -7,10 +7,16 @@ package org.whispersystems.textsecuregcm.push;
import static com.codahale.metrics.MetricRegistry.name;
import static org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import org.whispersystems.textsecuregcm.util.Util;
import java.util.concurrent.CompletableFuture;
/**
* A MessageSender sends Signal messages to destination devices. Messages may be "normal" user-to-user messages,
@@ -27,7 +33,7 @@ import org.whispersystems.textsecuregcm.storage.MessagesManager;
*/
public class MessageSender {
private final ClientPresenceManager clientPresenceManager;
private final PubSubClientEventManager pubSubClientEventManager;
private final MessagesManager messagesManager;
private final PushNotificationManager pushNotificationManager;
@@ -39,62 +45,64 @@ public class MessageSender {
private static final String STORY_TAG_NAME = "story";
private static final String SEALED_SENDER_TAG_NAME = "sealedSender";
public MessageSender(final ClientPresenceManager clientPresenceManager,
private static final Counter CLIENT_PRESENCE_ERROR =
Metrics.counter(MetricsUtil.name(MessageSender.class, "clientPresenceError"));
public MessageSender(final PubSubClientEventManager pubSubClientEventManager,
final MessagesManager messagesManager,
final PushNotificationManager pushNotificationManager) {
this.clientPresenceManager = clientPresenceManager;
this.pubSubClientEventManager = pubSubClientEventManager;
this.messagesManager = messagesManager;
this.pushNotificationManager = pushNotificationManager;
}
public void sendMessage(final Account account, final Device device, final Envelope message, final boolean online) {
public CompletableFuture<Void> sendMessage(final Account account, final Device device, final Envelope message, final boolean online) {
messagesManager.insert(account.getUuid(),
device.getId(),
online ? message.toBuilder().setEphemeral(true).build() : message);
final String channel;
return pubSubClientEventManager.handleNewMessageAvailable(account.getIdentifier(IdentityType.ACI), device.getId())
.exceptionally(throwable -> {
// It's unlikely that the message insert (synchronous) would succeed and sending a "new message available"
// event would fail since both things happen in the same cluster, but just in case, we should "fail open" and
// act as if the client wasn't present if this happens. This is a conservative measure that biases toward
// sending more push notifications, though again, it shouldn't happen often.
CLIENT_PRESENCE_ERROR.increment();
return false;
})
.thenApply(clientPresent -> {
if (!clientPresent && !online) {
try {
pushNotificationManager.sendNewMessageNotification(account, device.getId(), message.getUrgent());
} catch (final NotPushRegisteredException ignored) {
}
}
return clientPresent;
})
.whenComplete((clientPresent, throwable) -> Metrics.counter(SEND_COUNTER_NAME,
CHANNEL_TAG_NAME, getDeliveryChannelName(device),
EPHEMERAL_TAG_NAME, String.valueOf(online),
CLIENT_ONLINE_TAG_NAME, String.valueOf(clientPresent),
URGENT_TAG_NAME, String.valueOf(message.getUrgent()),
STORY_TAG_NAME, String.valueOf(message.getStory()),
SEALED_SENDER_TAG_NAME, String.valueOf(!message.hasSourceServiceId()))
.increment())
.thenRun(Util.NOOP)
.toCompletableFuture();
}
@VisibleForTesting
static String getDeliveryChannelName(final Device device) {
if (device.getGcmId() != null) {
channel = "gcm";
return "gcm";
} else if (device.getApnId() != null) {
channel = "apn";
return "apn";
} else if (device.getFetchesMessages()) {
channel = "websocket";
return "websocket";
} else {
channel = "none";
return "none";
}
final boolean clientPresent;
if (online) {
clientPresent = clientPresenceManager.isPresent(account.getUuid(), device.getId());
if (clientPresent) {
messagesManager.insert(account.getUuid(), device.getId(), message.toBuilder().setEphemeral(true).build());
} else {
messagesManager.removeRecipientViewFromMrmData(device.getId(), message);
}
} else {
messagesManager.insert(account.getUuid(), device.getId(), message);
// We check for client presence after inserting the message to take a conservative view of notifications. If the
// client wasn't present at the time of insertion but is now, they'll retrieve the message. If they were present
// but disconnected before the message was delivered, we should send a notification.
clientPresent = clientPresenceManager.isPresent(account.getUuid(), device.getId());
if (!clientPresent) {
try {
pushNotificationManager.sendNewMessageNotification(account, device.getId(), message.getUrgent());
} catch (final NotPushRegisteredException ignored) {
}
}
}
Metrics.counter(SEND_COUNTER_NAME,
CHANNEL_TAG_NAME, channel,
EPHEMERAL_TAG_NAME, String.valueOf(online),
CLIENT_ONLINE_TAG_NAME, String.valueOf(clientPresent),
URGENT_TAG_NAME, String.valueOf(message.getUrgent()),
STORY_TAG_NAME, String.valueOf(message.getStory()),
SEALED_SENDER_TAG_NAME, String.valueOf(!message.hasSourceServiceId()))
.increment();
}
}
@@ -0,0 +1,371 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.push;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.InvalidProtocolBufferException;
import io.dropwizard.lifecycle.Managed;
import io.lettuce.core.cluster.SlotHash;
import io.lettuce.core.cluster.event.ClusterTopologyChangedEvent;
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
import io.lettuce.core.cluster.pubsub.RedisClusterPubSubAdapter;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubClusterConnection;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.util.RedisClusterUtil;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import org.whispersystems.textsecuregcm.util.Util;
/**
* The pub/sub-based client presence manager uses the Redis 7 sharded pub/sub system to notify connected clients that
* new messages are available for retrieval and report to senders whether a client was present to receive a message when
* sent. This system makes a best effort to ensure that a given client has only a single open connection across the
* fleet of servers, but cannot guarantee at-most-one behavior.
*/
public class PubSubClientEventManager extends RedisClusterPubSubAdapter<byte[], byte[]> implements Managed {
private final FaultTolerantRedisClusterClient clusterClient;
private final Executor listenerEventExecutor;
private final UUID serverId = UUID.randomUUID();
private final byte[] CLIENT_CONNECTED_EVENT_BYTES = ClientEvent.newBuilder()
.setClientConnected(ClientConnectedEvent.newBuilder()
.setServerId(UUIDUtil.toByteString(serverId))
.build())
.build()
.toByteArray();
@Nullable
private FaultTolerantPubSubClusterConnection<byte[], byte[]> pubSubConnection;
private final Map<AccountAndDeviceIdentifier, ClientEventListener> listenersByAccountAndDeviceIdentifier;
private static final byte[] NEW_MESSAGE_EVENT_BYTES = ClientEvent.newBuilder()
.setNewMessageAvailable(NewMessageAvailableEvent.getDefaultInstance())
.build()
.toByteArray();
private static final byte[] DISCONNECT_REQUESTED_EVENT_BYTES = ClientEvent.newBuilder()
.setDisconnectRequested(DisconnectRequested.getDefaultInstance())
.build()
.toByteArray();
private static final Counter PUBLISH_CLIENT_CONNECTION_EVENT_ERROR_COUNTER =
Metrics.counter(MetricsUtil.name(PubSubClientEventManager.class, "publishClientConnectionEventError"));
private static final Counter UNSUBSCRIBE_ERROR_COUNTER =
Metrics.counter(MetricsUtil.name(PubSubClientEventManager.class, "unsubscribeError"));
private static final Counter MESSAGE_WITHOUT_LISTENER_COUNTER =
Metrics.counter(MetricsUtil.name(PubSubClientEventManager.class, "messageWithoutListener"));
private static final String LISTENER_GAUGE_NAME =
MetricsUtil.name(PubSubClientEventManager.class, "listeners");
private static final Logger logger = LoggerFactory.getLogger(PubSubClientEventManager.class);
private record AccountAndDeviceIdentifier(UUID accountIdentifier, byte deviceId) {
}
public PubSubClientEventManager(final FaultTolerantRedisClusterClient clusterClient,
final Executor listenerEventExecutor) {
this.clusterClient = clusterClient;
this.listenerEventExecutor = listenerEventExecutor;
this.listenersByAccountAndDeviceIdentifier =
Metrics.gaugeMapSize(LISTENER_GAUGE_NAME, Tags.empty(), new ConcurrentHashMap<>());
}
@Override
public synchronized void start() {
this.pubSubConnection = clusterClient.createBinaryPubSubConnection();
this.pubSubConnection.usePubSubConnection(connection -> connection.addListener(this));
pubSubConnection.subscribeToClusterTopologyChangedEvents(this::resubscribe);
}
@Override
public synchronized void stop() {
if (pubSubConnection != null) {
pubSubConnection.usePubSubConnection(connection -> {
connection.removeListener(this);
connection.close();
});
}
pubSubConnection = null;
}
/**
* Marks the given device as "present" and registers a listener for new messages and conflicting connections. If the
* given device already has a presence registered with this presence manager instance, that presence is displaced
* immediately and the listener's {@link ClientEventListener#handleConnectionDisplaced(boolean)} method is called.
*
* @param accountIdentifier the account identifier for the newly-connected device
* @param deviceId the ID of the newly-connected device within the given account
* @param listener the listener to notify when new messages or conflicting connections arrive for the newly-conencted
* device
*
* @return a future that yields a connection identifier when the new device's presence has been registered; the future
* may fail if a pub/sub subscription could not be established, in which case callers should close the client's
* connection to the server
*/
public CompletionStage<UUID> handleClientConnected(final UUID accountIdentifier, final byte deviceId, final ClientEventListener listener) {
if (pubSubConnection == null) {
throw new IllegalStateException("Presence manager not started");
}
final UUID connectionId = UUID.randomUUID();
final byte[] clientPresenceKey = getClientPresenceKey(accountIdentifier, deviceId);
final AtomicReference<ClientEventListener> displacedListener = new AtomicReference<>();
final AtomicReference<CompletionStage<Void>> subscribeFuture = new AtomicReference<>();
// Note that we're relying on some specific implementation details of `ConcurrentHashMap#compute(...)`. In
// particular, the behavioral contract for `ConcurrentHashMap#compute(...)` says:
//
// > The entire method invocation is performed atomically. The supplied function is invoked exactly once per
// > invocation of this method. Some attempted update operations on this map by other threads may be blocked while
// > computation is in progress, so the computation should be short and simple.
//
// This provides a mechanism to make sure that we enqueue subscription/unsubscription operations in the same order
// as adding/removing listeners from the map and helps us avoid races and conflicts. Note that the enqueued
// operation is asynchronous; we're not blocking on it in the scope of the `compute` operation.
listenersByAccountAndDeviceIdentifier.compute(new AccountAndDeviceIdentifier(accountIdentifier, deviceId),
(key, existingListener) -> {
subscribeFuture.set(pubSubConnection.withPubSubConnection(connection ->
connection.async().ssubscribe(clientPresenceKey)));
if (existingListener != null) {
displacedListener.set(existingListener);
}
return listener;
});
if (displacedListener.get() != null) {
listenerEventExecutor.execute(() -> displacedListener.get().handleConnectionDisplaced(true));
}
return subscribeFuture.get()
.thenCompose(ignored -> clusterClient.withBinaryCluster(connection -> connection.async()
.spublish(clientPresenceKey, CLIENT_CONNECTED_EVENT_BYTES)))
.handle((ignored, throwable) -> {
if (throwable != null) {
PUBLISH_CLIENT_CONNECTION_EVENT_ERROR_COUNTER.increment();
}
return connectionId;
});
}
/**
* Removes the "presence" for the given device. Callers should call this method when they have been notified that
* the client's underlying network connection has been closed.
*
* @param accountIdentifier the identifier of the account for the disconnected device
* @param deviceId the ID of the disconnected device within the given account
*
* @return a future that completes when the presence has been removed
*/
public CompletionStage<Void> handleClientDisconnected(final UUID accountIdentifier, final byte deviceId) {
if (pubSubConnection == null) {
throw new IllegalStateException("Presence manager not started");
}
final AtomicReference<CompletionStage<Void>> unsubscribeFuture = new AtomicReference<>();
// Note that we're relying on some specific implementation details of `ConcurrentHashMap#compute(...)`. In
// particular, the behavioral contract for `ConcurrentHashMap#compute(...)` says:
//
// > The entire method invocation is performed atomically. The supplied function is invoked exactly once per
// > invocation of this method. Some attempted update operations on this map by other threads may be blocked while
// > computation is in progress, so the computation should be short and simple.
//
// This provides a mechanism to make sure that we enqueue subscription/unsubscription operations in the same order
// as adding/removing listeners from the map and helps us avoid races and conflicts. Note that the enqueued
// operation is asynchronous; we're not blocking on it in the scope of the `compute` operation.
listenersByAccountAndDeviceIdentifier.compute(new AccountAndDeviceIdentifier(accountIdentifier, deviceId),
(ignored, existingListener) -> {
unsubscribeFuture.set(pubSubConnection.withPubSubConnection(connection ->
connection.async().sunsubscribe(getClientPresenceKey(accountIdentifier, deviceId)))
.thenRun(Util.NOOP));
return null;
});
return unsubscribeFuture.get().whenComplete((ignored, throwable) -> {
if (throwable != null) {
UNSUBSCRIBE_ERROR_COUNTER.increment();
}
});
}
/**
* Publishes an event notifying a specific device that a new message is available for retrieval. This method indicates
* whether the target device is "present" (i.e. has an active listener). Callers may choose to take follow-up action
* (like sending a push notification) if the target device is not present.
*
* @param accountIdentifier the account identifier of the receiving device
* @param deviceId the ID of the receiving device within the target account
*
* @return a future that yields {@code true} if the target device had an active listener or {@code false} otherwise
*/
public CompletionStage<Boolean> handleNewMessageAvailable(final UUID accountIdentifier, final byte deviceId) {
if (pubSubConnection == null) {
throw new IllegalStateException("Presence manager not started");
}
return pubSubConnection.withPubSubConnection(connection ->
connection.async().spublish(getClientPresenceKey(accountIdentifier, deviceId), NEW_MESSAGE_EVENT_BYTES))
.thenApply(listeners -> listeners > 0);
}
/**
* Tests whether a client with the given account/device is connected to this presence manager instance.
*
* @param accountUuid the account identifier for the client to check
* @param deviceId the ID of the device within the given account
*
* @return {@code true} if a client with the given account/device is connected to this presence manager instance or
* {@code false} if the client is not connected at all or is connected to a different presence manager instance
*/
public boolean isLocallyPresent(final UUID accountUuid, final byte deviceId) {
return listenersByAccountAndDeviceIdentifier.containsKey(new AccountAndDeviceIdentifier(accountUuid, deviceId));
}
/**
* Broadcasts a request that all devices associated with the identified account and connected to any client presence
* instance close their network connections.
*
* @param accountIdentifier the account identifier for which to request disconnection
*
* @return a future that completes when the request has been sent
*/
public CompletableFuture<Void> requestDisconnection(final UUID accountIdentifier) {
return requestDisconnection(accountIdentifier, Device.ALL_POSSIBLE_DEVICE_IDS);
}
/**
* Broadcasts a request that the specified devices associated with the identified account and connected to any client
* presence instance close their network connections.
*
* @param accountIdentifier the account identifier for which to request disconnection
* @param deviceIds the IDs of the devices for which to request disconnection
*
* @return a future that completes when the request has been sent
*/
public CompletableFuture<Void> requestDisconnection(final UUID accountIdentifier, final Collection<Byte> deviceIds) {
return CompletableFuture.allOf(deviceIds.stream()
.map(deviceId -> {
final byte[] clientPresenceKey = getClientPresenceKey(accountIdentifier, deviceId);
return clusterClient.withBinaryCluster(connection -> connection.async()
.spublish(clientPresenceKey, DISCONNECT_REQUESTED_EVENT_BYTES))
.toCompletableFuture();
})
.toArray(CompletableFuture[]::new));
}
@VisibleForTesting
void resubscribe(final ClusterTopologyChangedEvent clusterTopologyChangedEvent) {
final boolean[] changedSlots = RedisClusterUtil.getChangedSlots(clusterTopologyChangedEvent);
final Map<Integer, List<byte[]>> clientPresenceKeysBySlot = new HashMap<>();
// Organize subscriptions by slot so we can issue a smaller number of larger resubscription commands
listenersByAccountAndDeviceIdentifier.keySet()
.stream()
.map(accountAndDeviceIdentifier -> getClientPresenceKey(accountAndDeviceIdentifier.accountIdentifier(), accountAndDeviceIdentifier.deviceId()))
.forEach(clientPresenceKey -> {
final int slot = SlotHash.getSlot(clientPresenceKey);
if (changedSlots[slot]) {
clientPresenceKeysBySlot.computeIfAbsent(slot, ignored -> new ArrayList<>()).add(clientPresenceKey);
}
});
// Issue one resubscription command per affected slot
clientPresenceKeysBySlot.forEach((slot, clientPresenceKeys) -> {
if (pubSubConnection != null) {
final byte[][] clientPresenceKeyArray = clientPresenceKeys.toArray(byte[][]::new);
pubSubConnection.usePubSubConnection(connection -> connection.sync().ssubscribe(clientPresenceKeyArray));
}
});
}
@Override
public void smessage(final RedisClusterNode node, final byte[] shardChannel, final byte[] message) {
final ClientEvent clientEvent;
try {
clientEvent = ClientEvent.parseFrom(message);
} catch (final InvalidProtocolBufferException e) {
logger.error("Failed to parse pub/sub event protobuf", e);
return;
}
final AccountAndDeviceIdentifier accountAndDeviceIdentifier = parseClientPresenceKey(shardChannel);
@Nullable final ClientEventListener listener =
listenersByAccountAndDeviceIdentifier.get(accountAndDeviceIdentifier);
if (listener != null) {
switch (clientEvent.getEventCase()) {
case NEW_MESSAGE_AVAILABLE -> listener.handleNewMessageAvailable();
case CLIENT_CONNECTED -> {
// Only act on new connections to other presence manager instances; we'll learn about displacements in THIS
// instance when we update the listener map in `handleClientConnected`
if (!this.serverId.equals(UUIDUtil.fromByteString(clientEvent.getClientConnected().getServerId()))) {
listenerEventExecutor.execute(() -> listener.handleConnectionDisplaced(true));
}
}
case DISCONNECT_REQUESTED -> listenerEventExecutor.execute(() -> listener.handleConnectionDisplaced(false));
default -> logger.warn("Unexpected client event type: {}", clientEvent.getClass());
}
} else {
MESSAGE_WITHOUT_LISTENER_COUNTER.increment();
}
}
@VisibleForTesting
static byte[] getClientPresenceKey(final UUID accountIdentifier, final byte deviceId) {
return ("client_presence::{" + accountIdentifier + "::" + deviceId + "}").getBytes(StandardCharsets.UTF_8);
}
private static AccountAndDeviceIdentifier parseClientPresenceKey(final byte[] clientPresenceKeyBytes) {
final String clientPresenceKey = new String(clientPresenceKeyBytes, StandardCharsets.UTF_8);
final int uuidStart = "client_presence::{".length();
final UUID accountIdentifier = UUID.fromString(clientPresenceKey.substring(uuidStart, uuidStart + 36));
final byte deviceId = Byte.parseByte(clientPresenceKey.substring(uuidStart + 38, clientPresenceKey.length() - 1));
return new AccountAndDeviceIdentifier(accountIdentifier, deviceId);
}
}
@@ -7,7 +7,6 @@ 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;
@@ -20,17 +19,11 @@ abstract class AbstractFaultTolerantPubSubConnection<K, V, C extends StatefulRed
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) {
protected AbstractFaultTolerantPubSubConnection(final String name, final C pubSubConnection) {
this.name = name;
this.pubSubConnection = pubSubConnection;
this.retry = retry;
this.executeTimer = Metrics.timer(name(getClass(), "execute"), "clusterName", name + "-pubsub");
}
@@ -41,7 +34,7 @@ abstract class AbstractFaultTolerantPubSubConnection<K, V, C extends StatefulRed
public void usePubSubConnection(final Consumer<C> consumer) {
try {
retry.executeRunnable(() -> executeTimer.record(() -> consumer.accept(pubSubConnection)));
executeTimer.record(() -> consumer.accept(pubSubConnection));
} catch (final Throwable t) {
if (t instanceof RedisException) {
throw (RedisException) t;
@@ -53,7 +46,7 @@ abstract class AbstractFaultTolerantPubSubConnection<K, V, C extends StatefulRed
public <T> T withPubSubConnection(final Function<C, T> function) {
try {
return retry.executeCallable(() -> executeTimer.record(() -> function.apply(pubSubConnection)));
return executeTimer.record(() -> function.apply(pubSubConnection));
} catch (final Throwable t) {
if (t instanceof RedisException) {
throw (RedisException) t;
@@ -11,6 +11,7 @@ import io.lettuce.core.cluster.pubsub.StatefulRedisClusterPubSubConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.scheduler.Scheduler;
import java.util.function.Consumer;
public class FaultTolerantPubSubClusterConnection<K, V> extends AbstractFaultTolerantPubSubConnection<K, V, StatefulRedisClusterPubSubConnection<K, V>> {
@@ -21,11 +22,10 @@ public class FaultTolerantPubSubClusterConnection<K, V> extends AbstractFaultTol
protected FaultTolerantPubSubClusterConnection(final String name,
final StatefulRedisClusterPubSubConnection<K, V> pubSubConnection,
final Retry retry,
final Retry resubscribeRetry,
final Scheduler topologyChangedEventScheduler) {
super(name, pubSubConnection, retry);
super(name, pubSubConnection);
pubSubConnection.setNodeMessagePropagation(true);
@@ -33,17 +33,28 @@ public class FaultTolerantPubSubClusterConnection<K, V> extends AbstractFaultTol
this.topologyChangedEventScheduler = topologyChangedEventScheduler;
}
public void subscribeToClusterTopologyChangedEvents(final Runnable eventHandler) {
public void subscribeToClusterTopologyChangedEvents(final Consumer<ClusterTopologyChangedEvent> eventHandler) {
usePubSubConnection(connection -> connection.getResources().eventBus().get()
.filter(event -> event instanceof ClusterTopologyChangedEvent)
.filter(event -> {
// If we use shared `ClientResources` for multiple clients, we may receive topology change events for clusters
// other than our own. Filter for clusters that have at least one node in common with our current view of our
// partitions.
if (event instanceof ClusterTopologyChangedEvent clusterTopologyChangedEvent) {
return withPubSubConnection(c -> c.getPartitions().stream().anyMatch(redisClusterNode ->
clusterTopologyChangedEvent.before().contains(redisClusterNode) ||
clusterTopologyChangedEvent.after().contains(redisClusterNode)));
}
return false;
})
.subscribeOn(topologyChangedEventScheduler)
.subscribe(event -> {
logger.info("Got topology change event for {}, resubscribing all keyspace notifications", getName());
resubscribeRetry.executeRunnable(() -> {
try {
eventHandler.run();
eventHandler.accept((ClusterTopologyChangedEvent) event);
} catch (final RuntimeException e) {
logger.warn("Resubscribe for {} failed", getName(), e);
throw e;
@@ -5,15 +5,13 @@
package org.whispersystems.textsecuregcm.redis;
import io.github.resilience4j.retry.Retry;
import io.lettuce.core.pubsub.StatefulRedisPubSubConnection;
public class FaultTolerantPubSubConnection<K, V> extends AbstractFaultTolerantPubSubConnection<K, V, StatefulRedisPubSubConnection<K, V>> {
protected FaultTolerantPubSubConnection(final String name,
final StatefulRedisPubSubConnection<K, V> pubSubConnection,
final Retry retry) {
final StatefulRedisPubSubConnection<K, V> pubSubConnection) {
super(name, pubSubConnection, retry);
super(name, pubSubConnection);
}
}
@@ -59,6 +59,17 @@ public class FaultTolerantRedisClient {
this.name = name;
// Lettuce will issue a CLIENT SETINFO command unconditionally if these fields are set (and they are by default),
// which can generate a bunch of spurious warnings in versions of Redis before 7.2.0.
//
// See:
//
// - https://github.com/redis/lettuce/pull/2823
// - https://github.com/redis/lettuce/issues/2817
redisUri.setClientName(null);
redisUri.setLibraryName(null);
redisUri.setLibraryVersion(null);
final LettuceShardCircuitBreaker lettuceShardCircuitBreaker = new LettuceShardCircuitBreaker(name,
circuitBreakerConfiguration.toCircuitBreakerConfig(), Schedulers.newSingle("topology-changed-" + name, true));
this.redisClient = RedisClient.create(clientResourcesBuilder.build(), redisUri);
@@ -147,13 +158,13 @@ public class FaultTolerantRedisClient {
final StatefulRedisPubSubConnection<String, String> pubSubConnection = redisClient.connectPubSub();
pubSubConnections.add(pubSubConnection);
return new FaultTolerantPubSubConnection<>(name, pubSubConnection, retry);
return new FaultTolerantPubSubConnection<>(name, pubSubConnection);
}
public FaultTolerantPubSubConnection<byte[], byte[]> createBinaryPubSubConnection() {
final StatefulRedisPubSubConnection<byte[], byte[]> pubSubConnection = redisClient.connectPubSub(ByteArrayCodec.INSTANCE);
pubSubConnections.add(pubSubConnection);
return new FaultTolerantPubSubConnection<>(name, pubSubConnection, retry);
return new FaultTolerantPubSubConnection<>(name, pubSubConnection);
}
}
@@ -75,6 +75,19 @@ public class FaultTolerantRedisClusterClient {
this.name = name;
// Lettuce will issue a CLIENT SETINFO command unconditionally if these fields are set (and they are by default),
// which can generate a bunch of spurious warnings in versions of Redis before 7.2.0.
//
// See:
//
// - https://github.com/redis/lettuce/pull/2823
// - https://github.com/redis/lettuce/issues/2817
redisUris.forEach(redisUri -> {
redisUri.setClientName(null);
redisUri.setLibraryName(null);
redisUri.setLibraryVersion(null);
});
final LettuceShardCircuitBreaker lettuceShardCircuitBreaker = new LettuceShardCircuitBreaker(name,
circuitBreakerConfig.toCircuitBreakerConfig(), Schedulers.newSingle("topology-changed-" + name, true));
this.clusterClient = RedisClusterClient.create(
@@ -198,8 +211,15 @@ public class FaultTolerantRedisClusterClient {
final StatefulRedisClusterPubSubConnection<String, String> pubSubConnection = clusterClient.connectPubSub();
pubSubConnections.add(pubSubConnection);
return new FaultTolerantPubSubClusterConnection<>(name, pubSubConnection, retry, topologyChangedEventRetry,
return new FaultTolerantPubSubClusterConnection<>(name, pubSubConnection, topologyChangedEventRetry,
Schedulers.newSingle(name + "-redisPubSubEvents", true));
}
public FaultTolerantPubSubClusterConnection<byte[], byte[]> createBinaryPubSubConnection() {
final StatefulRedisClusterPubSubConnection<byte[], byte[]> pubSubConnection = clusterClient.connectPubSub(ByteArrayCodec.INSTANCE);
pubSubConnections.add(pubSubConnection);
return new FaultTolerantPubSubClusterConnection<>(name, pubSubConnection, topologyChangedEventRetry,
Schedulers.newSingle(name + "-redisPubSubEvents", true));
}
}
@@ -23,6 +23,7 @@ import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import java.net.SocketAddress;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@@ -195,9 +196,6 @@ public class LettuceShardCircuitBreaker implements NettyCustomizer {
logger.trace("Breaker state is {}", breaker.getState());
// Note: io.lettuce.core.protocol.CommandHandler also supports batches (List/Collection<RedisCommand>),
// but we do not use that feature, so we can just check for single commands
//
// There are two types of RedisCommands that are not CompleteableCommand:
// - io.lettuce.core.protocol.Command
// - io.lettuce.core.protocol.PristineFallbackCommand
@@ -206,36 +204,55 @@ public class LettuceShardCircuitBreaker implements NettyCustomizer {
// to consume responses.
if (msg instanceof RedisCommand<?, ?, ?> rc && rc instanceof CompleteableCommand<?> command) {
try {
breaker.acquirePermission();
// state can change in acquirePermission()
logger.trace("Breaker is permitted: {}", breaker.getState());
final long startNanos = System.nanoTime();
command.onComplete((ignored, throwable) -> {
final long durationNanos = System.nanoTime() - startNanos;
// RedisNoScriptException doesn’t indicate a fault the breaker can protect
if (throwable != null && !(throwable instanceof RedisNoScriptException)) {
breaker.onError(durationNanos, TimeUnit.NANOSECONDS, throwable);
logger.warn("Command completed with error", throwable);
} else {
breaker.onSuccess(durationNanos, TimeUnit.NANOSECONDS);
}
});
instrumentCommand(command);
} catch (final CallNotPermittedException e) {
rc.completeExceptionally(e);
promise.tryFailure(e);
return;
}
} else if (msg instanceof Collection<?> collection &&
!collection.isEmpty() &&
collection.stream().allMatch(obj -> obj instanceof RedisCommand && obj instanceof CompleteableCommand<?>)) {
@SuppressWarnings("unchecked") final Collection<RedisCommand<?, ?, ?>> commandCollection =
(Collection<RedisCommand<?, ?, ?>>) collection;
try {
// If we have a collection of commands, we only acquire a single permit for the whole batch (since there's
// only a single write promise to fail). We choose a single command from the collection to sample for failure.
instrumentCommand((CompleteableCommand<?>) commandCollection.iterator().next());
} catch (final CallNotPermittedException e) {
commandCollection.forEach(redisCommand -> redisCommand.completeExceptionally(e));
promise.tryFailure(e);
return;
}
} else {
logger.warn("Unexpected msg type: {}", msg.getClass());
}
super.write(ctx, msg, promise);
}
private void instrumentCommand(final CompleteableCommand<?> command) throws CallNotPermittedException {
breaker.acquirePermission();
// state can change in acquirePermission()
logger.trace("Breaker is permitted: {}", breaker.getState());
final long startNanos = System.nanoTime();
command.onComplete((ignored, throwable) -> {
final long durationNanos = System.nanoTime() - startNanos;
// RedisNoScriptException doesn’t indicate a fault the breaker can protect
if (throwable != null && !(throwable instanceof RedisNoScriptException)) {
breaker.onError(durationNanos, TimeUnit.NANOSECONDS, throwable);
logger.warn("Command completed with error", throwable);
} else {
breaker.onSuccess(durationNanos, TimeUnit.NANOSECONDS);
}
});
}
}
}
@@ -45,7 +45,7 @@ public interface SpamChecker {
final ContainerRequestContext requestContext,
final Optional<? extends AccountAndAuthenticatedDeviceHolder> maybeSource,
final Optional<Account> maybeDestination,
final Optional<ServiceIdentifier> destinationIdentifier);
final Optional<ServiceIdentifier> maybeDestinationIdentifier);
static SpamChecker noop() {
return (ignoredContext, ignoredSource, ignoredDestination, ignoredDestinationIdentifier) -> NotSpam.EMPTY_TOKEN;
@@ -8,7 +8,11 @@ package org.whispersystems.textsecuregcm.spam;
import io.dropwizard.configuration.ConfigurationValidationException;
import io.dropwizard.lifecycle.Managed;
import java.io.IOException;
import java.util.List;
import java.util.function.Function;
import javax.validation.Validator;
import org.whispersystems.textsecuregcm.captcha.CaptchaChecker;
import org.whispersystems.textsecuregcm.captcha.CaptchaClient;
import org.whispersystems.textsecuregcm.storage.ReportedMessageListener;
/**
@@ -80,4 +84,13 @@ public interface SpamFilter extends Managed {
* @return a {@link RegistrationRecoveryChecker} controlled by the spam filter
*/
RegistrationRecoveryChecker getRegistrationRecoveryChecker();
/**
* Return a function that will be used to lazily fetch the captcha client for a specified scheme. This is to avoid
* initialization issues with the spam filter if eagerly fetched.
*
* @return a {@link Function} that takes the scheme and returns a {@link CaptchaClient}. Returns null if no captcha
* client for the scheme exists
*/
Function<String, CaptchaClient> getCaptchaClientSupplier();
}
@@ -18,10 +18,10 @@ import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Predicate;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
@@ -29,7 +29,6 @@ import org.whispersystems.textsecuregcm.auth.StoredRegistrationLock;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.Device.DeviceCapabilities;
import org.whispersystems.textsecuregcm.util.ByteArrayBase64UrlAdapter;
import org.whispersystems.textsecuregcm.util.IdentityKeyAdapter;
@@ -116,7 +115,11 @@ public class Account {
@JsonProperty("bcr")
@Nullable
private byte[] backupCredentialRequest;
private byte[] messagesBackupCredentialRequest;
@JsonProperty("mbcr")
@Nullable
private byte[] mediaBackupCredentialRequest;
@JsonProperty("bv")
@Nullable
@@ -274,33 +277,14 @@ public class Account {
return devices.stream().filter(device -> device.getId() == deviceId).findFirst();
}
public boolean isStorageSupported() {
public boolean hasCapability(final DeviceCapability capability) {
requireNotStale();
return devices.stream().anyMatch(device -> device.getCapabilities() != null && device.getCapabilities().storage());
}
public boolean isTransferSupported() {
requireNotStale();
return Optional.ofNullable(getPrimaryDevice().getCapabilities())
.map(Device.DeviceCapabilities::transfer)
.orElse(false);
}
public boolean isDeleteSyncSupported() {
return allDevicesHaveCapability(DeviceCapabilities::deleteSync);
}
public boolean isVersionedExpirationTimerSupported() {
return allDevicesHaveCapability(DeviceCapabilities::versionedExpirationTimer);
}
private boolean allDevicesHaveCapability(final Predicate<DeviceCapabilities> predicate) {
requireNotStale();
return devices.stream()
.allMatch(device -> device.getCapabilities() != null && predicate.test(device.getCapabilities()));
return switch (capability.getAccountCapabilityMode()) {
case PRIMARY_DEVICE -> getPrimaryDevice().hasCapability(capability);
case ANY_DEVICE -> devices.stream().anyMatch(device -> device.hasCapability(capability));
case ALL_DEVICES -> devices.stream().allMatch(device -> device.hasCapability(capability));
};
}
public byte getNextDeviceId() {
@@ -509,19 +493,33 @@ public class Account {
this.svr3ShareSet = svr3ShareSet;
}
public byte[] getBackupCredentialRequest() {
return backupCredentialRequest;
public void setBackupCredentialRequests(final byte[] messagesBackupCredentialRequest,
final byte[] mediaBackupCredentialRequest) {
requireNotStale();
this.messagesBackupCredentialRequest = messagesBackupCredentialRequest;
this.mediaBackupCredentialRequest = mediaBackupCredentialRequest;
}
public void setBackupCredentialRequest(final byte[] backupCredentialRequest) {
this.backupCredentialRequest = backupCredentialRequest;
public Optional<byte[]> getBackupCredentialRequest(final BackupCredentialType credentialType) {
requireNotStale();
return Optional.ofNullable(switch (credentialType) {
case MESSAGES -> messagesBackupCredentialRequest;
case MEDIA -> mediaBackupCredentialRequest;
});
}
public @Nullable BackupVoucher getBackupVoucher() {
requireNotStale();
return backupVoucher;
}
public void setBackupVoucher(final @Nullable BackupVoucher backupVoucher) {
requireNotStale();
this.backupVoucher = backupVoucher;
}
@@ -36,6 +36,7 @@ import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.util.AsyncTimerUtil;
@@ -321,7 +322,9 @@ public class Accounts extends AbstractDynamoDbStore {
// Carry over the old backup id commitment. If the new account claimer cannot does not have the secret used to
// generate their backup-id, this credential is useless, however if they can produce the same credential they
// won't be rate-limited for setting their backup-id.
accountToCreate.setBackupCredentialRequest(existingAccount.getBackupCredentialRequest());
accountToCreate.setBackupCredentialRequests(
existingAccount.getBackupCredentialRequest(BackupCredentialType.MESSAGES).orElse(null),
existingAccount.getBackupCredentialRequest(BackupCredentialType.MEDIA).orElse(null));
// Carry over the old SVR3 share-set. This is required for an account to restore information from SVR. The share-
// set is not a secret, if the new account claimer does not have the SVR3 pin, it is useless.
@@ -68,6 +68,7 @@ import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfigurati
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.entities.DeviceInfo;
import org.whispersystems.textsecuregcm.entities.RestoreAccountRequest;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.entities.RemoteAttachment;
@@ -75,6 +76,7 @@ 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.push.PubSubClientEventManager;
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubConnection;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
@@ -125,6 +127,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
private final SecureStorageClient secureStorageClient;
private final SecureValueRecovery2Client secureValueRecovery2Client;
private final ClientPresenceManager clientPresenceManager;
private final PubSubClientEventManager pubSubClientEventManager;
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
private final ClientPublicKeysManager clientPublicKeysManager;
private final Executor accountLockExecutor;
@@ -142,6 +145,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
private final Map<TimestampedDeviceIdentifier, CompletableFuture<Optional<RemoteAttachment>>> waitForTransferArchiveFuturesByDeviceIdentifier =
new ConcurrentHashMap<>();
private final Map<String, CompletableFuture<Optional<RestoreAccountRequest>>> waitForRestoreAccountRequestFuturesByToken =
new ConcurrentHashMap<>();
private static final int SHA256_HASH_LENGTH = getSha256MessageDigest().getDigestLength();
private static final Duration RECENTLY_ADDED_DEVICE_TTL = Duration.ofHours(1);
@@ -152,6 +158,10 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
private static final String TRANSFER_ARCHIVE_PREFIX = "transfer_archive::";
private static final String TRANSFER_ARCHIVE_KEYSPACE_PATTERN = "__keyspace@0__:" + TRANSFER_ARCHIVE_PREFIX + "*";
private static final Duration RESTORE_ACCOUNT_REQUEST_TTL = Duration.ofHours(1);
private static final String RESTORE_ACCOUNT_REQUEST_PREFIX = "restore_account::";
private static final String RESTORE_ACCOUNT_REQUEST_KEYSPACE_PATTERN = "__keyspace@0__:" + RESTORE_ACCOUNT_REQUEST_PREFIX + "*";
private static final ObjectWriter ACCOUNT_REDIS_JSON_WRITER = SystemMapper.jsonMapper()
.writer(SystemMapper.excludingField(Account.class, List.of("uuid")));
@@ -197,6 +207,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final SecureStorageClient secureStorageClient,
final SecureValueRecovery2Client secureValueRecovery2Client,
final ClientPresenceManager clientPresenceManager,
final PubSubClientEventManager pubSubClientEventManager,
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
final ClientPublicKeysManager clientPublicKeysManager,
final Executor accountLockExecutor,
@@ -215,6 +226,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
this.secureStorageClient = secureStorageClient;
this.secureValueRecovery2Client = secureValueRecovery2Client;
this.clientPresenceManager = clientPresenceManager;
this.pubSubClientEventManager = pubSubClientEventManager;
this.registrationRecoveryPasswordsManager = requireNonNull(registrationRecoveryPasswordsManager);
this.clientPublicKeysManager = clientPublicKeysManager;
this.accountLockExecutor = accountLockExecutor;
@@ -238,7 +250,8 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
public void start() {
pubSubConnection.usePubSubConnection(connection -> {
connection.addListener(this);
connection.sync().psubscribe(LINKED_DEVICE_KEYSPACE_PATTERN, TRANSFER_ARCHIVE_KEYSPACE_PATTERN);
connection.sync().psubscribe(LINKED_DEVICE_KEYSPACE_PATTERN, TRANSFER_ARCHIVE_KEYSPACE_PATTERN,
RESTORE_ACCOUNT_REQUEST_KEYSPACE_PATTERN);
});
}
@@ -320,7 +333,10 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
keysManager.deleteSingleUsePreKeys(pni),
messagesManager.clear(aci),
profilesManager.deleteAll(aci))
.thenRunAsync(() -> clientPresenceManager.disconnectAllPresencesForUuid(aci), clientPresenceExecutor)
.thenRunAsync(() -> {
clientPresenceManager.disconnectAllPresencesForUuid(aci);
pubSubClientEventManager.requestDisconnection(aci);
}, clientPresenceExecutor)
.thenCompose(ignored -> accounts.reclaimAccount(e.getExistingAccount(), account, additionalWriteItems))
.thenCompose(ignored -> {
// We should have cleared all messages before overwriting the old account, but more may have arrived
@@ -585,6 +601,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
.whenCompleteAsync((ignored, throwable) -> {
if (throwable == null) {
RedisOperation.unchecked(() -> clientPresenceManager.disconnectPresence(accountIdentifier, deviceId));
pubSubClientEventManager.requestDisconnection(accountIdentifier, List.of(deviceId));
}
}, clientPresenceExecutor);
}
@@ -1231,9 +1248,11 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
registrationRecoveryPasswordsManager.removeForNumber(account.getNumber()))
.thenCompose(ignored -> accounts.delete(account.getUuid(), additionalWriteItems))
.thenCompose(ignored -> redisDeleteAsync(account))
.thenRunAsync(() -> RedisOperation.unchecked(() ->
account.getDevices().forEach(device ->
clientPresenceManager.disconnectPresence(account.getUuid(), device.getId()))), clientPresenceExecutor);
.thenRunAsync(() -> {
RedisOperation.unchecked(() -> clientPresenceManager.disconnectAllPresencesForUuid(account.getUuid()));
pubSubClientEventManager.requestDisconnection(account.getUuid());
}, clientPresenceExecutor);
}
private String getAccountMapKey(String key) {
@@ -1496,6 +1515,44 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
":" + destinationDeviceCreationTimestamp.toEpochMilli();
}
public CompletableFuture<Optional<RestoreAccountRequest>> waitForRestoreAccountRequest(final String token, final Duration timeout) {
return waitForPubSubKey(waitForRestoreAccountRequestFuturesByToken,
token,
getRestoreAccountRequestKey(token),
timeout,
this::handleRestoreAccountRequest);
}
public CompletableFuture<Void> recordRestoreAccountRequest(final String token, final RestoreAccountRequest restoreAccountRequest) {
final String key = getRestoreAccountRequestKey(token);
final String requestJson;
try {
requestJson = SystemMapper.jsonMapper().writeValueAsString(restoreAccountRequest);
} catch (final JsonProcessingException e) {
throw new UncheckedIOException(e);
}
return pubSubRedisClient.withConnection(connection ->
connection.async().set(key, requestJson, SetArgs.Builder.ex(RESTORE_ACCOUNT_REQUEST_TTL)))
.thenRun(Util.NOOP)
.toCompletableFuture();
}
private void handleRestoreAccountRequest(final CompletableFuture<Optional<RestoreAccountRequest>> future, final String transferRequestJson) {
try {
future.complete(Optional.of(SystemMapper.jsonMapper().readValue(transferRequestJson, RestoreAccountRequest.class)));
} catch (final JsonProcessingException e) {
logger.error("Could not parse device transfer request JSON", e);
future.completeExceptionally(e);
}
}
private static String getRestoreAccountRequestKey(final String token) {
return RESTORE_ACCOUNT_REQUEST_PREFIX + token;
}
private <K, T> CompletableFuture<Optional<T>> waitForPubSubKey(final Map<K, CompletableFuture<Optional<T>>> futureMap,
final K mapKey,
final String redisKey,
@@ -1535,7 +1592,13 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
Optional.ofNullable(waitForDeviceFuturesByTokenIdentifier.remove(tokenIdentifier))
.ifPresent(future -> pubSubRedisClient.withConnection(connection -> connection.async().get(getLinkedDeviceKey(tokenIdentifier)))
.thenAccept(deviceInfoJson -> handleDeviceAdded(future, deviceInfoJson)));
.whenComplete((deviceInfoJson, throwable) -> {
if (throwable != null) {
future.completeExceptionally(throwable);
} else {
handleDeviceAdded(future, deviceInfoJson);
}
}));
} else if (TRANSFER_ARCHIVE_KEYSPACE_PATTERN.equals(pattern) && "set".equalsIgnoreCase(message)) {
// The `- 1` here compensates for the '*' in the pattern
final String[] deviceIdentifierComponents =
@@ -1560,10 +1623,30 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
Optional.ofNullable(waitForTransferArchiveFuturesByDeviceIdentifier.remove(deviceIdentifier))
.ifPresent(future -> pubSubRedisClient.withConnection(connection -> connection.async().get(transferArchiveKey))
.thenAccept(transferArchiveJson -> handleTransferArchiveAdded(future, transferArchiveJson)));
.whenComplete((transferArchiveJson, throwable) -> {
if (throwable != null) {
future.completeExceptionally(throwable);
} else {
handleTransferArchiveAdded(future, transferArchiveJson);
}
}));
} catch (final IllegalArgumentException e) {
logger.error("Could not parse timestamped device identifier", e);
}
} else if (RESTORE_ACCOUNT_REQUEST_KEYSPACE_PATTERN.equalsIgnoreCase(pattern) && "set".equalsIgnoreCase(message)) {
// The `- 1` here compensates for the '*' in the pattern
final String token = channel.substring(RESTORE_ACCOUNT_REQUEST_KEYSPACE_PATTERN.length() - 1);
Optional.ofNullable(waitForRestoreAccountRequestFuturesByToken.remove(token))
.ifPresent(future -> pubSubRedisClient.withConnection(connection -> connection.async().get(
getRestoreAccountRequestKey(token)))
.whenComplete((requestJson, throwable) -> {
if (throwable != null) {
future.completeExceptionally(throwable);
} else {
handleRestoreAccountRequest(future, requestJson);
}
}));
}
}
@@ -6,15 +6,21 @@ package org.whispersystems.textsecuregcm.storage;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSetter;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.time.Duration;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.OptionalInt;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javax.annotation.Nullable;
import com.google.common.annotations.VisibleForTesting;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.util.DeviceCapabilityAdapter;
import org.whispersystems.textsecuregcm.util.DeviceNameByteArrayAdapter;
public class Device {
@@ -72,7 +78,9 @@ public class Device {
private String userAgent;
@JsonProperty
private DeviceCapabilities capabilities;
@JsonSerialize(using = DeviceCapabilityAdapter.Serializer.class)
@JsonDeserialize(using = DeviceCapabilityAdapter.Deserializer.class)
private Set<DeviceCapability> capabilities = Collections.emptySet();
public String getApnId() {
return apnId;
@@ -166,13 +174,20 @@ public class Device {
return new SaltedTokenHash(authToken, salt);
}
@Nullable
public DeviceCapabilities getCapabilities() {
@VisibleForTesting
public Set<DeviceCapability> getCapabilities() {
return capabilities;
}
public void setCapabilities(DeviceCapabilities capabilities) {
this.capabilities = capabilities;
@JsonSetter
public void setCapabilities(@Nullable final Set<DeviceCapability> capabilities) {
this.capabilities = (capabilities == null || capabilities.isEmpty())
? Collections.emptySet()
: EnumSet.copyOf(capabilities);
}
public boolean hasCapability(final DeviceCapability capability) {
return capabilities.contains(capability);
}
public boolean isExpired() {
@@ -220,8 +235,4 @@ public class Device {
public String getUserAgent() {
return this.userAgent;
}
public record DeviceCapabilities(boolean storage, boolean transfer, boolean deleteSync,
boolean versionedExpirationTimer) {
}
}
@@ -0,0 +1,63 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import java.util.Optional;
public enum DeviceCapability {
STORAGE("storage", AccountCapabilityMode.ANY_DEVICE, false, false),
TRANSFER("transfer", AccountCapabilityMode.PRIMARY_DEVICE, false, false),
DELETE_SYNC("deleteSync", AccountCapabilityMode.ALL_DEVICES, true, true),
VERSIONED_EXPIRATION_TIMER("versionedExpirationTimer", AccountCapabilityMode.ALL_DEVICES, true, true),
STORAGE_SERVICE_RECORD_KEY_ROTATION("ssre2", AccountCapabilityMode.ALL_DEVICES, true, true);
public enum AccountCapabilityMode {
PRIMARY_DEVICE,
ANY_DEVICE,
ALL_DEVICES,
}
private final String name;
private final AccountCapabilityMode accountCapabilityMode;
private final boolean preventDowngrade;
private final boolean includeInProfile;
DeviceCapability(final String name,
final AccountCapabilityMode accountCapabilityMode,
final boolean preventDowngrade,
final boolean includeInProfile) {
this.name = name;
this.accountCapabilityMode = accountCapabilityMode;
this.preventDowngrade = preventDowngrade;
this.includeInProfile = includeInProfile;
}
public String getName() {
return name;
}
public AccountCapabilityMode getAccountCapabilityMode() {
return accountCapabilityMode;
}
public boolean preventDowngrade() {
return preventDowngrade;
}
public boolean includeInProfile() {
return includeInProfile;
}
public static Optional<DeviceCapability> forName(final String name) {
for (final DeviceCapability capability : DeviceCapability.values()) {
if (capability.getName().equals(name)) {
return Optional.of(capability);
}
}
return Optional.empty();
}
}
@@ -1,21 +1,22 @@
package org.whispersystems.textsecuregcm.storage;
import java.time.Clock;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.entities.ApnRegistrationId;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.GcmRegistrationId;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.util.Util;
import java.time.Clock;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;
public record DeviceSpec(
byte[] deviceNameCiphertext,
String password,
String signalAgent,
Device.DeviceCapabilities capabilities,
Set<DeviceCapability> capabilities,
int aciRegistrationId,
int pniRegistrationId,
boolean fetchesMessages,
@@ -7,44 +7,31 @@ package org.whispersystems.textsecuregcm.storage;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Metrics;
import java.time.Duration;
import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.s3.S3ObjectMonitor;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.Util;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.services.appconfigdata.AppConfigDataClient;
import software.amazon.awssdk.services.appconfigdata.model.GetLatestConfigurationRequest;
import software.amazon.awssdk.services.appconfigdata.model.GetLatestConfigurationResponse;
import software.amazon.awssdk.services.appconfigdata.model.StartConfigurationSessionRequest;
import software.amazon.awssdk.services.appconfigdata.model.StartConfigurationSessionResponse;
public class DynamicConfigurationManager<T> {
private final String application;
private final String environment;
private final String configurationName;
private final AppConfigDataClient appConfigClient;
private final S3ObjectMonitor configMonitor;
private final Class<T> configurationClass;
// Set on initial config fetch
private final AtomicReference<T> configuration = new AtomicReference<>();
private final CountDownLatch initialized = new CountDownLatch(1);
private final ScheduledExecutorService scheduledExecutorService;
private String configurationToken = null;
private static final Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();
@@ -54,28 +41,9 @@ public class DynamicConfigurationManager<T> {
private static final Logger logger = LoggerFactory.getLogger(DynamicConfigurationManager.class);
public DynamicConfigurationManager(String application, String environment, String configurationName,
AwsCredentialsProvider awsCredentialsProvider, Class<T> configurationClass,
ScheduledExecutorService scheduledExecutorService) {
this(AppConfigDataClient
.builder()
.credentialsProvider(awsCredentialsProvider)
.overrideConfiguration(ClientOverrideConfiguration.builder()
.apiCallTimeout(Duration.ofSeconds(10))
.apiCallAttemptTimeout(Duration.ofSeconds(10)).build())
.build(),
application, environment, configurationName, configurationClass, scheduledExecutorService);
}
@VisibleForTesting
DynamicConfigurationManager(AppConfigDataClient appConfigClient, String application, String environment,
String configurationName, Class<T> configurationClass, ScheduledExecutorService scheduledExecutorService) {
this.appConfigClient = appConfigClient;
this.application = application;
this.environment = environment;
this.configurationName = configurationName;
public DynamicConfigurationManager(final S3ObjectMonitor configMonitor, final Class<T> configurationClass) {
this.configMonitor = configMonitor;
this.configurationClass = configurationClass;
this.scheduledExecutorService = scheduledExecutorService;
}
public T getConfiguration() {
@@ -88,92 +56,63 @@ public class DynamicConfigurationManager<T> {
return configuration.get();
}
public void start() {
public synchronized void start() {
if (initialized.getCount() == 0) {
return;
}
configuration.set(retrieveInitialDynamicConfiguration());
initialized.countDown();
scheduledExecutorService.scheduleWithFixedDelay(() -> {
this.configMonitor.start(this::receiveConfiguration);
// Starting an S3ObjectMonitor immediately does a blocking retrieve of the data, but it might
// fail to parse, in which case we wait for an update (which will happen on another thread) to
// give us a valid configuration before marking ourselves ready
while (configuration.get() == null) {
logger.warn("Failed to retrieve or parse initial dynamic configuration");
try {
retrieveDynamicConfiguration().ifPresent(configuration::set);
} catch (Exception e) {
logger.warn("Error retrieving dynamic configuration", e);
}
}, 0, 5, TimeUnit.SECONDS);
this.wait();
} catch (InterruptedException e) {}
}
initialized.countDown();
}
private Optional<T> retrieveDynamicConfiguration() throws JsonProcessingException {
if (configurationToken == null) {
logger.error("Invalid configuration token, will not be able to fetch configuration updates");
}
GetLatestConfigurationResponse latestConfiguration;
private synchronized void receiveConfiguration(InputStream configDataStream) {
final String configData;
try {
latestConfiguration = appConfigClient.getLatestConfiguration(GetLatestConfigurationRequest.builder()
.configurationToken(configurationToken)
.build());
// token to use in the next fetch
configurationToken = latestConfiguration.nextPollConfigurationToken();
logger.debug("next token: {}", configurationToken);
} catch (final RuntimeException e) {
configData = new String(configDataStream.readAllBytes());
} catch (IOException e) {
Metrics.counter(ERROR_COUNTER_NAME, ERROR_TYPE_TAG_NAME, "fetch").increment();
throw e;
return;
}
if (!latestConfiguration.configuration().asByteBuffer().hasRemaining()) {
// empty configuration means nothing has changed
return Optional.empty();
}
logger.info("Received new config of length {}, next configuration token: {}",
latestConfiguration.configuration().asByteBuffer().remaining(),
configurationToken);
try {
return parseConfiguration(latestConfiguration.configuration().asUtf8String(), configurationClass);
} catch (final JsonProcessingException e) {
Metrics.counter(ERROR_COUNTER_NAME,
ERROR_TYPE_TAG_NAME, "parse",
CONFIG_CLASS_TAG_NAME, configurationClass.getName()).increment();
throw e;
}
logger.info("Received new dynamic configuration of length {}", configData.length());
parseConfiguration(configData, configurationClass).ifPresent(configuration::set);
this.notify();
}
@VisibleForTesting
public static <T> Optional<T> parseConfiguration(final String configurationYaml, final Class<T> configurationClass)
throws JsonProcessingException {
final T configuration = SystemMapper.yamlMapper().readValue(configurationYaml, configurationClass);
public static <T> Optional<T> parseConfiguration(final String configurationYaml, final Class<T> configurationClass) {
final T configuration;
try {
configuration = SystemMapper.yamlMapper().readValue(configurationYaml, configurationClass);
} catch (final IOException e) {
logger.warn("Failed to parse dynamic configuration", e);
Metrics.counter(ERROR_COUNTER_NAME,
ERROR_TYPE_TAG_NAME, "parse",
CONFIG_CLASS_TAG_NAME, configurationClass.getName()).increment();
return Optional.empty();
}
final Set<ConstraintViolation<T>> violations = VALIDATOR.validate(configuration);
final Optional<T> maybeDynamicConfiguration;
if (violations.isEmpty()) {
maybeDynamicConfiguration = Optional.of(configuration);
} else {
if (!violations.isEmpty()) {
logger.warn("Failed to validate configuration: {}", violations);
maybeDynamicConfiguration = Optional.empty();
Metrics.counter(ERROR_COUNTER_NAME,
ERROR_TYPE_TAG_NAME, "validate",
CONFIG_CLASS_TAG_NAME, configurationClass.getName()).increment();
return Optional.empty();
}
return maybeDynamicConfiguration;
return Optional.of(configuration);
}
private T retrieveInitialDynamicConfiguration() {
for (;;) {
try {
if (configurationToken == null) {
// first time around, start the configuration session
final StartConfigurationSessionResponse startResponse = appConfigClient
.startConfigurationSession(StartConfigurationSessionRequest.builder()
.applicationIdentifier(application)
.environmentIdentifier(environment)
.configurationProfileIdentifier(configurationName).build());
configurationToken = startResponse.initialConfigurationToken();
}
return retrieveDynamicConfiguration().orElseThrow(() -> new IllegalStateException("No initial configuration available"));
} catch (Exception e) {
logger.warn("Error retrieving initial dynamic configuration", e);
Util.sleep(1000);
}
}
}
}
@@ -13,6 +13,7 @@ import com.google.protobuf.InvalidProtocolBufferException;
import io.dropwizard.lifecycle.Managed;
import io.lettuce.core.ZAddArgs;
import io.lettuce.core.cluster.SlotHash;
import io.lettuce.core.cluster.event.ClusterTopologyChangedEvent;
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
import io.lettuce.core.cluster.pubsub.RedisClusterPubSubAdapter;
import io.micrometer.core.instrument.Counter;
@@ -247,7 +248,7 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
pubSubConnection.usePubSubConnection(connection -> connection.sync().upstream().commands().unsubscribe());
}
private void resubscribeAll() {
private void resubscribeAll(final ClusterTopologyChangedEvent event) {
final Set<String> queueNames;
@@ -336,7 +337,8 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
final long earliestAllowableEphemeralTimestamp =
clock.millis() - MAX_EPHEMERAL_MESSAGE_DELAY.toMillis();
final Flux<MessageProtos.Envelope> allMessages = getAllMessages(destinationUuid, destinationDevice)
final Flux<MessageProtos.Envelope> allMessages = getAllMessages(destinationUuid, destinationDevice,
earliestAllowableEphemeralTimestamp)
.publish()
// We expect exactly two subscribers to this base flux:
// 1. the websocket that delivers messages to clients
@@ -375,7 +377,8 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
}
@VisibleForTesting
Flux<MessageProtos.Envelope> getAllMessages(final UUID destinationUuid, final byte destinationDevice) {
Flux<MessageProtos.Envelope> getAllMessages(final UUID destinationUuid, final byte destinationDevice,
final long earliestAllowableEphemeralTimestamp) {
// fetch messages by page
return getNextMessagePage(destinationUuid, destinationDevice, -1)
@@ -401,7 +404,14 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
final Mono<MessageProtos.Envelope> messageMono;
if (message.hasSharedMrmKey()) {
final Mono<?> experimentMono = maybeRunMrmViewExperiment(message, destinationUuid, destinationDevice);
final Mono<?> experimentMono;
if (isStaleEphemeralMessage(message, earliestAllowableEphemeralTimestamp)) {
// skip fetching content for message that will be discarded
experimentMono = Mono.empty();
} else {
experimentMono = maybeRunMrmViewExperiment(message, destinationUuid, destinationDevice);
}
// mrm views phase 1: messageMono for sharedMrmKey is always Mono.just(), because messages always have content
// To avoid races, wait for the experiment to run, but ignore any errors
@@ -0,0 +1,63 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.util;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import java.io.IOException;
import java.util.EnumSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
public class DeviceCapabilityAdapter {
private static final TypeReference<Map<String, Boolean>> STRING_TO_BOOLEAN_MAP_TYPE = new TypeReference<>() {};
private DeviceCapabilityAdapter() {
}
public static class Serializer extends JsonSerializer<Set<DeviceCapability>> {
@Override
public void serialize(final Set<DeviceCapability> capabilities,
final JsonGenerator jsonGenerator,
final SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeObject(capabilities.stream()
.collect(Collectors.toMap(DeviceCapability::getName, ignored -> true)));
}
}
public static class Deserializer extends JsonDeserializer<Set<DeviceCapability>> {
@Override
public Set<DeviceCapability> deserialize(final JsonParser jsonParser,
final DeserializationContext deserializationContext) throws IOException {
return mapToSet(jsonParser.readValueAs(STRING_TO_BOOLEAN_MAP_TYPE));
}
}
public static Set<DeviceCapability> mapToSet(Map<String, Boolean> capabilitiesMap) {
return capabilitiesMap.entrySet()
.stream()
.filter(Map.Entry::getValue)
.map(entry -> DeviceCapability.forName(entry.getKey()))
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toCollection(() -> EnumSet.noneOf(DeviceCapability.class)));
}
}
@@ -6,6 +6,12 @@
package org.whispersystems.textsecuregcm.util;
import io.lettuce.core.cluster.SlotHash;
import io.lettuce.core.cluster.event.ClusterTopologyChangedEvent;
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class RedisClusterUtil {
@@ -38,4 +44,51 @@ public class RedisClusterUtil {
public static String getMinimalHashTag(final int slot) {
return HASHES_BY_SLOT[slot];
}
/**
* Returns an array indicating which slots have moved as part of a {@link ClusterTopologyChangedEvent}. The elements
* of the array map to slots in the cluster; for example, if slot 1234 has changed, then element 1234 of the returned
* array will be {@code true}.
*
* @param clusterTopologyChangedEvent the event from which to derive an array of changed slots
*
* @return an array indicating which slots of changed
*/
public static boolean[] getChangedSlots(final ClusterTopologyChangedEvent clusterTopologyChangedEvent) {
final Map<String, RedisClusterNode> beforeNodesById = clusterTopologyChangedEvent.before().stream()
.collect(Collectors.toMap(RedisClusterNode::getNodeId, node -> node));
final Map<String, RedisClusterNode> afterNodesById = clusterTopologyChangedEvent.after().stream()
.collect(Collectors.toMap(RedisClusterNode::getNodeId, node -> node));
final Set<String> nodeIds = new HashSet<>(beforeNodesById.keySet());
nodeIds.addAll(afterNodesById.keySet());
final boolean[] changedSlots = new boolean[SlotHash.SLOT_COUNT];
for (final String nodeId : nodeIds) {
if (beforeNodesById.containsKey(nodeId) && afterNodesById.containsKey(nodeId)) {
// This node was present before and after the topology change, but its slots may have changed
final boolean[] beforeSlots = new boolean[SlotHash.SLOT_COUNT];
beforeNodesById.get(nodeId).getSlots().forEach(slot -> beforeSlots[slot] = true);
final boolean[] afterSlots = new boolean[SlotHash.SLOT_COUNT];
afterNodesById.get(nodeId).getSlots().forEach(slot -> afterSlots[slot] = true);
for (int slot = 0; slot < SlotHash.SLOT_COUNT; slot++) {
changedSlots[slot] |= beforeSlots[slot] ^ afterSlots[slot];
}
} else if (beforeNodesById.containsKey(nodeId)) {
// The node was present before the topology change, but is gone now; all of its slots should be considered
// changed
beforeNodesById.get(nodeId).getSlots().forEach(slot -> changedSlots[slot] = true);
} else {
// The node was present after the change, but wasn't there before; all of its slots should be considered
// changed
afterNodesById.get(nodeId).getSlots().forEach(slot -> changedSlots[slot] = true);
}
}
return changedSlots;
}
}
@@ -19,6 +19,7 @@ import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor;
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
import org.whispersystems.textsecuregcm.metrics.OpenWebSocketCounter;
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
import org.whispersystems.textsecuregcm.push.ReceiptSender;
@@ -47,6 +48,7 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
private final PushNotificationManager pushNotificationManager;
private final PushNotificationScheduler pushNotificationScheduler;
private final ClientPresenceManager clientPresenceManager;
private final PubSubClientEventManager pubSubClientEventManager;
private final ScheduledExecutorService scheduledExecutorService;
private final Scheduler messageDeliveryScheduler;
private final ClientReleaseManager clientReleaseManager;
@@ -61,6 +63,7 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
PushNotificationManager pushNotificationManager,
PushNotificationScheduler pushNotificationScheduler,
ClientPresenceManager clientPresenceManager,
PubSubClientEventManager pubSubClientEventManager,
ScheduledExecutorService scheduledExecutorService,
Scheduler messageDeliveryScheduler,
ClientReleaseManager clientReleaseManager,
@@ -71,6 +74,7 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
this.pushNotificationManager = pushNotificationManager;
this.pushNotificationScheduler = pushNotificationScheduler;
this.clientPresenceManager = clientPresenceManager;
this.pubSubClientEventManager = pubSubClientEventManager;
this.scheduledExecutorService = scheduledExecutorService;
this.messageDeliveryScheduler = messageDeliveryScheduler;
this.clientReleaseManager = clientReleaseManager;
@@ -121,6 +125,9 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
// It's preferable to start sending push notifications as soon as possible.
RedisOperation.unchecked(() -> clientPresenceManager.clearPresence(auth.getAccount().getUuid(), auth.getAuthenticatedDevice().getId(), connection));
pubSubClientEventManager.handleClientDisconnected(auth.getAccount().getUuid(),
auth.getAuthenticatedDevice().getId());
// Next, we stop listening for inbound messages. If a message arrives after this call, the websocket connection
// will not be notified and will not change its state, but that's okay because it has already closed and
// attempts to deliver mesages via this connection will not succeed.
@@ -147,6 +154,7 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
// Finally, we register this client's presence, which suppresses push notifications. We do this last because
// receiving extra push notifications is generally preferable to missing out on a push notification.
clientPresenceManager.setPresent(auth.getAccount().getUuid(), auth.getAuthenticatedDevice().getId(), connection);
pubSubClientEventManager.handleClientConnected(auth.getAccount().getUuid(), auth.getAuthenticatedDevice().getId(), connection);
renewPresenceFutureReference.set(scheduledExecutorService.scheduleAtFixedRate(() -> RedisOperation.unchecked(() ->
clientPresenceManager.renewPresence(auth.getAccount().getUuid(), auth.getAuthenticatedDevice().getId())),
@@ -45,6 +45,7 @@ import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor;
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.ClientEventListener;
import org.whispersystems.textsecuregcm.push.DisplacedPresenceListener;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
@@ -63,15 +64,13 @@ import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
public class WebSocketConnection implements MessageAvailabilityListener, DisplacedPresenceListener {
public class WebSocketConnection implements MessageAvailabilityListener, DisplacedPresenceListener, ClientEventListener {
private static final DistributionSummary messageTime = Metrics.summary(
name(MessageController.class, "messageDeliveryDuration"));
private static final DistributionSummary primaryDeviceMessageTime = Metrics.summary(
name(MessageController.class, "primaryDeviceMessageDeliveryDuration"));
private static final Counter sendMessageCounter = Metrics.counter(name(WebSocketConnection.class, "sendMessage"));
private static final Counter messageAvailableCounter = Metrics.counter(
name(WebSocketConnection.class, "messagesAvailable"));
private static final Counter messagesPersistedCounter = Metrics.counter(
name(WebSocketConnection.class, "messagesPersisted"));
private static final Counter bytesSentCounter = Metrics.counter(name(WebSocketConnection.class, "bytesSent"));
@@ -91,6 +90,9 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
"sendMessages");
private static final String SEND_MESSAGE_ERROR_COUNTER = MetricsUtil.name(WebSocketConnection.class,
"sendMessageError");
private static final String MESSAGE_AVAILABLE_COUNTER_NAME = name(WebSocketConnection.class, "messagesAvailable");
private static final String PRESENCE_MANAGER_TAG = "presenceManager";
private static final String STATUS_CODE_TAG = "status";
private static final String STATUS_MESSAGE_TAG = "message";
private static final String ERROR_TYPE_TAG = "errorType";
@@ -468,7 +470,9 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
return false;
}
messageAvailableCounter.increment();
Metrics.counter(MESSAGE_AVAILABLE_COUNTER_NAME,
PRESENCE_MANAGER_TAG, "legacy")
.increment();
storedMessageState.compareAndSet(StoredMessageState.EMPTY, StoredMessageState.CACHED_NEW_MESSAGES_AVAILABLE);
@@ -477,6 +481,13 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
return true;
}
@Override
public void handleNewMessageAvailable() {
Metrics.counter(MESSAGE_AVAILABLE_COUNTER_NAME,
PRESENCE_MANAGER_TAG, "pubsub")
.increment();
}
@Override
public boolean handleMessagesPersisted() {
if (!client.isOpen()) {
@@ -497,7 +508,19 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
public void handleDisplacement(final boolean connectedElsewhere) {
final Tags tags = Tags.of(
UserAgentTagUtil.getPlatformTag(client.getUserAgent()),
Tag.of("connectedElsewhere", String.valueOf(connectedElsewhere))
Tag.of("connectedElsewhere", String.valueOf(connectedElsewhere)),
Tag.of(PRESENCE_MANAGER_TAG, "legacy")
);
Metrics.counter(DISPLACEMENT_COUNTER_NAME, tags).increment();
}
@Override
public void handleConnectionDisplaced(final boolean connectedElsewhere) {
final Tags tags = Tags.of(
UserAgentTagUtil.getPlatformTag(client.getUserAgent()),
Tag.of("connectedElsewhere", String.valueOf(connectedElsewhere)),
Tag.of(PRESENCE_MANAGER_TAG, "pubsub")
);
Metrics.counter(DISPLACEMENT_COUNTER_NAME, tags).increment();
@@ -6,8 +6,6 @@
package org.whispersystems.textsecuregcm.workers;
import io.dropwizard.core.Application;
import io.dropwizard.core.cli.Cli;
import io.dropwizard.core.cli.EnvironmentCommand;
import io.dropwizard.core.setup.Environment;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
@@ -18,8 +16,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
import org.whispersystems.textsecuregcm.backup.BackupManager;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.util.logging.UncaughtExceptionHandler;
import reactor.core.scheduler.Schedulers;
import java.time.Clock;
@@ -69,13 +65,13 @@ public class BackupMetricsCommand extends AbstractCommandWithDependencies {
Runtime.getRuntime().availableProcessors());
final DistributionSummary numObjectsMediaTier = Metrics.summary(name(getClass(), "numObjects"),
"tier", BackupLevel.MEDIA.name());
"tier", BackupLevel.PAID.name());
final DistributionSummary bytesUsedMediaTier = Metrics.summary(name(getClass(), "bytesUsed"),
"tier", BackupLevel.MEDIA.name());
"tier", BackupLevel.PAID.name());
final DistributionSummary numObjectsMessagesTier = Metrics.summary(name(getClass(), "numObjects"),
"tier", BackupLevel.MESSAGES.name());
"tier", BackupLevel.FREE.name());
final DistributionSummary bytesUsedMessagesTier = Metrics.summary(name(getClass(), "bytesUsed"),
"tier", BackupLevel.MESSAGES.name());
"tier", BackupLevel.FREE.name());
final DistributionSummary timeSinceLastRefresh = Metrics.summary(name(getClass(),
"timeSinceLastRefresh"));
@@ -5,7 +5,6 @@
package org.whispersystems.textsecuregcm.workers;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.dropwizard.core.cli.Command;
import io.dropwizard.core.setup.Bootstrap;
import java.nio.file.Files;
@@ -37,12 +36,7 @@ public class CheckDynamicConfigurationCommand extends Command {
}
private boolean isValid(final Class<?> configurationClass, final String yamlConfig) {
try {
return DynamicConfigurationManager.parseConfiguration(yamlConfig, configurationClass).isPresent();
} catch (JsonProcessingException e) {
System.err.println(e.getMessage());
return false;
}
return DynamicConfigurationManager.parseConfiguration(yamlConfig, configurationClass).isPresent();
}
/**
@@ -35,12 +35,13 @@ import org.whispersystems.textsecuregcm.experiment.PushNotificationExperimentSam
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.MicrometerAwsSdkMetricPublisher;
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.PubSubClientEventManager;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
import org.whispersystems.textsecuregcm.storage.AccountLockManager;
@@ -103,8 +104,9 @@ record CommandDependencies(
ScheduledExecutorService dynamicConfigurationExecutor = environment.lifecycle()
.scheduledExecutorService(name(name, "dynamicConfiguration-%d")).threads(1).build();
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = configuration.getAppConfig().build(
DynamicConfiguration.class, dynamicConfigurationExecutor, awsCredentialsProvider);
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
new DynamicConfigurationManager<>(
configuration.getDynamicConfig().build(awsCredentialsProvider, dynamicConfigurationExecutor), DynamicConfiguration.class);
dynamicConfigurationManager.start();
final ClientResources.Builder redisClientResourcesBuilder = ClientResources.builder();
@@ -140,6 +142,8 @@ record CommandDependencies(
.maxThreads(1).minThreads(1).build();
ExecutorService fcmSenderExecutor = environment.lifecycle().executorService(name(name, "fcmSender-%d"))
.maxThreads(16).minThreads(16).build();
ExecutorService clientEventExecutor = environment.lifecycle()
.virtualExecutorService(name(name, "clientEvent-%d"));
ScheduledExecutorService secureValueRecoveryServiceRetryExecutor = environment.lifecycle()
.scheduledExecutorService(name(name, "secureValueRecoveryServiceRetry-%d")).threads(1).build();
@@ -213,6 +217,7 @@ record CommandDependencies(
storageServiceExecutor, storageServiceRetryExecutor, configuration.getSecureStorageServiceConfiguration());
ClientPresenceManager clientPresenceManager = new ClientPresenceManager(clientPresenceCluster,
recurringJobExecutor, keyspaceNotificationDispatchExecutor);
PubSubClientEventManager pubSubClientEventManager = new PubSubClientEventManager(messagesCluster, clientEventExecutor);
MessagesCache messagesCache = new MessagesCache(messagesCluster, keyspaceNotificationDispatchExecutor,
messageDeliveryScheduler, messageDeletionExecutor, Clock.systemUTC(), dynamicConfigurationManager);
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster);
@@ -229,7 +234,7 @@ record CommandDependencies(
new ClientPublicKeysManager(clientPublicKeys, accountLockManager, accountLockExecutor);
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
pubsubClient, accountLockManager, keys, messagesManager, profilesManager,
secureStorageClient, secureValueRecovery2Client, clientPresenceManager,
secureStorageClient, secureValueRecovery2Client, clientPresenceManager, pubSubClientEventManager,
registrationRecoveryPasswordsManager, clientPublicKeysManager, accountLockExecutor, clientPresenceExecutor,
clock, configuration.getLinkDeviceSecretConfiguration().secret().value(), dynamicConfigurationManager);
RateLimiters rateLimiters = RateLimiters.createAndValidate(configuration.getLimitsConfiguration(),
@@ -268,6 +273,7 @@ record CommandDependencies(
environment.lifecycle().manage(apnSender);
environment.lifecycle().manage(messagesCache);
environment.lifecycle().manage(clientPresenceManager);
environment.lifecycle().manage(pubSubClientEventManager);
environment.lifecycle().manage(new ManagedAwsCrt());
return new CommandDependencies(
@@ -42,10 +42,10 @@ public class NotifyIdleDevicesCommand extends AbstractSinglePassCrawlAccountsCom
static final Duration MAX_SHORT_IDLE_DURATION = Duration.ofDays(30);
@VisibleForTesting
static final Duration MIN_LONG_IDLE_DURATION = Duration.ofDays(30);
static final Duration MIN_LONG_IDLE_DURATION = Duration.ofDays(60);
@VisibleForTesting
static final Duration MAX_LONG_IDLE_DURATION = Duration.ofDays(45);
static final Duration MAX_LONG_IDLE_DURATION = Duration.ofDays(75);
private static final Counter DEVICE_INSPECTED_COUNTER =
Metrics.counter(MetricsUtil.name(NotifyIdleDevicesCommand.class, "deviceInspected"));
@@ -0,0 +1,38 @@
/**
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
syntax = "proto3";
package org.signal.chat.presence;
option java_package = "org.whispersystems.textsecuregcm.push";
option java_multiple_files = true;
message ClientEvent {
oneof event {
NewMessageAvailableEvent new_message_available = 1;
ClientConnectedEvent client_connected = 2;
DisconnectRequested disconnect_requested = 3;
}
}
/**
* Indicates that a new message is available for the client to retrieve.
*/
message NewMessageAvailableEvent {
}
/**
* Indicates that a client has connected to the presence system.
*/
message ClientConnectedEvent {
bytes server_id = 1;
}
/**
* Indicates that the server has requested that the client disconnect due to
* (for example) account lifecycle events.
*/
message DisconnectRequested {
}
@@ -11,22 +11,100 @@ option java_package = "org.signal.keytransparency.client";
package kt_query;
/**
* An external-facing, read-only key transparency service used by Signal's chat server
* to look up and monitor search keys.
*/
* An external-facing, read-only key transparency service used by Signal's chat server
* to look up and monitor identifiers.
* There are three types of identifier mappings stored by the key transparency log:
* - An ACI which maps to an ACI identity key
* - An E164-formatted phone number which maps to an ACI
* - A username hash which also maps to an ACI
* Separately, the log also stores and periodically updates a fixed value known as the `distinguished` key.
* Clients use the verified tree head from looking up this key for future calls to the Search and Monitor endpoints.
*/
service KeyTransparencyQueryService {
/**
* 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.
* An endpoint used by clients to retrieve the most recent distinguished tree
* head, which should be used to derive consistency parameters for
* subsequent Search and Monitor requests. It should be the first key
* transparency RPC a client calls.
*/
rpc Distinguished(DistinguishedRequest) returns (DistinguishedResponse) {}
/**
* An endpoint used by clients to search for one or more identifiers in the transparency log.
* The server returns proof that the identifier(s) exist in the log.
*/
rpc Search(SearchRequest) returns (SearchResponse) {}
/**
* 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.
* An endpoint that allows users to monitor a set of identifiers by returning proof that the log continues to be
* constructed correctly in later entries for those identifiers.
*/
rpc Monitor(MonitorRequest) returns (MonitorResponse) {}
}
message SearchRequest {
/**
* The ACI to look up in the log.
*/
bytes aci = 1;
/**
* The ACI identity key that the client thinks the ACI maps to in the log.
*/
bytes aci_identity_key = 2;
/**
* The username hash to look up in the log.
*/
optional bytes username_hash = 3;
/**
* The E164 to look up in the log along with associated data.
*/
optional E164SearchRequest e164_search_request = 4;
/**
* The tree head size(s) to prove consistency against.
*/
ConsistencyParameters consistency = 5;
}
/**
* E164SearchRequest contains the data that the user must provide when looking up an E164.
*/
message E164SearchRequest {
/**
* The E164 that the client wishes to look up in the transparency log.
*/
string e164 = 1;
/**
* The unidentified access key of the account associated with the provided E164.
*/
bytes unidentified_access_key = 2;
}
/**
* SearchResponse contains search proofs for each of the requested identifiers.
*/
message SearchResponse {
/**
* A signed representation of the log tree's current state along with some
* additional information necessary for validation such as a consistency proof and an auditor-signed tree head.
*/
FullTreeHead tree_head = 1;
/**
* The ACI search response is always provided.
*/
CondensedTreeSearchResponse aci = 2;
/**
* This response is only provided if all of the conditions are met:
* - the E164 exists in the log
* - its mapped ACI matches the one provided in the request
* - the account associated with the ACI is discoverable
* - the unidentified access key provided in E164SearchRequest matches the one on the account
*/
optional CondensedTreeSearchResponse e164 = 3;
/**
* This response is only provided if the username hash exists in the log and
* its mapped ACI matches the one provided in the request.
*/
optional CondensedTreeSearchResponse username_hash = 4;
}
/**
* The tree head size(s) to prove consistency against. A client's very first
* key transparency request should be looking up the "distinguished" key;
@@ -36,7 +114,7 @@ service KeyTransparencyQueryService {
message ConsistencyParameters {
/**
* The non-distinguished tree head size to prove consistency against.
* This field may be omitted if the client is looking up a search key
* This field may be omitted if the client is looking up an identifier
* for the first time.
*/
optional uint64 last = 1;
@@ -48,51 +126,55 @@ message ConsistencyParameters {
optional uint64 distinguished = 2;
}
// TODO: add a `value` field so that the KT server can verify that the given search key is mapped
// to the provided value.
message SearchRequest {
/**
* DistinguishedRequest looks up the most recent distinguished key in the
* transparency log.
*/
message DistinguishedRequest {
/**
* The key to look up in the log tree.
* A key can be an ACI, an E164 phone number, or a username hash and
* is prefixed with a unique identifier to indicate its type.
* The tree size of the client's last verified distinguished request. With the
* exception of a client's very first request, this field should always be
* set.
*/
bytes search_key = 1;
/**
* TODO: Remove this protobuf field in the KT server
* The version of the key to look up. If not specified, the key transparency server
* defaults to returning the most recent version of the key.
*/
optional uint32 version = 2;
/**
* The tree head size(s) to prove consistency against.
*/
ConsistencyParameters consistency = 3;
optional uint64 last = 1;
}
message SearchResponse {
/**
* DistinguishedResponse contains the tree head and search proof for the most
* recent `distinguished` key in the log.
*/
message DistinguishedResponse {
/**
* A signed representation of the log tree's current state along with some
* additional information necessary for validation such as a consistency proof and an auditor-signed tree head.
*/
FullTreeHead tree_head = 1;
/**
* A proof that is combined with the original requested search key and the VRF public key
* This search response is always provided.
*/
CondensedTreeSearchResponse distinguished = 2;
}
message CondensedTreeSearchResponse {
/**
* A proof that is combined with the original requested identifier and the VRF public key
* and outputs whether the proof is valid, and if so, the commitment index.
*/
bytes vrf_proof = 2;
bytes vrf_proof = 1;
/**
* A proof that the binary search for the given search key was done correctly.
* A proof that the binary search for the given identifier was done correctly.
*/
SearchProof search = 3;
SearchProof search = 2;
/**
* A 32 byte value computed based on the log position and a random 32 byte key that is only known by
* the key transparency service. It is provided so that clients can recompute and verify the commitment.
* A 32-byte value computed based on the log position of the identifier
* and a random 32 byte key that is only known by the key transparency service.
* It is provided so that clients can recompute and verify the commitment.
*/
bytes opening = 4;
bytes opening = 3;
/**
* The new or updated value of the search key.
* The new or updated value that the identifier maps to.
*/
UpdateValue value = 5;
UpdateValue value = 4;
}
message FullTreeHead {
@@ -100,14 +182,14 @@ message FullTreeHead {
* A representation of the log tree's current state signed by the key transparency service.
*/
TreeHead tree_head = 1;
/**
* A consistency proof between the current tree size and the requested distinguished tree size.
*/
repeated bytes distinguished = 2;
/**
* A consistency proof between the current tree size and the requested tree size.
*/
repeated bytes consistency = 3;
repeated bytes last = 2;
/**
* A consistency proof between the current tree size and the requested distinguished tree size.
*/
repeated bytes distinguished = 3;
/**
* A tree head signed by a third-party auditor.
*/
@@ -165,17 +247,17 @@ message ProofStep {
message SearchProof {
/**
* The position in the log tree of the first occurrence of the requested search key.
* The position in the log tree of the first occurrence of the requested identifier.
*/
uint64 pos = 1;
/**
* The steps of a binary search through the entries of the log tree for the given search key version.
* The steps of a binary search through the entries of the log tree for the given identifier version.
* Each ProofStep corresponds to a log entry and provides the information necessary to recompute a log tree
* leaf hash.
*/
repeated ProofStep steps = 2;
/**
* A batch inclusion proof for all log tree leaves involved in the binary search for the given search key.
* A batch inclusion proof for all log tree leaves involved in the binary search for the given identifier.
*/
repeated bytes inclusion = 3;
}
@@ -187,19 +269,19 @@ message UpdateValue {
*/
// optional bytes signature = 1;
/**
* The new value for a search key.
* The new value for a identifier.
*/
bytes value = 2;
}
message PrefixSearchResult {
/**
* A proof from a prefix tree that indicates a search was done correctly for a given search key.
* A proof from a prefix tree that indicates a search was done correctly for a given identifier.
* The elements of this array are the copath of the prefix tree leaf node in bottom-to-top order.
*/
repeated bytes proof = 1;
/**
* The version of the requested search key in the prefix tree.
* The version of the requested identifier in the prefix tree.
*/
uint32 counter = 2;
}
@@ -210,7 +292,7 @@ message MonitorKey {
*/
bytes search_key = 1;
/**
* A list of log tree positions maintained by a client for the search key being monitored.
* A list of log tree positions maintained by a client for the identifier being monitored.
* Each position is in the direct path to a key version and corresponds to a tree head
* that has been verified to contain that version or greater.
* The key transparency server uses this list to compute which log entries to return
@@ -218,7 +300,7 @@ message MonitorKey {
*/
repeated uint64 entries = 2;
/**
* The commitment index for the search key. This is derived from vrf_proof in
* The commitment index for the identifier. This is derived from vrf_proof in
* the SearchResponse.
*/
bytes commitment_index = 3;
@@ -231,8 +313,8 @@ message MonitorRequest {
*/
repeated MonitorKey owned_keys = 1;
/**
* The list of search keys that the client would like to monitor.
* All search keys *must* belong to the same user.
* The list of identifiers that the client would like to monitor.
* All identifiers *must* belong to the same user.
*/
repeated MonitorKey contact_keys = 2;
/**
@@ -264,8 +346,8 @@ message MonitorResponse {
*/
repeated MonitorProof owned_proofs = 2;
/**
* A list of proofs, one for each key in MonitorRequest.contact_keys, each proving that the given search key
* continues to be constructed correctly in later entries of hte log tree.
* A list of proofs, one for each identifier in MonitorRequest.contact_keys, each proving that the given identifier
* continues to be constructed correctly in later entries of the log tree.
*/
repeated MonitorProof contact_proofs = 3;
/**
@@ -92,3 +92,12 @@ message KemSignedPreKey {
*/
bytes signature = 3;
}
enum DeviceCapability {
DEVICE_CAPABILITY_UNSPECIFIED = 0;
DEVICE_CAPABILITY_STORAGE = 1;
DEVICE_CAPABILITY_TRANSFER = 2;
DEVICE_CAPABILITY_DELETE_SYNC = 3;
DEVICE_CAPABILITY_VERSIONED_EXPIRATION_TIMER = 4;
DEVICE_CAPABILITY_STORAGE_SERVICE_RECORD_KEY_ROTATION = 5;
}
@@ -9,6 +9,8 @@ option java_multiple_files = true;
package org.signal.chat.device;
import "org/signal/chat/common.proto";
/**
* Provides methods for working with devices attached to a Signal account.
*/
@@ -27,6 +29,14 @@ service Devices {
*/
rpc RemoveDevice(RemoveDeviceRequest) returns (RemoveDeviceResponse) {}
/**
* Sets the encrypted human-readable name for a specific devices. Primary
* devices may change the name of any device associated with their account,
* but linked devices may only change their own name. This call will fail with
* a status of `NOT_FOUND` if no device was found with the given identifier.
* It will also fail with a status of `PERMISSION_DENIED` if a linked device
* tries to change the name of any device other than itself.
*/
rpc SetDeviceName(SetDeviceNameRequest) returns (SetDeviceNameResponse) {}
/**
@@ -95,6 +105,11 @@ message SetDeviceNameRequest {
* device.
*/
bytes name = 1;
/**
* The identifier for the device for which to set a name.
*/
uint32 id = 2;
}
message SetDeviceNameResponse {}
@@ -138,10 +153,7 @@ message ClearPushTokenRequest {}
message ClearPushTokenResponse {}
message SetCapabilitiesRequest {
bool storage = 1;
bool transfer = 2;
bool deleteSync = 3;
bool versionedExpirationTimer = 4;
repeated common.DeviceCapability capabilities = 1;
}
message SetCapabilitiesResponse {}
@@ -154,7 +154,7 @@ message GetPreKeysRequest {
* retrieve pre-keys. If not set, pre-keys are returned for all devices
* associated with the targeted account.
*/
uint32 device_id = 2;
optional uint32 device_id = 2;
}
message GetPreKeysAnonymousRequest {
@@ -241,7 +241,7 @@ message GetUnversionedProfileResponse {
/**
* A list of capabilities enabled on the account.
*/
UserCapabilities capabilities = 4;
repeated common.DeviceCapability capabilities = 4;
/**
* A list of badges associated with the account.
*/
@@ -317,17 +317,6 @@ message ProfileAvatarUploadAttributes {
bytes signature = 7;
}
message UserCapabilities {
/**
* Whether all devices linked to the account support delete syncing
*/
bool delete_sync = 1;
/**
* Whether all devices linked to the account support a versioned expiration timer
*/
bool versioned_expiration_timer = 2;
}
message Badge {
/**
* An ID that uniquely identifies the badge.
@@ -1,8 +1,6 @@
org.whispersystems.textsecuregcm.configuration.AwsCredentialsProviderFactory
org.whispersystems.textsecuregcm.configuration.DatadogConfiguration
org.whispersystems.textsecuregcm.configuration.DynamicConfigurationManagerFactory
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
@@ -1,13 +0,0 @@
#
# Copyright 2021 Signal Messenger, LLC
# SPDX-License-Identifier: AGPL-3.0-only
#
# These are deprecated, will be unused by clients in a future update, and can be removed in ~April 2023.
# First subscription level
R_LOW = Sustainer 1
# Second subscription level
R_MED = Sustainer 2
# Third subscription level
R_HIGH = Sustainer 3
@@ -5,7 +5,6 @@
package org.whispersystems.textsecuregcm.auth;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
@@ -61,6 +60,7 @@ import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
@@ -97,6 +97,7 @@ class LinkedDeviceRefreshRequirementProviderTest {
private AccountsManager accountsManager;
private ClientPresenceManager clientPresenceManager;
private PubSubClientEventManager pubSubClientEventManager;
private LinkedDeviceRefreshRequirementProvider provider;
@@ -104,11 +105,12 @@ class LinkedDeviceRefreshRequirementProviderTest {
void setup() {
accountsManager = mock(AccountsManager.class);
clientPresenceManager = mock(ClientPresenceManager.class);
pubSubClientEventManager = mock(PubSubClientEventManager.class);
provider = new LinkedDeviceRefreshRequirementProvider(accountsManager);
final WebsocketRefreshRequestEventListener listener =
new WebsocketRefreshRequestEventListener(clientPresenceManager, provider);
new WebsocketRefreshRequestEventListener(clientPresenceManager, pubSubClientEventManager, provider);
when(applicationEventListener.onRequest(any())).thenReturn(listener);
@@ -146,6 +148,10 @@ class LinkedDeviceRefreshRequirementProviderTest {
verify(clientPresenceManager).disconnectPresence(account.getUuid(), (byte) 1);
verify(clientPresenceManager).disconnectPresence(account.getUuid(), (byte) 2);
verify(clientPresenceManager).disconnectPresence(account.getUuid(), (byte) 3);
verify(pubSubClientEventManager).requestDisconnection(account.getUuid(), List.of((byte) 1));
verify(pubSubClientEventManager).requestDisconnection(account.getUuid(), List.of((byte) 2));
verify(pubSubClientEventManager).requestDisconnection(account.getUuid(), List.of((byte) 3));
}
@ParameterizedTest
@@ -173,8 +179,10 @@ class LinkedDeviceRefreshRequirementProviderTest {
assertEquals(200, response.getStatus());
initialDeviceIds.forEach(deviceId ->
verify(clientPresenceManager).disconnectPresence(account.getUuid(), deviceId));
initialDeviceIds.forEach(deviceId -> {
verify(clientPresenceManager).disconnectPresence(account.getUuid(), deviceId);
verify(pubSubClientEventManager).requestDisconnection(account.getUuid(), List.of(deviceId));
});
verifyNoMoreInteractions(clientPresenceManager);
}
@@ -28,6 +28,7 @@ import java.io.IOException;
import java.net.URI;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import javax.servlet.DispatcherType;
@@ -47,6 +48,7 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
@@ -74,6 +76,7 @@ class PhoneNumberChangeRefreshRequirementProviderTest {
private static final AccountAuthenticator AUTHENTICATOR = mock(AccountAuthenticator.class);
private static final AccountsManager ACCOUNTS_MANAGER = mock(AccountsManager.class);
private static final ClientPresenceManager CLIENT_PRESENCE = mock(ClientPresenceManager.class);
private static final PubSubClientEventManager PUBSUB_CLIENT_PRESENCE = mock(PubSubClientEventManager.class);
private WebSocketClient client;
private final Account account1 = new Account();
@@ -122,9 +125,9 @@ class PhoneNumberChangeRefreshRequirementProviderTest {
.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");
webSocketEnvironment.jersey().register(new RemoteAddressFilter());
webSocketEnvironment.jersey()
.register(new WebsocketRefreshApplicationEventListener(ACCOUNTS_MANAGER, CLIENT_PRESENCE));
.register(new WebsocketRefreshApplicationEventListener(ACCOUNTS_MANAGER, CLIENT_PRESENCE, PUBSUB_CLIENT_PRESENCE));
environment.jersey()
.register(new WebsocketRefreshApplicationEventListener(ACCOUNTS_MANAGER, CLIENT_PRESENCE));
.register(new WebsocketRefreshApplicationEventListener(ACCOUNTS_MANAGER, CLIENT_PRESENCE, PUBSUB_CLIENT_PRESENCE));
webSocketEnvironment.setConnectListener(webSocketSessionContext -> {
});
@@ -215,6 +218,10 @@ class PhoneNumberChangeRefreshRequirementProviderTest {
verify(CLIENT_PRESENCE, timeout(5000))
.disconnectPresence(eq(account1.getUuid()), eq(authenticatedDevice.getId()));
verifyNoMoreInteractions(CLIENT_PRESENCE);
verify(PUBSUB_CLIENT_PRESENCE, timeout(5000))
.requestDisconnection(account1.getUuid(), List.of(authenticatedDevice.getId()));
verifyNoMoreInteractions(PUBSUB_CLIENT_PRESENCE);
}
@Test
@@ -231,6 +238,10 @@ class PhoneNumberChangeRefreshRequirementProviderTest {
verify(CLIENT_PRESENCE, timeout(5000))
.disconnectPresence(eq(account1.getUuid()), eq(authenticatedDevice.getId()));
verifyNoMoreInteractions(CLIENT_PRESENCE);
verify(PUBSUB_CLIENT_PRESENCE, timeout(5000))
.requestDisconnection(account1.getUuid(), List.of(authenticatedDevice.getId()));
verifyNoMoreInteractions(PUBSUB_CLIENT_PRESENCE);
}
@ParameterizedTest
@@ -35,6 +35,7 @@ import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
@@ -47,6 +48,7 @@ class RegistrationLockVerificationManagerTest {
private final AccountsManager accountsManager = mock(AccountsManager.class);
private final ClientPresenceManager clientPresenceManager = mock(ClientPresenceManager.class);
private final PubSubClientEventManager pubSubClientEventManager = mock(PubSubClientEventManager.class);
private final ExternalServiceCredentialsGenerator svr2CredentialsGenerator = mock(
ExternalServiceCredentialsGenerator.class);
private final ExternalServiceCredentialsGenerator svr3CredentialsGenerator = mock(
@@ -56,7 +58,7 @@ class RegistrationLockVerificationManagerTest {
private static PushNotificationManager pushNotificationManager = mock(PushNotificationManager.class);
private final RateLimiters rateLimiters = mock(RateLimiters.class);
private final RegistrationLockVerificationManager registrationLockVerificationManager = new RegistrationLockVerificationManager(
accountsManager, clientPresenceManager, svr2CredentialsGenerator, svr3CredentialsGenerator,
accountsManager, clientPresenceManager, pubSubClientEventManager, svr2CredentialsGenerator, svr3CredentialsGenerator,
registrationRecoveryPasswordsManager, pushNotificationManager, rateLimiters);
private final RateLimiter pinLimiter = mock(RateLimiter.class);
@@ -108,6 +110,7 @@ class RegistrationLockVerificationManagerTest {
verify(registrationRecoveryPasswordsManager, never()).removeForNumber(account.getNumber());
}
verify(clientPresenceManager).disconnectAllPresences(account.getUuid(), List.of(Device.PRIMARY_ID));
verify(pubSubClientEventManager).requestDisconnection(account.getUuid(), List.of(Device.PRIMARY_ID));
try {
verify(pushNotificationManager).sendAttemptLoginNotification(any(), eq("failedRegistrationLock"));
} catch (NotPushRegisteredException npre) {}
@@ -131,6 +134,7 @@ class RegistrationLockVerificationManagerTest {
} catch (NotPushRegisteredException npre) {}
verify(registrationRecoveryPasswordsManager, never()).removeForNumber(account.getNumber());
verify(clientPresenceManager, never()).disconnectAllPresences(account.getUuid(), List.of(Device.PRIMARY_ID));
verify(pubSubClientEventManager, never()).requestDisconnection(any(), any());
});
}
};
@@ -169,6 +173,7 @@ class RegistrationLockVerificationManagerTest {
verify(account, never()).lockAuthTokenHash();
verify(registrationRecoveryPasswordsManager, never()).removeForNumber(account.getNumber());
verify(clientPresenceManager, never()).disconnectAllPresences(account.getUuid(), List.of(Device.PRIMARY_ID));
verify(pubSubClientEventManager, never()).requestDisconnection(any(), any());
}
static Stream<Arguments> testSuccess() {
Loaded 100 of 157 files, more files were not shown because too many files have changed in this diff. Show more