mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 15:56:47 +00:00
Compare commits
45
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4c5dc118aa | ||
|
|
ad84cd848a | ||
|
|
127bd56f73 | ||
|
|
ad3721acf1 | ||
|
|
085127326b | ||
|
|
2e32ab3282 | ||
|
|
8bb125597b | ||
|
|
8ca7f85bf0 | ||
|
|
9d4d36939c | ||
|
|
dabe1c157b | ||
|
|
36d0c4422e | ||
|
|
1429efd573 | ||
|
|
93c03c5676 | ||
|
|
bd1bd007c0 | ||
|
|
f485406c4d | ||
|
|
d96c360016 | ||
|
|
6d71f43b6c | ||
|
|
d6824fcaf6 | ||
|
|
61f388f5f4 | ||
|
|
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 |
No files matched your search
@@ -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;
|
||||
@@ -273,7 +272,6 @@ import org.whispersystems.textsecuregcm.workers.BackupUsageRecalculationCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CertificateCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CheckDynamicConfigurationCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.EncryptDeviceCreationTimestampCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.IdleDeviceNotificationSchedulerFactory;
|
||||
import org.whispersystems.textsecuregcm.workers.MessagePersisterServiceCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.NotifyIdleDevicesCommand;
|
||||
@@ -348,7 +346,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new IdleDeviceNotificationSchedulerFactory()));
|
||||
|
||||
bootstrap.addCommand(new RegenerateSecondaryDynamoDbTableDataCommand());
|
||||
bootstrap.addCommand(new EncryptDeviceCreationTimestampCommand());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -504,7 +501,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")
|
||||
@@ -596,9 +592,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);
|
||||
@@ -626,7 +622,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);
|
||||
@@ -636,15 +633,17 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
Clock.systemUTC());
|
||||
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster,
|
||||
config.getReportMessageConfiguration().getCounterTtl());
|
||||
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager,
|
||||
messageDeletionAsyncExecutor, Clock.systemUTC());
|
||||
RedisMessageAvailabilityManager redisMessageAvailabilityManager =
|
||||
new RedisMessageAvailabilityManager(messagesCluster, clientEventExecutor, asyncOperationQueueingExecutor);
|
||||
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
|
||||
reportMessageManager, messageDeletionAsyncExecutor, Clock.systemUTC());
|
||||
AccountLockManager accountLockManager = new AccountLockManager(dynamoDbClient,
|
||||
config.getDynamoDbTables().getDeletedAccountsLock().getTableName());
|
||||
ClientPublicKeysManager clientPublicKeysManager =
|
||||
new ClientPublicKeysManager(clientPublicKeys, accountLockManager, accountLockExecutor);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
pubsubClient, accountLockManager, keysManager, messagesManager, profilesManager,
|
||||
secureStorageClient, secureValueRecovery2Client, secureValueRecoveryBClient, disconnectionRequestManager,
|
||||
secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
|
||||
registrationRecoveryPasswordsManager, clientPublicKeysManager, accountLockExecutor, messagePollExecutor,
|
||||
clock, config.getLinkDeviceSecretConfiguration().secret().value(), dynamicConfigurationManager);
|
||||
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs);
|
||||
@@ -654,8 +653,6 @@ 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);
|
||||
RateLimiters rateLimiters = RateLimiters.create(dynamicConfigurationManager, rateLimitersCluster);
|
||||
ProvisioningManager provisioningManager = new ProvisioningManager(pubsubClient);
|
||||
IssuedReceiptsManager issuedReceiptsManager = new IssuedReceiptsManager(
|
||||
@@ -675,8 +672,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);
|
||||
@@ -753,7 +748,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);
|
||||
@@ -800,6 +795,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
tusAttachmentGenerator,
|
||||
cdn3BackupCredentialGenerator,
|
||||
cdn3RemoteStorageManager,
|
||||
svrbCredentialsGenerator,
|
||||
secureValueRecoveryBClient,
|
||||
clock);
|
||||
|
||||
final AppleDeviceChecks appleDeviceChecks = new AppleDeviceChecks(
|
||||
@@ -816,10 +813,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);
|
||||
@@ -975,7 +968,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
final MetricsHttpChannelListener metricsHttpChannelListener = new MetricsHttpChannelListener(clientReleaseManager,
|
||||
Set.of(websocketServletPath, provisioningWebsocketServletPath, "/health-check"));
|
||||
metricsHttpChannelListener.configure(environment);
|
||||
final MessageMetrics messageMetrics = new MessageMetrics();
|
||||
final MessageMetrics messageMetrics = new MessageMetrics(config.getDynamoDbTables().getMessages().getExpiration());
|
||||
final BackupMetrics backupMetrics = new BackupMetrics();
|
||||
|
||||
// BufferingInterceptor is needed on the base environment but not the WebSocketEnvironment,
|
||||
@@ -1001,13 +994,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)
|
||||
@@ -1121,7 +1114,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()),
|
||||
@@ -1150,7 +1142,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);
|
||||
@@ -1179,9 +1171,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);
|
||||
}
|
||||
|
||||
|
||||
-15
@@ -6,8 +6,6 @@
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import io.netty.resolver.dns.DnsNameResolver;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
@@ -26,7 +24,6 @@ import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
|
||||
@@ -34,9 +31,6 @@ public class CloudflareTurnCredentialsManager {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(CloudflareTurnCredentialsManager.class);
|
||||
|
||||
private static final String CREDENTIAL_FETCH_TIMER_NAME = MetricsUtil.name(CloudflareTurnCredentialsManager.class,
|
||||
"credentialFetchLatency");
|
||||
|
||||
private final List<String> cloudflareTurnUrls;
|
||||
private final List<String> cloudflareTurnUrlsWithIps;
|
||||
private final String cloudflareTurnHostname;
|
||||
@@ -119,20 +113,11 @@ public class CloudflareTurnCredentialsManager {
|
||||
throw new IOException(e);
|
||||
}
|
||||
|
||||
final Timer.Sample sample = Timer.start();
|
||||
final HttpResponse<String> response;
|
||||
try {
|
||||
response = cloudflareTurnClient.sendAsync(getCredentialsRequest, HttpResponse.BodyHandlers.ofString()).join();
|
||||
sample.stop(Timer.builder(CREDENTIAL_FETCH_TIMER_NAME)
|
||||
.publishPercentileHistogram(true)
|
||||
.tags("outcome", "success")
|
||||
.register(Metrics.globalRegistry));
|
||||
} catch (CompletionException e) {
|
||||
logger.warn("failed to make http request to Cloudflare Turn: {}", e.getMessage());
|
||||
sample.stop(Timer.builder(CREDENTIAL_FETCH_TIMER_NAME)
|
||||
.publishPercentileHistogram(true)
|
||||
.tags("outcome", "failure")
|
||||
.register(Metrics.globalRegistry));
|
||||
throw new IOException(ExceptionUtils.unwrap(e));
|
||||
}
|
||||
|
||||
|
||||
+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());
|
||||
}
|
||||
}
|
||||
+10
@@ -15,6 +15,8 @@ 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 {
|
||||
|
||||
@@ -23,6 +25,14 @@ public record OpenTelemetryConfiguration(
|
||||
return otlpConfig.get(key.split("\\.", 2)[1]);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Integer> maxBucketsPerMeter() {
|
||||
if (maxBucketsPerMeter == null) {
|
||||
return Map.of();
|
||||
}
|
||||
return maxBucketsPerMeter;
|
||||
}
|
||||
|
||||
public Duration shutdownWaitDuration() {
|
||||
if (shutdownWaitDuration == null) {
|
||||
return step().plus(step().dividedBy(2));
|
||||
|
||||
+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,
|
||||
|
||||
+18
-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;
|
||||
@@ -392,6 +394,8 @@ public class DeviceController {
|
||||
if (response != null && response.getStatus() == Response.Status.OK.getStatusCode()) {
|
||||
accountAndSample.second().stop(Timer.builder(WAIT_FOR_LINKED_DEVICE_TIMER_NAME)
|
||||
.publishPercentileHistogram(true)
|
||||
.minimumExpectedValue(Duration.ofMillis(100))
|
||||
.maximumExpectedValue(Duration.ofMinutes(1))
|
||||
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.register(Metrics.globalRegistry));
|
||||
}
|
||||
@@ -446,6 +450,8 @@ public class DeviceController {
|
||||
|
||||
private static boolean isCapabilityDowngrade(final Account account, final Set<DeviceCapability> capabilities) {
|
||||
final Set<DeviceCapability> requiredCapabilities = Arrays.stream(DeviceCapability.values())
|
||||
// `ALWAYS_CAPABLE` capabilities are always assumed to be present, so we don't require callers to specify them
|
||||
.filter(capability -> capability.getAccountCapabilityMode() != DeviceCapability.AccountCapabilityMode.ALWAYS_CAPABLE)
|
||||
.filter(DeviceCapability::preventDowngrade)
|
||||
.filter(account::hasCapability)
|
||||
.collect(Collectors.toSet());
|
||||
@@ -533,8 +539,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.destinationDeviceRegistrationId().isPresent()))
|
||||
)).increment();
|
||||
return rateLimiters.getUploadTransferArchiveLimiter()
|
||||
.validateAsync(authenticatedDevice.accountIdentifier())
|
||||
.thenCompose(ignored -> accounts.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
|
||||
@@ -544,7 +556,8 @@ public class DeviceController {
|
||||
|
||||
return accounts.recordTransferArchiveUpload(account,
|
||||
transferArchiveUploadedRequest.destinationDeviceId(),
|
||||
Instant.ofEpochMilli(transferArchiveUploadedRequest.destinationDeviceCreated()),
|
||||
transferArchiveUploadedRequest.destinationDeviceCreated().map(Instant::ofEpochMilli),
|
||||
transferArchiveUploadedRequest.destinationDeviceRegistrationId(),
|
||||
transferArchiveUploadedRequest.transferArchive());
|
||||
});
|
||||
}
|
||||
@@ -603,6 +616,8 @@ public class DeviceController {
|
||||
if (response != null && response.getStatus() == Response.Status.OK.getStatusCode()) {
|
||||
accountAndSample.second().stop(Timer.builder(WAIT_FOR_TRANSFER_ARCHIVE_TIMER_NAME)
|
||||
.publishPercentileHistogram(true)
|
||||
.minimumExpectedValue(Duration.ofMillis(250))
|
||||
.maximumExpectedValue(Duration.ofMinutes(5))
|
||||
.tags(Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
primaryPlatformTag(accountAndSample.first())))
|
||||
|
||||
+7
-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());
|
||||
|
||||
@@ -61,6 +61,8 @@ public class KeepAliveController {
|
||||
Timer.builder(CLOSED_CONNECTION_AGE_DISTRIBUTION_NAME)
|
||||
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(context.getClient().getUserAgent())))
|
||||
.publishPercentileHistogram(true)
|
||||
.minimumExpectedValue(Duration.ofMillis(50))
|
||||
.maximumExpectedValue(Duration.ofMinutes(2))
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(age);
|
||||
}
|
||||
|
||||
+8
-62
@@ -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,10 +90,7 @@ 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");
|
||||
private static final String PRIMARY_DEVICE_TAG_NAME = "isPrimary";
|
||||
private static final String IDENTITY_TYPE_TAG_NAME = "identityType";
|
||||
private static final String KEY_TYPE_TAG_NAME = "keyType";
|
||||
@@ -176,12 +171,6 @@ public class KeysController {
|
||||
|
||||
Metrics.counter(STORE_KEYS_COUNTER_NAME, tags).increment();
|
||||
|
||||
DistributionSummary.builder(STORE_KEY_BUNDLE_SIZE_DISTRIBUTION_NAME)
|
||||
.tags(tags)
|
||||
.publishPercentileHistogram()
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(setKeysRequest.preKeys().size());
|
||||
|
||||
storeFutures.add(keysManager.storeEcOneTimePreKeys(identifier, device.getId(), setKeysRequest.preKeys()));
|
||||
}
|
||||
|
||||
@@ -197,12 +186,6 @@ public class KeysController {
|
||||
final Tags tags = Tags.of(platformTag, primaryDeviceTag, identityTypeTag, Tag.of(KEY_TYPE_TAG_NAME, "kyber"));
|
||||
Metrics.counter(STORE_KEYS_COUNTER_NAME, tags).increment();
|
||||
|
||||
DistributionSummary.builder(STORE_KEY_BUNDLE_SIZE_DISTRIBUTION_NAME)
|
||||
.tags(tags)
|
||||
.publishPercentileHistogram()
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(setKeysRequest.pqPreKeys().size());
|
||||
|
||||
storeFutures.add(keysManager.storeKemOneTimePreKeys(identifier, device.getId(), setKeysRequest.pqPreKeys()));
|
||||
}
|
||||
|
||||
@@ -395,51 +378,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();
|
||||
|
||||
|
||||
+14
-9
@@ -110,7 +110,6 @@ import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import org.whispersystems.textsecuregcm.websocket.WebSocketConnection;
|
||||
import org.whispersystems.websocket.WebsocketHeaders;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
|
||||
@@ -153,14 +152,21 @@ public class MessageController {
|
||||
INDIVIDUAL_MESSAGE_LATENCY_TIMER = Timer.builder(timerName)
|
||||
.tags(multiRecipientTagName, "false")
|
||||
.publishPercentileHistogram(true)
|
||||
.minimumExpectedValue(Duration.ofMillis(1))
|
||||
.minimumExpectedValue(Duration.ofSeconds(10))
|
||||
.register(Metrics.globalRegistry);
|
||||
|
||||
MULTI_RECIPIENT_MESSAGE_LATENCY_TIMER = Timer.builder(timerName)
|
||||
.tags(multiRecipientTagName, "true")
|
||||
.publishPercentileHistogram(true)
|
||||
.minimumExpectedValue(Duration.ofMillis(1))
|
||||
.minimumExpectedValue(Duration.ofSeconds(10))
|
||||
.register(Metrics.globalRegistry);
|
||||
}
|
||||
|
||||
private static final String INCORRECT_SYNC_MESSAGE_REGISTRATION_IDS_COUNTER_NAME =
|
||||
MetricsUtil.name(MessageController.class, "incorrectSyncMessageRegistrationIds");
|
||||
|
||||
// The Signal desktop client (really, JavaScript in general) can handle message timestamps at most 100,000,000 days
|
||||
// past the epoch; please see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date
|
||||
// for additional details.
|
||||
@@ -452,6 +458,12 @@ public class MessageController {
|
||||
userAgent);
|
||||
} catch (final MismatchedDevicesException e) {
|
||||
if (!e.getMismatchedDevices().staleDeviceIds().isEmpty()) {
|
||||
if (messageType == MessageType.SYNC) {
|
||||
Metrics.counter(INCORRECT_SYNC_MESSAGE_REGISTRATION_IDS_COUNTER_NAME,
|
||||
Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.increment();
|
||||
}
|
||||
|
||||
throw new WebApplicationException(Response.status(410)
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.entity(new StaleDevicesResponse(e.getMismatchedDevices().staleDeviceIds()))
|
||||
@@ -841,15 +853,8 @@ public class MessageController {
|
||||
final Device device = account.getDevice(auth.deviceId())
|
||||
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
|
||||
|
||||
return messagesManager.delete(
|
||||
auth.accountIdentifier(),
|
||||
device,
|
||||
uuid,
|
||||
null)
|
||||
return messagesManager.delete(auth.accountIdentifier(), device, uuid, null)
|
||||
.thenAccept(maybeRemovedMessage -> maybeRemovedMessage.ifPresent(removedMessage -> {
|
||||
|
||||
WebSocketConnection.recordMessageDeliveryDuration(removedMessage.serverTimestamp(), device);
|
||||
|
||||
if (removedMessage.sourceServiceId().isPresent()
|
||||
&& removedMessage.envelopeType() != Type.SERVER_DELIVERY_RECEIPT) {
|
||||
if (removedMessage.sourceServiceId().get() instanceof AciServiceIdentifier aciServiceIdentifier) {
|
||||
|
||||
-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 `destinationDeviceRegistrationId`.
|
||||
""", 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> destinationDeviceRegistrationId,
|
||||
|
||||
@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() ^ destinationDeviceRegistrationId.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);
|
||||
}
|
||||
}
|
||||
@@ -32,15 +32,17 @@ public final class MessageMetrics {
|
||||
"mismatchedAccountEnvelopeUuid");
|
||||
|
||||
public static final String DELIVERY_LATENCY_TIMER_NAME = name(MessageMetrics.class, "deliveryLatency");
|
||||
private final Duration messageTtl;
|
||||
private final MeterRegistry metricRegistry;
|
||||
|
||||
@VisibleForTesting
|
||||
MessageMetrics(final MeterRegistry metricRegistry) {
|
||||
MessageMetrics(final MeterRegistry metricRegistry, final Duration messageTtl) {
|
||||
this.metricRegistry = metricRegistry;
|
||||
this.messageTtl = messageTtl;
|
||||
}
|
||||
|
||||
public MessageMetrics() {
|
||||
this(Metrics.globalRegistry);
|
||||
public MessageMetrics(final Duration messageTtl) {
|
||||
this(Metrics.globalRegistry, messageTtl);
|
||||
}
|
||||
|
||||
public void measureAccountOutgoingMessageUuidMismatches(final Account account,
|
||||
@@ -83,10 +85,13 @@ public final class MessageMetrics {
|
||||
tags.add(Tag.of("isUrgent", String.valueOf(isUrgent)));
|
||||
tags.add(Tag.of("isEphemeral", String.valueOf(isEphemeral)));
|
||||
|
||||
UserAgentTagUtil.getClientVersionTag(userAgent, clientReleaseManager).ifPresent(tags::add);
|
||||
// This tag makes the metric extremely expensive on some platforms
|
||||
// UserAgentTagUtil.getClientVersionTag(userAgent, clientReleaseManager).ifPresent(tags::add);
|
||||
|
||||
Timer.builder(DELIVERY_LATENCY_TIMER_NAME)
|
||||
.publishPercentileHistogram(true)
|
||||
.minimumExpectedValue(Duration.ofSeconds(1))
|
||||
.maximumExpectedValue(messageTtl)
|
||||
.tags(tags)
|
||||
.register(metricRegistry)
|
||||
.record(Duration.between(Instant.ofEpochMilli(serverTimestamp), Instant.now()));
|
||||
|
||||
@@ -19,19 +19,25 @@ 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.HistogramFlavor;
|
||||
import io.micrometer.registry.otlp.OtlpMeterRegistry;
|
||||
import io.micrometer.statsd.StatsdMeterRegistry;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.stream.IntStream;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerVersion;
|
||||
import org.whispersystems.textsecuregcm.configuration.OpenTelemetryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
|
||||
public class MetricsUtil {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(MetricsUtil.class);
|
||||
|
||||
public static final String PREFIX = "chat";
|
||||
|
||||
private static volatile boolean registeredMetrics = false;
|
||||
@@ -65,7 +71,7 @@ public class MetricsUtil {
|
||||
|
||||
Duration shutdownWaitDuration = Duration.ZERO;
|
||||
|
||||
if (config.getDatadogConfiguration() != null && config.getDatadogConfiguration().enabled()) {
|
||||
if (config.getDatadogConfiguration().enabled()) {
|
||||
final StatsdMeterRegistry dogstatsdMeterRegistry = new StatsdMeterRegistry(
|
||||
config.getDatadogConfiguration(), io.micrometer.core.instrument.Clock.SYSTEM);
|
||||
|
||||
@@ -81,11 +87,12 @@ public class MetricsUtil {
|
||||
shutdownWaitDuration = config.getDatadogConfiguration().getShutdownWaitDuration();
|
||||
}
|
||||
|
||||
if (config.getOpenTelemetryConfiguration() != null && config.getOpenTelemetryConfiguration().enabled()) {
|
||||
if (config.getOpenTelemetryConfiguration().enabled()) {
|
||||
final OtlpMeterRegistry otlpMeterRegistry = new OtlpMeterRegistry(
|
||||
config.getOpenTelemetryConfiguration(), io.micrometer.core.instrument.Clock.SYSTEM);
|
||||
|
||||
configureMeterFilters(otlpMeterRegistry.config(), dynamicConfigurationManager);
|
||||
configureHistogramFilters(otlpMeterRegistry.config(), config.getOpenTelemetryConfiguration());
|
||||
Metrics.addRegistry(otlpMeterRegistry);
|
||||
|
||||
if (config.getOpenTelemetryConfiguration().shutdownWaitDuration().compareTo(shutdownWaitDuration) > 0) {
|
||||
@@ -113,7 +120,7 @@ public class MetricsUtil {
|
||||
config.meterFilter(new MeterFilter() {
|
||||
@Override
|
||||
public DistributionStatisticConfig configure(final Meter.Id id, final DistributionStatisticConfig config) {
|
||||
return defaultDistributionStatisticConfig.merge(config);
|
||||
return Optional.ofNullable(config.isPercentileHistogram()).orElse(false) ? config : defaultDistributionStatisticConfig.merge(config);
|
||||
}
|
||||
})
|
||||
// Remove high-cardinality `command` tags from Lettuce metrics and prepend "chat." to meter names
|
||||
@@ -137,6 +144,54 @@ public class MetricsUtil {
|
||||
&& id.getName().startsWith(awsSdkMetricNamePrefix)));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static void configureHistogramFilters(MeterRegistry.Config config, OpenTelemetryConfiguration openTelemetryConfig) {
|
||||
if (openTelemetryConfig.histogramFlavor() != HistogramFlavor.EXPLICIT_BUCKET_HISTOGRAM) {
|
||||
// This workaround for Micrometer's awful defaults is only required for explicit bucket histograms.
|
||||
return;
|
||||
}
|
||||
|
||||
config.meterFilter(new MeterFilter() {
|
||||
@Override
|
||||
public DistributionStatisticConfig configure(final Meter.Id id, final DistributionStatisticConfig config) {
|
||||
if (config.isPercentileHistogram() == null || !config.isPercentileHistogram()) {
|
||||
return config;
|
||||
}
|
||||
|
||||
if (config.getMinimumExpectedValueAsDouble() == null || config.getMaximumExpectedValueAsDouble() == null) {
|
||||
log.error("Distribution {} does not specify lower or upper bounds, not exporting histograms", id.getName());
|
||||
return DistributionStatisticConfig.builder()
|
||||
.percentilesHistogram(false)
|
||||
.build()
|
||||
.merge(config);
|
||||
}
|
||||
|
||||
final double lowerBound = config.getMinimumExpectedValueAsDouble();
|
||||
final double upperBound = config.getMaximumExpectedValueAsDouble();
|
||||
|
||||
final int numBuckets = Optional.ofNullable(openTelemetryConfig.maxBucketsPerMeter().get(id.getName()))
|
||||
.orElse(openTelemetryConfig.maxBucketCount());
|
||||
|
||||
// Bucket i covers values from (buckets[i-1], buckets[i]] except the first one which covers (-inf, buckets[0]].
|
||||
// A final bucket will automatically be added at positive infinity, so if we want numBuckets total buckets, we
|
||||
// need numBuckets - 1 explicit ones; if we want those to have equal ratios between values, and want an explicit
|
||||
// bucket for (-inf, lowerBound] as well as an implicit one for (upperBound, inf], the ratio between buckets will be
|
||||
// r = (upperBound/lowerBound)^(1/(numBuckets - 2)), so that we have values at lowerBound * r^i
|
||||
// for i in [0, numBuckets-2] i.e. numBuckets - 1 values, plus the one at infinity
|
||||
final double scale = Math.pow(upperBound / lowerBound, 1.0 / (numBuckets - 2));
|
||||
final double[] buckets = IntStream.range(0, numBuckets - 1).mapToDouble(i -> lowerBound * Math.pow(scale, i)).toArray();
|
||||
|
||||
// yes, percentilesHistogram(false)! Otherwise, Micrometer will add its own non-configurable buckets based on an
|
||||
// inferior selection algorithm that produces 69(!) buckets for a range from 1ms to 30s and still yields ±25% relative error
|
||||
return DistributionStatisticConfig.builder()
|
||||
.percentilesHistogram(false)
|
||||
.serviceLevelObjectives(buckets)
|
||||
.build()
|
||||
.merge(config);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static void registerSystemResourceMetrics(final Environment environment) {
|
||||
new ProcessorMetrics().bindTo(Metrics.globalRegistry);
|
||||
new FileDescriptorMetrics().bindTo(Metrics.globalRegistry);
|
||||
|
||||
+11
-3
@@ -6,6 +6,8 @@ import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import org.whispersystems.textsecuregcm.util.EnumMapUtil;
|
||||
@@ -20,6 +22,7 @@ public class OpenWebSocketCounter {
|
||||
|
||||
private final String newConnectionCounterName;
|
||||
private final String durationTimerName;
|
||||
private final Duration longestExpectedConnectionDuration;
|
||||
|
||||
private final Tags tags;
|
||||
|
||||
@@ -28,18 +31,21 @@ public class OpenWebSocketCounter {
|
||||
|
||||
public OpenWebSocketCounter(final String openWebSocketGaugeName,
|
||||
final String newConnectionCounterName,
|
||||
final String durationTimerName) {
|
||||
final String durationTimerName,
|
||||
final Duration longestExpectedConnectionDuration) {
|
||||
|
||||
this(openWebSocketGaugeName, newConnectionCounterName, durationTimerName, Tags.empty());
|
||||
this(openWebSocketGaugeName, newConnectionCounterName, durationTimerName, longestExpectedConnectionDuration, Tags.empty());
|
||||
}
|
||||
|
||||
public OpenWebSocketCounter(final String openWebSocketGaugeName,
|
||||
final String newConnectionCounterName,
|
||||
final String durationTimerName,
|
||||
final Duration longestExpectedConnectionDuration,
|
||||
final Tags tags) {
|
||||
|
||||
this.newConnectionCounterName = newConnectionCounterName;
|
||||
this.durationTimerName = durationTimerName;
|
||||
this.longestExpectedConnectionDuration = longestExpectedConnectionDuration;
|
||||
|
||||
this.tags = tags;
|
||||
|
||||
@@ -83,9 +89,11 @@ public class OpenWebSocketCounter {
|
||||
|
||||
Metrics.counter(newConnectionCounterName, tagsWithClientPlatform).increment();
|
||||
|
||||
context.addWebsocketClosedListener((context1, statusCode, reason) -> {
|
||||
context.addWebsocketClosedListener((_, statusCode, _) -> {
|
||||
sample.stop(Timer.builder(durationTimerName)
|
||||
.publishPercentileHistogram(true)
|
||||
.minimumExpectedValue(Duration.ofSeconds(1))
|
||||
.maximumExpectedValue(longestExpectedConnectionDuration)
|
||||
.tags(tagsWithClientPlatform)
|
||||
.register(Metrics.globalRegistry));
|
||||
|
||||
|
||||
+2
@@ -37,6 +37,8 @@ public class MultiRecipientMessageProvider implements MessageBodyReader<SealedSe
|
||||
private static final DistributionSummary RECIPIENT_COUNT_DISTRIBUTION = DistributionSummary
|
||||
.builder(name(MultiRecipientMessageProvider.class, "recipients"))
|
||||
.publishPercentileHistogram(true)
|
||||
.minimumExpectedValue(1.0)
|
||||
.maximumExpectedValue((double) MAX_RECIPIENT_COUNT)
|
||||
.register(Metrics.globalRegistry);
|
||||
|
||||
@Override
|
||||
|
||||
-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 handleConflictingMessageConsumer();
|
||||
}
|
||||
@@ -313,26 +313,23 @@ public class MessageSender {
|
||||
final boolean isStory,
|
||||
final Tag platformTag) throws MessageTooLargeException {
|
||||
|
||||
final boolean oversize = contentLength > MAX_MESSAGE_SIZE;
|
||||
final Tags tags = Tags.of(platformTag,
|
||||
Tag.of("multiRecipientMessage", String.valueOf(isMultiRecipientMessage)),
|
||||
Tag.of("syncMessage", String.valueOf(isSyncMessage)),
|
||||
Tag.of("story", String.valueOf(isStory)));
|
||||
|
||||
DistributionSummary.builder(CONTENT_SIZE_DISTRIBUTION_NAME)
|
||||
.tags(Tags.of(platformTag,
|
||||
Tag.of("oversize", String.valueOf(oversize)),
|
||||
Tag.of("multiRecipientMessage", String.valueOf(isMultiRecipientMessage)),
|
||||
Tag.of("syncMessage", String.valueOf(isSyncMessage)),
|
||||
Tag.of("story", String.valueOf(isStory))))
|
||||
.publishPercentileHistogram(true)
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(contentLength);
|
||||
|
||||
if (oversize) {
|
||||
Metrics.counter(REJECT_OVERSIZE_MESSAGE_COUNTER_NAME, Tags.of(platformTag,
|
||||
Tag.of("multiRecipientMessage", String.valueOf(isMultiRecipientMessage)),
|
||||
Tag.of("syncMessage", String.valueOf(isSyncMessage)),
|
||||
Tag.of("story", String.valueOf(isStory))))
|
||||
.increment();
|
||||
if (contentLength > MAX_MESSAGE_SIZE) {
|
||||
Metrics.counter(REJECT_OVERSIZE_MESSAGE_COUNTER_NAME, tags).increment();
|
||||
|
||||
throw new MessageTooLargeException();
|
||||
} else {
|
||||
DistributionSummary.builder(CONTENT_SIZE_DISTRIBUTION_NAME)
|
||||
.tags(tags)
|
||||
.publishPercentileHistogram(true)
|
||||
.minimumExpectedValue(256.0)
|
||||
.maximumExpectedValue((double) MAX_MESSAGE_SIZE)
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(contentLength);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
-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#handleConflictingMessageConsumer()} 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().handleConflictingMessageConsumer());
|
||||
}
|
||||
|
||||
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::handleConflictingMessageConsumer);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
|
||||
+12
-12
@@ -9,7 +9,6 @@ import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.zone.ZoneRules;
|
||||
import java.util.Comparator;
|
||||
@@ -19,19 +18,21 @@ import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
|
||||
public class SchedulingUtil {
|
||||
private static final String PARSED_TIMEZONE_COUNTER_NAME = MetricsUtil.name(SchedulingUtil.class, "parsedTimezone");
|
||||
private static final String HAS_TIMEZONE_TAG_NAME = "hasTimezone";
|
||||
|
||||
/**
|
||||
* Gets a present or future time at which to send a notification to a device associated with the given account. This
|
||||
* is mainly intended to facilitate scheduling notifications such that they arrive during a recipient's waking hours.
|
||||
* <p/>
|
||||
* This method will attempt to use a timezone derived from the account's phone number to choose an appropriate time
|
||||
* to send a notification. If a timezone cannot be derived from the account's phone number, then this method will use
|
||||
* the account's creation time as a hint. As an example, if the account was created at 07:17 in the server's local
|
||||
* time, we can assume that the account holder was awake at that time of day, and it's likely a safe time to send a
|
||||
* notification in the absence of other hints.
|
||||
* to send a notification. If a timezone cannot be derived from the account's phone number, then this method will
|
||||
* default to the preferred time in the server's timezone.
|
||||
*
|
||||
* @param account the account that will receive the notification
|
||||
* @param preferredTime the preferred local time (e.g. "noon") at which to deliver the notification
|
||||
@@ -44,14 +45,13 @@ public class SchedulingUtil {
|
||||
final Clock clock) {
|
||||
|
||||
final ZonedDateTime candidateNotificationTime = getZoneId(account, clock)
|
||||
.map(zoneId -> ZonedDateTime.now(clock.withZone(zoneId)).with(preferredTime))
|
||||
.map(zoneId -> {
|
||||
Metrics.counter(PARSED_TIMEZONE_COUNTER_NAME, HAS_TIMEZONE_TAG_NAME, String.valueOf(true)).increment();
|
||||
return ZonedDateTime.now(clock.withZone(zoneId)).with(preferredTime);
|
||||
})
|
||||
.orElseGet(() -> {
|
||||
// We couldn't find a reasonable timezone for the account for some reason, so make an educated guess at a
|
||||
// reasonable time to send a notification based on the account's creation time.
|
||||
final Instant accountCreation = Instant.ofEpochMilli(account.getPrimaryDevice().getCreated());
|
||||
final LocalTime accountCreationLocalTime = LocalTime.ofInstant(accountCreation, ZoneId.systemDefault());
|
||||
|
||||
return ZonedDateTime.now(ZoneId.systemDefault()).with(accountCreationLocalTime);
|
||||
Metrics.counter(PARSED_TIMEZONE_COUNTER_NAME, HAS_TIMEZONE_TAG_NAME, String.valueOf(false)).increment();
|
||||
return ZonedDateTime.now(ZoneId.systemDefault()).with(preferredTime);
|
||||
});
|
||||
|
||||
if (candidateNotificationTime.toInstant().isBefore(clock.instant())) {
|
||||
|
||||
+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()));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -271,6 +271,7 @@ public class Account {
|
||||
case PRIMARY_DEVICE -> getPrimaryDevice().hasCapability(capability);
|
||||
case ANY_DEVICE -> devices.stream().anyMatch(device -> device.hasCapability(capability));
|
||||
case ALL_DEVICES -> devices.stream().allMatch(device -> device.hasCapability(capability));
|
||||
case ALWAYS_CAPABLE -> true;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+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
|
||||
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
|
||||
|
||||
/// Indicates that more than one consumer is trying to read a specific message queue at the same time.
|
||||
public class ConflictingMessageConsumerException extends NoStackTraceException {
|
||||
}
|
||||
+9
-2
@@ -10,8 +10,10 @@ import java.util.Optional;
|
||||
public enum DeviceCapability {
|
||||
STORAGE("storage", AccountCapabilityMode.ANY_DEVICE, false, false),
|
||||
TRANSFER("transfer", AccountCapabilityMode.PRIMARY_DEVICE, false, false),
|
||||
DELETE_SYNC("deleteSync", AccountCapabilityMode.ALL_DEVICES, true, true),
|
||||
STORAGE_SERVICE_RECORD_KEY_ROTATION("ssre2", AccountCapabilityMode.ALL_DEVICES, true, true),
|
||||
@Deprecated(forRemoval = true) // Can be removed sometime after 11/10/2025
|
||||
DELETE_SYNC("deleteSync", AccountCapabilityMode.ALWAYS_CAPABLE, true, true),
|
||||
@Deprecated(forRemoval = true) // Can be removed sometime after 11/10/2025
|
||||
STORAGE_SERVICE_RECORD_KEY_ROTATION("ssre2", AccountCapabilityMode.ALWAYS_CAPABLE, true, true),
|
||||
ATTACHMENT_BACKFILL("attachmentBackfill", AccountCapabilityMode.PRIMARY_DEVICE, false, true),
|
||||
SPARSE_POST_QUANTUM_RATCHET("spqr", AccountCapabilityMode.ALL_DEVICES, true, true);
|
||||
|
||||
@@ -28,6 +30,11 @@ public enum DeviceCapability {
|
||||
* The account will have the capability iff all devices on the account have the capability
|
||||
*/
|
||||
ALL_DEVICES,
|
||||
/**
|
||||
* The account always has this capability, regardless of the constituent devices' capabilities.
|
||||
* This supports retiring capabilities where older clients still need the field provided.
|
||||
*/
|
||||
ALWAYS_CAPABLE,
|
||||
}
|
||||
|
||||
private final String name;
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
+7
-5
@@ -22,6 +22,7 @@ import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.stream.IntStream;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -58,16 +59,17 @@ public class MessagePersister implements Managed {
|
||||
private static final Counter TRIMMED_MESSAGE_COUNTER = Metrics.counter(name(MessagePersister.class, "trimmedMessage"));
|
||||
private static final Counter TRIMMED_MESSAGE_BYTES_COUNTER = Metrics.counter(name(MessagePersister.class, "trimmedMessageBytes"));
|
||||
|
||||
private static final DistributionSummary QUEUE_COUNT_DISTRIBUTION_SUMMARY = DistributionSummary.builder(
|
||||
name(MessagePersister.class, "queueCount"))
|
||||
.publishPercentileHistogram(true)
|
||||
.register(Metrics.globalRegistry);
|
||||
|
||||
private static final String QUEUE_SIZE_DISTRIBUTION_SUMMARY_NAME = name(MessagePersister.class, "queueSize");
|
||||
|
||||
static final int QUEUE_BATCH_LIMIT = 100;
|
||||
static final int MESSAGE_BATCH_LIMIT = 100;
|
||||
|
||||
private static final DistributionSummary QUEUE_COUNT_DISTRIBUTION_SUMMARY = DistributionSummary.builder(
|
||||
name(MessagePersister.class, "queueCount"))
|
||||
.publishPercentiles(new double[0])
|
||||
.serviceLevelObjectives(IntStream.range(1, QUEUE_BATCH_LIMIT + 1).mapToDouble(i -> i).toArray())
|
||||
.register(Metrics.globalRegistry);
|
||||
|
||||
private static final long EXCEPTION_PAUSE_MILLIS = Duration.ofSeconds(3).toMillis();
|
||||
|
||||
private static final int CONSECUTIVE_EMPTY_CACHE_REMOVAL_LIMIT = 3;
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Flow;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
|
||||
/// A message stream publishes an ordered stream of Signal messages from a destination device's queue and provides a
|
||||
/// mechanism for consumers to acknowledge receipt of delivered messages.
|
||||
public interface MessageStream {
|
||||
|
||||
/// Publishes a non-terminating stream of [MessageStreamEntry.Envelope] entities and at most one
|
||||
/// [MessageStreamEntry.QueueEmpty].
|
||||
///
|
||||
/// @return a non-terminating stream of message stream entries
|
||||
Flow.Publisher<MessageStreamEntry> getMessages();
|
||||
|
||||
/// Acknowledges receipt of the given message. Implementations may delete the message immediately or defer deletion for
|
||||
/// inclusion in a more efficient batch deletion.
|
||||
///
|
||||
/// @param message the message to acknowledge
|
||||
///
|
||||
/// @return a future that completes when the message stream has processed the acknowledgement
|
||||
CompletableFuture<Void> acknowledgeMessage(MessageProtos.Envelope message);
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
|
||||
/// A `MessageStreamEntr` is an entity that can be emitted by the publisher returned by [MessageStream#getMessages()].
|
||||
/// Message stream entries either produce an individual message (see [Envelope]) or that the initial contents of a
|
||||
/// message queue have been drained (see [QueueEmpty]).
|
||||
public sealed interface MessageStreamEntry permits MessageStreamEntry.Envelope, MessageStreamEntry.QueueEmpty {
|
||||
|
||||
/// A message stream entry that carries a single message.
|
||||
///
|
||||
/// @param message the message emitted by the publisher
|
||||
record Envelope(MessageProtos.Envelope message) implements MessageStreamEntry {
|
||||
}
|
||||
|
||||
/// A message stream entry that indicates that the initial contents of a message queue have been emitted by the
|
||||
/// publisher; any [Envelope] entries after a `QueueEmpty` entry arrived after caller started reading
|
||||
/// messages from the queue.
|
||||
record QueueEmpty() implements MessageStreamEntry {
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
+10
-2
@@ -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;
|
||||
@@ -56,6 +57,7 @@ public class MessagesManager {
|
||||
|
||||
private final MessagesDynamoDb messagesDynamoDb;
|
||||
private final MessagesCache messagesCache;
|
||||
private final RedisMessageAvailabilityManager redisMessageAvailabilityManager;
|
||||
private final ReportMessageManager reportMessageManager;
|
||||
private final ExecutorService messageDeletionExecutor;
|
||||
private final Clock clock;
|
||||
@@ -63,12 +65,14 @@ public class MessagesManager {
|
||||
public MessagesManager(
|
||||
final MessagesDynamoDb messagesDynamoDb,
|
||||
final MessagesCache messagesCache,
|
||||
final RedisMessageAvailabilityManager redisMessageAvailabilityManager,
|
||||
final ReportMessageManager reportMessageManager,
|
||||
final ExecutorService messageDeletionExecutor,
|
||||
final Clock clock) {
|
||||
|
||||
this.messagesDynamoDb = messagesDynamoDb;
|
||||
this.messagesCache = messagesCache;
|
||||
this.redisMessageAvailabilityManager = redisMessageAvailabilityManager;
|
||||
this.reportMessageManager = reportMessageManager;
|
||||
this.messageDeletionExecutor = messageDeletionExecutor;
|
||||
this.clock = clock;
|
||||
@@ -82,7 +86,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 +131,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,
|
||||
@@ -220,6 +224,10 @@ public class MessagesManager {
|
||||
return getMessagesForDevice(destinationUuid, destinationDevice, null, cachedMessagesOnly);
|
||||
}
|
||||
|
||||
public MessageStream getMessages(final UUID destinationUuid, final Device destinationDevice) {
|
||||
return new RedisDynamoDbMessageStream(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, destinationUuid, destinationDevice);
|
||||
}
|
||||
|
||||
private Publisher<Envelope> getMessagesForDevice(UUID destinationUuid, Device destinationDevice,
|
||||
@Nullable Integer limit, final boolean cachedMessagesOnly) {
|
||||
|
||||
|
||||
+4
-1
@@ -22,6 +22,8 @@ import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import org.signal.libsignal.protocol.InvalidKeyException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -73,7 +75,8 @@ public class PagedSingleUseKEMPreKeyStore {
|
||||
|
||||
final DistributionSummary availableKeyCountDistributionSummary = DistributionSummary
|
||||
.builder(name(getClass(), "availableKeyCount"))
|
||||
.publishPercentileHistogram()
|
||||
.publishPercentiles(new double[0])
|
||||
.serviceLevelObjectives(IntStream.range(1, 102).mapToDouble(i -> i).toArray())
|
||||
.register(Metrics.globalRegistry);
|
||||
|
||||
private final String takeKeyTimerName = name(getClass(), "takeKey");
|
||||
|
||||
+327
@@ -0,0 +1,327 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Flow;
|
||||
import javax.annotation.Nullable;
|
||||
import org.reactivestreams.Publisher;
|
||||
import org.reactivestreams.Subscription;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.push.MessageAvailabilityListener;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import reactor.core.observability.micrometer.Micrometer;
|
||||
import reactor.core.publisher.BaseSubscriber;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
/// A Redis/DynamoDB message publisher produces a non-terminating stream of messages for a specific device. It listens
|
||||
/// for message availability signals from [RedisMessageAvailabilityManager] and emits new messages to its subscriber
|
||||
/// when available.
|
||||
///
|
||||
/// This publisher supports only a single subscriber. It assumes that subscribers acknowledge (delete) messages as they
|
||||
/// read the messages, and may emit duplicate messages if subscribers do not acknowledge messages before requesting more
|
||||
/// messages.
|
||||
class RedisDynamoDbMessagePublisher implements MessageAvailabilityListener, Flow.Publisher<MessageStreamEntry> {
|
||||
|
||||
private final MessagesDynamoDb messagesDynamoDb;
|
||||
private final MessagesCache messagesCache;
|
||||
private final RedisMessageAvailabilityManager redisMessageAvailabilityManager;
|
||||
|
||||
private final UUID accountIdentifier;
|
||||
private final Device device;
|
||||
|
||||
// Indicates which data source(s) we think might contain messages for the destination device. Messages initially land
|
||||
// in Redis, but are eventually "persisted" to DynamoDB. This state changes in response to signals this publisher
|
||||
// receives as a MessageAvailabilityListener. As an initial state, we assume that we have messages in both DynamoDB
|
||||
// and Redis.
|
||||
private StoredMessageState storedMessageState = StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE;
|
||||
|
||||
// The number of messages the downstream subscriber is ready to receive. This changes in response to new requests from
|
||||
// the downstream subscriber and gets decremented every time we publish a message.
|
||||
private long unmetDemand = 0;
|
||||
|
||||
// Although technically nullable, operation of this publisher really begins once we get a subscriber. This publisher
|
||||
// supports only a single subscriber.
|
||||
@Nullable private Flow.Subscriber<? super MessageStreamEntry> subscriber;
|
||||
|
||||
// If terminated (i.e. by an error or by downstream cancellation), this publisher will stop emitting signals. Once
|
||||
// terminated, a publisher cannot be un-terminated.
|
||||
private boolean terminated = false;
|
||||
|
||||
// This publisher will emit exactly one "queue empty" signal once the initial contents of the message queue have been
|
||||
// drained. Once emitted, this flag is set to `true` and will never change again.
|
||||
private boolean publishedQueueEmptySignal = false;
|
||||
|
||||
// …but we may not be able to send the "queue empty" signal downstream immediately if there's no demand. This flag
|
||||
// tracks whether we're ready to publish a "queue empty" signal, regardless of whether we've actually sent it. Once
|
||||
// this flag is set to `true`, it will never change again.
|
||||
private boolean readyToPublishQueueEmptySignal = false;
|
||||
|
||||
// A message source subscriber subscribes to messages from upstream data sources (i.e. DynamoDB and Redis), and this
|
||||
// publisher relays signals the message source subscriber to the downstream subscriber. The message source subscriber
|
||||
// may be null if we're not actively fetching messages from an upstream source and changes every time an upstream
|
||||
// publisher completes.
|
||||
@Nullable private MessageSourceSubscriber messageSourceSubscriber;
|
||||
|
||||
private static final String GET_MESSAGES_FOR_DEVICE_FLUX_NAME =
|
||||
name(RedisDynamoDbMessagePublisher.class, "getMessagesForDevice");
|
||||
|
||||
private enum StoredMessageState {
|
||||
// Indicates that stored messages are available in at least DynamoDB and possibly also Redis
|
||||
PERSISTED_NEW_MESSAGES_AVAILABLE,
|
||||
|
||||
// Indicates that messages are available in Redis, but have not yet been persisted to DynamoDB
|
||||
CACHED_NEW_MESSAGES_AVAILABLE,
|
||||
|
||||
// Indicates that no new messages are available in either Redis or DynamoDB
|
||||
EMPTY
|
||||
}
|
||||
|
||||
/// A message source subscriber subscribes to upstream message source publishers and relays signals to the downstream
|
||||
/// subscriber via the parent `RedisDynamoDbMessagePublisher`.
|
||||
private static class MessageSourceSubscriber extends BaseSubscriber<MessageProtos.Envelope> {
|
||||
|
||||
private final RedisDynamoDbMessagePublisher redisDynamoDbMessagePublisher;
|
||||
|
||||
private MessageSourceSubscriber(RedisDynamoDbMessagePublisher redisDynamoDbMessagePublisher) {
|
||||
this.redisDynamoDbMessagePublisher = redisDynamoDbMessagePublisher;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void hookOnSubscribe(final Subscription subscription) {
|
||||
final long unmetDemand = redisDynamoDbMessagePublisher.getUnmetDemand();
|
||||
|
||||
// If we already have some unmet demand, pass that on to the upstream publisher immediately on subscribing
|
||||
if (unmetDemand > 0) {
|
||||
subscription.request(unmetDemand);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void hookOnNext(final MessageProtos.Envelope message) {
|
||||
redisDynamoDbMessagePublisher.handleNextMessage(message);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void hookOnComplete() {
|
||||
redisDynamoDbMessagePublisher.handleMessageSourceComplete();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void hookOnError(final Throwable throwable) {
|
||||
redisDynamoDbMessagePublisher.handleMessageSourceError(throwable);
|
||||
}
|
||||
}
|
||||
|
||||
RedisDynamoDbMessagePublisher(final MessagesDynamoDb messagesDynamoDb,
|
||||
final MessagesCache messagesCache,
|
||||
final RedisMessageAvailabilityManager redisMessageAvailabilityManager,
|
||||
final UUID accountIdentifier,
|
||||
final Device device) {
|
||||
|
||||
this.messagesDynamoDb = messagesDynamoDb;
|
||||
this.messagesCache = messagesCache;
|
||||
this.redisMessageAvailabilityManager = redisMessageAvailabilityManager;
|
||||
this.accountIdentifier = accountIdentifier;
|
||||
this.device = device;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void subscribe(final Flow.Subscriber<? super MessageStreamEntry> subscriber) {
|
||||
if (this.subscriber != null) {
|
||||
subscriber.onError(new IllegalStateException("Redis/DynamoDB message publisher only allows one subscriber"));
|
||||
return;
|
||||
}
|
||||
|
||||
this.subscriber = subscriber;
|
||||
|
||||
// Listen for signals indicating that new messages are available in Redis, that messages have been persisted from
|
||||
// Redis to DynamoDB, or that there's a conflicting message reader connected somewhere else
|
||||
redisMessageAvailabilityManager.handleClientConnected(accountIdentifier, device.getId(), this);
|
||||
|
||||
subscriber.onSubscribe(new Flow.Subscription() {
|
||||
@Override
|
||||
public void request(final long n) {
|
||||
addDemand(n);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancel() {
|
||||
terminate();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void handleNewMessageAvailable() {
|
||||
// We only need to take action if we think there aren't already messages to pass downstream. Any other stored
|
||||
// message state implies that we're either actively sending messages downstream or we're waiting for demand from the
|
||||
// downstream subscriber and don't need to take any action now. We'll call `maybeGenerateMessageSource` either when
|
||||
// we receive a request for more messages or when the current upstream publisher completes.
|
||||
if (storedMessageState == StoredMessageState.EMPTY) {
|
||||
storedMessageState = StoredMessageState.CACHED_NEW_MESSAGES_AVAILABLE;
|
||||
maybeGenerateMessageSource();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void handleMessagesPersisted() {
|
||||
// We only need to take action if we think there aren't already messages in DynamoDB. If we're already aware of
|
||||
// messages in DynamoDB, then we're either actively sending messages downstream or we're waiting for demand from the
|
||||
// downstream subscriber and don't need to take any action now. We'll call `maybeGenerateMessageSource` either when
|
||||
// we receive a request for more messages or when the current upstream publisher completes.
|
||||
if (storedMessageState != StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE) {
|
||||
storedMessageState = StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE;
|
||||
maybeGenerateMessageSource();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void handleConflictingMessageConsumer() {
|
||||
// We don't register as a listener for conflicting consumer signals until we have a subscriber
|
||||
assert subscriber != null;
|
||||
|
||||
if (!terminated) {
|
||||
subscriber.onError(new ConflictingMessageConsumerException());
|
||||
}
|
||||
|
||||
terminate();
|
||||
}
|
||||
|
||||
private synchronized boolean maybeSendQueueEmptySignal() {
|
||||
// Regardless of any other state, don't do anything if terminated
|
||||
if (terminated) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// The machinery that produces messages won't activate until we have a subscriber
|
||||
assert subscriber != null;
|
||||
|
||||
if (readyToPublishQueueEmptySignal && !publishedQueueEmptySignal && getUnmetDemand() > 0) {
|
||||
subscriber.onNext(new MessageStreamEntry.QueueEmpty());
|
||||
unmetDemand -= 1;
|
||||
|
||||
assert unmetDemand >= 0;
|
||||
|
||||
publishedQueueEmptySignal = true;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private synchronized void maybeGenerateMessageSource() {
|
||||
// Regardless of any other state, don't do anything if terminated
|
||||
if (terminated) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (storedMessageState == StoredMessageState.EMPTY || unmetDemand == 0) {
|
||||
// We don't think there are any messages in either source or there's no demand for messages; either way, wait for
|
||||
// things to change before trying to generate a message source
|
||||
return;
|
||||
}
|
||||
|
||||
// We maybe be able to skip reading from DynamoDB entirely if we think messages are only stored in Redis
|
||||
final Publisher<MessageProtos.Envelope> dynamoPublisher =
|
||||
storedMessageState == StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE
|
||||
? messagesDynamoDb.load(accountIdentifier, device, null)
|
||||
: Flux.empty();
|
||||
|
||||
final Publisher<MessageProtos.Envelope> redisPublisher = messagesCache.get(accountIdentifier, device.getId());
|
||||
|
||||
final Flux<MessageProtos.Envelope> messageSource = Flux.concat(dynamoPublisher, redisPublisher)
|
||||
.name(GET_MESSAGES_FOR_DEVICE_FLUX_NAME)
|
||||
.tap(Micrometer.metrics(Metrics.globalRegistry));
|
||||
|
||||
messageSourceSubscriber = new MessageSourceSubscriber(this);
|
||||
messageSource.subscribe(messageSourceSubscriber);
|
||||
|
||||
// If nothing else happens before the DynamoDB/Redis publisher completes, then we'll have emptied all stored
|
||||
// messages; new signals about persisted messages or newly-arrived messages will change this state
|
||||
storedMessageState = StoredMessageState.EMPTY;
|
||||
}
|
||||
|
||||
private synchronized void handleNextMessage(final MessageProtos.Envelope message) {
|
||||
// The machinery that produces messages won't activate until we have a subscriber
|
||||
assert subscriber != null;
|
||||
|
||||
if (!terminated) {
|
||||
unmetDemand -= 1;
|
||||
assert unmetDemand >= 0;
|
||||
|
||||
subscriber.onNext(new MessageStreamEntry.Envelope(message));
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void handleMessageSourceComplete() {
|
||||
// The machinery that produces messages won't activate until we have a subscriber
|
||||
assert subscriber != null;
|
||||
|
||||
messageSourceSubscriber = null;
|
||||
|
||||
// Attempt to send a "queue empty" signal if we haven't already
|
||||
readyToPublishQueueEmptySignal = true;
|
||||
maybeSendQueueEmptySignal();
|
||||
|
||||
// New messages may have arrived already; fetch them if possible
|
||||
maybeGenerateMessageSource();
|
||||
}
|
||||
|
||||
private synchronized void handleMessageSourceError(final Throwable throwable) {
|
||||
// The machinery that produces messages won't activate until we have a subscriber
|
||||
assert subscriber != null;
|
||||
|
||||
if (!terminated) {
|
||||
subscriber.onError(throwable);
|
||||
terminate();
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void addDemand(final long demand) {
|
||||
if (demand <= 0) {
|
||||
throw new IllegalArgumentException("Demand must be positive");
|
||||
}
|
||||
|
||||
unmetDemand += demand;
|
||||
|
||||
// We may have been waiting for non-zero demand before sending a "queue empty" signal
|
||||
final boolean sentQueueEmptySignal = maybeSendQueueEmptySignal();
|
||||
|
||||
// This is a little tricky; if we already have a subscriber, we only want to request NEW demand, not the total
|
||||
// outstanding demand. On top of that, we may have consumed some demand by sending a "queue empty" message.
|
||||
final long newDemand = demand - (sentQueueEmptySignal ? 1 : 0);
|
||||
|
||||
if (newDemand > 0) {
|
||||
if (messageSourceSubscriber != null) {
|
||||
messageSourceSubscriber.request(newDemand);
|
||||
} else {
|
||||
maybeGenerateMessageSource();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized long getUnmetDemand() {
|
||||
return unmetDemand;
|
||||
}
|
||||
|
||||
private synchronized void terminate() {
|
||||
if (!terminated) {
|
||||
terminated = true;
|
||||
|
||||
// Stop receiving signals about new messages/conflicting consumers
|
||||
redisMessageAvailabilityManager.handleClientDisconnected(accountIdentifier, device.getId());
|
||||
|
||||
if (messageSourceSubscriber != null) {
|
||||
messageSourceSubscriber.dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Flow;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
/// A [MessageStream] implementation that produces message from a joint DynamoDB/Redis message store.
|
||||
public class RedisDynamoDbMessageStream implements MessageStream {
|
||||
|
||||
private final MessagesDynamoDb messagesDynamoDb;
|
||||
private final MessagesCache messagesCache;
|
||||
|
||||
private final UUID accountIdentifier;
|
||||
private final Device device;
|
||||
|
||||
private final RedisDynamoDbMessagePublisher messagePublisher;
|
||||
|
||||
public RedisDynamoDbMessageStream(final MessagesDynamoDb messagesDynamoDb,
|
||||
final MessagesCache messagesCache,
|
||||
final RedisMessageAvailabilityManager redisMessageAvailabilityManager,
|
||||
final UUID accountIdentifier,
|
||||
final Device device) {
|
||||
|
||||
this.messagesDynamoDb = messagesDynamoDb;
|
||||
this.messagesCache = messagesCache;
|
||||
this.accountIdentifier = accountIdentifier;
|
||||
this.device = device;
|
||||
|
||||
this.messagePublisher = new RedisDynamoDbMessagePublisher(messagesDynamoDb,
|
||||
messagesCache,
|
||||
redisMessageAvailabilityManager,
|
||||
accountIdentifier,
|
||||
device);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flow.Publisher<MessageStreamEntry> getMessages() {
|
||||
return messagePublisher;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> acknowledgeMessage(final MessageProtos.Envelope message) {
|
||||
final UUID guid = UUID.fromString(message.getServerGuid());
|
||||
|
||||
return messagesCache.remove(accountIdentifier, device.getId(), guid)
|
||||
.thenCompose(removed -> removed.map(_ -> CompletableFuture.<Void>completedFuture(null))
|
||||
.orElseGet(() ->
|
||||
messagesDynamoDb.deleteMessage(accountIdentifier, device, guid, message.getServerTimestamp())
|
||||
.thenRun(Util.NOOP)));
|
||||
}
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.MutationType;
|
||||
import com.apple.foundationdb.Transaction;
|
||||
import com.apple.foundationdb.subspace.Subspace;
|
||||
import com.apple.foundationdb.tuple.Tuple;
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.hash.Hashing;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.function.Function;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
|
||||
/// An implementation of a message store backed by FoundationDB.
|
||||
///
|
||||
/// @implNote The layout of elements in FoundationDB is as follows:
|
||||
/// * messages
|
||||
/// * {aci}
|
||||
/// * last => versionstamp
|
||||
/// * {deviceId}
|
||||
/// * queue
|
||||
/// * {versionstamp_1} => envelope_1
|
||||
/// * {versionstamp_2} => envelope_2
|
||||
public class FoundationDbMessageStore {
|
||||
|
||||
private final Database[] databases;
|
||||
private static final Subspace MESSAGES_SUBSPACE = new Subspace(Tuple.from("M"));
|
||||
private final Executor executor;
|
||||
|
||||
public FoundationDbMessageStore(final Database[] databases, final Executor executor) {
|
||||
this.databases = databases;
|
||||
this.executor = executor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert a message bundle for a set of devices belonging to a single recipient
|
||||
*
|
||||
* @param aci destination account identifier
|
||||
* @param messagesByDeviceId a map of deviceId => message envelope
|
||||
* @return a future that completes with a {@link Versionstamp} of the committed transaction
|
||||
*/
|
||||
public CompletableFuture<Versionstamp> insert(final AciServiceIdentifier aci,
|
||||
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId) {
|
||||
// We use Database#runAsync and not Database#run here because the latter would commit the transaction synchronously
|
||||
// and we would like to avoid any potential blocking in native code that could unexpectedly pin virtual threads. See https://forums.foundationdb.org/t/fdbdatabase-usage-from-java-api/593/2
|
||||
// for details.
|
||||
return getShardForAci(aci).runAsync(transaction -> {
|
||||
insert(aci, messagesByDeviceId, transaction);
|
||||
return CompletableFuture.completedFuture(transaction.getVersionstamp());
|
||||
})
|
||||
.thenComposeAsync(Function.identity(), executor)
|
||||
.thenApply(Versionstamp::complete);
|
||||
}
|
||||
|
||||
private void insert(final AciServiceIdentifier aci, final Map<Byte, MessageProtos.Envelope> messagesByDeviceId,
|
||||
final Transaction transaction) {
|
||||
messagesByDeviceId.forEach((deviceId, message) -> {
|
||||
final Subspace deviceQueueSubspace = getDeviceQueueSubspace(aci, deviceId);
|
||||
transaction.mutate(MutationType.SET_VERSIONSTAMPED_KEY, deviceQueueSubspace.packWithVersionstamp(Tuple.from(
|
||||
Versionstamp.incomplete())), message.toByteArray());
|
||||
});
|
||||
transaction.mutate(MutationType.SET_VERSIONSTAMPED_VALUE, getLastMessageKey(aci),
|
||||
Tuple.from(Versionstamp.incomplete()).packWithVersionstamp());
|
||||
}
|
||||
|
||||
private Database getShardForAci(final AciServiceIdentifier aci) {
|
||||
return databases[hashAciToShardNumber(aci)];
|
||||
}
|
||||
|
||||
private int hashAciToShardNumber(final AciServiceIdentifier aci) {
|
||||
// We use a consistent hash here to reduce the number of key remappings if we increase the number of shards
|
||||
return Hashing.consistentHash(aci.uuid().getLeastSignificantBits(), databases.length);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
Subspace getDeviceQueueSubspace(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return getDeviceSubspace(aci, deviceId).get("Q");
|
||||
}
|
||||
|
||||
private Subspace getDeviceSubspace(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return getAccountSubspace(aci).get(deviceId);
|
||||
}
|
||||
|
||||
private Subspace getAccountSubspace(final AciServiceIdentifier aci) {
|
||||
return MESSAGES_SUBSPACE.get(aci.uuid());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
byte[] getLastMessageKey(final AciServiceIdentifier aci) {
|
||||
return getAccountSubspace(aci).pack("l");
|
||||
}
|
||||
|
||||
}
|
||||
+1
-1
@@ -229,7 +229,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
try {
|
||||
return stripeClient.paymentIntents().create(builder.build(), commonOptions());
|
||||
} catch (StripeException e) {
|
||||
final String errorCode = e.getCode().toLowerCase(Locale.ROOT);
|
||||
final String errorCode = StringUtils.lowerCase(e.getCode(), Locale.ROOT);
|
||||
switch (errorCode) {
|
||||
case "amount_too_small","amount_too_large" ->
|
||||
throw ExceptionUtils.wrap(new SubscriptionException.InvalidAmount(errorCode));
|
||||
|
||||
@@ -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)));
|
||||
}
|
||||
}
|
||||
+34
-24
@@ -8,19 +8,22 @@ package org.whispersystems.textsecuregcm.websocket;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
|
||||
import java.time.Duration;
|
||||
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 +50,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 +61,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,18 +80,18 @@ 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;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
|
||||
openAuthenticatedWebSocketCounter =
|
||||
new OpenWebSocketCounter(OPEN_WEBSOCKET_GAUGE_NAME, NEW_CONNECTION_COUNTER_NAME, CONNECTED_DURATION_TIMER_NAME, Tags.of(AUTHENTICATED_TAG_NAME, "true"));
|
||||
new OpenWebSocketCounter(OPEN_WEBSOCKET_GAUGE_NAME, NEW_CONNECTION_COUNTER_NAME, CONNECTED_DURATION_TIMER_NAME, Duration.ofHours(3), Tags.of(AUTHENTICATED_TAG_NAME, "true"));
|
||||
|
||||
openUnauthenticatedWebSocketCounter =
|
||||
new OpenWebSocketCounter(OPEN_WEBSOCKET_GAUGE_NAME, NEW_CONNECTION_COUNTER_NAME, CONNECTED_DURATION_TIMER_NAME, Tags.of(AUTHENTICATED_TAG_NAME, "false"));
|
||||
new OpenWebSocketCounter(OPEN_WEBSOCKET_GAUGE_NAME, NEW_CONNECTION_COUNTER_NAME, CONNECTED_DURATION_TIMER_NAME, Duration.ofHours(3), Tags.of(AUTHENTICATED_TAG_NAME, "false"));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -104,7 +107,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 +124,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 +158,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");
|
||||
|
||||
+2
-1
@@ -55,7 +55,8 @@ public class ProvisioningConnectListener implements WebSocketConnectListener {
|
||||
this.timeout = timeout;
|
||||
this.openWebSocketCounter = new OpenWebSocketCounter(MetricsUtil.name(getClass(), "openWebsockets"),
|
||||
MetricsUtil.name(getClass(), "newConnections"),
|
||||
MetricsUtil.name(getClass(), "sessionDuration"));
|
||||
MetricsUtil.name(getClass(), "sessionDuration"),
|
||||
Duration.ofSeconds(90));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+74
-165
@@ -9,35 +9,30 @@ import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.time.Duration;
|
||||
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 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.controllers.MessageController;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestListener;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
@@ -47,10 +42,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,13 +59,10 @@ 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"));
|
||||
private static final DistributionSummary primaryDeviceMessageTime = Metrics.summary(
|
||||
name(MessageController.class, "primaryDeviceMessageDeliveryDuration"));
|
||||
private static final Counter sendMessageCounter = Metrics.counter(name(WebSocketConnection.class, "sendMessage"));
|
||||
private static final Counter bytesSentCounter = Metrics.counter(name(WebSocketConnection.class, "bytesSent"));
|
||||
private static final Counter sendFailuresCounter = Metrics.counter(name(WebSocketConnection.class, "sendFailures"));
|
||||
@@ -79,7 +71,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 +80,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 +96,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 +112,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 AtomicLong queueDrainStartNanoTime = new AtomicLong();
|
||||
private final AtomicReference<Disposable> messageSubscription = new AtomicReference<>();
|
||||
|
||||
private final Random random = new Random();
|
||||
private final Scheduler messageDeliveryScheduler;
|
||||
|
||||
private final ClientReleaseManager clientReleaseManager;
|
||||
@@ -152,50 +130,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 +151,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;
|
||||
@@ -215,17 +159,11 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
|
||||
|
||||
public void start() {
|
||||
pushNotificationManager.handleMessagesRetrieved(authenticatedAccount, authenticatedDevice, client.getUserAgent());
|
||||
queueDrainStartTime.set(System.currentTimeMillis());
|
||||
queueDrainStartNanoTime.set(System.nanoTime());
|
||||
processStoredMessages();
|
||||
}
|
||||
|
||||
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 +187,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)
|
||||
@@ -273,7 +213,6 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
|
||||
.thenApply(ignored -> null);
|
||||
|
||||
if (message.getType() != Envelope.Type.SERVER_DELIVERY_RECEIPT) {
|
||||
recordMessageDeliveryDuration(message.getServerTimestamp(), authenticatedDevice);
|
||||
sendDeliveryReceiptFor(message);
|
||||
}
|
||||
} else {
|
||||
@@ -294,15 +233,13 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
|
||||
}
|
||||
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
public static void recordMessageDeliveryDuration(long timestamp, Device messageDestinationDevice) {
|
||||
final long messageDeliveryDuration = System.currentTimeMillis() - timestamp;
|
||||
messageTime.record(messageDeliveryDuration);
|
||||
if (messageDestinationDevice.isPrimary()) {
|
||||
primaryDeviceMessageTime.record(messageDeliveryDuration);
|
||||
}
|
||||
})
|
||||
.thenRun(() -> sample.stop(Timer.builder(SEND_MESSAGE_DURATION_TIMER_NAME)
|
||||
.publishPercentileHistogram(true)
|
||||
.minimumExpectedValue(Duration.ofMillis(100))
|
||||
.maximumExpectedValue(Duration.ofDays(1))
|
||||
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(client.getUserAgent())))
|
||||
.register(Metrics.globalRegistry)));
|
||||
}
|
||||
|
||||
private void sendDeliveryReceiptFor(Envelope message) {
|
||||
@@ -341,15 +278,14 @@ 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();
|
||||
final long drainDurationNanos = System.nanoTime() - queueDrainStartNanoTime.get();
|
||||
|
||||
Metrics.summary(INITIAL_QUEUE_LENGTH_DISTRIBUTION_NAME, tags).record(sentMessageCounter.sum());
|
||||
Metrics.timer(INITIAL_QUEUE_DRAIN_TIMER_NAME, tags).record(drainDuration, TimeUnit.MILLISECONDS);
|
||||
Metrics.timer(INITIAL_QUEUE_DRAIN_TIMER_NAME, tags).record(drainDurationNanos, TimeUnit.NANOSECONDS);
|
||||
|
||||
if (drainDuration > SLOW_DRAIN_THRESHOLD) {
|
||||
if (drainDurationNanos > SLOW_DRAIN_THRESHOLD) {
|
||||
Metrics.counter(SLOW_QUEUE_DRAIN_COUNTER_NAME, tags).increment();
|
||||
}
|
||||
|
||||
@@ -361,44 +297,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 +323,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 +337,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 +355,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 +374,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 +416,23 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleConnectionDisplaced(final boolean connectedElsewhere) {
|
||||
public void handleConflictingMessageConsumer() {
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
+14
-11
@@ -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,
|
||||
@@ -264,7 +266,9 @@ record CommandDependencies(
|
||||
configuration.getReportMessageConfiguration().getReportTtl());
|
||||
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster,
|
||||
configuration.getReportMessageConfiguration().getCounterTtl());
|
||||
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache,
|
||||
RedisMessageAvailabilityManager redisMessageAvailabilityManager =
|
||||
new RedisMessageAvailabilityManager(messagesCluster, clientEventExecutor, asyncOperationQueueingExecutor);
|
||||
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
|
||||
reportMessageManager, messageDeletionExecutor, Clock.systemUTC());
|
||||
AccountLockManager accountLockManager = new AccountLockManager(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getDeletedAccountsLock().getTableName());
|
||||
@@ -274,7 +278,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 +301,8 @@ record CommandDependencies(
|
||||
remoteStorageHttpExecutor,
|
||||
remoteStorageRetryExecutor,
|
||||
configuration.getCdn3StorageManagerConfiguration()),
|
||||
secureValueRecoveryBCredentialsGenerator,
|
||||
secureValueRecoveryBClient,
|
||||
clock);
|
||||
|
||||
final IssuedReceiptsManager issuedReceiptsManager = new IssuedReceiptsManager(
|
||||
@@ -317,15 +323,12 @@ record CommandDependencies(
|
||||
configuration.getDynamoDbTables().getPushNotificationExperimentSamples().getTableName(),
|
||||
Clock.systemUTC());
|
||||
|
||||
WebSocketConnectionEventManager webSocketConnectionEventManager =
|
||||
new WebSocketConnectionEventManager(accountsManager, pushNotificationManager, 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(
|
||||
|
||||
-88
@@ -1,88 +0,0 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Duration;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.util.EncryptDeviceCreationTimestampUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.util.retry.Retry;
|
||||
|
||||
public class EncryptDeviceCreationTimestampCommand extends AbstractSinglePassCrawlAccountsCommand {
|
||||
@VisibleForTesting
|
||||
static final String DRY_RUN_ARGUMENT = "dry-run";
|
||||
|
||||
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");
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(EncryptDeviceCreationTimestampCommand.class);
|
||||
|
||||
public EncryptDeviceCreationTimestampCommand() {
|
||||
super("encrypt-device-creation-timestamps", "Encrypts the creation timestamp of devices on accounts");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(final Subparser subparser) {
|
||||
super.configure(subparser);
|
||||
|
||||
subparser.addArgument("--dry-run")
|
||||
.type(Boolean.class)
|
||||
.dest(DRY_RUN_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(true)
|
||||
.help("If true, don't actually update device records");
|
||||
}
|
||||
|
||||
@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 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)
|
||||
.then()
|
||||
.block();
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -177,13 +177,6 @@ class WhisperServerServiceTest {
|
||||
.build());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testOtlpConfig() {
|
||||
final OpenTelemetryConfiguration otelConfig =EXTENSION.getConfiguration().getOpenTelemetryConfiguration();
|
||||
assertTrue(otelConfig.enabled());
|
||||
assertEquals("http://127.0.0.1:4318/", otelConfig.url());
|
||||
}
|
||||
|
||||
private static DynamoDbClient getDynamoDbClient() {
|
||||
final AwsCredentialsProvider awsCredentialsProvider = EXTENSION.getConfiguration().getAwsCredentialsConfiguration()
|
||||
.build();
|
||||
|
||||
+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 =
|
||||
|
||||
+40
-27
@@ -348,7 +348,8 @@ class DeviceControllerTest {
|
||||
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.of(new GcmRegistrationId("gcm-id"))));
|
||||
|
||||
final int expectedStatus =
|
||||
capability.preventDowngrade() && accountHasCapability && !requestHasCapability ? 409 : 200;
|
||||
capability.getAccountCapabilityMode() != DeviceCapability.AccountCapabilityMode.ALWAYS_CAPABLE
|
||||
&& capability.preventDowngrade() && accountHasCapability && !requestHasCapability ? 409 : 200;
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v1/devices/link")
|
||||
@@ -1082,31 +1083,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 +1123,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 +1154,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 +1193,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()
|
||||
|
||||
+1
-1
@@ -195,7 +195,7 @@ class MessageControllerTest {
|
||||
new MessageController(rateLimiters, cardinalityEstimator, messageSender, receiptSender, accountsManager,
|
||||
messagesManager, phoneNumberIdentifiers, pushNotificationManager, pushNotificationScheduler,
|
||||
reportMessageManager, messageDeliveryScheduler, mock(ClientReleaseManager.class),
|
||||
serverSecretParams, SpamChecker.noop(), new MessageMetrics(), mock(MessageDeliveryLoopMonitor.class),
|
||||
serverSecretParams, SpamChecker.noop(), new MessageMetrics(Duration.ofDays(30)), mock(MessageDeliveryLoopMonitor.class),
|
||||
clock))
|
||||
.build();
|
||||
|
||||
|
||||
-3
@@ -442,9 +442,7 @@ class ProfileControllerTest {
|
||||
|
||||
@CartesianTest
|
||||
void testProfileCapabilities(
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean isDeleteSyncSupported,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean isAttachmentBackfillSupported) {
|
||||
when(capabilitiesAccount.hasCapability(DeviceCapability.DELETE_SYNC)).thenReturn(isDeleteSyncSupported);
|
||||
when(capabilitiesAccount.hasCapability(DeviceCapability.ATTACHMENT_BACKFILL)).thenReturn(isAttachmentBackfillSupported);
|
||||
final BaseProfileResponse profile = resources.getJerseyTest()
|
||||
.target("/v1/profile/" + AuthHelper.VALID_UUID)
|
||||
@@ -452,7 +450,6 @@ class ProfileControllerTest {
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get(BaseProfileResponse.class);
|
||||
|
||||
assertEquals(isDeleteSyncSupported, profile.getCapabilities().get("deleteSync"));
|
||||
assertEquals(isAttachmentBackfillSupported, profile.getCapabilities().get("attachmentBackfill"));
|
||||
}
|
||||
|
||||
|
||||
-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);
|
||||
|
||||
-3
@@ -100,7 +100,6 @@ import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
|
||||
@@ -451,7 +450,6 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
|
||||
when(account.getBadges()).thenReturn(Collections.emptyList());
|
||||
when(account.hasCapability(any())).thenReturn(false);
|
||||
when(account.hasCapability(DeviceCapability.DELETE_SYNC)).thenReturn(true);
|
||||
when(profileBadgeConverter.convert(any(), any(), anyBoolean())).thenReturn(badges);
|
||||
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
|
||||
|
||||
@@ -462,7 +460,6 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
|
||||
.setUnidentifiedAccess(ByteString.copyFrom(unidentifiedAccessChecksum))
|
||||
.setUnrestrictedUnidentifiedAccess(true)
|
||||
.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_DELETE_SYNC)
|
||||
.addAllBadges(ProfileGrpcHelper.buildBadges(badges))
|
||||
.build();
|
||||
|
||||
|
||||
+2
-1
@@ -14,6 +14,7 @@ import static org.mockito.Mockito.when;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Meter;
|
||||
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
|
||||
import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -42,7 +43,7 @@ class MessageMetricsTest {
|
||||
when(account.isIdentifiedBy(new AciServiceIdentifier(aci))).thenReturn(true);
|
||||
when(account.isIdentifiedBy(new PniServiceIdentifier(pni))).thenReturn(true);
|
||||
simpleMeterRegistry = new SimpleMeterRegistry();
|
||||
messageMetrics = new MessageMetrics(simpleMeterRegistry);
|
||||
messageMetrics = new MessageMetrics(simpleMeterRegistry, Duration.ofDays(30));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -10,14 +10,26 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import io.micrometer.core.instrument.Clock;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Meter;
|
||||
import io.micrometer.core.instrument.MeterRegistry;
|
||||
import io.micrometer.core.instrument.cumulative.CumulativeDistributionSummary;
|
||||
import io.micrometer.core.instrument.distribution.CountAtBucket;
|
||||
import io.micrometer.core.instrument.distribution.DistributionStatisticConfig;
|
||||
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
|
||||
import io.micrometer.registry.otlp.OtlpMeterRegistry;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import org.assertj.core.api.AbstractStringAssert;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.whispersystems.textsecuregcm.configuration.OpenTelemetryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicMetricsConfiguration;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
@@ -81,4 +93,34 @@ class MetricsUtilTest {
|
||||
|
||||
assertThat(registry.getMeters()).hasSize(enableAwsSdkMetrics ? 1 : 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void exponentialHistogramBuckets() {
|
||||
final OpenTelemetryConfiguration openTelemetryConfig =
|
||||
new OpenTelemetryConfiguration(true, Duration.ZERO, 8, Map.of(), Map.of());
|
||||
|
||||
// Yes, this has to be OtlpMeterRegistry—its histograms behave differently than SimpleMeterRegistry's
|
||||
final MeterRegistry registry = new OtlpMeterRegistry(openTelemetryConfig, Clock.SYSTEM);
|
||||
|
||||
MetricsUtil.configureHistogramFilters(registry.config(), openTelemetryConfig);
|
||||
final DistributionSummary summary = DistributionSummary.builder("test.distribution")
|
||||
.publishPercentileHistogram()
|
||||
.minimumExpectedValue(1.0)
|
||||
.maximumExpectedValue(64.0)
|
||||
.register(registry);
|
||||
|
||||
IntStream.range(1, 128).forEach(summary::record);
|
||||
|
||||
final CountAtBucket[] counts = summary.takeSnapshot().histogramCounts();
|
||||
assertThat(counts).containsExactly(
|
||||
new CountAtBucket(1.0, 1),
|
||||
new CountAtBucket(2.0, 1),
|
||||
new CountAtBucket(4.0, 2),
|
||||
new CountAtBucket(8.0, 4),
|
||||
new CountAtBucket(16.0, 8),
|
||||
new CountAtBucket(32.0, 16),
|
||||
new CountAtBucket(64.0, 32),
|
||||
new CountAtBucket(Double.POSITIVE_INFINITY, 63));
|
||||
}
|
||||
|
||||
}
|
||||
+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 handleConflictingMessageConsumer() {
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 handleConflictingMessageConsumer() {
|
||||
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 handleConflictingMessageConsumer() {
|
||||
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
@@ -70,7 +70,7 @@ import org.whispersystems.textsecuregcm.util.RedisClusterUtil;
|
||||
@Timeout(value = 5, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
|
||||
class FaultTolerantRedisClusterClientTest {
|
||||
|
||||
private static final Duration TIMEOUT = Duration.ofMillis(50);
|
||||
private static final Duration TIMEOUT = Duration.ofMillis(200);
|
||||
|
||||
private static final RetryConfiguration RETRY_CONFIGURATION = new RetryConfiguration();
|
||||
|
||||
|
||||
+7
-15
@@ -4,7 +4,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.i18n.phonenumbers.PhoneNumberToTimeZonesMapper;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
@@ -13,13 +12,9 @@ import java.time.LocalTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
|
||||
class SchedulingUtilTest {
|
||||
@@ -51,26 +46,23 @@ class SchedulingUtilTest {
|
||||
|
||||
{
|
||||
final Account account = mock(Account.class);
|
||||
final Device primaryDevice = mock(Device.class);
|
||||
|
||||
// The account does not have a phone number that can be connected to a region/time zone
|
||||
when(account.getNumber()).thenReturn("Not a parseable number");
|
||||
when(account.getPrimaryDevice()).thenReturn(primaryDevice);
|
||||
when(primaryDevice.getCreated())
|
||||
.thenReturn(ZonedDateTime.of(2024, 7, 10, 9, 53, 12, 0, ZoneId.systemDefault()).toInstant().toEpochMilli());
|
||||
|
||||
final ZonedDateTime beforeNotificationTime = ZonedDateTime.now(ZoneId.systemDefault()).with(LocalTime.of(9, 0));
|
||||
final ZonedDateTime beforeNotificationTime = ZonedDateTime.now(ZoneId.systemDefault()).with(LocalTime.of(13, 59));
|
||||
final LocalTime preferredNotificationTime = LocalTime.of(14, 0);
|
||||
|
||||
assertEquals(
|
||||
beforeNotificationTime.with(LocalTime.of(9, 53, 12)).toInstant(),
|
||||
SchedulingUtil.getNextRecommendedNotificationTime(account, LocalTime.of(14, 0),
|
||||
beforeNotificationTime.with(preferredNotificationTime).toInstant(),
|
||||
SchedulingUtil.getNextRecommendedNotificationTime(account, preferredNotificationTime,
|
||||
Clock.fixed(beforeNotificationTime.toInstant(), ZoneId.systemDefault())));
|
||||
|
||||
final ZonedDateTime afterNotificationTime = ZonedDateTime.now(ZoneId.systemDefault()).with(LocalTime.of(10, 0));
|
||||
final ZonedDateTime afterNotificationTime = ZonedDateTime.now(ZoneId.systemDefault()).with(LocalTime.of(14, 1));
|
||||
|
||||
assertEquals(
|
||||
afterNotificationTime.with(LocalTime.of(9, 53, 12)).plusDays(1).toInstant(),
|
||||
SchedulingUtil.getNextRecommendedNotificationTime(account, LocalTime.of(14, 0),
|
||||
afterNotificationTime.with(preferredNotificationTime).plusDays(1).toInstant(),
|
||||
SchedulingUtil.getNextRecommendedNotificationTime(account, preferredNotificationTime,
|
||||
Clock.fixed(afterNotificationTime.toInstant(), ZoneId.systemDefault())));
|
||||
}
|
||||
}
|
||||
|
||||
+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")
|
||||
|
||||
@@ -38,8 +38,6 @@ class AccountTest {
|
||||
private final Device agingSecondaryDevice = mock(Device.class);
|
||||
private final Device recentSecondaryDevice = mock(Device.class);
|
||||
private final Device oldSecondaryDevice = mock(Device.class);
|
||||
private final Device deleteSyncCapableDevice = mock(Device.class);
|
||||
private final Device deleteSyncIncapableDevice = mock(Device.class);
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
@@ -58,12 +56,6 @@ class AccountTest {
|
||||
|
||||
when(oldSecondaryDevice.getLastSeen()).thenReturn(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(366));
|
||||
when(oldSecondaryDevice.getId()).thenReturn(deviceId2);
|
||||
|
||||
when(deleteSyncCapableDevice.getId()).thenReturn((byte) 1);
|
||||
when(deleteSyncCapableDevice.hasCapability(DeviceCapability.DELETE_SYNC)).thenReturn(true);
|
||||
|
||||
when(deleteSyncIncapableDevice.getId()).thenReturn((byte) 2);
|
||||
when(deleteSyncIncapableDevice.hasCapability(DeviceCapability.DELETE_SYNC)).thenReturn(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -121,13 +113,21 @@ class AccountTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void isDeleteSyncSupported() {
|
||||
void hardcodedCapabilities() {
|
||||
final Device mockDevice = mock(Device.class);
|
||||
when(mockDevice.getId()).thenReturn(Device.PRIMARY_ID);
|
||||
|
||||
assertTrue(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(),
|
||||
List.of(deleteSyncCapableDevice),
|
||||
List.of(mockDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).hasCapability(DeviceCapability.DELETE_SYNC));
|
||||
|
||||
assertTrue(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(),
|
||||
List.of(mockDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).hasCapability(DeviceCapability.STORAGE_SERVICE_RECORD_KEY_ROTATION));
|
||||
|
||||
assertFalse(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(),
|
||||
List.of(deleteSyncIncapableDevice, deleteSyncCapableDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).hasCapability(DeviceCapability.DELETE_SYNC));
|
||||
List.of(mockDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).hasCapability(DeviceCapability.TRANSFER));
|
||||
}
|
||||
|
||||
void stale() {
|
||||
|
||||
+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,
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@ import java.io.IOException;
|
||||
import org.junit.jupiter.api.extension.BeforeAllCallback;
|
||||
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||
|
||||
class FoundationDbExtension implements BeforeAllCallback, ExtensionContext.Store.CloseableResource {
|
||||
public class FoundationDbExtension implements BeforeAllCallback, ExtensionContext.Store.CloseableResource {
|
||||
|
||||
private static FoundationDbDatabaseLifecycleManager databaseLifecycleManager;
|
||||
|
||||
|
||||
+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());
|
||||
}
|
||||
|
||||
+10
-15
@@ -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;
|
||||
|
||||
@@ -85,18 +82,16 @@ class MessagePersisterIntegrationTest {
|
||||
|
||||
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
messageDeliveryScheduler, messageDeletionExecutorService, Clock.systemUTC());
|
||||
messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, mock(ReportMessageManager.class),
|
||||
messageDeletionExecutorService, Clock.systemUTC());
|
||||
messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, mock(RedisMessageAvailabilityManager.class),
|
||||
mock(ReportMessageManager.class), messageDeletionExecutorService, Clock.systemUTC());
|
||||
|
||||
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 handleConflictingMessageConsumer() {
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
+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<>();
|
||||
|
||||
|
||||
+2
-1
@@ -40,6 +40,7 @@ import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.tests.util.MultiRecipientMessageHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.TestRecipient;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
@@ -54,7 +55,7 @@ class MessagesManagerTest {
|
||||
private static final TestClock CLOCK = TestClock.pinned(Instant.now());
|
||||
|
||||
private final MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache,
|
||||
reportMessageManager, Executors.newSingleThreadExecutor(), CLOCK);
|
||||
mock(RedisMessageAvailabilityManager.class), reportMessageManager, Executors.newSingleThreadExecutor(), CLOCK);
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
|
||||
+398
@@ -0,0 +1,398 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.timeout;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.io.IOException;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
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;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.Disposable;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
import reactor.test.StepVerifier;
|
||||
|
||||
@Timeout(value = 5, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
|
||||
class RedisDynamoDbMessagePublisherTest {
|
||||
|
||||
private MessagesDynamoDb messagesDynamoDb;
|
||||
private MessagesCache messagesCache;
|
||||
private RedisMessageAvailabilityManager redisMessageAvailabilityManager;
|
||||
|
||||
private static ExecutorService sharedExecutorService;
|
||||
private static Scheduler messageDeliveryScheduler;
|
||||
|
||||
private Device destinationDevice;
|
||||
|
||||
@RegisterExtension
|
||||
static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(DynamoDbExtensionSchema.Tables.MESSAGES);
|
||||
|
||||
@RegisterExtension
|
||||
static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
|
||||
|
||||
private static final AtomicLong SERIAL_TIMESTAMP = new AtomicLong(0);
|
||||
|
||||
private static final ServiceIdentifier DESTINATION_SERVICE_IDENTIFIER = new AciServiceIdentifier(UUID.randomUUID());
|
||||
|
||||
@BeforeAll
|
||||
static void setUpBeforeAll() {
|
||||
sharedExecutorService = Executors.newVirtualThreadPerTaskExecutor();
|
||||
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
messagesDynamoDb = new MessagesDynamoDb(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
|
||||
DynamoDbExtensionSchema.Tables.MESSAGES.tableName(),
|
||||
Duration.ofDays(14),
|
||||
sharedExecutorService);
|
||||
|
||||
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
messageDeliveryScheduler, sharedExecutorService, Clock.systemUTC());
|
||||
|
||||
redisMessageAvailabilityManager = mock(RedisMessageAvailabilityManager.class);
|
||||
|
||||
destinationDevice = mock(Device.class);
|
||||
when(destinationDevice.getId()).thenReturn(Device.PRIMARY_ID);
|
||||
when(destinationDevice.getCreated()).thenReturn(System.currentTimeMillis());
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void tearDownAfterAll() {
|
||||
sharedExecutorService.shutdown();
|
||||
messageDeliveryScheduler.dispose();
|
||||
}
|
||||
|
||||
@Test
|
||||
void subscribeDispose() {
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getId()).thenReturn(deviceId);
|
||||
when(device.getCreated()).thenReturn(System.currentTimeMillis());
|
||||
|
||||
{
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
|
||||
final RedisDynamoDbMessagePublisher _ =
|
||||
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, accountIdentifier, device);
|
||||
|
||||
verify(redisMessageAvailabilityManager, never()).handleClientConnected(eq(accountIdentifier), eq(deviceId), any());
|
||||
verify(redisMessageAvailabilityManager, never()).handleClientDisconnected(eq(accountIdentifier), eq(deviceId));
|
||||
}
|
||||
|
||||
{
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
|
||||
final RedisDynamoDbMessagePublisher messagePublisher =
|
||||
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, accountIdentifier, device);
|
||||
|
||||
JdkFlowAdapter.flowPublisherToFlux(messagePublisher).subscribe();
|
||||
|
||||
verify(redisMessageAvailabilityManager).handleClientConnected(eq(accountIdentifier), eq(deviceId), any());
|
||||
verify(redisMessageAvailabilityManager, never()).handleClientDisconnected(eq(accountIdentifier), eq(deviceId));
|
||||
}
|
||||
|
||||
{
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
|
||||
final RedisDynamoDbMessagePublisher messagePublisher =
|
||||
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, accountIdentifier, device);
|
||||
|
||||
final Disposable disposable = JdkFlowAdapter.flowPublisherToFlux(messagePublisher).subscribe();
|
||||
disposable.dispose();
|
||||
|
||||
verify(redisMessageAvailabilityManager).handleClientConnected(eq(accountIdentifier), eq(deviceId), any());
|
||||
verify(redisMessageAvailabilityManager).handleClientDisconnected(eq(accountIdentifier), eq(deviceId));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishMessages() {
|
||||
final MessageProtos.Envelope dynamoDbMessage = insertDynamoDbMessage(generateRandomMessage());
|
||||
final MessageProtos.Envelope redisMessage = insertRedisMessage(generateRandomMessage());
|
||||
|
||||
final RedisDynamoDbMessagePublisher messagePublisher =
|
||||
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice);
|
||||
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher))
|
||||
.expectNext(new MessageStreamEntry.Envelope(dynamoDbMessage))
|
||||
.expectNext(new MessageStreamEntry.Envelope(redisMessage))
|
||||
.expectNext(new MessageStreamEntry.QueueEmpty())
|
||||
.verifyTimeout(Duration.ofMillis(500));
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishMessagesDynamoDbOnly() {
|
||||
final MessageProtos.Envelope dynamoDbMessage = insertDynamoDbMessage(generateRandomMessage());
|
||||
|
||||
final RedisDynamoDbMessagePublisher messagePublisher =
|
||||
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice);
|
||||
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher))
|
||||
.expectNext(new MessageStreamEntry.Envelope(dynamoDbMessage))
|
||||
.expectNext(new MessageStreamEntry.QueueEmpty())
|
||||
.verifyTimeout(Duration.ofMillis(500));
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishMessagesRedisOnly() {
|
||||
final MessageProtos.Envelope redisMessage = insertRedisMessage(generateRandomMessage());
|
||||
|
||||
final RedisDynamoDbMessagePublisher messagePublisher =
|
||||
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice);
|
||||
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher))
|
||||
.expectNext(new MessageStreamEntry.Envelope(redisMessage))
|
||||
.expectNext(new MessageStreamEntry.QueueEmpty())
|
||||
.verifyTimeout(Duration.ofMillis(500));
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishMessagesTailNewRedisMessages() {
|
||||
final MessageProtos.Envelope dynamoDbMessage = insertDynamoDbMessage(generateRandomMessage());
|
||||
final MessageProtos.Envelope redisMessage = insertRedisMessage(generateRandomMessage());
|
||||
|
||||
final MessageProtos.Envelope newArrivalRedisMessage = generateRandomMessage();
|
||||
|
||||
final RedisDynamoDbMessagePublisher messagePublisher =
|
||||
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice);
|
||||
|
||||
final CountDownLatch queueEmptyCountDownLatch = new CountDownLatch(1);
|
||||
|
||||
Thread.ofVirtual().start(() -> {
|
||||
try {
|
||||
queueEmptyCountDownLatch.await();
|
||||
} catch (final InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
deleteRedisMessage(redisMessage);
|
||||
deleteDynamoDbMessage(dynamoDbMessage);
|
||||
|
||||
insertRedisMessage(newArrivalRedisMessage);
|
||||
messagePublisher.handleNewMessageAvailable();
|
||||
});
|
||||
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher)
|
||||
.doOnNext(entry -> {
|
||||
if (entry instanceof MessageStreamEntry.QueueEmpty) {
|
||||
queueEmptyCountDownLatch.countDown();
|
||||
}
|
||||
}))
|
||||
.expectNext(new MessageStreamEntry.Envelope(dynamoDbMessage))
|
||||
.expectNext(new MessageStreamEntry.Envelope(redisMessage))
|
||||
.expectNext(new MessageStreamEntry.QueueEmpty())
|
||||
.expectNext(new MessageStreamEntry.Envelope(newArrivalRedisMessage))
|
||||
.verifyTimeout(Duration.ofMillis(500));
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishMessagesTailNewPersistedMessages() {
|
||||
final MessageProtos.Envelope dynamoDbMessage = insertDynamoDbMessage(generateRandomMessage());
|
||||
final MessageProtos.Envelope redisMessage = insertRedisMessage(generateRandomMessage());
|
||||
|
||||
final MessageProtos.Envelope persistedMessage = generateRandomMessage();
|
||||
|
||||
final RedisDynamoDbMessagePublisher messagePublisher =
|
||||
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice);
|
||||
|
||||
final CountDownLatch queueEmptyCountDownLatch = new CountDownLatch(1);
|
||||
|
||||
Thread.ofVirtual().start(() -> {
|
||||
try {
|
||||
queueEmptyCountDownLatch.await();
|
||||
} catch (final InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
deleteRedisMessage(redisMessage);
|
||||
deleteDynamoDbMessage(dynamoDbMessage);
|
||||
|
||||
insertDynamoDbMessage(persistedMessage);
|
||||
messagePublisher.handleMessagesPersisted();
|
||||
});
|
||||
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher)
|
||||
.doOnNext(entry -> {
|
||||
if (entry instanceof MessageStreamEntry.QueueEmpty) {
|
||||
queueEmptyCountDownLatch.countDown();
|
||||
}
|
||||
}))
|
||||
.expectNext(new MessageStreamEntry.Envelope(dynamoDbMessage))
|
||||
.expectNext(new MessageStreamEntry.Envelope(redisMessage))
|
||||
.expectNext(new MessageStreamEntry.QueueEmpty())
|
||||
.expectNext(new MessageStreamEntry.Envelope(persistedMessage))
|
||||
.verifyTimeout(Duration.ofMillis(500));
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishMessagesConsumerConflict() {
|
||||
final RedisDynamoDbMessagePublisher messagePublisher =
|
||||
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice);
|
||||
|
||||
final CountDownLatch countDownLatch = new CountDownLatch(1);
|
||||
|
||||
Thread.ofVirtual().start(() -> {
|
||||
try {
|
||||
countDownLatch.await();
|
||||
} catch (final InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
messagePublisher.handleConflictingMessageConsumer();
|
||||
});
|
||||
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher)
|
||||
.doOnSubscribe(_ -> countDownLatch.countDown()))
|
||||
.expectError(ConflictingMessageConsumerException.class)
|
||||
.verify();
|
||||
|
||||
verify(redisMessageAvailabilityManager, timeout(1_000)).handleClientConnected(DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice.getId(), messagePublisher);
|
||||
verify(redisMessageAvailabilityManager, timeout(1_000)).handleClientDisconnected(DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice.getId());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"207, 173",
|
||||
"323, 0",
|
||||
"0, 221",
|
||||
})
|
||||
void publishMessagesMultipleRequests(final int persistedMessageCount, final int cachedMessageCount) {
|
||||
final List<MessageProtos.Envelope> expectedMessages = new ArrayList<>(persistedMessageCount + cachedMessageCount);
|
||||
|
||||
for (int i = 0; i < persistedMessageCount; i++) {
|
||||
expectedMessages.add(insertDynamoDbMessage(generateRandomMessage()));
|
||||
}
|
||||
|
||||
for (int i = 0; i < cachedMessageCount; i++) {
|
||||
expectedMessages.add(insertRedisMessage(generateRandomMessage()));
|
||||
}
|
||||
|
||||
final RedisDynamoDbMessagePublisher messagePublisher =
|
||||
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice);
|
||||
|
||||
final List<MessageProtos.Envelope> publishedMessages = new ArrayList<>(expectedMessages.size());
|
||||
|
||||
final CompletableFuture<Void> queueEmptyFuture = new CompletableFuture<>();
|
||||
|
||||
final Disposable disposable = JdkFlowAdapter.flowPublisherToFlux(messagePublisher)
|
||||
.limitRate(20)
|
||||
.doOnNext(entry -> {
|
||||
if (entry instanceof MessageStreamEntry.Envelope(final MessageProtos.Envelope message)) {
|
||||
publishedMessages.add(message);
|
||||
} else if (entry instanceof MessageStreamEntry.QueueEmpty) {
|
||||
queueEmptyFuture.complete(null);
|
||||
}
|
||||
})
|
||||
.subscribe();
|
||||
|
||||
queueEmptyFuture.thenRun(disposable::dispose).join();
|
||||
|
||||
assertEquals(expectedMessages, publishedMessages);
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishQueueEmptySignalDeferred() {
|
||||
final MessageProtos.Envelope redisMessage = insertRedisMessage(generateRandomMessage());
|
||||
|
||||
{
|
||||
final RedisDynamoDbMessagePublisher messagePublisher =
|
||||
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
|
||||
DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice);
|
||||
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher), 1)
|
||||
.expectNext(new MessageStreamEntry.Envelope(redisMessage))
|
||||
.verifyTimeout(Duration.ofMillis(500));
|
||||
}
|
||||
|
||||
{
|
||||
final RedisDynamoDbMessagePublisher messagePublisher =
|
||||
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
|
||||
DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice);
|
||||
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher), 2)
|
||||
.expectNext(new MessageStreamEntry.Envelope(redisMessage))
|
||||
.expectNext(new MessageStreamEntry.QueueEmpty())
|
||||
.verifyTimeout(Duration.ofMillis(500));
|
||||
}
|
||||
}
|
||||
|
||||
private MessageProtos.Envelope insertRedisMessage(final MessageProtos.Envelope message) {
|
||||
messagesCache.insert(UUID.fromString(message.getServerGuid()),
|
||||
DESTINATION_SERVICE_IDENTIFIER.uuid(),
|
||||
destinationDevice.getId(),
|
||||
message)
|
||||
.join();
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
private void deleteRedisMessage(final MessageProtos.Envelope message) {
|
||||
messagesCache.remove(DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice.getId(), UUID.fromString(message.getServerGuid())).join();
|
||||
}
|
||||
|
||||
private MessageProtos.Envelope insertDynamoDbMessage(final MessageProtos.Envelope message) {
|
||||
messagesDynamoDb.store(List.of(message), DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice);
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
private void deleteDynamoDbMessage(final MessageProtos.Envelope message) {
|
||||
messagesDynamoDb.deleteMessage(DESTINATION_SERVICE_IDENTIFIER.uuid(),
|
||||
destinationDevice,
|
||||
UUID.fromString(message.getServerGuid()),
|
||||
message.getServerTimestamp())
|
||||
.join();
|
||||
}
|
||||
|
||||
private static MessageProtos.Envelope generateRandomMessage() {
|
||||
|
||||
final long timestamp = SERIAL_TIMESTAMP.incrementAndGet();
|
||||
|
||||
final MessageProtos.Envelope.Builder envelopeBuilder = MessageProtos.Envelope.newBuilder()
|
||||
.setClientTimestamp(timestamp)
|
||||
.setServerTimestamp(timestamp)
|
||||
.setContent(ByteString.copyFromUtf8(RandomStringUtils.secure().nextAlphanumeric(256)))
|
||||
.setType(MessageProtos.Envelope.Type.CIPHERTEXT)
|
||||
.setServerGuid(UUID.randomUUID().toString())
|
||||
.setDestinationServiceId(DESTINATION_SERVICE_IDENTIFIER.toServiceIdentifierString());
|
||||
|
||||
return envelopeBuilder.build();
|
||||
}
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyByte;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
|
||||
class RedisDynamoDbMessageStreamTest {
|
||||
|
||||
private MessagesDynamoDb messagesDynamoDb;
|
||||
private MessagesCache messagesCache;
|
||||
|
||||
private RedisDynamoDbMessageStream redisDynamoDbMessageStream;
|
||||
|
||||
private Device device;
|
||||
|
||||
private static final UUID ACCOUNT_IDENTIFIER = UUID.randomUUID();
|
||||
private static final byte DEVICE_ID = Device.PRIMARY_ID;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
messagesDynamoDb = mock(MessagesDynamoDb.class);
|
||||
messagesCache = mock(MessagesCache.class);
|
||||
|
||||
device = mock(Device.class);
|
||||
when(device.getId()).thenReturn(DEVICE_ID);
|
||||
|
||||
redisDynamoDbMessageStream = new RedisDynamoDbMessageStream(messagesDynamoDb,
|
||||
messagesCache,
|
||||
mock(RedisMessageAvailabilityManager.class),
|
||||
ACCOUNT_IDENTIFIER,
|
||||
device);
|
||||
|
||||
when(messagesDynamoDb.deleteMessage(any(), any(), any(), anyLong()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.empty()));
|
||||
|
||||
when(messagesCache.remove(any(), anyByte(), any(UUID.class)))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.empty()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void acknowledgeMessageDynamoDb() {
|
||||
final MessageProtos.Envelope message = generateMessage();
|
||||
final UUID messageGuid = UUID.fromString(message.getServerGuid());
|
||||
final long serverTimestamp = message.getServerTimestamp();
|
||||
|
||||
when(messagesDynamoDb.deleteMessage(ACCOUNT_IDENTIFIER, device, messageGuid, serverTimestamp))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(message)));
|
||||
|
||||
redisDynamoDbMessageStream.acknowledgeMessage(message).join();
|
||||
|
||||
verify(messagesCache).remove(ACCOUNT_IDENTIFIER, DEVICE_ID, messageGuid);
|
||||
verify(messagesDynamoDb).deleteMessage(ACCOUNT_IDENTIFIER, device, messageGuid, serverTimestamp);
|
||||
}
|
||||
|
||||
@Test
|
||||
void acknowledgeMessageRedis() {
|
||||
final MessageProtos.Envelope message = generateMessage();
|
||||
final UUID messageGuid = UUID.fromString(message.getServerGuid());
|
||||
final long serverTimestamp = message.getServerTimestamp();
|
||||
|
||||
when(messagesCache.remove(ACCOUNT_IDENTIFIER, DEVICE_ID, messageGuid))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(RemovedMessage.fromEnvelope(message))));
|
||||
|
||||
redisDynamoDbMessageStream.acknowledgeMessage(message).join();
|
||||
|
||||
verify(messagesCache).remove(ACCOUNT_IDENTIFIER, DEVICE_ID, messageGuid);
|
||||
verify(messagesDynamoDb, never()).deleteMessage(any(), any(), any(), anyLong());
|
||||
}
|
||||
|
||||
private static MessageProtos.Envelope generateMessage() {
|
||||
return MessageProtos.Envelope.newBuilder()
|
||||
.setServerGuid(UUID.randomUUID().toString())
|
||||
.setDestinationServiceId(new AciServiceIdentifier(ACCOUNT_IDENTIFIER).toServiceIdentifierString())
|
||||
.setServerTimestamp(System.currentTimeMillis())
|
||||
.setClientTimestamp(System.currentTimeMillis())
|
||||
.setType(MessageProtos.Envelope.Type.CIPHERTEXT)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.tuple.Tuple;
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
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.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.FoundationDbExtension;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
|
||||
@Timeout(value = 5, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
|
||||
class FoundationDbMessageStoreTest {
|
||||
|
||||
@RegisterExtension
|
||||
static FoundationDbExtension FOUNDATION_DB_EXTENSION = new FoundationDbExtension();
|
||||
|
||||
private FoundationDbMessageStore foundationDbMessageStore;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
foundationDbMessageStore = new FoundationDbMessageStore(
|
||||
new Database[]{FOUNDATION_DB_EXTENSION.getDatabase()},
|
||||
Executors.newVirtualThreadPerTaskExecutor());
|
||||
}
|
||||
|
||||
@Test
|
||||
void insert() {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final List<Byte> deviceIds = IntStream.range(Device.PRIMARY_ID, Device.PRIMARY_ID + 6)
|
||||
.mapToObj(i -> (byte) i)
|
||||
.toList();
|
||||
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId = deviceIds.stream()
|
||||
.collect(Collectors.toMap(Function.identity(), _ -> generateRandomMessage()));
|
||||
final Versionstamp versionstamp = foundationDbMessageStore.insert(aci, messagesByDeviceId).join();
|
||||
assertNotNull(versionstamp);
|
||||
|
||||
final Map<Byte, MessageProtos.Envelope> storedMessagesByDeviceId = deviceIds.stream()
|
||||
.collect(Collectors.toMap(Function.identity(), deviceId -> {
|
||||
try {
|
||||
return MessageProtos.Envelope.parseFrom(getMessageByVersionstamp(aci, deviceId, versionstamp));
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}));
|
||||
|
||||
assertEquals(messagesByDeviceId, storedMessagesByDeviceId);
|
||||
assertEquals(versionstamp, getLastMessageVersionstamp(aci),
|
||||
"last message versionstamp should be the versionstamp of the last insert transaction");
|
||||
}
|
||||
|
||||
@Test
|
||||
void versionstampCorrectlyUpdatedOnMultipleInserts() {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage())).join();
|
||||
final Versionstamp secondMessageVersionstamp = foundationDbMessageStore.insert(aci,
|
||||
Map.of(Device.PRIMARY_ID, generateRandomMessage())).join();
|
||||
assertEquals(secondMessageVersionstamp, getLastMessageVersionstamp(aci));
|
||||
}
|
||||
|
||||
private static MessageProtos.Envelope generateRandomMessage() {
|
||||
return MessageProtos.Envelope.newBuilder()
|
||||
.setContent(ByteString.copyFrom(TestRandomUtil.nextBytes(16)))
|
||||
.build();
|
||||
}
|
||||
|
||||
private byte[] getMessageByVersionstamp(final AciServiceIdentifier aci, final byte deviceId,
|
||||
final Versionstamp versionstamp) {
|
||||
return FOUNDATION_DB_EXTENSION.getDatabase().read(transaction -> {
|
||||
final byte[] key = foundationDbMessageStore.getDeviceQueueSubspace(aci, deviceId)
|
||||
.pack(Tuple.from(versionstamp));
|
||||
return transaction.get(key);
|
||||
}).join();
|
||||
}
|
||||
|
||||
private Versionstamp getLastMessageVersionstamp(final AciServiceIdentifier aci) {
|
||||
return FOUNDATION_DB_EXTENSION.getDatabase()
|
||||
.read(transaction -> transaction.get(foundationDbMessageStore.getLastMessageKey(aci))
|
||||
.thenApply(Tuple::fromBytes)
|
||||
.thenApply(t -> t.getVersionstamp(0)))
|
||||
.join();
|
||||
}
|
||||
|
||||
}
|
||||
Loaded 100 of 105 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user