mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 10:46:47 +00:00
Compare commits
29
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6955e1ee20 | ||
|
|
7bb4a4bc90 | ||
|
|
6fa01a5d48 | ||
|
|
5a65a46fc1 | ||
|
|
c255355e5c | ||
|
|
8d3781db90 | ||
|
|
f6a87b2ec0 | ||
|
|
e8a1854c5e | ||
|
|
f8d27d8fab | ||
|
|
94dd2712b1 | ||
|
|
a4804f6501 | ||
|
|
5cb3a053fb | ||
|
|
4923b6da68 | ||
|
|
b7e64e09a3 | ||
|
|
76e65a47a2 | ||
|
|
ef644ce319 | ||
|
|
08c4179a7a | ||
|
|
5c3be9c3d6 | ||
|
|
8fc0b49994 | ||
|
|
db4c71368c | ||
|
|
30774bbc40 | ||
|
|
3b48c82c72 | ||
|
|
038c68c594 | ||
|
|
cf222e1105 | ||
|
|
541c87e262 | ||
|
|
5f5c345f94 | ||
|
|
8aa408a3c1 | ||
|
|
4f0337021c | ||
|
|
00062fdd5c |
No files matched your search
@@ -298,6 +298,11 @@ dogstatsd:
|
||||
environment: dev
|
||||
host: 127.0.0.1
|
||||
|
||||
openTelemetry:
|
||||
enabled: true
|
||||
environment: dev
|
||||
url: http://127.0.0.1:4318/
|
||||
|
||||
unidentifiedDelivery:
|
||||
certificate: CgIIAQ==
|
||||
privateKey: secret://unidentifiedDelivery.privateKey
|
||||
|
||||
@@ -324,6 +324,10 @@
|
||||
<groupId>io.micrometer</groupId>
|
||||
<artifactId>micrometer-registry-statsd</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.micrometer</groupId>
|
||||
<artifactId>micrometer-registry-otlp</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.coursera</groupId>
|
||||
<artifactId>dropwizard-metrics-datadog</artifactId>
|
||||
|
||||
+10
@@ -45,6 +45,7 @@ import org.whispersystems.textsecuregcm.configuration.MessageByteLimitCardinalit
|
||||
import org.whispersystems.textsecuregcm.configuration.MessageCacheConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.NoiseTunnelConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.OpenTelemetryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.PagedSingleUseKEMPreKeyStoreConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.PaymentsServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.RegistrationServiceClientFactory;
|
||||
@@ -138,6 +139,11 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private DatadogConfiguration dogstatsd = new DogstatsdConfiguration();
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private OpenTelemetryConfiguration openTelemetry;
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
@@ -442,6 +448,10 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return dogstatsd;
|
||||
}
|
||||
|
||||
public OpenTelemetryConfiguration getOpenTelemetryConfiguration() {
|
||||
return openTelemetry;
|
||||
}
|
||||
|
||||
public UnidentifiedDeliveryConfiguration getDeliveryCertificate() {
|
||||
return unidentifiedDelivery;
|
||||
}
|
||||
|
||||
@@ -93,6 +93,7 @@ import org.whispersystems.textsecuregcm.backup.BackupManager;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupsDb;
|
||||
import org.whispersystems.textsecuregcm.backup.Cdn3BackupCredentialGenerator;
|
||||
import org.whispersystems.textsecuregcm.backup.Cdn3RemoteStorageManager;
|
||||
import org.whispersystems.textsecuregcm.backup.SecureValueRecoveryBCredentialsGeneratorFactory;
|
||||
import org.whispersystems.textsecuregcm.badges.ConfiguredProfileBadgeConverter;
|
||||
import org.whispersystems.textsecuregcm.captcha.CaptchaChecker;
|
||||
import org.whispersystems.textsecuregcm.captcha.CaptchaClient;
|
||||
@@ -126,7 +127,6 @@ import org.whispersystems.textsecuregcm.controllers.RemoteConfigController;
|
||||
import org.whispersystems.textsecuregcm.controllers.RemoteConfigControllerV1;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery2Controller;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureValueRecoveryBController;
|
||||
import org.whispersystems.textsecuregcm.controllers.StickerController;
|
||||
import org.whispersystems.textsecuregcm.controllers.SubscriptionController;
|
||||
import org.whispersystems.textsecuregcm.controllers.VerificationController;
|
||||
@@ -191,7 +191,6 @@ import org.whispersystems.textsecuregcm.metrics.ReportedMessageMetricsListener;
|
||||
import org.whispersystems.textsecuregcm.metrics.TlsCertificateExpirationUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.TrafficSource;
|
||||
import org.whispersystems.textsecuregcm.providers.MultiRecipientMessageProvider;
|
||||
import org.whispersystems.textsecuregcm.providers.RedisClusterHealthCheck;
|
||||
import org.whispersystems.textsecuregcm.push.APNSender;
|
||||
import org.whispersystems.textsecuregcm.push.FcmSender;
|
||||
import org.whispersystems.textsecuregcm.push.MessageSender;
|
||||
@@ -199,7 +198,7 @@ import org.whispersystems.textsecuregcm.push.ProvisioningManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.redis.ConnectionEventLogger;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
@@ -398,7 +397,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
environment.lifecycle().manage(new ManagedAwsCrt());
|
||||
|
||||
final ExecutorService awsSdkMetricsExecutor = virtualExecutorService(environment, "awsSdkMetrics");
|
||||
final ExecutorService awsSdkMetricsExecutor = environment.lifecycle()
|
||||
.virtualExecutorService(name(getClass(), "awsSdkMetrics-%d"));
|
||||
|
||||
final DynamoDbAsyncClient dynamoDbAsyncClient = config.getDynamoDbClientConfiguration()
|
||||
.buildAsyncClient(awsCredentialsProvider, new MicrometerAwsSdkMetricPublisher(awsSdkMetricsExecutor, "dynamoDbAsync"));
|
||||
@@ -503,7 +503,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
messageDeliveryQueue);
|
||||
|
||||
ScheduledExecutorService recurringJobExecutor = ScheduledExecutorServiceBuilder.of(environment, "recurringJob").threads(6).build();
|
||||
ScheduledExecutorService websocketScheduledExecutor = ScheduledExecutorServiceBuilder.of(environment, "websocket").threads(8).build();
|
||||
ExecutorService apnSenderExecutor = ExecutorServiceBuilder.of(environment, "apnSender")
|
||||
.maxThreads(1).minThreads(1).build();
|
||||
ExecutorService fcmSenderExecutor = ExecutorServiceBuilder.of(environment, "fcmSender")
|
||||
@@ -565,10 +564,14 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.maxThreads(2)
|
||||
.minThreads(2)
|
||||
.build();
|
||||
ExecutorService googlePlayBillingExecutor = virtualExecutorService(environment, "googlePlayBilling");
|
||||
ExecutorService appleAppStoreExecutor = virtualExecutorService(environment, "appleAppStore");
|
||||
ExecutorService clientEventExecutor = virtualExecutorService(environment, "clientEvent");
|
||||
ExecutorService disconnectionRequestListenerExecutor = virtualExecutorService(environment, "disconnectionRequest");
|
||||
ExecutorService googlePlayBillingExecutor = environment.lifecycle()
|
||||
.virtualExecutorService(name(getClass(), "googlePlayBilling-%d"));
|
||||
ExecutorService appleAppStoreExecutor = environment.lifecycle()
|
||||
.virtualExecutorService(name(getClass(), "appleAppStore-%d"));
|
||||
ExecutorService clientEventExecutor = environment.lifecycle()
|
||||
.virtualExecutorService(name(getClass(), "clientEvent-%d"));
|
||||
ExecutorService disconnectionRequestListenerExecutor = environment.lifecycle()
|
||||
.virtualExecutorService(name(getClass(), "disconnectionRequest-%d"));
|
||||
|
||||
ScheduledExecutorService appleAppStoreRetryExecutor = ScheduledExecutorServiceBuilder.of(environment, "appleAppStoreRetry").threads(1).build();
|
||||
ScheduledExecutorService subscriptionProcessorRetryExecutor = ScheduledExecutorServiceBuilder.of(environment, "subscriptionProcessorRetry").threads(1).build();
|
||||
@@ -591,9 +594,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
ExternalServiceCredentialsGenerator paymentsCredentialsGenerator = PaymentsController.credentialsGenerator(
|
||||
config.getPaymentsServiceConfiguration());
|
||||
ExternalServiceCredentialsGenerator svr2CredentialsGenerator = SecureValueRecovery2Controller.credentialsGenerator(
|
||||
config.getSvr2Configuration());
|
||||
ExternalServiceCredentialsGenerator svrbCredentialsGenerator = SecureValueRecoveryBController.credentialsGenerator(
|
||||
config.getSvrbConfiguration());
|
||||
config.getSvr2Configuration());
|
||||
ExternalServiceCredentialsGenerator svrbCredentialsGenerator =
|
||||
SecureValueRecoveryBCredentialsGeneratorFactory.svrbCredentialsGenerator(config.getSvrbConfiguration());
|
||||
|
||||
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager =
|
||||
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords);
|
||||
@@ -621,7 +624,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
() -> dynamicConfigurationManager.getConfiguration().getSvrbStatusCodesToIgnoreForAccountDeletion());
|
||||
SecureStorageClient secureStorageClient = new SecureStorageClient(storageCredentialsGenerator,
|
||||
storageServiceExecutor, storageServiceRetryExecutor, config.getSecureStorageServiceConfiguration());
|
||||
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient, disconnectionRequestListenerExecutor);
|
||||
final GrpcClientConnectionManager grpcClientConnectionManager = new GrpcClientConnectionManager();
|
||||
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient, grpcClientConnectionManager, disconnectionRequestListenerExecutor);
|
||||
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster, asyncCdnS3Client, config.getCdnConfiguration().bucket());
|
||||
MessagesCache messagesCache = new MessagesCache(messagesCluster, messageDeliveryScheduler,
|
||||
messageDeletionAsyncExecutor, clock);
|
||||
@@ -639,7 +643,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new ClientPublicKeysManager(clientPublicKeys, accountLockManager, accountLockExecutor);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
pubsubClient, accountLockManager, keysManager, messagesManager, profilesManager,
|
||||
secureStorageClient, secureValueRecovery2Client, secureValueRecoveryBClient, disconnectionRequestManager,
|
||||
secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
|
||||
registrationRecoveryPasswordsManager, clientPublicKeysManager, accountLockExecutor, messagePollExecutor,
|
||||
clock, config.getLinkDeviceSecretConfiguration().secret().value(), dynamicConfigurationManager);
|
||||
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs);
|
||||
@@ -649,8 +653,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
apnSender, fcmSender, accountsManager, 0, 0);
|
||||
PushNotificationManager pushNotificationManager =
|
||||
new PushNotificationManager(accountsManager, apnSender, fcmSender, pushNotificationScheduler);
|
||||
WebSocketConnectionEventManager webSocketConnectionEventManager =
|
||||
new WebSocketConnectionEventManager(accountsManager, pushNotificationManager, messagesCluster, clientEventExecutor, asyncOperationQueueingExecutor);
|
||||
RedisMessageAvailabilityManager redisMessageAvailabilityManager =
|
||||
new RedisMessageAvailabilityManager(messagesCluster, clientEventExecutor, asyncOperationQueueingExecutor);
|
||||
RateLimiters rateLimiters = RateLimiters.create(dynamicConfigurationManager, rateLimitersCluster);
|
||||
ProvisioningManager provisioningManager = new ProvisioningManager(pubsubClient);
|
||||
IssuedReceiptsManager issuedReceiptsManager = new IssuedReceiptsManager(
|
||||
@@ -670,8 +674,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
MessageDeliveryLoopMonitor messageDeliveryLoopMonitor =
|
||||
config.logMessageDeliveryLoops() ? new RedisMessageDeliveryLoopMonitor(rateLimitersCluster) : new NoopMessageDeliveryLoopMonitor();
|
||||
|
||||
disconnectionRequestManager.addListener(webSocketConnectionEventManager);
|
||||
|
||||
final RegistrationLockVerificationManager registrationLockVerificationManager = new RegistrationLockVerificationManager(
|
||||
accountsManager, disconnectionRequestManager, svr2CredentialsGenerator, registrationRecoveryPasswordsManager,
|
||||
pushNotificationManager, rateLimiters);
|
||||
@@ -748,7 +750,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
environment.lifecycle().manage(pushNotificationScheduler);
|
||||
environment.lifecycle().manage(provisioningManager);
|
||||
environment.lifecycle().manage(disconnectionRequestManager);
|
||||
environment.lifecycle().manage(webSocketConnectionEventManager);
|
||||
environment.lifecycle().manage(redisMessageAvailabilityManager);
|
||||
environment.lifecycle().manage(currencyManager);
|
||||
environment.lifecycle().manage(registrationServiceClient);
|
||||
environment.lifecycle().manage(keyTransparencyServiceClient);
|
||||
@@ -795,6 +797,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
tusAttachmentGenerator,
|
||||
cdn3BackupCredentialGenerator,
|
||||
cdn3RemoteStorageManager,
|
||||
svrbCredentialsGenerator,
|
||||
secureValueRecoveryBClient,
|
||||
clock);
|
||||
|
||||
final AppleDeviceChecks appleDeviceChecks = new AppleDeviceChecks(
|
||||
@@ -811,10 +815,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getAppleDeviceCheck().teamId(),
|
||||
config.getAppleDeviceCheck().bundleId());
|
||||
|
||||
final GrpcClientConnectionManager grpcClientConnectionManager = new GrpcClientConnectionManager();
|
||||
|
||||
disconnectionRequestManager.addListener(grpcClientConnectionManager);
|
||||
|
||||
final ManagedDefaultEventLoopGroup localEventLoopGroup = new ManagedDefaultEventLoopGroup();
|
||||
|
||||
final RemoteDeprecationFilter remoteDeprecationFilter = new RemoteDeprecationFilter(dynamicConfigurationManager);
|
||||
@@ -996,13 +996,13 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.idlePrimaryDeviceReminderConfiguration().minIdleDuration(), Clock.systemUTC()));
|
||||
webSocketEnvironment.setConnectListener(
|
||||
new AuthenticatedConnectListener(accountsManager, receiptSender, messagesManager, messageMetrics, pushNotificationManager,
|
||||
pushNotificationScheduler, webSocketConnectionEventManager, websocketScheduledExecutor,
|
||||
pushNotificationScheduler, redisMessageAvailabilityManager, disconnectionRequestManager,
|
||||
messageDeliveryScheduler, clientReleaseManager, messageDeliveryLoopMonitor, experimentEnrollmentManager));
|
||||
webSocketEnvironment.jersey().register(new RateLimitByIpFilter(rateLimiters));
|
||||
webSocketEnvironment.jersey().register(new RequestStatisticsFilter(TrafficSource.WEBSOCKET));
|
||||
webSocketEnvironment.jersey().register(MultiRecipientMessageProvider.class);
|
||||
webSocketEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET, clientReleaseManager));
|
||||
webSocketEnvironment.jersey().register(new KeepAliveController(webSocketConnectionEventManager));
|
||||
webSocketEnvironment.jersey().register(new KeepAliveController(redisMessageAvailabilityManager));
|
||||
webSocketEnvironment.jersey().register(new TimestampResponseFilter());
|
||||
|
||||
final List<SpamFilter> spamFilters = ServiceLoader.load(SpamFilter.class)
|
||||
@@ -1116,7 +1116,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new RemoteConfigController(remoteConfigsManager, config.getRemoteConfigConfiguration().globalConfig(), clock),
|
||||
new SecureStorageController(storageCredentialsGenerator),
|
||||
new SecureValueRecovery2Controller(svr2CredentialsGenerator, accountsManager),
|
||||
new SecureValueRecoveryBController(svrbCredentialsGenerator),
|
||||
new StickerController(rateLimiters, config.getCdnConfiguration().credentials().accessKeyId().value(),
|
||||
config.getCdnConfiguration().credentials().secretAccessKey().value(), config.getCdnConfiguration().region(),
|
||||
config.getCdnConfiguration().bucket()),
|
||||
@@ -1145,7 +1144,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
webSocketEnvironment.getRequestLog(), Duration.ofMillis(60000));
|
||||
provisioningEnvironment.setConnectListener(new ProvisioningConnectListener(provisioningManager, provisioningWebsocketTimeoutExecutor, Duration.ofSeconds(90)));
|
||||
provisioningEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET, clientReleaseManager));
|
||||
provisioningEnvironment.jersey().register(new KeepAliveController(webSocketConnectionEventManager));
|
||||
provisioningEnvironment.jersey().register(new KeepAliveController(redisMessageAvailabilityManager));
|
||||
provisioningEnvironment.jersey().register(new TimestampResponseFilter());
|
||||
|
||||
registerExceptionMappers(environment, webSocketEnvironment, provisioningEnvironment);
|
||||
@@ -1174,9 +1173,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
environment.admin().addTask(new SetRequestLoggingEnabledTask());
|
||||
|
||||
// healthcheck, admin port
|
||||
environment.healthChecks().register("cacheCluster", new RedisClusterHealthCheck(cacheCluster));
|
||||
|
||||
MetricsUtil.registerSystemResourceMetrics(environment);
|
||||
}
|
||||
|
||||
@@ -1242,11 +1238,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
}
|
||||
}
|
||||
|
||||
private ExecutorService virtualExecutorService(final Environment environment, final String name) {
|
||||
return ExecutorServiceMetrics.monitor(
|
||||
Metrics.globalRegistry, environment.lifecycle().virtualExecutorService(name(getClass(), name) + "-%d"), name, MetricsUtil.PREFIX);
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
new WhisperServerService().run(args);
|
||||
}
|
||||
|
||||
+4
-9
@@ -5,20 +5,15 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* A disconnection request listener receives and handles requests to close authenticated client network connections.
|
||||
* A disconnection request listener receives and handles a request to close an authenticated network connection for a
|
||||
* specific client.
|
||||
*/
|
||||
public interface DisconnectionRequestListener {
|
||||
|
||||
/**
|
||||
* Handles a request to close authenticated network connections for one or more authenticated devices. Requests are
|
||||
* Handles a request to close an authenticated network connection for a specific authenticated device. Requests are
|
||||
* dispatched on dedicated threads, and implementations may safely block.
|
||||
*
|
||||
* @param accountIdentifier the account identifier for which to close authenticated connections
|
||||
* @param deviceIds the device IDs within the identified account for which to close authenticated connections
|
||||
*/
|
||||
void handleDisconnectionRequest(UUID accountIdentifier, Collection<Byte> deviceIds);
|
||||
void handleDisconnectionRequest();
|
||||
}
|
||||
+67
-24
@@ -5,25 +5,32 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import io.lettuce.core.pubsub.RedisPubSubAdapter;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Executor;
|
||||
import javax.annotation.Nullable;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.GrpcClientConnectionManager;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubConnection;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
|
||||
@@ -36,11 +43,11 @@ import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
public class DisconnectionRequestManager extends RedisPubSubAdapter<byte[], byte[]> implements Managed {
|
||||
|
||||
private final FaultTolerantRedisClient pubSubClient;
|
||||
private final GrpcClientConnectionManager grpcClientConnectionManager;
|
||||
private final Executor listenerEventExecutor;
|
||||
|
||||
// We expect just a couple listeners to get added at startup time and not at all at steady-state. There are several
|
||||
// reasonable ways to model this, but a copy-on-write list gives us good flexibility with minimal performance cost.
|
||||
private final List<DisconnectionRequestListener> listeners = new CopyOnWriteArrayList<>();
|
||||
private final Map<AccountIdentifierAndDeviceId, List<DisconnectionRequestListener>> listeners =
|
||||
new ConcurrentHashMap<>();
|
||||
|
||||
@Nullable
|
||||
private FaultTolerantPubSubConnection<byte[], byte[]> pubSubConnection;
|
||||
@@ -55,10 +62,14 @@ public class DisconnectionRequestManager extends RedisPubSubAdapter<byte[], byte
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(DisconnectionRequestManager.class);
|
||||
|
||||
private record AccountIdentifierAndDeviceId(UUID accountIdentifier, byte deviceId) {}
|
||||
|
||||
public DisconnectionRequestManager(final FaultTolerantRedisClient pubSubClient,
|
||||
final GrpcClientConnectionManager grpcClientConnectionManager,
|
||||
final Executor listenerEventExecutor) {
|
||||
|
||||
this.pubSubClient = pubSubClient;
|
||||
this.grpcClientConnectionManager = grpcClientConnectionManager;
|
||||
this.listenerEventExecutor = listenerEventExecutor;
|
||||
}
|
||||
|
||||
@@ -84,24 +95,53 @@ public class DisconnectionRequestManager extends RedisPubSubAdapter<byte[], byte
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a listener for disconnection requests. Listeners will receive all broadcast disconnection requests regardless
|
||||
* of whether the device in connection is connected to this server.
|
||||
* Adds a listener for disconnection requests for a specific authenticated device.
|
||||
*
|
||||
* @param accountIdentifier TODO
|
||||
* @param deviceId TODO
|
||||
* @param listener the listener to register
|
||||
*/
|
||||
public void addListener(final DisconnectionRequestListener listener) {
|
||||
listeners.add(listener);
|
||||
public void addListener(final UUID accountIdentifier, final byte deviceId, final DisconnectionRequestListener listener) {
|
||||
listeners.compute(new AccountIdentifierAndDeviceId(accountIdentifier, deviceId), (_, existingListeners) -> {
|
||||
final List<DisconnectionRequestListener> listeners =
|
||||
existingListeners == null ? new ArrayList<>() : existingListeners;
|
||||
|
||||
listeners.add(listener);
|
||||
|
||||
return listeners;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a listener for disconnection requests for a specific authenticated device.
|
||||
*
|
||||
* @param accountIdentifier TODO
|
||||
* @param deviceId TODO
|
||||
* @param listener the listener to remove
|
||||
*/
|
||||
public void removeListener(final UUID accountIdentifier, final byte deviceId, final DisconnectionRequestListener listener) {
|
||||
listeners.computeIfPresent(new AccountIdentifierAndDeviceId(accountIdentifier, deviceId), (_, existingListeners) -> {
|
||||
existingListeners.remove(listener);
|
||||
|
||||
return existingListeners.isEmpty() ? null : existingListeners;
|
||||
});
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
List<DisconnectionRequestListener> getListeners(final UUID accountIdentifier, final byte deviceId) {
|
||||
return listeners.getOrDefault(new AccountIdentifierAndDeviceId(accountIdentifier, deviceId), Collections.emptyList());
|
||||
}
|
||||
|
||||
/**
|
||||
* Broadcasts a request to close all connections associated with the given account identifier to all servers.
|
||||
*
|
||||
* @param accountIdentifier the account for which to close connections
|
||||
* @param account the account for which to close connections
|
||||
*
|
||||
* @return a future that completes when the request has been broadcast
|
||||
*/
|
||||
public CompletionStage<Void> requestDisconnection(final UUID accountIdentifier) {
|
||||
return requestDisconnection(accountIdentifier, Collections.emptyList());
|
||||
public CompletionStage<Void> requestDisconnection(final Account account) {
|
||||
return requestDisconnection(account.getIdentifier(IdentityType.ACI),
|
||||
account.getDevices().stream().map(Device::getId).toList());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -135,8 +175,7 @@ public class DisconnectionRequestManager extends RedisPubSubAdapter<byte[], byte
|
||||
DISCONNECTION_REQUESTS_RECEIVED_COUNTER.increment();
|
||||
|
||||
accountIdentifier = UUIDUtil.fromByteString(disconnectionRequest.getAccountIdentifier());
|
||||
deviceIds = disconnectionRequest.getDeviceIdsCount() > 0
|
||||
? disconnectionRequest.getDeviceIdsList().stream()
|
||||
deviceIds = disconnectionRequest.getDeviceIdsList().stream()
|
||||
.map(deviceIdInt -> {
|
||||
if (deviceIdInt == null || deviceIdInt < Device.PRIMARY_ID || deviceIdInt > Byte.MAX_VALUE) {
|
||||
throw new IllegalArgumentException("Invalid device ID: " + deviceIdInt);
|
||||
@@ -144,8 +183,7 @@ public class DisconnectionRequestManager extends RedisPubSubAdapter<byte[], byte
|
||||
|
||||
return deviceIdInt.byteValue();
|
||||
})
|
||||
.toList()
|
||||
: Device.ALL_POSSIBLE_DEVICE_IDS;
|
||||
.toList();
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
logger.error("Could not parse disconnection request protobuf", e);
|
||||
return;
|
||||
@@ -154,12 +192,17 @@ public class DisconnectionRequestManager extends RedisPubSubAdapter<byte[], byte
|
||||
return;
|
||||
}
|
||||
|
||||
for (final DisconnectionRequestListener listener : listeners) {
|
||||
try {
|
||||
listenerEventExecutor.execute(() -> listener.handleDisconnectionRequest(accountIdentifier, deviceIds));
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Listener failed to handle disconnection request", e);
|
||||
}
|
||||
}
|
||||
deviceIds.forEach(deviceId -> {
|
||||
grpcClientConnectionManager.closeConnection(new AuthenticatedDevice(accountIdentifier, deviceId));
|
||||
|
||||
listeners.getOrDefault(new AccountIdentifierAndDeviceId(accountIdentifier, deviceId), Collections.emptyList())
|
||||
.forEach(listener -> listenerEventExecutor.execute(() -> {
|
||||
try {
|
||||
listener.handleDisconnectionRequest();
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Listener failed to handle disconnection request", e);
|
||||
}
|
||||
}));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.backup;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.util.DataSize;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
@@ -19,6 +18,7 @@ import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -38,9 +38,12 @@ 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.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient;
|
||||
import org.whispersystems.textsecuregcm.util.AsyncTimerUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
@@ -94,9 +97,10 @@ public class BackupManager {
|
||||
private final Cdn3BackupCredentialGenerator cdn3BackupCredentialGenerator;
|
||||
private final RemoteStorageManager remoteStorageManager;
|
||||
private final SecureRandom secureRandom = new SecureRandom();
|
||||
private final ExternalServiceCredentialsGenerator secureValueRecoveryBCredentialsGenerator;
|
||||
private final SecureValueRecoveryClient secureValueRecoveryBClient;
|
||||
private final Clock clock;
|
||||
|
||||
|
||||
public BackupManager(
|
||||
final BackupsDb backupsDb,
|
||||
final GenericServerSecretParams serverSecretParams,
|
||||
@@ -104,6 +108,8 @@ public class BackupManager {
|
||||
final TusAttachmentGenerator tusAttachmentGenerator,
|
||||
final Cdn3BackupCredentialGenerator cdn3BackupCredentialGenerator,
|
||||
final RemoteStorageManager remoteStorageManager,
|
||||
final ExternalServiceCredentialsGenerator secureValueRecoveryBCredentialsGenerator,
|
||||
final SecureValueRecoveryClient secureValueRecoveryBClient,
|
||||
final Clock clock) {
|
||||
this.backupsDb = backupsDb;
|
||||
this.serverSecretParams = serverSecretParams;
|
||||
@@ -111,7 +117,9 @@ public class BackupManager {
|
||||
this.tusAttachmentGenerator = tusAttachmentGenerator;
|
||||
this.cdn3BackupCredentialGenerator = cdn3BackupCredentialGenerator;
|
||||
this.remoteStorageManager = remoteStorageManager;
|
||||
this.secureValueRecoveryBClient = secureValueRecoveryBClient;
|
||||
this.clock = clock;
|
||||
this.secureValueRecoveryBCredentialsGenerator = secureValueRecoveryBCredentialsGenerator;
|
||||
}
|
||||
|
||||
|
||||
@@ -387,6 +395,26 @@ public class BackupManager {
|
||||
return cdn3BackupCredentialGenerator.readHeaders(backupUser.backupDir());
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate credentials that can be used with SVRB
|
||||
*
|
||||
* @param backupUser an already ZK authenticated backup user
|
||||
* @return the credential that may be used with SVRB
|
||||
*/
|
||||
public ExternalServiceCredentials generateSvrbAuth(final AuthenticatedBackupUser backupUser) {
|
||||
checkBackupLevel(backupUser, BackupLevel.FREE);
|
||||
// Clients may only use SVRB with their messages backup-id
|
||||
checkBackupCredentialType(backupUser, BackupCredentialType.MESSAGES);
|
||||
return secureValueRecoveryBCredentialsGenerator.generateFor(svrbIdentifier(backupUser));
|
||||
}
|
||||
|
||||
private static String svrbIdentifier(final AuthenticatedBackupUser backupUser) {
|
||||
return svrbIdentifier(BackupsDb.hashedBackupId(backupUser.backupId()));
|
||||
}
|
||||
|
||||
private static String svrbIdentifier(final byte[] hashedBackupId) {
|
||||
return HexFormat.of().formatHex(hashedBackupId);
|
||||
}
|
||||
|
||||
/**
|
||||
* List of media stored for a particular backup id
|
||||
@@ -427,13 +455,19 @@ public class BackupManager {
|
||||
|
||||
public CompletableFuture<Void> deleteEntireBackup(final AuthenticatedBackupUser backupUser) {
|
||||
checkBackupLevel(backupUser, BackupLevel.FREE);
|
||||
return backupsDb
|
||||
|
||||
// Clients only include SVRB data with their messages backup-id
|
||||
final CompletableFuture<Void> svrbRemoval = switch(backupUser.credentialType()) {
|
||||
case BackupCredentialType.MESSAGES -> secureValueRecoveryBClient.removeData(svrbIdentifier(backupUser));
|
||||
case BackupCredentialType.MEDIA -> CompletableFuture.completedFuture(null);
|
||||
};
|
||||
return svrbRemoval.thenCompose(_ -> backupsDb
|
||||
// Try to swap out the backupDir for the user
|
||||
.scheduleBackupDeletion(backupUser)
|
||||
// If there was already a pending swap, try to delete the cdn objects directly
|
||||
.exceptionallyCompose(ExceptionUtils.exceptionallyHandler(BackupsDb.PendingDeletionException.class, e ->
|
||||
AsyncTimerUtil.record(SYNCHRONOUS_DELETE_TIMER, () ->
|
||||
deletePrefix(backupUser.backupDir(), DELETION_CONCURRENCY))));
|
||||
deletePrefix(backupUser.backupDir(), DELETION_CONCURRENCY)))));
|
||||
}
|
||||
|
||||
|
||||
@@ -617,12 +651,17 @@ public class BackupManager {
|
||||
* @return A stage that completes when the deletion operation is finished
|
||||
*/
|
||||
public CompletableFuture<Void> expireBackup(final ExpiredBackup expiredBackup) {
|
||||
return backupsDb.startExpiration(expiredBackup)
|
||||
// Clients only include SVRB data with their messages backup-id
|
||||
final CompletableFuture<Void> svrbRemoval = switch(expiredBackup.expirationType()) {
|
||||
case ALL -> secureValueRecoveryBClient.removeData(svrbIdentifier(expiredBackup.hashedBackupId()));
|
||||
case MEDIA, GARBAGE_COLLECTION -> CompletableFuture.completedFuture(null);
|
||||
};
|
||||
return svrbRemoval.thenCompose(_ -> backupsDb.startExpiration(expiredBackup)
|
||||
// the deletion operation is effectively single threaded -- it's expected that the caller can increase
|
||||
// concurrency by deleting more backups at once, rather than increasing concurrency deleting an individual
|
||||
// backup
|
||||
.thenCompose(ignored -> deletePrefix(expiredBackup.prefixToDelete(), 1))
|
||||
.thenCompose(ignored -> backupsDb.finishExpiration(expiredBackup));
|
||||
.thenCompose(ignored -> backupsDb.finishExpiration(expiredBackup)));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureValueRecoveryConfiguration;
|
||||
import java.time.Clock;
|
||||
|
||||
public class SecureValueRecoveryBCredentialsGeneratorFactory {
|
||||
private SecureValueRecoveryBCredentialsGeneratorFactory() {}
|
||||
|
||||
|
||||
@VisibleForTesting
|
||||
static ExternalServiceCredentialsGenerator svrbCredentialsGenerator(
|
||||
final SecureValueRecoveryConfiguration cfg,
|
||||
final Clock clock) {
|
||||
return ExternalServiceCredentialsGenerator
|
||||
.builder(cfg.userAuthenticationTokenSharedSecret())
|
||||
.withUserDerivationKey(cfg.userIdTokenSharedSecret().value())
|
||||
.prependUsername(false)
|
||||
.withDerivedUsernameTruncateLength(16)
|
||||
.withClock(clock)
|
||||
.build();
|
||||
}
|
||||
|
||||
public static ExternalServiceCredentialsGenerator svrbCredentialsGenerator(final SecureValueRecoveryConfiguration cfg) {
|
||||
return svrbCredentialsGenerator(cfg, Clock.systemUTC());
|
||||
}
|
||||
}
|
||||
+2
@@ -13,6 +13,8 @@ import java.time.Duration;
|
||||
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = DogstatsdConfiguration.class)
|
||||
public interface DatadogConfiguration extends StatsdConfig, Discoverable {
|
||||
|
||||
boolean enabled();
|
||||
|
||||
String getEnvironment();
|
||||
|
||||
Duration getShutdownWaitDuration();
|
||||
|
||||
+8
@@ -15,6 +15,9 @@ import java.time.Duration;
|
||||
@JsonTypeName("default")
|
||||
public class DogstatsdConfiguration implements DatadogConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
private boolean enabled = true;
|
||||
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
private Duration step = Duration.ofSeconds(10);
|
||||
@@ -27,6 +30,11 @@ public class DogstatsdConfiguration implements DatadogConfiguration {
|
||||
@NotBlank
|
||||
private String host;
|
||||
|
||||
@Override
|
||||
public boolean enabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Duration step() {
|
||||
return step;
|
||||
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAnyGetter;
|
||||
import com.fasterxml.jackson.annotation.JsonAnySetter;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import io.micrometer.registry.otlp.HistogramFlavor;
|
||||
import io.micrometer.registry.otlp.OtlpConfig;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
|
||||
public record OpenTelemetryConfiguration(
|
||||
@JsonProperty boolean enabled,
|
||||
@JsonProperty Duration shutdownWaitDuration,
|
||||
@JsonProperty int maxBucketCount,
|
||||
@JsonProperty Map<String, Integer> maxBucketsPerMeter,
|
||||
@JsonAnyGetter @JsonAnySetter Map<String, String> otlpConfig
|
||||
) implements OtlpConfig {
|
||||
|
||||
@Override
|
||||
public String get(String key) {
|
||||
return otlpConfig.get(key.split("\\.", 2)[1]);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Integer> maxBucketsPerMeter() {
|
||||
if (maxBucketsPerMeter == null) {
|
||||
return Map.of();
|
||||
}
|
||||
return maxBucketsPerMeter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HistogramFlavor histogramFlavor() {
|
||||
return HistogramFlavor.BASE2_EXPONENTIAL_BUCKET_HISTOGRAM;
|
||||
}
|
||||
|
||||
public Duration shutdownWaitDuration() {
|
||||
if (shutdownWaitDuration == null) {
|
||||
return step().plus(step().dividedBy(2));
|
||||
}
|
||||
return shutdownWaitDuration;
|
||||
}
|
||||
|
||||
}
|
||||
+30
@@ -64,6 +64,7 @@ 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.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupManager;
|
||||
import org.whispersystems.textsecuregcm.backup.CopyParameters;
|
||||
@@ -389,6 +390,35 @@ public class ArchiveController {
|
||||
.thenApply(ReadAuthResponse::new);
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/auth/svrb")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(
|
||||
summary = "Generate credentials for SVRB",
|
||||
description = """
|
||||
Generate SVRB service credentials. Generated credentials have an expiration time of 1 day (subject to change)
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "`JSON` with generated credentials.", useReturnTypeSchema = true)
|
||||
@ApiResponseZkAuth
|
||||
public CompletionStage<ExternalServiceCredentials> svrbAuth(
|
||||
@Auth final Optional<AuthenticatedDevice> account,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
|
||||
@Parameter(description = BackupAuthCredentialPresentationHeader.DESCRIPTION, schema = @Schema(implementation = String.class))
|
||||
@NotNull
|
||||
@HeaderParam(X_SIGNAL_ZK_AUTH) final ArchiveController.BackupAuthCredentialPresentationHeader presentation,
|
||||
|
||||
@Parameter(description = BackupAuthCredentialPresentationSignature.DESCRIPTION, schema = @Schema(implementation = String.class))
|
||||
@NotNull
|
||||
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature) {
|
||||
if (account.isPresent()) {
|
||||
throw new BadRequestException("must not use authenticated connection for anonymous operations");
|
||||
}
|
||||
return backupManager
|
||||
.authenticateBackupUser(presentation.presentation, signature.signature, userAgent)
|
||||
.thenApply(backupManager::generateSvrbAuth);
|
||||
}
|
||||
|
||||
public record BackupInfoResponse(
|
||||
@Schema(description = "The CDN type where the message backup is stored. Media may be stored elsewhere.")
|
||||
int cdn,
|
||||
|
||||
+12
-3
@@ -115,6 +115,8 @@ public class DeviceController {
|
||||
private static final String WAIT_FOR_TRANSFER_ARCHIVE_TIMER_NAME =
|
||||
MetricsUtil.name(DeviceController.class, "waitForTransferArchiveDuration");
|
||||
|
||||
private static final String RECORD_TRANSFER_ARCHIVE_UPLOADED_COUNTER_NAME = MetricsUtil.name(DeviceController.class, "recordTransferArchiveUploaded");
|
||||
private static final String HAS_REGISTRATION_ID_TAG_NAME = "hasRegistrationId";
|
||||
|
||||
@VisibleForTesting
|
||||
static final int MIN_TOKEN_IDENTIFIER_LENGTH = 32;
|
||||
@@ -533,8 +535,14 @@ public class DeviceController {
|
||||
@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")
|
||||
public CompletionStage<Void> recordTransferArchiveUploaded(@Auth final AuthenticatedDevice authenticatedDevice,
|
||||
@NotNull @Valid final TransferArchiveUploadedRequest transferArchiveUploadedRequest) {
|
||||
|
||||
@NotNull @Valid final TransferArchiveUploadedRequest transferArchiveUploadedRequest,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable String userAgent) {
|
||||
Metrics.counter(RECORD_TRANSFER_ARCHIVE_UPLOADED_COUNTER_NAME, Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
io.micrometer.core.instrument.Tag.of(
|
||||
HAS_REGISTRATION_ID_TAG_NAME,
|
||||
String.valueOf(transferArchiveUploadedRequest.registrationId().isPresent()))
|
||||
)).increment();
|
||||
return rateLimiters.getUploadTransferArchiveLimiter()
|
||||
.validateAsync(authenticatedDevice.accountIdentifier())
|
||||
.thenCompose(ignored -> accounts.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
|
||||
@@ -544,7 +552,8 @@ public class DeviceController {
|
||||
|
||||
return accounts.recordTransferArchiveUpload(account,
|
||||
transferArchiveUploadedRequest.destinationDeviceId(),
|
||||
Instant.ofEpochMilli(transferArchiveUploadedRequest.destinationDeviceCreated()),
|
||||
transferArchiveUploadedRequest.destinationDeviceCreated().map(Instant::ofEpochMilli),
|
||||
transferArchiveUploadedRequest.registrationId(),
|
||||
transferArchiveUploadedRequest.transferArchive());
|
||||
});
|
||||
}
|
||||
|
||||
+5
-5
@@ -22,7 +22,7 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.websocket.session.WebSocketSession;
|
||||
import org.whispersystems.websocket.session.WebSocketSessionContext;
|
||||
|
||||
@@ -33,14 +33,14 @@ public class KeepAliveController {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(KeepAliveController.class);
|
||||
|
||||
private final WebSocketConnectionEventManager webSocketConnectionEventManager;
|
||||
private final RedisMessageAvailabilityManager redisMessageAvailabilityManager;
|
||||
|
||||
private static final String CLOSED_CONNECTION_AGE_DISTRIBUTION_NAME = name(KeepAliveController.class,
|
||||
"closedConnectionAge");
|
||||
|
||||
|
||||
public KeepAliveController(final WebSocketConnectionEventManager webSocketConnectionEventManager) {
|
||||
this.webSocketConnectionEventManager = webSocketConnectionEventManager;
|
||||
public KeepAliveController(final RedisMessageAvailabilityManager redisMessageAvailabilityManager) {
|
||||
this.redisMessageAvailabilityManager = redisMessageAvailabilityManager;
|
||||
}
|
||||
|
||||
@GET
|
||||
@@ -48,7 +48,7 @@ public class KeepAliveController {
|
||||
@WebSocketSession WebSocketSessionContext context) {
|
||||
|
||||
maybeAuth.ifPresent(auth -> {
|
||||
if (!webSocketConnectionEventManager.isLocallyPresent(auth.accountIdentifier(), auth.deviceId())) {
|
||||
if (!redisMessageAvailabilityManager.isLocallyPresent(auth.accountIdentifier(), auth.deviceId())) {
|
||||
|
||||
final Duration age = Duration.between(context.getClient().getCreated(), Instant.now());
|
||||
|
||||
|
||||
+8
-48
@@ -34,7 +34,6 @@ import jakarta.ws.rs.QueryParam;
|
||||
import jakarta.ws.rs.WebApplicationException;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
@@ -57,7 +56,6 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.GroupSendTokenHeader;
|
||||
import org.whispersystems.textsecuregcm.auth.OptionalAccess;
|
||||
import org.whispersystems.textsecuregcm.entities.CheckKeysRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.ECPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.PreKeyCount;
|
||||
@@ -92,7 +90,6 @@ public class KeysController {
|
||||
private final ServerSecretParams serverSecretParams;
|
||||
private final Clock clock;
|
||||
|
||||
private static final String GET_KEYS_COUNTER_NAME = MetricsUtil.name(KeysController.class, "getKeys");
|
||||
private static final String STORE_KEYS_COUNTER_NAME = MetricsUtil.name(KeysController.class, "storeKeys");
|
||||
private static final String STORE_KEY_BUNDLE_SIZE_DISTRIBUTION_NAME =
|
||||
MetricsUtil.name(KeysController.class, "storeKeyBundleSize");
|
||||
@@ -395,51 +392,14 @@ public class KeysController {
|
||||
|
||||
final List<Device> devices = parseDeviceId(deviceId, target);
|
||||
|
||||
final List<PreKeyResponseItem> responseItems = Flux.fromIterable(devices)
|
||||
.flatMap(device -> Mono.zip(
|
||||
Mono.just(device),
|
||||
Mono.fromFuture(keysManager.takeEC(targetIdentifier.uuid(), device.getId())),
|
||||
Mono.fromFuture(keysManager.getEcSignedPreKey(targetIdentifier.uuid(), device.getId())),
|
||||
Mono.fromFuture(keysManager.takePQ(targetIdentifier.uuid(), device.getId()))))
|
||||
.flatMap(deviceAndPreKeys -> {
|
||||
final Device device = deviceAndPreKeys.getT1();
|
||||
final KEMSignedPreKey pqPreKey = deviceAndPreKeys.getT4().orElse(null);
|
||||
final ECPreKey unsignedEcPreKey = deviceAndPreKeys.getT2().orElse(null);
|
||||
final ECSignedPreKey signedEcPreKey = deviceAndPreKeys.getT3().orElse(null);
|
||||
final int registrationId = device.getRegistrationId(targetIdentifier.identityType());
|
||||
|
||||
Metrics.counter(GET_KEYS_COUNTER_NAME, Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(IDENTITY_TYPE_TAG_NAME, targetIdentifier.identityType().name()),
|
||||
Tag.of("oneTimeEcKeyAvailable", String.valueOf(unsignedEcPreKey != null)),
|
||||
Tag.of("signedEcKeyAvailable", String.valueOf(signedEcPreKey != null)),
|
||||
Tag.of("pqKeyAvailable", String.valueOf(pqPreKey != null))))
|
||||
.increment();
|
||||
|
||||
if (pqPreKey == null) {
|
||||
// The PQ prekey should never be null. This should only happen if the account or device has been
|
||||
// removed.
|
||||
return Mono.fromCompletionStage(() -> accounts.getByServiceIdentifierAsync(targetIdentifier))
|
||||
.flatMap(maybeAccount -> maybeAccount
|
||||
.flatMap(rereadAccount -> rereadAccount.getDevice(device.getId()))
|
||||
.filter(rereadDevice ->
|
||||
registrationId == rereadDevice.getRegistrationId(targetIdentifier.identityType()))
|
||||
.map(rereadDevice -> {
|
||||
// The account and device still exist, and the device we originally read matches the current
|
||||
// registrationId, so the lastResort key should have existed
|
||||
log.error(
|
||||
"Target {}, Account {}, DeviceId {}, RegistrationId {} was missing a last resort prekey",
|
||||
targetIdentifier,
|
||||
target.getIdentifier(IdentityType.ACI),
|
||||
rereadDevice.getId(),
|
||||
rereadDevice.getRegistrationId(targetIdentifier.identityType()));
|
||||
return Mono.<PreKeyResponseItem>error(new IOException("Device missing last resort prekey"));
|
||||
})
|
||||
.orElse(Mono.empty()));
|
||||
}
|
||||
return Mono.just(new PreKeyResponseItem(
|
||||
device.getId(), registrationId, signedEcPreKey, unsignedEcPreKey, pqPreKey));
|
||||
})
|
||||
final List<PreKeyResponseItem> responseItems = Flux.fromIterable(devices).flatMap(device -> Mono
|
||||
.fromCompletionStage(keysManager.takeDevicePreKeys(device.getId(), targetIdentifier, userAgent))
|
||||
.flatMap(Mono::justOrEmpty)
|
||||
.map(devicePreKeys -> new PreKeyResponseItem(
|
||||
device.getId(), device.getRegistrationId(targetIdentifier.identityType()),
|
||||
devicePreKeys.ecSignedPreKey(),
|
||||
devicePreKeys.ecPreKey().orElse(null),
|
||||
devicePreKeys.kemSignedPreKey())))
|
||||
.collectList()
|
||||
.block();
|
||||
|
||||
|
||||
-63
@@ -1,63 +0,0 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import java.time.Clock;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureValueRecoveryConfiguration;
|
||||
|
||||
@Path("/v1/svrb")
|
||||
@Tag(name = "Secure Value Recovery B")
|
||||
public class SecureValueRecoveryBController {
|
||||
|
||||
public static ExternalServiceCredentialsGenerator credentialsGenerator(final SecureValueRecoveryConfiguration cfg) {
|
||||
return credentialsGenerator(cfg, Clock.systemUTC());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public static ExternalServiceCredentialsGenerator credentialsGenerator(final SecureValueRecoveryConfiguration cfg,
|
||||
final Clock clock) {
|
||||
return ExternalServiceCredentialsGenerator
|
||||
.builder(cfg.userAuthenticationTokenSharedSecret())
|
||||
.withUserDerivationKey(cfg.userIdTokenSharedSecret().value())
|
||||
.prependUsername(false)
|
||||
.withDerivedUsernameTruncateLength(16)
|
||||
.withClock(clock)
|
||||
.build();
|
||||
}
|
||||
|
||||
private final ExternalServiceCredentialsGenerator svrbCredentialGenerator;
|
||||
|
||||
public SecureValueRecoveryBController(final ExternalServiceCredentialsGenerator svrbCredentialGenerator) {
|
||||
this.svrbCredentialGenerator = svrbCredentialGenerator;
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(
|
||||
summary = "Generate credentials for SVRB",
|
||||
description = """
|
||||
Generate SVRB service credentials. Generated credentials have an expiration time of 1 day (subject to change)
|
||||
"""
|
||||
)
|
||||
@ApiResponse(responseCode = "200", description = "`JSON` with generated credentials.", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
public ExternalServiceCredentials getAuth(@Auth final AuthenticatedDevice auth) {
|
||||
return svrbCredentialGenerator.generateFor(auth.accountIdentifier().toString());
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -19,7 +19,7 @@ public class PreKeyResponseItem {
|
||||
private int registrationId;
|
||||
|
||||
@JsonProperty
|
||||
@Schema(description="the signed elliptic-curve prekey for the device, if one has been set")
|
||||
@Schema(description="the signed elliptic-curve prekey for the device")
|
||||
private ECSignedPreKey signedPreKey;
|
||||
|
||||
@JsonProperty
|
||||
@@ -28,7 +28,7 @@ public class PreKeyResponseItem {
|
||||
|
||||
@JsonProperty
|
||||
@Schema(description="a signed post-quantum prekey for the device " +
|
||||
"(a one-time prekey if any remain, otherwise the last-resort prekey if one has been set)")
|
||||
"(a one-time prekey if any remain, otherwise the last-resort prekey)")
|
||||
private KEMSignedPreKey pqPreKey;
|
||||
|
||||
public PreKeyResponseItem() {}
|
||||
|
||||
+19
-4
@@ -7,21 +7,30 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.AssertTrue;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Positive;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public record TransferArchiveUploadedRequest(
|
||||
@Min(1)
|
||||
@Max(Device.MAXIMUM_DEVICE_ID)
|
||||
@Schema(description = "The ID of the device for which the transfer archive has been prepared")
|
||||
byte destinationDeviceId,
|
||||
|
||||
@Positive
|
||||
@Schema(description = "The timestamp, in milliseconds since the epoch, at which the destination device was created")
|
||||
long destinationDeviceCreated,
|
||||
@Schema(description = """
|
||||
The timestamp, in milliseconds since the epoch, at which the destination device was created.
|
||||
Deprecated in favor of registrationId.
|
||||
""", deprecated = true)
|
||||
@Deprecated
|
||||
Optional<@Positive Long> destinationDeviceCreated,
|
||||
|
||||
@Schema(description = "The registration ID of the destination device")
|
||||
Optional<@Min(0) @Max(Device.MAX_REGISTRATION_ID) Integer> registrationId,
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@@ -29,4 +38,10 @@ public record TransferArchiveUploadedRequest(
|
||||
The location of the transfer archive if the archive was successfully uploaded, otherwise a error indicating that
|
||||
the upload has failed and the destination device should stop waiting
|
||||
""", oneOf = {RemoteAttachment.class, RemoteAttachmentError.class})
|
||||
TransferArchiveResult transferArchive) {}
|
||||
TransferArchiveResult transferArchive) {
|
||||
@AssertTrue
|
||||
@Schema(hidden = true)
|
||||
public boolean isExactlyOneDisambiguatorProvided() {
|
||||
return destinationDeviceCreated.isPresent() ^ registrationId.isPresent();
|
||||
}
|
||||
}
|
||||
+12
@@ -21,6 +21,8 @@ import org.signal.chat.backup.GetBackupInfoRequest;
|
||||
import org.signal.chat.backup.GetBackupInfoResponse;
|
||||
import org.signal.chat.backup.GetCdnCredentialsRequest;
|
||||
import org.signal.chat.backup.GetCdnCredentialsResponse;
|
||||
import org.signal.chat.backup.GetSvrBCredentialsRequest;
|
||||
import org.signal.chat.backup.GetSvrBCredentialsResponse;
|
||||
import org.signal.chat.backup.GetUploadFormRequest;
|
||||
import org.signal.chat.backup.GetUploadFormResponse;
|
||||
import org.signal.chat.backup.ListMediaRequest;
|
||||
@@ -64,6 +66,16 @@ public class BackupsAnonymousGrpcService extends ReactorBackupsAnonymousGrpc.Bac
|
||||
.map(credentials -> GetCdnCredentialsResponse.newBuilder().putAllHeaders(credentials).build());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<GetSvrBCredentialsResponse> getSvrBCredentials(final GetSvrBCredentialsRequest request) {
|
||||
return authenticateBackupUserMono(request.getSignedPresentation())
|
||||
.map(backupManager::generateSvrbAuth)
|
||||
.map(credentials -> GetSvrBCredentialsResponse.newBuilder()
|
||||
.setUsername(credentials.username())
|
||||
.setPassword(credentials.password())
|
||||
.build());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<GetBackupInfoResponse> getBackupInfo(final GetBackupInfoRequest request) {
|
||||
return Mono.fromFuture(() ->
|
||||
|
||||
-10
@@ -47,16 +47,6 @@ enum ExternalServiceDefinitions {
|
||||
.withClock(clock)
|
||||
.build();
|
||||
}),
|
||||
SVRB(ExternalServiceType.EXTERNAL_SERVICE_TYPE_SVRB, (chatConfig, clock) -> {
|
||||
final SecureValueRecoveryConfiguration cfg = chatConfig.getSvrbConfiguration();
|
||||
return ExternalServiceCredentialsGenerator
|
||||
.builder(cfg.userAuthenticationTokenSharedSecret())
|
||||
.withUserDerivationKey(cfg.userIdTokenSharedSecret().value())
|
||||
.prependUsername(false)
|
||||
.withDerivedUsernameTruncateLength(16)
|
||||
.withClock(clock)
|
||||
.build();
|
||||
}),
|
||||
STORAGE(ExternalServiceType.EXTERNAL_SERVICE_TYPE_STORAGE, (chatConfig, clock) -> {
|
||||
final PaymentsServiceConfiguration cfg = chatConfig.getPaymentsServiceConfiguration();
|
||||
return ExternalServiceCredentialsGenerator
|
||||
|
||||
+2
-2
@@ -56,7 +56,7 @@ public class KeysAnonymousGrpcService extends ReactorKeysAnonymousGrpc.KeysAnony
|
||||
groupSendTokenUtil.checkGroupSendToken(request.getGroupSendToken(), serviceIdentifier);
|
||||
|
||||
yield lookUpAccount(serviceIdentifier, Status.NOT_FOUND)
|
||||
.flatMap(targetAccount -> KeysGrpcHelper.getPreKeys(targetAccount, serviceIdentifier.identityType(), deviceId, keysManager));
|
||||
.flatMap(targetAccount -> KeysGrpcHelper.getPreKeys(targetAccount, serviceIdentifier, deviceId, keysManager));
|
||||
} catch (final StatusException e) {
|
||||
yield Mono.error(e);
|
||||
}
|
||||
@@ -66,7 +66,7 @@ public class KeysAnonymousGrpcService extends ReactorKeysAnonymousGrpc.KeysAnony
|
||||
lookUpAccount(serviceIdentifier, Status.UNAUTHENTICATED)
|
||||
.flatMap(targetAccount ->
|
||||
UnidentifiedAccessUtil.checkUnidentifiedAccess(targetAccount, request.getUnidentifiedAccessKey().toByteArray())
|
||||
? KeysGrpcHelper.getPreKeys(targetAccount, serviceIdentifier.identityType(), deviceId, keysManager)
|
||||
? KeysGrpcHelper.getPreKeys(targetAccount, serviceIdentifier, deviceId, keysManager)
|
||||
: Mono.error(Status.UNAUTHENTICATED.asException()));
|
||||
|
||||
default -> Mono.error(Status.INVALID_ARGUMENT.asException());
|
||||
|
||||
@@ -11,10 +11,7 @@ import org.signal.chat.common.EcPreKey;
|
||||
import org.signal.chat.common.EcSignedPreKey;
|
||||
import org.signal.chat.common.KemSignedPreKey;
|
||||
import org.signal.chat.keys.GetPreKeysResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ECPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.KeysManager;
|
||||
@@ -28,7 +25,7 @@ class KeysGrpcHelper {
|
||||
static final byte ALL_DEVICES = 0;
|
||||
|
||||
static Mono<GetPreKeysResponse> getPreKeys(final Account targetAccount,
|
||||
final IdentityType identityType,
|
||||
final ServiceIdentifier targetServiceIdentifier,
|
||||
final byte targetDeviceId,
|
||||
final KeysManager keysManager) {
|
||||
|
||||
@@ -36,42 +33,37 @@ class KeysGrpcHelper {
|
||||
? Flux.fromIterable(targetAccount.getDevices())
|
||||
: Flux.from(Mono.justOrEmpty(targetAccount.getDevice(targetDeviceId)));
|
||||
|
||||
final String userAgent = RequestAttributesUtil.getUserAgent().orElse(null);
|
||||
return devices
|
||||
.switchIfEmpty(Mono.error(Status.NOT_FOUND.asException()))
|
||||
.flatMap(device -> Flux.merge(
|
||||
Mono.fromFuture(() -> keysManager.takeEC(targetAccount.getIdentifier(identityType), device.getId())),
|
||||
Mono.fromFuture(() -> keysManager.getEcSignedPreKey(targetAccount.getIdentifier(identityType), device.getId())),
|
||||
Mono.fromFuture(() -> keysManager.takePQ(targetAccount.getIdentifier(identityType), device.getId())))
|
||||
.flatMap(device -> Mono
|
||||
.fromFuture(keysManager.takeDevicePreKeys(device.getId(), targetServiceIdentifier, userAgent))
|
||||
.flatMap(Mono::justOrEmpty)
|
||||
.reduce(GetPreKeysResponse.PreKeyBundle.newBuilder(), (builder, preKey) -> {
|
||||
if (preKey instanceof ECPreKey ecPreKey) {
|
||||
builder.setEcOneTimePreKey(EcPreKey.newBuilder()
|
||||
.map(devicePreKeys -> {
|
||||
final GetPreKeysResponse.PreKeyBundle.Builder builder = GetPreKeysResponse.PreKeyBundle.newBuilder()
|
||||
.setEcSignedPreKey(EcSignedPreKey.newBuilder()
|
||||
.setKeyId(devicePreKeys.ecSignedPreKey().keyId())
|
||||
.setPublicKey(ByteString.copyFrom(devicePreKeys.ecSignedPreKey().serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(devicePreKeys.ecSignedPreKey().signature()))
|
||||
.build())
|
||||
.setKemOneTimePreKey(KemSignedPreKey.newBuilder()
|
||||
.setKeyId(devicePreKeys.kemSignedPreKey().keyId())
|
||||
.setPublicKey(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().signature()))
|
||||
.build());
|
||||
devicePreKeys.ecPreKey().ifPresent(ecPreKey -> builder.setEcOneTimePreKey(EcPreKey.newBuilder()
|
||||
.setKeyId(ecPreKey.keyId())
|
||||
.setPublicKey(ByteString.copyFrom(ecPreKey.serializedPublicKey()))
|
||||
.build());
|
||||
} else if (preKey instanceof ECSignedPreKey ecSignedPreKey) {
|
||||
builder.setEcSignedPreKey(EcSignedPreKey.newBuilder()
|
||||
.setKeyId(ecSignedPreKey.keyId())
|
||||
.setPublicKey(ByteString.copyFrom(ecSignedPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(ecSignedPreKey.signature()))
|
||||
.build());
|
||||
} else if (preKey instanceof KEMSignedPreKey kemSignedPreKey) {
|
||||
builder.setKemOneTimePreKey(KemSignedPreKey.newBuilder()
|
||||
.setKeyId(kemSignedPreKey.keyId())
|
||||
.setPublicKey(ByteString.copyFrom(kemSignedPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(kemSignedPreKey.signature()))
|
||||
.build());
|
||||
} else {
|
||||
throw new AssertionError("Unexpected pre-key type: " + preKey.getClass());
|
||||
}
|
||||
|
||||
return builder;
|
||||
})
|
||||
// Cast device IDs to `int` to match data types in the response object’s protobuf definition
|
||||
.map(builder -> Tuples.of((int) device.getId(), builder.build())))
|
||||
.build()));
|
||||
// Cast device IDs to `int` to match data types in the response object’s protobuf definition
|
||||
return Tuples.of((int) device.getId(), builder.build());
|
||||
}))
|
||||
// If there were no devices with valid prekey bundles in the account, the account is gone
|
||||
.switchIfEmpty(Mono.error(Status.NOT_FOUND.asException()))
|
||||
.collectMap(Tuple2::getT1, Tuple2::getT2)
|
||||
.map(preKeyBundles -> GetPreKeysResponse.newBuilder()
|
||||
.setIdentityKey(ByteString.copyFrom(targetAccount.getIdentityKey(identityType).serialize()))
|
||||
.setIdentityKey(ByteString
|
||||
.copyFrom(targetAccount.getIdentityKey(targetServiceIdentifier.identityType())
|
||||
.serialize()))
|
||||
.putAllPreKeys(preKeyBundles)
|
||||
.build());
|
||||
}
|
||||
|
||||
@@ -136,7 +136,7 @@ public class KeysGrpcService extends ReactorKeysGrpc.KeysImplBase {
|
||||
.flatMap(Mono::justOrEmpty))
|
||||
.switchIfEmpty(Mono.error(Status.NOT_FOUND.asException()))
|
||||
.flatMap(targetAccount ->
|
||||
KeysGrpcHelper.getPreKeys(targetAccount, targetIdentifier.identityType(), deviceId, keysManager));
|
||||
KeysGrpcHelper.getPreKeys(targetAccount, targetIdentifier, deviceId, keysManager));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+2
-12
@@ -10,19 +10,16 @@ import io.netty.channel.local.LocalChannel;
|
||||
import io.netty.util.AttributeKey;
|
||||
import java.net.InetAddress;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestListener;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.grpc.ChannelNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.grpc.RequestAttributes;
|
||||
@@ -45,7 +42,7 @@ import org.whispersystems.textsecuregcm.util.ClosableEpoch;
|
||||
* Methods for requesting connection closure accept an {@link AuthenticatedDevice} to identify the connection and may
|
||||
* be called from any application code.
|
||||
*/
|
||||
public class GrpcClientConnectionManager implements DisconnectionRequestListener {
|
||||
public class GrpcClientConnectionManager {
|
||||
|
||||
private final Map<LocalAddress, Channel> remoteChannelsByLocalAddress = new ConcurrentHashMap<>();
|
||||
private final Map<AuthenticatedDevice, List<Channel>> remoteChannelsByAuthenticatedDevice = new ConcurrentHashMap<>();
|
||||
@@ -62,7 +59,7 @@ public class GrpcClientConnectionManager implements DisconnectionRequestListener
|
||||
static final AttributeKey<ClosableEpoch> EPOCH_ATTRIBUTE_KEY =
|
||||
AttributeKey.valueOf(GrpcClientConnectionManager.class, "epoch");
|
||||
|
||||
private static OutboundCloseErrorMessage SERVER_CLOSED =
|
||||
private static final OutboundCloseErrorMessage SERVER_CLOSED =
|
||||
new OutboundCloseErrorMessage(OutboundCloseErrorMessage.Code.SERVER_CLOSED, "server closed");
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(GrpcClientConnectionManager.class);
|
||||
@@ -268,11 +265,4 @@ public class GrpcClientConnectionManager implements DisconnectionRequestListener
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleDisconnectionRequest(final UUID accountIdentifier, final Collection<Byte> deviceIds) {
|
||||
deviceIds.stream()
|
||||
.map(deviceId -> new AuthenticatedDevice(accountIdentifier, deviceId))
|
||||
.forEach(this::closeConnection);
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,11 @@ import io.micrometer.core.instrument.binder.system.FileDescriptorMetrics;
|
||||
import io.micrometer.core.instrument.binder.system.ProcessorMetrics;
|
||||
import io.micrometer.core.instrument.config.MeterFilter;
|
||||
import io.micrometer.core.instrument.distribution.DistributionStatisticConfig;
|
||||
import io.micrometer.registry.otlp.OtlpMeterRegistry;
|
||||
import io.micrometer.statsd.StatsdMeterRegistry;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerVersion;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
@@ -59,7 +63,9 @@ public class MetricsUtil {
|
||||
|
||||
SharedMetricRegistries.add(Constants.METRICS_NAME, environment.metrics());
|
||||
|
||||
{
|
||||
Duration shutdownWaitDuration = Duration.ZERO;
|
||||
|
||||
if (config.getDatadogConfiguration().enabled()) {
|
||||
final StatsdMeterRegistry dogstatsdMeterRegistry = new StatsdMeterRegistry(
|
||||
config.getDatadogConfiguration(), io.micrometer.core.instrument.Clock.SYSTEM);
|
||||
|
||||
@@ -71,6 +77,20 @@ public class MetricsUtil {
|
||||
|
||||
configureMeterFilters(dogstatsdMeterRegistry.config(), dynamicConfigurationManager);
|
||||
Metrics.addRegistry(dogstatsdMeterRegistry);
|
||||
|
||||
shutdownWaitDuration = config.getDatadogConfiguration().getShutdownWaitDuration();
|
||||
}
|
||||
|
||||
if (config.getOpenTelemetryConfiguration().enabled()) {
|
||||
final OtlpMeterRegistry otlpMeterRegistry = new OtlpMeterRegistry(
|
||||
config.getOpenTelemetryConfiguration(), io.micrometer.core.instrument.Clock.SYSTEM);
|
||||
|
||||
configureMeterFilters(otlpMeterRegistry.config(), dynamicConfigurationManager);
|
||||
Metrics.addRegistry(otlpMeterRegistry);
|
||||
|
||||
if (config.getOpenTelemetryConfiguration().shutdownWaitDuration().compareTo(shutdownWaitDuration) > 0) {
|
||||
shutdownWaitDuration = config.getOpenTelemetryConfiguration().shutdownWaitDuration();
|
||||
}
|
||||
}
|
||||
|
||||
environment.lifecycle().addServerLifecycleListener(
|
||||
@@ -78,8 +98,7 @@ public class MetricsUtil {
|
||||
|
||||
environment.lifecycle().addEventListener(new ApplicationShutdownMonitor(Metrics.globalRegistry));
|
||||
environment.lifecycle().addEventListener(
|
||||
new MicrometerRegistryManager(Metrics.globalRegistry,
|
||||
config.getDatadogConfiguration().getShutdownWaitDuration()));
|
||||
new MicrometerRegistryManager(Metrics.globalRegistry, shutdownWaitDuration));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.providers;
|
||||
|
||||
import com.codahale.metrics.health.HealthCheck;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
|
||||
public class RedisClusterHealthCheck extends HealthCheck {
|
||||
|
||||
private final FaultTolerantRedisClusterClient redisCluster;
|
||||
|
||||
public RedisClusterHealthCheck(final FaultTolerantRedisClusterClient redisCluster) {
|
||||
this.redisCluster = redisCluster;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Result check() {
|
||||
redisCluster.withCluster(connection -> connection.sync().upstream().commands().ping());
|
||||
return Result.healthy();
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.push;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* A message availability listener handles message availability and presence events related to a client's open message
|
||||
* stream. Handler methods are run on dedicated threads and may safely perform blocking operations.
|
||||
*
|
||||
* @see RedisMessageAvailabilityManager#handleClientConnected(UUID, byte, MessageAvailabilityListener)
|
||||
*/
|
||||
public interface MessageAvailabilityListener {
|
||||
|
||||
/**
|
||||
* Indicates that a new message is available in the connected client's message queue.
|
||||
*/
|
||||
void handleNewMessageAvailable();
|
||||
|
||||
/**
|
||||
* Indicates that messages for the client have been persisted from short-term storage to long-term storage.
|
||||
*/
|
||||
void handleMessagesPersisted();
|
||||
|
||||
/**
|
||||
* Indicates a newer instance of this client has started reading messages and the listener should close this client's
|
||||
* underlying network connection.
|
||||
*/
|
||||
void handleConflictingMessageReader();
|
||||
}
|
||||
-2
@@ -78,8 +78,6 @@ public class PushNotificationScheduler implements Managed {
|
||||
|
||||
private final int maxConcurrency;
|
||||
|
||||
private static final int PAGE_SIZE = 128;
|
||||
|
||||
NotificationWorker(final int maxConcurrency) {
|
||||
this.maxConcurrency = maxConcurrency;
|
||||
}
|
||||
|
||||
+22
-59
@@ -17,11 +17,9 @@ 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.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
@@ -32,37 +30,31 @@ import java.util.function.Function;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestListener;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubClusterConnection;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.util.RedisClusterUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
/**
|
||||
* The WebSocket connection event manager distributes events related to client presence and message availability to
|
||||
* The Redis message availability manager distributes events related to client presence and message availability to
|
||||
* registered listeners. In the current Signal server implementation, clients generally interact with the service by
|
||||
* opening a dual-purpose WebSocket. The WebSocket serves as both a delivery mechanism for messages and as a channel
|
||||
* for the client to issue API requests to the server. Clients are considered "present" if they have an open WebSocket
|
||||
* connection and are therefore likely to receive messages as soon as they're delivered to the server. WebSocket
|
||||
* connection managers make a best effort to ensure that clients have at most one active message delivery channel at
|
||||
* a time.
|
||||
* connection and are therefore likely to receive messages as soon as they're delivered to the server. Redis message
|
||||
* availability managers ensure that clients have at most one active message delivery channel at a time on a
|
||||
* best-effort basis.
|
||||
*
|
||||
* @implNote The WebSocket connection event manager uses the Redis 7 sharded pub/sub system to distribute events. This
|
||||
* @implNote The Redis message availability manager uses the Redis 7 sharded pub/sub system to distribute events. 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.
|
||||
*
|
||||
* @see WebSocketConnectionEventListener
|
||||
* @see org.whispersystems.textsecuregcm.storage.MessagesManager#insert(UUID, byte, MessageProtos.Envelope)
|
||||
* @see MessageAvailabilityListener
|
||||
* @see org.whispersystems.textsecuregcm.storage.MessagesManager#insert(UUID, Map)
|
||||
*/
|
||||
public class WebSocketConnectionEventManager extends RedisClusterPubSubAdapter<byte[], byte[]> implements Managed,
|
||||
DisconnectionRequestListener {
|
||||
public class RedisMessageAvailabilityManager extends RedisClusterPubSubAdapter<byte[], byte[]> implements Managed {
|
||||
|
||||
private final AccountsManager accountsManager;
|
||||
private final PushNotificationManager pushNotificationManager;
|
||||
private final FaultTolerantRedisClusterClient clusterClient;
|
||||
private final Executor listenerEventExecutor;
|
||||
|
||||
@@ -73,7 +65,7 @@ public class WebSocketConnectionEventManager extends RedisClusterPubSubAdapter<b
|
||||
@Nullable
|
||||
private FaultTolerantPubSubClusterConnection<byte[], byte[]> pubSubConnection;
|
||||
|
||||
private final Map<AccountAndDeviceIdentifier, WebSocketConnectionEventListener> listenersByAccountAndDeviceIdentifier;
|
||||
private final Map<AccountAndDeviceIdentifier, MessageAvailabilityListener> listenersByAccountAndDeviceIdentifier;
|
||||
|
||||
private final UUID serverId = UUID.randomUUID();
|
||||
|
||||
@@ -85,35 +77,30 @@ public class WebSocketConnectionEventManager extends RedisClusterPubSubAdapter<b
|
||||
.toByteArray();
|
||||
|
||||
private static final Counter PUBLISH_CLIENT_CONNECTION_EVENT_ERROR_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(WebSocketConnectionEventManager.class, "publishClientConnectionEventError"));
|
||||
Metrics.counter(MetricsUtil.name(RedisMessageAvailabilityManager.class, "publishClientConnectionEventError"));
|
||||
|
||||
private static final Counter UNSUBSCRIBE_ERROR_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(WebSocketConnectionEventManager.class, "unsubscribeError"));
|
||||
Metrics.counter(MetricsUtil.name(RedisMessageAvailabilityManager.class, "unsubscribeError"));
|
||||
|
||||
private static final Counter PUB_SUB_EVENT_WITHOUT_LISTENER_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(WebSocketConnectionEventManager.class, "pubSubEventWithoutListener"));
|
||||
Metrics.counter(MetricsUtil.name(RedisMessageAvailabilityManager.class, "pubSubEventWithoutListener"));
|
||||
|
||||
private static final Counter MESSAGE_AVAILABLE_WITHOUT_LISTENER_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(WebSocketConnectionEventManager.class, "messageAvailableWithoutListener"));
|
||||
Metrics.counter(MetricsUtil.name(RedisMessageAvailabilityManager.class, "messageAvailableWithoutListener"));
|
||||
|
||||
private static final String LISTENER_GAUGE_NAME =
|
||||
MetricsUtil.name(WebSocketConnectionEventManager.class, "listeners");
|
||||
MetricsUtil.name(RedisMessageAvailabilityManager.class, "listeners");
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(WebSocketConnectionEventManager.class);
|
||||
private static final Logger logger = LoggerFactory.getLogger(RedisMessageAvailabilityManager.class);
|
||||
|
||||
@VisibleForTesting
|
||||
record AccountAndDeviceIdentifier(UUID accountIdentifier, byte deviceId) {
|
||||
}
|
||||
|
||||
public WebSocketConnectionEventManager(final AccountsManager accountsManager,
|
||||
final PushNotificationManager pushNotificationManager,
|
||||
final FaultTolerantRedisClusterClient clusterClient,
|
||||
public RedisMessageAvailabilityManager(final FaultTolerantRedisClusterClient clusterClient,
|
||||
final Executor listenerEventExecutor,
|
||||
final Executor asyncOperationQueueingExecutor) {
|
||||
|
||||
this.accountsManager = accountsManager;
|
||||
this.pushNotificationManager = pushNotificationManager;
|
||||
|
||||
this.clusterClient = clusterClient;
|
||||
this.listenerEventExecutor = listenerEventExecutor;
|
||||
this.asyncOperationQueueingExecutor = asyncOperationQueueingExecutor;
|
||||
@@ -145,7 +132,7 @@ public class WebSocketConnectionEventManager extends RedisClusterPubSubAdapter<b
|
||||
/**
|
||||
* Marks the given device as "present" for message delivery and registers a listener for new messages and conflicting
|
||||
* connections. If the given device already has a presence registered with this manager, that presence is displaced
|
||||
* immediately and the listener's {@link WebSocketConnectionEventListener#handleConnectionDisplaced(boolean)} method is called.
|
||||
* immediately and the listener's {@link MessageAvailabilityListener#handleConflictingMessageReader()} 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
|
||||
@@ -156,13 +143,13 @@ public class WebSocketConnectionEventManager extends RedisClusterPubSubAdapter<b
|
||||
* pub/sub subscription could not be established, in which case callers should close the client's connection to the
|
||||
* server
|
||||
*/
|
||||
public CompletionStage<Void> handleClientConnected(final UUID accountIdentifier, final byte deviceId, final WebSocketConnectionEventListener listener) {
|
||||
public CompletionStage<Void> handleClientConnected(final UUID accountIdentifier, final byte deviceId, final MessageAvailabilityListener listener) {
|
||||
if (pubSubConnection == null) {
|
||||
throw new IllegalStateException("WebSocket connection event manager not started");
|
||||
}
|
||||
|
||||
final byte[] eventChannel = getClientEventChannel(accountIdentifier, deviceId);
|
||||
final AtomicReference<WebSocketConnectionEventListener> displacedListener = new AtomicReference<>();
|
||||
final AtomicReference<MessageAvailabilityListener> displacedListener = new AtomicReference<>();
|
||||
final AtomicReference<CompletionStage<Void>> subscribeFuture = new AtomicReference<>();
|
||||
|
||||
// Note that we're relying on some specific implementation details of `ConcurrentHashMap#compute(...)`. In
|
||||
@@ -189,7 +176,7 @@ public class WebSocketConnectionEventManager extends RedisClusterPubSubAdapter<b
|
||||
});
|
||||
|
||||
if (displacedListener.get() != null) {
|
||||
listenerEventExecutor.execute(() -> displacedListener.get().handleConnectionDisplaced(true));
|
||||
listenerEventExecutor.execute(() -> displacedListener.get().handleConflictingMessageReader());
|
||||
}
|
||||
|
||||
return subscribeFuture.get()
|
||||
@@ -260,14 +247,6 @@ public class WebSocketConnectionEventManager extends RedisClusterPubSubAdapter<b
|
||||
return listenersByAccountAndDeviceIdentifier.containsKey(new AccountAndDeviceIdentifier(accountUuid, deviceId));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleDisconnectionRequest(final UUID accountIdentifier, final Collection<Byte> deviceIds) {
|
||||
deviceIds.stream()
|
||||
.map(deviceId -> listenersByAccountAndDeviceIdentifier.get(new AccountAndDeviceIdentifier(accountIdentifier, deviceId)))
|
||||
.filter(Objects::nonNull)
|
||||
.forEach(listener -> listener.handleConnectionDisplaced(false));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
void resubscribe(final ClusterTopologyChangedEvent clusterTopologyChangedEvent) {
|
||||
final boolean[] changedSlots = RedisClusterUtil.getChangedSlots(clusterTopologyChangedEvent);
|
||||
@@ -328,7 +307,7 @@ public class WebSocketConnectionEventManager extends RedisClusterPubSubAdapter<b
|
||||
|
||||
final AccountAndDeviceIdentifier accountAndDeviceIdentifier = parseClientEventChannel(shardChannel);
|
||||
|
||||
@Nullable final WebSocketConnectionEventListener listener =
|
||||
@Nullable final MessageAvailabilityListener listener =
|
||||
listenersByAccountAndDeviceIdentifier.get(accountAndDeviceIdentifier);
|
||||
|
||||
if (listener != null) {
|
||||
@@ -339,7 +318,7 @@ public class WebSocketConnectionEventManager extends RedisClusterPubSubAdapter<b
|
||||
// Only act on new connections to other event 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));
|
||||
listenerEventExecutor.execute(listener::handleConflictingMessageReader);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -354,22 +333,6 @@ public class WebSocketConnectionEventManager extends RedisClusterPubSubAdapter<b
|
||||
|
||||
if (clientEvent.getEventCase() == ClientEvent.EventCase.NEW_MESSAGE_AVAILABLE) {
|
||||
MESSAGE_AVAILABLE_WITHOUT_LISTENER_COUNTER.increment();
|
||||
|
||||
// If we have an active subscription but no registered listener, it's likely that the publisher of this event
|
||||
// believes that the receiving client was present when it really wasn't. Send a push notification as a
|
||||
// just-in-case measure.
|
||||
accountsManager.getByAccountIdentifierAsync(accountAndDeviceIdentifier.accountIdentifier())
|
||||
.thenAccept(maybeAccount -> maybeAccount.ifPresent(account -> {
|
||||
try {
|
||||
pushNotificationManager.sendNewMessageNotification(account, accountAndDeviceIdentifier.deviceId(), true);
|
||||
} catch (final NotPushRegisteredException ignored) {
|
||||
}
|
||||
}))
|
||||
.whenComplete((ignored, throwable) -> {
|
||||
if (throwable != null) {
|
||||
logger.warn("Failed to send follow-up notification to {}:{}", accountAndDeviceIdentifier.accountIdentifier(), accountAndDeviceIdentifier.deviceId());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.push;
|
||||
|
||||
/**
|
||||
* A WebSocket connection event listener handles message availability and presence events related to a client's open
|
||||
* WebSocket connection. Handler methods are run on dedicated threads and may safely perform blocking operations.
|
||||
*/
|
||||
public interface WebSocketConnectionEventListener {
|
||||
|
||||
/**
|
||||
* Indicates that a new message is available in the connected client's message queue.
|
||||
*/
|
||||
void handleNewMessageAvailable();
|
||||
|
||||
/**
|
||||
* Indicates that messages for the client have been persisted from short-term storage to long-term storage.
|
||||
*/
|
||||
void handleMessagesPersisted();
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
@@ -21,7 +21,6 @@ import java.util.concurrent.CompletableFuture;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
public class ClusterLuaScript {
|
||||
|
||||
@@ -133,13 +132,7 @@ public class ClusterLuaScript {
|
||||
final T[] keys, final T[] args) {
|
||||
|
||||
return connection.reactive().evalsha(sha, scriptOutputType, keys, args)
|
||||
.onErrorResume(e -> {
|
||||
if (e instanceof RedisNoScriptException) {
|
||||
return connection.reactive().eval(script, scriptOutputType, keys, args);
|
||||
}
|
||||
|
||||
log.warn("Failed to execute script", e);
|
||||
return Mono.error(e);
|
||||
});
|
||||
.onErrorResume(RedisNoScriptException.class, _ -> connection.reactive().eval(script, scriptOutputType, keys, args))
|
||||
.doOnError(throwable -> log.warn("Failed to execute script", throwable));
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -128,7 +128,7 @@ public class FaultTolerantRedisClient {
|
||||
return withConnection(binaryConnection, function);
|
||||
}
|
||||
|
||||
public <K, V> void useConnection(final StatefulRedisConnection<K, V> connection,
|
||||
private <K, V> void useConnection(final StatefulRedisConnection<K, V> connection,
|
||||
final Consumer<StatefulRedisConnection<K, V>> consumer) {
|
||||
try {
|
||||
circuitBreaker.executeRunnable(() -> retry.executeRunnable(() -> consumer.accept(connection)));
|
||||
@@ -141,7 +141,7 @@ public class FaultTolerantRedisClient {
|
||||
}
|
||||
}
|
||||
|
||||
public <T, K, V> T withConnection(final StatefulRedisConnection<K, V> connection,
|
||||
private <T, K, V> T withConnection(final StatefulRedisConnection<K, V> connection,
|
||||
final Function<StatefulRedisConnection<K, V>, T> function) {
|
||||
try {
|
||||
return circuitBreaker.executeCallable(() -> retry.executeCallable(() -> function.apply(connection)));
|
||||
|
||||
+3
-3
@@ -165,7 +165,7 @@ public class FaultTolerantRedisClusterClient {
|
||||
return withConnectionReactive(binaryConnection, function);
|
||||
}
|
||||
|
||||
public <K, V> void useConnection(final StatefulRedisClusterConnection<K, V> connection,
|
||||
private <K, V> void useConnection(final StatefulRedisClusterConnection<K, V> connection,
|
||||
final Consumer<StatefulRedisClusterConnection<K, V>> consumer) {
|
||||
try {
|
||||
retry.executeRunnable(() -> consumer.accept(connection));
|
||||
@@ -178,7 +178,7 @@ public class FaultTolerantRedisClusterClient {
|
||||
}
|
||||
}
|
||||
|
||||
public <T, K, V> T withConnection(final StatefulRedisClusterConnection<K, V> connection,
|
||||
private <T, K, V> T withConnection(final StatefulRedisClusterConnection<K, V> connection,
|
||||
final Function<StatefulRedisClusterConnection<K, V>, T> function) {
|
||||
try {
|
||||
return retry.executeCallable(() -> function.apply(connection));
|
||||
@@ -191,7 +191,7 @@ public class FaultTolerantRedisClusterClient {
|
||||
}
|
||||
}
|
||||
|
||||
public <T, K, V> Publisher<T> withConnectionReactive(
|
||||
private <T, K, V> Publisher<T> withConnectionReactive(
|
||||
final StatefulRedisClusterConnection<K, V> connection,
|
||||
final Function<StatefulRedisClusterConnection<K, V>, Publisher<T>> function) {
|
||||
|
||||
|
||||
+10
-5
@@ -30,9 +30,10 @@ import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
|
||||
import org.whispersystems.textsecuregcm.util.HttpUtils;
|
||||
|
||||
/**
|
||||
* A client for sending requests to Signal's secure value recovery v2 service on behalf of authenticated users.
|
||||
* A client for sending requests to Signal's secure value recovery service on behalf of authenticated users.
|
||||
*/
|
||||
public class SecureValueRecoveryClient {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(SecureValueRecoveryClient.class);
|
||||
|
||||
private final ExternalServiceCredentialsGenerator secureValueRecoveryCredentialsGenerator;
|
||||
@@ -67,8 +68,12 @@ public class SecureValueRecoveryClient {
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> removeData(final UUID accountUuid) {
|
||||
return removeData(accountUuid.toString());
|
||||
}
|
||||
|
||||
final ExternalServiceCredentials credentials = secureValueRecoveryCredentialsGenerator.generateForUuid(accountUuid);
|
||||
public CompletableFuture<Void> removeData(final String userIdentifier) {
|
||||
|
||||
final ExternalServiceCredentials credentials = secureValueRecoveryCredentialsGenerator.generateFor(userIdentifier);
|
||||
|
||||
final HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(deleteUri)
|
||||
@@ -83,11 +88,11 @@ public class SecureValueRecoveryClient {
|
||||
|
||||
final List<Integer> allowedErrors = allowedDeletionErrorStatusCodes.get();
|
||||
if (allowedErrors.contains(response.statusCode())) {
|
||||
logger.warn("Ignoring failure to delete svr entry for account {} with status {}",
|
||||
accountUuid, response.statusCode());
|
||||
logger.warn("Ignoring failure to delete svr entry for identifier {} with status {}",
|
||||
userIdentifier, response.statusCode());
|
||||
return null;
|
||||
}
|
||||
logger.warn("Failed to delete svr entry for account {} with status {}", accountUuid, response.statusCode());
|
||||
logger.warn("Failed to delete svr entry for identifier {} with status {}", userIdentifier, response.statusCode());
|
||||
throw new SecureValueRecoveryException("Failed to delete backup", String.valueOf(response.statusCode()));
|
||||
});
|
||||
}
|
||||
|
||||
+102
-37
@@ -50,6 +50,7 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
@@ -85,6 +86,7 @@ import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.RegistrationIdValidator;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.core.publisher.Flux;
|
||||
@@ -111,6 +113,8 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
private static final String DELETE_COUNTER_NAME = name(AccountsManager.class, "deleteCounter");
|
||||
private static final String COUNTRY_CODE_TAG_NAME = "country";
|
||||
private static final String DELETION_REASON_TAG_NAME = "reason";
|
||||
private static final String TIMESTAMP_BASED_TRANSFER_ARCHIVE_KEY_COUNTER_NAME = name(AccountsManager.class, "timestampRedisKeyCounter");
|
||||
private static final String REGISTRATION_ID_BASED_TRANSFER_ARCHIVE_KEY_COUNTER_NAME = name(AccountsManager.class,"registrationIdRedisKeyCounter");
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(AccountsManager.class);
|
||||
|
||||
@@ -124,7 +128,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
private final ProfilesManager profilesManager;
|
||||
private final SecureStorageClient secureStorageClient;
|
||||
private final SecureValueRecoveryClient secureValueRecovery2Client;
|
||||
private final SecureValueRecoveryClient secureValueRecoveryBClient;
|
||||
private final DisconnectionRequestManager disconnectionRequestManager;
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
private final ClientPublicKeysManager clientPublicKeysManager;
|
||||
@@ -140,7 +143,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
private final Map<String, CompletableFuture<Optional<DeviceInfo>>> waitForDeviceFuturesByTokenIdentifier =
|
||||
new ConcurrentHashMap<>();
|
||||
|
||||
private final Map<TimestampedDeviceIdentifier, CompletableFuture<Optional<TransferArchiveResult>>> waitForTransferArchiveFuturesByDeviceIdentifier =
|
||||
private final Map<DeviceIdentifier, CompletableFuture<Optional<TransferArchiveResult>>> waitForTransferArchiveFuturesByDeviceIdentifier =
|
||||
new ConcurrentHashMap<>();
|
||||
|
||||
private final Map<String, CompletableFuture<Optional<RestoreAccountRequest>>> waitForRestoreAccountRequestFuturesByToken =
|
||||
@@ -155,6 +158,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
private static final Duration RECENTLY_ADDED_TRANSFER_ARCHIVE_TTL = Duration.ofHours(1);
|
||||
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 String TRANSFER_ARCHIVE_REGISTRATION_ID_PATTERN = "registrationId";
|
||||
|
||||
private static final Duration RESTORE_ACCOUNT_REQUEST_TTL = Duration.ofHours(1);
|
||||
private static final String RESTORE_ACCOUNT_REQUEST_PREFIX = "restore_account::";
|
||||
@@ -194,7 +198,14 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
}
|
||||
}
|
||||
|
||||
private record TimestampedDeviceIdentifier(UUID accountIdentifier, byte deviceId, Instant deviceCreationTimestamp) {
|
||||
private interface DeviceIdentifier {}
|
||||
|
||||
private record TimestampDeviceIdentifier(UUID accountIdentifier, byte deviceId, Instant deviceCreationTimestamp)
|
||||
implements DeviceIdentifier {
|
||||
}
|
||||
|
||||
private record RegistrationIdDeviceIdentifier(UUID accountIdentifier, byte deviceId,
|
||||
int registrationId) implements DeviceIdentifier {
|
||||
}
|
||||
|
||||
public AccountsManager(final Accounts accounts,
|
||||
@@ -207,7 +218,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
final ProfilesManager profilesManager,
|
||||
final SecureStorageClient secureStorageClient,
|
||||
final SecureValueRecoveryClient secureValueRecovery2Client,
|
||||
final SecureValueRecoveryClient secureValueRecoveryBClient,
|
||||
final DisconnectionRequestManager disconnectionRequestManager,
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
|
||||
final ClientPublicKeysManager clientPublicKeysManager,
|
||||
@@ -226,7 +236,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
this.profilesManager = profilesManager;
|
||||
this.secureStorageClient = secureStorageClient;
|
||||
this.secureValueRecovery2Client = secureValueRecovery2Client;
|
||||
this.secureValueRecoveryBClient = secureValueRecoveryBClient;
|
||||
this.disconnectionRequestManager = disconnectionRequestManager;
|
||||
this.registrationRecoveryPasswordsManager = requireNonNull(registrationRecoveryPasswordsManager);
|
||||
this.clientPublicKeysManager = clientPublicKeysManager;
|
||||
@@ -374,7 +383,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
keysManager.deleteSingleUsePreKeys(pni),
|
||||
messagesManager.clear(aci),
|
||||
profilesManager.deleteAll(aci, false))
|
||||
.thenCompose(ignored -> disconnectionRequestManager.requestDisconnection(aci))
|
||||
.thenCompose(ignored -> disconnectionRequestManager.requestDisconnection(e.getExistingAccount()))
|
||||
.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
|
||||
@@ -1220,7 +1229,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
return CompletableFuture.allOf(
|
||||
secureStorageClient.deleteStoredData(account.getUuid()),
|
||||
secureValueRecovery2Client.removeData(account.getUuid()),
|
||||
secureValueRecoveryBClient.removeData(account.getUuid()),
|
||||
keysManager.deleteSingleUsePreKeys(account.getUuid()),
|
||||
keysManager.deleteSingleUsePreKeys(account.getPhoneNumberIdentifier()),
|
||||
messagesManager.clear(account.getUuid()),
|
||||
@@ -1228,7 +1236,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
registrationRecoveryPasswordsManager.remove(account.getIdentifier(IdentityType.PNI)))
|
||||
.thenCompose(ignored -> accounts.delete(account.getUuid(), additionalWriteItems))
|
||||
.thenCompose(ignored -> redisDeleteAsync(account))
|
||||
.thenRun(() -> disconnectionRequestManager.requestDisconnection(account.getUuid()));
|
||||
.thenRun(() -> disconnectionRequestManager.requestDisconnection(account));
|
||||
}
|
||||
|
||||
private String getAccountMapKey(String key) {
|
||||
@@ -1509,34 +1517,66 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<TransferArchiveResult>> waitForTransferArchive(final Account account, final Device device, final Duration timeout) {
|
||||
final TimestampedDeviceIdentifier deviceIdentifier =
|
||||
new TimestampedDeviceIdentifier(account.getIdentifier(IdentityType.ACI),
|
||||
device.getId(),
|
||||
Instant.ofEpochMilli(device.getCreated()));
|
||||
final DeviceIdentifier timestampDeviceIdentifier = new TimestampDeviceIdentifier(account.getIdentifier(IdentityType.ACI), device.getId(), Instant.ofEpochMilli(device.getCreated()));
|
||||
final String timestampTransferArchiveKey = getTimestampTransferArchiveKey(account.getIdentifier(IdentityType.ACI), device.getId(), Instant.ofEpochMilli(device.getCreated()));
|
||||
|
||||
return waitForPubSubKey(waitForTransferArchiveFuturesByDeviceIdentifier,
|
||||
deviceIdentifier,
|
||||
getTransferArchiveKey(account.getIdentifier(IdentityType.ACI), device.getId(), Instant.ofEpochMilli(device.getCreated())),
|
||||
final DeviceIdentifier registrationIdDeviceIdentifier = new RegistrationIdDeviceIdentifier(account.getIdentifier(IdentityType.ACI), device.getId(), device.getRegistrationId(IdentityType.ACI));
|
||||
final String registrationIdTransferArchiveKey = getRegistrationIdTransferArchiveKey(account.getIdentifier(IdentityType.ACI), device.getId(), device.getRegistrationId(IdentityType.ACI));
|
||||
|
||||
final CompletableFuture<Optional<TransferArchiveResult>> timestampFuture = waitForPubSubKey(waitForTransferArchiveFuturesByDeviceIdentifier,
|
||||
timestampDeviceIdentifier,
|
||||
timestampTransferArchiveKey,
|
||||
timeout,
|
||||
this::handleTransferArchiveAdded);
|
||||
|
||||
final CompletableFuture<Optional<TransferArchiveResult>> registrationIdFuture = waitForPubSubKey(waitForTransferArchiveFuturesByDeviceIdentifier,
|
||||
registrationIdDeviceIdentifier,
|
||||
registrationIdTransferArchiveKey,
|
||||
timeout,
|
||||
this::handleTransferArchiveAdded);
|
||||
return firstSuccessfulTransferArchiveFuture(List.of(timestampFuture, registrationIdFuture));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static CompletableFuture<Optional<TransferArchiveResult>> firstSuccessfulTransferArchiveFuture(
|
||||
final List<CompletableFuture<Optional<TransferArchiveResult>>> futures) {
|
||||
final CompletableFuture<Optional<TransferArchiveResult>> result = new CompletableFuture<>();
|
||||
final AtomicInteger remaining = new AtomicInteger(futures.size());
|
||||
|
||||
for (CompletableFuture<Optional<TransferArchiveResult>> future : futures) {
|
||||
future.whenComplete((value, _) -> {
|
||||
if (value.isPresent()) {
|
||||
result.complete(value);
|
||||
} else if (remaining.decrementAndGet() == 0) {
|
||||
result.complete(Optional.empty());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> recordTransferArchiveUpload(final Account account,
|
||||
final byte destinationDeviceId,
|
||||
final Instant destinationDeviceCreationTimestamp,
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType") final Optional<Instant> destinationDeviceCreationTimestamp,
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType") final Optional<Integer> maybeRegistrationId,
|
||||
final TransferArchiveResult transferArchiveResult) {
|
||||
|
||||
final String key = getTransferArchiveKey(account.getIdentifier(IdentityType.ACI),
|
||||
destinationDeviceId,
|
||||
destinationDeviceCreationTimestamp);
|
||||
|
||||
try {
|
||||
final String transferArchiveJson = SystemMapper.jsonMapper().writeValueAsString(transferArchiveResult);
|
||||
|
||||
return pubSubRedisClient.withConnection(connection ->
|
||||
connection.async().set(key, transferArchiveJson, SetArgs.Builder.ex(RECENTLY_ADDED_TRANSFER_ARCHIVE_TTL)))
|
||||
.thenRun(Util.NOOP)
|
||||
.toCompletableFuture();
|
||||
return pubSubRedisClient.withConnection(connection -> {
|
||||
final String key = destinationDeviceCreationTimestamp
|
||||
.map(timestamp -> getTimestampTransferArchiveKey(account.getIdentifier(IdentityType.ACI), destinationDeviceId, timestamp))
|
||||
.orElseGet(() -> maybeRegistrationId
|
||||
.map(registrationId -> getRegistrationIdTransferArchiveKey(account.getIdentifier(IdentityType.ACI), destinationDeviceId, registrationId))
|
||||
// We validate the request object so this should never happen
|
||||
.orElseThrow(() -> new AssertionError("No creation timestamp or registration ID provided")));
|
||||
|
||||
return connection.async()
|
||||
.set(key, transferArchiveJson, SetArgs.Builder.ex(RECENTLY_ADDED_TRANSFER_ARCHIVE_TTL))
|
||||
.thenRun(Util.NOOP)
|
||||
.toCompletableFuture();
|
||||
});
|
||||
} catch (final JsonProcessingException e) {
|
||||
// This should never happen for well-defined objects we control
|
||||
throw new UncheckedIOException(e);
|
||||
@@ -1552,15 +1592,27 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
}
|
||||
}
|
||||
|
||||
private static String getTransferArchiveKey(final UUID accountIdentifier,
|
||||
private static String getTimestampTransferArchiveKey(final UUID accountIdentifier,
|
||||
final byte destinationDeviceId,
|
||||
final Instant destinationDeviceCreationTimestamp) {
|
||||
Metrics.counter(TIMESTAMP_BASED_TRANSFER_ARCHIVE_KEY_COUNTER_NAME).increment();
|
||||
|
||||
return TRANSFER_ARCHIVE_PREFIX + accountIdentifier.toString() +
|
||||
":" + destinationDeviceId +
|
||||
":" + destinationDeviceCreationTimestamp.toEpochMilli();
|
||||
}
|
||||
|
||||
private static String getRegistrationIdTransferArchiveKey(final UUID accountIdentifier,
|
||||
final byte destinationDeviceId,
|
||||
final int registrationId) {
|
||||
Metrics.counter(REGISTRATION_ID_BASED_TRANSFER_ARCHIVE_KEY_COUNTER_NAME).increment();
|
||||
|
||||
return TRANSFER_ARCHIVE_PREFIX + accountIdentifier.toString() +
|
||||
":" + destinationDeviceId +
|
||||
":" + TRANSFER_ARCHIVE_REGISTRATION_ID_PATTERN +
|
||||
":" + registrationId;
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<RestoreAccountRequest>> waitForRestoreAccountRequest(final String token, final Duration timeout) {
|
||||
return waitForPubSubKey(waitForRestoreAccountRequestFuturesByToken,
|
||||
token,
|
||||
@@ -1648,23 +1700,36 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
} else if (TRANSFER_ARCHIVE_KEYSPACE_PATTERN.equals(pattern) && "set".equalsIgnoreCase(message)) {
|
||||
// The `- 1` here compensates for the '*' in the pattern
|
||||
final String[] deviceIdentifierComponents =
|
||||
channel.substring(TRANSFER_ARCHIVE_KEYSPACE_PATTERN.length() - 1).split(":", 3);
|
||||
channel.substring(TRANSFER_ARCHIVE_KEYSPACE_PATTERN.length() - 1).split(":", 4);
|
||||
|
||||
if (deviceIdentifierComponents.length != 3) {
|
||||
logger.error("Could not parse timestamped device identifier; unexpected component count");
|
||||
if (deviceIdentifierComponents.length != 3 && deviceIdentifierComponents.length != 4) {
|
||||
logger.error("Could not parse device identifier; unexpected component count");
|
||||
return;
|
||||
}
|
||||
|
||||
final DeviceIdentifier deviceIdentifier;
|
||||
final String transferArchiveKey;
|
||||
try {
|
||||
final TimestampedDeviceIdentifier deviceIdentifier;
|
||||
final String transferArchiveKey;
|
||||
{
|
||||
final UUID accountIdentifier = UUID.fromString(deviceIdentifierComponents[0]);
|
||||
final byte deviceId = Byte.parseByte(deviceIdentifierComponents[1]);
|
||||
final UUID accountIdentifier = UUID.fromString(deviceIdentifierComponents[0]);
|
||||
final byte deviceId = Byte.parseByte(deviceIdentifierComponents[1]);
|
||||
|
||||
if (deviceIdentifierComponents.length == 3) {
|
||||
// Parse the old transfer archive Redis key format
|
||||
final Instant deviceCreationTimestamp = Instant.ofEpochMilli(Long.parseLong(deviceIdentifierComponents[2]));
|
||||
|
||||
deviceIdentifier = new TimestampedDeviceIdentifier(accountIdentifier, deviceId, deviceCreationTimestamp);
|
||||
transferArchiveKey = getTransferArchiveKey(accountIdentifier, deviceId, deviceCreationTimestamp);
|
||||
deviceIdentifier = new TimestampDeviceIdentifier(accountIdentifier, deviceId, deviceCreationTimestamp);
|
||||
transferArchiveKey = getTimestampTransferArchiveKey(accountIdentifier, deviceId, deviceCreationTimestamp);
|
||||
} else {
|
||||
final String maybeRegistrationIdPattern = deviceIdentifierComponents[2];
|
||||
if (!maybeRegistrationIdPattern.equals(TRANSFER_ARCHIVE_REGISTRATION_ID_PATTERN)) {
|
||||
throw new IllegalArgumentException("Could not parse Redis key with pattern " + maybeRegistrationIdPattern);
|
||||
}
|
||||
final int registrationId = Integer.parseInt(deviceIdentifierComponents[3]);
|
||||
if (!RegistrationIdValidator.validRegistrationId(registrationId)) {
|
||||
throw new IllegalArgumentException("Invalid registration ID: " + registrationId);
|
||||
}
|
||||
deviceIdentifier = new RegistrationIdDeviceIdentifier(accountIdentifier, deviceId, registrationId);
|
||||
transferArchiveKey = getRegistrationIdTransferArchiveKey(accountIdentifier, deviceId, registrationId);
|
||||
}
|
||||
|
||||
Optional.ofNullable(waitForTransferArchiveFuturesByDeviceIdentifier.remove(deviceIdentifier))
|
||||
@@ -1677,7 +1742,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
}
|
||||
}));
|
||||
} catch (final IllegalArgumentException e) {
|
||||
logger.error("Could not parse timestamped device identifier", e);
|
||||
logger.error("Could not parse device identifier", e);
|
||||
}
|
||||
} else if (RESTORE_ACCOUNT_REQUEST_KEYSPACE_PATTERN.equalsIgnoreCase(pattern) && "set".equalsIgnoreCase(message)) {
|
||||
// The `- 1` here compensates for the '*' in the pattern
|
||||
|
||||
@@ -5,20 +5,31 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import org.whispersystems.textsecuregcm.controllers.KeysController;
|
||||
import org.whispersystems.textsecuregcm.entities.ECPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Futures;
|
||||
import org.whispersystems.textsecuregcm.util.Optionals;
|
||||
import reactor.core.publisher.Flux;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
public class KeysManager {
|
||||
// KeysController for backwards compatibility
|
||||
private static final String GET_KEYS_COUNTER_NAME = MetricsUtil.name(KeysController.class, "getKeys");
|
||||
|
||||
private final SingleUseECPreKeyStore ecPreKeys;
|
||||
private final SingleUseKEMPreKeyStore pqPreKeys;
|
||||
@@ -115,11 +126,13 @@ public class KeysManager {
|
||||
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<ECPreKey>> takeEC(final UUID identifier, final byte deviceId) {
|
||||
@VisibleForTesting
|
||||
CompletableFuture<Optional<ECPreKey>> takeEC(final UUID identifier, final byte deviceId) {
|
||||
return ecPreKeys.take(identifier, deviceId);
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<KEMSignedPreKey>> takePQ(final UUID identifier, final byte deviceId) {
|
||||
@VisibleForTesting
|
||||
CompletableFuture<Optional<KEMSignedPreKey>> takePQ(final UUID identifier, final byte deviceId) {
|
||||
final boolean enrolledInPagedKeys = experimentEnrollmentManager.isEnrolled(identifier, PAGED_KEYS_EXPERIMENT_NAME);
|
||||
return tagTakePQ(pagedPqPreKeys.take(identifier, deviceId), PQSource.PAGE, enrolledInPagedKeys)
|
||||
.thenCompose(maybeSingleUsePreKey -> maybeSingleUsePreKey
|
||||
@@ -209,4 +222,36 @@ public class KeysManager {
|
||||
public CompletableFuture<Void> pruneDeadPage(final UUID identifier, final byte deviceId, final UUID pageId) {
|
||||
return pagedPqPreKeys.deleteBundleFromS3(identifier, deviceId, pageId);
|
||||
}
|
||||
|
||||
public record DevicePreKeys(
|
||||
ECSignedPreKey ecSignedPreKey,
|
||||
Optional<ECPreKey> ecPreKey,
|
||||
KEMSignedPreKey kemSignedPreKey) {}
|
||||
|
||||
public CompletableFuture<Optional<DevicePreKeys>> takeDevicePreKeys(
|
||||
final byte deviceId,
|
||||
final ServiceIdentifier serviceIdentifier,
|
||||
final @Nullable String userAgent) {
|
||||
final UUID uuid = serviceIdentifier.uuid();
|
||||
return Futures.zipWith(
|
||||
this.takeEC(uuid, deviceId),
|
||||
this.getEcSignedPreKey(uuid, deviceId),
|
||||
this.takePQ(uuid, deviceId),
|
||||
(maybeUnsignedEcPreKey, maybeSignedEcPreKey, maybePqPreKey) -> {
|
||||
|
||||
Metrics.counter(GET_KEYS_COUNTER_NAME, Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of("identityType", serviceIdentifier.identityType().name()),
|
||||
Tag.of("oneTimeEcKeyAvailable", String.valueOf(maybeUnsignedEcPreKey.isPresent())),
|
||||
Tag.of("signedEcKeyAvailable", String.valueOf(maybeSignedEcPreKey.isPresent())),
|
||||
Tag.of("pqKeyAvailable", String.valueOf(maybePqPreKey.isPresent()))))
|
||||
.increment();
|
||||
|
||||
// The pq prekey and signed EC prekey should never be null for an existing account. This should only happen
|
||||
// if the account or device has been removed and the read was split, so we can return empty in those cases.
|
||||
return Optionals.zipWith(maybeSignedEcPreKey, maybePqPreKey, (signedEcPreKey, pqPreKey) ->
|
||||
new DevicePreKeys(signedEcPreKey, maybeUnsignedEcPreKey, pqPreKey));
|
||||
})
|
||||
.toCompletableFuture();
|
||||
}
|
||||
}
|
||||
@@ -52,6 +52,7 @@ import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
import reactor.util.retry.RetrySpec;
|
||||
|
||||
/**
|
||||
* Manages short-term storage of messages in Redis. Messages are frequently delivered to their destination and deleted
|
||||
@@ -284,11 +285,6 @@ public class MessagesCache {
|
||||
|
||||
}
|
||||
|
||||
public boolean hasMessages(final UUID destinationUuid, final byte destinationDevice) {
|
||||
return redisCluster.withBinaryCluster(
|
||||
connection -> connection.sync().zcard(getMessageQueueKey(destinationUuid, destinationDevice)) > 0);
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> hasMessagesAsync(final UUID destinationUuid, final byte destinationDevice) {
|
||||
return redisCluster.withBinaryCluster(connection ->
|
||||
connection.async().zcard(getMessageQueueKey(destinationUuid, destinationDevice))
|
||||
@@ -521,6 +517,7 @@ public class MessagesCache {
|
||||
long messageId, int pageSize) {
|
||||
|
||||
return getItemsScript.execute(destinationUuid, destinationDevice, pageSize, messageId)
|
||||
.retryWhen(RetrySpec.backoff(4, Duration.ofSeconds(1)).maxBackoff(Duration.ofSeconds(4)))
|
||||
.map(queueItems -> {
|
||||
logger.trace("Processing page: {}", messageId);
|
||||
|
||||
|
||||
+2
-2
@@ -16,7 +16,7 @@ import java.util.concurrent.CompletableFuture;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.push.ClientEvent;
|
||||
import org.whispersystems.textsecuregcm.push.NewMessageAvailableEvent;
|
||||
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
|
||||
@@ -53,7 +53,7 @@ class MessagesCacheInsertScript {
|
||||
MessagesCache.getMessageQueueKey(destinationUuid, destinationDevice), // queueKey
|
||||
MessagesCache.getMessageQueueMetadataKey(destinationUuid, destinationDevice), // queueMetadataKey
|
||||
MessagesCache.getQueueIndexKey(destinationUuid, destinationDevice), // queueTotalIndexKey
|
||||
WebSocketConnectionEventManager.getClientEventChannel(destinationUuid, destinationDevice) // eventChannelKey
|
||||
RedisMessageAvailabilityManager.getClientEventChannel(destinationUuid, destinationDevice) // eventChannelKey
|
||||
);
|
||||
|
||||
final List<byte[]> args = new ArrayList<>(Arrays.asList(
|
||||
|
||||
+2
-2
@@ -8,7 +8,7 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
import io.lettuce.core.ScriptOutputType;
|
||||
import org.whispersystems.textsecuregcm.push.ClientEvent;
|
||||
import org.whispersystems.textsecuregcm.push.MessagesPersistedEvent;
|
||||
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import java.io.IOException;
|
||||
@@ -35,7 +35,7 @@ class MessagesCacheUnlockQueueScript {
|
||||
void execute(final UUID accountIdentifier, final byte deviceId) {
|
||||
final List<byte[]> keys = List.of(
|
||||
MessagesCache.getPersistInProgressKey(accountIdentifier, deviceId), // persistInProgressKey
|
||||
WebSocketConnectionEventManager.getClientEventChannel(accountIdentifier, deviceId) // eventChannelKey
|
||||
RedisMessageAvailabilityManager.getClientEventChannel(accountIdentifier, deviceId) // eventChannelKey
|
||||
);
|
||||
|
||||
unlockQueueScript.executeBinary(keys, MESSAGES_PERSISTED_EVENT_ARGS);
|
||||
|
||||
@@ -33,6 +33,7 @@ import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import reactor.core.observability.micrometer.Micrometer;
|
||||
import reactor.core.publisher.Flux;
|
||||
@@ -82,7 +83,7 @@ public class MessagesManager {
|
||||
*
|
||||
* @return a map of device IDs to a device's presence state (i.e. if the device has an active event listener)
|
||||
*
|
||||
* @see org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager
|
||||
* @see RedisMessageAvailabilityManager
|
||||
*/
|
||||
public Map<Byte, Boolean> insert(final UUID accountIdentifier, final Map<Byte, Envelope> messagesByDeviceId) {
|
||||
return insertAsync(accountIdentifier, messagesByDeviceId).join();
|
||||
@@ -127,7 +128,7 @@ public class MessagesManager {
|
||||
* @return a map of accounts to maps of device IDs to a device's presence state (i.e. if the device has an active
|
||||
* event listener)
|
||||
*
|
||||
* @see org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager
|
||||
* @see RedisMessageAvailabilityManager
|
||||
*/
|
||||
public CompletableFuture<Map<Account, Map<Byte, Boolean>>> insertMultiRecipientMessage(
|
||||
final SealedSenderMultiRecipientMessage multiRecipientMessage,
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import org.apache.commons.lang3.function.TriFunction;
|
||||
|
||||
public class Futures {
|
||||
|
||||
public static <T, U, V, R> CompletionStage<R> zipWith(
|
||||
CompletionStage<T> futureT,
|
||||
CompletionStage<U> futureU,
|
||||
CompletionStage<V> futureV,
|
||||
TriFunction<T, U, V, R> fun) {
|
||||
|
||||
return futureT.thenCompose(t -> futureU.thenCombine(futureV, (u, v) -> fun.apply(t, u, v)));
|
||||
}
|
||||
}
|
||||
+30
-22
@@ -9,18 +9,19 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor;
|
||||
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
|
||||
import org.whispersystems.textsecuregcm.metrics.OpenWebSocketCounter;
|
||||
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
|
||||
@@ -47,8 +48,8 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
private final MessageMetrics messageMetrics;
|
||||
private final PushNotificationManager pushNotificationManager;
|
||||
private final PushNotificationScheduler pushNotificationScheduler;
|
||||
private final WebSocketConnectionEventManager webSocketConnectionEventManager;
|
||||
private final ScheduledExecutorService scheduledExecutorService;
|
||||
private final RedisMessageAvailabilityManager redisMessageAvailabilityManager;
|
||||
private final DisconnectionRequestManager disconnectionRequestManager;
|
||||
private final Scheduler messageDeliveryScheduler;
|
||||
private final ClientReleaseManager clientReleaseManager;
|
||||
private final MessageDeliveryLoopMonitor messageDeliveryLoopMonitor;
|
||||
@@ -58,17 +59,17 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
private final OpenWebSocketCounter openUnauthenticatedWebSocketCounter;
|
||||
|
||||
public AuthenticatedConnectListener(
|
||||
AccountsManager accountsManager,
|
||||
ReceiptSender receiptSender,
|
||||
MessagesManager messagesManager,
|
||||
MessageMetrics messageMetrics,
|
||||
PushNotificationManager pushNotificationManager,
|
||||
PushNotificationScheduler pushNotificationScheduler,
|
||||
WebSocketConnectionEventManager webSocketConnectionEventManager,
|
||||
ScheduledExecutorService scheduledExecutorService,
|
||||
Scheduler messageDeliveryScheduler,
|
||||
ClientReleaseManager clientReleaseManager,
|
||||
MessageDeliveryLoopMonitor messageDeliveryLoopMonitor,
|
||||
final AccountsManager accountsManager,
|
||||
final ReceiptSender receiptSender,
|
||||
final MessagesManager messagesManager,
|
||||
final MessageMetrics messageMetrics,
|
||||
final PushNotificationManager pushNotificationManager,
|
||||
final PushNotificationScheduler pushNotificationScheduler,
|
||||
final RedisMessageAvailabilityManager redisMessageAvailabilityManager,
|
||||
final DisconnectionRequestManager disconnectionRequestManager,
|
||||
final Scheduler messageDeliveryScheduler,
|
||||
final ClientReleaseManager clientReleaseManager,
|
||||
final MessageDeliveryLoopMonitor messageDeliveryLoopMonitor,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager) {
|
||||
|
||||
this.accountsManager = accountsManager;
|
||||
@@ -77,8 +78,8 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
this.messageMetrics = messageMetrics;
|
||||
this.pushNotificationManager = pushNotificationManager;
|
||||
this.pushNotificationScheduler = pushNotificationScheduler;
|
||||
this.webSocketConnectionEventManager = webSocketConnectionEventManager;
|
||||
this.scheduledExecutorService = scheduledExecutorService;
|
||||
this.redisMessageAvailabilityManager = redisMessageAvailabilityManager;
|
||||
this.disconnectionRequestManager = disconnectionRequestManager;
|
||||
this.messageDeliveryScheduler = messageDeliveryScheduler;
|
||||
this.clientReleaseManager = clientReleaseManager;
|
||||
this.messageDeliveryLoopMonitor = messageDeliveryLoopMonitor;
|
||||
@@ -104,7 +105,7 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
final AuthenticatedDevice auth = context.getAuthenticated(AuthenticatedDevice.class);
|
||||
|
||||
final Optional<Account> maybeAuthenticatedAccount = accountsManager.getByAccountIdentifier(auth.accountIdentifier());
|
||||
final Optional<Device> maybeAuthenticatedDevice = maybeAuthenticatedAccount.flatMap(account -> account.getDevice(auth.deviceId()));;
|
||||
final Optional<Device> maybeAuthenticatedDevice = maybeAuthenticatedAccount.flatMap(account -> account.getDevice(auth.deviceId()));
|
||||
|
||||
if (maybeAuthenticatedAccount.isEmpty() || maybeAuthenticatedDevice.isEmpty()) {
|
||||
log.warn("{}:{} not found when opening authenticated WebSocket", auth.accountIdentifier(), auth.deviceId());
|
||||
@@ -121,18 +122,25 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
maybeAuthenticatedAccount.get(),
|
||||
maybeAuthenticatedDevice.get(),
|
||||
context.getClient(),
|
||||
scheduledExecutorService,
|
||||
messageDeliveryScheduler,
|
||||
clientReleaseManager,
|
||||
messageDeliveryLoopMonitor,
|
||||
experimentEnrollmentManager);
|
||||
|
||||
context.addWebsocketClosedListener((closingContext, statusCode, reason) -> {
|
||||
disconnectionRequestManager.addListener(maybeAuthenticatedAccount.get().getIdentifier(IdentityType.ACI),
|
||||
maybeAuthenticatedDevice.get().getId(),
|
||||
connection);
|
||||
|
||||
context.addWebsocketClosedListener((_, _, _) -> {
|
||||
disconnectionRequestManager.removeListener(maybeAuthenticatedAccount.get().getIdentifier(IdentityType.ACI),
|
||||
maybeAuthenticatedDevice.get().getId(),
|
||||
connection);
|
||||
|
||||
// We begin the shutdown process by removing this client's "presence," which means it will again begin to
|
||||
// receive push notifications for inbound messages. We should do this first because, at this point, the
|
||||
// connection has already closed and attempts to actually deliver a message via the connection will not succeed.
|
||||
// It's preferable to start sending push notifications as soon as possible.
|
||||
webSocketConnectionEventManager.handleClientDisconnected(auth.accountIdentifier(), auth.deviceId());
|
||||
redisMessageAvailabilityManager.handleClientDisconnected(auth.accountIdentifier(), auth.deviceId());
|
||||
|
||||
// Finally, stop trying to deliver messages and send a push notification if the connection is aware of any
|
||||
// undelivered messages.
|
||||
@@ -148,7 +156,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.
|
||||
webSocketConnectionEventManager.handleClientConnected(auth.accountIdentifier(), auth.deviceId(), connection);
|
||||
redisMessageAvailabilityManager.handleClientConnected(auth.accountIdentifier(), auth.deviceId(), connection);
|
||||
} catch (final Exception e) {
|
||||
log.warn("Failed to initialize websocket", e);
|
||||
context.getClient().close(1011, "Unexpected error initializing connection");
|
||||
|
||||
+67
-145
@@ -18,25 +18,22 @@ import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Random;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.concurrent.atomic.LongAdder;
|
||||
import javax.annotation.Nullable;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.eclipse.jetty.util.StaticException;
|
||||
import org.reactivestreams.Publisher;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestListener;
|
||||
import org.whispersystems.textsecuregcm.controllers.MessageController;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
@@ -47,10 +44,10 @@ 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.MessageAvailabilityListener;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventListener;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
@@ -64,8 +61,9 @@ import reactor.core.observability.micrometer.Micrometer;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.util.retry.Retry;
|
||||
|
||||
public class WebSocketConnection implements WebSocketConnectionEventListener {
|
||||
public class WebSocketConnection implements MessageAvailabilityListener, DisconnectionRequestListener {
|
||||
|
||||
private static final DistributionSummary messageTime = Metrics.summary(
|
||||
name(MessageController.class, "messageDeliveryDuration"));
|
||||
@@ -79,7 +77,6 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
|
||||
"initialQueueLength");
|
||||
private static final String INITIAL_QUEUE_DRAIN_TIMER_NAME = name(WebSocketConnection.class, "drainInitialQueue");
|
||||
private static final String SLOW_QUEUE_DRAIN_COUNTER_NAME = name(WebSocketConnection.class, "slowQueueDrain");
|
||||
private static final String QUEUE_DRAIN_RETRY_COUNTER_NAME = name(WebSocketConnection.class, "queueDrainRetry");
|
||||
private static final String DISPLACEMENT_COUNTER_NAME = name(WebSocketConnection.class, "displacement");
|
||||
private static final String NON_SUCCESS_RESPONSE_COUNTER_NAME = name(WebSocketConnection.class,
|
||||
"clientNonSuccessResponse");
|
||||
@@ -89,6 +86,7 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
|
||||
"sendMessageError");
|
||||
private static final String MESSAGE_AVAILABLE_COUNTER_NAME = name(WebSocketConnection.class, "messagesAvailable");
|
||||
private static final String MESSAGES_PERSISTED_COUNTER_NAME = name(WebSocketConnection.class, "messagesPersisted");
|
||||
private static final String SEND_MESSAGE_DURATION_TIMER_NAME = name(WebSocketConnection.class, "sendMessageDuration");
|
||||
|
||||
private static final String PRESENCE_MANAGER_TAG = "presenceManager";
|
||||
private static final String STATUS_CODE_TAG = "status";
|
||||
@@ -104,13 +102,6 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
|
||||
@VisibleForTesting
|
||||
static final int MESSAGE_SENDER_MAX_CONCURRENCY = 256;
|
||||
|
||||
@VisibleForTesting
|
||||
static final int MAX_CONSECUTIVE_RETRIES = 5;
|
||||
private static final long RETRY_DELAY_MILLIS = 1_000;
|
||||
private static final int RETRY_DELAY_JITTER_MILLIS = 500;
|
||||
|
||||
private static final int DEFAULT_SEND_FUTURES_TIMEOUT_MILLIS = 5 * 60 * 1000;
|
||||
|
||||
private static final Duration CLOSE_WITH_PENDING_MESSAGES_NOTIFICATION_DELAY = Duration.ofMinutes(1);
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(WebSocketConnection.class);
|
||||
@@ -127,21 +118,14 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
|
||||
private final Device authenticatedDevice;
|
||||
private final WebSocketClient client;
|
||||
|
||||
private final int sendFuturesTimeoutMillis;
|
||||
|
||||
private final ScheduledExecutorService scheduledExecutorService;
|
||||
|
||||
private final Semaphore processStoredMessagesSemaphore = new Semaphore(1);
|
||||
private final AtomicReference<StoredMessageState> storedMessageState = new AtomicReference<>(
|
||||
StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE);
|
||||
private final AtomicBoolean sentInitialQueueEmptyMessage = new AtomicBoolean(false);
|
||||
private final LongAdder sentMessageCounter = new LongAdder();
|
||||
private final AtomicLong queueDrainStartTime = new AtomicLong();
|
||||
private final AtomicInteger consecutiveRetries = new AtomicInteger();
|
||||
private final AtomicReference<ScheduledFuture<?>> retryFuture = new AtomicReference<>();
|
||||
private final AtomicReference<Disposable> messageSubscription = new AtomicReference<>();
|
||||
|
||||
private final Random random = new Random();
|
||||
private final Scheduler messageDeliveryScheduler;
|
||||
|
||||
private final ClientReleaseManager clientReleaseManager;
|
||||
@@ -152,50 +136,18 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
|
||||
PERSISTED_NEW_MESSAGES_AVAILABLE
|
||||
}
|
||||
|
||||
public WebSocketConnection(ReceiptSender receiptSender,
|
||||
MessagesManager messagesManager,
|
||||
MessageMetrics messageMetrics,
|
||||
PushNotificationManager pushNotificationManager,
|
||||
PushNotificationScheduler pushNotificationScheduler,
|
||||
Account authenticatedAccount,
|
||||
Device authenticatedDevice,
|
||||
WebSocketClient client,
|
||||
ScheduledExecutorService scheduledExecutorService,
|
||||
Scheduler messageDeliveryScheduler,
|
||||
ClientReleaseManager clientReleaseManager,
|
||||
MessageDeliveryLoopMonitor messageDeliveryLoopMonitor,
|
||||
ExperimentEnrollmentManager experimentEnrollmentManager) {
|
||||
|
||||
this(receiptSender,
|
||||
messagesManager,
|
||||
messageMetrics,
|
||||
pushNotificationManager,
|
||||
pushNotificationScheduler,
|
||||
authenticatedAccount,
|
||||
authenticatedDevice,
|
||||
client,
|
||||
DEFAULT_SEND_FUTURES_TIMEOUT_MILLIS,
|
||||
scheduledExecutorService,
|
||||
messageDeliveryScheduler,
|
||||
clientReleaseManager,
|
||||
messageDeliveryLoopMonitor, experimentEnrollmentManager);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
WebSocketConnection(ReceiptSender receiptSender,
|
||||
MessagesManager messagesManager,
|
||||
MessageMetrics messageMetrics,
|
||||
PushNotificationManager pushNotificationManager,
|
||||
PushNotificationScheduler pushNotificationScheduler,
|
||||
Account authenticatedAccount,
|
||||
Device authenticatedDevice,
|
||||
WebSocketClient client,
|
||||
int sendFuturesTimeoutMillis,
|
||||
ScheduledExecutorService scheduledExecutorService,
|
||||
Scheduler messageDeliveryScheduler,
|
||||
ClientReleaseManager clientReleaseManager,
|
||||
MessageDeliveryLoopMonitor messageDeliveryLoopMonitor,
|
||||
ExperimentEnrollmentManager experimentEnrollmentManager) {
|
||||
public WebSocketConnection(final ReceiptSender receiptSender,
|
||||
final MessagesManager messagesManager,
|
||||
final MessageMetrics messageMetrics,
|
||||
final PushNotificationManager pushNotificationManager,
|
||||
final PushNotificationScheduler pushNotificationScheduler,
|
||||
final Account authenticatedAccount,
|
||||
final Device authenticatedDevice,
|
||||
final WebSocketClient client,
|
||||
final Scheduler messageDeliveryScheduler,
|
||||
final ClientReleaseManager clientReleaseManager,
|
||||
final MessageDeliveryLoopMonitor messageDeliveryLoopMonitor,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager) {
|
||||
|
||||
this.receiptSender = receiptSender;
|
||||
this.messagesManager = messagesManager;
|
||||
@@ -205,8 +157,6 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
|
||||
this.authenticatedAccount = authenticatedAccount;
|
||||
this.authenticatedDevice = authenticatedDevice;
|
||||
this.client = client;
|
||||
this.sendFuturesTimeoutMillis = sendFuturesTimeoutMillis;
|
||||
this.scheduledExecutorService = scheduledExecutorService;
|
||||
this.messageDeliveryScheduler = messageDeliveryScheduler;
|
||||
this.clientReleaseManager = clientReleaseManager;
|
||||
this.messageDeliveryLoopMonitor = messageDeliveryLoopMonitor;
|
||||
@@ -220,12 +170,6 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
final ScheduledFuture<?> future = retryFuture.get();
|
||||
|
||||
if (future != null) {
|
||||
future.cancel(false);
|
||||
}
|
||||
|
||||
final Disposable subscription = messageSubscription.get();
|
||||
if (subscription != null) {
|
||||
subscription.dispose();
|
||||
@@ -249,6 +193,8 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
|
||||
bytesSentCounter.increment(body.map(bytes -> bytes.length).orElse(0));
|
||||
messageMetrics.measureAccountEnvelopeUuidMismatches(authenticatedAccount, message);
|
||||
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
// X-Signal-Key: false must be sent until Android stops assuming it missing means true
|
||||
return client.sendRequest("PUT", "/api/v1/message",
|
||||
List.of(HeaderUtils.X_SIGNAL_KEY + ": false", HeaderUtils.getTimestampHeader()), body)
|
||||
@@ -294,7 +240,11 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
|
||||
}
|
||||
|
||||
return result;
|
||||
});
|
||||
})
|
||||
.thenRun(() -> sample.stop(Timer.builder(SEND_MESSAGE_DURATION_TIMER_NAME)
|
||||
.publishPercentileHistogram(true)
|
||||
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(client.getUserAgent())))
|
||||
.register(Metrics.globalRegistry)));
|
||||
}
|
||||
|
||||
public static void recordMessageDeliveryDuration(long timestamp, Device messageDestinationDevice) {
|
||||
@@ -341,7 +291,6 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
|
||||
}
|
||||
|
||||
// Cleared the queue! Send a queue empty message if we need to
|
||||
consecutiveRetries.set(0);
|
||||
if (sentInitialQueueEmptyMessage.compareAndSet(false, true)) {
|
||||
final Tags tags = Tags.of(UserAgentTagUtil.getPlatformTag(client.getUserAgent()));
|
||||
final long drainDuration = System.currentTimeMillis() - queueDrainStartTime.get();
|
||||
@@ -361,44 +310,25 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
|
||||
}
|
||||
})
|
||||
// Potentially kick off more work, must happen after we release the semaphore
|
||||
.whenComplete((ignored, cause) -> processMoreIfRequested(cause));
|
||||
.whenComplete((ignored, cause) -> {
|
||||
if (cause != null) {
|
||||
if (!client.isOpen()) {
|
||||
logger.debug("Client disconnected before queue cleared");
|
||||
return;
|
||||
}
|
||||
|
||||
client.close(1011, "Failed to retrieve messages");
|
||||
return;
|
||||
}
|
||||
|
||||
// Success, but check if more messages came in while we were processing
|
||||
if (storedMessageState.get() != StoredMessageState.EMPTY) {
|
||||
processStoredMessages();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* After processing messages, kick off another processing job if more messages came in or if there was an error
|
||||
*
|
||||
* @param cause An error that was encountered when processing the message queue, if there was one
|
||||
*/
|
||||
private void processMoreIfRequested(final @Nullable Throwable cause) {
|
||||
if (cause == null) {
|
||||
// Success, but check if more messages came in while we were processing
|
||||
if (storedMessageState.get() != StoredMessageState.EMPTY) {
|
||||
processStoredMessages();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!client.isOpen()) {
|
||||
logger.debug("Client disconnected before queue cleared");
|
||||
return;
|
||||
}
|
||||
|
||||
if (consecutiveRetries.incrementAndGet() > MAX_CONSECUTIVE_RETRIES) {
|
||||
logger.warn("Max consecutive retries exceeded", cause);
|
||||
client.close(1011, "Failed to retrieve messages");
|
||||
return;
|
||||
}
|
||||
|
||||
logger.debug("Failed to clear queue", cause);
|
||||
final Tags tags = Tags.of(UserAgentTagUtil.getPlatformTag(client.getUserAgent()));
|
||||
|
||||
Metrics.counter(QUEUE_DRAIN_RETRY_COUNTER_NAME, tags).increment();
|
||||
|
||||
final long delay = RETRY_DELAY_MILLIS + random.nextInt(RETRY_DELAY_JITTER_MILLIS);
|
||||
retryFuture.set(scheduledExecutorService.schedule(this::processStoredMessages, delay, TimeUnit.MILLISECONDS));
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> sendMessages(final boolean cachedMessagesOnly) {
|
||||
final CompletableFuture<Void> queueCleared = new CompletableFuture<>();
|
||||
|
||||
@@ -406,7 +336,6 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
|
||||
messagesManager.getMessagesForDeviceReactive(authenticatedAccount.getIdentifier(IdentityType.ACI), authenticatedDevice, cachedMessagesOnly);
|
||||
|
||||
final AtomicBoolean hasSentFirstMessage = new AtomicBoolean();
|
||||
final AtomicBoolean hasErrored = new AtomicBoolean();
|
||||
|
||||
final Disposable subscription = Flux.from(messages)
|
||||
.name(SEND_MESSAGES_FLUX_NAME)
|
||||
@@ -421,20 +350,10 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
|
||||
"websocket");
|
||||
}
|
||||
})
|
||||
.flatMapSequential(envelope ->
|
||||
Mono.fromFuture(() -> sendMessage(envelope)
|
||||
.orTimeout(sendFuturesTimeoutMillis, TimeUnit.MILLISECONDS))
|
||||
.onErrorResume(
|
||||
// let the first error pass through to terminate the subscription
|
||||
e -> {
|
||||
final boolean firstError = !hasErrored.getAndSet(true);
|
||||
measureSendMessageErrors(e, firstError);
|
||||
|
||||
return !firstError;
|
||||
},
|
||||
// otherwise just emit nothing
|
||||
e -> Mono.empty()
|
||||
), MESSAGE_SENDER_MAX_CONCURRENCY)
|
||||
.flatMapSequential(envelope -> Mono.fromFuture(() -> sendMessage(envelope))
|
||||
.retryWhen(Retry.backoff(4, Duration.ofSeconds(1)).filter(throwable -> !isConnectionClosedException(throwable))),
|
||||
MESSAGE_SENDER_MAX_CONCURRENCY)
|
||||
.doOnError(this::measureSendMessageErrors)
|
||||
.subscribeOn(messageDeliveryScheduler)
|
||||
.subscribe(
|
||||
// no additional consumer of values - it is Flux<Void> by now
|
||||
@@ -449,18 +368,15 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
|
||||
return queueCleared;
|
||||
}
|
||||
|
||||
private void measureSendMessageErrors(final Throwable e, final boolean terminal) {
|
||||
private void measureSendMessageErrors(final Throwable e) {
|
||||
final String errorType;
|
||||
|
||||
if (e instanceof TimeoutException) {
|
||||
errorType = "timeout";
|
||||
} else if (e instanceof java.nio.channels.ClosedChannelException ||
|
||||
e == WebSocketResourceProvider.CONNECTION_CLOSED_EXCEPTION ||
|
||||
e instanceof org.eclipse.jetty.io.EofException ||
|
||||
(e instanceof StaticException staticException && "Closed".equals(staticException.getMessage()))) {
|
||||
} else if (isConnectionClosedException(e)) {
|
||||
errorType = "connectionClosed";
|
||||
} else {
|
||||
logger.warn(terminal ? "Send message failure terminated stream" : "Send message failed", e);
|
||||
logger.warn("Send message failed", e);
|
||||
errorType = "other";
|
||||
}
|
||||
|
||||
@@ -471,6 +387,13 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
|
||||
.increment();
|
||||
}
|
||||
|
||||
private static boolean isConnectionClosedException(final Throwable throwable) {
|
||||
return throwable instanceof java.nio.channels.ClosedChannelException ||
|
||||
throwable == WebSocketResourceProvider.CONNECTION_CLOSED_EXCEPTION ||
|
||||
throwable instanceof org.eclipse.jetty.io.EofException ||
|
||||
(throwable instanceof StaticException staticException && "Closed".equals(staticException.getMessage()));
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> sendMessage(Envelope envelope) {
|
||||
final UUID messageGuid = UUID.fromString(envelope.getServerGuid());
|
||||
|
||||
@@ -506,24 +429,23 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleConnectionDisplaced(final boolean connectedElsewhere) {
|
||||
public void handleConflictingMessageReader() {
|
||||
closeConnection(4409, "Connected elsewhere");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleDisconnectionRequest() {
|
||||
closeConnection(4401, "Reauthentication required");
|
||||
}
|
||||
|
||||
private void closeConnection(final int code, final String message) {
|
||||
final Tags tags = Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(client.getUserAgent()),
|
||||
Tag.of("connectedElsewhere", String.valueOf(connectedElsewhere)));
|
||||
// TODO We should probably just use the status code directly
|
||||
Tag.of("connectedElsewhere", String.valueOf(code == 4409)));
|
||||
|
||||
Metrics.counter(DISPLACEMENT_COUNTER_NAME, tags).increment();
|
||||
|
||||
final int code;
|
||||
final String message;
|
||||
|
||||
if (connectedElsewhere) {
|
||||
code = 4409;
|
||||
message = "Connected elsewhere";
|
||||
} else {
|
||||
code = 4401;
|
||||
message = "Reauthentication required";
|
||||
}
|
||||
|
||||
client.close(code, message);
|
||||
}
|
||||
|
||||
|
||||
+13
-9
@@ -30,19 +30,20 @@ import org.whispersystems.textsecuregcm.backup.BackupManager;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupsDb;
|
||||
import org.whispersystems.textsecuregcm.backup.Cdn3BackupCredentialGenerator;
|
||||
import org.whispersystems.textsecuregcm.backup.Cdn3RemoteStorageManager;
|
||||
import org.whispersystems.textsecuregcm.backup.SecureValueRecoveryBCredentialsGeneratorFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery2Controller;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureValueRecoveryBController;
|
||||
import org.whispersystems.textsecuregcm.experiment.PushNotificationExperimentSamples;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.GrpcClientConnectionManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.MicrometerAwsSdkMetricPublisher;
|
||||
import org.whispersystems.textsecuregcm.push.APNSender;
|
||||
import org.whispersystems.textsecuregcm.push.FcmSender;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
@@ -173,8 +174,8 @@ record CommandDependencies(
|
||||
configuration.getSecureStorageServiceConfiguration());
|
||||
ExternalServiceCredentialsGenerator secureValueRecovery2CredentialsGenerator = SecureValueRecovery2Controller.credentialsGenerator(
|
||||
configuration.getSvr2Configuration());
|
||||
ExternalServiceCredentialsGenerator secureValueRecoveryBCredentialsGenerator = SecureValueRecoveryBController.credentialsGenerator(
|
||||
configuration.getSvrbConfiguration());
|
||||
ExternalServiceCredentialsGenerator secureValueRecoveryBCredentialsGenerator =
|
||||
SecureValueRecoveryBCredentialsGeneratorFactory.svrbCredentialsGenerator(configuration.getSvrbConfiguration());
|
||||
|
||||
final ExecutorService awsSdkMetricsExecutor = environment.lifecycle()
|
||||
.virtualExecutorService(MetricRegistry.name(WhisperServerService.class, "awsSdkMetrics-%d"));
|
||||
@@ -254,7 +255,8 @@ record CommandDependencies(
|
||||
() -> dynamicConfigurationManager.getConfiguration().getSvrbStatusCodesToIgnoreForAccountDeletion());
|
||||
SecureStorageClient secureStorageClient = new SecureStorageClient(storageCredentialsGenerator,
|
||||
storageServiceExecutor, storageServiceRetryExecutor, configuration.getSecureStorageServiceConfiguration());
|
||||
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient, disconnectionRequestListenerExecutor);
|
||||
GrpcClientConnectionManager grpcClientConnectionManager = new GrpcClientConnectionManager();
|
||||
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient, grpcClientConnectionManager, disconnectionRequestListenerExecutor);
|
||||
MessagesCache messagesCache = new MessagesCache(messagesCluster,
|
||||
messageDeliveryScheduler, messageDeletionExecutor, Clock.systemUTC());
|
||||
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster, asyncCdnS3Client,
|
||||
@@ -274,7 +276,7 @@ record CommandDependencies(
|
||||
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
pubsubClient, accountLockManager, keys, messagesManager, profilesManager,
|
||||
secureStorageClient, secureValueRecovery2Client, secureValueRecoveryBClient, disconnectionRequestManager,
|
||||
secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
|
||||
registrationRecoveryPasswordsManager, clientPublicKeysManager, accountLockExecutor, messagePollExecutor,
|
||||
clock, configuration.getLinkDeviceSecretConfiguration().secret().value(), dynamicConfigurationManager);
|
||||
RateLimiters rateLimiters = RateLimiters.create(dynamicConfigurationManager, rateLimitersCluster);
|
||||
@@ -297,6 +299,8 @@ record CommandDependencies(
|
||||
remoteStorageHttpExecutor,
|
||||
remoteStorageRetryExecutor,
|
||||
configuration.getCdn3StorageManagerConfiguration()),
|
||||
secureValueRecoveryBCredentialsGenerator,
|
||||
secureValueRecoveryBClient,
|
||||
clock);
|
||||
|
||||
final IssuedReceiptsManager issuedReceiptsManager = new IssuedReceiptsManager(
|
||||
@@ -317,15 +321,15 @@ record CommandDependencies(
|
||||
configuration.getDynamoDbTables().getPushNotificationExperimentSamples().getTableName(),
|
||||
Clock.systemUTC());
|
||||
|
||||
WebSocketConnectionEventManager webSocketConnectionEventManager =
|
||||
new WebSocketConnectionEventManager(accountsManager, pushNotificationManager, messagesCluster, clientEventExecutor, asyncOperationQueueingExecutor);
|
||||
RedisMessageAvailabilityManager redisMessageAvailabilityManager =
|
||||
new RedisMessageAvailabilityManager(messagesCluster, clientEventExecutor, asyncOperationQueueingExecutor);
|
||||
|
||||
final DynamoDbRecoveryManager dynamoDbRecoveryManager =
|
||||
new DynamoDbRecoveryManager(accounts, phoneNumberIdentifiers);
|
||||
|
||||
environment.lifecycle().manage(apnSender);
|
||||
environment.lifecycle().manage(disconnectionRequestManager);
|
||||
environment.lifecycle().manage(webSocketConnectionEventManager);
|
||||
environment.lifecycle().manage(redisMessageAvailabilityManager);
|
||||
environment.lifecycle().manage(new ManagedAwsCrt());
|
||||
|
||||
return new CommandDependencies(
|
||||
|
||||
+51
-27
@@ -11,11 +11,17 @@ import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.EncryptDeviceCreationTimestampUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.core.publisher.Mono;
|
||||
@@ -26,10 +32,11 @@ public class EncryptDeviceCreationTimestampCommand extends AbstractSinglePassCra
|
||||
@VisibleForTesting
|
||||
static final String DRY_RUN_ARGUMENT = "dry-run";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String BUFFER_ARGUMENT = "buffer";
|
||||
|
||||
private static final int MAX_CONCURRENCY = 16;
|
||||
|
||||
private static final String ENCRYPTED_CREATION_TIMESTAMP_COUNTER_NAME =
|
||||
name(EncryptDeviceCreationTimestampCommand.class, "encryptedCreationTimestamp");
|
||||
private static final String PROCESSED_ACCOUNT_COUNTER_NAME =
|
||||
name(EncryptDeviceCreationTimestampCommand.class, "processedAccount");
|
||||
|
||||
@@ -49,40 +56,57 @@ public class EncryptDeviceCreationTimestampCommand extends AbstractSinglePassCra
|
||||
.required(false)
|
||||
.setDefault(true)
|
||||
.help("If true, don't actually update device records");
|
||||
|
||||
subparser.addArgument("--buffer")
|
||||
.type(Integer.class)
|
||||
.dest(BUFFER_ARGUMENT)
|
||||
.setDefault(16_384)
|
||||
.help("Records to buffer");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void crawlAccounts(final Flux<Account> accounts) {
|
||||
final boolean isDryRun = getNamespace().getBoolean(DRY_RUN_ARGUMENT);
|
||||
final Counter encryptedTimestampCounter =
|
||||
Metrics.counter(ENCRYPTED_CREATION_TIMESTAMP_COUNTER_NAME, "dryRun", String.valueOf(isDryRun));
|
||||
final int bufferSize = getNamespace().getInt(BUFFER_ARGUMENT);
|
||||
|
||||
final Counter processedAccountCounter =
|
||||
Metrics.counter(PROCESSED_ACCOUNT_COUNTER_NAME, "dryRun", String.valueOf(isDryRun));
|
||||
accounts
|
||||
.flatMap(account ->
|
||||
Flux.fromIterable(account.getDevices())
|
||||
.flatMap(device -> {
|
||||
final byte[] createdAtCiphertext = EncryptDeviceCreationTimestampUtil.encrypt(
|
||||
device.getCreated(), account.getIdentityKey(IdentityType.ACI),
|
||||
device.getId(), device.getRegistrationId(IdentityType.ACI));
|
||||
|
||||
final Mono<Void> encryptTimestampMono = isDryRun
|
||||
? Mono.empty()
|
||||
: Mono.fromFuture(() -> getCommandDependencies().accountsManager().updateDeviceAsync(
|
||||
account, device.getId(), d -> d.setCreatedAtCiphertext(createdAtCiphertext))
|
||||
.thenRun(Util.NOOP));
|
||||
return encryptTimestampMono
|
||||
.doOnSuccess(_ -> encryptedTimestampCounter.increment())
|
||||
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1)).maxBackoff(Duration.ofSeconds(4)))
|
||||
.onErrorResume(throwable -> {
|
||||
log.warn("Failed to encrypt creation timestamp on device {}, account {}", device.getId(), account.getUuid(), throwable);
|
||||
return Mono.empty();
|
||||
});
|
||||
}, MAX_CONCURRENCY)
|
||||
.then()
|
||||
.doOnSuccess(_ -> processedAccountCounter.increment()),
|
||||
MAX_CONCURRENCY)
|
||||
accounts
|
||||
// We've partially processed enough accounts now that this should speed up the crawler
|
||||
.filter(a -> a.getDevices().stream().anyMatch(d -> d.getCreatedAtCiphertext() == null || d.getCreatedAtCiphertext().length == 0))
|
||||
.buffer(bufferSize)
|
||||
.map(source -> {
|
||||
final List<Account> shuffled = new ArrayList<>(source);
|
||||
Collections.shuffle(shuffled);
|
||||
return shuffled;
|
||||
})
|
||||
.limitRate(2)
|
||||
.flatMapIterable(Function.identity())
|
||||
.flatMap(account -> {
|
||||
Mono<Void> encryptTimestampMono = isDryRun
|
||||
? Mono.empty()
|
||||
: Mono.fromFuture(
|
||||
() -> getCommandDependencies().accountsManager().updateAsync(account, a -> {
|
||||
final IdentityKey aciIdentityKey = account.getIdentityKey(IdentityType.ACI);
|
||||
for (final Device device : a.getDevices()) {
|
||||
final byte[] createdAtCiphertext = EncryptDeviceCreationTimestampUtil.encrypt(
|
||||
device.getCreated(), aciIdentityKey,
|
||||
device.getId(), device.getRegistrationId(IdentityType.ACI));
|
||||
device.setCreatedAtCiphertext(createdAtCiphertext);
|
||||
}
|
||||
}).thenRun(Util.NOOP));
|
||||
return encryptTimestampMono
|
||||
.doOnSuccess(_ -> processedAccountCounter.increment())
|
||||
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1)).maxBackoff(Duration.ofSeconds(4)))
|
||||
.onErrorResume(throwable -> {
|
||||
log.warn("Failed to encrypt creation timestamps on account {}", account.getUuid(), throwable);
|
||||
return Mono.empty();
|
||||
});
|
||||
}, MAX_CONCURRENCY)
|
||||
.then()
|
||||
.block();
|
||||
|
||||
log.info("Finished encrypting device timestamps");
|
||||
}
|
||||
}
|
||||
@@ -188,6 +188,11 @@ service BackupsAnonymous {
|
||||
*/
|
||||
rpc GetCdnCredentials(GetCdnCredentialsRequest) returns (GetCdnCredentialsResponse) {}
|
||||
|
||||
/**
|
||||
* Retrieve credentials used to interact with the SecureValueRecoveryB service
|
||||
*/
|
||||
rpc GetSvrBCredentials(GetSvrBCredentialsRequest) returns (GetSvrBCredentialsResponse) {}
|
||||
|
||||
/**
|
||||
* Retrieve information about the currently stored backup
|
||||
*/
|
||||
@@ -291,6 +296,21 @@ message GetCdnCredentialsResponse {
|
||||
map<string, string> headers = 1;
|
||||
}
|
||||
|
||||
message GetSvrBCredentialsRequest {
|
||||
SignedPresentation signed_presentation = 1;
|
||||
}
|
||||
message GetSvrBCredentialsResponse {
|
||||
/**
|
||||
* A username that can be presented to authenticate with SVRB
|
||||
*/
|
||||
string username = 1;
|
||||
|
||||
/**
|
||||
* A password that can be presented to authenticate with SVRB
|
||||
*/
|
||||
string password = 2;
|
||||
}
|
||||
|
||||
message GetBackupInfoRequest {
|
||||
SignedPresentation signed_presentation = 1;
|
||||
}
|
||||
|
||||
@@ -53,7 +53,6 @@ enum ExternalServiceType {
|
||||
EXTERNAL_SERVICE_TYPE_PAYMENTS = 2;
|
||||
EXTERNAL_SERVICE_TYPE_STORAGE = 3;
|
||||
EXTERNAL_SERVICE_TYPE_SVR = 4;
|
||||
EXTERNAL_SERVICE_TYPE_SVRB = 5;
|
||||
}
|
||||
|
||||
message GetExternalServiceCredentialsRequest {
|
||||
|
||||
@@ -195,8 +195,7 @@ message GetPreKeysResponse {
|
||||
|
||||
/**
|
||||
* A one-time KEM pre-key (or a last-resort KEM pre-key) for the targeted
|
||||
* account/device/identity. May not be set if the targeted device has not
|
||||
* yet uploaded any KEM pre-keys.
|
||||
* account/device/identity.
|
||||
*/
|
||||
common.KemSignedPreKey kem_one_time_pre_key = 3;
|
||||
}
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
-- keys: lock_key
|
||||
-- argv: lock_value
|
||||
|
||||
if redis.call("GET", KEYS[1]) == ARGV[1] then
|
||||
return redis.call("DEL", KEYS[1])
|
||||
else
|
||||
return 0
|
||||
end
|
||||
@@ -1,9 +0,0 @@
|
||||
local presenceKey = KEYS[1]
|
||||
local presenceUuid = ARGV[1]
|
||||
|
||||
if redis.call("GET", presenceKey) == presenceUuid then
|
||||
redis.call("DEL", presenceKey)
|
||||
return true
|
||||
end
|
||||
|
||||
return false
|
||||
@@ -1,7 +0,0 @@
|
||||
local presenceKey = KEYS[1]
|
||||
local presenceUuid = ARGV[1]
|
||||
local expireSeconds = ARGV[2]
|
||||
|
||||
if redis.call("GET", presenceKey) == presenceUuid then
|
||||
redis.call("EXPIRE", presenceKey, expireSeconds)
|
||||
end
|
||||
@@ -27,6 +27,7 @@ import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.configuration.OpenTelemetryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.metrics.NoopAwsSdkMetricPublisher;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema;
|
||||
|
||||
+95
-46
@@ -6,58 +6,42 @@
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.timeout;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.GrpcClientConnectionManager;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisServerExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
|
||||
@Timeout(value = 5, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
|
||||
class DisconnectionRequestManagerTest {
|
||||
|
||||
private GrpcClientConnectionManager grpcClientConnectionManager;
|
||||
private DisconnectionRequestManager disconnectionRequestManager;
|
||||
|
||||
@RegisterExtension
|
||||
static final RedisServerExtension REDIS_EXTENSION = RedisServerExtension.builder().build();
|
||||
|
||||
private static class DisconnectionRequestTestListener implements DisconnectionRequestListener {
|
||||
|
||||
private final CountDownLatch requestLatch = new CountDownLatch(1);
|
||||
|
||||
private UUID accountIdentifier;
|
||||
private Collection<Byte> deviceIds;
|
||||
|
||||
@Override
|
||||
public void handleDisconnectionRequest(final UUID accountIdentifier, final Collection<Byte> deviceIds) {
|
||||
this.accountIdentifier = accountIdentifier;
|
||||
this.deviceIds = deviceIds;
|
||||
|
||||
requestLatch.countDown();
|
||||
}
|
||||
|
||||
public UUID getAccountIdentifier() {
|
||||
return accountIdentifier;
|
||||
}
|
||||
|
||||
public Collection<Byte> getDeviceIds() {
|
||||
return deviceIds;
|
||||
}
|
||||
|
||||
public void waitForRequest() throws InterruptedException {
|
||||
requestLatch.await();
|
||||
}
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
disconnectionRequestManager = new DisconnectionRequestManager(REDIS_EXTENSION.getRedisClient(), Runnable::run);
|
||||
grpcClientConnectionManager = mock(GrpcClientConnectionManager.class);
|
||||
|
||||
disconnectionRequestManager =
|
||||
new DisconnectionRequestManager(REDIS_EXTENSION.getRedisClient(), grpcClientConnectionManager, Runnable::run);
|
||||
|
||||
disconnectionRequestManager.start();
|
||||
}
|
||||
|
||||
@@ -67,33 +51,98 @@ class DisconnectionRequestManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void requestDisconnection() throws InterruptedException {
|
||||
void addRemoveListener() {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
final List<Byte> deviceIds = List.of(Device.PRIMARY_ID, (byte) (Device.PRIMARY_ID + 1));
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
|
||||
final DisconnectionRequestTestListener listener = new DisconnectionRequestTestListener();
|
||||
final DisconnectionRequestListener firstListener = mock(DisconnectionRequestListener.class);
|
||||
final DisconnectionRequestListener secondListener = mock(DisconnectionRequestListener.class);
|
||||
|
||||
disconnectionRequestManager.addListener(listener);
|
||||
disconnectionRequestManager.requestDisconnection(accountIdentifier, deviceIds).toCompletableFuture().join();
|
||||
assertTrue(disconnectionRequestManager.getListeners(accountIdentifier, deviceId).isEmpty());
|
||||
|
||||
listener.waitForRequest();
|
||||
disconnectionRequestManager.addListener(accountIdentifier, deviceId, firstListener);
|
||||
|
||||
assertEquals(accountIdentifier, listener.getAccountIdentifier());
|
||||
assertEquals(deviceIds, listener.getDeviceIds());
|
||||
assertEquals(List.of(firstListener), disconnectionRequestManager.getListeners(accountIdentifier, deviceId));
|
||||
|
||||
disconnectionRequestManager.addListener(accountIdentifier, deviceId, secondListener);
|
||||
|
||||
assertEquals(List.of(firstListener, secondListener),
|
||||
disconnectionRequestManager.getListeners(accountIdentifier, deviceId));
|
||||
|
||||
disconnectionRequestManager.removeListener(accountIdentifier, deviceId, mock(DisconnectionRequestListener.class));
|
||||
|
||||
assertEquals(List.of(firstListener, secondListener),
|
||||
disconnectionRequestManager.getListeners(accountIdentifier, deviceId));
|
||||
|
||||
disconnectionRequestManager.removeListener(accountIdentifier, deviceId, firstListener);
|
||||
|
||||
assertEquals(List.of(secondListener), disconnectionRequestManager.getListeners(accountIdentifier, deviceId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void requestDisconnectionAllDevices() throws InterruptedException {
|
||||
void requestDisconnection() {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
final byte primaryDeviceId = Device.PRIMARY_ID;
|
||||
final byte linkedDeviceId = primaryDeviceId + 1;
|
||||
|
||||
final DisconnectionRequestTestListener listener = new DisconnectionRequestTestListener();
|
||||
final UUID otherAccountIdentifier = UUID.randomUUID();
|
||||
final byte otherDeviceId = linkedDeviceId + 1;
|
||||
|
||||
disconnectionRequestManager.addListener(listener);
|
||||
disconnectionRequestManager.requestDisconnection(accountIdentifier).toCompletableFuture().join();
|
||||
final List<Byte> deviceIds = List.of(primaryDeviceId, linkedDeviceId);
|
||||
|
||||
listener.waitForRequest();
|
||||
final DisconnectionRequestListener primaryDeviceListener = mock(DisconnectionRequestListener.class);
|
||||
final DisconnectionRequestListener linkedDeviceListener = mock(DisconnectionRequestListener.class);
|
||||
|
||||
assertEquals(accountIdentifier, listener.getAccountIdentifier());
|
||||
assertEquals(Device.ALL_POSSIBLE_DEVICE_IDS, listener.getDeviceIds());
|
||||
disconnectionRequestManager.addListener(accountIdentifier, primaryDeviceId, primaryDeviceListener);
|
||||
disconnectionRequestManager.addListener(accountIdentifier, linkedDeviceId, linkedDeviceListener);
|
||||
|
||||
disconnectionRequestManager.requestDisconnection(accountIdentifier, deviceIds).toCompletableFuture().join();
|
||||
|
||||
verify(primaryDeviceListener, timeout(1_000)).handleDisconnectionRequest();
|
||||
verify(linkedDeviceListener, timeout(1_000)).handleDisconnectionRequest();
|
||||
verify(grpcClientConnectionManager, timeout(1_000))
|
||||
.closeConnection(new AuthenticatedDevice(accountIdentifier, primaryDeviceId));
|
||||
|
||||
verify(grpcClientConnectionManager, timeout(1_000))
|
||||
.closeConnection(new AuthenticatedDevice(accountIdentifier, linkedDeviceId));
|
||||
|
||||
disconnectionRequestManager.requestDisconnection(otherAccountIdentifier, List.of(otherDeviceId));
|
||||
|
||||
verify(grpcClientConnectionManager, timeout(1_000))
|
||||
.closeConnection(new AuthenticatedDevice(otherAccountIdentifier, otherDeviceId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void requestDisconnectionAllDevices() {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
final byte primaryDeviceId = Device.PRIMARY_ID;
|
||||
final byte linkedDeviceId = primaryDeviceId + 1;
|
||||
|
||||
final Device primaryDevice = mock(Device.class);
|
||||
when(primaryDevice.getId()).thenReturn(primaryDeviceId);
|
||||
|
||||
final Device linkedDevice = mock(Device.class);
|
||||
when(linkedDevice.getId()).thenReturn(linkedDeviceId);
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
|
||||
when(account.getDevices()).thenReturn(List.of(primaryDevice, linkedDevice));
|
||||
|
||||
final DisconnectionRequestListener primaryDeviceListener = mock(DisconnectionRequestListener.class);
|
||||
final DisconnectionRequestListener linkedDeviceListener = mock(DisconnectionRequestListener.class);
|
||||
|
||||
disconnectionRequestManager.addListener(accountIdentifier, primaryDeviceId, primaryDeviceListener);
|
||||
disconnectionRequestManager.addListener(accountIdentifier, linkedDeviceId, linkedDeviceListener);
|
||||
|
||||
disconnectionRequestManager.requestDisconnection(account).toCompletableFuture().join();
|
||||
|
||||
verify(primaryDeviceListener, timeout(1_000)).handleDisconnectionRequest();
|
||||
verify(linkedDeviceListener, timeout(1_000)).handleDisconnectionRequest();
|
||||
|
||||
verify(grpcClientConnectionManager, timeout(1_000))
|
||||
.closeConnection(new AuthenticatedDevice(accountIdentifier, primaryDeviceId));
|
||||
|
||||
verify(grpcClientConnectionManager, timeout(1_000))
|
||||
.closeConnection(new AuthenticatedDevice(accountIdentifier, linkedDeviceId));
|
||||
}
|
||||
}
|
||||
+54
-3
@@ -20,6 +20,7 @@ import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.whispersystems.textsecuregcm.util.MockUtils.randomSecretBytes;
|
||||
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
@@ -36,6 +37,7 @@ import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -43,11 +45,8 @@ import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
@@ -71,9 +70,13 @@ import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
|
||||
import org.signal.libsignal.zkgroup.backups.BackupLevel;
|
||||
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureValueRecoveryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
@@ -107,6 +110,18 @@ public class BackupManagerTest {
|
||||
private final byte[] backupKey = TestRandomUtil.nextBytes(32);
|
||||
private final UUID aci = UUID.randomUUID();
|
||||
|
||||
|
||||
private static final SecureValueRecoveryConfiguration CFG = new SecureValueRecoveryConfiguration(
|
||||
"",
|
||||
randomSecretBytes(32),
|
||||
randomSecretBytes(32),
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
private final ExternalServiceCredentialsGenerator svrbCredentialGenerator =
|
||||
SecureValueRecoveryBCredentialsGeneratorFactory.svrbCredentialsGenerator(CFG, testClock);
|
||||
private final SecureValueRecoveryClient svrbClient = mock(SecureValueRecoveryClient.class);
|
||||
|
||||
private BackupManager backupManager;
|
||||
private BackupsDb backupsDb;
|
||||
|
||||
@@ -131,6 +146,8 @@ public class BackupManagerTest {
|
||||
tusAttachmentGenerator,
|
||||
tusCredentialGenerator,
|
||||
remoteStorageManager,
|
||||
svrbCredentialGenerator,
|
||||
svrbClient,
|
||||
testClock);
|
||||
}
|
||||
|
||||
@@ -697,9 +714,13 @@ public class BackupManagerTest {
|
||||
|
||||
testClock.pin(Instant.ofEpochSecond(10));
|
||||
|
||||
when(svrbClient.removeData(anyString())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
// Deleting should swap the backupDir for the user
|
||||
backupManager.deleteEntireBackup(original).join();
|
||||
verifyNoInteractions(remoteStorageManager);
|
||||
verify(svrbClient).removeData(HexFormat.of().formatHex(BackupsDb.hashedBackupId(original.backupId())));
|
||||
|
||||
final AuthenticatedBackupUser after = retrieveBackupUser(original.backupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID);
|
||||
assertThat(original.backupDir()).isNotEqualTo(after.backupDir());
|
||||
assertThat(original.mediaDir()).isNotEqualTo(after.mediaDir());
|
||||
@@ -959,11 +980,15 @@ public class BackupManagerTest {
|
||||
new RemoteStorageManager.ListResult.Entry("ghi", 1)), Optional.empty())));
|
||||
when(remoteStorageManager.delete(anyString())).thenReturn(CompletableFuture.completedFuture(1L));
|
||||
|
||||
when(svrbClient.removeData(anyString())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
backupManager.expireBackup(expiredBackup(expirationType, backupUser)).join();
|
||||
verify(remoteStorageManager, times(1)).list(anyString(), any(), anyLong());
|
||||
verify(remoteStorageManager, times(1)).delete(expectedPrefixToDelete + "abc");
|
||||
verify(remoteStorageManager, times(1)).delete(expectedPrefixToDelete + "def");
|
||||
verify(remoteStorageManager, times(1)).delete(expectedPrefixToDelete + "ghi");
|
||||
verify(svrbClient, times(expirationType == ExpiredBackup.ExpirationType.ALL ? 1 : 0))
|
||||
.removeData(HexFormat.of().formatHex(BackupsDb.hashedBackupId(backupUser.backupId())));
|
||||
verifyNoMoreInteractions(remoteStorageManager);
|
||||
|
||||
final BackupsDb.TimestampedUsageInfo usage = backupsDb.getMediaUsage(backupUser).join();
|
||||
@@ -1020,6 +1045,32 @@ public class BackupManagerTest {
|
||||
verifyNoMoreInteractions(remoteStorageManager);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(BackupLevel.class)
|
||||
void svrbAuthValid(BackupLevel backupLevel) {
|
||||
testClock.pin(Instant.ofEpochSecond(123));
|
||||
final AuthenticatedBackupUser backupUser =
|
||||
backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MESSAGES, backupLevel);
|
||||
final ExternalServiceCredentials creds = backupManager.generateSvrbAuth(backupUser);
|
||||
|
||||
assertThat(HexFormat.of().parseHex(creds.username())).hasSize(16);
|
||||
final String[] split = creds.password().split(":", 2);
|
||||
assertThat(Long.parseLong(split[0])).isEqualTo(123);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(BackupLevel.class)
|
||||
void svrbAuthInvalid(BackupLevel backupLevel) {
|
||||
// Can't use MEDIA for svrb auth
|
||||
final AuthenticatedBackupUser backupUser =
|
||||
backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MEDIA, backupLevel);
|
||||
assertThatExceptionOfType(StatusRuntimeException.class)
|
||||
.isThrownBy(() -> backupManager.generateSvrbAuth(backupUser))
|
||||
.extracting(StatusRuntimeException::getStatus)
|
||||
.extracting(Status::getCode)
|
||||
.isEqualTo(Status.Code.UNAUTHENTICATED);
|
||||
}
|
||||
|
||||
private CopyResult copyError(final AuthenticatedBackupUser backupUser, Throwable copyException) {
|
||||
when(tusCredentialGenerator.generateUpload(any()))
|
||||
.thenReturn(new BackupUploadDescriptor(3, "def", Collections.emptyMap(), ""));
|
||||
|
||||
+20
@@ -63,6 +63,7 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
|
||||
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupAuthTestUtil;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupManager;
|
||||
@@ -116,6 +117,7 @@ public class ArchiveControllerTest {
|
||||
@ParameterizedTest
|
||||
@CsvSource(textBlock = """
|
||||
GET, v1/archives/auth/read,
|
||||
GET, v1/archives/auth/svrb,
|
||||
GET, v1/archives/,
|
||||
GET, v1/archives/upload/form,
|
||||
GET, v1/archives/media/upload/form,
|
||||
@@ -663,6 +665,24 @@ public class ArchiveControllerTest {
|
||||
assertThat(response.headers()).containsExactlyEntriesOf(Map.of("key", "value"));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void svrbAuth() throws VerificationFailedException {
|
||||
final BackupAuthCredentialPresentation presentation =
|
||||
backupAuthTestUtil.getPresentation(BackupLevel.PAID, messagesBackupKey, aci);
|
||||
when(backupManager.authenticateBackupUser(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID)));
|
||||
final ExternalServiceCredentials credentials = new ExternalServiceCredentials("username", "password");
|
||||
when(backupManager.generateSvrbAuth(any())).thenReturn(credentials);
|
||||
final ExternalServiceCredentials response = resources.getJerseyTest()
|
||||
.target("v1/archives/auth/svrb")
|
||||
.request()
|
||||
.header("X-Signal-ZK-Auth", Base64.getEncoder().encodeToString(presentation.serialize()))
|
||||
.header("X-Signal-ZK-Auth-Signature", "aaa")
|
||||
.get(ExternalServiceCredentials.class);
|
||||
assertThat(response).isEqualTo(credentials);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void readAuthInvalidParam() throws VerificationFailedException {
|
||||
final BackupAuthCredentialPresentation presentation =
|
||||
|
||||
+38
-26
@@ -1082,31 +1082,39 @@ class DeviceControllerTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordTransferArchiveUploaded() {
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
void recordTransferArchiveUploaded(final Optional<Instant> deviceCreated, final Optional<Integer> registrationId) {
|
||||
final byte deviceId = Device.PRIMARY_ID + 1;
|
||||
final Instant deviceCreated = Instant.now().truncatedTo(ChronoUnit.MILLIS);
|
||||
final RemoteAttachment transferArchive =
|
||||
new RemoteAttachment(3, Base64.getUrlEncoder().encodeToString("test".getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
when(rateLimiter.validateAsync(AuthHelper.VALID_UUID)).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(accountsManager.recordTransferArchiveUpload(account, deviceId, deviceCreated, transferArchive))
|
||||
when(accountsManager.recordTransferArchiveUpload(account, deviceId, deviceCreated, registrationId, transferArchive))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v1/devices/transfer_archive")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.put(Entity.entity(new TransferArchiveUploadedRequest(deviceId, deviceCreated.toEpochMilli(), transferArchive),
|
||||
.put(Entity.entity(new TransferArchiveUploadedRequest(deviceId, deviceCreated.map(Instant::toEpochMilli), registrationId, transferArchive),
|
||||
MediaType.APPLICATION_JSON_TYPE))) {
|
||||
|
||||
assertEquals(204, response.getStatus());
|
||||
|
||||
verify(accountsManager)
|
||||
.recordTransferArchiveUpload(account, deviceId, deviceCreated, transferArchive);
|
||||
.recordTransferArchiveUpload(account, deviceId, deviceCreated, registrationId, transferArchive);
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Arguments> recordTransferArchiveUploaded() {
|
||||
return List.of(
|
||||
Arguments.of(Optional.empty(), Optional.of(123)),
|
||||
Arguments.of(Optional.of(Instant.now().truncatedTo(ChronoUnit.MILLIS)), Optional.empty())
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordTransferArchiveFailed() {
|
||||
final byte deviceId = Device.PRIMARY_ID + 1;
|
||||
@@ -1114,20 +1122,20 @@ class DeviceControllerTest {
|
||||
final RemoteAttachmentError transferFailure = new RemoteAttachmentError(RemoteAttachmentError.ErrorType.CONTINUE_WITHOUT_UPLOAD);
|
||||
|
||||
when(rateLimiter.validateAsync(AuthHelper.VALID_UUID)).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(accountsManager.recordTransferArchiveUpload(account, deviceId, deviceCreated, transferFailure))
|
||||
when(accountsManager.recordTransferArchiveUpload(account, deviceId, Optional.of(deviceCreated), Optional.empty(), transferFailure))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v1/devices/transfer_archive")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.put(Entity.entity(new TransferArchiveUploadedRequest(deviceId, deviceCreated.toEpochMilli(), transferFailure),
|
||||
.put(Entity.entity(new TransferArchiveUploadedRequest(deviceId, Optional.of(deviceCreated.toEpochMilli()), Optional.empty(), transferFailure),
|
||||
MediaType.APPLICATION_JSON_TYPE))) {
|
||||
|
||||
assertEquals(204, response.getStatus());
|
||||
|
||||
verify(accountsManager)
|
||||
.recordTransferArchiveUpload(account, deviceId, deviceCreated, transferFailure);
|
||||
.recordTransferArchiveUpload(account, deviceId, Optional.of(deviceCreated), Optional.empty(), transferFailure);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1145,29 +1153,33 @@ class DeviceControllerTest {
|
||||
assertEquals(422, response.getStatus());
|
||||
|
||||
verify(accountsManager, never())
|
||||
.recordTransferArchiveUpload(any(), anyByte(), any(), any());
|
||||
.recordTransferArchiveUpload(any(), anyByte(), any(), any(), any());
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("DataFlowIssue")
|
||||
private static List<TransferArchiveUploadedRequest> recordTransferArchiveUploadedBadRequest() {
|
||||
private static List<Arguments> recordTransferArchiveUploadedBadRequest() {
|
||||
final RemoteAttachment validTransferArchive =
|
||||
new RemoteAttachment(3, Base64.getUrlEncoder().encodeToString("archive".getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
return List.of(
|
||||
// Invalid device ID
|
||||
new TransferArchiveUploadedRequest((byte) -1, System.currentTimeMillis(), validTransferArchive),
|
||||
|
||||
// Invalid "created at" timestamp
|
||||
new TransferArchiveUploadedRequest(Device.PRIMARY_ID, -1, validTransferArchive),
|
||||
|
||||
// Missing CDN number
|
||||
new TransferArchiveUploadedRequest(Device.PRIMARY_ID, System.currentTimeMillis(),
|
||||
new RemoteAttachment(null, Base64.getUrlEncoder().encodeToString("archive".getBytes(StandardCharsets.UTF_8)))),
|
||||
|
||||
// Bad attachment key
|
||||
new TransferArchiveUploadedRequest(Device.PRIMARY_ID, System.currentTimeMillis(),
|
||||
new RemoteAttachment(3, "This is not a valid base64 string"))
|
||||
Arguments.argumentSet("Invalid device ID", new TransferArchiveUploadedRequest((byte) -1, Optional.of(System.currentTimeMillis()), Optional.empty(), validTransferArchive)),
|
||||
Arguments.argumentSet("Invalid \"created at\" timestamp",
|
||||
new TransferArchiveUploadedRequest(Device.PRIMARY_ID, Optional.of((long) -1), Optional.empty(), validTransferArchive)),
|
||||
Arguments.argumentSet("Invalid registration ID - negative",
|
||||
new TransferArchiveUploadedRequest(Device.PRIMARY_ID, Optional.empty(), Optional.of(-1), validTransferArchive)),
|
||||
Arguments.argumentSet("Invalid registration ID - too large",
|
||||
new TransferArchiveUploadedRequest(Device.PRIMARY_ID, Optional.empty(), Optional.of(0x4000), validTransferArchive)),
|
||||
Arguments.argumentSet("Exactly one of \"created at\" timestamp and registration ID must be present - neither provided",
|
||||
new TransferArchiveUploadedRequest(Device.PRIMARY_ID, Optional.empty(), Optional.empty(), validTransferArchive)),
|
||||
Arguments.argumentSet("Exactly one of \"created at\" timestamp and registration ID must be present - both provided",
|
||||
new TransferArchiveUploadedRequest(Device.PRIMARY_ID, Optional.of(System.currentTimeMillis()), Optional.of(123), validTransferArchive)),
|
||||
Arguments.argumentSet("Missing CDN number",
|
||||
new TransferArchiveUploadedRequest(Device.PRIMARY_ID, Optional.of(System.currentTimeMillis()), Optional.empty(),
|
||||
new RemoteAttachment(null, Base64.getUrlEncoder().encodeToString("archive".getBytes(StandardCharsets.UTF_8))))),
|
||||
Arguments.argumentSet("Bad attachment key",
|
||||
new TransferArchiveUploadedRequest(Device.PRIMARY_ID, Optional.of(System.currentTimeMillis()), Optional.empty(),
|
||||
new RemoteAttachment(3, "This is not a valid base64 string")))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1180,14 +1192,14 @@ class DeviceControllerTest {
|
||||
.target("/v1/devices/transfer_archive")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.put(Entity.entity(new TransferArchiveUploadedRequest(Device.PRIMARY_ID, System.currentTimeMillis(),
|
||||
.put(Entity.entity(new TransferArchiveUploadedRequest(Device.PRIMARY_ID, Optional.of(System.currentTimeMillis()), Optional.empty(),
|
||||
new RemoteAttachment(3, Base64.getUrlEncoder().encodeToString("test".getBytes(StandardCharsets.UTF_8)))),
|
||||
MediaType.APPLICATION_JSON_TYPE))) {
|
||||
|
||||
assertEquals(429, response.getStatus());
|
||||
|
||||
verify(accountsManager, never())
|
||||
.recordTransferArchiveUpload(any(), anyByte(), any(), any());
|
||||
.recordTransferArchiveUpload(any(), anyByte(), any(), any(), any());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+105
-304
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyByte;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
@@ -35,6 +36,7 @@ import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
@@ -63,6 +65,7 @@ import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.PreKeyCount;
|
||||
import org.whispersystems.textsecuregcm.entities.PreKeyResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.PreKeyResponseItem;
|
||||
import org.whispersystems.textsecuregcm.entities.SetKeysRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.SignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
@@ -93,6 +96,7 @@ class KeysControllerTest {
|
||||
private static final UUID EXISTS_UUID = UUID.randomUUID();
|
||||
private static final UUID EXISTS_PNI = UUID.randomUUID();
|
||||
private static final AciServiceIdentifier EXISTS_ACI = new AciServiceIdentifier(EXISTS_UUID);
|
||||
private static final PniServiceIdentifier EXISTS_PNI_SERVICE_ID = new PniServiceIdentifier(EXISTS_PNI);
|
||||
|
||||
private static final UUID OTHER_UUID = UUID.randomUUID();
|
||||
private static final AciServiceIdentifier OTHER_ACI = new AciServiceIdentifier(OTHER_UUID);
|
||||
@@ -101,16 +105,9 @@ class KeysControllerTest {
|
||||
private static final AciServiceIdentifier NOT_EXISTS_ACI = new AciServiceIdentifier(NOT_EXISTS_UUID);
|
||||
|
||||
private static final byte SAMPLE_DEVICE_ID = 1;
|
||||
private static final byte SAMPLE_DEVICE_ID2 = 2;
|
||||
private static final byte SAMPLE_DEVICE_ID3 = 3;
|
||||
private static final byte SAMPLE_DEVICE_ID4 = 4;
|
||||
|
||||
private static final int SAMPLE_REGISTRATION_ID = 999;
|
||||
private static final int SAMPLE_REGISTRATION_ID2 = 1002;
|
||||
private static final int SAMPLE_REGISTRATION_ID4 = 1555;
|
||||
|
||||
private static final int SAMPLE_PNI_REGISTRATION_ID = 1717;
|
||||
private static final int SAMPLE_PNI_REGISTRATION_ID2 = 1718;
|
||||
|
||||
private final ECKeyPair IDENTITY_KEY_PAIR = ECKeyPair.generate();
|
||||
private final IdentityKey IDENTITY_KEY = new IdentityKey(IDENTITY_KEY_PAIR.getPublicKey());
|
||||
@@ -119,34 +116,21 @@ class KeysControllerTest {
|
||||
private final IdentityKey PNI_IDENTITY_KEY = new IdentityKey(PNI_IDENTITY_KEY_PAIR.getPublicKey());
|
||||
|
||||
private final ECPreKey SAMPLE_KEY = KeysHelper.ecPreKey(1234);
|
||||
private final ECPreKey SAMPLE_KEY2 = KeysHelper.ecPreKey(5667);
|
||||
private final ECPreKey SAMPLE_KEY3 = KeysHelper.ecPreKey(334);
|
||||
private final ECPreKey SAMPLE_KEY4 = KeysHelper.ecPreKey(336);
|
||||
|
||||
private final ECPreKey SAMPLE_KEY_PNI = KeysHelper.ecPreKey(7777);
|
||||
|
||||
private final KEMSignedPreKey SAMPLE_PQ_KEY = KeysHelper.signedKEMPreKey(2424, ECKeyPair.generate());
|
||||
private final KEMSignedPreKey SAMPLE_PQ_KEY2 = KeysHelper.signedKEMPreKey(6868, ECKeyPair.generate());
|
||||
private final KEMSignedPreKey SAMPLE_PQ_KEY3 = KeysHelper.signedKEMPreKey(1313, ECKeyPair.generate());
|
||||
private final KEMSignedPreKey SAMPLE_PQ_KEY4 = KeysHelper.signedKEMPreKey(7676, ECKeyPair.generate());
|
||||
|
||||
private final KEMSignedPreKey SAMPLE_PQ_KEY_PNI = KeysHelper.signedKEMPreKey(8888, ECKeyPair.generate());
|
||||
|
||||
private final ECSignedPreKey SAMPLE_SIGNED_KEY = KeysHelper.signedECPreKey(1111, IDENTITY_KEY_PAIR);
|
||||
private final ECSignedPreKey SAMPLE_SIGNED_KEY2 = KeysHelper.signedECPreKey(2222, IDENTITY_KEY_PAIR);
|
||||
private final ECSignedPreKey SAMPLE_SIGNED_KEY3 = KeysHelper.signedECPreKey(3333, IDENTITY_KEY_PAIR);
|
||||
private final ECSignedPreKey SAMPLE_SIGNED_PNI_KEY = KeysHelper.signedECPreKey(4444, PNI_IDENTITY_KEY_PAIR);
|
||||
private final ECSignedPreKey SAMPLE_SIGNED_PNI_KEY2 = KeysHelper.signedECPreKey(5555, PNI_IDENTITY_KEY_PAIR);
|
||||
private final ECSignedPreKey SAMPLE_SIGNED_PNI_KEY3 = KeysHelper.signedECPreKey(6666, PNI_IDENTITY_KEY_PAIR);
|
||||
private final ECSignedPreKey VALID_DEVICE_SIGNED_KEY = KeysHelper.signedECPreKey(89898, IDENTITY_KEY_PAIR);
|
||||
private final ECSignedPreKey VALID_DEVICE_PNI_SIGNED_KEY = KeysHelper.signedECPreKey(7777, PNI_IDENTITY_KEY_PAIR);
|
||||
private final ECSignedPreKey SAMPLE_SIGNED_PNI_KEY = KeysHelper.signedECPreKey(5555, PNI_IDENTITY_KEY_PAIR);
|
||||
|
||||
private final static KeysManager KEYS = mock(KeysManager.class );
|
||||
private final static AccountsManager accounts = mock(AccountsManager.class );
|
||||
private final static Account existsAccount = mock(Account.class );
|
||||
|
||||
private static final RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
private static final RateLimiter rateLimiter = mock(RateLimiter.class );
|
||||
private final static KeysManager KEYS = mock(KeysManager.class);
|
||||
private final static AccountsManager accounts = mock(AccountsManager.class);
|
||||
private final static Account existsAccount = mock(Account.class);
|
||||
|
||||
private static final RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
private static final RateLimiter rateLimiter = mock(RateLimiter.class);
|
||||
|
||||
private static final ServerSecretParams serverSecretParams = ServerSecretParams.generate();
|
||||
|
||||
@@ -163,9 +147,6 @@ class KeysControllerTest {
|
||||
.addResource(new RateLimitExceededExceptionMapper())
|
||||
.build();
|
||||
|
||||
private Device sampleDevice;
|
||||
private Device sampleDevice2;
|
||||
|
||||
private record WeaklyTypedPreKey(long keyId,
|
||||
|
||||
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
|
||||
@@ -198,34 +179,33 @@ class KeysControllerTest {
|
||||
byte[] identityKey) {
|
||||
}
|
||||
|
||||
private Device createSampleDevice(byte deviceId, int registrationId, int pniRegistrationId) {
|
||||
final Device sampleDevice = mock(Device.class);
|
||||
when(sampleDevice.getRegistrationId(IdentityType.ACI)).thenReturn(registrationId);
|
||||
when(sampleDevice.getRegistrationId(IdentityType.PNI)).thenReturn(pniRegistrationId);
|
||||
when(sampleDevice.getId()).thenReturn(deviceId);
|
||||
|
||||
return sampleDevice;
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
clock.unpin();
|
||||
|
||||
sampleDevice = mock(Device.class);
|
||||
sampleDevice2 = mock(Device.class);
|
||||
final Device sampleDevice3 = mock(Device.class);
|
||||
final Device sampleDevice4 = mock(Device.class);
|
||||
|
||||
final List<Device> allDevices = List.of(sampleDevice, sampleDevice2, sampleDevice3, sampleDevice4);
|
||||
|
||||
final byte sampleDeviceId = 1;
|
||||
final byte sampleDevice2Id = 2;
|
||||
final byte sampleDevice3Id = 3;
|
||||
final byte sampleDevice4Id = 4;
|
||||
|
||||
AccountsHelper.setupMockUpdate(accounts);
|
||||
|
||||
when(sampleDevice.getRegistrationId(IdentityType.ACI)).thenReturn(SAMPLE_REGISTRATION_ID);
|
||||
when(sampleDevice2.getRegistrationId(IdentityType.ACI)).thenReturn(SAMPLE_REGISTRATION_ID2);
|
||||
when(sampleDevice3.getRegistrationId(IdentityType.ACI)).thenReturn(SAMPLE_REGISTRATION_ID2);
|
||||
when(sampleDevice4.getRegistrationId(IdentityType.ACI)).thenReturn(SAMPLE_REGISTRATION_ID4);
|
||||
when(sampleDevice.getRegistrationId(IdentityType.PNI)).thenReturn(SAMPLE_PNI_REGISTRATION_ID);
|
||||
when(sampleDevice2.getRegistrationId(IdentityType.PNI)).thenReturn(SAMPLE_PNI_REGISTRATION_ID2);
|
||||
when(sampleDevice.getId()).thenReturn(sampleDeviceId);
|
||||
when(sampleDevice2.getId()).thenReturn(sampleDevice2Id);
|
||||
when(sampleDevice3.getId()).thenReturn(sampleDevice3Id);
|
||||
when(sampleDevice4.getId()).thenReturn(sampleDevice4Id);
|
||||
final Device sampleDevice =
|
||||
createSampleDevice(SAMPLE_DEVICE_ID, SAMPLE_REGISTRATION_ID, SAMPLE_PNI_REGISTRATION_ID);
|
||||
|
||||
final KeysManager.DevicePreKeys aciKeys =
|
||||
new KeysManager.DevicePreKeys(SAMPLE_SIGNED_KEY, Optional.of(SAMPLE_KEY), SAMPLE_PQ_KEY);
|
||||
final KeysManager.DevicePreKeys pniKeys =
|
||||
new KeysManager.DevicePreKeys(SAMPLE_SIGNED_PNI_KEY, Optional.of(SAMPLE_KEY_PNI), SAMPLE_PQ_KEY_PNI);
|
||||
|
||||
when(KEYS.takeDevicePreKeys(eq(SAMPLE_DEVICE_ID), eq(EXISTS_ACI), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(aciKeys)));
|
||||
when(KEYS.takeDevicePreKeys(eq(SAMPLE_DEVICE_ID), eq(EXISTS_PNI_SERVICE_ID), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(pniKeys)));
|
||||
|
||||
when(existsAccount.getUuid()).thenReturn(EXISTS_UUID);
|
||||
when(existsAccount.isIdentifiedBy(new AciServiceIdentifier(EXISTS_UUID))).thenReturn(true);
|
||||
@@ -233,12 +213,8 @@ class KeysControllerTest {
|
||||
when(existsAccount.isIdentifiedBy(new PniServiceIdentifier(EXISTS_PNI))).thenReturn(true);
|
||||
when(existsAccount.getIdentifier(IdentityType.ACI)).thenReturn(EXISTS_UUID);
|
||||
when(existsAccount.getIdentifier(IdentityType.PNI)).thenReturn(EXISTS_PNI);
|
||||
when(existsAccount.getDevice(sampleDeviceId)).thenReturn(Optional.of(sampleDevice));
|
||||
when(existsAccount.getDevice(sampleDevice2Id)).thenReturn(Optional.of(sampleDevice2));
|
||||
when(existsAccount.getDevice(sampleDevice3Id)).thenReturn(Optional.of(sampleDevice3));
|
||||
when(existsAccount.getDevice(sampleDevice4Id)).thenReturn(Optional.of(sampleDevice4));
|
||||
when(existsAccount.getDevice((byte) 22)).thenReturn(Optional.empty());
|
||||
when(existsAccount.getDevices()).thenReturn(allDevices);
|
||||
when(existsAccount.getDevice(SAMPLE_DEVICE_ID)).thenReturn(Optional.of(sampleDevice));
|
||||
when(existsAccount.getDevices()).thenReturn(List.of(sampleDevice));
|
||||
when(existsAccount.getIdentityKey(IdentityType.ACI)).thenReturn(IDENTITY_KEY);
|
||||
when(existsAccount.getIdentityKey(IdentityType.PNI)).thenReturn(PNI_IDENTITY_KEY);
|
||||
when(existsAccount.getNumber()).thenReturn(EXISTS_NUMBER);
|
||||
@@ -264,51 +240,12 @@ class KeysControllerTest {
|
||||
|
||||
when(KEYS.storeEcOneTimePreKeys(any(), anyByte(), any()))
|
||||
.thenReturn(CompletableFutureTestUtil.almostCompletedFuture(null));
|
||||
|
||||
when(KEYS.storeKemOneTimePreKeys(any(), anyByte(), any()))
|
||||
.thenReturn(CompletableFutureTestUtil.almostCompletedFuture(null));
|
||||
|
||||
when(KEYS.storePqLastResort(any(), anyByte(), any()))
|
||||
.thenReturn(CompletableFutureTestUtil.almostCompletedFuture(null));
|
||||
|
||||
when(KEYS.getEcSignedPreKey(any(), anyByte())).thenReturn(CompletableFuture.completedFuture(Optional.empty()));
|
||||
when(KEYS.storeEcSignedPreKeys(any(), anyByte(), any())).thenReturn(CompletableFutureTestUtil.almostCompletedFuture(null));
|
||||
|
||||
when(KEYS.getEcSignedPreKey(EXISTS_UUID, sampleDeviceId))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(SAMPLE_SIGNED_KEY)));
|
||||
|
||||
when(KEYS.getEcSignedPreKey(EXISTS_UUID, sampleDevice2Id))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(SAMPLE_SIGNED_KEY2)));
|
||||
|
||||
when(KEYS.getEcSignedPreKey(EXISTS_UUID, sampleDevice3Id))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(SAMPLE_SIGNED_KEY3)));
|
||||
|
||||
when(KEYS.getEcSignedPreKey(EXISTS_PNI, sampleDeviceId))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(SAMPLE_SIGNED_PNI_KEY)));
|
||||
|
||||
when(KEYS.getEcSignedPreKey(EXISTS_PNI, sampleDevice2Id))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(SAMPLE_SIGNED_PNI_KEY2)));
|
||||
|
||||
when(KEYS.getEcSignedPreKey(EXISTS_PNI, sampleDevice3Id))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(SAMPLE_SIGNED_PNI_KEY3)));
|
||||
|
||||
when(KEYS.takeEC(EXISTS_UUID, sampleDeviceId)).thenReturn(
|
||||
CompletableFuture.completedFuture(Optional.of(SAMPLE_KEY)));
|
||||
when(KEYS.takePQ(EXISTS_UUID, sampleDeviceId)).thenReturn(
|
||||
CompletableFuture.completedFuture(Optional.of(SAMPLE_PQ_KEY)));
|
||||
when(KEYS.takeEC(EXISTS_PNI, sampleDeviceId)).thenReturn(
|
||||
CompletableFuture.completedFuture(Optional.of(SAMPLE_KEY_PNI)));
|
||||
when(KEYS.takePQ(EXISTS_PNI, sampleDeviceId)).thenReturn(
|
||||
CompletableFuture.completedFuture(Optional.of(SAMPLE_PQ_KEY_PNI)));
|
||||
|
||||
when(KEYS.getEcCount(AuthHelper.VALID_UUID, sampleDeviceId)).thenReturn(CompletableFuture.completedFuture(5));
|
||||
when(KEYS.getPqCount(AuthHelper.VALID_UUID, sampleDeviceId)).thenReturn(CompletableFuture.completedFuture(5));
|
||||
|
||||
when(KEYS.getEcSignedPreKey(AuthHelper.VALID_UUID, AuthHelper.VALID_DEVICE.getId()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(VALID_DEVICE_SIGNED_KEY)));
|
||||
|
||||
when(KEYS.getEcSignedPreKey(AuthHelper.VALID_PNI, AuthHelper.VALID_DEVICE.getId()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(VALID_DEVICE_PNI_SIGNED_KEY)));
|
||||
when(KEYS.storeEcSignedPreKeys(any(), anyByte(), any()))
|
||||
.thenReturn(CompletableFutureTestUtil.almostCompletedFuture(null));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
@@ -326,6 +263,11 @@ class KeysControllerTest {
|
||||
|
||||
@Test
|
||||
void validKeyStatusTest() {
|
||||
when(KEYS.getEcCount(AuthHelper.VALID_UUID, SAMPLE_DEVICE_ID)).thenReturn(CompletableFuture.completedFuture(5));
|
||||
when(KEYS.getPqCount(AuthHelper.VALID_UUID, SAMPLE_DEVICE_ID)).thenReturn(CompletableFuture.completedFuture(5));
|
||||
when(KEYS.getEcSignedPreKey(AuthHelper.VALID_UUID, AuthHelper.VALID_DEVICE.getId()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(KeysHelper.signedECPreKey(123, IDENTITY_KEY_PAIR))));
|
||||
|
||||
PreKeyCount result = resources.getJerseyTest()
|
||||
.target("/v2/keys")
|
||||
.request()
|
||||
@@ -355,9 +297,7 @@ class KeysControllerTest {
|
||||
assertThat(result.getDevice(SAMPLE_DEVICE_ID).getRegistrationId()).isEqualTo(SAMPLE_REGISTRATION_ID);
|
||||
assertEquals(SAMPLE_SIGNED_KEY, result.getDevice(SAMPLE_DEVICE_ID).getSignedPreKey());
|
||||
|
||||
verify(KEYS).takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID);
|
||||
verify(KEYS).takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID);
|
||||
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, SAMPLE_DEVICE_ID);
|
||||
verify(KEYS).takeDevicePreKeys(eq(SAMPLE_DEVICE_ID), eq(EXISTS_ACI), any());
|
||||
verifyNoMoreInteractions(KEYS);
|
||||
}
|
||||
|
||||
@@ -377,9 +317,7 @@ class KeysControllerTest {
|
||||
assertThat(result.getDevice(SAMPLE_DEVICE_ID).getRegistrationId()).isEqualTo(SAMPLE_REGISTRATION_ID);
|
||||
assertEquals(SAMPLE_SIGNED_KEY, result.getDevice(SAMPLE_DEVICE_ID).getSignedPreKey());
|
||||
|
||||
verify(KEYS).takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID);
|
||||
verify(KEYS).takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID);
|
||||
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, SAMPLE_DEVICE_ID);
|
||||
verify(KEYS).takeDevicePreKeys(eq(SAMPLE_DEVICE_ID), eq(EXISTS_ACI), any());
|
||||
verifyNoMoreInteractions(KEYS);
|
||||
}
|
||||
|
||||
@@ -398,9 +336,7 @@ class KeysControllerTest {
|
||||
assertThat(result.getDevice(SAMPLE_DEVICE_ID).getRegistrationId()).isEqualTo(SAMPLE_PNI_REGISTRATION_ID);
|
||||
assertEquals(SAMPLE_SIGNED_PNI_KEY, result.getDevice(SAMPLE_DEVICE_ID).getSignedPreKey());
|
||||
|
||||
verify(KEYS).takeEC(EXISTS_PNI, SAMPLE_DEVICE_ID);
|
||||
verify(KEYS).takePQ(EXISTS_PNI, SAMPLE_DEVICE_ID);
|
||||
verify(KEYS).getEcSignedPreKey(EXISTS_PNI, SAMPLE_DEVICE_ID);
|
||||
verify(KEYS).takeDevicePreKeys(eq(SAMPLE_DEVICE_ID), eq(EXISTS_PNI_SERVICE_ID), any());
|
||||
verifyNoMoreInteractions(KEYS);
|
||||
}
|
||||
|
||||
@@ -420,9 +356,7 @@ class KeysControllerTest {
|
||||
assertThat(result.getDevice(SAMPLE_DEVICE_ID).getRegistrationId()).isEqualTo(SAMPLE_PNI_REGISTRATION_ID);
|
||||
assertEquals(SAMPLE_SIGNED_PNI_KEY, result.getDevice(SAMPLE_DEVICE_ID).getSignedPreKey());
|
||||
|
||||
verify(KEYS).takeEC(EXISTS_PNI, SAMPLE_DEVICE_ID);
|
||||
verify(KEYS).takePQ(EXISTS_PNI, SAMPLE_DEVICE_ID);
|
||||
verify(KEYS).getEcSignedPreKey(EXISTS_PNI, SAMPLE_DEVICE_ID);
|
||||
verify(KEYS).takeDevicePreKeys(eq(SAMPLE_DEVICE_ID), eq(EXISTS_PNI_SERVICE_ID), any());
|
||||
verifyNoMoreInteractions(KEYS);
|
||||
}
|
||||
|
||||
@@ -456,64 +390,40 @@ class KeysControllerTest {
|
||||
assertEquals(SAMPLE_PQ_KEY, result.getDevice(SAMPLE_DEVICE_ID).getPqPreKey());
|
||||
assertEquals(SAMPLE_SIGNED_KEY, result.getDevice(SAMPLE_DEVICE_ID).getSignedPreKey());
|
||||
|
||||
verify(KEYS).takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID);
|
||||
verify(KEYS).takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID);
|
||||
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, SAMPLE_DEVICE_ID);
|
||||
verify(KEYS).takeDevicePreKeys(eq(SAMPLE_DEVICE_ID), eq(EXISTS_ACI), any());
|
||||
verifyNoMoreInteractions(KEYS);
|
||||
}
|
||||
|
||||
private enum RereadBehavior {
|
||||
ACCOUNT_MISSING,
|
||||
DEVICE_MISSING,
|
||||
REG_ID_CHANGED,
|
||||
PRESENT
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(RereadBehavior.class)
|
||||
void testGetKeysMissingLastResort(RereadBehavior rereadBehavior) {
|
||||
when(KEYS.takeEC(EXISTS_PNI, SAMPLE_DEVICE_ID))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(SAMPLE_KEY)));
|
||||
when(KEYS.takeEC(EXISTS_PNI, SAMPLE_DEVICE_ID2))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(SAMPLE_KEY2)));
|
||||
|
||||
when(KEYS.takePQ(EXISTS_PNI, SAMPLE_DEVICE_ID))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(SAMPLE_PQ_KEY)));
|
||||
when(KEYS.takePQ(EXISTS_PNI, SAMPLE_DEVICE_ID2))
|
||||
// Missing PQ key
|
||||
@Test
|
||||
void testNoKeysForDevice() {
|
||||
final List<Device> devices = List.of(
|
||||
createSampleDevice((byte) 1, 2, 3),
|
||||
createSampleDevice((byte) 4, 5, 6));
|
||||
// device 1 is missing required prekeys, device 4 is missing an optional EC prekey
|
||||
when(KEYS.takeDevicePreKeys(eq((byte) 4), eq(EXISTS_PNI_SERVICE_ID), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(
|
||||
new KeysManager.DevicePreKeys(SAMPLE_SIGNED_PNI_KEY, Optional.empty(), SAMPLE_PQ_KEY_PNI))));
|
||||
when(KEYS.takeDevicePreKeys(eq((byte) 1), eq(EXISTS_PNI_SERVICE_ID), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.empty()));
|
||||
|
||||
switch (rereadBehavior) {
|
||||
case ACCOUNT_MISSING -> when(accounts.getByServiceIdentifierAsync(new PniServiceIdentifier(EXISTS_PNI)))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.empty()));
|
||||
case DEVICE_MISSING -> when(existsAccount.getDevice(SAMPLE_DEVICE_ID2))
|
||||
.thenReturn(Optional.empty());
|
||||
case REG_ID_CHANGED -> when(sampleDevice2.getRegistrationId(IdentityType.PNI))
|
||||
.thenReturn(SAMPLE_PNI_REGISTRATION_ID2)
|
||||
.thenReturn(SAMPLE_PNI_REGISTRATION_ID2 + 1);
|
||||
case PRESENT -> {
|
||||
}
|
||||
}
|
||||
when(existsAccount.getDevice((byte) 1)).thenReturn(Optional.of(devices.get(0)));
|
||||
when(existsAccount.getDevice((byte) 4)).thenReturn(Optional.of(devices.get(1)));
|
||||
when(existsAccount.getDevices()).thenReturn(devices);
|
||||
|
||||
when(existsAccount.getDevices()).thenReturn(List.of(sampleDevice, sampleDevice2));
|
||||
|
||||
Response response = resources.getJerseyTest()
|
||||
PreKeyResponse results = resources.getJerseyTest()
|
||||
.target(String.format("/v2/keys/PNI:%s/*", EXISTS_PNI))
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get();
|
||||
if (rereadBehavior == RereadBehavior.PRESENT) {
|
||||
// The device was missing a last resort prekey which should be impossible
|
||||
assertThat(response.getStatus()).isEqualTo(500);
|
||||
} else {
|
||||
// In the other cases, the device plausibly disappeared so we can just leave that device out
|
||||
final PreKeyResponse result = response.readEntity(PreKeyResponse.class);
|
||||
assertThat(result.getDevicesCount()).isEqualTo(1);
|
||||
assertThat(result.getIdentityKey()).isEqualTo(existsAccount.getIdentityKey(IdentityType.PNI));
|
||||
assertThat(result.getDevice(SAMPLE_DEVICE_ID).getPqPreKey()).isEqualTo(SAMPLE_PQ_KEY);
|
||||
}
|
||||
}
|
||||
.get(PreKeyResponse.class);
|
||||
|
||||
// Should drop device 1 and keep device 4
|
||||
assertThat(results.getDevicesCount()).isEqualTo(1);
|
||||
final PreKeyResponseItem result = results.getDevice((byte) 4);
|
||||
assertEquals(6, result.getRegistrationId());
|
||||
assertNull(result.getPreKey());
|
||||
assertEquals(SAMPLE_SIGNED_PNI_KEY, result.getSignedPreKey());
|
||||
assertEquals(SAMPLE_PQ_KEY_PNI, result.getPqPreKey());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
@@ -545,9 +455,7 @@ class KeysControllerTest {
|
||||
assertEquals(SAMPLE_PQ_KEY, result.getDevice(SAMPLE_DEVICE_ID).getPqPreKey());
|
||||
assertEquals(SAMPLE_SIGNED_KEY, result.getDevice(SAMPLE_DEVICE_ID).getSignedPreKey());
|
||||
|
||||
verify(KEYS).takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID);
|
||||
verify(KEYS).takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID);
|
||||
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, SAMPLE_DEVICE_ID);
|
||||
verify(KEYS).takeDevicePreKeys(eq(SAMPLE_DEVICE_ID), eq(EXISTS_ACI), any());
|
||||
}
|
||||
|
||||
verifyNoMoreInteractions(KEYS);
|
||||
@@ -617,162 +525,54 @@ class KeysControllerTest {
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void validMultiRequestTestV2() {
|
||||
when(KEYS.takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID)).thenReturn(
|
||||
CompletableFuture.completedFuture(Optional.of(SAMPLE_KEY)));
|
||||
when(KEYS.takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID2)).thenReturn(
|
||||
CompletableFuture.completedFuture(Optional.of(SAMPLE_KEY2)));
|
||||
when(KEYS.takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID3)).thenReturn(
|
||||
CompletableFuture.completedFuture(Optional.of(SAMPLE_KEY3)));
|
||||
when(KEYS.takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID4)).thenReturn(
|
||||
CompletableFuture.completedFuture(Optional.of(SAMPLE_KEY4)));
|
||||
@ParameterizedTest
|
||||
@EnumSource
|
||||
void validMultiRequestTestV2(IdentityType identityType) {
|
||||
final ServiceIdentifier serviceIdentifier = switch (identityType) {
|
||||
case ACI -> new AciServiceIdentifier(EXISTS_UUID);
|
||||
case PNI -> new PniServiceIdentifier(EXISTS_PNI);
|
||||
};
|
||||
|
||||
when(KEYS.takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID)).thenReturn(
|
||||
CompletableFuture.completedFuture(Optional.of(SAMPLE_PQ_KEY)));
|
||||
when(KEYS.takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID2)).thenReturn(
|
||||
CompletableFuture.completedFuture(Optional.of(SAMPLE_PQ_KEY2)));
|
||||
when(KEYS.takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID3)).thenReturn(
|
||||
CompletableFuture.completedFuture(Optional.of(SAMPLE_PQ_KEY3)));
|
||||
when(KEYS.takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID4)).thenReturn(
|
||||
CompletableFuture.completedFuture(Optional.of(SAMPLE_PQ_KEY4)));
|
||||
final List<Device> devices = new ArrayList<>();
|
||||
final List<KeysManager.DevicePreKeys> devicePreKeys = new ArrayList<>();
|
||||
for (int i = 0; i < 4; i++) {
|
||||
devices.add(createSampleDevice((byte) i, i + 100, i + 200));
|
||||
|
||||
final ECSignedPreKey signedEcPreKey = KeysHelper.signedECPreKey(i + 300, IDENTITY_KEY_PAIR);
|
||||
final ECPreKey ecPreKey = KeysHelper.ecPreKey(i + 400);
|
||||
final KEMSignedPreKey kemSignedPreKey = KeysHelper.signedKEMPreKey(i + 500, ECKeyPair.generate());
|
||||
devicePreKeys.add(new KeysManager.DevicePreKeys(signedEcPreKey, Optional.of(ecPreKey), kemSignedPreKey));
|
||||
|
||||
when(existsAccount.getDevice((byte) i)).thenReturn(Optional.of(devices.getLast()));
|
||||
when(KEYS.takeDevicePreKeys(eq((byte) i), eq(serviceIdentifier), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(devicePreKeys.getLast())));
|
||||
}
|
||||
when(existsAccount.getDevices()).thenReturn(devices);
|
||||
|
||||
PreKeyResponse results = resources.getJerseyTest()
|
||||
.target(String.format("/v2/keys/%s/*", EXISTS_UUID))
|
||||
.target(String.format("/v2/keys/%s/*", serviceIdentifier.toServiceIdentifierString()))
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get(PreKeyResponse.class);
|
||||
|
||||
assertThat(results.getDevicesCount()).isEqualTo(4);
|
||||
assertThat(results.getIdentityKey()).isEqualTo(existsAccount.getIdentityKey(IdentityType.ACI));
|
||||
assertThat(results.getIdentityKey()).isEqualTo(existsAccount.getIdentityKey(identityType));
|
||||
|
||||
ECSignedPreKey signedPreKey = results.getDevice(SAMPLE_DEVICE_ID).getSignedPreKey();
|
||||
ECPreKey preKey = results.getDevice(SAMPLE_DEVICE_ID).getPreKey();
|
||||
long registrationId = results.getDevice(SAMPLE_DEVICE_ID).getRegistrationId();
|
||||
byte deviceId = results.getDevice(SAMPLE_DEVICE_ID).getDeviceId();
|
||||
for (int i = 0; i < 4; i++) {
|
||||
final PreKeyResponseItem result = results.getDevice((byte) i);
|
||||
final KeysManager.DevicePreKeys expectedPreKeys = devicePreKeys.get(i);
|
||||
final Device expectedDevice = devices.get(i);
|
||||
|
||||
assertEquals(SAMPLE_KEY, preKey);
|
||||
assertThat(registrationId).isEqualTo(SAMPLE_REGISTRATION_ID);
|
||||
assertEquals(SAMPLE_SIGNED_KEY, signedPreKey);
|
||||
assertThat(deviceId).isEqualTo(SAMPLE_DEVICE_ID);
|
||||
assertEquals(expectedDevice.getRegistrationId(identityType), result.getRegistrationId());
|
||||
assertEquals(expectedPreKeys.ecPreKey().orElseThrow(), result.getPreKey());
|
||||
assertEquals(expectedPreKeys.ecSignedPreKey(), result.getSignedPreKey());
|
||||
assertEquals(expectedPreKeys.kemSignedPreKey(), result.getPqPreKey());
|
||||
|
||||
signedPreKey = results.getDevice(SAMPLE_DEVICE_ID2).getSignedPreKey();
|
||||
preKey = results.getDevice(SAMPLE_DEVICE_ID2).getPreKey();
|
||||
registrationId = results.getDevice(SAMPLE_DEVICE_ID2).getRegistrationId();
|
||||
deviceId = results.getDevice(SAMPLE_DEVICE_ID2).getDeviceId();
|
||||
|
||||
assertEquals(SAMPLE_KEY2, preKey);
|
||||
assertThat(registrationId).isEqualTo(SAMPLE_REGISTRATION_ID2);
|
||||
assertEquals(SAMPLE_SIGNED_KEY2, signedPreKey);
|
||||
assertThat(deviceId).isEqualTo(SAMPLE_DEVICE_ID2);
|
||||
|
||||
signedPreKey = results.getDevice(SAMPLE_DEVICE_ID4).getSignedPreKey();
|
||||
preKey = results.getDevice(SAMPLE_DEVICE_ID4).getPreKey();
|
||||
registrationId = results.getDevice(SAMPLE_DEVICE_ID4).getRegistrationId();
|
||||
deviceId = results.getDevice(SAMPLE_DEVICE_ID4).getDeviceId();
|
||||
|
||||
assertEquals(SAMPLE_KEY4, preKey);
|
||||
assertThat(registrationId).isEqualTo(SAMPLE_REGISTRATION_ID4);
|
||||
assertThat(signedPreKey).isNull();
|
||||
assertThat(deviceId).isEqualTo(SAMPLE_DEVICE_ID4);
|
||||
|
||||
verify(KEYS).takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID);
|
||||
verify(KEYS).takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID2);
|
||||
verify(KEYS).takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID3);
|
||||
verify(KEYS).takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID4);
|
||||
verify(KEYS).takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID);
|
||||
verify(KEYS).takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID2);
|
||||
verify(KEYS).takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID3);
|
||||
verify(KEYS).takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID4);
|
||||
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, SAMPLE_DEVICE_ID);
|
||||
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, SAMPLE_DEVICE_ID2);
|
||||
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, SAMPLE_DEVICE_ID3);
|
||||
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, SAMPLE_DEVICE_ID4);
|
||||
verify(KEYS).takeDevicePreKeys(eq((byte) i), eq(serviceIdentifier), any());
|
||||
}
|
||||
verifyNoMoreInteractions(KEYS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void validMultiRequestPqTestV2() {
|
||||
when(KEYS.takeEC(any(), anyByte())).thenReturn(CompletableFuture.completedFuture(Optional.empty()));
|
||||
when(KEYS.takePQ(any(), anyByte())).thenReturn(CompletableFuture.completedFuture(Optional.empty()));
|
||||
|
||||
when(KEYS.takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID)).thenReturn(
|
||||
CompletableFuture.completedFuture(Optional.of(SAMPLE_KEY)));
|
||||
when(KEYS.takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID3)).thenReturn(
|
||||
CompletableFuture.completedFuture(Optional.of(SAMPLE_KEY3)));
|
||||
when(KEYS.takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID4)).thenReturn(
|
||||
CompletableFuture.completedFuture(Optional.of(SAMPLE_KEY4)));
|
||||
when(KEYS.takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID)).thenReturn(
|
||||
CompletableFuture.completedFuture(Optional.of(SAMPLE_PQ_KEY)));
|
||||
when(KEYS.takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID2)).thenReturn(
|
||||
CompletableFuture.completedFuture(Optional.of(SAMPLE_PQ_KEY2)));
|
||||
when(KEYS.takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID3)).thenReturn(
|
||||
CompletableFuture.completedFuture(Optional.of(SAMPLE_PQ_KEY3)));
|
||||
when(KEYS.takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID4)).thenReturn(
|
||||
CompletableFuture.completedFuture(Optional.of(SAMPLE_PQ_KEY4)));
|
||||
|
||||
PreKeyResponse results = resources.getJerseyTest()
|
||||
.target(String.format("/v2/keys/%s/*", EXISTS_UUID))
|
||||
.queryParam("pq", "true")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get(PreKeyResponse.class);
|
||||
|
||||
assertThat(results.getDevicesCount()).isEqualTo(4);
|
||||
assertThat(results.getIdentityKey()).isEqualTo(existsAccount.getIdentityKey(IdentityType.ACI));
|
||||
|
||||
ECSignedPreKey signedPreKey = results.getDevice(SAMPLE_DEVICE_ID).getSignedPreKey();
|
||||
ECPreKey preKey = results.getDevice(SAMPLE_DEVICE_ID).getPreKey();
|
||||
KEMSignedPreKey pqPreKey = results.getDevice(SAMPLE_DEVICE_ID).getPqPreKey();
|
||||
int registrationId = results.getDevice(SAMPLE_DEVICE_ID).getRegistrationId();
|
||||
byte deviceId = results.getDevice(SAMPLE_DEVICE_ID).getDeviceId();
|
||||
|
||||
assertEquals(SAMPLE_KEY, preKey);
|
||||
assertEquals(SAMPLE_PQ_KEY, pqPreKey);
|
||||
assertThat(registrationId).isEqualTo(SAMPLE_REGISTRATION_ID);
|
||||
assertEquals(SAMPLE_SIGNED_KEY, signedPreKey);
|
||||
assertThat(deviceId).isEqualTo(SAMPLE_DEVICE_ID);
|
||||
|
||||
signedPreKey = results.getDevice(SAMPLE_DEVICE_ID2).getSignedPreKey();
|
||||
preKey = results.getDevice(SAMPLE_DEVICE_ID2).getPreKey();
|
||||
pqPreKey = results.getDevice(SAMPLE_DEVICE_ID2).getPqPreKey();
|
||||
registrationId = results.getDevice(SAMPLE_DEVICE_ID2).getRegistrationId();
|
||||
deviceId = results.getDevice(SAMPLE_DEVICE_ID2).getDeviceId();
|
||||
|
||||
assertThat(preKey).isNull();
|
||||
assertEquals(SAMPLE_PQ_KEY2, pqPreKey);
|
||||
assertThat(registrationId).isEqualTo(SAMPLE_REGISTRATION_ID2);
|
||||
assertEquals(SAMPLE_SIGNED_KEY2, signedPreKey);
|
||||
assertThat(deviceId).isEqualTo(SAMPLE_DEVICE_ID2);
|
||||
|
||||
signedPreKey = results.getDevice(SAMPLE_DEVICE_ID4).getSignedPreKey();
|
||||
preKey = results.getDevice(SAMPLE_DEVICE_ID4).getPreKey();
|
||||
pqPreKey = results.getDevice(SAMPLE_DEVICE_ID4).getPqPreKey();
|
||||
registrationId = results.getDevice(SAMPLE_DEVICE_ID4).getRegistrationId();
|
||||
deviceId = results.getDevice(SAMPLE_DEVICE_ID4).getDeviceId();
|
||||
|
||||
assertEquals(SAMPLE_KEY4, preKey);
|
||||
assertThat(pqPreKey).isEqualTo(SAMPLE_PQ_KEY4);
|
||||
assertThat(registrationId).isEqualTo(SAMPLE_REGISTRATION_ID4);
|
||||
assertThat(signedPreKey).isNull();
|
||||
assertThat(deviceId).isEqualTo(SAMPLE_DEVICE_ID4);
|
||||
|
||||
verify(KEYS).takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID);
|
||||
verify(KEYS).takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID);
|
||||
verify(KEYS).takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID2);
|
||||
verify(KEYS).takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID2);
|
||||
verify(KEYS).takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID3);
|
||||
verify(KEYS).takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID3);
|
||||
verify(KEYS).takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID4);
|
||||
verify(KEYS).takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID4);
|
||||
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, SAMPLE_DEVICE_ID);
|
||||
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, SAMPLE_DEVICE_ID2);
|
||||
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, SAMPLE_DEVICE_ID3);
|
||||
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, SAMPLE_DEVICE_ID4);
|
||||
verifyNoMoreInteractions(KEYS);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void invalidRequestTestV2() {
|
||||
Response response = resources.getJerseyTest()
|
||||
@@ -786,6 +586,7 @@ class KeysControllerTest {
|
||||
|
||||
@Test
|
||||
void anotherInvalidRequestTestV2() {
|
||||
when(existsAccount.getDevice((byte) 22)).thenReturn(Optional.empty());
|
||||
Response response = resources.getJerseyTest()
|
||||
.target(String.format("/v2/keys/%s/22", EXISTS_UUID))
|
||||
.request()
|
||||
|
||||
-70
@@ -1,70 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.whispersystems.textsecuregcm.util.MockUtils.randomSecretBytes;
|
||||
|
||||
import io.dropwizard.auth.AuthValueFactoryProvider;
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import io.dropwizard.testing.junit5.ResourceExtension;
|
||||
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureValueRecoveryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.util.MutableClock;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import java.time.Instant;
|
||||
import java.util.HexFormat;
|
||||
|
||||
@ExtendWith(DropwizardExtensionsSupport.class)
|
||||
public class SecureValueRecoveryBControllerTest {
|
||||
|
||||
private static final SecureValueRecoveryConfiguration CFG = new SecureValueRecoveryConfiguration(
|
||||
"",
|
||||
randomSecretBytes(32),
|
||||
randomSecretBytes(32),
|
||||
null,
|
||||
null,
|
||||
null
|
||||
);
|
||||
|
||||
private static final MutableClock CLOCK = new MutableClock();
|
||||
|
||||
private static final ExternalServiceCredentialsGenerator CREDENTIAL_GENERATOR =
|
||||
SecureValueRecoveryBController.credentialsGenerator(CFG, CLOCK);
|
||||
|
||||
private static final SecureValueRecoveryBController CONTROLLER =
|
||||
new SecureValueRecoveryBController(CREDENTIAL_GENERATOR);
|
||||
|
||||
private static final ResourceExtension RESOURCES = ResourceExtension.builder()
|
||||
.addProvider(AuthHelper.getAuthFilter())
|
||||
.addProvider(new AuthValueFactoryProvider.Binder<>(AuthenticatedDevice.class))
|
||||
.setMapper(SystemMapper.jsonMapper())
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addResource(CONTROLLER)
|
||||
.build();
|
||||
|
||||
@Test
|
||||
public void testGetCredentials() {
|
||||
CLOCK.setTimeInstant(Instant.ofEpochSecond(123));
|
||||
final ExternalServiceCredentials creds = RESOURCES.getJerseyTest()
|
||||
.target("/v1/svrb/auth")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get(ExternalServiceCredentials.class);
|
||||
|
||||
assertThat(HexFormat.of().parseHex(creds.username())).hasSize(16);
|
||||
System.out.println(creds.password());
|
||||
final String[] split = creds.password().split(":", 2);
|
||||
assertThat(Long.parseLong(split[0])).isEqualTo(123);
|
||||
}
|
||||
}
|
||||
+9
-16
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.grpc;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyByte;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -100,15 +101,11 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
|
||||
final ECPreKey ecPreKey = new ECPreKey(1, ECKeyPair.generate().getPublicKey());
|
||||
final ECSignedPreKey ecSignedPreKey = KeysHelper.signedECPreKey(2, identityKeyPair);
|
||||
final KEMSignedPreKey kemSignedPreKey = KeysHelper.signedKEMPreKey(3, identityKeyPair);
|
||||
final KeysManager.DevicePreKeys devicePreKeys =
|
||||
new KeysManager.DevicePreKeys(ecSignedPreKey, Optional.of(ecPreKey), kemSignedPreKey);
|
||||
|
||||
when(keysManager.takeEC(uuid, Device.PRIMARY_ID))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(ecPreKey)));
|
||||
|
||||
when(keysManager.takePQ(uuid, Device.PRIMARY_ID))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(kemSignedPreKey)));
|
||||
|
||||
when(keysManager.getEcSignedPreKey(uuid, Device.PRIMARY_ID))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(ecSignedPreKey)));
|
||||
when(keysManager.takeDevicePreKeys(eq(Device.PRIMARY_ID), eq(identifier), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(devicePreKeys)));
|
||||
|
||||
final GetPreKeysResponse response = unauthenticatedServiceStub().getPreKeys(GetPreKeysAnonymousRequest.newBuilder()
|
||||
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
|
||||
@@ -151,15 +148,11 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
|
||||
final ECPreKey ecPreKey = new ECPreKey(1, ECKeyPair.generate().getPublicKey());
|
||||
final ECSignedPreKey ecSignedPreKey = KeysHelper.signedECPreKey(2, identityKeyPair);
|
||||
final KEMSignedPreKey kemSignedPreKey = KeysHelper.signedKEMPreKey(3, identityKeyPair);
|
||||
final KeysManager.DevicePreKeys devicePreKeys =
|
||||
new KeysManager.DevicePreKeys(ecSignedPreKey, Optional.of(ecPreKey), kemSignedPreKey);
|
||||
|
||||
when(keysManager.takeEC(uuid, Device.PRIMARY_ID))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(ecPreKey)));
|
||||
|
||||
when(keysManager.takePQ(uuid, Device.PRIMARY_ID))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(kemSignedPreKey)));
|
||||
|
||||
when(keysManager.getEcSignedPreKey(uuid, Device.PRIMARY_ID))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(ecSignedPreKey)));
|
||||
when(keysManager.takeDevicePreKeys(eq(Device.PRIMARY_ID), eq(identifier), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(devicePreKeys)));
|
||||
|
||||
// Expirations must be on day boundaries or libsignal will refuse to create or verify the token
|
||||
final Instant expiration = Instant.now().truncatedTo(ChronoUnit.DAYS);
|
||||
|
||||
+41
-58
@@ -10,7 +10,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyByte;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
@@ -59,6 +59,7 @@ import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
@@ -464,26 +465,52 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest<KeysGrpcService, KeysGrpc.K
|
||||
final UUID identifier = UUID.randomUUID();
|
||||
|
||||
final IdentityType identityType = IdentityTypeUtil.fromGrpcIdentityType(grpcIdentityType);
|
||||
final org.whispersystems.textsecuregcm.identity.ServiceIdentifier serviceIdentifier = switch (identityType) {
|
||||
case PNI -> new PniServiceIdentifier(identifier);
|
||||
case ACI -> new AciServiceIdentifier(identifier);
|
||||
};
|
||||
|
||||
when(targetAccount.getUuid()).thenReturn(UUID.randomUUID());
|
||||
when(targetAccount.getIdentifier(identityType)).thenReturn(identifier);
|
||||
when(targetAccount.getIdentityKey(identityType)).thenReturn(identityKey);
|
||||
when(accountsManager.getByServiceIdentifierAsync(argThat(serviceIdentifier -> serviceIdentifier.uuid().equals(identifier))))
|
||||
when(accountsManager.getByServiceIdentifierAsync(serviceIdentifier))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(targetAccount)));
|
||||
|
||||
final Map<Byte, ECPreKey> ecOneTimePreKeys = new HashMap<>();
|
||||
final Map<Byte, KEMSignedPreKey> kemPreKeys = new HashMap<>();
|
||||
final Map<Byte, ECSignedPreKey> ecSignedPreKeys = new HashMap<>();
|
||||
final Map<Byte, KeysManager.DevicePreKeys> devicePreKeysMap = new HashMap<>();
|
||||
|
||||
final Map<Byte, Device> devices = new HashMap<>();
|
||||
final Map<Byte, GetPreKeysResponse.PreKeyBundle> expectedPreKeyBundles = new HashMap<>();
|
||||
|
||||
final byte deviceId1 = 1;
|
||||
final byte deviceId2 = 2;
|
||||
|
||||
for (final byte deviceId : List.of(deviceId1, deviceId2)) {
|
||||
ecOneTimePreKeys.put(deviceId, new ECPreKey(1, ECKeyPair.generate().getPublicKey()));
|
||||
kemPreKeys.put(deviceId, KeysHelper.signedKEMPreKey(2, identityKeyPair));
|
||||
ecSignedPreKeys.put(deviceId, KeysHelper.signedECPreKey(3, identityKeyPair));
|
||||
|
||||
final ECSignedPreKey ecSignedPreKey = KeysHelper.signedECPreKey(3, identityKeyPair);
|
||||
final Optional<ECPreKey> maybeEcPreKey = Optional
|
||||
.of(new ECPreKey(1, ECKeyPair.generate().getPublicKey()))
|
||||
.filter(_ -> deviceId == deviceId1);
|
||||
final KEMSignedPreKey kemSignedPreKey = KeysHelper.signedKEMPreKey(2, identityKeyPair);
|
||||
|
||||
devicePreKeysMap.put(deviceId, new KeysManager.DevicePreKeys(ecSignedPreKey, maybeEcPreKey, kemSignedPreKey));
|
||||
|
||||
final GetPreKeysResponse.PreKeyBundle.Builder builder = GetPreKeysResponse.PreKeyBundle.newBuilder()
|
||||
.setEcSignedPreKey(EcSignedPreKey.newBuilder()
|
||||
.setKeyId(ecSignedPreKey.keyId())
|
||||
.setPublicKey(ByteString.copyFrom(ecSignedPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(ecSignedPreKey.signature()))
|
||||
.build())
|
||||
.setKemOneTimePreKey(KemSignedPreKey.newBuilder()
|
||||
.setKeyId(kemSignedPreKey.keyId())
|
||||
.setPublicKey(ByteString.copyFrom(kemSignedPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(kemSignedPreKey.signature()))
|
||||
.build());
|
||||
maybeEcPreKey.ifPresent(ecPreKey -> builder
|
||||
.setEcOneTimePreKey(EcPreKey.newBuilder()
|
||||
.setKeyId(ecPreKey.keyId())
|
||||
.setPublicKey(ByteString.copyFrom(ecPreKey.serializedPublicKey()))
|
||||
.build()));
|
||||
expectedPreKeyBundles.put(deviceId, builder.build());
|
||||
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getId()).thenReturn(deviceId);
|
||||
@@ -494,14 +521,9 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest<KeysGrpcService, KeysGrpc.K
|
||||
|
||||
when(targetAccount.getDevices()).thenReturn(new ArrayList<>(devices.values()));
|
||||
|
||||
ecOneTimePreKeys.forEach((deviceId, preKey) -> when(keysManager.takeEC(identifier, deviceId))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(preKey))));
|
||||
|
||||
ecSignedPreKeys.forEach((deviceId, preKey) -> when(keysManager.getEcSignedPreKey(identifier, deviceId))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(preKey))));
|
||||
|
||||
kemPreKeys.forEach((deviceId, preKey) -> when(keysManager.takePQ(identifier, deviceId))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(preKey))));
|
||||
devicePreKeysMap.forEach((deviceId, preKeys) -> when(keysManager.takeDevicePreKeys(eq(deviceId),
|
||||
eq(serviceIdentifier), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(preKeys))));
|
||||
|
||||
{
|
||||
final GetPreKeysResponse response = authenticatedServiceStub().getPreKeys(GetPreKeysRequest.newBuilder()
|
||||
@@ -514,30 +536,12 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest<KeysGrpcService, KeysGrpc.K
|
||||
|
||||
final GetPreKeysResponse expectedResponse = GetPreKeysResponse.newBuilder()
|
||||
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
|
||||
.putPreKeys(1, GetPreKeysResponse.PreKeyBundle.newBuilder()
|
||||
.setEcSignedPreKey(EcSignedPreKey.newBuilder()
|
||||
.setKeyId(ecSignedPreKeys.get(deviceId1).keyId())
|
||||
.setPublicKey(ByteString.copyFrom(ecSignedPreKeys.get(deviceId1).serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(ecSignedPreKeys.get(deviceId1).signature()))
|
||||
.build())
|
||||
.setEcOneTimePreKey(EcPreKey.newBuilder()
|
||||
.setKeyId(ecOneTimePreKeys.get(deviceId1).keyId())
|
||||
.setPublicKey(ByteString.copyFrom(ecOneTimePreKeys.get(deviceId1).serializedPublicKey()))
|
||||
.build())
|
||||
.setKemOneTimePreKey(KemSignedPreKey.newBuilder()
|
||||
.setKeyId(kemPreKeys.get(deviceId1).keyId())
|
||||
.setPublicKey(ByteString.copyFrom(kemPreKeys.get(deviceId1).serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(kemPreKeys.get(deviceId1).signature()))
|
||||
.build())
|
||||
.build())
|
||||
.putPreKeys(1, expectedPreKeyBundles.get(deviceId1))
|
||||
.build();
|
||||
|
||||
assertEquals(expectedResponse, response);
|
||||
}
|
||||
|
||||
when(keysManager.takeEC(identifier, deviceId2)).thenReturn(CompletableFuture.completedFuture(Optional.empty()));
|
||||
when(keysManager.takePQ(identifier, deviceId2)).thenReturn(CompletableFuture.completedFuture(Optional.empty()));
|
||||
|
||||
{
|
||||
final GetPreKeysResponse response = authenticatedServiceStub().getPreKeys(GetPreKeysRequest.newBuilder()
|
||||
.setTargetIdentifier(ServiceIdentifier.newBuilder()
|
||||
@@ -548,29 +552,8 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest<KeysGrpcService, KeysGrpc.K
|
||||
|
||||
final GetPreKeysResponse expectedResponse = GetPreKeysResponse.newBuilder()
|
||||
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
|
||||
.putPreKeys(1, GetPreKeysResponse.PreKeyBundle.newBuilder()
|
||||
.setEcSignedPreKey(EcSignedPreKey.newBuilder()
|
||||
.setKeyId(ecSignedPreKeys.get(deviceId1).keyId())
|
||||
.setPublicKey(ByteString.copyFrom(ecSignedPreKeys.get(deviceId1).serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(ecSignedPreKeys.get(deviceId1).signature()))
|
||||
.build())
|
||||
.setEcOneTimePreKey(EcPreKey.newBuilder()
|
||||
.setKeyId(ecOneTimePreKeys.get(deviceId1).keyId())
|
||||
.setPublicKey(ByteString.copyFrom(ecOneTimePreKeys.get(deviceId1).serializedPublicKey()))
|
||||
.build())
|
||||
.setKemOneTimePreKey(KemSignedPreKey.newBuilder()
|
||||
.setKeyId(kemPreKeys.get(deviceId1).keyId())
|
||||
.setPublicKey(ByteString.copyFrom(kemPreKeys.get(deviceId1).serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(kemPreKeys.get(deviceId1).signature()))
|
||||
.build())
|
||||
.build())
|
||||
.putPreKeys(2, GetPreKeysResponse.PreKeyBundle.newBuilder()
|
||||
.setEcSignedPreKey(EcSignedPreKey.newBuilder()
|
||||
.setKeyId(ecSignedPreKeys.get(deviceId2).keyId())
|
||||
.setPublicKey(ByteString.copyFrom(ecSignedPreKeys.get(deviceId2).serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(ecSignedPreKeys.get(deviceId2).signature()))
|
||||
.build())
|
||||
.build())
|
||||
.putPreKeys(1, expectedPreKeyBundles.get(deviceId1))
|
||||
.putPreKeys(2, expectedPreKeyBundles.get(deviceId2))
|
||||
.build();
|
||||
|
||||
assertEquals(expectedResponse, response);
|
||||
|
||||
+27
-151
@@ -11,7 +11,6 @@ import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import io.lettuce.core.cluster.SlotHash;
|
||||
@@ -20,9 +19,7 @@ import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
|
||||
import io.lettuce.core.cluster.pubsub.api.async.RedisClusterPubSubAsyncCommands;
|
||||
import io.lettuce.core.cluster.pubsub.api.sync.RedisClusterPubSubCommands;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
@@ -38,17 +35,15 @@ import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.tests.util.MockRedisFuture;
|
||||
import org.whispersystems.textsecuregcm.tests.util.RedisClusterHelper;
|
||||
|
||||
@Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
|
||||
class WebSocketConnectionEventManagerTest {
|
||||
class RedisMessageAvailabilityManagerTest {
|
||||
|
||||
private WebSocketConnectionEventManager localEventManager;
|
||||
private WebSocketConnectionEventManager remoteEventManager;
|
||||
private RedisMessageAvailabilityManager localEventManager;
|
||||
private RedisMessageAvailabilityManager remoteEventManager;
|
||||
|
||||
private static ExecutorService webSocketConnectionEventExecutor;
|
||||
private static ExecutorService asyncOperationQueueingExecutor;
|
||||
@@ -56,7 +51,7 @@ class WebSocketConnectionEventManagerTest {
|
||||
@RegisterExtension
|
||||
static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
|
||||
|
||||
private static class WebSocketConnectionEventAdapter implements WebSocketConnectionEventListener {
|
||||
private static class MessageAvailabilityAdapter implements MessageAvailabilityListener {
|
||||
|
||||
@Override
|
||||
public void handleNewMessageAvailable() {
|
||||
@@ -67,7 +62,7 @@ class WebSocketConnectionEventManagerTest {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleConnectionDisplaced(final boolean connectedElsewhere) {
|
||||
public void handleConflictingMessageReader() {
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,15 +74,11 @@ class WebSocketConnectionEventManagerTest {
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
localEventManager = new WebSocketConnectionEventManager(mock(AccountsManager.class),
|
||||
mock(PushNotificationManager.class),
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
localEventManager = new RedisMessageAvailabilityManager(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
webSocketConnectionEventExecutor,
|
||||
asyncOperationQueueingExecutor);
|
||||
|
||||
remoteEventManager = new WebSocketConnectionEventManager(mock(AccountsManager.class),
|
||||
mock(PushNotificationManager.class),
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
remoteEventManager = new RedisMessageAvailabilityManager(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
webSocketConnectionEventExecutor,
|
||||
asyncOperationQueueingExecutor);
|
||||
|
||||
@@ -116,15 +107,12 @@ class WebSocketConnectionEventManagerTest {
|
||||
final AtomicBoolean firstListenerDisplaced = new AtomicBoolean(false);
|
||||
|
||||
final AtomicBoolean secondListenerDisplaced = new AtomicBoolean(false);
|
||||
final AtomicBoolean firstListenerConnectedElsewhere = new AtomicBoolean(false);
|
||||
|
||||
localEventManager.handleClientConnected(accountIdentifier, deviceId, new WebSocketConnectionEventAdapter() {
|
||||
localEventManager.handleClientConnected(accountIdentifier, deviceId, new MessageAvailabilityAdapter() {
|
||||
@Override
|
||||
public void handleConnectionDisplaced(final boolean connectedElsewhere) {
|
||||
public void handleConflictingMessageReader() {
|
||||
synchronized (firstListenerDisplaced) {
|
||||
firstListenerDisplaced.set(true);
|
||||
firstListenerConnectedElsewhere.set(connectedElsewhere);
|
||||
|
||||
firstListenerDisplaced.notifyAll();
|
||||
}
|
||||
}
|
||||
@@ -133,12 +121,12 @@ class WebSocketConnectionEventManagerTest {
|
||||
assertFalse(firstListenerDisplaced.get());
|
||||
assertFalse(secondListenerDisplaced.get());
|
||||
|
||||
final WebSocketConnectionEventManager displacingManager =
|
||||
final RedisMessageAvailabilityManager displacingManager =
|
||||
displaceRemotely ? remoteEventManager : localEventManager;
|
||||
|
||||
displacingManager.handleClientConnected(accountIdentifier, deviceId, new WebSocketConnectionEventAdapter() {
|
||||
displacingManager.handleClientConnected(accountIdentifier, deviceId, new MessageAvailabilityAdapter() {
|
||||
@Override
|
||||
public void handleConnectionDisplaced(final boolean connectedElsewhere) {
|
||||
public void handleConflictingMessageReader() {
|
||||
secondListenerDisplaced.set(true);
|
||||
}
|
||||
}).toCompletableFuture().join();
|
||||
@@ -151,8 +139,6 @@ class WebSocketConnectionEventManagerTest {
|
||||
|
||||
assertTrue(firstListenerDisplaced.get());
|
||||
assertFalse(secondListenerDisplaced.get());
|
||||
|
||||
assertTrue(firstListenerConnectedElsewhere.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -163,7 +149,7 @@ class WebSocketConnectionEventManagerTest {
|
||||
assertFalse(localEventManager.isLocallyPresent(accountIdentifier, deviceId));
|
||||
assertFalse(remoteEventManager.isLocallyPresent(accountIdentifier, deviceId));
|
||||
|
||||
localEventManager.handleClientConnected(accountIdentifier, deviceId, new WebSocketConnectionEventAdapter())
|
||||
localEventManager.handleClientConnected(accountIdentifier, deviceId, new MessageAvailabilityAdapter())
|
||||
.toCompletableFuture()
|
||||
.join();
|
||||
|
||||
@@ -178,56 +164,6 @@ class WebSocketConnectionEventManagerTest {
|
||||
assertFalse(remoteEventManager.isLocallyPresent(accountIdentifier, deviceId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void handleDisconnectionRequest() throws InterruptedException {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
final byte firstDeviceId = Device.PRIMARY_ID;
|
||||
final byte secondDeviceId = firstDeviceId + 1;
|
||||
|
||||
final AtomicBoolean firstListenerDisplaced = new AtomicBoolean(false);
|
||||
final AtomicBoolean secondListenerDisplaced = new AtomicBoolean(false);
|
||||
|
||||
final AtomicBoolean firstListenerConnectedElsewhere = new AtomicBoolean(false);
|
||||
|
||||
localEventManager.handleClientConnected(accountIdentifier, firstDeviceId, new WebSocketConnectionEventAdapter() {
|
||||
@Override
|
||||
public void handleConnectionDisplaced(final boolean connectedElsewhere) {
|
||||
synchronized (firstListenerDisplaced) {
|
||||
firstListenerDisplaced.set(true);
|
||||
firstListenerConnectedElsewhere.set(connectedElsewhere);
|
||||
|
||||
firstListenerDisplaced.notifyAll();
|
||||
}
|
||||
}
|
||||
}).toCompletableFuture().join();
|
||||
|
||||
localEventManager.handleClientConnected(accountIdentifier, secondDeviceId, new WebSocketConnectionEventAdapter() {
|
||||
@Override
|
||||
public void handleConnectionDisplaced(final boolean connectedElsewhere) {
|
||||
synchronized (secondListenerDisplaced) {
|
||||
secondListenerDisplaced.set(true);
|
||||
secondListenerDisplaced.notifyAll();
|
||||
}
|
||||
}
|
||||
}).toCompletableFuture().join();
|
||||
|
||||
assertFalse(firstListenerDisplaced.get());
|
||||
assertFalse(secondListenerDisplaced.get());
|
||||
|
||||
localEventManager.handleDisconnectionRequest(accountIdentifier, List.of(firstDeviceId));
|
||||
|
||||
synchronized (firstListenerDisplaced) {
|
||||
while (!firstListenerDisplaced.get()) {
|
||||
firstListenerDisplaced.wait();
|
||||
}
|
||||
}
|
||||
|
||||
assertTrue(firstListenerDisplaced.get());
|
||||
assertFalse(secondListenerDisplaced.get());
|
||||
|
||||
assertFalse(firstListenerConnectedElsewhere.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resubscribe() {
|
||||
@SuppressWarnings("unchecked") final RedisClusterPubSubCommands<byte[], byte[]> pubSubCommands =
|
||||
@@ -243,9 +179,7 @@ class WebSocketConnectionEventManagerTest {
|
||||
.binaryPubSubAsyncCommands(pubSubAsyncCommands)
|
||||
.build();
|
||||
|
||||
final WebSocketConnectionEventManager eventManager = new WebSocketConnectionEventManager(
|
||||
mock(AccountsManager.class),
|
||||
mock(PushNotificationManager.class),
|
||||
final RedisMessageAvailabilityManager eventManager = new RedisMessageAvailabilityManager(
|
||||
clusterClient,
|
||||
Runnable::run,
|
||||
Runnable::run);
|
||||
@@ -254,7 +188,7 @@ class WebSocketConnectionEventManagerTest {
|
||||
|
||||
final UUID firstAccountIdentifier = UUID.randomUUID();
|
||||
final byte firstDeviceId = Device.PRIMARY_ID;
|
||||
final int firstSlot = SlotHash.getSlot(WebSocketConnectionEventManager.getClientEventChannel(firstAccountIdentifier, firstDeviceId));
|
||||
final int firstSlot = SlotHash.getSlot(RedisMessageAvailabilityManager.getClientEventChannel(firstAccountIdentifier, firstDeviceId));
|
||||
|
||||
final UUID secondAccountIdentifier;
|
||||
final byte secondDeviceId = firstDeviceId + 1;
|
||||
@@ -265,15 +199,15 @@ class WebSocketConnectionEventManagerTest {
|
||||
|
||||
do {
|
||||
candidateIdentifier = UUID.randomUUID();
|
||||
} while (SlotHash.getSlot(WebSocketConnectionEventManager.getClientEventChannel(candidateIdentifier, secondDeviceId)) == firstSlot);
|
||||
} while (SlotHash.getSlot(RedisMessageAvailabilityManager.getClientEventChannel(candidateIdentifier, secondDeviceId)) == firstSlot);
|
||||
|
||||
secondAccountIdentifier = candidateIdentifier;
|
||||
}
|
||||
|
||||
eventManager.handleClientConnected(firstAccountIdentifier, firstDeviceId, new WebSocketConnectionEventAdapter()).toCompletableFuture().join();
|
||||
eventManager.handleClientConnected(secondAccountIdentifier, secondDeviceId, new WebSocketConnectionEventAdapter()).toCompletableFuture().join();
|
||||
eventManager.handleClientConnected(firstAccountIdentifier, firstDeviceId, new MessageAvailabilityAdapter()).toCompletableFuture().join();
|
||||
eventManager.handleClientConnected(secondAccountIdentifier, secondDeviceId, new MessageAvailabilityAdapter()).toCompletableFuture().join();
|
||||
|
||||
final int secondSlot = SlotHash.getSlot(WebSocketConnectionEventManager.getClientEventChannel(secondAccountIdentifier, secondDeviceId));
|
||||
final int secondSlot = SlotHash.getSlot(RedisMessageAvailabilityManager.getClientEventChannel(secondAccountIdentifier, secondDeviceId));
|
||||
|
||||
final String firstNodeId = UUID.randomUUID().toString();
|
||||
|
||||
@@ -296,8 +230,8 @@ class WebSocketConnectionEventManagerTest {
|
||||
List.of(firstBeforeNode),
|
||||
List.of(firstAfterNode, secondAfterNode)));
|
||||
|
||||
verify(pubSubCommands).ssubscribe(WebSocketConnectionEventManager.getClientEventChannel(secondAccountIdentifier, secondDeviceId));
|
||||
verify(pubSubCommands, never()).ssubscribe(WebSocketConnectionEventManager.getClientEventChannel(firstAccountIdentifier, firstDeviceId));
|
||||
verify(pubSubCommands).ssubscribe(RedisMessageAvailabilityManager.getClientEventChannel(secondAccountIdentifier, secondDeviceId));
|
||||
verify(pubSubCommands, never()).ssubscribe(RedisMessageAvailabilityManager.getClientEventChannel(firstAccountIdentifier, firstDeviceId));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -311,9 +245,7 @@ class WebSocketConnectionEventManagerTest {
|
||||
.binaryPubSubAsyncCommands(pubSubAsyncCommands)
|
||||
.build();
|
||||
|
||||
final WebSocketConnectionEventManager eventManager = new WebSocketConnectionEventManager(
|
||||
mock(AccountsManager.class),
|
||||
mock(PushNotificationManager.class),
|
||||
final RedisMessageAvailabilityManager eventManager = new RedisMessageAvailabilityManager(
|
||||
clusterClient,
|
||||
Runnable::run,
|
||||
Runnable::run);
|
||||
@@ -326,76 +258,20 @@ class WebSocketConnectionEventManagerTest {
|
||||
final UUID noListenerAccountIdentifier = UUID.randomUUID();
|
||||
final byte noListenerDeviceId = listenerDeviceId + 1;
|
||||
|
||||
eventManager.handleClientConnected(listenerAccountIdentifier, listenerDeviceId, new WebSocketConnectionEventAdapter())
|
||||
eventManager.handleClientConnected(listenerAccountIdentifier, listenerDeviceId, new MessageAvailabilityAdapter())
|
||||
.toCompletableFuture()
|
||||
.join();
|
||||
|
||||
eventManager.unsubscribeIfMissingListener(
|
||||
new WebSocketConnectionEventManager.AccountAndDeviceIdentifier(listenerAccountIdentifier, listenerDeviceId));
|
||||
new RedisMessageAvailabilityManager.AccountAndDeviceIdentifier(listenerAccountIdentifier, listenerDeviceId));
|
||||
|
||||
eventManager.unsubscribeIfMissingListener(
|
||||
new WebSocketConnectionEventManager.AccountAndDeviceIdentifier(noListenerAccountIdentifier, noListenerDeviceId));
|
||||
new RedisMessageAvailabilityManager.AccountAndDeviceIdentifier(noListenerAccountIdentifier, noListenerDeviceId));
|
||||
|
||||
verify(pubSubAsyncCommands, never())
|
||||
.sunsubscribe(WebSocketConnectionEventManager.getClientEventChannel(listenerAccountIdentifier, listenerDeviceId));
|
||||
.sunsubscribe(RedisMessageAvailabilityManager.getClientEventChannel(listenerAccountIdentifier, listenerDeviceId));
|
||||
|
||||
verify(pubSubAsyncCommands)
|
||||
.sunsubscribe(WebSocketConnectionEventManager.getClientEventChannel(noListenerAccountIdentifier, noListenerDeviceId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void newMessageNotificationWithoutListener() throws NotPushRegisteredException {
|
||||
final UUID listenerAccountIdentifier = UUID.randomUUID();
|
||||
final byte listenerDeviceId = Device.PRIMARY_ID;
|
||||
|
||||
final UUID noListenerAccountIdentifier = UUID.randomUUID();
|
||||
final byte noListenerDeviceId = listenerDeviceId + 1;
|
||||
|
||||
final Account noListenerAccount = mock(Account.class);
|
||||
|
||||
final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
|
||||
when(accountsManager.getByAccountIdentifierAsync(noListenerAccountIdentifier))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(noListenerAccount)));
|
||||
|
||||
final PushNotificationManager pushNotificationManager = mock(PushNotificationManager.class);
|
||||
|
||||
@SuppressWarnings("unchecked") final RedisClusterPubSubAsyncCommands<byte[], byte[]> pubSubAsyncCommands =
|
||||
mock(RedisClusterPubSubAsyncCommands.class);
|
||||
|
||||
when(pubSubAsyncCommands.ssubscribe(any())).thenReturn(MockRedisFuture.completedFuture(null));
|
||||
|
||||
final FaultTolerantRedisClusterClient clusterClient = RedisClusterHelper.builder()
|
||||
.binaryPubSubAsyncCommands(pubSubAsyncCommands)
|
||||
.build();
|
||||
|
||||
final WebSocketConnectionEventManager eventManager = new WebSocketConnectionEventManager(
|
||||
accountsManager,
|
||||
pushNotificationManager,
|
||||
clusterClient,
|
||||
Runnable::run,
|
||||
Runnable::run);
|
||||
|
||||
eventManager.start();
|
||||
|
||||
eventManager.handleClientConnected(listenerAccountIdentifier, listenerDeviceId, new WebSocketConnectionEventAdapter())
|
||||
.toCompletableFuture()
|
||||
.join();
|
||||
|
||||
final byte[] newMessagePayload = ClientEvent.newBuilder()
|
||||
.setNewMessageAvailable(NewMessageAvailableEvent.getDefaultInstance())
|
||||
.build()
|
||||
.toByteArray();
|
||||
|
||||
eventManager.smessage(mock(RedisClusterNode.class),
|
||||
WebSocketConnectionEventManager.getClientEventChannel(listenerAccountIdentifier, listenerDeviceId),
|
||||
newMessagePayload);
|
||||
|
||||
eventManager.smessage(mock(RedisClusterNode.class),
|
||||
WebSocketConnectionEventManager.getClientEventChannel(noListenerAccountIdentifier, noListenerDeviceId),
|
||||
newMessagePayload);
|
||||
|
||||
verify(pushNotificationManager).sendNewMessageNotification(noListenerAccount, noListenerDeviceId, true);
|
||||
verifyNoMoreInteractions(pushNotificationManager);
|
||||
.sunsubscribe(RedisMessageAvailabilityManager.getClientEventChannel(noListenerAccountIdentifier, noListenerDeviceId));
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -135,7 +135,7 @@ class SecureValueRecoveryClientTest {
|
||||
final String username = RandomStringUtils.secure().nextAlphabetic(16);
|
||||
final String password = RandomStringUtils.secure().nextAlphanumeric(32);
|
||||
|
||||
when(credentialsGenerator.generateForUuid(accountUuid)).thenReturn(
|
||||
when(credentialsGenerator.generateFor(accountUuid.toString())).thenReturn(
|
||||
new ExternalServiceCredentials(username, password));
|
||||
|
||||
wireMock.stubFor(delete(urlEqualTo(SecureValueRecoveryClient.DELETE_PATH))
|
||||
|
||||
+7
-6
@@ -8,6 +8,7 @@ import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -136,7 +137,7 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
when(secureStorageClient.deleteStoredData(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final SecureValueRecoveryClient svr2Client = mock(SecureValueRecoveryClient.class);
|
||||
when(svr2Client.removeData(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(svr2Client.removeData(any(UUID.class))).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers =
|
||||
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
|
||||
@@ -168,7 +169,6 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
profilesManager,
|
||||
secureStorageClient,
|
||||
svr2Client,
|
||||
svr2Client,
|
||||
disconnectionRequestManager,
|
||||
registrationRecoveryPasswordsManager,
|
||||
clientPublicKeysManager,
|
||||
@@ -314,7 +314,7 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
final KEMSignedPreKey aciPqLastResortPreKey = KeysHelper.signedKEMPreKey(3, aciKeyPair);
|
||||
final KEMSignedPreKey pniPqLastResortPreKey = KeysHelper.signedKEMPreKey(4, pniKeyPair);
|
||||
|
||||
final Account originalAccount = accountsManager.create(number,
|
||||
final Account existingAccount = accountsManager.create(number,
|
||||
new AccountAttributes(true, 1, 1, "name".getBytes(StandardCharsets.UTF_8), "registration-lock", false, Set.of()),
|
||||
Collections.emptyList(),
|
||||
new IdentityKey(aciKeyPair.getPublicKey()),
|
||||
@@ -334,7 +334,7 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
pniPqLastResortPreKey),
|
||||
null);
|
||||
|
||||
existingAccountUuid = originalAccount.getUuid();
|
||||
existingAccountUuid = existingAccount.getUuid();
|
||||
}
|
||||
|
||||
final String password = RandomStringUtils.secure().nextAlphanumeric(16);
|
||||
@@ -417,7 +417,8 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
|
||||
assertEquals(existingAccountUuid, reregisteredAccount.getUuid());
|
||||
|
||||
verify(disconnectionRequestManager).requestDisconnection(existingAccountUuid);
|
||||
verify(disconnectionRequestManager).requestDisconnection(argThat(account ->
|
||||
account.getIdentifier(IdentityType.ACI).equals(existingAccountUuid) && account != reregisteredAccount));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -492,7 +493,7 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
assertFalse(keysManager.getLastResort(account.getPhoneNumberIdentifier(), Device.PRIMARY_ID).join().isPresent());
|
||||
assertFalse(clientPublicKeysManager.findPublicKey(account.getUuid(), Device.PRIMARY_ID).join().isPresent());
|
||||
|
||||
verify(disconnectionRequestManager).requestDisconnection(aci);
|
||||
verify(disconnectionRequestManager).requestDisconnection(account);
|
||||
}
|
||||
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
|
||||
+4
-3
@@ -10,6 +10,7 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -127,7 +128,7 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
when(secureStorageClient.deleteStoredData(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final SecureValueRecoveryClient svr2Client = mock(SecureValueRecoveryClient.class);
|
||||
when(svr2Client.removeData(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(svr2Client.removeData(any(UUID.class))).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
disconnectionRequestManager = mock(DisconnectionRequestManager.class);
|
||||
|
||||
@@ -157,7 +158,6 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
profilesManager,
|
||||
secureStorageClient,
|
||||
svr2Client,
|
||||
svr2Client,
|
||||
disconnectionRequestManager,
|
||||
registrationRecoveryPasswordsManager,
|
||||
clientPublicKeysManager,
|
||||
@@ -350,7 +350,8 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
|
||||
assertEquals(secondNumber, accountsManager.getByAccountIdentifier(originalUuid).map(Account::getNumber).orElseThrow());
|
||||
|
||||
verify(disconnectionRequestManager).requestDisconnection(existingAccountUuid);
|
||||
verify(disconnectionRequestManager).requestDisconnection(argThat(disconnectedAccount ->
|
||||
disconnectedAccount.getIdentifier(IdentityType.ACI).equals(existingAccountUuid) && disconnectedAccount != account));
|
||||
|
||||
assertEquals(Optional.of(existingAccountUuid), accountsManager.findRecentlyDeletedAccountIdentifier(originalPni));
|
||||
assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(secondPni));
|
||||
|
||||
-1
@@ -135,7 +135,6 @@ class AccountsManagerConcurrentModificationIntegrationTest {
|
||||
mock(ProfilesManager.class),
|
||||
mock(SecureStorageClient.class),
|
||||
mock(SecureValueRecoveryClient.class),
|
||||
mock(SecureValueRecoveryClient.class),
|
||||
mock(DisconnectionRequestManager.class),
|
||||
mock(RegistrationRecoveryPasswordsManager.class),
|
||||
mock(ClientPublicKeysManager.class),
|
||||
|
||||
+81
-24
@@ -11,6 +11,9 @@ import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
|
||||
import org.whispersystems.textsecuregcm.entities.RemoteAttachmentError;
|
||||
import org.whispersystems.textsecuregcm.entities.RestoreAccountRequest;
|
||||
@@ -28,6 +31,7 @@ import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
@@ -69,7 +73,6 @@ public class AccountsManagerDeviceTransferIntegrationTest {
|
||||
mock(ProfilesManager.class),
|
||||
mock(SecureStorageClient.class),
|
||||
mock(SecureValueRecoveryClient.class),
|
||||
mock(SecureValueRecoveryClient.class),
|
||||
mock(DisconnectionRequestManager.class),
|
||||
mock(RegistrationRecoveryPasswordsManager.class),
|
||||
mock(ClientPublicKeysManager.class),
|
||||
@@ -87,18 +90,22 @@ public class AccountsManagerDeviceTransferIntegrationTest {
|
||||
accountsManager.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
void waitForTransferArchive() {
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
void waitForTransferArchive(
|
||||
final Optional<Long> recordUploadDeviceCreated,
|
||||
final Optional<Integer> recordUploadRegistrationId) {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
final long deviceCreated = System.currentTimeMillis();
|
||||
|
||||
final RemoteAttachment transferArchive =
|
||||
new RemoteAttachment(3, Base64.getUrlEncoder().encodeToString("transfer-archive".getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getId()).thenReturn(deviceId);
|
||||
when(device.getCreated()).thenReturn(deviceCreated);
|
||||
when(device.getCreated()).thenReturn(recordUploadDeviceCreated.orElse(System.currentTimeMillis()));
|
||||
when(device.getRegistrationId(IdentityType.ACI)).thenReturn(recordUploadRegistrationId.orElse(1));
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
|
||||
@@ -111,66 +118,106 @@ public class AccountsManagerDeviceTransferIntegrationTest {
|
||||
|
||||
assertEquals(Optional.empty(), displacedFuture.join());
|
||||
|
||||
accountsManager.recordTransferArchiveUpload(account, deviceId, Instant.ofEpochMilli(deviceCreated), transferArchive).join();
|
||||
accountsManager.recordTransferArchiveUpload(account, deviceId, recordUploadDeviceCreated.map(Instant::ofEpochMilli), recordUploadRegistrationId, transferArchive).join();
|
||||
|
||||
assertEquals(Optional.of(transferArchive), activeFuture.join());
|
||||
}
|
||||
|
||||
@Test
|
||||
void waitForTransferArchiveAlreadyAdded() {
|
||||
private static List<Arguments> waitForTransferArchive() {
|
||||
final long deviceCreated = System.currentTimeMillis();
|
||||
final int registrationId = 123;
|
||||
|
||||
return List.of(
|
||||
Arguments.of(Optional.empty(), Optional.of(registrationId)),
|
||||
Arguments.of(Optional.of(deviceCreated), Optional.empty())
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
void waitForTransferArchiveAlreadyAdded(
|
||||
final Optional<Long> recordUploadDeviceCreated,
|
||||
final Optional<Integer> recordUploadRegistrationId) {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
final long deviceCreated = System.currentTimeMillis();
|
||||
|
||||
|
||||
final RemoteAttachment transferArchive =
|
||||
new RemoteAttachment(3, Base64.getUrlEncoder().encodeToString("transfer-archive".getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getId()).thenReturn(deviceId);
|
||||
when(device.getCreated()).thenReturn(deviceCreated);
|
||||
when(device.getCreated()).thenReturn(recordUploadDeviceCreated.orElse(System.currentTimeMillis()));
|
||||
when(device.getRegistrationId(IdentityType.ACI)).thenReturn(recordUploadRegistrationId.orElse(1));
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
|
||||
|
||||
accountsManager.recordTransferArchiveUpload(account, deviceId, Instant.ofEpochMilli(deviceCreated), transferArchive).join();
|
||||
accountsManager.recordTransferArchiveUpload(account, deviceId, recordUploadDeviceCreated.map(Instant::ofEpochMilli), recordUploadRegistrationId, transferArchive).join();
|
||||
|
||||
assertEquals(Optional.of(transferArchive),
|
||||
accountsManager.waitForTransferArchive(account, device, Duration.ofSeconds(5)).join());
|
||||
}
|
||||
|
||||
@Test
|
||||
void waitForErrorTransferArchive() {
|
||||
private static List<Arguments> waitForTransferArchiveAlreadyAdded() {
|
||||
final long deviceCreated = System.currentTimeMillis();
|
||||
final int registrationId = 123;
|
||||
|
||||
return List.of(
|
||||
Arguments.of(Optional.empty(), Optional.of(registrationId)),
|
||||
Arguments.of(Optional.of(deviceCreated), Optional.empty())
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
void waitForErrorTransferArchive(
|
||||
final Optional<Long> recordUploadDeviceCreated,
|
||||
final Optional<Integer> recordUploadRegistrationId) {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
final long deviceCreated = System.currentTimeMillis();
|
||||
|
||||
final RemoteAttachmentError transferArchiveError =
|
||||
new RemoteAttachmentError(RemoteAttachmentError.ErrorType.CONTINUE_WITHOUT_UPLOAD);
|
||||
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getId()).thenReturn(deviceId);
|
||||
when(device.getCreated()).thenReturn(deviceCreated);
|
||||
when(device.getCreated()).thenReturn(recordUploadDeviceCreated.orElse(System.currentTimeMillis()));
|
||||
when(device.getRegistrationId(IdentityType.ACI)).thenReturn(recordUploadRegistrationId.orElse(1));
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
|
||||
|
||||
accountsManager
|
||||
.recordTransferArchiveUpload(account, deviceId, Instant.ofEpochMilli(deviceCreated), transferArchiveError)
|
||||
.join();
|
||||
accountsManager.recordTransferArchiveUpload(account, deviceId, recordUploadDeviceCreated.map(Instant::ofEpochMilli),
|
||||
recordUploadRegistrationId, transferArchiveError).join();
|
||||
|
||||
assertEquals(Optional.of(transferArchiveError),
|
||||
accountsManager.waitForTransferArchive(account, device, Duration.ofSeconds(5)).join());
|
||||
}
|
||||
|
||||
@Test
|
||||
void waitForTransferArchiveTimeout() {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
private static List<Arguments> waitForErrorTransferArchive() {
|
||||
final long deviceCreated = System.currentTimeMillis();
|
||||
final int registrationId = 123;
|
||||
|
||||
return List.of(
|
||||
Arguments.of(Optional.empty(), Optional.of(registrationId)),
|
||||
Arguments.of(Optional.of(deviceCreated), Optional.empty())
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
void waitForTransferArchiveTimeout(
|
||||
final Optional<Long> recordUploadDeviceCreated,
|
||||
final Optional<Integer> recordUploadRegistrationId) {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getId()).thenReturn(deviceId);
|
||||
when(device.getCreated()).thenReturn(deviceCreated);
|
||||
when(device.getCreated()).thenReturn(recordUploadDeviceCreated.orElse(System.currentTimeMillis()));
|
||||
when(device.getRegistrationId(IdentityType.ACI)).thenReturn(recordUploadRegistrationId.orElse(1));
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
|
||||
@@ -179,6 +226,16 @@ public class AccountsManagerDeviceTransferIntegrationTest {
|
||||
accountsManager.waitForTransferArchive(account, device, Duration.ofMillis(1)).join());
|
||||
}
|
||||
|
||||
private static List<Arguments> waitForTransferArchiveTimeout() {
|
||||
final long deviceCreated = System.currentTimeMillis();
|
||||
final int registrationId = 123;
|
||||
|
||||
return List.of(
|
||||
Arguments.of(Optional.empty(), Optional.of(registrationId)),
|
||||
Arguments.of(Optional.of(deviceCreated), Optional.empty())
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void waitForRestoreAccountRequest() {
|
||||
final String token = RandomStringUtils.secure().nextAlphanumeric(16);
|
||||
|
||||
+62
-8
@@ -57,6 +57,7 @@ import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Stream;
|
||||
@@ -82,6 +83,8 @@ import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.RemoteAttachment;
|
||||
import org.whispersystems.textsecuregcm.entities.TransferArchiveResult;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
@@ -131,7 +134,6 @@ class AccountsManagerTest {
|
||||
private RedisAdvancedClusterAsyncCommands<String, String> asyncClusterCommands;
|
||||
private AccountsManager accountsManager;
|
||||
private SecureValueRecoveryClient svr2Client;
|
||||
private SecureValueRecoveryClient svrbClient;
|
||||
private DynamicConfiguration dynamicConfiguration;
|
||||
|
||||
private static final Answer<?> ACCOUNT_UPDATE_ANSWER = (answer) -> {
|
||||
@@ -190,13 +192,10 @@ class AccountsManagerTest {
|
||||
}).when(accounts).changeNumber(any(), anyString(), any(), any(), any());
|
||||
|
||||
final SecureStorageClient storageClient = mock(SecureStorageClient.class);
|
||||
when(storageClient.deleteStoredData(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(storageClient.deleteStoredData(any(UUID.class))).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
svr2Client = mock(SecureValueRecoveryClient.class);
|
||||
when(svr2Client.removeData(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
svrbClient = mock(SecureValueRecoveryClient.class);
|
||||
when(svrbClient.removeData(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(svr2Client.removeData(any(UUID.class))).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers = mock(PhoneNumberIdentifiers.class);
|
||||
phoneNumberIdentifiersByE164 = new HashMap<>();
|
||||
@@ -256,7 +255,6 @@ class AccountsManagerTest {
|
||||
profilesManager,
|
||||
storageClient,
|
||||
svr2Client,
|
||||
svrbClient,
|
||||
disconnectionRequestManager,
|
||||
registrationRecoveryPasswordsManager,
|
||||
clientPublicKeysManager,
|
||||
@@ -867,7 +865,8 @@ class AccountsManagerTest {
|
||||
verify(keysManager, times(2)).deleteSingleUsePreKeys(phoneNumberIdentifiersByE164.get(e164));
|
||||
verify(messagesManager, times(2)).clear(existingUuid);
|
||||
verify(profilesManager, times(2)).deleteAll(existingUuid, false);
|
||||
verify(disconnectionRequestManager).requestDisconnection(existingUuid);
|
||||
verify(disconnectionRequestManager).requestDisconnection(argThat(account ->
|
||||
account.getIdentifier(IdentityType.ACI).equals(existingUuid) && account != reregisteredAccount));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1497,6 +1496,61 @@ class AccountsManagerTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testFirstSuccessfulTransferArchiveCompletableFutureOneTimeout() {
|
||||
// First future times out, second one completes successfully
|
||||
final RemoteAttachment transferArchive = new RemoteAttachment(3, Base64.getUrlEncoder().encodeToString("test".getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
final CompletableFuture<Optional<TransferArchiveResult>> timeoutFuture = new CompletableFuture<>();
|
||||
timeoutFuture.completeOnTimeout(Optional.empty(), 50, TimeUnit.MILLISECONDS);
|
||||
|
||||
final CompletableFuture<Optional<TransferArchiveResult>> successfulFuture = new CompletableFuture<>();
|
||||
|
||||
final CompletableFuture<Optional<TransferArchiveResult>> result =
|
||||
AccountsManager.firstSuccessfulTransferArchiveFuture(List.of(timeoutFuture, successfulFuture));
|
||||
|
||||
CompletableFuture.delayedExecutor(100, TimeUnit.MILLISECONDS)
|
||||
.execute(() -> successfulFuture.complete(Optional.of(transferArchive)));
|
||||
|
||||
final Optional<TransferArchiveResult> maybeTransferArchive = result.join();
|
||||
assertTrue(maybeTransferArchive.isPresent());
|
||||
assertEquals(transferArchive, maybeTransferArchive.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testFirstSuccessfulTransferArchiveCompletableFutureBothTimeout() {
|
||||
// Both futures time out
|
||||
final CompletableFuture<Optional<TransferArchiveResult>> firstTimeoutFuture = new CompletableFuture<>();
|
||||
firstTimeoutFuture.completeOnTimeout(Optional.empty(), 10, TimeUnit.MILLISECONDS);
|
||||
|
||||
final CompletableFuture<Optional<TransferArchiveResult>> secondTimeoutFuture = new CompletableFuture<>();
|
||||
secondTimeoutFuture.completeOnTimeout(Optional.empty(), 10, TimeUnit.MILLISECONDS);
|
||||
|
||||
final CompletableFuture<Optional<TransferArchiveResult>> result =
|
||||
AccountsManager.firstSuccessfulTransferArchiveFuture(List.of(firstTimeoutFuture, secondTimeoutFuture));
|
||||
|
||||
assertTrue(result.join().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testFirstSuccessfulTransferArchiveCompletableFuture() {
|
||||
// First future completes successfully, second one times out
|
||||
final RemoteAttachment transferArchive = new RemoteAttachment(3, Base64.getUrlEncoder().encodeToString("test".getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
final CompletableFuture<Optional<TransferArchiveResult>> successfulFuture = new CompletableFuture<>();
|
||||
|
||||
final CompletableFuture<Optional<TransferArchiveResult>> timeoutFuture = new CompletableFuture<>();
|
||||
timeoutFuture.completeOnTimeout(Optional.empty(), 50, TimeUnit.MILLISECONDS);
|
||||
|
||||
final CompletableFuture<Optional<TransferArchiveResult>> result =
|
||||
AccountsManager.firstSuccessfulTransferArchiveFuture(List.of(successfulFuture, timeoutFuture));
|
||||
successfulFuture.complete(Optional.of(transferArchive));
|
||||
|
||||
final Optional<TransferArchiveResult> maybeTransferArchive = result.join();
|
||||
assertTrue(maybeTransferArchive.isPresent());
|
||||
assertEquals(transferArchive, maybeTransferArchive.get());
|
||||
}
|
||||
|
||||
private static List<Arguments> validateCompleteDeviceList() {
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
final byte extraDeviceId = deviceId + 1;
|
||||
|
||||
-1
@@ -162,7 +162,6 @@ class AccountsManagerUsernameIntegrationTest {
|
||||
profileManager,
|
||||
mock(SecureStorageClient.class),
|
||||
mock(SecureValueRecoveryClient.class),
|
||||
mock(SecureValueRecoveryClient.class),
|
||||
disconnectionRequestManager,
|
||||
mock(RegistrationRecoveryPasswordsManager.class),
|
||||
mock(ClientPublicKeysManager.class),
|
||||
|
||||
+1
-2
@@ -136,7 +136,7 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
when(secureStorageClient.deleteStoredData(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final SecureValueRecoveryClient svr2Client = mock(SecureValueRecoveryClient.class);
|
||||
when(svr2Client.removeData(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(svr2Client.removeData(any(UUID.class))).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers =
|
||||
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
|
||||
@@ -170,7 +170,6 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
profilesManager,
|
||||
secureStorageClient,
|
||||
svr2Client,
|
||||
svr2Client,
|
||||
mock(DisconnectionRequestManager.class),
|
||||
mock(RegistrationRecoveryPasswordsManager.class),
|
||||
clientPublicKeysManager,
|
||||
|
||||
+38
-3
@@ -8,25 +8,25 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.reset;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.whispersystems.textsecuregcm.entities.ECPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
|
||||
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
@@ -48,6 +48,7 @@ class KeysManagerTest {
|
||||
static final S3LocalStackExtension S3_EXTENSION = new S3LocalStackExtension("testbucket");
|
||||
|
||||
private static final UUID ACCOUNT_UUID = UUID.randomUUID();
|
||||
private static final AciServiceIdentifier ACI_SERVICE_IDENTIFIER = new AciServiceIdentifier(ACCOUNT_UUID);
|
||||
private static final byte DEVICE_ID = 1;
|
||||
|
||||
private static final ECKeyPair IDENTITY_KEY_PAIR = ECKeyPair.generate();
|
||||
@@ -287,6 +288,40 @@ class KeysManagerTest {
|
||||
"storing new last-resort keys should overwrite old ones");
|
||||
}
|
||||
|
||||
private enum MissingKeyType {
|
||||
EC,
|
||||
SIGNED_EC,
|
||||
PQ,
|
||||
NONE
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(MissingKeyType.class)
|
||||
void testTakeWithMissingKeys(final MissingKeyType missingKeyType) {
|
||||
if (missingKeyType != MissingKeyType.PQ) {
|
||||
keysManager.storePqLastResort(ACCOUNT_UUID, DEVICE_ID, generateTestKEMSignedPreKey(1)).join();
|
||||
}
|
||||
if (missingKeyType != MissingKeyType.SIGNED_EC) {
|
||||
keysManager.storeEcSignedPreKeys(ACCOUNT_UUID, DEVICE_ID, generateTestECSignedPreKey(2)).join();
|
||||
}
|
||||
if (missingKeyType != MissingKeyType.EC) {
|
||||
keysManager.storeEcOneTimePreKeys(ACCOUNT_UUID, DEVICE_ID, List.of(generateTestPreKey(3))).join();
|
||||
}
|
||||
|
||||
final Optional<KeysManager.DevicePreKeys> keys =
|
||||
keysManager.takeDevicePreKeys(DEVICE_ID, ACI_SERVICE_IDENTIFIER, null).join();
|
||||
|
||||
assertEquals(keys.isPresent(), switch (missingKeyType) {
|
||||
// We should successfully get keys if every key is present, or if only EC one-time keys are missing
|
||||
case EC, NONE -> true;
|
||||
// If the signed EC key or the last-resort PQ key is missing, we shouldn't get keys back
|
||||
case SIGNED_EC, PQ -> false;
|
||||
});
|
||||
|
||||
final boolean hasEcPreKey = keys.flatMap(KeysManager.DevicePreKeys::ecPreKey).isPresent();
|
||||
assertEquals(hasEcPreKey, missingKeyType == MissingKeyType.NONE);
|
||||
}
|
||||
|
||||
private static ECPreKey generateTestPreKey(final long keyId) {
|
||||
return new ECPreKey(keyId, ECKeyPair.generate().getPublicKey());
|
||||
}
|
||||
|
||||
+8
-13
@@ -30,13 +30,10 @@ import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventListener;
|
||||
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
|
||||
import org.whispersystems.textsecuregcm.push.MessageAvailabilityListener;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
|
||||
import org.whispersystems.textsecuregcm.tests.util.DevicesHelper;
|
||||
@@ -59,7 +56,7 @@ class MessagePersisterIntegrationTest {
|
||||
private ExecutorService asyncOperationQueueingExecutor;
|
||||
private MessagesCache messagesCache;
|
||||
private MessagesManager messagesManager;
|
||||
private WebSocketConnectionEventManager webSocketConnectionEventManager;
|
||||
private RedisMessageAvailabilityManager redisMessageAvailabilityManager;
|
||||
private MessagePersister messagePersister;
|
||||
private Account account;
|
||||
|
||||
@@ -90,13 +87,11 @@ class MessagePersisterIntegrationTest {
|
||||
|
||||
websocketConnectionEventExecutor = Executors.newVirtualThreadPerTaskExecutor();
|
||||
asyncOperationQueueingExecutor = Executors.newSingleThreadExecutor();
|
||||
webSocketConnectionEventManager = new WebSocketConnectionEventManager(mock(AccountsManager.class),
|
||||
mock(PushNotificationManager.class),
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
redisMessageAvailabilityManager = new RedisMessageAvailabilityManager(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
websocketConnectionEventExecutor,
|
||||
asyncOperationQueueingExecutor);
|
||||
|
||||
webSocketConnectionEventManager.start();
|
||||
redisMessageAvailabilityManager.start();
|
||||
|
||||
messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager,
|
||||
dynamicConfigurationManager, PERSIST_DELAY, 1);
|
||||
@@ -127,7 +122,7 @@ class MessagePersisterIntegrationTest {
|
||||
|
||||
messageDeliveryScheduler.dispose();
|
||||
|
||||
webSocketConnectionEventManager.stop();
|
||||
redisMessageAvailabilityManager.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -156,7 +151,7 @@ class MessagePersisterIntegrationTest {
|
||||
|
||||
final AtomicBoolean messagesPersisted = new AtomicBoolean(false);
|
||||
|
||||
webSocketConnectionEventManager.handleClientConnected(account.getUuid(), Device.PRIMARY_ID, new WebSocketConnectionEventListener() {
|
||||
redisMessageAvailabilityManager.handleClientConnected(account.getUuid(), Device.PRIMARY_ID, new MessageAvailabilityListener() {
|
||||
@Override
|
||||
public void handleNewMessageAvailable() {
|
||||
}
|
||||
@@ -170,7 +165,7 @@ class MessagePersisterIntegrationTest {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleConnectionDisplaced(final boolean connectedElsewhere) {
|
||||
public void handleConflictingMessageReader() {
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
+2
-2
@@ -20,7 +20,7 @@ import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubClusterConnection;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
|
||||
@@ -100,7 +100,7 @@ class MessagesCacheInsertScriptTest {
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().createBinaryPubSubConnection();
|
||||
|
||||
pubSubClusterConnection.usePubSubConnection(connection ->
|
||||
connection.sync().ssubscribe(WebSocketConnectionEventManager.getClientEventChannel(destinationUuid, deviceId)));
|
||||
connection.sync().ssubscribe(RedisMessageAvailabilityManager.getClientEventChannel(destinationUuid, deviceId)));
|
||||
|
||||
assertTrue(insertScript.executeAsync(destinationUuid, deviceId, MessageProtos.Envelope.newBuilder()
|
||||
.setServerTimestamp(Instant.now().getEpochSecond())
|
||||
|
||||
+43
-11
@@ -22,6 +22,7 @@ import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.lettuce.core.RedisCommandTimeoutException;
|
||||
import io.lettuce.core.RedisFuture;
|
||||
import io.lettuce.core.cluster.SlotHash;
|
||||
import io.lettuce.core.cluster.api.async.RedisAdvancedClusterAsyncCommands;
|
||||
@@ -52,6 +53,7 @@ import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.stream.Collectors;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
@@ -191,17 +193,6 @@ class MessagesCacheTest {
|
||||
assertEquals(messagesToPreserve, get(DESTINATION_UUID, DESTINATION_DEVICE_ID, messageCount));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testHasMessages() {
|
||||
assertFalse(messagesCache.hasMessages(DESTINATION_UUID, DESTINATION_DEVICE_ID));
|
||||
|
||||
final UUID messageGuid = UUID.randomUUID();
|
||||
final MessageProtos.Envelope message = generateRandomMessage(messageGuid, true);
|
||||
messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message).join();
|
||||
|
||||
assertTrue(messagesCache.hasMessages(DESTINATION_UUID, DESTINATION_DEVICE_ID));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testHasMessagesAsync() {
|
||||
assertFalse(messagesCache.hasMessagesAsync(DESTINATION_UUID, DESTINATION_DEVICE_ID).join());
|
||||
@@ -781,6 +772,47 @@ class MessagesCacheTest {
|
||||
verify(asyncCommands, atLeast(1)).evalsha(any(), any(), any(byte[][].class), any(byte[][].class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRetries() {
|
||||
final List<byte[]> page = generatePage();
|
||||
|
||||
final AtomicBoolean emittedError = new AtomicBoolean(false);
|
||||
final AtomicBoolean emittedPage = new AtomicBoolean(false);
|
||||
|
||||
when(reactiveCommands.evalsha(any(), any(), any(byte[][].class), any(byte[][].class)))
|
||||
.thenReturn(Flux.defer(() -> {
|
||||
if (emittedError.compareAndSet(false, true)) {
|
||||
return Flux.error(new RedisCommandTimeoutException("Timeout"));
|
||||
} else if (emittedPage.compareAndSet(false, true)) {
|
||||
return Flux.just(page);
|
||||
}
|
||||
|
||||
return Flux.empty();
|
||||
}));
|
||||
|
||||
final AsyncCommand<?, ?, ?> removeSuccess = new AsyncCommand<>(mock(RedisCommand.class));
|
||||
removeSuccess.complete();
|
||||
|
||||
when(asyncCommands.evalsha(any(), any(), any(byte[][].class), any(byte[][].class)))
|
||||
.thenReturn((RedisFuture) removeSuccess);
|
||||
|
||||
final Publisher<?> allMessages = messagesCache.get(UUID.randomUUID(), Device.PRIMARY_ID);
|
||||
|
||||
StepVerifier.setDefaultTimeout(Duration.ofSeconds(5));
|
||||
|
||||
// async commands are used for remove(), and nothing should happen until we are subscribed
|
||||
verify(asyncCommands, never()).evalsha(any(), any(), any(byte[][].class), any(byte[][].class));
|
||||
// the reactive commands will be called once, to prep the first page fetch (but no remote request would actually be sent)
|
||||
verify(reactiveCommands, times(1)).evalsha(any(), any(), any(byte[][].class), any(byte[][].class));
|
||||
|
||||
StepVerifier.create(allMessages)
|
||||
.expectSubscription()
|
||||
.expectNextCount(page.size() / 2)
|
||||
.expectComplete()
|
||||
.log()
|
||||
.verify();
|
||||
}
|
||||
|
||||
private List<byte[]> generatePage() {
|
||||
final List<byte[]> messagesAndIds = new ArrayList<>();
|
||||
|
||||
|
||||
+3
-108
@@ -31,13 +31,13 @@ import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
@@ -69,6 +69,7 @@ import org.whispersystems.websocket.messages.WebSocketResponseMessage;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
|
||||
@Timeout(value = 30, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
|
||||
class WebSocketConnectionIntegrationTest {
|
||||
|
||||
@RegisterExtension
|
||||
@@ -78,7 +79,6 @@ class WebSocketConnectionIntegrationTest {
|
||||
static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
|
||||
|
||||
private ExecutorService sharedExecutorService;
|
||||
private ScheduledExecutorService scheduledExecutorService;
|
||||
private MessagesDynamoDb messagesDynamoDb;
|
||||
private MessagesCache messagesCache;
|
||||
private ReportMessageManager reportMessageManager;
|
||||
@@ -95,7 +95,6 @@ class WebSocketConnectionIntegrationTest {
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
sharedExecutorService = Executors.newSingleThreadExecutor();
|
||||
scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
|
||||
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
|
||||
dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(new DynamicConfiguration());
|
||||
@@ -118,10 +117,8 @@ class WebSocketConnectionIntegrationTest {
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
sharedExecutorService.shutdown();
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
sharedExecutorService.awaitTermination(2, TimeUnit.SECONDS);
|
||||
|
||||
scheduledExecutorService.shutdown();
|
||||
scheduledExecutorService.awaitTermination(2, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -140,7 +137,6 @@ class WebSocketConnectionIntegrationTest {
|
||||
account,
|
||||
device,
|
||||
webSocketClient,
|
||||
scheduledExecutorService,
|
||||
messageDeliveryScheduler,
|
||||
clientReleaseManager,
|
||||
mock(MessageDeliveryLoopMonitor.class),
|
||||
@@ -230,7 +226,6 @@ class WebSocketConnectionIntegrationTest {
|
||||
account,
|
||||
device,
|
||||
webSocketClient,
|
||||
scheduledExecutorService,
|
||||
messageDeliveryScheduler,
|
||||
clientReleaseManager,
|
||||
mock(MessageDeliveryLoopMonitor.class),
|
||||
@@ -290,106 +285,6 @@ class WebSocketConnectionIntegrationTest {
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessStoredMessagesSendFutureTimeout() {
|
||||
final WebSocketConnection webSocketConnection = new WebSocketConnection(
|
||||
mock(ReceiptSender.class),
|
||||
new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager, sharedExecutorService, Clock.systemUTC()),
|
||||
new MessageMetrics(),
|
||||
mock(PushNotificationManager.class),
|
||||
mock(PushNotificationScheduler.class),
|
||||
account,
|
||||
device,
|
||||
webSocketClient,
|
||||
100, // use a very short timeout, so that this test completes quickly
|
||||
scheduledExecutorService,
|
||||
messageDeliveryScheduler,
|
||||
clientReleaseManager,
|
||||
mock(MessageDeliveryLoopMonitor.class),
|
||||
mock(ExperimentEnrollmentManager.class));
|
||||
|
||||
final int persistedMessageCount = 207;
|
||||
final int cachedMessageCount = 173;
|
||||
|
||||
final List<MessageProtos.Envelope> expectedMessages = new ArrayList<>(persistedMessageCount + cachedMessageCount);
|
||||
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(15), () -> {
|
||||
|
||||
{
|
||||
final List<MessageProtos.Envelope> persistedMessages = new ArrayList<>(persistedMessageCount);
|
||||
|
||||
for (int i = 0; i < persistedMessageCount; i++) {
|
||||
final MessageProtos.Envelope envelope = generateRandomMessage(UUID.randomUUID());
|
||||
persistedMessages.add(envelope);
|
||||
expectedMessages.add(envelope);
|
||||
}
|
||||
|
||||
messagesDynamoDb.store(persistedMessages, account.getIdentifier(IdentityType.ACI), device);
|
||||
}
|
||||
|
||||
for (int i = 0; i < cachedMessageCount; i++) {
|
||||
final UUID messageGuid = UUID.randomUUID();
|
||||
final MessageProtos.Envelope envelope = generateRandomMessage(messageGuid);
|
||||
messagesCache.insert(messageGuid, account.getIdentifier(IdentityType.ACI), device.getId(), envelope).join();
|
||||
|
||||
expectedMessages.add(envelope);
|
||||
}
|
||||
|
||||
final WebSocketResponseMessage successResponse = mock(WebSocketResponseMessage.class);
|
||||
when(successResponse.getStatus()).thenReturn(200);
|
||||
|
||||
final CompletableFuture<WebSocketResponseMessage> neverCompleting = new CompletableFuture<>();
|
||||
|
||||
// for the first message, return a future that never completes
|
||||
when(webSocketClient.sendRequest(eq("PUT"), eq("/api/v1/message"), anyList(), any()))
|
||||
.thenReturn(neverCompleting)
|
||||
.thenReturn(CompletableFuture.completedFuture(successResponse));
|
||||
|
||||
when(webSocketClient.isOpen()).thenReturn(true);
|
||||
|
||||
final AtomicBoolean queueCleared = new AtomicBoolean(false);
|
||||
|
||||
when(webSocketClient.sendRequest(eq("PUT"), eq("/api/v1/queue/empty"), anyList(), any())).thenAnswer(
|
||||
(Answer<CompletableFuture<WebSocketResponseMessage>>) invocation -> {
|
||||
synchronized (queueCleared) {
|
||||
queueCleared.set(true);
|
||||
queueCleared.notifyAll();
|
||||
}
|
||||
|
||||
return CompletableFuture.completedFuture(successResponse);
|
||||
});
|
||||
|
||||
webSocketConnection.processStoredMessages();
|
||||
|
||||
synchronized (queueCleared) {
|
||||
while (!queueCleared.get()) {
|
||||
queueCleared.wait();
|
||||
}
|
||||
}
|
||||
|
||||
//noinspection unchecked
|
||||
ArgumentCaptor<Optional<byte[]>> messageBodyCaptor = ArgumentCaptor.forClass(Optional.class);
|
||||
|
||||
// We expect all of the messages from both pools to be sent, plus one for the future that times out
|
||||
verify(webSocketClient, atMost(persistedMessageCount + cachedMessageCount + 1)).sendRequest(eq("PUT"),
|
||||
eq("/api/v1/message"), anyList(), messageBodyCaptor.capture());
|
||||
|
||||
verify(webSocketClient).sendRequest(eq("PUT"), eq("/api/v1/queue/empty"), anyList(), eq(Optional.empty()));
|
||||
|
||||
final List<MessageProtos.Envelope> sentMessages = messageBodyCaptor.getAllValues().stream()
|
||||
.map(Optional::get)
|
||||
.map(messageBytes -> {
|
||||
try {
|
||||
return Envelope.parseFrom(messageBytes);
|
||||
} catch (InvalidProtocolBufferException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}).toList();
|
||||
|
||||
assertTrue(expectedMessages.containsAll(sentMessages));
|
||||
});
|
||||
}
|
||||
|
||||
private MessageProtos.Envelope generateRandomMessage(final UUID messageGuid) {
|
||||
final long timestamp = serialTimestamp++;
|
||||
|
||||
|
||||
+15
-20
@@ -15,7 +15,6 @@ import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.nullable;
|
||||
import static org.mockito.Mockito.any;
|
||||
import static org.mockito.Mockito.anyInt;
|
||||
import static org.mockito.Mockito.anyLong;
|
||||
import static org.mockito.Mockito.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
@@ -42,8 +41,6 @@ import java.util.Queue;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.stream.IntStream;
|
||||
@@ -55,6 +52,7 @@ import org.junit.jupiter.api.Test;
|
||||
import org.mockito.stubbing.Answer;
|
||||
import org.whispersystems.textsecuregcm.auth.AccountAuthenticator;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
@@ -63,7 +61,7 @@ import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
|
||||
@@ -94,7 +92,6 @@ class WebSocketConnectionTest {
|
||||
private UpgradeRequest upgradeRequest;
|
||||
private MessagesManager messagesManager;
|
||||
private ReceiptSender receiptSender;
|
||||
private ScheduledExecutorService retrySchedulingExecutor;
|
||||
private Scheduler messageDeliveryScheduler;
|
||||
private ClientReleaseManager clientReleaseManager;
|
||||
|
||||
@@ -107,7 +104,6 @@ class WebSocketConnectionTest {
|
||||
upgradeRequest = mock(UpgradeRequest.class);
|
||||
messagesManager = mock(MessagesManager.class);
|
||||
receiptSender = mock(ReceiptSender.class);
|
||||
retrySchedulingExecutor = mock(ScheduledExecutorService.class);
|
||||
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
|
||||
clientReleaseManager = mock(ClientReleaseManager.class);
|
||||
}
|
||||
@@ -124,7 +120,7 @@ class WebSocketConnectionTest {
|
||||
new WebSocketAccountAuthenticator(accountAuthenticator);
|
||||
AuthenticatedConnectListener connectListener = new AuthenticatedConnectListener(accountsManager, receiptSender, messagesManager,
|
||||
new MessageMetrics(), mock(PushNotificationManager.class), mock(PushNotificationScheduler.class),
|
||||
mock(WebSocketConnectionEventManager.class), retrySchedulingExecutor,
|
||||
mock(RedisMessageAvailabilityManager.class), mock(DisconnectionRequestManager.class),
|
||||
messageDeliveryScheduler, clientReleaseManager, mock(MessageDeliveryLoopMonitor.class),
|
||||
mock(ExperimentEnrollmentManager.class));
|
||||
WebSocketSessionContext sessionContext = mock(WebSocketSessionContext.class);
|
||||
@@ -627,10 +623,18 @@ class WebSocketConnectionTest {
|
||||
}
|
||||
|
||||
private WebSocketConnection webSocketConnection(final WebSocketClient client) {
|
||||
return new WebSocketConnection(receiptSender, messagesManager, new MessageMetrics(),
|
||||
mock(PushNotificationManager.class), mock(PushNotificationScheduler.class), account, device, client,
|
||||
retrySchedulingExecutor, Schedulers.immediate(), clientReleaseManager,
|
||||
mock(MessageDeliveryLoopMonitor.class), mock(ExperimentEnrollmentManager.class));
|
||||
return new WebSocketConnection(receiptSender,
|
||||
messagesManager,
|
||||
new MessageMetrics(),
|
||||
mock(PushNotificationManager.class),
|
||||
mock(PushNotificationScheduler.class),
|
||||
account,
|
||||
device,
|
||||
client,
|
||||
Schedulers.immediate(),
|
||||
clientReleaseManager,
|
||||
mock(MessageDeliveryLoopMonitor.class),
|
||||
mock(ExperimentEnrollmentManager.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -787,20 +791,12 @@ class WebSocketConnectionTest {
|
||||
when(messagesManager.getMessagesForDeviceReactive(account.getIdentifier(IdentityType.ACI), device, false))
|
||||
.thenReturn(Flux.error(new RedisException("OH NO")));
|
||||
|
||||
when(retrySchedulingExecutor.schedule(any(Runnable.class), anyLong(), any())).thenAnswer(
|
||||
(Answer<ScheduledFuture<?>>) invocation -> {
|
||||
invocation.getArgument(0, Runnable.class).run();
|
||||
return mock(ScheduledFuture.class);
|
||||
});
|
||||
|
||||
final WebSocketClient client = mock(WebSocketClient.class);
|
||||
when(client.isOpen()).thenReturn(true);
|
||||
|
||||
WebSocketConnection connection = webSocketConnection(client);
|
||||
connection.start();
|
||||
|
||||
verify(retrySchedulingExecutor, times(WebSocketConnection.MAX_CONSECUTIVE_RETRIES)).schedule(any(Runnable.class),
|
||||
anyLong(), any());
|
||||
verify(client).close(eq(1011), anyString());
|
||||
}
|
||||
|
||||
@@ -822,7 +818,6 @@ class WebSocketConnectionTest {
|
||||
WebSocketConnection connection = webSocketConnection(client);
|
||||
connection.start();
|
||||
|
||||
verify(retrySchedulingExecutor, never()).schedule(any(Runnable.class), anyLong(), any());
|
||||
verify(client, never()).close(anyInt(), anyString());
|
||||
}
|
||||
|
||||
|
||||
+70
-37
@@ -6,29 +6,31 @@
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.EncryptDeviceCreationTimestampUtil;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.DevicesHelper;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
import reactor.core.publisher.Flux;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyByte;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -47,6 +49,7 @@ public class EncryptDeviceCreationTimestampCommandTest {
|
||||
|
||||
namespace = mock(Namespace.class);
|
||||
when(namespace.getBoolean(EncryptDeviceCreationTimestampCommand.DRY_RUN_ARGUMENT)).thenReturn(isDryRun);
|
||||
when(namespace.getInt(EncryptDeviceCreationTimestampCommand.BUFFER_ARGUMENT)).thenReturn(5);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -63,44 +66,74 @@ public class EncryptDeviceCreationTimestampCommandTest {
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void crawlAccounts(final boolean isDryRun) {
|
||||
final Account account = mock(Account.class);
|
||||
final Device device = mock(Device.class);
|
||||
final String number = "+14152222222";
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
|
||||
final IdentityKey identityKey = new IdentityKey(ECKeyPair.generate().getPublicKey());
|
||||
final byte deviceId = (byte) 1;
|
||||
final long createdAt = System.currentTimeMillis();
|
||||
final int registrationId = 123;
|
||||
|
||||
when(account.getDevices()).thenReturn(List.of(device));
|
||||
when(account.getIdentityKey(IdentityType.ACI)).thenReturn(identityKey);
|
||||
when(device.getCreated()).thenReturn(createdAt);
|
||||
when(device.getId()).thenReturn(deviceId);
|
||||
when(device.getRegistrationId(IdentityType.ACI)).thenReturn(registrationId);
|
||||
final Account testAccount = AccountsHelper.generateTestAccount(number, uuid, UUID.randomUUID(), List.of(
|
||||
DevicesHelper.createDevice(Device.PRIMARY_ID)), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
|
||||
testAccount.setIdentityKey(new IdentityKey(ECKeyPair.generate().getPublicKey()));
|
||||
|
||||
final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
when(accountsManager.updateDeviceAsync(any(), anyByte(), any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(accountsManager.updateAsync(any(), any())).thenAnswer(invocation -> {
|
||||
final Account account = invocation.getArgument(0);
|
||||
final Consumer<Account> updater = invocation.getArgument(1);
|
||||
updater.accept(account);
|
||||
return CompletableFuture.completedFuture(account);
|
||||
});
|
||||
|
||||
final EncryptDeviceCreationTimestampCommand encryptDeviceCreationTimestampCommand =
|
||||
new TestEncryptDeviceCreationTimestampCommand(accountsManager, isDryRun);
|
||||
|
||||
try (MockedStatic<EncryptDeviceCreationTimestampUtil> mockUtil = mockStatic(EncryptDeviceCreationTimestampUtil.class)) {
|
||||
mockUtil.when(() -> EncryptDeviceCreationTimestampUtil.encrypt(anyLong(), any(), anyByte(), anyInt()))
|
||||
.thenReturn(TestRandomUtil.nextBytes(56));
|
||||
encryptDeviceCreationTimestampCommand.crawlAccounts(Flux.just(testAccount));
|
||||
|
||||
encryptDeviceCreationTimestampCommand.crawlAccounts(Flux.just(account));
|
||||
|
||||
mockUtil.verify(() -> EncryptDeviceCreationTimestampUtil.encrypt(
|
||||
eq(createdAt),
|
||||
eq(identityKey),
|
||||
eq(deviceId),
|
||||
eq(registrationId)
|
||||
));
|
||||
|
||||
if (isDryRun) {
|
||||
verify(accountsManager, never()).updateDeviceAsync(any(), anyByte(), any());
|
||||
} else {
|
||||
verify(accountsManager).updateDeviceAsync(eq(account), eq(deviceId), any());
|
||||
}
|
||||
if (isDryRun) {
|
||||
verify(accountsManager, never()).updateAsync(any(), any());
|
||||
assertNull(testAccount.getDevices().getFirst().getCreatedAtCiphertext());
|
||||
} else {
|
||||
verify(accountsManager).updateAsync(eq(testAccount), any());
|
||||
assertNotNull(testAccount.getDevices().getFirst().getCreatedAtCiphertext());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void crawlAccountsWithEncryptedTimestamps() {
|
||||
final Account unencryptedTimestampAccount = AccountsHelper.generateTestAccount("+14152222222", UUID.randomUUID(), UUID.randomUUID(), List.of(
|
||||
DevicesHelper.createDevice(Device.PRIMARY_ID)), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
|
||||
unencryptedTimestampAccount.setIdentityKey(new IdentityKey(ECKeyPair.generate().getPublicKey()));
|
||||
|
||||
final Account encryptedTimestampAccount = AccountsHelper.generateTestAccount("+14152222223", UUID.randomUUID(), UUID.randomUUID(), List.of(
|
||||
DevicesHelper.createDevice(Device.PRIMARY_ID)), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
|
||||
encryptedTimestampAccount.setIdentityKey(new IdentityKey(ECKeyPair.generate().getPublicKey()));
|
||||
encryptedTimestampAccount.getDevices().getFirst().setCreatedAtCiphertext(TestRandomUtil.nextBytes(56));
|
||||
|
||||
final Account halfEncryptedTimestampAccount = AccountsHelper.generateTestAccount("+14152222224", UUID.randomUUID(), UUID.randomUUID(), List.of(
|
||||
DevicesHelper.createDevice(Device.PRIMARY_ID), DevicesHelper.createDevice((byte) 2)), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
|
||||
halfEncryptedTimestampAccount.setIdentityKey(new IdentityKey(ECKeyPair.generate().getPublicKey()));
|
||||
halfEncryptedTimestampAccount.getDevices().getFirst().setCreatedAtCiphertext(TestRandomUtil.nextBytes(56));
|
||||
|
||||
final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
when(accountsManager.updateAsync(any(), any())).thenAnswer(invocation -> {
|
||||
final Account account = invocation.getArgument(0);
|
||||
final Consumer<Account> updater = invocation.getArgument(1);
|
||||
updater.accept(account);
|
||||
return CompletableFuture.completedFuture(account);
|
||||
});
|
||||
|
||||
final EncryptDeviceCreationTimestampCommand encryptDeviceCreationTimestampCommand =
|
||||
new TestEncryptDeviceCreationTimestampCommand(accountsManager, false);
|
||||
|
||||
assertNull(unencryptedTimestampAccount.getDevices().getFirst().getCreatedAtCiphertext());
|
||||
assertNull(halfEncryptedTimestampAccount.getDevices().get(1).getCreatedAtCiphertext());
|
||||
|
||||
encryptDeviceCreationTimestampCommand.crawlAccounts(Flux.just(unencryptedTimestampAccount,
|
||||
encryptedTimestampAccount,
|
||||
halfEncryptedTimestampAccount));
|
||||
|
||||
verify(accountsManager, times(1)).updateAsync(eq(unencryptedTimestampAccount), any());
|
||||
verify(accountsManager, never()).updateAsync(eq(encryptedTimestampAccount), any());
|
||||
verify(accountsManager, times(1)).updateAsync(eq(halfEncryptedTimestampAccount), any());
|
||||
|
||||
assertNotNull(unencryptedTimestampAccount.getDevices().getFirst().getCreatedAtCiphertext());
|
||||
assertNotNull(halfEncryptedTimestampAccount.getDevices().get(1).getCreatedAtCiphertext());
|
||||
}
|
||||
}
|
||||
@@ -298,6 +298,12 @@ dogstatsd:
|
||||
environment: dev
|
||||
host: 127.0.0.1
|
||||
|
||||
openTelemetry:
|
||||
enabled: false
|
||||
environment: dev
|
||||
shutdownWaitDuration: PT0S
|
||||
url: http://127.0.0.1:4318/
|
||||
|
||||
unidentifiedDelivery:
|
||||
certificate: CgIIAQ==
|
||||
privateKey: secret://unidentifiedDelivery.privateKey
|
||||
|
||||
+1
-1
Submodule spam-filter updated: 5afdaef008...ac649619ec.
Reference in new issue
Block a user