mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 09:56:47 +00:00
Compare commits
48
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8955e31a1e | ||
|
|
f7a3971c64 | ||
|
|
552079d3c2 | ||
|
|
59d984e25d | ||
|
|
d17b9322b7 | ||
|
|
12bc175776 | ||
|
|
376458efa8 | ||
|
|
886984861f | ||
|
|
b248b6bc12 | ||
|
|
8d0d0d61f1 | ||
|
|
26c348520f | ||
|
|
ec79386306 | ||
|
|
093ac6fb16 | ||
|
|
68e2c511b7 | ||
|
|
47c82b42d9 | ||
|
|
e1a3b48c6e | ||
|
|
b8b17ae473 | ||
|
|
b203344ed4 | ||
|
|
6d30a45017 | ||
|
|
3f9863c441 | ||
|
|
47294ef6b8 | ||
|
|
2356d7c629 | ||
|
|
4908a0aa9e | ||
|
|
6032764052 | ||
|
|
908a41814b | ||
|
|
3ae145bd60 | ||
|
|
b086a73353 | ||
|
|
794e254d90 | ||
|
|
760c5737f9 | ||
|
|
ea17eee320 | ||
|
|
09ce79bd43 | ||
|
|
2dfd17af4a | ||
|
|
a9975e524b | ||
|
|
5d062285c2 | ||
|
|
e4b0f3ced5 | ||
|
|
6545bb9edb | ||
|
|
70ce6eff9e | ||
|
|
c84d96abee | ||
|
|
09eb42e5c6 | ||
|
|
06388b514c | ||
|
|
7c17a4067c | ||
|
|
48ada8e8ca | ||
|
|
282bcf6f34 | ||
|
|
1446d1acf8 | ||
|
|
aae94ffae3 | ||
|
|
ebd906a45d | ||
|
|
e30beb9c9f | ||
|
|
5a2e297991 |
No files matched your search
@@ -9,6 +9,7 @@ jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
container: ubuntu:22.04
|
||||
timeout-minutes: 20
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
|
||||
@@ -8,9 +8,26 @@ Looking for protocol documentation? Check out the website!
|
||||
|
||||
https://signal.org/docs/
|
||||
|
||||
Cryptography Notice
|
||||
How to Build
|
||||
------------
|
||||
|
||||
```shell script
|
||||
$ ./mvnw clean test
|
||||
```
|
||||
|
||||
Security
|
||||
--------
|
||||
|
||||
Security issues should be sent to <a href=mailto:security@signal.org>security@signal.org</a>.
|
||||
|
||||
Help
|
||||
----
|
||||
|
||||
We cannot provide direct technical support. Get help running this software in your own environment in our [unofficial community forum][community forum].
|
||||
|
||||
Cryptography Notice
|
||||
-------------------
|
||||
|
||||
This distribution includes cryptographic software. The country in which you currently reside may have restrictions on the import, possession, use, and/or re-export to another country, of encryption software.
|
||||
BEFORE using any encryption software, please check your country's laws, regulations and policies concerning the import, possession, or use, and re-export of encryption software, to see if this is permitted.
|
||||
See <https://www.wassenaar.org/> for more information.
|
||||
@@ -19,8 +36,10 @@ The U.S. Government Department of Commerce, Bureau of Industry and Security (BIS
|
||||
The form and manner of this distribution makes it eligible for export under the License Exception ENC Technology Software Unrestricted (TSU) exception (see the BIS Export Administration Regulations, Section 740.13) for both object code and source code.
|
||||
|
||||
License
|
||||
---------------------
|
||||
-------
|
||||
|
||||
Copyright 2013-2024 Signal Messenger, LLC
|
||||
Copyright 2013 Signal Messenger, LLC
|
||||
|
||||
Licensed under the GNU AGPLv3: https://www.gnu.org/licenses/agpl-3.0.html
|
||||
|
||||
[community forum]: https://community.signalusers.org
|
||||
@@ -529,3 +529,6 @@ externalRequestFilter:
|
||||
- /example
|
||||
permittedInternalRanges:
|
||||
- 127.0.0.0/8
|
||||
|
||||
idlePrimaryDeviceReminder:
|
||||
minIdleDuration: P30D
|
||||
+16
@@ -37,6 +37,7 @@ import org.whispersystems.textsecuregcm.configuration.FcmConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.GcpAttachmentsConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.GenericZkConfig;
|
||||
import org.whispersystems.textsecuregcm.configuration.GooglePlayBillingConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.IdlePrimaryDeviceReminderConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.KeyTransparencyServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.LinkDeviceSecretConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.MaxDeviceConfiguration;
|
||||
@@ -336,6 +337,13 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private KeyTransparencyServiceConfiguration keyTransparencyService;
|
||||
|
||||
@JsonProperty
|
||||
private boolean logMessageDeliveryLoops;
|
||||
|
||||
@JsonProperty
|
||||
private IdlePrimaryDeviceReminderConfiguration idlePrimaryDeviceReminder =
|
||||
new IdlePrimaryDeviceReminderConfiguration(Duration.ofDays(30));
|
||||
|
||||
public TlsKeyStoreConfiguration getTlsKeyStoreConfiguration() {
|
||||
return tlsKeyStore;
|
||||
}
|
||||
@@ -558,4 +566,12 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
public KeyTransparencyServiceConfiguration getKeyTransparencyServiceConfiguration() {
|
||||
return keyTransparencyService;
|
||||
}
|
||||
|
||||
public boolean logMessageDeliveryLoops() {
|
||||
return logMessageDeliveryLoops;
|
||||
}
|
||||
|
||||
public IdlePrimaryDeviceReminderConfiguration idlePrimaryDeviceReminderConfiguration() {
|
||||
return idlePrimaryDeviceReminder;
|
||||
}
|
||||
}
|
||||
@@ -82,6 +82,7 @@ import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.CloudflareTurnCredentialsManager;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.IdlePrimaryDeviceAuthenticatedWebSocketUpgradeFilter;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
|
||||
@@ -94,10 +95,6 @@ import org.whispersystems.textsecuregcm.backup.BackupsDb;
|
||||
import org.whispersystems.textsecuregcm.backup.Cdn3BackupCredentialGenerator;
|
||||
import org.whispersystems.textsecuregcm.backup.Cdn3RemoteStorageManager;
|
||||
import org.whispersystems.textsecuregcm.badges.ConfiguredProfileBadgeConverter;
|
||||
import org.whispersystems.textsecuregcm.calls.routing.CallDnsRecordsManager;
|
||||
import org.whispersystems.textsecuregcm.calls.routing.CallRoutingTableManager;
|
||||
import org.whispersystems.textsecuregcm.calls.routing.DynamicConfigTurnRouter;
|
||||
import org.whispersystems.textsecuregcm.calls.routing.TurnCallRouter;
|
||||
import org.whispersystems.textsecuregcm.captcha.CaptchaChecker;
|
||||
import org.whispersystems.textsecuregcm.captcha.CaptchaClient;
|
||||
import org.whispersystems.textsecuregcm.captcha.RegistrationCaptchaManager;
|
||||
@@ -110,7 +107,6 @@ import org.whispersystems.textsecuregcm.controllers.AccountControllerV2;
|
||||
import org.whispersystems.textsecuregcm.controllers.ArchiveController;
|
||||
import org.whispersystems.textsecuregcm.controllers.AttachmentControllerV4;
|
||||
import org.whispersystems.textsecuregcm.controllers.CallLinkController;
|
||||
import org.whispersystems.textsecuregcm.controllers.CallRoutingController;
|
||||
import org.whispersystems.textsecuregcm.controllers.CallRoutingControllerV2;
|
||||
import org.whispersystems.textsecuregcm.controllers.CertificateController;
|
||||
import org.whispersystems.textsecuregcm.controllers.ChallengeController;
|
||||
@@ -141,8 +137,8 @@ import org.whispersystems.textsecuregcm.filters.ExternalRequestFilter;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteDeprecationFilter;
|
||||
import org.whispersystems.textsecuregcm.filters.RequestStatisticsFilter;
|
||||
import org.whispersystems.textsecuregcm.filters.RestDeprecationFilter;
|
||||
import org.whispersystems.textsecuregcm.filters.TimestampResponseFilter;
|
||||
import org.whispersystems.textsecuregcm.geo.MaxMindDatabaseManager;
|
||||
import org.whispersystems.textsecuregcm.grpc.AccountsAnonymousGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.AccountsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.ErrorMappingInterceptor;
|
||||
@@ -164,10 +160,12 @@ import org.whispersystems.textsecuregcm.jetty.JettyHttpConfigurationCustomizer;
|
||||
import org.whispersystems.textsecuregcm.keytransparency.KeyTransparencyServiceClient;
|
||||
import org.whispersystems.textsecuregcm.limits.CardinalityEstimator;
|
||||
import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor;
|
||||
import org.whispersystems.textsecuregcm.limits.NoopMessageDeliveryLoopMonitor;
|
||||
import org.whispersystems.textsecuregcm.limits.PushChallengeManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitByIpFilter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitChallengeManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.limits.RedisMessageDeliveryLoopMonitor;
|
||||
import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.DeviceLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.GrpcStatusRuntimeExceptionMapper;
|
||||
@@ -227,6 +225,7 @@ import org.whispersystems.textsecuregcm.storage.MessagesCache;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PersistentTimer;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.Profiles;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
@@ -331,6 +330,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
bootstrap.addCommand(new BackupMetricsCommand(Clock.systemUTC()));
|
||||
bootstrap.addCommand(new RemoveExpiredLinkedDevicesCommand());
|
||||
bootstrap.addCommand(new NotifyIdleDevicesCommand());
|
||||
|
||||
bootstrap.addCommand(new ProcessScheduledJobsServiceCommand("process-idle-device-notification-jobs",
|
||||
"Processes scheduled jobs to send notifications to idle devices",
|
||||
new IdleDeviceNotificationSchedulerFactory()));
|
||||
@@ -429,7 +429,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getDynamoDbTables().getRemoteConfig().getTableName());
|
||||
PushChallengeDynamoDb pushChallengeDynamoDb = new PushChallengeDynamoDb(dynamoDbClient,
|
||||
config.getDynamoDbTables().getPushChallenge().getTableName());
|
||||
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbClient,
|
||||
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
|
||||
config.getDynamoDbTables().getReportMessage().getTableName(),
|
||||
config.getReportMessageConfiguration().getReportTtl());
|
||||
RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
|
||||
@@ -616,7 +616,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster,
|
||||
config.getReportMessageConfiguration().getCounterTtl());
|
||||
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager,
|
||||
messageDeletionAsyncExecutor);
|
||||
messageDeletionAsyncExecutor, Clock.systemUTC());
|
||||
AccountLockManager accountLockManager = new AccountLockManager(dynamoDbClient,
|
||||
config.getDynamoDbTables().getDeletedAccountsLock().getTableName());
|
||||
ClientPublicKeysManager clientPublicKeysManager =
|
||||
@@ -653,7 +653,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
Subscriptions subscriptions = new Subscriptions(
|
||||
config.getDynamoDbTables().getSubscriptions().getTableName(), dynamoDbAsyncClient);
|
||||
MessageDeliveryLoopMonitor messageDeliveryLoopMonitor =
|
||||
new MessageDeliveryLoopMonitor(rateLimitersCluster);
|
||||
config.logMessageDeliveryLoops() ? new RedisMessageDeliveryLoopMonitor(rateLimitersCluster) : new NoopMessageDeliveryLoopMonitor();
|
||||
|
||||
disconnectionRequestManager.addListener(webSocketConnectionEventManager);
|
||||
|
||||
@@ -809,45 +809,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getAppleDeviceCheck().teamId(),
|
||||
config.getAppleDeviceCheck().bundleId());
|
||||
|
||||
final DynamicConfigTurnRouter configTurnRouter = new DynamicConfigTurnRouter(dynamicConfigurationManager);
|
||||
|
||||
MaxMindDatabaseManager geoIpCityDatabaseManager = new MaxMindDatabaseManager(
|
||||
recurringConfigSyncExecutor,
|
||||
awsCredentialsProvider,
|
||||
config.getMaxmindCityDatabase(),
|
||||
"city"
|
||||
);
|
||||
environment.lifecycle().manage(geoIpCityDatabaseManager);
|
||||
CallDnsRecordsManager callDnsRecordsManager = new CallDnsRecordsManager(
|
||||
recurringConfigSyncExecutor,
|
||||
awsCredentialsProvider,
|
||||
config.getCallingTurnDnsRecords()
|
||||
);
|
||||
environment.lifecycle().manage(callDnsRecordsManager);
|
||||
CallRoutingTableManager callRoutingTableManager = new CallRoutingTableManager(
|
||||
recurringConfigSyncExecutor,
|
||||
awsCredentialsProvider,
|
||||
config.getCallingTurnPerformanceTable(),
|
||||
"Performance"
|
||||
);
|
||||
environment.lifecycle().manage(callRoutingTableManager);
|
||||
CallRoutingTableManager manualCallRoutingTableManager = new CallRoutingTableManager(
|
||||
recurringConfigSyncExecutor,
|
||||
awsCredentialsProvider,
|
||||
config.getCallingTurnManualTable(),
|
||||
"Manual"
|
||||
);
|
||||
environment.lifecycle().manage(manualCallRoutingTableManager);
|
||||
|
||||
TurnCallRouter callRouter = new TurnCallRouter(
|
||||
callDnsRecordsManager,
|
||||
callRoutingTableManager,
|
||||
manualCallRoutingTableManager,
|
||||
configTurnRouter,
|
||||
geoIpCityDatabaseManager,
|
||||
false
|
||||
);
|
||||
|
||||
final GrpcClientConnectionManager grpcClientConnectionManager = new GrpcClientConnectionManager();
|
||||
|
||||
disconnectionRequestManager.addListener(grpcClientConnectionManager);
|
||||
@@ -999,7 +960,12 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
metricsHttpChannelListener.configure(environment);
|
||||
final MessageMetrics messageMetrics = new MessageMetrics();
|
||||
|
||||
// BufferingInterceptor is needed on the base environment but not the WebSocketEnvironment,
|
||||
// because we handle serialization of http responses on the websocket on our own and can
|
||||
// compute content lengths without it
|
||||
environment.jersey().register(new BufferingInterceptor());
|
||||
environment.jersey().register(new RestDeprecationFilter(dynamicConfigurationManager, experimentEnrollmentManager));
|
||||
|
||||
environment.jersey().register(new VirtualExecutorServiceProvider("managed-async-virtual-thread-"));
|
||||
environment.jersey().register(new RateLimitByIpFilter(rateLimiters));
|
||||
environment.jersey().register(new RequestStatisticsFilter(TrafficSource.HTTP));
|
||||
@@ -1015,6 +981,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getWebSocketConfiguration(), Duration.ofMillis(90000));
|
||||
webSocketEnvironment.jersey().register(new VirtualExecutorServiceProvider("managed-async-websocket-virtual-thread-"));
|
||||
webSocketEnvironment.setAuthenticator(new WebSocketAccountAuthenticator(accountAuthenticator, new AccountPrincipalSupplier(accountsManager)));
|
||||
webSocketEnvironment.setAuthenticatedWebSocketUpgradeFilter(new IdlePrimaryDeviceAuthenticatedWebSocketUpgradeFilter(
|
||||
config.idlePrimaryDeviceReminderConfiguration().minIdleDuration(), Clock.systemUTC()));
|
||||
webSocketEnvironment.setConnectListener(
|
||||
new AuthenticatedConnectListener(receiptSender, messagesManager, messageMetrics, pushNotificationManager,
|
||||
pushNotificationScheduler, webSocketConnectionEventManager, websocketScheduledExecutor,
|
||||
@@ -1096,6 +1064,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
log.info("Registered spam filter: {}", filter.getClass().getName());
|
||||
});
|
||||
|
||||
final PersistentTimer persistentTimer = new PersistentTimer(rateLimitersCluster, clock);
|
||||
|
||||
final PhoneVerificationTokenManager phoneVerificationTokenManager = new PhoneVerificationTokenManager(
|
||||
phoneNumberIdentifiers, registrationServiceClient, registrationRecoveryPasswordsManager, registrationRecoveryChecker);
|
||||
@@ -1107,14 +1076,13 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new AttachmentControllerV4(rateLimiters, gcsAttachmentGenerator, tusAttachmentGenerator,
|
||||
experimentEnrollmentManager),
|
||||
new ArchiveController(backupAuthManager, backupManager),
|
||||
new CallRoutingController(rateLimiters, callRouter, turnTokenGenerator, experimentEnrollmentManager, cloudflareTurnCredentialsManager),
|
||||
new CallRoutingControllerV2(rateLimiters, callRouter, turnTokenGenerator, experimentEnrollmentManager, cloudflareTurnCredentialsManager),
|
||||
new CallRoutingControllerV2(rateLimiters, cloudflareTurnCredentialsManager),
|
||||
new CallLinkController(rateLimiters, callingGenericZkSecretParams),
|
||||
new CertificateController(new CertificateGenerator(config.getDeliveryCertificate().certificate().value(),
|
||||
config.getDeliveryCertificate().ecPrivateKey(), config.getDeliveryCertificate().expiresDays()),
|
||||
zkAuthOperations, callingGenericZkSecretParams, clock),
|
||||
new ChallengeController(rateLimitChallengeManager, challengeConstraintChecker),
|
||||
new DeviceController(accountsManager, clientPublicKeysManager, rateLimiters, config.getMaxDevices()),
|
||||
new DeviceController(accountsManager, clientPublicKeysManager, rateLimiters, persistentTimer, config.getMaxDevices()),
|
||||
new DeviceCheckController(clock, backupAuthManager, appleDeviceCheckManager, rateLimiters,
|
||||
config.getDeviceCheck().backupRedemptionLevel(),
|
||||
config.getDeviceCheck().backupRedemptionDuration()),
|
||||
@@ -1125,7 +1093,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new KeyTransparencyController(keyTransparencyServiceClient),
|
||||
new MessageController(rateLimiters, messageByteLimitCardinalityEstimator, messageSender, receiptSender,
|
||||
accountsManager, messagesManager, phoneNumberIdentifiers, pushNotificationManager, pushNotificationScheduler,
|
||||
reportMessageManager, multiRecipientMessageExecutor, messageDeliveryScheduler, clientReleaseManager,
|
||||
reportMessageManager, messageDeliveryScheduler, clientReleaseManager,
|
||||
dynamicConfigurationManager, zkSecretParams, spamChecker, messageMetrics, messageDeliveryLoopMonitor,
|
||||
Clock.systemUTC()),
|
||||
new PaymentsController(currencyManager, paymentsCredentialsGenerator),
|
||||
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import org.eclipse.jetty.websocket.server.JettyServerUpgradeRequest;
|
||||
import org.eclipse.jetty.websocket.server.JettyServerUpgradeResponse;
|
||||
import org.whispersystems.websocket.ReusableAuth;
|
||||
import org.whispersystems.websocket.auth.AuthenticatedWebSocketUpgradeFilter;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
|
||||
public class IdlePrimaryDeviceAuthenticatedWebSocketUpgradeFilter implements
|
||||
AuthenticatedWebSocketUpgradeFilter<AuthenticatedDevice> {
|
||||
|
||||
private final Duration minIdleDuration;
|
||||
private final Clock clock;
|
||||
|
||||
@VisibleForTesting
|
||||
static final String ALERT_HEADER = "X-Signal-Alert";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String IDLE_PRIMARY_DEVICE_ALERT = "idle-primary-device";
|
||||
|
||||
public IdlePrimaryDeviceAuthenticatedWebSocketUpgradeFilter(final Duration minIdleDuration, final Clock clock) {
|
||||
this.minIdleDuration = minIdleDuration;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleAuthentication(final ReusableAuth<AuthenticatedDevice> authenticated,
|
||||
final JettyServerUpgradeRequest request,
|
||||
final JettyServerUpgradeResponse response) {
|
||||
|
||||
// No action needed if the connection is unauthenticated (in which case we don't know when we've last seen the
|
||||
// primary device) or if the authenticated device IS the primary device
|
||||
authenticated.ref()
|
||||
.filter(authenticatedDevice -> !authenticatedDevice.getAuthenticatedDevice().isPrimary())
|
||||
.ifPresent(authenticatedDevice -> {
|
||||
final Instant primaryDeviceLastSeen =
|
||||
Instant.ofEpochMilli(authenticatedDevice.getAccount().getPrimaryDevice().getLastSeen());
|
||||
|
||||
if (primaryDeviceLastSeen.isBefore(clock.instant().minus(minIdleDuration))) {
|
||||
response.addHeader(ALERT_HEADER, IDLE_PRIMARY_DEVICE_ALERT);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -169,8 +169,7 @@ public class RegistrationLockVerificationManager {
|
||||
throw new WebApplicationException(Response.status(FAILURE_HTTP_STATUS)
|
||||
.entity(new RegistrationLockFailure(
|
||||
existingRegistrationLock.getTimeRemaining().toMillis(),
|
||||
svr2FailureCredentials(existingRegistrationLock, updatedAccount),
|
||||
null))
|
||||
svr2FailureCredentials(existingRegistrationLock, updatedAccount)))
|
||||
.build());
|
||||
}
|
||||
|
||||
|
||||
+41
@@ -7,6 +7,9 @@ package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.Collection;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class UnidentifiedAccessUtil {
|
||||
|
||||
@@ -31,4 +34,42 @@ public class UnidentifiedAccessUtil {
|
||||
.map(targetUnidentifiedAccessKey -> MessageDigest.isEqual(targetUnidentifiedAccessKey, unidentifiedAccessKey))
|
||||
.orElse(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether an action (e.g. sending a message or retrieving pre-keys) may be taken on the collection of target
|
||||
* accounts by an actor presenting the given combined unidentified access key.
|
||||
*
|
||||
* @param targetAccounts the accounts on which an actor wishes to take an action
|
||||
* @param combinedUnidentifiedAccessKey the unidentified access key presented by the actor
|
||||
*
|
||||
* @return {@code true} if an actor presenting the given unidentified access key has permission to take an action on
|
||||
* the target accounts or {@code false} otherwise
|
||||
*/
|
||||
public static boolean checkUnidentifiedAccess(final Collection<Account> targetAccounts, final byte[] combinedUnidentifiedAccessKey) {
|
||||
return MessageDigest.isEqual(getCombinedUnidentifiedAccessKey(targetAccounts), combinedUnidentifiedAccessKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates a combined unidentified access key for the given collection of accounts.
|
||||
*
|
||||
* @param accounts the accounts from which to derive a combined unidentified access key
|
||||
* @return a combined unidentified access key
|
||||
*
|
||||
* @throws IllegalArgumentException if one or more of the given accounts had an unidentified access key with an
|
||||
* unexpected length
|
||||
*/
|
||||
public static byte[] getCombinedUnidentifiedAccessKey(final Collection<Account> accounts) {
|
||||
return accounts.stream()
|
||||
.filter(Predicate.not(Account::isUnrestrictedUnidentifiedAccess))
|
||||
.map(account ->
|
||||
account.getUnidentifiedAccessKey()
|
||||
.filter(b -> b.length == UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH)
|
||||
.orElseThrow(IllegalArgumentException::new))
|
||||
.reduce(new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH],
|
||||
(a, b) -> {
|
||||
final byte[] xor = new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH];
|
||||
IntStream.range(0, UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH).forEach(i -> xor[i] = (byte) (a[i] ^ b[i]));
|
||||
return xor;
|
||||
});
|
||||
}
|
||||
}
|
||||
+23
-4
@@ -14,6 +14,7 @@ import java.time.temporal.ChronoUnit;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
@@ -114,9 +115,17 @@ public class BackupAuthManager {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
|
||||
return rateLimiters.forDescriptor(RateLimiters.For.SET_BACKUP_ID)
|
||||
.validateAsync(account.getUuid())
|
||||
.thenCompose(ignored -> this.accountsManager
|
||||
CompletionStage<Void> rateLimitFuture = rateLimiters
|
||||
.forDescriptor(RateLimiters.For.SET_BACKUP_ID)
|
||||
.validateAsync(account.getUuid());
|
||||
|
||||
if (!mediaCredentialRequestMatches && hasActiveVoucher(account)) {
|
||||
rateLimitFuture = rateLimitFuture.thenCombine(
|
||||
rateLimiters.forDescriptor(RateLimiters.For.SET_PAID_MEDIA_BACKUP_ID).validateAsync(account.getUuid()),
|
||||
(ignore1, ignore2) -> null);
|
||||
}
|
||||
|
||||
return rateLimitFuture.thenCompose(ignored -> this.accountsManager
|
||||
.updateAsync(account, a -> a.setBackupCredentialRequests(serializedMessageCredentialRequest, serializedMediaCredentialRequest))
|
||||
.thenRun(Util.NOOP))
|
||||
.toCompletableFuture();
|
||||
@@ -227,6 +236,12 @@ public class BackupAuthManager {
|
||||
.asRuntimeException();
|
||||
}
|
||||
|
||||
if (account.getBackupCredentialRequest(BackupCredentialType.MEDIA).isEmpty()) {
|
||||
throw Status.ABORTED
|
||||
.withDescription("account must have a backup-id commitment")
|
||||
.asRuntimeException();
|
||||
}
|
||||
|
||||
return redeemedReceiptsManager
|
||||
.put(receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, account.getUuid())
|
||||
.thenCompose(receiptAllowed -> {
|
||||
@@ -280,8 +295,12 @@ public class BackupAuthManager {
|
||||
return next;
|
||||
}
|
||||
|
||||
private boolean hasActiveVoucher(final Account account) {
|
||||
return account.getBackupVoucher() != null && clock.instant().isBefore(account.getBackupVoucher().expiration());
|
||||
}
|
||||
|
||||
private boolean hasExpiredVoucher(final Account account) {
|
||||
return account.getBackupVoucher() != null && clock.instant().isAfter(account.getBackupVoucher().expiration());
|
||||
return account.getBackupVoucher() != null && !hasActiveVoucher(account);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
public record IdlePrimaryDeviceReminderConfiguration(Duration minIdleDuration) {
|
||||
}
|
||||
+10
@@ -6,6 +6,7 @@
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.vdurmont.semver4j.Semver;
|
||||
import jakarta.validation.Valid;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
@@ -13,6 +14,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiterConfig;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
|
||||
public class DynamicConfiguration {
|
||||
|
||||
@@ -72,6 +74,10 @@ public class DynamicConfiguration {
|
||||
@Valid
|
||||
List<String> svrStatusCodesToIgnoreForAccountDeletion = Collections.emptyList();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
Map<ClientPlatform, Semver> minimumRestFreeVersion = Map.of();
|
||||
|
||||
public Optional<DynamicExperimentEnrollmentConfiguration> getExperimentEnrollmentConfiguration(
|
||||
final String experimentName) {
|
||||
return Optional.ofNullable(experiments.get(experimentName));
|
||||
@@ -130,4 +136,8 @@ public class DynamicConfiguration {
|
||||
return svrStatusCodesToIgnoreForAccountDeletion;
|
||||
}
|
||||
|
||||
public Map<ClientPlatform, Semver> minimumRestFreeVersion() {
|
||||
return minimumRestFreeVersion;
|
||||
}
|
||||
|
||||
}
|
||||
+4
-1
@@ -34,6 +34,7 @@ import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.signal.libsignal.usernames.BaseUsernameException;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
@@ -232,7 +233,9 @@ public class AccountController {
|
||||
d.setName(attributes.getName());
|
||||
d.setLastSeen(Util.todayInMillis());
|
||||
d.setCapabilities(attributes.getCapabilities());
|
||||
d.setUserAgent(userAgent);
|
||||
if (StringUtils.isNotBlank(userAgent)) {
|
||||
d.setUserAgent(userAgent);
|
||||
}
|
||||
});
|
||||
|
||||
a.setRegistrationLockFromAttributes(attributes);
|
||||
|
||||
+4
@@ -173,9 +173,13 @@ public class ArchiveController {
|
||||
|
||||
After successful redemption, subsequent requests to /v1/archive/auth will return credentials with the level on
|
||||
the provided receipt until the expiration time on the receipt.
|
||||
|
||||
Accounts must have an existing backup credential request in order to redeem a receipt. This request will fail
|
||||
if the account has not already set a backup credential request via PUT `/v1/archives/backupid`.
|
||||
""")
|
||||
@ApiResponse(responseCode = "204", description = "The receipt was redeemed")
|
||||
@ApiResponse(responseCode = "400", description = "The provided presentation or receipt was invalid")
|
||||
@ApiResponse(responseCode = "409", description = "The target account does not have a backup-id commitment")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
public CompletionStage<Response> redeemReceipt(
|
||||
@Mutable @Auth final AuthenticatedDevice account,
|
||||
|
||||
-103
@@ -1,103 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.CloudflareTurnCredentialsManager;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnToken;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
|
||||
import org.whispersystems.textsecuregcm.calls.routing.TurnCallRouter;
|
||||
import org.whispersystems.textsecuregcm.calls.routing.TurnServerOptions;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
@Path("/v1/calling")
|
||||
@io.swagger.v3.oas.annotations.tags.Tag(name = "Calling")
|
||||
public class CallRoutingController {
|
||||
|
||||
private static final int TURN_INSTANCE_LIMIT = 2;
|
||||
private static final Counter INVALID_IP_COUNTER = Metrics.counter(name(CallRoutingController.class, "invalidIP"));
|
||||
private static final Logger log = LoggerFactory.getLogger(CallRoutingController.class);
|
||||
private final RateLimiters rateLimiters;
|
||||
private final TurnCallRouter turnCallRouter;
|
||||
private final TurnTokenGenerator tokenGenerator;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
private final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager;
|
||||
|
||||
public CallRoutingController(
|
||||
final RateLimiters rateLimiters,
|
||||
final TurnCallRouter turnCallRouter,
|
||||
final TurnTokenGenerator tokenGenerator,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager,
|
||||
final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager
|
||||
) {
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.turnCallRouter = turnCallRouter;
|
||||
this.tokenGenerator = tokenGenerator;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
this.cloudflareTurnCredentialsManager = cloudflareTurnCredentialsManager;
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/relays")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(
|
||||
summary = "Get 1:1 calling relay options for the client",
|
||||
description = """
|
||||
Get 1:1 relay addresses in IpV4, Ipv6, and URL formats.
|
||||
"""
|
||||
)
|
||||
@ApiResponse(responseCode = "200", description = "`JSON` with call endpoints.", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "400", description = "Invalid get call endpoint request.")
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format.")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
public TurnToken getCallingRelays(
|
||||
final @ReadOnly @Auth AuthenticatedDevice auth,
|
||||
@Context ContainerRequestContext requestContext
|
||||
) throws RateLimitExceededException, IOException {
|
||||
UUID aci = auth.getAccount().getUuid();
|
||||
rateLimiters.getCallEndpointLimiter().validate(aci);
|
||||
|
||||
if (experimentEnrollmentManager.isEnrolled(auth.getAccount().getNumber(), aci, "cloudflareTurn")) {
|
||||
return cloudflareTurnCredentialsManager.retrieveFromCloudflare();
|
||||
}
|
||||
|
||||
Optional<InetAddress> address = Optional.empty();
|
||||
try {
|
||||
final String remoteAddress = (String) requestContext.getProperty(
|
||||
RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
|
||||
address = Optional.of(InetAddress.getByName(remoteAddress));
|
||||
} catch (UnknownHostException e) {
|
||||
INVALID_IP_COUNTER.increment();
|
||||
}
|
||||
|
||||
TurnServerOptions options = turnCallRouter.getRoutingFor(aci, address, TURN_INSTANCE_LIMIT);
|
||||
return tokenGenerator.generateWithTurnServerOptions(options);
|
||||
}
|
||||
}
|
||||
+6
-38
@@ -18,20 +18,13 @@ import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.CloudflareTurnCredentialsManager;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnToken;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
|
||||
import org.whispersystems.textsecuregcm.calls.routing.TurnCallRouter;
|
||||
import org.whispersystems.textsecuregcm.calls.routing.TurnServerOptions;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
@@ -39,25 +32,15 @@ import org.whispersystems.websocket.auth.ReadOnly;
|
||||
@Path("/v2/calling")
|
||||
public class CallRoutingControllerV2 {
|
||||
|
||||
private static final Counter INVALID_IP_COUNTER = Metrics.counter(name(CallRoutingControllerV2.class, "invalidIP"));
|
||||
private static final Counter CLOUDFLARE_TURN_ERROR_COUNTER = Metrics.counter(name(CallRoutingController.class, "cloudflareTurnError"));
|
||||
private static final Counter CLOUDFLARE_TURN_ERROR_COUNTER = Metrics.counter(name(CallRoutingControllerV2.class, "cloudflareTurnError"));
|
||||
private final RateLimiters rateLimiters;
|
||||
private final TurnCallRouter turnCallRouter;
|
||||
private final TurnTokenGenerator tokenGenerator;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
private final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager;
|
||||
|
||||
public CallRoutingControllerV2(
|
||||
final RateLimiters rateLimiters,
|
||||
final TurnCallRouter turnCallRouter,
|
||||
final TurnTokenGenerator tokenGenerator,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager,
|
||||
final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager
|
||||
) {
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.turnCallRouter = turnCallRouter;
|
||||
this.tokenGenerator = tokenGenerator;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
this.cloudflareTurnCredentialsManager = cloudflareTurnCredentialsManager;
|
||||
}
|
||||
|
||||
@@ -76,34 +59,19 @@ public class CallRoutingControllerV2 {
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format.")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
public GetCallingRelaysResponse getCallingRelays(
|
||||
final @ReadOnly @Auth AuthenticatedDevice auth,
|
||||
@Context ContainerRequestContext requestContext
|
||||
) throws RateLimitExceededException {
|
||||
final @ReadOnly @Auth AuthenticatedDevice auth
|
||||
) throws RateLimitExceededException, IOException {
|
||||
UUID aci = auth.getAccount().getUuid();
|
||||
rateLimiters.getCallEndpointLimiter().validate(aci);
|
||||
|
||||
List<TurnToken> tokens = new ArrayList<>();
|
||||
try {
|
||||
if (experimentEnrollmentManager.isEnrolled(auth.getAccount().getNumber(), aci, "cloudflareTurn")) {
|
||||
tokens.add(cloudflareTurnCredentialsManager.retrieveFromCloudflare());
|
||||
}
|
||||
tokens.add(cloudflareTurnCredentialsManager.retrieveFromCloudflare());
|
||||
} catch (Exception e) {
|
||||
// emit counter, rely on Signal URL fallback
|
||||
CallRoutingControllerV2.CLOUDFLARE_TURN_ERROR_COUNTER.increment();
|
||||
throw e;
|
||||
}
|
||||
|
||||
Optional<InetAddress> address = Optional.empty();
|
||||
try {
|
||||
final String remoteAddress = (String) requestContext.getProperty(
|
||||
RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
|
||||
address = Optional.of(InetAddress.getByName(remoteAddress));
|
||||
} catch (UnknownHostException e) {
|
||||
INVALID_IP_COUNTER.increment();
|
||||
}
|
||||
|
||||
TurnServerOptions options = turnCallRouter.getRoutingFor(aci, address);
|
||||
tokens.add(tokenGenerator.generateWithTurnServerOptions(options));
|
||||
|
||||
return new GetCallingRelaysResponse(tokens);
|
||||
}
|
||||
|
||||
|
||||
+84
-40
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.lettuce.core.RedisException;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
@@ -43,7 +42,9 @@ import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import java.util.EnumMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
@@ -51,6 +52,7 @@ import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.glassfish.jersey.server.ContainerRequest;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
|
||||
@@ -81,6 +83,7 @@ import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceSpec;
|
||||
import org.whispersystems.textsecuregcm.storage.LinkDeviceTokenAlreadyUsedException;
|
||||
import org.whispersystems.textsecuregcm.storage.PersistentTimer;
|
||||
import org.whispersystems.textsecuregcm.util.DeviceCapabilityAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.EnumMapUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
@@ -100,6 +103,7 @@ public class DeviceController {
|
||||
private final AccountsManager accounts;
|
||||
private final ClientPublicKeysManager clientPublicKeysManager;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final PersistentTimer persistentTimer;
|
||||
private final Map<String, Integer> maxDeviceConfiguration;
|
||||
|
||||
private final EnumMap<ClientPlatform, AtomicInteger> linkedDeviceListenersByPlatform;
|
||||
@@ -108,9 +112,15 @@ public class DeviceController {
|
||||
private static final String LINKED_DEVICE_LISTENER_GAUGE_NAME =
|
||||
MetricsUtil.name(DeviceController.class, "linkedDeviceListeners");
|
||||
|
||||
private static final String WAIT_FOR_LINKED_DEVICE_TIMER_NAMESPACE = "wait_for_linked_device";
|
||||
private static final String WAIT_FOR_LINKED_DEVICE_TIMER_NAME =
|
||||
MetricsUtil.name(DeviceController.class, "waitForLinkedDeviceDuration");
|
||||
|
||||
private static final String WAIT_FOR_TRANSFER_ARCHIVE_TIMER_NAMESPACE = "wait_for_transfer_archive";
|
||||
private static final String WAIT_FOR_TRANSFER_ARCHIVE_TIMER_NAME =
|
||||
MetricsUtil.name(DeviceController.class, "waitForTransferArchiveDuration");
|
||||
|
||||
|
||||
@VisibleForTesting
|
||||
static final int MIN_TOKEN_IDENTIFIER_LENGTH = 32;
|
||||
|
||||
@@ -120,11 +130,13 @@ public class DeviceController {
|
||||
public DeviceController(final AccountsManager accounts,
|
||||
final ClientPublicKeysManager clientPublicKeysManager,
|
||||
final RateLimiters rateLimiters,
|
||||
final PersistentTimer persistentTimer,
|
||||
final Map<String, Integer> maxDeviceConfiguration) {
|
||||
|
||||
this.accounts = accounts;
|
||||
this.clientPublicKeysManager = clientPublicKeysManager;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.persistentTimer = persistentTimer;
|
||||
this.maxDeviceConfiguration = maxDeviceConfiguration;
|
||||
|
||||
linkedDeviceListenersByPlatform =
|
||||
@@ -339,7 +351,7 @@ public class DeviceController {
|
||||
@ApiResponse(responseCode = "204", description = "No device was linked to the account before the call completed; clients may repeat the call to continue waiting")
|
||||
@ApiResponse(responseCode = "400", description = "The given token identifier or timeout was invalid")
|
||||
@ApiResponse(responseCode = "429", description = "Rate-limited; try again after the prescribed delay")
|
||||
public CompletableFuture<Response> waitForLinkedDevice(
|
||||
public CompletionStage<Response> waitForLinkedDevice(
|
||||
@ReadOnly @Auth final AuthenticatedDevice authenticatedDevice,
|
||||
|
||||
@PathParam("tokenIdentifier")
|
||||
@@ -359,40 +371,33 @@ public class DeviceController {
|
||||
given amount of time, this endpoint will return a status of HTTP/204.
|
||||
""") final int timeoutSeconds,
|
||||
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent) throws RateLimitExceededException {
|
||||
|
||||
rateLimiters.getWaitForLinkedDeviceLimiter().validate(authenticatedDevice.getAccount().getIdentifier(IdentityType.ACI));
|
||||
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent) {
|
||||
final AtomicInteger linkedDeviceListenerCounter = getCounterForLinkedDeviceListeners(userAgent);
|
||||
linkedDeviceListenerCounter.incrementAndGet();
|
||||
|
||||
final Timer.Sample sample = Timer.start();
|
||||
try {
|
||||
return accounts.waitForNewLinkedDevice(authenticatedDevice.getAccount().getUuid(),
|
||||
authenticatedDevice.getAuthenticatedDevice(), tokenIdentifier, Duration.ofSeconds(timeoutSeconds))
|
||||
.thenApply(maybeDeviceInfo -> maybeDeviceInfo
|
||||
.map(deviceInfo -> Response.status(Response.Status.OK).entity(deviceInfo).build())
|
||||
.orElseGet(() -> Response.status(Response.Status.NO_CONTENT).build()))
|
||||
.exceptionally(ExceptionUtils.exceptionallyHandler(IllegalArgumentException.class,
|
||||
e -> Response.status(Response.Status.BAD_REQUEST).build()))
|
||||
.whenComplete((response, throwable) -> {
|
||||
linkedDeviceListenerCounter.decrementAndGet();
|
||||
return rateLimiters.getWaitForLinkedDeviceLimiter()
|
||||
.validateAsync(authenticatedDevice.getAccount().getIdentifier(IdentityType.ACI))
|
||||
.thenCompose(ignored -> persistentTimer.start(WAIT_FOR_LINKED_DEVICE_TIMER_NAMESPACE, tokenIdentifier))
|
||||
.thenCompose(sample -> accounts.waitForNewLinkedDevice(
|
||||
authenticatedDevice.getAccount().getUuid(),
|
||||
authenticatedDevice.getAuthenticatedDevice(),
|
||||
tokenIdentifier,
|
||||
Duration.ofSeconds(timeoutSeconds))
|
||||
.thenApply(maybeDeviceInfo -> maybeDeviceInfo
|
||||
.map(deviceInfo -> Response.status(Response.Status.OK).entity(deviceInfo).build())
|
||||
.orElseGet(() -> Response.status(Response.Status.NO_CONTENT).build()))
|
||||
.exceptionally(ExceptionUtils.exceptionallyHandler(IllegalArgumentException.class,
|
||||
e -> Response.status(Response.Status.BAD_REQUEST).build()))
|
||||
.whenComplete((response, throwable) -> {
|
||||
linkedDeviceListenerCounter.decrementAndGet();
|
||||
|
||||
if (response != null) {
|
||||
sample.stop(Timer.builder(WAIT_FOR_LINKED_DEVICE_TIMER_NAME)
|
||||
.publishPercentileHistogram(true)
|
||||
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
io.micrometer.core.instrument.Tag.of("deviceFound",
|
||||
String.valueOf(response.getStatus() == Response.Status.OK.getStatusCode()))))
|
||||
.register(Metrics.globalRegistry));
|
||||
}
|
||||
});
|
||||
} catch (final RedisException e) {
|
||||
// `waitForNewLinkedDevice` could fail synchronously if the Redis circuit breaker is open; prevent counter drift
|
||||
// if that happens
|
||||
linkedDeviceListenerCounter.decrementAndGet();
|
||||
throw e;
|
||||
}
|
||||
if (response != null && response.getStatus() == Response.Status.OK.getStatusCode()) {
|
||||
sample.stop(Timer.builder(WAIT_FOR_LINKED_DEVICE_TIMER_NAME)
|
||||
.publishPercentileHistogram(true)
|
||||
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.register(Metrics.globalRegistry));
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
private AtomicInteger getCounterForLinkedDeviceListeners(final String userAgent) {
|
||||
@@ -530,7 +535,8 @@ public class DeviceController {
|
||||
public CompletionStage<Void> recordTransferArchiveUploaded(@ReadOnly @Auth final AuthenticatedDevice authenticatedDevice,
|
||||
@NotNull @Valid final TransferArchiveUploadedRequest transferArchiveUploadedRequest) {
|
||||
|
||||
return rateLimiters.getUploadTransferArchiveLimiter().validateAsync(authenticatedDevice.getAccount().getIdentifier(IdentityType.ACI))
|
||||
return rateLimiters.getUploadTransferArchiveLimiter()
|
||||
.validateAsync(authenticatedDevice.getAccount().getIdentifier(IdentityType.ACI))
|
||||
.thenCompose(ignored -> accounts.recordTransferArchiveUpload(authenticatedDevice.getAccount(),
|
||||
transferArchiveUploadedRequest.destinationDeviceId(),
|
||||
Instant.ofEpochMilli(transferArchiveUploadedRequest.destinationDeviceCreated()),
|
||||
@@ -565,17 +571,55 @@ public class DeviceController {
|
||||
description = """
|
||||
The amount of time (in seconds) to wait for a response. If a transfer archive for the authenticated
|
||||
device is not available within the given amount of time, this endpoint will return a status of HTTP/204.
|
||||
""") final int timeoutSeconds) {
|
||||
""") final int timeoutSeconds,
|
||||
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable String userAgent) {
|
||||
|
||||
|
||||
final String rateLimiterKey = authenticatedDevice.getAccount().getIdentifier(IdentityType.ACI) +
|
||||
":" + authenticatedDevice.getAuthenticatedDevice().getId();
|
||||
|
||||
return rateLimiters.getWaitForTransferArchiveLimiter().validateAsync(rateLimiterKey)
|
||||
.thenCompose(ignored -> accounts.waitForTransferArchive(authenticatedDevice.getAccount(),
|
||||
authenticatedDevice.getAuthenticatedDevice(),
|
||||
Duration.ofSeconds(timeoutSeconds)))
|
||||
.thenApply(maybeTransferArchive -> maybeTransferArchive
|
||||
.map(transferArchive -> Response.status(Response.Status.OK).entity(transferArchive).build())
|
||||
.orElseGet(() -> Response.status(Response.Status.NO_CONTENT).build()));
|
||||
.thenCompose(ignored -> persistentTimer.start(WAIT_FOR_TRANSFER_ARCHIVE_TIMER_NAMESPACE, rateLimiterKey))
|
||||
.thenCompose(sample -> accounts.waitForTransferArchive(authenticatedDevice.getAccount(),
|
||||
authenticatedDevice.getAuthenticatedDevice(),
|
||||
Duration.ofSeconds(timeoutSeconds))
|
||||
.thenApply(maybeTransferArchive -> maybeTransferArchive
|
||||
.map(transferArchive -> Response.status(Response.Status.OK).entity(transferArchive).build())
|
||||
.orElseGet(() -> Response.status(Response.Status.NO_CONTENT).build()))
|
||||
.whenComplete((response, throwable) -> {
|
||||
if (response != null && response.getStatus() == Response.Status.OK.getStatusCode()) {
|
||||
sample.stop(Timer.builder(WAIT_FOR_TRANSFER_ARCHIVE_TIMER_NAME)
|
||||
.publishPercentileHistogram(true)
|
||||
.tags(Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
primaryPlatformTag(authenticatedDevice.getAccount())))
|
||||
.register(Metrics.globalRegistry));
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
private static io.micrometer.core.instrument.Tag primaryPlatformTag(final Account account) {
|
||||
final Device primaryDevice = account.getPrimaryDevice();
|
||||
|
||||
Optional<ClientPlatform> clientPlatform = Optional.empty();
|
||||
if (StringUtils.isNotBlank(primaryDevice.getGcmId())) {
|
||||
clientPlatform = Optional.of(ClientPlatform.ANDROID);
|
||||
} else if (StringUtils.isNotBlank(primaryDevice.getApnId())) {
|
||||
clientPlatform = Optional.of(ClientPlatform.IOS);
|
||||
}
|
||||
clientPlatform = clientPlatform.or(() -> Optional.ofNullable(
|
||||
switch (primaryDevice.getUserAgent()) {
|
||||
case "OWA" -> ClientPlatform.ANDROID;
|
||||
case "OWI", "OWP" -> ClientPlatform.IOS;
|
||||
case "OWD" -> ClientPlatform.DESKTOP;
|
||||
case null, default -> null;
|
||||
}));
|
||||
|
||||
return io.micrometer.core.instrument.Tag.of(
|
||||
"primaryPlatform",
|
||||
clientPlatform
|
||||
.map(p -> p.name().toLowerCase(Locale.ROOT))
|
||||
.orElse("unknown"));
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -381,7 +381,8 @@ public class KeysController {
|
||||
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("oneTimeEcKeyAvailable", String.valueOf(unsignedEcPreKey != null)),
|
||||
Tag.of("pqKeyAvailable", String.valueOf(pqPreKey != null))))
|
||||
.increment();
|
||||
|
||||
if (signedEcPreKey != null || unsignedEcPreKey != null || pqPreKey != null) {
|
||||
|
||||
+185
-238
@@ -9,10 +9,8 @@ import static com.codahale.metrics.MetricRegistry.name;
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.dropwizard.util.DataSize;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
@@ -47,33 +45,27 @@ import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.core.Response.Status;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
|
||||
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage.Recipient;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.protocol.util.Pair;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
@@ -135,6 +127,7 @@ import org.whispersystems.websocket.auth.ReadOnly;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.util.function.Tuple2;
|
||||
import reactor.util.function.Tuples;
|
||||
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
@@ -142,14 +135,6 @@ import reactor.util.function.Tuples;
|
||||
@io.swagger.v3.oas.annotations.tags.Tag(name = "Messages")
|
||||
public class MessageController {
|
||||
|
||||
|
||||
private record MultiRecipientDeliveryData(
|
||||
ServiceIdentifier serviceIdentifier,
|
||||
Account account,
|
||||
Recipient recipient,
|
||||
Map<Byte, Short> deviceIdToRegistrationId) {
|
||||
}
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessageController.class);
|
||||
|
||||
private final RateLimiters rateLimiters;
|
||||
@@ -162,7 +147,6 @@ public class MessageController {
|
||||
private final PushNotificationManager pushNotificationManager;
|
||||
private final PushNotificationScheduler pushNotificationScheduler;
|
||||
private final ReportMessageManager reportMessageManager;
|
||||
private final ExecutorService multiRecipientMessageExecutor;
|
||||
private final Scheduler messageDeliveryScheduler;
|
||||
private final ClientReleaseManager clientReleaseManager;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
@@ -183,7 +167,6 @@ public class MessageController {
|
||||
private static final String OUTGOING_MESSAGE_LIST_SIZE_BYTES_DISTRIBUTION_NAME = name(MessageController.class, "outgoingMessageListSizeBytes");
|
||||
private static final String RATE_LIMITED_MESSAGE_COUNTER_NAME = name(MessageController.class, "rateLimitedMessage");
|
||||
|
||||
private static final String REJECT_INVALID_ENVELOPE_TYPE = name(MessageController.class, "rejectInvalidEnvelopeType");
|
||||
private static final String SEND_MESSAGE_LATENCY_TIMER_NAME = MetricsUtil.name(MessageController.class, "sendMessageLatency");
|
||||
|
||||
private static final String EPHEMERAL_TAG_NAME = "ephemeral";
|
||||
@@ -191,7 +174,6 @@ public class MessageController {
|
||||
private static final String AUTH_TYPE_TAG_NAME = "authType";
|
||||
private static final String SENDER_COUNTRY_TAG_NAME = "senderCountry";
|
||||
private static final String RATE_LIMIT_REASON_TAG_NAME = "rateLimitReason";
|
||||
private static final String ENVELOPE_TYPE_TAG_NAME = "envelopeType";
|
||||
private static final String IDENTITY_TYPE_TAG_NAME = "identityType";
|
||||
private static final String ENDPOINT_TYPE_TAG_NAME = "endpoint";
|
||||
|
||||
@@ -208,7 +190,7 @@ public class MessageController {
|
||||
private static final String ENDPOINT_TYPE_MULTI = "multi";
|
||||
|
||||
@VisibleForTesting
|
||||
static final long MAX_MESSAGE_SIZE = DataSize.kibibytes(256).toBytes();
|
||||
static final int MAX_MESSAGE_SIZE = (int) DataSize.kibibytes(256).toBytes();
|
||||
private static final long LARGE_MESSAGE_SIZE = DataSize.kibibytes(8).toBytes();
|
||||
|
||||
// The Signal desktop client (really, JavaScript in general) can handle message timestamps at most 100,000,000 days
|
||||
@@ -229,7 +211,6 @@ public class MessageController {
|
||||
PushNotificationManager pushNotificationManager,
|
||||
PushNotificationScheduler pushNotificationScheduler,
|
||||
ReportMessageManager reportMessageManager,
|
||||
@Nonnull ExecutorService multiRecipientMessageExecutor,
|
||||
Scheduler messageDeliveryScheduler,
|
||||
final ClientReleaseManager clientReleaseManager,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
@@ -248,7 +229,6 @@ public class MessageController {
|
||||
this.pushNotificationManager = pushNotificationManager;
|
||||
this.pushNotificationScheduler = pushNotificationScheduler;
|
||||
this.reportMessageManager = reportMessageManager;
|
||||
this.multiRecipientMessageExecutor = Objects.requireNonNull(multiRecipientMessageExecutor);
|
||||
this.messageDeliveryScheduler = messageDeliveryScheduler;
|
||||
this.clientReleaseManager = clientReleaseManager;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
@@ -332,15 +312,15 @@ public class MessageController {
|
||||
throw new WebApplicationException(Status.FORBIDDEN);
|
||||
}
|
||||
|
||||
final Optional<Account> destination;
|
||||
final Optional<Account> maybeDestination;
|
||||
if (!isSyncMessage) {
|
||||
destination = accountsManager.getByServiceIdentifier(destinationIdentifier);
|
||||
maybeDestination = accountsManager.getByServiceIdentifier(destinationIdentifier);
|
||||
} else {
|
||||
destination = source.map(AuthenticatedDevice::getAccount);
|
||||
maybeDestination = source.map(AuthenticatedDevice::getAccount);
|
||||
}
|
||||
|
||||
final SpamChecker.SpamCheckResult spamCheck = spamChecker.checkForSpam(
|
||||
context, source, destination, Optional.of(destinationIdentifier));
|
||||
context, source, maybeDestination, Optional.of(destinationIdentifier));
|
||||
final Optional<byte[]> reportSpamToken;
|
||||
switch (spamCheck) {
|
||||
case final SpamChecker.Spam spam: return spam.response();
|
||||
@@ -350,14 +330,9 @@ public class MessageController {
|
||||
int totalContentLength = 0;
|
||||
|
||||
for (final IncomingMessage message : messages.messages()) {
|
||||
int contentLength = 0;
|
||||
final int contentLength = decodedSize(message.content());
|
||||
|
||||
if (StringUtils.isNotEmpty(message.content())) {
|
||||
contentLength += message.content().length();
|
||||
}
|
||||
|
||||
validateContentLength(contentLength, false, userAgent);
|
||||
validateEnvelopeType(message.type(), userAgent);
|
||||
validateContentLength(contentLength, false, isSyncMessage, isStory, userAgent);
|
||||
|
||||
totalContentLength += contentLength;
|
||||
}
|
||||
@@ -376,11 +351,11 @@ public class MessageController {
|
||||
// Stories will be checked by the client; we bypass access checks here for stories.
|
||||
} else if (groupSendToken != null) {
|
||||
checkGroupSendToken(List.of(destinationIdentifier.toLibsignal()), groupSendToken);
|
||||
if (destination.isEmpty()) {
|
||||
if (maybeDestination.isEmpty()) {
|
||||
throw new NotFoundException();
|
||||
}
|
||||
} else {
|
||||
OptionalAccess.verify(source.map(AuthenticatedDevice::getAccount), accessKey, destination,
|
||||
OptionalAccess.verify(source.map(AuthenticatedDevice::getAccount), accessKey, maybeDestination,
|
||||
destinationIdentifier);
|
||||
}
|
||||
|
||||
@@ -389,20 +364,20 @@ public class MessageController {
|
||||
// We return 200 when stories are sent to a non-existent account. Since story sends bypass OptionalAccess.verify
|
||||
// we leak information about whether a destination UUID exists if we return any other code (e.g. 404) from
|
||||
// these requests.
|
||||
if (isStory && destination.isEmpty()) {
|
||||
if (isStory && maybeDestination.isEmpty()) {
|
||||
return Response.ok(new SendMessageResponse(needsSync)).build();
|
||||
}
|
||||
|
||||
// if destination is empty we would either throw an exception in OptionalAccess.verify when isStory is false
|
||||
// or else return a 200 response when isStory is true.
|
||||
assert destination.isPresent();
|
||||
final Account destination = maybeDestination.orElseThrow();
|
||||
|
||||
if (source.isPresent() && !isSyncMessage) {
|
||||
checkMessageRateLimit(source.get(), destination.get(), userAgent);
|
||||
checkMessageRateLimit(source.get(), destination, userAgent);
|
||||
}
|
||||
|
||||
if (isStory) {
|
||||
rateLimiters.getStoriesLimiter().validate(destination.get().getUuid());
|
||||
rateLimiters.getStoriesLimiter().validate(destination.getUuid());
|
||||
}
|
||||
|
||||
final Set<Byte> excludedDeviceIds;
|
||||
@@ -413,15 +388,33 @@ public class MessageController {
|
||||
excludedDeviceIds = Collections.emptySet();
|
||||
}
|
||||
|
||||
DestinationDeviceValidator.validateCompleteDeviceList(destination.get(),
|
||||
messages.messages().stream().map(IncomingMessage::destinationDeviceId).collect(Collectors.toSet()),
|
||||
final Map<Byte, Envelope> messagesByDeviceId = messages.messages().stream()
|
||||
.collect(Collectors.toMap(IncomingMessage::destinationDeviceId, message -> {
|
||||
try {
|
||||
return message.toEnvelope(
|
||||
destinationIdentifier,
|
||||
source.map(AuthenticatedDevice::getAccount).orElse(null),
|
||||
source.map(account -> account.getAuthenticatedDevice().getId()).orElse(null),
|
||||
messages.timestamp() == 0 ? System.currentTimeMillis() : messages.timestamp(),
|
||||
isStory,
|
||||
messages.online(),
|
||||
messages.urgent(),
|
||||
reportSpamToken.orElse(null));
|
||||
} catch (final IllegalArgumentException e) {
|
||||
logger.warn("Received bad envelope type {} from {}", message.type(), userAgent);
|
||||
throw new BadRequestException(e);
|
||||
}
|
||||
}));
|
||||
|
||||
DestinationDeviceValidator.validateCompleteDeviceList(destination,
|
||||
messagesByDeviceId.keySet(),
|
||||
excludedDeviceIds);
|
||||
|
||||
DestinationDeviceValidator.validateRegistrationIds(destination.get(),
|
||||
DestinationDeviceValidator.validateRegistrationIds(destination,
|
||||
messages.messages(),
|
||||
IncomingMessage::destinationDeviceId,
|
||||
IncomingMessage::destinationRegistrationId,
|
||||
destination.get().getPhoneNumberIdentifier().equals(destinationIdentifier.uuid()));
|
||||
destination.getPhoneNumberIdentifier().equals(destinationIdentifier.uuid()));
|
||||
|
||||
final String authType;
|
||||
if (SENDER_TYPE_IDENTIFIED.equals(senderType)) {
|
||||
@@ -434,31 +427,15 @@ public class MessageController {
|
||||
authType = AUTH_TYPE_ACCESS_KEY;
|
||||
}
|
||||
|
||||
final List<Tag> tags = List.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
messageSender.sendMessages(destination, messagesByDeviceId);
|
||||
|
||||
Metrics.counter(SENT_MESSAGE_COUNTER_NAME, List.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(ENDPOINT_TYPE_TAG_NAME, ENDPOINT_TYPE_SINGLE),
|
||||
Tag.of(EPHEMERAL_TAG_NAME, String.valueOf(messages.online())),
|
||||
Tag.of(SENDER_TYPE_TAG_NAME, senderType),
|
||||
Tag.of(AUTH_TYPE_TAG_NAME, authType),
|
||||
Tag.of(IDENTITY_TYPE_TAG_NAME, destinationIdentifier.identityType().name()));
|
||||
|
||||
for (final IncomingMessage incomingMessage : messages.messages()) {
|
||||
destination.get().getDevice(incomingMessage.destinationDeviceId())
|
||||
.ifPresent(destinationDevice -> {
|
||||
Metrics.counter(SENT_MESSAGE_COUNTER_NAME, tags).increment();
|
||||
sendIndividualMessage(
|
||||
source,
|
||||
destination.get(),
|
||||
destinationDevice,
|
||||
destinationIdentifier,
|
||||
messages.timestamp(),
|
||||
messages.online(),
|
||||
isStory,
|
||||
messages.urgent(),
|
||||
incomingMessage,
|
||||
userAgent,
|
||||
reportSpamToken);
|
||||
});
|
||||
}
|
||||
Tag.of(IDENTITY_TYPE_TAG_NAME, destinationIdentifier.identityType().name())))
|
||||
.increment(messagesByDeviceId.size());
|
||||
|
||||
return Response.ok(new SendMessageResponse(needsSync)).build();
|
||||
} catch (final MismatchedDevicesException e) {
|
||||
@@ -481,34 +458,6 @@ public class MessageController {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Build mapping of service IDs to resolved accounts and device/registration IDs
|
||||
*/
|
||||
private Map<ServiceIdentifier, MultiRecipientDeliveryData> buildRecipientMap(
|
||||
SealedSenderMultiRecipientMessage multiRecipientMessage, boolean isStory) {
|
||||
return Flux.fromIterable(multiRecipientMessage.getRecipients().entrySet())
|
||||
.switchIfEmpty(Flux.error(BadRequestException::new))
|
||||
.map(e -> Tuples.of(ServiceIdentifier.fromLibsignal(e.getKey()), e.getValue()))
|
||||
.flatMap(
|
||||
t -> Mono.fromFuture(() -> accountsManager.getByServiceIdentifierAsync(t.getT1()))
|
||||
.flatMap(Mono::justOrEmpty)
|
||||
.switchIfEmpty(isStory ? Mono.empty() : Mono.error(NotFoundException::new))
|
||||
.map(
|
||||
account ->
|
||||
new MultiRecipientDeliveryData(
|
||||
t.getT1(),
|
||||
account,
|
||||
t.getT2(),
|
||||
t.getT2().getDevicesAndRegistrationIds().collect(
|
||||
Collectors.toMap(Pair<Byte, Short>::first, Pair<Byte, Short>::second))))
|
||||
// IllegalStateException is thrown by Collectors#toMap when we have multiple entries for the same device
|
||||
.onErrorMap(e -> e instanceof IllegalStateException ? new BadRequestException() : e),
|
||||
MAX_FETCH_ACCOUNT_CONCURRENCY)
|
||||
.collectMap(MultiRecipientDeliveryData::serviceIdentifier)
|
||||
.block();
|
||||
}
|
||||
|
||||
@Timed
|
||||
@Path("/multi_recipient")
|
||||
@PUT
|
||||
@@ -520,7 +469,10 @@ public class MessageController {
|
||||
Deliver a common-payload message to multiple recipients.
|
||||
An unidentifed-access key for all recipients must be provided, unless the message is a story.
|
||||
""")
|
||||
@ApiResponse(responseCode="200", description="Message was successfully sent to all recipients", useReturnTypeSchema=true)
|
||||
@ApiResponse(
|
||||
responseCode="200",
|
||||
description="Message was successfully sent",
|
||||
content = @Content(schema = @Schema(implementation = SendMultiRecipientMessageResponse.class)))
|
||||
@ApiResponse(responseCode="400", description="The envelope specified delivery to the same recipient device multiple times")
|
||||
@ApiResponse(
|
||||
responseCode="401",
|
||||
@@ -565,6 +517,32 @@ public class MessageController {
|
||||
throw new BadRequestException("Illegal timestamp");
|
||||
}
|
||||
|
||||
if (multiRecipientMessage.getRecipients().isEmpty()) {
|
||||
throw new BadRequestException("Recipient list is empty");
|
||||
}
|
||||
|
||||
// Verify that the message isn't too large before performing more expensive validations
|
||||
multiRecipientMessage.getRecipients().values().forEach(recipient ->
|
||||
validateContentLength(multiRecipientMessage.messageSizeForRecipient(recipient), true, false, isStory, userAgent));
|
||||
|
||||
// Check that the request is well-formed and doesn't contain repeated entries for the same device for the same
|
||||
// recipient
|
||||
{
|
||||
final boolean[] usedDeviceIds = new boolean[Device.MAXIMUM_DEVICE_ID];
|
||||
|
||||
for (final SealedSenderMultiRecipientMessage.Recipient recipient : multiRecipientMessage.getRecipients().values()) {
|
||||
Arrays.fill(usedDeviceIds, false);
|
||||
|
||||
for (final byte deviceId : recipient.getDevices()) {
|
||||
if (usedDeviceIds[deviceId]) {
|
||||
throw new BadRequestException();
|
||||
}
|
||||
|
||||
usedDeviceIds[deviceId] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final SpamChecker.SpamCheckResult spamCheck = spamChecker.checkForSpam(context, Optional.empty(), Optional.empty(), Optional.empty());
|
||||
if (spamCheck instanceof final SpamChecker.Spam spam) {
|
||||
return spam.response();
|
||||
@@ -584,28 +562,43 @@ public class MessageController {
|
||||
if (groupSendToken != null) {
|
||||
// Group send endorsements are checked before we even attempt to resolve any accounts, since
|
||||
// the lists of service IDs in the envelope are all that we need to check against
|
||||
checkGroupSendToken(
|
||||
multiRecipientMessage.getRecipients().keySet(), groupSendToken);
|
||||
checkGroupSendToken(multiRecipientMessage.getRecipients().keySet(), groupSendToken);
|
||||
}
|
||||
|
||||
final Map<ServiceIdentifier, MultiRecipientDeliveryData> recipients = buildRecipientMap(multiRecipientMessage, isStory);
|
||||
// At this point, the caller has at least superficially provided the information needed to send a multi-recipient
|
||||
// message. Attempt to resolve the destination service identifiers to Signal accounts.
|
||||
final Map<SealedSenderMultiRecipientMessage.Recipient, Account> resolvedRecipients =
|
||||
Flux.fromIterable(multiRecipientMessage.getRecipients().entrySet())
|
||||
.flatMap(serviceIdAndRecipient -> {
|
||||
final ServiceIdentifier serviceIdentifier =
|
||||
ServiceIdentifier.fromLibsignal(serviceIdAndRecipient.getKey());
|
||||
|
||||
return Mono.fromFuture(() -> accountsManager.getByServiceIdentifierAsync(serviceIdentifier))
|
||||
.flatMap(Mono::justOrEmpty)
|
||||
.switchIfEmpty(isStory || groupSendToken != null ? Mono.empty() : Mono.error(NotFoundException::new))
|
||||
.map(account -> Tuples.of(serviceIdAndRecipient.getValue(), account));
|
||||
}, MAX_FETCH_ACCOUNT_CONCURRENCY)
|
||||
.collectMap(Tuple2::getT1, Tuple2::getT2)
|
||||
.blockOptional()
|
||||
.orElse(Collections.emptyMap());
|
||||
|
||||
// Access keys are checked against the UAK in the resolved accounts, so we have to check after resolving accounts above.
|
||||
// Group send endorsements are checked earlier; for stories, we don't check permissions at all because only clients check them
|
||||
if (groupSendToken == null && !isStory) {
|
||||
checkAccessKeys(accessKeys, recipients.values());
|
||||
checkAccessKeys(accessKeys, multiRecipientMessage, resolvedRecipients);
|
||||
}
|
||||
|
||||
// We might filter out all the recipients of a story (if none exist).
|
||||
// In this case there is no error so we should just return 200 now.
|
||||
if (isStory) {
|
||||
if (recipients.isEmpty()) {
|
||||
if (resolvedRecipients.isEmpty()) {
|
||||
return Response.ok(new SendMultiRecipientMessageResponse(List.of())).build();
|
||||
}
|
||||
|
||||
try {
|
||||
CompletableFuture.allOf(recipients.values()
|
||||
CompletableFuture.allOf(resolvedRecipients.values()
|
||||
.stream()
|
||||
.map(recipient -> recipient.account().getUuid())
|
||||
.map(account -> account.getIdentifier(IdentityType.ACI))
|
||||
.map(accountIdentifier ->
|
||||
rateLimiters.getStoriesLimiter().validateAsync(accountIdentifier).toCompletableFuture())
|
||||
.toList()
|
||||
@@ -620,31 +613,42 @@ public class MessageController {
|
||||
}
|
||||
}
|
||||
|
||||
Collection<AccountMismatchedDevices> accountMismatchedDevices = new ArrayList<>();
|
||||
Collection<AccountStaleDevices> accountStaleDevices = new ArrayList<>();
|
||||
recipients.values().forEach(recipient -> {
|
||||
final Account account = recipient.account();
|
||||
final Collection<AccountMismatchedDevices> accountMismatchedDevices = new ArrayList<>();
|
||||
final Collection<AccountStaleDevices> accountStaleDevices = new ArrayList<>();
|
||||
|
||||
multiRecipientMessage.getRecipients().forEach((serviceId, recipient) -> {
|
||||
if (!resolvedRecipients.containsKey(recipient)) {
|
||||
// When sending stories, we might not be able to resolve all recipients to existing accounts. That's okay! We
|
||||
// can just skip them.
|
||||
return;
|
||||
}
|
||||
|
||||
final Account account = resolvedRecipients.get(recipient);
|
||||
|
||||
try {
|
||||
DestinationDeviceValidator.validateCompleteDeviceList(account, recipient.deviceIdToRegistrationId().keySet(),
|
||||
final Map<Byte, Short> deviceIdsToRegistrationIds = recipient.getDevicesAndRegistrationIds()
|
||||
.collect(Collectors.toMap(Pair<Byte, Short>::first, Pair<Byte, Short>::second));
|
||||
|
||||
DestinationDeviceValidator.validateCompleteDeviceList(account, deviceIdsToRegistrationIds.keySet(),
|
||||
Collections.emptySet());
|
||||
|
||||
DestinationDeviceValidator.validateRegistrationIds(
|
||||
account,
|
||||
recipient.deviceIdToRegistrationId().entrySet(),
|
||||
deviceIdsToRegistrationIds.entrySet(),
|
||||
Map.Entry<Byte, Short>::getKey,
|
||||
e -> Integer.valueOf(e.getValue()),
|
||||
recipient.serviceIdentifier().identityType() == IdentityType.PNI);
|
||||
} catch (MismatchedDevicesException e) {
|
||||
serviceId instanceof ServiceId.Pni);
|
||||
} catch (final MismatchedDevicesException e) {
|
||||
accountMismatchedDevices.add(
|
||||
new AccountMismatchedDevices(
|
||||
recipient.serviceIdentifier(),
|
||||
ServiceIdentifier.fromLibsignal(serviceId),
|
||||
new MismatchedDevices(e.getMissingDevices(), e.getExtraDevices())));
|
||||
} catch (StaleDevicesException e) {
|
||||
} catch (final StaleDevicesException e) {
|
||||
accountStaleDevices.add(
|
||||
new AccountStaleDevices(recipient.serviceIdentifier(), new StaleDevices(e.getStaleDevices())));
|
||||
new AccountStaleDevices(ServiceIdentifier.fromLibsignal(serviceId), new StaleDevices(e.getStaleDevices())));
|
||||
}
|
||||
});
|
||||
|
||||
if (!accountMismatchedDevices.isEmpty()) {
|
||||
return Response
|
||||
.status(409)
|
||||
@@ -670,39 +674,45 @@ public class MessageController {
|
||||
}
|
||||
|
||||
try {
|
||||
final byte[] sharedMrmKey = messagesManager.insertSharedMultiRecipientMessagePayload(multiRecipientMessage);
|
||||
if (!resolvedRecipients.isEmpty()) {
|
||||
messageSender.sendMultiRecipientMessage(multiRecipientMessage, resolvedRecipients, timestamp, isStory, online, isUrgent).get();
|
||||
}
|
||||
|
||||
CompletableFuture.allOf(
|
||||
recipients.values().stream()
|
||||
.flatMap(recipientData -> {
|
||||
final Counter sentMessageCounter = Metrics.counter(SENT_MESSAGE_COUNTER_NAME, Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(ENDPOINT_TYPE_TAG_NAME, ENDPOINT_TYPE_MULTI),
|
||||
Tag.of(EPHEMERAL_TAG_NAME, String.valueOf(online)),
|
||||
Tag.of(SENDER_TYPE_TAG_NAME, SENDER_TYPE_UNIDENTIFIED),
|
||||
Tag.of(AUTH_TYPE_TAG_NAME, authType),
|
||||
Tag.of(IDENTITY_TYPE_TAG_NAME, recipientData.serviceIdentifier().identityType().name())));
|
||||
final List<ServiceIdentifier> unresolvedRecipientServiceIds;
|
||||
if (AUTH_TYPE_GROUP_SEND_TOKEN.equals(authType)) {
|
||||
unresolvedRecipientServiceIds = multiRecipientMessage.getRecipients().entrySet().stream()
|
||||
.filter(entry -> !resolvedRecipients.containsKey(entry.getValue()))
|
||||
.map(entry -> ServiceIdentifier.fromLibsignal(entry.getKey()))
|
||||
.toList();
|
||||
} else {
|
||||
unresolvedRecipientServiceIds = List.of();
|
||||
}
|
||||
|
||||
validateContentLength(multiRecipientMessage.messageSizeForRecipient(recipientData.recipient()), true, userAgent);
|
||||
multiRecipientMessage.getRecipients().forEach((serviceId, recipient) -> {
|
||||
if (!resolvedRecipients.containsKey(recipient)) {
|
||||
// We skipped sending to this recipient because we couldn't resolve the recipient to an
|
||||
// existing account; don't increment the counter for this recipient. If the client was
|
||||
// using a GSE, track the missing recipients to include in the response.
|
||||
return;
|
||||
}
|
||||
|
||||
return recipientData.deviceIdToRegistrationId().keySet().stream().map(
|
||||
deviceId -> CompletableFuture.runAsync(
|
||||
() -> {
|
||||
final Account destinationAccount = recipientData.account();
|
||||
final byte[] payload = multiRecipientMessage.messageForRecipient(recipientData.recipient());
|
||||
final String identityType = switch (serviceId) {
|
||||
case ServiceId.Aci ignored -> "ACI";
|
||||
case ServiceId.Pni ignored -> "PNI";
|
||||
default -> "unknown";
|
||||
};
|
||||
|
||||
// we asserted this must exist in validateCompleteDeviceList
|
||||
final Device destinationDevice = destinationAccount.getDevice(deviceId).orElseThrow();
|
||||
Metrics.counter(SENT_MESSAGE_COUNTER_NAME, Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(ENDPOINT_TYPE_TAG_NAME, ENDPOINT_TYPE_MULTI),
|
||||
Tag.of(EPHEMERAL_TAG_NAME, String.valueOf(online)),
|
||||
Tag.of(SENDER_TYPE_TAG_NAME, SENDER_TYPE_UNIDENTIFIED),
|
||||
Tag.of(AUTH_TYPE_TAG_NAME, authType),
|
||||
Tag.of(IDENTITY_TYPE_TAG_NAME, identityType)))
|
||||
.increment(recipient.getDevices().length);
|
||||
});
|
||||
|
||||
sentMessageCounter.increment();
|
||||
sendCommonPayloadMessage(
|
||||
destinationAccount, destinationDevice, recipientData.serviceIdentifier(), timestamp,
|
||||
online, isStory, isUrgent, payload, sharedMrmKey);
|
||||
},
|
||||
multiRecipientMessageExecutor));
|
||||
})
|
||||
.toArray(CompletableFuture[]::new))
|
||||
.get();
|
||||
return Response.ok(new SendMultiRecipientMessageResponse(unresolvedRecipientServiceIds)).build();
|
||||
} catch (InterruptedException e) {
|
||||
logger.error("interrupted while delivering multi-recipient messages", e);
|
||||
throw new InternalServerErrorException("interrupted during delivery");
|
||||
@@ -713,7 +723,6 @@ public class MessageController {
|
||||
logger.error("partial failure while delivering multi-recipient messages", e.getCause());
|
||||
throw new InternalServerErrorException("failure during delivery");
|
||||
}
|
||||
return Response.ok(new SendMultiRecipientMessageResponse(Collections.emptyList())).build();
|
||||
}
|
||||
|
||||
private void checkGroupSendToken(
|
||||
@@ -729,29 +738,21 @@ public class MessageController {
|
||||
|
||||
private void checkAccessKeys(
|
||||
final @NotNull CombinedUnidentifiedSenderAccessKeys accessKeys,
|
||||
final Collection<MultiRecipientDeliveryData> destinations) {
|
||||
final int keyLength = UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH;
|
||||
final SealedSenderMultiRecipientMessage multiRecipientMessage,
|
||||
final Map<SealedSenderMultiRecipientMessage.Recipient, Account> resolvedRecipients) {
|
||||
|
||||
if (multiRecipientMessage.getRecipients().keySet().stream()
|
||||
.anyMatch(serviceId -> serviceId instanceof ServiceId.Pni)) {
|
||||
|
||||
if (destinations.stream()
|
||||
.anyMatch(destination -> IdentityType.PNI.equals(destination.serviceIdentifier.identityType()))) {
|
||||
throw new WebApplicationException("Multi-recipient messages must be addressed to ACI service IDs",
|
||||
Status.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
final byte[] combinedUnidentifiedAccessKeys = destinations.stream()
|
||||
.map(MultiRecipientDeliveryData::account)
|
||||
.filter(Predicate.not(Account::isUnrestrictedUnidentifiedAccess))
|
||||
.map(account ->
|
||||
account.getUnidentifiedAccessKey()
|
||||
.filter(b -> b.length == keyLength)
|
||||
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED)))
|
||||
.reduce(new byte[keyLength],
|
||||
(a, b) -> {
|
||||
final byte[] xor = new byte[keyLength];
|
||||
IntStream.range(0, keyLength).forEach(i -> xor[i] = (byte) (a[i] ^ b[i]));
|
||||
return xor;
|
||||
});
|
||||
if (!MessageDigest.isEqual(combinedUnidentifiedAccessKeys, accessKeys.getAccessKeys())) {
|
||||
try {
|
||||
if (!UnidentifiedAccessUtil.checkUnidentifiedAccess(resolvedRecipients.values(), accessKeys.getAccessKeys())) {
|
||||
throw new WebApplicationException(Status.UNAUTHORIZED);
|
||||
}
|
||||
} catch (final IllegalArgumentException ignored) {
|
||||
throw new WebApplicationException(Status.UNAUTHORIZED);
|
||||
}
|
||||
}
|
||||
@@ -912,65 +913,6 @@ public class MessageController {
|
||||
.build();
|
||||
}
|
||||
|
||||
private void sendIndividualMessage(
|
||||
Optional<AuthenticatedDevice> source,
|
||||
Account destinationAccount,
|
||||
Device destinationDevice,
|
||||
ServiceIdentifier destinationIdentifier,
|
||||
long timestamp,
|
||||
boolean online,
|
||||
boolean story,
|
||||
boolean urgent,
|
||||
IncomingMessage incomingMessage,
|
||||
String userAgentString,
|
||||
Optional<byte[]> spamReportToken) {
|
||||
|
||||
final Envelope envelope;
|
||||
|
||||
try {
|
||||
final Account sourceAccount = source.map(AuthenticatedDevice::getAccount).orElse(null);
|
||||
final Byte sourceDeviceId = source.map(account -> account.getAuthenticatedDevice().getId()).orElse(null);
|
||||
envelope = incomingMessage.toEnvelope(
|
||||
destinationIdentifier,
|
||||
sourceAccount,
|
||||
sourceDeviceId,
|
||||
timestamp == 0 ? System.currentTimeMillis() : timestamp,
|
||||
story,
|
||||
urgent,
|
||||
spamReportToken.orElse(null));
|
||||
} catch (final IllegalArgumentException e) {
|
||||
logger.warn("Received bad envelope type {} from {}", incomingMessage.type(), userAgentString);
|
||||
throw new BadRequestException(e);
|
||||
}
|
||||
|
||||
messageSender.sendMessage(destinationAccount, destinationDevice, envelope, online);
|
||||
}
|
||||
|
||||
private void sendCommonPayloadMessage(Account destinationAccount,
|
||||
Device destinationDevice,
|
||||
ServiceIdentifier serviceIdentifier,
|
||||
long timestamp,
|
||||
boolean online,
|
||||
boolean story,
|
||||
boolean urgent,
|
||||
byte[] payload,
|
||||
byte[] sharedMrmKey) {
|
||||
|
||||
final Envelope.Builder messageBuilder = Envelope.newBuilder();
|
||||
final long serverTimestamp = System.currentTimeMillis();
|
||||
|
||||
messageBuilder
|
||||
.setType(Type.UNIDENTIFIED_SENDER)
|
||||
.setClientTimestamp(timestamp == 0 ? serverTimestamp : timestamp)
|
||||
.setServerTimestamp(serverTimestamp)
|
||||
.setStory(story)
|
||||
.setUrgent(urgent)
|
||||
.setDestinationServiceId(serviceIdentifier.toServiceIdentifierString())
|
||||
.setSharedMrmKey(ByteString.copyFrom(sharedMrmKey));
|
||||
|
||||
messageSender.sendMessage(destinationAccount, destinationDevice, messageBuilder.build(), online);
|
||||
}
|
||||
|
||||
private void checkMessageRateLimit(AuthenticatedDevice source, Account destination, String userAgent)
|
||||
throws RateLimitExceededException {
|
||||
final String senderCountryCode = Util.getCountryCode(source.getAccount().getNumber());
|
||||
@@ -988,47 +930,52 @@ public class MessageController {
|
||||
}
|
||||
}
|
||||
|
||||
private void validateContentLength(final int contentLength, final boolean multiRecipientMessage, final String userAgent) {
|
||||
private void validateContentLength(final int contentLength,
|
||||
final boolean isMultiRecipientMessage,
|
||||
final boolean isSyncMessage,
|
||||
final boolean isStory,
|
||||
final String userAgent) {
|
||||
|
||||
final boolean oversize = contentLength > MAX_MESSAGE_SIZE;
|
||||
|
||||
DistributionSummary.builder(CONTENT_SIZE_DISTRIBUTION_NAME)
|
||||
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of("oversize", String.valueOf(oversize)),
|
||||
Tag.of("multiRecipientMessage", String.valueOf(multiRecipientMessage))))
|
||||
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, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
Metrics.counter(REJECT_OVERSIZE_MESSAGE_COUNTER, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of("multiRecipientMessage", String.valueOf(isMultiRecipientMessage)),
|
||||
Tag.of("syncMessage", String.valueOf(isSyncMessage)),
|
||||
Tag.of("story", String.valueOf(isStory))))
|
||||
.increment();
|
||||
throw new WebApplicationException(Status.REQUEST_ENTITY_TOO_LARGE);
|
||||
}
|
||||
if (contentLength > LARGE_MESSAGE_SIZE) {
|
||||
Metrics.counter(
|
||||
LARGE_BUT_NOT_OVERSIZE_MESSAGE_COUNTER,
|
||||
Tags.of(UserAgentTagUtil.getPlatformTag(userAgent), Tag.of("multiRecipientMessage", String.valueOf(multiRecipientMessage))))
|
||||
Tags.of(UserAgentTagUtil.getPlatformTag(userAgent), Tag.of("multiRecipientMessage", String.valueOf(isMultiRecipientMessage))))
|
||||
.increment();
|
||||
}
|
||||
}
|
||||
|
||||
private void validateEnvelopeType(final int type, final String userAgent) {
|
||||
if (type == Type.SERVER_DELIVERY_RECEIPT_VALUE) {
|
||||
Metrics.counter(REJECT_INVALID_ENVELOPE_TYPE,
|
||||
Tags.of(UserAgentTagUtil.getPlatformTag(userAgent), Tag.of(ENVELOPE_TYPE_TAG_NAME, String.valueOf(type))))
|
||||
.increment();
|
||||
throw new BadRequestException("reserved envelope type");
|
||||
}
|
||||
}
|
||||
@VisibleForTesting
|
||||
static int decodedSize(final String base64) {
|
||||
final int padding;
|
||||
|
||||
public static Optional<byte[]> getMessageContent(IncomingMessage message) {
|
||||
if (StringUtils.isEmpty(message.content())) return Optional.empty();
|
||||
|
||||
try {
|
||||
return Optional.of(Base64.getDecoder().decode(message.content()));
|
||||
} catch (IllegalArgumentException e) {
|
||||
logger.debug("Bad B64", e);
|
||||
return Optional.empty();
|
||||
if (StringUtils.endsWith(base64, "==")) {
|
||||
padding = 2;
|
||||
} else if (StringUtils.endsWith(base64, "=")) {
|
||||
padding = 1;
|
||||
} else {
|
||||
padding = 0;
|
||||
}
|
||||
|
||||
return ((StringUtils.length(base64) - padding) * 3) / 4;
|
||||
}
|
||||
}
|
||||
+5
-2
@@ -36,6 +36,7 @@ import java.util.Optional;
|
||||
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountCreationResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
|
||||
@@ -100,7 +101,7 @@ public class RegistrationController {
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
public AccountIdentityResponse register(
|
||||
public AccountCreationResponse register(
|
||||
@HeaderParam(HttpHeaders.AUTHORIZATION) @NotNull final BasicAuthorizationHeader authorizationHeader,
|
||||
@HeaderParam(HeaderUtils.X_SIGNAL_AGENT) final String signalAgent,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@@ -166,12 +167,14 @@ public class RegistrationController {
|
||||
Tag.of(VERIFICATION_TYPE_TAG_NAME, verificationType.name())))
|
||||
.increment();
|
||||
|
||||
return new AccountIdentityResponseBuilder(account)
|
||||
final AccountIdentityResponse identityResponse = new AccountIdentityResponseBuilder(account)
|
||||
// If there was an existing account, return whether it could have had something in the storage service
|
||||
.storageCapable(existingAccount
|
||||
.map(a -> a.hasCapability(DeviceCapability.STORAGE))
|
||||
.orElse(false))
|
||||
.build();
|
||||
|
||||
return new AccountCreationResponse(identityResponse, existingAccount.isPresent());
|
||||
}
|
||||
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonUnwrapped;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
// Note, this class cannot be converted into a record because @JsonUnwrapped does not work with records until 2.19. We are on 2.18 until Dropwizard’s BOM updates.
|
||||
// https://github.com/FasterXML/jackson-databind/issues/1467
|
||||
public class AccountCreationResponse {
|
||||
|
||||
@JsonUnwrapped
|
||||
private AccountIdentityResponse identityResponse;
|
||||
|
||||
@Schema(description = "If true, there was an existing account registered for this number")
|
||||
private boolean reregistration;
|
||||
|
||||
public AccountCreationResponse() {
|
||||
}
|
||||
|
||||
public AccountCreationResponse(AccountIdentityResponse identityResponse, boolean reregistration) {
|
||||
this.identityResponse = identityResponse;
|
||||
this.reregistration = reregistration;
|
||||
}
|
||||
|
||||
public boolean isReregistration() {
|
||||
return reregistration;
|
||||
}
|
||||
}
|
||||
+23
-7
@@ -5,36 +5,39 @@
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import jakarta.validation.constraints.AssertTrue;
|
||||
import java.util.Base64;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
|
||||
public record IncomingMessage(int type, byte destinationDeviceId, int destinationRegistrationId, String content) {
|
||||
|
||||
private static final String REJECT_INVALID_ENVELOPE_TYPE_COUNTER_NAME =
|
||||
MetricsUtil.name(IncomingMessage.class, "rejectInvalidEnvelopeType");
|
||||
|
||||
public MessageProtos.Envelope toEnvelope(final ServiceIdentifier destinationIdentifier,
|
||||
@Nullable Account sourceAccount,
|
||||
@Nullable Byte sourceDeviceId,
|
||||
final long timestamp,
|
||||
final boolean story,
|
||||
final boolean ephemeral,
|
||||
final boolean urgent,
|
||||
@Nullable byte[] reportSpamToken) {
|
||||
|
||||
final MessageProtos.Envelope.Type envelopeType = MessageProtos.Envelope.Type.forNumber(type());
|
||||
|
||||
if (envelopeType == null) {
|
||||
throw new IllegalArgumentException("Bad envelope type: " + type());
|
||||
}
|
||||
|
||||
final MessageProtos.Envelope.Builder envelopeBuilder = MessageProtos.Envelope.newBuilder();
|
||||
|
||||
envelopeBuilder.setType(envelopeType)
|
||||
envelopeBuilder
|
||||
.setType(MessageProtos.Envelope.Type.forNumber(type))
|
||||
.setClientTimestamp(timestamp)
|
||||
.setServerTimestamp(System.currentTimeMillis())
|
||||
.setDestinationServiceId(destinationIdentifier.toServiceIdentifierString())
|
||||
.setStory(story)
|
||||
.setEphemeral(ephemeral)
|
||||
.setUrgent(urgent);
|
||||
|
||||
if (sourceAccount != null && sourceDeviceId != null) {
|
||||
@@ -53,4 +56,17 @@ public record IncomingMessage(int type, byte destinationDeviceId, int destinatio
|
||||
|
||||
return envelopeBuilder.build();
|
||||
}
|
||||
|
||||
@AssertTrue
|
||||
public boolean isValidEnvelopeType() {
|
||||
if (type() == MessageProtos.Envelope.Type.SERVER_DELIVERY_RECEIPT_VALUE ||
|
||||
MessageProtos.Envelope.Type.forNumber(type()) == null) {
|
||||
|
||||
Metrics.counter(REJECT_INVALID_ENVELOPE_TYPE_COUNTER_NAME).increment();
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+10
-8
@@ -8,18 +8,16 @@ import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.PositiveOrZero;
|
||||
import org.whispersystems.textsecuregcm.controllers.MessageController;
|
||||
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
|
||||
import java.util.List;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.AssertTrue;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.PositiveOrZero;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import org.whispersystems.textsecuregcm.controllers.MessageController;
|
||||
|
||||
public record IncomingMessageList(@NotNull
|
||||
@Valid
|
||||
@@ -49,10 +47,14 @@ public record IncomingMessageList(@NotNull
|
||||
|
||||
@AssertTrue
|
||||
public boolean hasNoDuplicateRecipients() {
|
||||
boolean valid = messages.stream().filter(m -> m != null).map(IncomingMessage::destinationDeviceId).distinct().count() == messages.size();
|
||||
final boolean valid = messages.stream()
|
||||
.filter(Objects::nonNull)
|
||||
.map(IncomingMessage::destinationDeviceId).distinct().count() == messages.size();
|
||||
|
||||
if (!valid) {
|
||||
REJECT_DUPLICATE_RECIPIENT_COUNTER.increment();
|
||||
}
|
||||
|
||||
return valid;
|
||||
}
|
||||
}
|
||||
+1
-4
@@ -18,8 +18,5 @@ public record RegistrationLockFailure(
|
||||
long timeRemaining,
|
||||
@Schema(description = "Credentials that can be used with SVR2")
|
||||
@Nullable
|
||||
ExternalServiceCredentials svr2Credentials,
|
||||
@Deprecated
|
||||
@Nullable
|
||||
ExternalServiceCredentials svr3Credentials) {
|
||||
ExternalServiceCredentials svr2Credentials) {
|
||||
}
|
||||
+13
-1
@@ -5,8 +5,13 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
|
||||
@Schema(description = """
|
||||
Represents a request from a new device to restore account data by some method.
|
||||
@@ -14,7 +19,14 @@ import jakarta.validation.constraints.NotNull;
|
||||
public record RestoreAccountRequest(
|
||||
@NotNull
|
||||
@Schema(description = "The method by which the new device has requested account data restoration")
|
||||
Method method) {
|
||||
Method method,
|
||||
|
||||
@Schema(description = "Additional data to use to bootstrap a connection between devices, in standard unpadded base64.",
|
||||
implementation = String.class)
|
||||
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
|
||||
@Size(max = 4096)
|
||||
@Nullable byte[] deviceTransferBootstrap) {
|
||||
|
||||
public enum Method {
|
||||
@Schema(description = "Restore account data from a remote message history backup")
|
||||
|
||||
+9
-7
@@ -5,16 +5,18 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import java.util.List;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.util.ServiceIdentifierAdapter;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public record SendMultiRecipientMessageResponse(@JsonSerialize(contentUsing = ServiceIdentifierAdapter.ServiceIdentifierSerializer.class)
|
||||
@JsonDeserialize(contentUsing = ServiceIdentifierAdapter.ServiceIdentifierDeserializer.class)
|
||||
List<ServiceIdentifier> uuids404) {
|
||||
public record SendMultiRecipientMessageResponse(
|
||||
@Schema(description = "a list of the service identifiers in the request that do not correspond to registered Signal users; will only be present if a group send endorsement was supplied for the request")
|
||||
@JsonSerialize(contentUsing = ServiceIdentifierAdapter.ServiceIdentifierSerializer.class)
|
||||
@JsonDeserialize(contentUsing = ServiceIdentifierAdapter.ServiceIdentifierDeserializer.class)
|
||||
List<ServiceIdentifier> uuids404) {
|
||||
}
|
||||
+13
-19
@@ -6,18 +6,17 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.workers.IdleWakeupEligibilityChecker;
|
||||
import reactor.core.publisher.Flux;
|
||||
import javax.annotation.Nullable;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Collections;
|
||||
import java.util.EnumMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
abstract class IdleDevicePushNotificationExperiment implements PushNotificationExperiment<DeviceLastSeenState> {
|
||||
|
||||
private final Clock clock;
|
||||
private final IdleWakeupEligibilityChecker idleWakeupEligibilityChecker;
|
||||
|
||||
private final Logger log = LoggerFactory.getLogger(getClass());
|
||||
|
||||
@@ -37,19 +36,8 @@ abstract class IdleDevicePushNotificationExperiment implements PushNotificationE
|
||||
UNCHANGED
|
||||
}
|
||||
|
||||
protected IdleDevicePushNotificationExperiment(final Clock clock) {
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
protected abstract Duration getMinIdleDuration();
|
||||
|
||||
protected abstract Duration getMaxIdleDuration();
|
||||
|
||||
@VisibleForTesting
|
||||
boolean isIdle(final Device device) {
|
||||
final Duration idleDuration = Duration.between(Instant.ofEpochMilli(device.getLastSeen()), clock.instant());
|
||||
|
||||
return idleDuration.compareTo(getMinIdleDuration()) >= 0 && idleDuration.compareTo(getMaxIdleDuration()) < 0;
|
||||
protected IdleDevicePushNotificationExperiment(final IdleWakeupEligibilityChecker idleWakeupEligibilityChecker) {
|
||||
this.idleWakeupEligibilityChecker = idleWakeupEligibilityChecker;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -57,11 +45,18 @@ abstract class IdleDevicePushNotificationExperiment implements PushNotificationE
|
||||
return !StringUtils.isAllBlank(device.getApnId(), device.getGcmId());
|
||||
}
|
||||
|
||||
abstract boolean isIdleDeviceEligible(final Account account, final Device idleDevice, final DeviceLastSeenState state);
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Boolean> isDeviceEligible(final Account account, final Device device) {
|
||||
return idleWakeupEligibilityChecker.isDeviceEligible(account, device).thenApply(idle ->
|
||||
idle && isIdleDeviceEligible(account, device, getState(account, device)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public DeviceLastSeenState getState(@Nullable final Account account, @Nullable final Device device) {
|
||||
if (account != null && device != null) {
|
||||
final DeviceLastSeenState.PushTokenType pushTokenType;
|
||||
|
||||
if (StringUtils.isNotBlank(device.getApnId())) {
|
||||
pushTokenType = DeviceLastSeenState.PushTokenType.APNS;
|
||||
} else if (StringUtils.isNotBlank(device.getGcmId())) {
|
||||
@@ -69,7 +64,6 @@ abstract class IdleDevicePushNotificationExperiment implements PushNotificationE
|
||||
} else {
|
||||
pushTokenType = null;
|
||||
}
|
||||
|
||||
return new DeviceLastSeenState(true, device.getCreated(), hasPushToken(device), device.getLastSeen(), pushTokenType);
|
||||
} else {
|
||||
return DeviceLastSeenState.MISSING_DEVICE_STATE;
|
||||
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.filters;
|
||||
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import com.vdurmont.semver4j.Semver;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import jakarta.ws.rs.WebApplicationException;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.container.ContainerRequestFilter;
|
||||
import jakarta.ws.rs.core.SecurityContext;
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UserAgent;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
|
||||
|
||||
public class RestDeprecationFilter implements ContainerRequestFilter {
|
||||
|
||||
private static final String EXPERIMENT_NAME = "restDeprecation";
|
||||
private static final String DEPRECATED_REST_COUNTER_NAME = MetricsUtil.name(RestDeprecationFilter.class, "blockedRestRequest");
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(RestDeprecationFilter.class);
|
||||
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
public RestDeprecationFilter(
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager) {
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void filter(final ContainerRequestContext requestContext) throws IOException {
|
||||
|
||||
final SecurityContext securityContext = requestContext.getSecurityContext();
|
||||
|
||||
if (securityContext == null || securityContext.getUserPrincipal() == null) {
|
||||
// We can't check if an unauthenticated request is in the experiment
|
||||
return;
|
||||
}
|
||||
|
||||
if (securityContext.getUserPrincipal() instanceof AuthenticatedDevice ad) {
|
||||
if (!experimentEnrollmentManager.isEnrolled(ad.getAccount().getUuid(), EXPERIMENT_NAME)) {
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
log.error("Security context was not null but user principal was of type {}", securityContext.getUserPrincipal().getClass().getName());
|
||||
return;
|
||||
}
|
||||
|
||||
final Map<ClientPlatform, Semver> minimumRestFreeVersion = dynamicConfigurationManager.getConfiguration().minimumRestFreeVersion();
|
||||
final String userAgentString = requestContext.getHeaderString(HttpHeaders.USER_AGENT);
|
||||
|
||||
try {
|
||||
final UserAgent userAgent = UserAgentUtil.parseUserAgentString(userAgentString);
|
||||
final ClientPlatform platform = userAgent.getPlatform();
|
||||
final Semver version = userAgent.getVersion();
|
||||
if (!minimumRestFreeVersion.containsKey(platform)) {
|
||||
return;
|
||||
}
|
||||
if (version.isGreaterThanOrEqualTo(minimumRestFreeVersion.get(platform))) {
|
||||
Metrics.counter(
|
||||
DEPRECATED_REST_COUNTER_NAME, Tags.of("platform", platform.name().toLowerCase(), "version", version.toString()))
|
||||
.increment();
|
||||
throw new WebApplicationException("use websockets", 498);
|
||||
}
|
||||
} catch (final UnrecognizedUserAgentException e) {
|
||||
return; // at present we're only interested in experimenting on known clients
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-54
@@ -1,36 +1,8 @@
|
||||
package org.whispersystems.textsecuregcm.limits;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.lettuce.core.ScriptOutputType;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
|
||||
public class MessageDeliveryLoopMonitor {
|
||||
|
||||
private final ClusterLuaScript getDeliveryAttemptsScript;
|
||||
|
||||
private static final Duration DELIVERY_ATTEMPTS_COUNTER_TTL = Duration.ofHours(1);
|
||||
private static final int DELIVERY_LOOP_THRESHOLD = 5;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessageDeliveryLoopMonitor.class);
|
||||
|
||||
public MessageDeliveryLoopMonitor(final FaultTolerantRedisClusterClient rateLimitCluster) {
|
||||
try {
|
||||
getDeliveryAttemptsScript =
|
||||
ClusterLuaScript.fromResource(rateLimitCluster, "lua/get_delivery_attempt_count.lua", ScriptOutputType.INTEGER);
|
||||
} catch (final IOException e) {
|
||||
throw new UncheckedIOException("Failed to load 'get delivery attempt count' script", e);
|
||||
}
|
||||
}
|
||||
|
||||
public interface MessageDeliveryLoopMonitor {
|
||||
/**
|
||||
* Records an attempt to deliver a message with the given GUID to the given account/device pair and returns the number
|
||||
* of consecutive attempts to deliver the same message and logs a warning if the message appears to be in a delivery
|
||||
@@ -44,29 +16,5 @@ public class MessageDeliveryLoopMonitor {
|
||||
* @param userAgent the User-Agent header supplied by the caller
|
||||
* @param context a human-readable string identifying the mechanism of message delivery (e.g. "rest" or "websocket")
|
||||
*/
|
||||
public void recordDeliveryAttempt(final UUID accountIdentifier,
|
||||
final byte deviceId,
|
||||
final UUID messageGuid,
|
||||
final String userAgent,
|
||||
final String context) {
|
||||
|
||||
incrementDeliveryAttemptCount(accountIdentifier, deviceId, messageGuid)
|
||||
.thenAccept(deliveryAttemptCount -> {
|
||||
if (deliveryAttemptCount == DELIVERY_LOOP_THRESHOLD) {
|
||||
logger.warn("Detected loop delivering message {} via {} to {}:{} ({})",
|
||||
messageGuid, context, accountIdentifier, deviceId, userAgent);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
CompletableFuture<Long> incrementDeliveryAttemptCount(final UUID accountIdentifier, final byte deviceId, final UUID messageGuid) {
|
||||
final String firstMessageGuidKey = "firstMessageGuid::{" + accountIdentifier + ":" + deviceId + "}";
|
||||
final String deliveryAttemptsKey = "firstMessageDeliveryAttempts::{" + accountIdentifier + ":" + deviceId + "}";
|
||||
|
||||
return getDeliveryAttemptsScript.executeAsync(
|
||||
List.of(firstMessageGuidKey, deliveryAttemptsKey),
|
||||
List.of(messageGuid.toString(), String.valueOf(DELIVERY_ATTEMPTS_COUNTER_TTL.toSeconds())))
|
||||
.thenApply(result -> (long) result);
|
||||
}
|
||||
void recordDeliveryAttempt(UUID accountIdentifier, byte deviceId, UUID messageGuid, String userAgent, String context);
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package org.whispersystems.textsecuregcm.limits;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class NoopMessageDeliveryLoopMonitor implements MessageDeliveryLoopMonitor {
|
||||
|
||||
public NoopMessageDeliveryLoopMonitor() {
|
||||
}
|
||||
|
||||
public void recordDeliveryAttempt(final UUID accountIdentifier, final byte deviceId, final UUID messageGuid, final String userAgent, final String context) {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -41,7 +41,8 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
|
||||
RATE_LIMIT_RESET("rateLimitReset", true, new RateLimiterConfig(2, Duration.ofHours(12))),
|
||||
CAPTCHA_CHALLENGE_ATTEMPT("captchaChallengeAttempt", true, new RateLimiterConfig(10, Duration.ofMinutes(144))),
|
||||
CAPTCHA_CHALLENGE_SUCCESS("captchaChallengeSuccess", true, new RateLimiterConfig(2, Duration.ofHours(12))),
|
||||
SET_BACKUP_ID("setBackupId", true, new RateLimiterConfig(2, Duration.ofDays(7))),
|
||||
SET_BACKUP_ID("setBackupId", true, new RateLimiterConfig(10, Duration.ofHours(1))),
|
||||
SET_PAID_MEDIA_BACKUP_ID("setPaidMediaBackupId", true, new RateLimiterConfig(5, Duration.ofDays(7))),
|
||||
PUSH_CHALLENGE_ATTEMPT("pushChallengeAttempt", true, new RateLimiterConfig(10, Duration.ofMinutes(144))),
|
||||
PUSH_CHALLENGE_SUCCESS("pushChallengeSuccess", true, new RateLimiterConfig(2, Duration.ofHours(12))),
|
||||
GET_CALLING_RELAYS("getCallingRelays", false, new RateLimiterConfig(100, Duration.ofMinutes(10))),
|
||||
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
package org.whispersystems.textsecuregcm.limits;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.lettuce.core.ScriptOutputType;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
|
||||
public class RedisMessageDeliveryLoopMonitor implements MessageDeliveryLoopMonitor {
|
||||
|
||||
private final ClusterLuaScript getDeliveryAttemptsScript;
|
||||
|
||||
private static final Duration DELIVERY_ATTEMPTS_COUNTER_TTL = Duration.ofHours(1);
|
||||
private static final int DELIVERY_LOOP_THRESHOLD = 5;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessageDeliveryLoopMonitor.class);
|
||||
|
||||
public RedisMessageDeliveryLoopMonitor(final FaultTolerantRedisClusterClient rateLimitCluster) {
|
||||
try {
|
||||
getDeliveryAttemptsScript =
|
||||
ClusterLuaScript.fromResource(rateLimitCluster, "lua/get_delivery_attempt_count.lua", ScriptOutputType.INTEGER);
|
||||
} catch (final IOException e) {
|
||||
throw new UncheckedIOException("Failed to load 'get delivery attempt count' script", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Records an attempt to deliver a message with the given GUID to the given account/device pair and returns the number
|
||||
* of consecutive attempts to deliver the same message and logs a warning if the message appears to be in a delivery
|
||||
* loop. This method is intended to detect cases where a message remains at the head of a device's queue after
|
||||
* repeated attempts to deliver the message, and so the given message GUID should be the first message of a "page"
|
||||
* sent to clients.
|
||||
*
|
||||
* @param accountIdentifier the identifier of the destination account
|
||||
* @param deviceId the destination device's ID within the given account
|
||||
* @param messageGuid the GUID of the message
|
||||
* @param userAgent the User-Agent header supplied by the caller
|
||||
* @param context a human-readable string identifying the mechanism of message delivery (e.g. "rest" or "websocket")
|
||||
*/
|
||||
public void recordDeliveryAttempt(final UUID accountIdentifier,
|
||||
final byte deviceId,
|
||||
final UUID messageGuid,
|
||||
final String userAgent,
|
||||
final String context) {
|
||||
|
||||
incrementDeliveryAttemptCount(accountIdentifier, deviceId, messageGuid)
|
||||
.thenAccept(deliveryAttemptCount -> {
|
||||
if (deliveryAttemptCount == DELIVERY_LOOP_THRESHOLD) {
|
||||
logger.warn("Detected loop delivering message {} via {} to {}:{} ({})",
|
||||
messageGuid, context, accountIdentifier, deviceId, userAgent);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
CompletableFuture<Long> incrementDeliveryAttemptCount(final UUID accountIdentifier, final byte deviceId, final UUID messageGuid) {
|
||||
final String firstMessageGuidKey = "firstMessageGuid::{" + accountIdentifier + ":" + deviceId + "}";
|
||||
final String deliveryAttemptsKey = "firstMessageDeliveryAttempts::{" + accountIdentifier + ":" + deviceId + "}";
|
||||
|
||||
return getDeliveryAttemptsScript.executeAsync(
|
||||
List.of(firstMessageGuidKey, deliveryAttemptsKey),
|
||||
List.of(messageGuid.toString(), String.valueOf(DELIVERY_ATTEMPTS_COUNTER_TTL.toSeconds())))
|
||||
.thenApply(result -> (long) result);
|
||||
}
|
||||
|
||||
}
|
||||
+1
-1
@@ -81,7 +81,7 @@ public class MetricsRequestEventListener implements RequestEventListener {
|
||||
userAgent = userAgentValues != null && !userAgentValues.isEmpty() ? userAgentValues.get(0) : null;
|
||||
}
|
||||
|
||||
tags.add(UserAgentTagUtil.getPlatformTag(userAgent));
|
||||
tags.addAll(UserAgentTagUtil.getLibsignalAndPlatformTags(userAgent));
|
||||
|
||||
meterRegistry.counter(REQUEST_COUNTER_NAME, tags).increment();
|
||||
|
||||
|
||||
+9
-2
@@ -1,19 +1,23 @@
|
||||
package org.whispersystems.textsecuregcm.metrics;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
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.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import org.whispersystems.textsecuregcm.util.EnumMapUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
|
||||
import org.whispersystems.websocket.session.WebSocketSessionContext;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public class OpenWebSocketCounter {
|
||||
|
||||
private static final String WEBSOCKET_CLOSED_COUNTER_NAME = name(OpenWebSocketCounter.class, "websocketClosed");
|
||||
|
||||
private final Map<ClientPlatform, AtomicInteger> openWebsocketsByClientPlatform;
|
||||
private final AtomicInteger openWebsocketsFromUnknownPlatforms;
|
||||
|
||||
@@ -81,6 +85,9 @@ public class OpenWebSocketCounter {
|
||||
context.addWebsocketClosedListener((context1, statusCode, reason) -> {
|
||||
sample.stop(durationTimer);
|
||||
openWebSocketCounter.decrementAndGet();
|
||||
|
||||
Metrics.counter(WEBSOCKET_CLOSED_COUNTER_NAME, "status", String.valueOf(statusCode))
|
||||
.increment();
|
||||
});
|
||||
}
|
||||
}
|
||||
+21
-5
@@ -5,14 +5,10 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.metrics;
|
||||
|
||||
import com.vdurmont.semver4j.Semver;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UserAgent;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
|
||||
@@ -24,6 +20,7 @@ public class UserAgentTagUtil {
|
||||
|
||||
public static final String PLATFORM_TAG = "platform";
|
||||
public static final String VERSION_TAG = "clientVersion";
|
||||
public static final String LIBSIGNAL_TAG = "libsignal";
|
||||
|
||||
private UserAgentTagUtil() {
|
||||
}
|
||||
@@ -52,4 +49,23 @@ public class UserAgentTagUtil {
|
||||
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
public static List<Tag> getLibsignalAndPlatformTags(final String userAgentString) {
|
||||
String platform;
|
||||
boolean libsignal;
|
||||
|
||||
try {
|
||||
final UserAgent userAgent = UserAgentUtil.parseUserAgentString(userAgentString);
|
||||
platform = userAgent.getPlatform().name().toLowerCase();
|
||||
libsignal = userAgent.getAdditionalSpecifiers()
|
||||
.map(additionalSpecifiers -> additionalSpecifiers.contains("libsignal"))
|
||||
.orElse(false);
|
||||
} catch (final UnrecognizedUserAgentException e) {
|
||||
platform = "unrecognized";
|
||||
libsignal = false;
|
||||
}
|
||||
|
||||
return List.of(Tag.of(PLATFORM_TAG, platform), Tag.of(LIBSIGNAL_TAG, String.valueOf(libsignal)));
|
||||
}
|
||||
|
||||
}
|
||||
+1
-5
@@ -55,11 +55,7 @@ public class MultiRecipientMessageProvider implements MessageBodyReader<SealedSe
|
||||
|
||||
try {
|
||||
final SealedSenderMultiRecipientMessage message = SealedSenderMultiRecipientMessage.parse(fullMessage);
|
||||
RECIPIENT_COUNT_DISTRIBUTION.record(message.getRecipients().keySet().size());
|
||||
|
||||
if (message.getRecipients().values().stream().anyMatch(r -> message.messageSizeForRecipient(r) > MAX_MESSAGE_SIZE)) {
|
||||
throw new BadRequestException("message payload too large");
|
||||
}
|
||||
RECIPIENT_COUNT_DISTRIBUTION.record(message.getRecipients().size());
|
||||
return message;
|
||||
} catch (InvalidMessageException | InvalidVersionException e) {
|
||||
throw new BadRequestException(e);
|
||||
|
||||
@@ -98,24 +98,24 @@ public class FcmSender implements PushNotificationSender {
|
||||
return GoogleApiUtil.toCompletableFuture(firebaseMessagingClient.sendAsync(builder.build()), executor)
|
||||
.whenComplete((ignored, throwable) -> sample.stop(SEND_NOTIFICATION_TIMER))
|
||||
.thenApply(ignored -> new SendPushNotificationResult(true, Optional.empty(), false, Optional.empty()))
|
||||
.exceptionally(throwable -> {
|
||||
if (ExceptionUtils.unwrap(throwable) instanceof final FirebaseMessagingException firebaseMessagingException) {
|
||||
final String errorCode;
|
||||
.exceptionally(ExceptionUtils.exceptionallyHandler(FirebaseMessagingException.class,
|
||||
firebaseMessagingException -> {
|
||||
final String errorCode;
|
||||
|
||||
if (firebaseMessagingException.getMessagingErrorCode() != null) {
|
||||
errorCode = firebaseMessagingException.getMessagingErrorCode().name();
|
||||
} else {
|
||||
logger.warn("Received an FCM exception with no error code", firebaseMessagingException);
|
||||
errorCode = "unknown";
|
||||
}
|
||||
if (firebaseMessagingException.getMessagingErrorCode() != null) {
|
||||
errorCode = firebaseMessagingException.getMessagingErrorCode().name();
|
||||
} else if (firebaseMessagingException.getHttpResponse() != null) {
|
||||
errorCode = "http" + firebaseMessagingException.getHttpResponse().getStatusCode();
|
||||
} else {
|
||||
logger.warn("Received an FCM exception with no error code", firebaseMessagingException);
|
||||
errorCode = "unknown";
|
||||
}
|
||||
|
||||
final boolean unregistered =
|
||||
firebaseMessagingException.getMessagingErrorCode() == MessagingErrorCode.UNREGISTERED;
|
||||
final boolean unregistered =
|
||||
firebaseMessagingException.getMessagingErrorCode() == MessagingErrorCode.UNREGISTERED;
|
||||
|
||||
return new SendPushNotificationResult(false, Optional.of(errorCode), unregistered, Optional.empty());
|
||||
} else {
|
||||
throw ExceptionUtils.wrap(throwable);
|
||||
}
|
||||
});
|
||||
return new SendPushNotificationResult(false, Optional.of(errorCode), unregistered, Optional.empty());
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,9 +9,14 @@ import static org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
/**
|
||||
* A MessageSender sends Signal messages to destination devices. Messages may be "normal" user-to-user messages,
|
||||
@@ -42,26 +47,82 @@ public class MessageSender {
|
||||
this.pushNotificationManager = pushNotificationManager;
|
||||
}
|
||||
|
||||
public void sendMessage(final Account account, final Device device, final Envelope message, final boolean online) {
|
||||
final boolean destinationPresent = messagesManager.insert(account.getUuid(),
|
||||
device.getId(),
|
||||
online ? message.toBuilder().setEphemeral(true).build() : message);
|
||||
/**
|
||||
* Sends messages to devices associated with the given destination account. If a destination device has a valid push
|
||||
* notification token and does not have an active connection to a Signal server, then this method will also send a
|
||||
* push notification to that device to announce the availability of new messages.
|
||||
*
|
||||
* @param account the account to which to send messages
|
||||
* @param messagesByDeviceId a map of device IDs to message payloads
|
||||
*/
|
||||
public void sendMessages(final Account account, final Map<Byte, Envelope> messagesByDeviceId) {
|
||||
messagesManager.insert(account.getIdentifier(IdentityType.ACI), messagesByDeviceId)
|
||||
.forEach((deviceId, destinationPresent) -> {
|
||||
final Envelope message = messagesByDeviceId.get(deviceId);
|
||||
|
||||
if (!destinationPresent && !online) {
|
||||
try {
|
||||
pushNotificationManager.sendNewMessageNotification(account, device.getId(), message.getUrgent());
|
||||
} catch (final NotPushRegisteredException ignored) {
|
||||
}
|
||||
}
|
||||
if (!destinationPresent && !message.getEphemeral()) {
|
||||
try {
|
||||
pushNotificationManager.sendNewMessageNotification(account, deviceId, message.getUrgent());
|
||||
} catch (final NotPushRegisteredException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
Metrics.counter(SEND_COUNTER_NAME,
|
||||
CHANNEL_TAG_NAME, getDeliveryChannelName(device),
|
||||
EPHEMERAL_TAG_NAME, String.valueOf(online),
|
||||
CLIENT_ONLINE_TAG_NAME, String.valueOf(destinationPresent),
|
||||
URGENT_TAG_NAME, String.valueOf(message.getUrgent()),
|
||||
STORY_TAG_NAME, String.valueOf(message.getStory()),
|
||||
SEALED_SENDER_TAG_NAME, String.valueOf(!message.hasSourceServiceId()))
|
||||
.increment();
|
||||
Metrics.counter(SEND_COUNTER_NAME,
|
||||
CHANNEL_TAG_NAME, account.getDevice(deviceId).map(MessageSender::getDeliveryChannelName).orElse("unknown"),
|
||||
EPHEMERAL_TAG_NAME, String.valueOf(message.getEphemeral()),
|
||||
CLIENT_ONLINE_TAG_NAME, String.valueOf(destinationPresent),
|
||||
URGENT_TAG_NAME, String.valueOf(message.getUrgent()),
|
||||
STORY_TAG_NAME, String.valueOf(message.getStory()),
|
||||
SEALED_SENDER_TAG_NAME, String.valueOf(!message.hasSourceServiceId()))
|
||||
.increment();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends messages to a group of recipients. If a destination device has a valid push notification token and does not
|
||||
* have an active connection to a Signal server, then this method will also send a push notification to that device to
|
||||
* announce the availability of new messages.
|
||||
*
|
||||
* @param multiRecipientMessage the multi-recipient message to send to the given recipients
|
||||
* @param resolvedRecipients a map of recipients to resolved Signal accounts
|
||||
* @param clientTimestamp the time at which the sender reports the message was sent
|
||||
* @param isStory {@code true} if the message is a story or {@code false otherwise}
|
||||
* @param isEphemeral {@code true} if the message should only be delivered to devices with active connections or
|
||||
* {@code false otherwise}
|
||||
* @param isUrgent {@code true} if the message is urgent or {@code false otherwise}
|
||||
*
|
||||
* @return a future that completes when all messages have been inserted into delivery queues
|
||||
*/
|
||||
public CompletableFuture<Void> sendMultiRecipientMessage(final SealedSenderMultiRecipientMessage multiRecipientMessage,
|
||||
final Map<SealedSenderMultiRecipientMessage.Recipient, Account> resolvedRecipients,
|
||||
final long clientTimestamp,
|
||||
final boolean isStory,
|
||||
final boolean isEphemeral,
|
||||
final boolean isUrgent) {
|
||||
|
||||
return messagesManager.insertMultiRecipientMessage(multiRecipientMessage, resolvedRecipients, clientTimestamp,
|
||||
isStory, isEphemeral, isUrgent)
|
||||
.thenAccept(clientPresenceByAccountAndDevice ->
|
||||
clientPresenceByAccountAndDevice.forEach((account, clientPresenceByDeviceId) ->
|
||||
clientPresenceByDeviceId.forEach((deviceId, clientPresent) -> {
|
||||
if (!clientPresent && !isEphemeral) {
|
||||
try {
|
||||
pushNotificationManager.sendNewMessageNotification(account, deviceId, isUrgent);
|
||||
} catch (final NotPushRegisteredException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
Metrics.counter(SEND_COUNTER_NAME,
|
||||
CHANNEL_TAG_NAME,
|
||||
account.getDevice(deviceId).map(MessageSender::getDeliveryChannelName).orElse("unknown"),
|
||||
EPHEMERAL_TAG_NAME, String.valueOf(isEphemeral),
|
||||
CLIENT_ONLINE_TAG_NAME, String.valueOf(clientPresent),
|
||||
URGENT_TAG_NAME, String.valueOf(isUrgent),
|
||||
STORY_TAG_NAME, String.valueOf(isStory),
|
||||
SEALED_SENDER_TAG_NAME, String.valueOf(true))
|
||||
.increment();
|
||||
})))
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
|
||||
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.push;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.binder.jvm.ExecutorServiceMetrics;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.stream.Collectors;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
@@ -43,21 +44,21 @@ public class ReceiptSender {
|
||||
try {
|
||||
accountManager.getByAccountIdentifier(destinationIdentifier.uuid()).ifPresentOrElse(
|
||||
destinationAccount -> {
|
||||
final Envelope.Builder message = Envelope.newBuilder()
|
||||
final Envelope message = Envelope.newBuilder()
|
||||
.setServerTimestamp(System.currentTimeMillis())
|
||||
.setSourceServiceId(sourceIdentifier.toServiceIdentifierString())
|
||||
.setSourceDevice(sourceDeviceId)
|
||||
.setDestinationServiceId(destinationIdentifier.toServiceIdentifierString())
|
||||
.setClientTimestamp(messageId)
|
||||
.setType(Envelope.Type.SERVER_DELIVERY_RECEIPT)
|
||||
.setUrgent(false);
|
||||
.setUrgent(false)
|
||||
.build();
|
||||
|
||||
for (final Device destinationDevice : destinationAccount.getDevices()) {
|
||||
try {
|
||||
messageSender.sendMessage(destinationAccount, destinationDevice, message.build(), false);
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Could not send delivery receipt", e);
|
||||
}
|
||||
try {
|
||||
messageSender.sendMessages(destinationAccount, destinationAccount.getDevices().stream()
|
||||
.collect(Collectors.toMap(Device::getId, ignored -> message)));
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Could not send delivery receipt", e);
|
||||
}
|
||||
},
|
||||
() -> logger.info("No longer registered: {}", destinationIdentifier)
|
||||
|
||||
@@ -1242,6 +1242,26 @@ public class Accounts {
|
||||
.sequential();
|
||||
}
|
||||
|
||||
Flux<UUID> getAllAccountIdentifiers(final int segments, final Scheduler scheduler) {
|
||||
if (segments < 1) {
|
||||
throw new IllegalArgumentException("Total number of segments must be positive");
|
||||
}
|
||||
|
||||
return Flux.range(0, segments)
|
||||
.parallel()
|
||||
.runOn(scheduler)
|
||||
.flatMap(segment -> dynamoDbAsyncClient.scanPaginator(ScanRequest.builder()
|
||||
.tableName(accountsTableName)
|
||||
.consistentRead(false)
|
||||
.segment(segment)
|
||||
.totalSegments(segments)
|
||||
.projectionExpression(KEY_ACCOUNT_UUID)
|
||||
.build())
|
||||
.items()
|
||||
.map(item -> AttributeValues.getUUID(item, KEY_ACCOUNT_UUID, null)))
|
||||
.sequential();
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
private Optional<Account> getByIndirectLookup(
|
||||
final Timer timer,
|
||||
|
||||
@@ -1217,6 +1217,10 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
return accounts.getAll(segments, scheduler);
|
||||
}
|
||||
|
||||
public Flux<UUID> streamAccountIdentifiersFromDynamo(final int segments, final Scheduler scheduler) {
|
||||
return accounts.getAllAccountIdentifiers(segments, scheduler);
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> delete(final Account account, final DeletionReason deletionReason) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
|
||||
+29
-30
@@ -4,8 +4,8 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -13,10 +13,10 @@ import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.ObjectUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.controllers.MessageController;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
import org.whispersystems.textsecuregcm.controllers.StaleDevicesException;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
@@ -115,40 +115,39 @@ public class ChangeNumberManager {
|
||||
|
||||
private void sendDeviceMessages(final Account account, final List<IncomingMessage> deviceMessages) {
|
||||
try {
|
||||
deviceMessages.forEach(message ->
|
||||
sendMessageToSelf(account, account.getDevice(message.destinationDeviceId()), message));
|
||||
} catch (RuntimeException e) {
|
||||
final long serverTimestamp = System.currentTimeMillis();
|
||||
|
||||
messageSender.sendMessages(account, deviceMessages.stream()
|
||||
.filter(message -> getMessageContent(message).isPresent())
|
||||
.collect(Collectors.toMap(IncomingMessage::destinationDeviceId, message -> Envelope.newBuilder()
|
||||
.setType(Envelope.Type.forNumber(message.type()))
|
||||
.setClientTimestamp(serverTimestamp)
|
||||
.setServerTimestamp(serverTimestamp)
|
||||
.setDestinationServiceId(new AciServiceIdentifier(account.getUuid()).toServiceIdentifierString())
|
||||
.setContent(ByteString.copyFrom(getMessageContent(message).orElseThrow()))
|
||||
.setSourceServiceId(new AciServiceIdentifier(account.getUuid()).toServiceIdentifierString())
|
||||
.setSourceDevice(Device.PRIMARY_ID)
|
||||
.setUpdatedPni(account.getPhoneNumberIdentifier().toString())
|
||||
.setUrgent(true)
|
||||
.setEphemeral(false)
|
||||
.build())));
|
||||
} catch (final RuntimeException e) {
|
||||
logger.warn("Changed number but could not send all device messages on {}", account.getUuid(), e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
void sendMessageToSelf(
|
||||
Account sourceAndDestinationAccount, Optional<Device> destinationDevice, IncomingMessage message) {
|
||||
Optional<byte[]> contents = MessageController.getMessageContent(message);
|
||||
if (contents.isEmpty()) {
|
||||
logger.debug("empty message contents sending to self, ignoring");
|
||||
return;
|
||||
} else if (destinationDevice.isEmpty()) {
|
||||
logger.debug("destination device not present");
|
||||
return;
|
||||
private static Optional<byte[]> getMessageContent(final IncomingMessage message) {
|
||||
if (StringUtils.isEmpty(message.content())) {
|
||||
logger.warn("Message has no content");
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
final long serverTimestamp = System.currentTimeMillis();
|
||||
final Envelope envelope = Envelope.newBuilder()
|
||||
.setType(Envelope.Type.forNumber(message.type()))
|
||||
.setClientTimestamp(serverTimestamp)
|
||||
.setServerTimestamp(serverTimestamp)
|
||||
.setDestinationServiceId(
|
||||
new AciServiceIdentifier(sourceAndDestinationAccount.getUuid()).toServiceIdentifierString())
|
||||
.setContent(ByteString.copyFrom(contents.get()))
|
||||
.setSourceServiceId(new AciServiceIdentifier(sourceAndDestinationAccount.getUuid()).toServiceIdentifierString())
|
||||
.setSourceDevice(Device.PRIMARY_ID)
|
||||
.setUpdatedPni(sourceAndDestinationAccount.getPhoneNumberIdentifier().toString())
|
||||
.setUrgent(true)
|
||||
.build();
|
||||
|
||||
messageSender.sendMessage(sourceAndDestinationAccount, destinationDevice.get(), envelope, false);
|
||||
try {
|
||||
return Optional.of(Base64.getDecoder().decode(message.content()));
|
||||
} catch (final IllegalArgumentException e) {
|
||||
logger.warn("Failed to parse message content", e);
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
+101
-30
@@ -14,6 +14,7 @@ import io.lettuce.core.ZAddArgs;
|
||||
import io.lettuce.core.cluster.SlotHash;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
@@ -131,9 +132,11 @@ public class MessagesCache {
|
||||
private final Timer clearQueueTimer = Metrics.timer(name(MessagesCache.class, "clear"));
|
||||
private final Counter staleEphemeralMessagesCounter = Metrics.counter(
|
||||
name(MessagesCache.class, "staleEphemeralMessages"));
|
||||
private final Counter staleMrmMessagesCounter = Metrics.counter(name(MessagesCache.class, "staleMrmMessages"));
|
||||
private final Counter mrmContentRetrievedCounter = Metrics.counter(name(MessagesCache.class, "mrmViewRetrieved"));
|
||||
private final String MRM_RETRIEVAL_ERROR_COUNTER_NAME = name(MessagesCache.class, "mrmRetrievalError");
|
||||
private final String EPHEMERAL_TAG_NAME = "ephemeral";
|
||||
private final String MISSING_MRM_DATA_TAG_NAME = "missingMrmData";
|
||||
private final Counter skippedStaleEphemeralMrmCounter = Metrics.counter(
|
||||
name(MessagesCache.class, "skippedStaleEphemeralMrm"));
|
||||
private final Counter sharedMrmDataKeyRemovedCounter = Metrics.counter(
|
||||
@@ -142,6 +145,8 @@ public class MessagesCache {
|
||||
static final String NEXT_SLOT_TO_PERSIST_KEY = "user_queue_persist_slot";
|
||||
private static final byte[] LOCK_VALUE = "1".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
private static final ByteString STALE_MRM_KEY = ByteString.copyFromUtf8("stale");
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration MAX_EPHEMERAL_MESSAGE_DELAY = Duration.ofSeconds(10);
|
||||
|
||||
@@ -203,22 +208,28 @@ public class MessagesCache {
|
||||
this.unlockQueueScript = unlockQueueScript;
|
||||
}
|
||||
|
||||
public boolean insert(final UUID messageGuid,
|
||||
public CompletableFuture<Boolean> insert(final UUID messageGuid,
|
||||
final UUID destinationAccountIdentifier,
|
||||
final byte destinationDeviceId,
|
||||
final MessageProtos.Envelope message) {
|
||||
|
||||
final MessageProtos.Envelope messageWithGuid = message.toBuilder().setServerGuid(messageGuid.toString()).build();
|
||||
return insertTimer.record(() -> insertScript.execute(destinationAccountIdentifier, destinationDeviceId, messageWithGuid));
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
return insertScript.executeAsync(destinationAccountIdentifier, destinationDeviceId, messageWithGuid)
|
||||
.whenComplete((ignored, throwable) -> sample.stop(insertTimer));
|
||||
}
|
||||
|
||||
public byte[] insertSharedMultiRecipientMessagePayload(
|
||||
public CompletableFuture<byte[]> insertSharedMultiRecipientMessagePayload(
|
||||
final SealedSenderMultiRecipientMessage sealedSenderMultiRecipientMessage) {
|
||||
return insertSharedMrmPayloadTimer.record(() -> {
|
||||
final byte[] sharedMrmKey = getSharedMrmKey(UUID.randomUUID());
|
||||
insertMrmScript.execute(sharedMrmKey, sealedSenderMultiRecipientMessage);
|
||||
return sharedMrmKey;
|
||||
});
|
||||
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
final byte[] sharedMrmKey = getSharedMrmKey(UUID.randomUUID());
|
||||
|
||||
return insertMrmScript.executeAsync(sharedMrmKey, sealedSenderMultiRecipientMessage)
|
||||
.thenApply(ignored -> sharedMrmKey)
|
||||
.whenComplete((ignored, throwable) -> sample.stop(insertSharedMrmPayloadTimer));
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<RemovedMessage>> remove(final UUID destinationUuid, final byte destinationDevice,
|
||||
@@ -281,20 +292,26 @@ public class MessagesCache {
|
||||
final Flux<MessageProtos.Envelope> allMessages = getAllMessages(destinationUuid, destinationDevice,
|
||||
earliestAllowableEphemeralTimestamp, PAGE_SIZE)
|
||||
.publish()
|
||||
// We expect exactly two subscribers to this base flux:
|
||||
// We expect exactly three subscribers to this base flux:
|
||||
// 1. the websocket that delivers messages to clients
|
||||
// 2. an internal process to discard stale ephemeral messages
|
||||
// The discard subscriber will subscribe immediately, but we don’t want to do any work if the
|
||||
// 2. an internal processes to discard stale ephemeral messages
|
||||
// 3. an internal process to discard stale MRM messages
|
||||
// The discard subscribers will subscribe immediately, but we don’t want to do any work if the
|
||||
// websocket never subscribes.
|
||||
.autoConnect(2);
|
||||
.autoConnect(3);
|
||||
|
||||
final Flux<MessageProtos.Envelope> messagesToPublish = allMessages
|
||||
.filter(Predicate.not(envelope -> isStaleEphemeralMessage(envelope, earliestAllowableEphemeralTimestamp)));
|
||||
.filter(Predicate.not(envelope ->
|
||||
isStaleEphemeralMessage(envelope, earliestAllowableEphemeralTimestamp) || isStaleMrmMessage(envelope)));
|
||||
|
||||
final Flux<MessageProtos.Envelope> staleEphemeralMessages = allMessages
|
||||
.filter(envelope -> isStaleEphemeralMessage(envelope, earliestAllowableEphemeralTimestamp));
|
||||
discardStaleMessages(destinationUuid, destinationDevice, staleEphemeralMessages, staleEphemeralMessagesCounter, "ephemeral");
|
||||
|
||||
discardStaleEphemeralMessages(destinationUuid, destinationDevice, staleEphemeralMessages);
|
||||
final Flux<MessageProtos.Envelope> staleMrmMessages = allMessages.filter(MessagesCache::isStaleMrmMessage)
|
||||
// clearing the sharedMrmKey prevents unnecessary calls to update the shared MRM data
|
||||
.map(envelope -> envelope.toBuilder().clearSharedMrmKey().build());
|
||||
discardStaleMessages(destinationUuid, destinationDevice, staleMrmMessages, staleMrmMessagesCounter, "mrm");
|
||||
|
||||
return messagesToPublish.name(GET_FLUX_NAME)
|
||||
.tap(Micrometer.metrics(Metrics.globalRegistry));
|
||||
@@ -311,16 +328,25 @@ public class MessagesCache {
|
||||
return message.getEphemeral() && message.getClientTimestamp() < earliestAllowableTimestamp;
|
||||
}
|
||||
|
||||
private void discardStaleEphemeralMessages(final UUID destinationUuid, final byte destinationDevice,
|
||||
Flux<MessageProtos.Envelope> staleEphemeralMessages) {
|
||||
staleEphemeralMessages
|
||||
/**
|
||||
* Checks whether the given message is a stale MRM message
|
||||
*
|
||||
* @see #getMessageWithSharedMrmData(MessageProtos.Envelope, byte)
|
||||
*/
|
||||
private static boolean isStaleMrmMessage(final MessageProtos.Envelope message) {
|
||||
return message.hasSharedMrmKey() && STALE_MRM_KEY.equals(message.getSharedMrmKey());
|
||||
}
|
||||
|
||||
private void discardStaleMessages(final UUID destinationUuid, final byte destinationDevice,
|
||||
Flux<MessageProtos.Envelope> staleMessages, final Counter counter, final String context) {
|
||||
staleMessages
|
||||
.map(e -> UUID.fromString(e.getServerGuid()))
|
||||
.buffer(PAGE_SIZE)
|
||||
.subscribeOn(messageDeletionScheduler)
|
||||
.subscribe(staleEphemeralMessageGuids ->
|
||||
remove(destinationUuid, destinationDevice, staleEphemeralMessageGuids)
|
||||
.thenAccept(removedMessages -> staleEphemeralMessagesCounter.increment(removedMessages.size())),
|
||||
e -> logger.warn("Could not remove stale ephemeral messages from cache", e));
|
||||
.subscribe(messageGuids ->
|
||||
remove(destinationUuid, destinationDevice, messageGuids)
|
||||
.thenAccept(removedMessages -> counter.increment(removedMessages.size())),
|
||||
e -> logger.warn("Could not remove stale {} messages from cache", context, e));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -376,7 +402,13 @@ public class MessagesCache {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the given message with its shared MRM data.
|
||||
* Returns the given message with its shared MRM data. There are three possible cases:
|
||||
* <ol>
|
||||
* <li>The reconstructed message for delivery with {@code content} set and {@code sharedMrmKey} cleared</li>
|
||||
* <li>The input with {@code sharedMrmKey} set to a static value, indicating that the shared MRM data is no longer available, and the message should be
|
||||
* discarded from the queue</li>
|
||||
* <li>An empty {@code Mono}, if an unexpected error occurred</li>
|
||||
* </ol>
|
||||
*/
|
||||
private Mono<MessageProtos.Envelope> getMessageWithSharedMrmData(final MessageProtos.Envelope mrmMessage,
|
||||
final byte destinationDevice) {
|
||||
@@ -396,6 +428,18 @@ public class MessagesCache {
|
||||
try {
|
||||
assert mrmDataAndView.size() == 2;
|
||||
|
||||
if (mrmDataAndView.getFirst().isEmpty()) {
|
||||
// shared data is missing
|
||||
//noinspection ReactiveStreamsThrowInOperator
|
||||
throw new MrmDataMissingException(MrmDataMissingException.Type.SHARED);
|
||||
}
|
||||
|
||||
if (mrmDataAndView.getLast().isEmpty()) {
|
||||
// recipient's view is missing
|
||||
//noinspection ReactiveStreamsThrowInOperator
|
||||
throw new MrmDataMissingException(MrmDataMissingException.Type.RECIPIENT_VIEW);
|
||||
}
|
||||
|
||||
final byte[] content = SealedSenderMultiRecipientMessage.messageForRecipient(
|
||||
mrmDataAndView.getFirst().getValue(),
|
||||
mrmDataAndView.getLast().getValue());
|
||||
@@ -411,12 +455,25 @@ public class MessagesCache {
|
||||
}
|
||||
})
|
||||
.onErrorResume(throwable -> {
|
||||
logger.warn("Failed to retrieve shared mrm data", throwable);
|
||||
Metrics.counter(MRM_RETRIEVAL_ERROR_COUNTER_NAME,
|
||||
EPHEMERAL_TAG_NAME, String.valueOf(mrmMessage.getEphemeral()))
|
||||
.increment();
|
||||
|
||||
return Mono.empty();
|
||||
final List<Tag> tags = new ArrayList<>();
|
||||
tags.add(Tag.of(EPHEMERAL_TAG_NAME, String.valueOf(mrmMessage.getEphemeral())));
|
||||
|
||||
final Mono<MessageProtos.Envelope> result;
|
||||
if (throwable instanceof MrmDataMissingException mdme) {
|
||||
tags.add(Tag.of(MISSING_MRM_DATA_TAG_NAME, mdme.getType().name()));
|
||||
// MRM data may be missing if either of the two non-transactional writes (delete from queue, update shared
|
||||
// MRM data) fails after it has been delivered. We return it so that it may be discarded from the queue.
|
||||
result = Mono.just(mrmMessage.toBuilder().setSharedMrmKey(STALE_MRM_KEY).build());
|
||||
} else {
|
||||
logger.warn("Failed to retrieve shared mrm data", throwable);
|
||||
// For unexpected errors, return empty. The message will remain in the queue and be retried in the future.
|
||||
result = Mono.empty();
|
||||
}
|
||||
|
||||
Metrics.counter(MRM_RETRIEVAL_ERROR_COUNTER_NAME, tags).increment();
|
||||
|
||||
return result;
|
||||
})
|
||||
.share();
|
||||
}
|
||||
@@ -471,7 +528,6 @@ public class MessagesCache {
|
||||
});
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
List<MessageProtos.Envelope> getMessagesToPersist(final UUID accountUuid, final byte destinationDevice,
|
||||
final int limit) {
|
||||
|
||||
@@ -480,7 +536,7 @@ public class MessagesCache {
|
||||
final List<byte[]> messages = redisCluster.withBinaryCluster(connection ->
|
||||
connection.sync().zrange(getMessageQueueKey(accountUuid, destinationDevice), 0, limit));
|
||||
|
||||
return Flux.fromIterable(messages)
|
||||
final Flux<MessageProtos.Envelope> allMessages = Flux.fromIterable(messages)
|
||||
.mapNotNull(message -> {
|
||||
try {
|
||||
return MessageProtos.Envelope.parseFrom(message);
|
||||
@@ -498,7 +554,22 @@ public class MessagesCache {
|
||||
}
|
||||
|
||||
return messageMono;
|
||||
})
|
||||
});
|
||||
|
||||
final Flux<MessageProtos.Envelope> messagesToPersist = allMessages
|
||||
.filter(Predicate.not(envelope ->
|
||||
envelope.getEphemeral() || isStaleMrmMessage(envelope)));
|
||||
|
||||
final Flux<MessageProtos.Envelope> ephemeralMessages = allMessages
|
||||
.filter(MessageProtos.Envelope::getEphemeral);
|
||||
discardStaleMessages(accountUuid, destinationDevice, ephemeralMessages, staleEphemeralMessagesCounter, "ephemeral");
|
||||
|
||||
final Flux<MessageProtos.Envelope> staleMrmMessages = allMessages.filter(MessagesCache::isStaleMrmMessage)
|
||||
// clearing the sharedMrmKey prevents unnecessary calls to update the shared MRM data
|
||||
.map(envelope -> envelope.toBuilder().clearSharedMrmKey().build());
|
||||
discardStaleMessages(accountUuid, destinationDevice, staleMrmMessages, staleMrmMessagesCounter, "mrm");
|
||||
|
||||
return messagesToPersist
|
||||
.collectList()
|
||||
.doOnTerminate(() -> sample.stop(getMessagesTimer))
|
||||
.block(Duration.ofSeconds(5));
|
||||
|
||||
+4
-2
@@ -12,6 +12,7 @@ import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.push.ClientEvent;
|
||||
import org.whispersystems.textsecuregcm.push.NewMessageAvailableEvent;
|
||||
@@ -44,7 +45,7 @@ class MessagesCacheInsertScript {
|
||||
* @return {@code true} if the destination device had a registered "presence"/event subscriber or {@code false}
|
||||
* otherwise
|
||||
*/
|
||||
boolean execute(final UUID destinationUuid, final byte destinationDevice, final MessageProtos.Envelope envelope) {
|
||||
CompletableFuture<Boolean> executeAsync(final UUID destinationUuid, final byte destinationDevice, final MessageProtos.Envelope envelope) {
|
||||
assert envelope.hasServerGuid();
|
||||
assert envelope.hasServerTimestamp();
|
||||
|
||||
@@ -62,6 +63,7 @@ class MessagesCacheInsertScript {
|
||||
NEW_MESSAGE_EVENT_BYTES // eventPayload
|
||||
));
|
||||
|
||||
return (boolean) insertScript.executeBinary(keys, args);
|
||||
return insertScript.executeBinaryAsync(keys, args)
|
||||
.thenApply(result -> (boolean) result);
|
||||
}
|
||||
}
|
||||
+5
-2
@@ -9,9 +9,11 @@ import io.lettuce.core.ScriptOutputType;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
/**
|
||||
* Inserts the shared multi-recipient message payload into the cache. The list of recipients and views will be set as
|
||||
@@ -31,7 +33,7 @@ class MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript {
|
||||
ScriptOutputType.INTEGER);
|
||||
}
|
||||
|
||||
void execute(final byte[] sharedMrmKey, final SealedSenderMultiRecipientMessage message) {
|
||||
CompletableFuture<Void> executeAsync(final byte[] sharedMrmKey, final SealedSenderMultiRecipientMessage message) {
|
||||
final List<byte[]> keys = List.of(
|
||||
sharedMrmKey // sharedMrmKey
|
||||
);
|
||||
@@ -47,6 +49,7 @@ class MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript {
|
||||
}
|
||||
});
|
||||
|
||||
script.executeBinary(keys, args);
|
||||
return script.executeBinaryAsync(keys, args)
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
}
|
||||
+104
-22
@@ -6,18 +6,23 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import javax.annotation.Nullable;
|
||||
import org.reactivestreams.Publisher;
|
||||
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
|
||||
@@ -25,6 +30,8 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import reactor.core.observability.micrometer.Micrometer;
|
||||
@@ -48,41 +55,120 @@ public class MessagesManager {
|
||||
private final MessagesCache messagesCache;
|
||||
private final ReportMessageManager reportMessageManager;
|
||||
private final ExecutorService messageDeletionExecutor;
|
||||
private final Clock clock;
|
||||
|
||||
public MessagesManager(
|
||||
final MessagesDynamoDb messagesDynamoDb,
|
||||
final MessagesCache messagesCache,
|
||||
final ReportMessageManager reportMessageManager,
|
||||
final ExecutorService messageDeletionExecutor) {
|
||||
final ExecutorService messageDeletionExecutor,
|
||||
final Clock clock) {
|
||||
|
||||
this.messagesDynamoDb = messagesDynamoDb;
|
||||
this.messagesCache = messagesCache;
|
||||
this.reportMessageManager = reportMessageManager;
|
||||
this.messageDeletionExecutor = messageDeletionExecutor;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts a message into a target device's message queue and notifies registered listeners that a new message is
|
||||
* available.
|
||||
* Inserts messages into the message queues for devices associated with the identified account.
|
||||
*
|
||||
* @param destinationUuid the account identifier for the destination queue
|
||||
* @param destinationDeviceId the device ID for the destination queue
|
||||
* @param message the message to insert into the queue
|
||||
* @param accountIdentifier the account identifier for the destination queue
|
||||
* @param messagesByDeviceId a map of device IDs to messages
|
||||
*
|
||||
* @return {@code true} if the destination device is "present" (i.e. has an active event listener) or {@code false}
|
||||
* otherwise
|
||||
* @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
|
||||
*/
|
||||
public boolean insert(final UUID destinationUuid, final byte destinationDeviceId, final Envelope message) {
|
||||
final UUID messageGuid = UUID.randomUUID();
|
||||
public Map<Byte, Boolean> insert(final UUID accountIdentifier, final Map<Byte, Envelope> messagesByDeviceId) {
|
||||
return insertAsync(accountIdentifier, messagesByDeviceId).join();
|
||||
}
|
||||
|
||||
final boolean destinationPresent = messagesCache.insert(messageGuid, destinationUuid, destinationDeviceId, message);
|
||||
private CompletableFuture<Map<Byte, Boolean>> insertAsync(final UUID accountIdentifier, final Map<Byte, Envelope> messagesByDeviceId) {
|
||||
final Map<Byte, Boolean> devicePresenceById = new ConcurrentHashMap<>();
|
||||
|
||||
if (message.hasSourceServiceId() && !destinationUuid.toString().equals(message.getSourceServiceId())) {
|
||||
reportMessageManager.store(message.getSourceServiceId(), messageGuid);
|
||||
}
|
||||
return CompletableFuture.allOf(messagesByDeviceId.entrySet().stream()
|
||||
.map(deviceIdAndMessage -> {
|
||||
final byte deviceId = deviceIdAndMessage.getKey();
|
||||
final Envelope message = deviceIdAndMessage.getValue();
|
||||
final UUID messageGuid = UUID.randomUUID();
|
||||
|
||||
return destinationPresent;
|
||||
return messagesCache.insert(messageGuid, accountIdentifier, deviceId, message)
|
||||
.thenAccept(present -> {
|
||||
if (message.hasSourceServiceId() && !accountIdentifier.toString()
|
||||
.equals(message.getSourceServiceId())) {
|
||||
// Note that this is an asynchronous, best-effort, fire-and-forget operation
|
||||
reportMessageManager.store(message.getSourceServiceId(), messageGuid);
|
||||
}
|
||||
|
||||
devicePresenceById.put(deviceId, present);
|
||||
});
|
||||
})
|
||||
.toArray(CompletableFuture[]::new))
|
||||
.thenApply(ignored -> devicePresenceById);
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts messages into the message queues for devices associated with the identified accounts.
|
||||
*
|
||||
* @param multiRecipientMessage the multi-recipient message to insert into destination queues
|
||||
* @param resolvedRecipients a map of multi-recipient message {@code Recipient} entities to their corresponding
|
||||
* Signal accounts; messages will not be delivered to unresolved recipients
|
||||
* @param clientTimestamp the timestamp for the message as reported by the sending party
|
||||
* @param isStory {@code true} if the given message is a story or {@code false} otherwise
|
||||
* @param isEphemeral {@code true} if the given message should only be delivered to devices with active
|
||||
* connections to a Signal server or {@code false} otherwise
|
||||
* @param isUrgent {@code true} if the given message is urgent or {@code false} otherwise
|
||||
*
|
||||
* @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
|
||||
*/
|
||||
public CompletableFuture<Map<Account, Map<Byte, Boolean>>> insertMultiRecipientMessage(
|
||||
final SealedSenderMultiRecipientMessage multiRecipientMessage,
|
||||
final Map<SealedSenderMultiRecipientMessage.Recipient, Account> resolvedRecipients,
|
||||
final long clientTimestamp,
|
||||
final boolean isStory,
|
||||
final boolean isEphemeral,
|
||||
final boolean isUrgent) {
|
||||
|
||||
final long serverTimestamp = clock.millis();
|
||||
|
||||
return insertSharedMultiRecipientMessagePayload(multiRecipientMessage)
|
||||
.thenCompose(sharedMrmKey -> {
|
||||
final Envelope prototypeMessage = Envelope.newBuilder()
|
||||
.setType(Envelope.Type.UNIDENTIFIED_SENDER)
|
||||
.setClientTimestamp(clientTimestamp == 0 ? serverTimestamp : clientTimestamp)
|
||||
.setServerTimestamp(serverTimestamp)
|
||||
.setStory(isStory)
|
||||
.setEphemeral(isEphemeral)
|
||||
.setUrgent(isUrgent)
|
||||
.setSharedMrmKey(ByteString.copyFrom(sharedMrmKey))
|
||||
.build();
|
||||
|
||||
final Map<Account, Map<Byte, Boolean>> clientPresenceByAccountAndDevice = new ConcurrentHashMap<>();
|
||||
|
||||
return CompletableFuture.allOf(multiRecipientMessage.getRecipients().entrySet().stream()
|
||||
.filter(serviceIdAndRecipient -> resolvedRecipients.containsKey(serviceIdAndRecipient.getValue()))
|
||||
.map(serviceIdAndRecipient -> {
|
||||
final ServiceIdentifier serviceIdentifier = ServiceIdentifier.fromLibsignal(serviceIdAndRecipient.getKey());
|
||||
final SealedSenderMultiRecipientMessage.Recipient recipient = serviceIdAndRecipient.getValue();
|
||||
final byte[] devices = recipient.getDevices();
|
||||
|
||||
return insertAsync(resolvedRecipients.get(recipient).getIdentifier(IdentityType.ACI),
|
||||
IntStream.range(0, devices.length).mapToObj(i -> devices[i])
|
||||
.collect(Collectors.toMap(deviceId -> deviceId, deviceId -> prototypeMessage.toBuilder()
|
||||
.setDestinationServiceId(serviceIdentifier.toServiceIdentifierString())
|
||||
.build())))
|
||||
.thenAccept(clientPresenceByDeviceId ->
|
||||
clientPresenceByAccountAndDevice.put(resolvedRecipients.get(recipient),
|
||||
clientPresenceByDeviceId));
|
||||
})
|
||||
.toArray(CompletableFuture[]::new))
|
||||
.thenApply(ignored -> clientPresenceByAccountAndDevice);
|
||||
});
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> mayHavePersistedMessages(final UUID destinationUuid, final Device destinationDevice) {
|
||||
@@ -181,11 +267,7 @@ public class MessagesManager {
|
||||
final Device destinationDevice,
|
||||
final List<Envelope> messages) {
|
||||
|
||||
final List<Envelope> nonEphemeralMessages = messages.stream()
|
||||
.filter(envelope -> !envelope.getEphemeral())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
messagesDynamoDb.store(nonEphemeralMessages, destinationUuid, destinationDevice);
|
||||
messagesDynamoDb.store(messages, destinationUuid, destinationDevice);
|
||||
|
||||
final List<UUID> messageGuids = messages.stream().map(message -> UUID.fromString(message.getServerGuid()))
|
||||
.collect(Collectors.toList());
|
||||
@@ -193,7 +275,7 @@ public class MessagesManager {
|
||||
try {
|
||||
messagesRemovedFromCache = messagesCache.remove(destinationUuid, destinationDevice.getId(), messageGuids)
|
||||
.get(30, TimeUnit.SECONDS).size();
|
||||
PERSIST_MESSAGE_COUNTER.increment(nonEphemeralMessages.size());
|
||||
PERSIST_MESSAGE_COUNTER.increment(messages.size());
|
||||
|
||||
} catch (InterruptedException | ExecutionException | TimeoutException e) {
|
||||
logger.warn("Failed to remove messages from cache", e);
|
||||
@@ -217,7 +299,7 @@ public class MessagesManager {
|
||||
* @return a key where the shared data is stored
|
||||
* @see MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript
|
||||
*/
|
||||
public byte[] insertSharedMultiRecipientMessagePayload(
|
||||
private CompletableFuture<byte[]> insertSharedMultiRecipientMessagePayload(
|
||||
final SealedSenderMultiRecipientMessage sealedSenderMultiRecipientMessage) {
|
||||
return messagesCache.insertSharedMultiRecipientMessagePayload(sealedSenderMultiRecipientMessage);
|
||||
}
|
||||
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import org.whispersystems.textsecuregcm.util.NoStackTraceRuntimeException;
|
||||
|
||||
class MrmDataMissingException extends NoStackTraceRuntimeException {
|
||||
|
||||
enum Type {
|
||||
SHARED,
|
||||
RECIPIENT_VIEW
|
||||
}
|
||||
|
||||
private final Type type;
|
||||
|
||||
MrmDataMissingException(final Type type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
Type getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "MrmDataMissingException{type=%s}".formatted(type);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.lettuce.core.SetArgs;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
/**
|
||||
* Timers for operations that may span machines or requests and require a persistently stored timer start itme
|
||||
*/
|
||||
public class PersistentTimer {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(PersistentTimer.class);
|
||||
|
||||
private static String TIMER_NAMESPACE = "persistent_timer";
|
||||
@VisibleForTesting
|
||||
static final Duration TIMER_TTL = Duration.ofHours(1);
|
||||
|
||||
private final FaultTolerantRedisClusterClient redisClient;
|
||||
private final Clock clock;
|
||||
|
||||
|
||||
public PersistentTimer(final FaultTolerantRedisClusterClient redisClient, final Clock clock) {
|
||||
this.redisClient = redisClient;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
public class Sample {
|
||||
|
||||
private final Instant start;
|
||||
private final String redisKey;
|
||||
|
||||
public Sample(final Instant start, final String redisKey) {
|
||||
this.start = start;
|
||||
this.redisKey = redisKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop the timer, recording the duration between now and the first call to start. This deletes the persistent timer.
|
||||
*
|
||||
* @param timer The micrometer timer to record the duration to
|
||||
* @return A future that completes when the resources associated with the persistent timer have been destroyed
|
||||
*/
|
||||
public CompletableFuture<Void> stop(Timer timer) {
|
||||
Duration duration = Duration.between(start, clock.instant());
|
||||
timer.record(duration);
|
||||
return redisClient.withCluster(connection -> connection.async().del(redisKey))
|
||||
.toCompletableFuture()
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the timer if a timer with the provided namespaced key has not already been started, otherwise return the
|
||||
* existing sample.
|
||||
*
|
||||
* @param namespace A namespace prefix to use for the timer
|
||||
* @param key The unique key within the namespace that identifies the timer
|
||||
* @return A future that completes with a {@link Sample} that can later be used to record the final duration.
|
||||
*/
|
||||
public CompletableFuture<Sample> start(final String namespace, final String key) {
|
||||
final Instant now = clock.instant();
|
||||
final String redisKey = redisKey(namespace, key);
|
||||
|
||||
return redisClient.withCluster(connection ->
|
||||
connection.async().setGet(redisKey, String.valueOf(now.getEpochSecond()), SetArgs.Builder.nx().ex(TIMER_TTL)))
|
||||
.toCompletableFuture()
|
||||
.thenApply(serialized -> new Sample(parseStoredTimestamp(serialized).orElse(now), redisKey));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
String redisKey(final String namespace, final String key) {
|
||||
return String.format("%s::%s::%s", TIMER_NAMESPACE, namespace, key);
|
||||
}
|
||||
|
||||
private static Optional<Instant> parseStoredTimestamp(final @Nullable String serialized) {
|
||||
return Optional
|
||||
.ofNullable(serialized)
|
||||
.flatMap(s -> {
|
||||
try {
|
||||
return Optional.of(Long.parseLong(s));
|
||||
} catch (NumberFormatException e) {
|
||||
logger.warn("Failed to parse stored timestamp {}", s, e);
|
||||
return Optional.empty();
|
||||
}
|
||||
})
|
||||
.map(Instant::ofEpochSecond);
|
||||
}
|
||||
|
||||
}
|
||||
+14
-4
@@ -3,6 +3,8 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteItemResponse;
|
||||
@@ -11,6 +13,7 @@ import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
@@ -20,6 +23,7 @@ public class ReportMessageDynamoDb {
|
||||
static final String ATTR_TTL = "E";
|
||||
|
||||
private final DynamoDbClient db;
|
||||
private final DynamoDbAsyncClient dynamoDbAsyncClient;
|
||||
private final String tableName;
|
||||
private final Duration ttl;
|
||||
|
||||
@@ -30,20 +34,26 @@ public class ReportMessageDynamoDb {
|
||||
.distributionStatisticExpiry(Duration.ofDays(1))
|
||||
.register(Metrics.globalRegistry);
|
||||
|
||||
public ReportMessageDynamoDb(final DynamoDbClient dynamoDB, final String tableName, final Duration ttl) {
|
||||
public ReportMessageDynamoDb(final DynamoDbClient dynamoDB,
|
||||
final DynamoDbAsyncClient dynamoDbAsyncClient,
|
||||
final String tableName,
|
||||
final Duration ttl) {
|
||||
|
||||
this.db = dynamoDB;
|
||||
this.dynamoDbAsyncClient = dynamoDbAsyncClient;
|
||||
this.tableName = tableName;
|
||||
this.ttl = ttl;
|
||||
}
|
||||
|
||||
public void store(byte[] hash) {
|
||||
db.putItem(PutItemRequest.builder()
|
||||
public CompletableFuture<Void> store(byte[] hash) {
|
||||
return dynamoDbAsyncClient.putItem(PutItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.item(Map.of(
|
||||
KEY_HASH, AttributeValues.fromByteArray(hash),
|
||||
ATTR_TTL, AttributeValues.fromLong(Instant.now().plus(ttl).getEpochSecond())
|
||||
))
|
||||
.build());
|
||||
.build())
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
|
||||
public boolean remove(byte[] hash) {
|
||||
|
||||
+1
-4
@@ -54,11 +54,8 @@ public class ReportMessageManager {
|
||||
}
|
||||
|
||||
public void store(String sourceAci, UUID messageGuid) {
|
||||
|
||||
try {
|
||||
Objects.requireNonNull(sourceAci);
|
||||
|
||||
reportMessageDynamoDb.store(hash(messageGuid, sourceAci));
|
||||
reportMessageDynamoDb.store(hash(messageGuid, Objects.requireNonNull(sourceAci)));
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Failed to store hash", e);
|
||||
}
|
||||
|
||||
+6
-4
@@ -22,13 +22,15 @@ public class DestinationDeviceValidator {
|
||||
/**
|
||||
* @see #validateRegistrationIds(Account, Stream, boolean)
|
||||
*/
|
||||
public static <T> void validateRegistrationIds(final Account account, final Collection<T> messages,
|
||||
Function<T, Byte> getDeviceId, Function<T, Integer> getRegistrationId, boolean usePhoneNumberIdentity)
|
||||
throws StaleDevicesException {
|
||||
public static <T> void validateRegistrationIds(final Account account,
|
||||
final Collection<T> messages,
|
||||
Function<T, Byte> getDeviceId,
|
||||
Function<T, Integer> getRegistrationId,
|
||||
boolean usePhoneNumberIdentity) throws StaleDevicesException {
|
||||
|
||||
validateRegistrationIds(account,
|
||||
messages.stream().map(m -> new Pair<>(getDeviceId.apply(m), getRegistrationId.apply(m))),
|
||||
usePhoneNumberIdentity);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+1
-1
@@ -49,7 +49,7 @@ public class WebSocketAccountAuthenticator implements WebSocketAuthenticator<Aut
|
||||
return CREDENTIALS_NOT_PRESENTED;
|
||||
}
|
||||
return basicCredentialsFromAuthHeader(authHeader)
|
||||
.flatMap(credentials -> accountAuthenticator.authenticate(credentials))
|
||||
.flatMap(accountAuthenticator::authenticate)
|
||||
.map(authenticatedAccount -> ReusableAuth.authenticated(authenticatedAccount, this.principalSupplier))
|
||||
.orElse(INVALID_CREDENTIALS_PRESENTED);
|
||||
}
|
||||
|
||||
+2
-2
@@ -217,13 +217,13 @@ record CommandDependencies(
|
||||
MessagesCache messagesCache = new MessagesCache(messagesCluster,
|
||||
messageDeliveryScheduler, messageDeletionExecutor, Clock.systemUTC());
|
||||
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster);
|
||||
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbClient,
|
||||
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getReportMessage().getTableName(),
|
||||
configuration.getReportMessageConfiguration().getReportTtl());
|
||||
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster,
|
||||
configuration.getReportMessageConfiguration().getCounterTtl());
|
||||
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache,
|
||||
reportMessageManager, messageDeletionExecutor);
|
||||
reportMessageManager, messageDeletionExecutor, Clock.systemUTC());
|
||||
AccountLockManager accountLockManager = new AccountLockManager(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getDeletedAccountsLock().getTableName());
|
||||
ClientPublicKeysManager clientPublicKeysManager =
|
||||
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/**
|
||||
* Checks if a device may benefit from receiving a push notification
|
||||
*/
|
||||
public class IdleWakeupEligibilityChecker {
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration MIN_SHORT_IDLE_DURATION = Duration.ofDays(3);
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration MAX_SHORT_IDLE_DURATION = Duration.ofDays(30);
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration MIN_LONG_IDLE_DURATION = Duration.ofDays(60);
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration MAX_LONG_IDLE_DURATION = Duration.ofDays(75);
|
||||
|
||||
private final MessagesManager messagesManager;
|
||||
private final Clock clock;
|
||||
|
||||
public IdleWakeupEligibilityChecker(final Clock clock, final MessagesManager messagesManager) {
|
||||
this.messagesManager = messagesManager;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether the device may benefit from a push notification.
|
||||
*
|
||||
* @param account The account to check
|
||||
* @param device The device to check
|
||||
* @return true if the device may benefit from a push notification, otherwise false
|
||||
* @implNote There are two populations that may benefit from a wakeup:
|
||||
* <ol>
|
||||
* <li> Devices that have only been idle for a little while, but have messages that they don't seem to be retrieving
|
||||
* <li> Devices that have been idle for a long time, but don't have any messages
|
||||
* </ol>
|
||||
* We think the first group sometimes just needs a little nudge to wake up and get their messages, and the latter
|
||||
* group generally WOULD get their messages if they had any. We want to notify the first group to prompt them to
|
||||
* actually get their messages and the latter group to prevent them from getting deleted due to inactivity (since they
|
||||
* are otherwise healthy installations that just aren't getting much traffic).
|
||||
*/
|
||||
public CompletableFuture<Boolean> isDeviceEligible(final Account account, final Device device) {
|
||||
|
||||
if (!hasPushToken(device)) {
|
||||
return CompletableFuture.completedFuture(false);
|
||||
}
|
||||
|
||||
if (isShortIdle(device, clock)) {
|
||||
return messagesManager.mayHaveUrgentPersistedMessages(account.getIdentifier(IdentityType.ACI), device);
|
||||
} else if (isLongIdle(device, clock)) {
|
||||
return messagesManager.mayHavePersistedMessages(account.getIdentifier(IdentityType.ACI), device)
|
||||
.thenApply(mayHavePersistedMessages -> !mayHavePersistedMessages);
|
||||
} else {
|
||||
return CompletableFuture.completedFuture(false);
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static boolean isShortIdle(final Device device, final Clock clock) {
|
||||
final Duration idleDuration = Duration.between(Instant.ofEpochMilli(device.getLastSeen()), clock.instant());
|
||||
|
||||
return idleDuration.compareTo(MIN_SHORT_IDLE_DURATION) >= 0 && idleDuration.compareTo(MAX_SHORT_IDLE_DURATION) < 0;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static boolean isLongIdle(final Device device, final Clock clock) {
|
||||
final Duration idleDuration = Duration.between(Instant.ofEpochMilli(device.getLastSeen()), clock.instant());
|
||||
|
||||
return idleDuration.compareTo(MIN_LONG_IDLE_DURATION) >= 0 && idleDuration.compareTo(MAX_LONG_IDLE_DURATION) < 0;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static boolean hasPushToken(final Device device) {
|
||||
return !StringUtils.isAllBlank(device.getApnId(), device.getGcmId());
|
||||
}
|
||||
|
||||
}
|
||||
+5
-65
@@ -4,7 +4,6 @@ import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.DynamoDbTables;
|
||||
@@ -18,8 +17,6 @@ import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.util.function.Tuples;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalTime;
|
||||
|
||||
public class NotifyIdleDevicesCommand extends AbstractSinglePassCrawlAccountsCommand {
|
||||
@@ -35,18 +32,6 @@ public class NotifyIdleDevicesCommand extends AbstractSinglePassCrawlAccountsCom
|
||||
@VisibleForTesting
|
||||
static final LocalTime PREFERRED_NOTIFICATION_TIME = LocalTime.of(14, 0);
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration MIN_SHORT_IDLE_DURATION = Duration.ofDays(3);
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration MAX_SHORT_IDLE_DURATION = Duration.ofDays(30);
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration MIN_LONG_IDLE_DURATION = Duration.ofDays(60);
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration MAX_LONG_IDLE_DURATION = Duration.ofDays(75);
|
||||
|
||||
private static final Counter DEVICE_INSPECTED_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(NotifyIdleDevicesCommand.class, "deviceInspected"));
|
||||
|
||||
@@ -87,12 +72,15 @@ public class NotifyIdleDevicesCommand extends AbstractSinglePassCrawlAccountsCom
|
||||
final MessagesManager messagesManager = getCommandDependencies().messagesManager();
|
||||
final IdleDeviceNotificationScheduler idleDeviceNotificationScheduler = buildIdleDeviceNotificationScheduler();
|
||||
final Clock clock = getClock();
|
||||
final IdleWakeupEligibilityChecker idleWakeupEligibilityChecker = new IdleWakeupEligibilityChecker(clock, messagesManager);
|
||||
|
||||
accounts
|
||||
.flatMap(account -> Flux.fromIterable(account.getDevices()).map(device -> Tuples.of(account, device)))
|
||||
.doOnNext(ignored -> DEVICE_INSPECTED_COUNTER.increment())
|
||||
.flatMap(accountAndDevice -> isDeviceEligible(accountAndDevice.getT1(), accountAndDevice.getT2(), messagesManager, clock)
|
||||
.mapNotNull(eligible -> eligible ? accountAndDevice : null), maxConcurrency)
|
||||
.flatMap(accountAndDevice -> Mono.fromFuture(() ->
|
||||
idleWakeupEligibilityChecker.isDeviceEligible(accountAndDevice.getT1(), accountAndDevice.getT2()))
|
||||
.mapNotNull(eligible -> eligible ? accountAndDevice : null),
|
||||
maxConcurrency)
|
||||
.flatMap(accountAndDevice -> {
|
||||
final Account account = accountAndDevice.getT1();
|
||||
final Device device = accountAndDevice.getT2();
|
||||
@@ -136,52 +124,4 @@ public class NotifyIdleDevicesCommand extends AbstractSinglePassCrawlAccountsCom
|
||||
Clock.systemUTC());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static Mono<Boolean> isDeviceEligible(final Account account,
|
||||
final Device device,
|
||||
final MessagesManager messagesManager,
|
||||
final Clock clock) {
|
||||
|
||||
// There are two populations of interest for this crawler:
|
||||
//
|
||||
// 1. Devices that have only been idle for a little while, but have messages that they don't seem to be retrieving
|
||||
// 2. Devices that have been idle for a long time, but don't have any messages
|
||||
//
|
||||
// We think the first group sometimes just needs a little nudge to wake up and get their messages, and the latter
|
||||
// group generally WOULD get their messages if they had any. We want to notify the first group to prompt them to
|
||||
// actually get their messages and the latter group to prevent them from getting deleted due to inactivity (since
|
||||
// they are otherwise healthy installations that just aren't getting much traffic).
|
||||
|
||||
if (!hasPushToken(device)) {
|
||||
return Mono.just(false);
|
||||
}
|
||||
|
||||
if (isShortIdle(device, clock)) {
|
||||
return Mono.fromFuture(messagesManager.mayHaveUrgentPersistedMessages(account.getIdentifier(IdentityType.ACI), device));
|
||||
} else if (isLongIdle(device, clock)) {
|
||||
return Mono.fromFuture(messagesManager.mayHavePersistedMessages(account.getIdentifier(IdentityType.ACI), device))
|
||||
.map(mayHavePersistedMessages -> !mayHavePersistedMessages);
|
||||
} else {
|
||||
return Mono.just(false);
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static boolean isShortIdle(final Device device, final Clock clock) {
|
||||
final Duration idleDuration = Duration.between(Instant.ofEpochMilli(device.getLastSeen()), clock.instant());
|
||||
|
||||
return idleDuration.compareTo(MIN_SHORT_IDLE_DURATION) >= 0 && idleDuration.compareTo(MAX_SHORT_IDLE_DURATION) < 0;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static boolean isLongIdle(final Device device, final Clock clock) {
|
||||
final Duration idleDuration = Duration.between(Instant.ofEpochMilli(device.getLastSeen()), clock.instant());
|
||||
|
||||
return idleDuration.compareTo(MIN_LONG_IDLE_DURATION) >= 0 && idleDuration.compareTo(MAX_LONG_IDLE_DURATION) < 0;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static boolean hasPushToken(final Device device) {
|
||||
return !StringUtils.isAllBlank(device.getApnId(), device.getGcmId());
|
||||
}
|
||||
}
|
||||
@@ -265,13 +265,9 @@ message SearchProof {
|
||||
|
||||
message UpdateValue {
|
||||
/**
|
||||
* TODO: Update KT server to remove this field since it's only relevant to third-party management and we're not doing that.
|
||||
* The new mapped value for an identifier or the "distinguished" key.
|
||||
*/
|
||||
// optional bytes signature = 1;
|
||||
/**
|
||||
* The new value for a identifier.
|
||||
*/
|
||||
bytes value = 2;
|
||||
bytes value = 1;
|
||||
}
|
||||
|
||||
message PrefixSearchResult {
|
||||
|
||||
@@ -55,6 +55,9 @@ service Backups {
|
||||
* After successful redemption, subsequent requests to
|
||||
* GetBackupAuthCredentials will return credentials with the level on the
|
||||
* provided receipt until the expiration time on the receipt.
|
||||
*
|
||||
* errors:
|
||||
* ABORTED: The target account does not have a backup-id commitment
|
||||
*/
|
||||
rpc RedeemReceipt(RedeemReceiptRequest) returns (RedeemReceiptResponse) {}
|
||||
|
||||
|
||||
+32
-44
@@ -1,46 +1,34 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIEMjCCAxqgAwIBAgIBATANBgkqhkiG9w0BAQUFADB7MQswCQYDVQQGEwJHQjEb
|
||||
MBkGA1UECAwSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHDAdTYWxmb3JkMRow
|
||||
GAYDVQQKDBFDb21vZG8gQ0EgTGltaXRlZDEhMB8GA1UEAwwYQUFBIENlcnRpZmlj
|
||||
YXRlIFNlcnZpY2VzMB4XDTA0MDEwMTAwMDAwMFoXDTI4MTIzMTIzNTk1OVowezEL
|
||||
MAkGA1UEBhMCR0IxGzAZBgNVBAgMEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UE
|
||||
BwwHU2FsZm9yZDEaMBgGA1UECgwRQ29tb2RvIENBIExpbWl0ZWQxITAfBgNVBAMM
|
||||
GEFBQSBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczCCASIwDQYJKoZIhvcNAQEBBQADggEP
|
||||
ADCCAQoCggEBAL5AnfRu4ep2hxxNRUSOvkbIgwadwSr+GB+O5AL686tdUIoWMQua
|
||||
BtDFcCLNSS1UY8y2bmhGC1Pqy0wkwLxyTurxFa70VJoSCsN6sjNg4tqJVfMiWPPe
|
||||
3M/vg4aijJRPn2jymJBGhCfHdr/jzDUsi14HZGWCwEiwqJH5YZ92IFCokcdmtet4
|
||||
YgNW8IoaE+oxox6gmf049vYnMlhvB/VruPsUK6+3qszWY19zjNoFmag4qMsXeDZR
|
||||
rOme9Hg6jc8P2ULimAyrL58OAd7vn5lJ8S3frHRNG5i1R8XlKdH5kBjHYpy+g8cm
|
||||
ez6KJcfA3Z3mNWgQIJ2P2N7Sw4ScDV7oL8kCAwEAAaOBwDCBvTAdBgNVHQ4EFgQU
|
||||
oBEKIz6W8Qfs4q8p74Klf9AwpLQwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQF
|
||||
MAMBAf8wewYDVR0fBHQwcjA4oDagNIYyaHR0cDovL2NybC5jb21vZG9jYS5jb20v
|
||||
QUFBQ2VydGlmaWNhdGVTZXJ2aWNlcy5jcmwwNqA0oDKGMGh0dHA6Ly9jcmwuY29t
|
||||
b2RvLm5ldC9BQUFDZXJ0aWZpY2F0ZVNlcnZpY2VzLmNybDANBgkqhkiG9w0BAQUF
|
||||
AAOCAQEACFb8AvCb6P+k+tZ7xkSAzk/ExfYAWMymtrwUSWgEdujm7l3sAg9g1o1Q
|
||||
GE8mTgHj5rCl7r+8dFRBv/38ErjHT1r0iWAFf2C3BUrz9vHCv8S5dIa2LX1rzNLz
|
||||
Rt0vxuBqw8M0Ayx9lt1awg6nCpnBBYurDC/zXDrPbDdVCYfeU0BsWO/8tqtlbgT2
|
||||
G9w84FoVxp7Z8VlIMCFlA2zs6SFz7JsDoeA3raAVGI/6ugLOpyypEBMs1OUIJqsi
|
||||
l2D4kF501KKaU73yqWjgom7C12yxow+ev+to51byrvLjKzg6CYG1a4XXvi3tPxq3
|
||||
smPi9WIsgtRqAEFQ8TmDn5XpNpaYbg==
|
||||
-----END CERTIFICATE-----
|
||||
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDVDCCAjygAwIBAgIDAjRWMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT
|
||||
MRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9i
|
||||
YWwgQ0EwHhcNMDIwNTIxMDQwMDAwWhcNMjIwNTIxMDQwMDAwWjBCMQswCQYDVQQG
|
||||
EwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEbMBkGA1UEAxMSR2VvVHJ1c3Qg
|
||||
R2xvYmFsIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2swYYzD9
|
||||
9BcjGlZ+W988bDjkcbd4kdS8odhM+KhDtgPpTSEHCIjaWC9mOSm9BXiLnTjoBbdq
|
||||
fnGk5sRgprDvgOSJKA+eJdbtg/OtppHHmMlCGDUUna2YRpIuT8rxh0PBFpVXLVDv
|
||||
iS2Aelet8u5fa9IAjbkU+BQVNdnARqN7csiRv8lVK83Qlz6cJmTM386DGXHKTubU
|
||||
1XupGc1V3sjs0l44U+VcT4wt/lAjNvxm5suOpDkZALeVAjmRCw7+OC7RHQWa9k0+
|
||||
bw8HHa8sHo9gOeL6NlMTOdReJivbPagUvTLrGAMoUgRx5aszPeE4uwc2hGKceeoW
|
||||
MPRfwCvocWvk+QIDAQABo1MwUTAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBTA
|
||||
ephojYn7qwVkDBF9qn1luMrMTjAfBgNVHSMEGDAWgBTAephojYn7qwVkDBF9qn1l
|
||||
uMrMTjANBgkqhkiG9w0BAQUFAAOCAQEANeMpauUvXVSOKVCUn5kaFOSPeCpilKIn
|
||||
Z57QzxpeR+nBsqTP3UEaBU6bS+5Kb1VSsyShNwrrZHYqLizz/Tt1kL/6cdjHPTfS
|
||||
tQWVYrmm3ok9Nns4d0iXrKYgjy6myQzCsplFAMfOEVEiIuCl6rYVSAlk6l5PdPcF
|
||||
PseKUgzbFbS9bZvlxrFUaKnjaZC2mqUPuLk/IH2uSrW4nOQdtqvmlKXBx4Ot2/Un
|
||||
hw4EbNX/3aBd7YdStysVAq45pmp06drE57xNNB6pXE0zX5IJL4hmXXeXxx12E6nV
|
||||
5fEWCRE11azbJHFwLJhWC9kXtNHjUStedejV0NxPNO3CBWaAocvmMw==
|
||||
MIIF3jCCA8agAwIBAgIQAf1tMPyjylGoG7xkDjUDLTANBgkqhkiG9w0BAQwFADCB
|
||||
iDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0pl
|
||||
cnNleSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNV
|
||||
BAMTJVVTRVJUcnVzdCBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAw
|
||||
MjAxMDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBiDELMAkGA1UEBhMCVVMxEzARBgNV
|
||||
BAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQKExVU
|
||||
aGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMTJVVTRVJUcnVzdCBSU0EgQ2Vy
|
||||
dGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIK
|
||||
AoICAQCAEmUXNg7D2wiz0KxXDXbtzSfTTK1Qg2HiqiBNCS1kCdzOiZ/MPans9s/B
|
||||
3PHTsdZ7NygRK0faOca8Ohm0X6a9fZ2jY0K2dvKpOyuR+OJv0OwWIJAJPuLodMkY
|
||||
tJHUYmTbf6MG8YgYapAiPLz+E/CHFHv25B+O1ORRxhFnRghRy4YUVD+8M/5+bJz/
|
||||
Fp0YvVGONaanZshyZ9shZrHUm3gDwFA66Mzw3LyeTP6vBZY1H1dat//O+T23LLb2
|
||||
VN3I5xI6Ta5MirdcmrS3ID3KfyI0rn47aGYBROcBTkZTmzNg95S+UzeQc0PzMsNT
|
||||
79uq/nROacdrjGCT3sTHDN/hMq7MkztReJVni+49Vv4M0GkPGw/zJSZrM233bkf6
|
||||
c0Plfg6lZrEpfDKEY1WJxA3Bk1QwGROs0303p+tdOmw1XNtB1xLaqUkL39iAigmT
|
||||
Yo61Zs8liM2EuLE/pDkP2QKe6xJMlXzzawWpXhaDzLhn4ugTncxbgtNMs+1b/97l
|
||||
c6wjOy0AvzVVdAlJ2ElYGn+SNuZRkg7zJn0cTRe8yexDJtC/QV9AqURE9JnnV4ee
|
||||
UB9XVKg+/XRjL7FQZQnmWEIuQxpMtPAlR1n6BB6T1CZGSlCBst6+eLf8ZxXhyVeE
|
||||
Hg9j1uliutZfVS7qXMYoCAQlObgOK6nyTJccBz8NUvXt7y+CDwIDAQABo0IwQDAd
|
||||
BgNVHQ4EFgQUU3m/WqorSs9UgOHYm8Cd8rIDZsswDgYDVR0PAQH/BAQDAgEGMA8G
|
||||
A1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAFzUfA3P9wF9QZllDHPF
|
||||
Up/L+M+ZBn8b2kMVn54CVVeWFPFSPCeHlCjtHzoBN6J2/FNQwISbxmtOuowhT6KO
|
||||
VWKR82kV2LyI48SqC/3vqOlLVSoGIG1VeCkZ7l8wXEskEVX/JJpuXior7gtNn3/3
|
||||
ATiUFJVDBwn7YKnuHKsSjKCaXqeYalltiz8I+8jRRa8YFWSQEg9zKC7F4iRO/Fjs
|
||||
8PRF/iKz6y+O0tlFYQXBl2+odnKPi4w2r78NBc5xjeambx9spnFixdjQg3IM8WcR
|
||||
iQycE0xyNN+81XHfqnHd4blsjDwSXWXavVcStkNr/+XeTWYRUc+ZruwXtuhxkYze
|
||||
Sf7dNXGiFSeUHM9h4ya7b6NnJSFd5t0dCy5oGzuCr+yDZ4XUmFF0sbmZgIn/f3gZ
|
||||
XHlKYC6SQK5MNyosycdiyA5d9zZbyuAlJQG03RoHnHcAP9Dc1ew91Pq7P8yF1m9/
|
||||
qS3fuQL39ZeatTXaw2ewh0qpKJ4jjv9cJ2vhsE/zB+4ALtRZh8tSQZXq9EfX7mRB
|
||||
VXyNWQKV3WKdwrnuWih0hKWbt5DHDAff9Yk2dDLWKMGwsAvgnEzDHNb842m1R0aB
|
||||
L6KCq9NjRHDEjf8tM7qtj3u1cIiuPhnPQCjY/MiQu12ZIvVS5ljFH4gxQ+6IHdfG
|
||||
jjxDah2nGN59PRbxYvnKkKj9
|
||||
-----END CERTIFICATE-----
|
||||
+19
-11
@@ -17,11 +17,12 @@ import jakarta.ws.rs.core.Response;
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.eclipse.jetty.util.component.LifeCycle;
|
||||
import org.eclipse.jetty.websocket.api.Session;
|
||||
import org.eclipse.jetty.websocket.api.StatusCode;
|
||||
import org.eclipse.jetty.websocket.client.WebSocketClient;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.whispersystems.textsecuregcm.metrics.NoopAwsSdkMetricPublisher;
|
||||
@@ -47,27 +48,22 @@ class WhisperServerServiceTest {
|
||||
Resources.getResource("config/test-secrets-bundle.yml").getPath());
|
||||
}
|
||||
|
||||
private static final WebSocketClient webSocketClient = new WebSocketClient();
|
||||
|
||||
private static final DropwizardAppExtension<WhisperServerConfiguration> EXTENSION = new DropwizardAppExtension<>(
|
||||
WhisperServerService.class, Resources.getResource("config/test.yml").getPath());
|
||||
|
||||
private WebSocketClient webSocketClient;
|
||||
|
||||
@AfterAll
|
||||
static void teardown() {
|
||||
System.clearProperty("secrets.bundle.filename");
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
webSocketClient = new WebSocketClient();
|
||||
@BeforeAll
|
||||
static void setUp() throws Exception {
|
||||
webSocketClient.start();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
webSocketClient.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
void start() throws Exception {
|
||||
// make sure the service nominally starts and responds to health checks
|
||||
@@ -96,6 +92,16 @@ class WhisperServerServiceTest {
|
||||
|
||||
final TestWebsocketListener testWebsocketListener = new TestWebsocketListener();
|
||||
|
||||
EXTENSION.getTestSupport().getEnvironment().getApplicationContext().getServer()
|
||||
.addEventListener(new LifeCycle.Listener() {
|
||||
@Override
|
||||
public void lifeCycleStopped(final LifeCycle event) {
|
||||
// closed by org.eclipse.jetty.websocket.common.SessionTracker during the container Lifecycle stopping phase
|
||||
assertEquals(StatusCode.SHUTDOWN, testWebsocketListener.closeFuture().getNow(-1));
|
||||
}
|
||||
});
|
||||
|
||||
// Session is Closeable, but we intentionally keep it open so that we can confirm the container Lifecycle behavior
|
||||
final Session session = webSocketClient.connect(testWebsocketListener,
|
||||
URI.create(String.format("ws://localhost:%d/v1/websocket/", EXTENSION.getLocalPort())))
|
||||
.join();
|
||||
@@ -112,6 +118,8 @@ class WhisperServerServiceTest {
|
||||
assertEquals(401, whoami.getStatus());
|
||||
final long whoamiTimestamp = Long.parseLong(whoami.getHeaders().get(HeaderUtils.TIMESTAMP_HEADER.toLowerCase()));
|
||||
assertTrue(whoamiTimestamp >= start);
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import javax.annotation.Nullable;
|
||||
import org.eclipse.jetty.websocket.server.JettyServerUpgradeRequest;
|
||||
import org.eclipse.jetty.websocket.server.JettyServerUpgradeResponse;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
import org.whispersystems.websocket.ReusableAuth;
|
||||
import org.whispersystems.websocket.auth.PrincipalSupplier;
|
||||
|
||||
class IdlePrimaryDeviceAuthenticatedWebSocketUpgradeFilterTest {
|
||||
|
||||
private IdlePrimaryDeviceAuthenticatedWebSocketUpgradeFilter filter;
|
||||
|
||||
private static final Duration MIN_IDLE_DURATION = Duration.ofDays(30);
|
||||
private static final TestClock CLOCK = TestClock.pinned(Instant.now());
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
filter = new IdlePrimaryDeviceAuthenticatedWebSocketUpgradeFilter(MIN_IDLE_DURATION, CLOCK);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void handleAuthentication(@Nullable final AuthenticatedDevice authenticatedDevice, final boolean expectAlertHeader) {
|
||||
final ReusableAuth<AuthenticatedDevice> reusableAuth = authenticatedDevice != null
|
||||
? ReusableAuth.authenticated(authenticatedDevice, PrincipalSupplier.forImmutablePrincipal())
|
||||
: ReusableAuth.anonymous();
|
||||
|
||||
final JettyServerUpgradeResponse response = mock(JettyServerUpgradeResponse.class);
|
||||
|
||||
filter.handleAuthentication(reusableAuth, mock(JettyServerUpgradeRequest.class), response);
|
||||
|
||||
if (expectAlertHeader) {
|
||||
verify(response).addHeader(IdlePrimaryDeviceAuthenticatedWebSocketUpgradeFilter.ALERT_HEADER,
|
||||
IdlePrimaryDeviceAuthenticatedWebSocketUpgradeFilter.IDLE_PRIMARY_DEVICE_ALERT);
|
||||
} else {
|
||||
verifyNoInteractions(response);
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Arguments> handleAuthentication() {
|
||||
final Device activePrimaryDevice = mock(Device.class);
|
||||
when(activePrimaryDevice.isPrimary()).thenReturn(true);
|
||||
when(activePrimaryDevice.getLastSeen()).thenReturn(CLOCK.millis());
|
||||
|
||||
final Device idlePrimaryDevice = mock(Device.class);
|
||||
when(idlePrimaryDevice.isPrimary()).thenReturn(true);
|
||||
when(idlePrimaryDevice.getLastSeen())
|
||||
.thenReturn(CLOCK.instant().minus(MIN_IDLE_DURATION).minusSeconds(1).toEpochMilli());
|
||||
|
||||
final Device linkedDevice = mock(Device.class);
|
||||
when(linkedDevice.isPrimary()).thenReturn(false);
|
||||
|
||||
final Account accountWithActivePrimaryDevice = mock(Account.class);
|
||||
when(accountWithActivePrimaryDevice.getPrimaryDevice()).thenReturn(activePrimaryDevice);
|
||||
|
||||
final Account accountWithIdlePrimaryDevice = mock(Account.class);
|
||||
when(accountWithIdlePrimaryDevice.getPrimaryDevice()).thenReturn(idlePrimaryDevice);
|
||||
|
||||
return List.of(
|
||||
Arguments.argumentSet("Anonymous",
|
||||
null,
|
||||
false),
|
||||
|
||||
Arguments.argumentSet("Authenticated as active primary device",
|
||||
new AuthenticatedDevice(accountWithActivePrimaryDevice, activePrimaryDevice),
|
||||
false),
|
||||
|
||||
Arguments.argumentSet("Authenticated as idle primary device",
|
||||
new AuthenticatedDevice(accountWithIdlePrimaryDevice, idlePrimaryDevice),
|
||||
false),
|
||||
|
||||
Arguments.argumentSet("Authenticated as linked device with active primary device",
|
||||
new AuthenticatedDevice(accountWithActivePrimaryDevice, linkedDevice),
|
||||
false),
|
||||
|
||||
Arguments.argumentSet("Authenticated as linked device with idle primary device",
|
||||
new AuthenticatedDevice(accountWithIdlePrimaryDevice, linkedDevice),
|
||||
true)
|
||||
);
|
||||
}
|
||||
}
|
||||
+126
-45
@@ -85,10 +85,14 @@ public class BackupAuthManagerTest {
|
||||
reset(redeemedReceiptsManager);
|
||||
}
|
||||
|
||||
BackupAuthManager create(@Nullable BackupLevel backupLevel, boolean rateLimit) {
|
||||
BackupAuthManager create(@Nullable BackupLevel backupLevel) {
|
||||
return create(backupLevel, rateLimiter(aci, false, false));
|
||||
}
|
||||
|
||||
BackupAuthManager create(@Nullable BackupLevel backupLevel, RateLimiters rateLimiters) {
|
||||
return new BackupAuthManager(
|
||||
ExperimentHelper.withEnrollment(experimentName(backupLevel), aci),
|
||||
rateLimit ? denyRateLimiter(aci) : allowRateLimiter(),
|
||||
rateLimiters,
|
||||
accountsManager,
|
||||
new ServerZkReceiptOperations(receiptParams),
|
||||
redeemedReceiptsManager,
|
||||
@@ -98,7 +102,7 @@ public class BackupAuthManagerTest {
|
||||
|
||||
@Test
|
||||
void commitBackupId() {
|
||||
final BackupAuthManager authManager = create(BackupLevel.FREE, false);
|
||||
final BackupAuthManager authManager = create(BackupLevel.FREE);
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getUuid()).thenReturn(aci);
|
||||
@@ -124,7 +128,7 @@ public class BackupAuthManagerTest {
|
||||
@EnumSource
|
||||
@NullSource
|
||||
void commitRequiresBackupLevel(final BackupLevel backupLevel) {
|
||||
final BackupAuthManager authManager = create(backupLevel, false);
|
||||
final BackupAuthManager authManager = create(backupLevel);
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getUuid()).thenReturn(aci);
|
||||
when(accountsManager.updateAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(account));
|
||||
@@ -147,7 +151,7 @@ public class BackupAuthManagerTest {
|
||||
void getBackupAuthCredentials(@CartesianTest.Enum final BackupLevel backupLevel,
|
||||
@CartesianTest.Enum final BackupCredentialType credentialType) {
|
||||
|
||||
final BackupAuthManager authManager = create(backupLevel, false);
|
||||
final BackupAuthManager authManager = create(backupLevel);
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getUuid()).thenReturn(aci);
|
||||
@@ -166,7 +170,7 @@ public class BackupAuthManagerTest {
|
||||
@ParameterizedTest
|
||||
@EnumSource
|
||||
void getBackupAuthCredentialsNoBackupLevel(final BackupCredentialType credentialType) {
|
||||
final BackupAuthManager authManager = create(null, false);
|
||||
final BackupAuthManager authManager = create(null);
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getUuid()).thenReturn(aci);
|
||||
@@ -187,7 +191,7 @@ public class BackupAuthManagerTest {
|
||||
@CartesianTest
|
||||
void getReceiptCredentials(@CartesianTest.Enum final BackupLevel backupLevel,
|
||||
@CartesianTest.Enum final BackupCredentialType credentialType) throws VerificationFailedException {
|
||||
final BackupAuthManager authManager = create(backupLevel, false);
|
||||
final BackupAuthManager authManager = create(backupLevel);
|
||||
|
||||
final byte[] backupKey = switch (credentialType) {
|
||||
case MESSAGES -> messagesBackupKey;
|
||||
@@ -244,7 +248,7 @@ public class BackupAuthManagerTest {
|
||||
@MethodSource
|
||||
void invalidCredentialTimeWindows(final Instant requestRedemptionStart, final Instant requestRedemptionEnd,
|
||||
final Instant now) {
|
||||
final BackupAuthManager authManager = create(BackupLevel.FREE, false);
|
||||
final BackupAuthManager authManager = create(BackupLevel.FREE);
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getUuid()).thenReturn(aci);
|
||||
@@ -268,7 +272,7 @@ public class BackupAuthManagerTest {
|
||||
final Instant day4 = Instant.EPOCH.plus(Duration.ofDays(4));
|
||||
final Instant dayMax = day0.plus(BackupAuthManager.MAX_REDEMPTION_DURATION);
|
||||
|
||||
final BackupAuthManager authManager = create(BackupLevel.FREE, false);
|
||||
final BackupAuthManager authManager = create(BackupLevel.FREE);
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getUuid()).thenReturn(aci);
|
||||
@@ -301,7 +305,7 @@ public class BackupAuthManagerTest {
|
||||
final Instant day2 = Instant.EPOCH.plus(Duration.ofDays(2));
|
||||
final Instant day3 = Instant.EPOCH.plus(Duration.ofDays(3));
|
||||
|
||||
final BackupAuthManager authManager = create(BackupLevel.FREE, false);
|
||||
final BackupAuthManager authManager = create(BackupLevel.FREE);
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getUuid()).thenReturn(aci);
|
||||
when(account.getBackupVoucher()).thenReturn(new Account.BackupVoucher(3, day1));
|
||||
@@ -341,9 +345,10 @@ public class BackupAuthManagerTest {
|
||||
@Test
|
||||
void redeemReceipt() throws InvalidInputException, VerificationFailedException {
|
||||
final Instant expirationTime = Instant.EPOCH.plus(Duration.ofDays(1));
|
||||
final BackupAuthManager authManager = create(BackupLevel.FREE, false);
|
||||
final BackupAuthManager authManager = create(BackupLevel.FREE);
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getUuid()).thenReturn(aci);
|
||||
when(account.getBackupCredentialRequest(BackupCredentialType.MEDIA)).thenReturn(Optional.of(new byte[0]));
|
||||
|
||||
clock.pin(Instant.EPOCH.plus(Duration.ofDays(1)));
|
||||
when(accountsManager.updateAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(account));
|
||||
@@ -353,14 +358,33 @@ public class BackupAuthManagerTest {
|
||||
verify(accountsManager, times(1)).updateAsync(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void redeemReceiptNoBackupRequest() {
|
||||
final Instant expirationTime = Instant.EPOCH.plus(Duration.ofDays(1));
|
||||
final BackupAuthManager authManager = create(BackupLevel.FREE);
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getUuid()).thenReturn(aci);
|
||||
when(account.getBackupCredentialRequest(BackupCredentialType.MEDIA)).thenReturn(Optional.empty());
|
||||
|
||||
clock.pin(Instant.EPOCH.plus(Duration.ofDays(1)));
|
||||
when(redeemedReceiptsManager.put(any(), eq(expirationTime.getEpochSecond()), eq(201L), eq(aci)))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
assertThatExceptionOfType(StatusRuntimeException.class)
|
||||
.isThrownBy(() ->
|
||||
authManager.redeemReceipt(account, receiptPresentation(201, expirationTime)).join())
|
||||
.extracting(ex -> ex.getStatus().getCode())
|
||||
.isEqualTo(Status.Code.ABORTED);
|
||||
}
|
||||
|
||||
@Test
|
||||
void mergeRedemptions() throws InvalidInputException, VerificationFailedException {
|
||||
final Instant newExpirationTime = Instant.EPOCH.plus(Duration.ofDays(1));
|
||||
final Instant existingExpirationTime = Instant.EPOCH.plus(Duration.ofDays(1)).plus(Duration.ofSeconds(1));
|
||||
|
||||
final BackupAuthManager authManager = create(BackupLevel.FREE, false);
|
||||
final BackupAuthManager authManager = create(BackupLevel.FREE);
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getUuid()).thenReturn(aci);
|
||||
when(account.getBackupCredentialRequest(BackupCredentialType.MEDIA)).thenReturn(Optional.of(new byte[0]));
|
||||
|
||||
// The account has an existing voucher with a later expiration date
|
||||
when(account.getBackupVoucher()).thenReturn(new Account.BackupVoucher(201, existingExpirationTime));
|
||||
@@ -383,7 +407,7 @@ public class BackupAuthManagerTest {
|
||||
void redeemExpiredReceipt() {
|
||||
final Instant expirationTime = Instant.EPOCH.plus(Duration.ofDays(1));
|
||||
clock.pin(expirationTime.plus(Duration.ofSeconds(1)));
|
||||
final BackupAuthManager authManager = create(BackupLevel.FREE, false);
|
||||
final BackupAuthManager authManager = create(BackupLevel.FREE);
|
||||
assertThatExceptionOfType(StatusRuntimeException.class)
|
||||
.isThrownBy(() -> authManager.redeemReceipt(mock(Account.class), receiptPresentation(3, expirationTime)).join())
|
||||
.extracting(ex -> ex.getStatus().getCode())
|
||||
@@ -397,7 +421,7 @@ public class BackupAuthManagerTest {
|
||||
void redeemInvalidLevel(long level) {
|
||||
final Instant expirationTime = Instant.EPOCH.plus(Duration.ofDays(1));
|
||||
clock.pin(expirationTime.plus(Duration.ofSeconds(1)));
|
||||
final BackupAuthManager authManager = create(BackupLevel.FREE, false);
|
||||
final BackupAuthManager authManager = create(BackupLevel.FREE);
|
||||
assertThatExceptionOfType(StatusRuntimeException.class)
|
||||
.isThrownBy(() ->
|
||||
authManager.redeemReceipt(mock(Account.class), receiptPresentation(level, expirationTime)).join())
|
||||
@@ -409,7 +433,7 @@ public class BackupAuthManagerTest {
|
||||
|
||||
@Test
|
||||
void redeemInvalidPresentation() throws InvalidInputException, VerificationFailedException {
|
||||
final BackupAuthManager authManager = create(BackupLevel.FREE, false);
|
||||
final BackupAuthManager authManager = create(BackupLevel.FREE);
|
||||
final ReceiptCredentialPresentation invalid = receiptPresentation(ServerSecretParams.generate(), 3L, Instant.EPOCH);
|
||||
assertThatExceptionOfType(StatusRuntimeException.class)
|
||||
.isThrownBy(() -> authManager.redeemReceipt(mock(Account.class), invalid).join())
|
||||
@@ -422,9 +446,10 @@ public class BackupAuthManagerTest {
|
||||
@Test
|
||||
void receiptAlreadyRedeemed() throws InvalidInputException, VerificationFailedException {
|
||||
final Instant expirationTime = Instant.EPOCH.plus(Duration.ofDays(1));
|
||||
final BackupAuthManager authManager = create(BackupLevel.FREE, false);
|
||||
final BackupAuthManager authManager = create(BackupLevel.FREE);
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getUuid()).thenReturn(aci);
|
||||
when(account.getBackupCredentialRequest(BackupCredentialType.MEDIA)).thenReturn(Optional.of(new byte[0]));
|
||||
|
||||
clock.pin(Instant.EPOCH.plus(Duration.ofDays(1)));
|
||||
when(accountsManager.updateAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(account));
|
||||
@@ -459,30 +484,85 @@ public class BackupAuthManagerTest {
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void testRateLimits() {
|
||||
final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
final BackupAuthManager authManager = create(BackupLevel.FREE, true);
|
||||
@CartesianTest
|
||||
void testChangeIdRateLimits(
|
||||
@CartesianTest.Values(booleans = {true, false}) boolean changeMessage,
|
||||
@CartesianTest.Values(booleans = {true, false}) boolean changeMedia,
|
||||
@CartesianTest.Values(booleans = {true, false}) boolean rateLimitBackupId) {
|
||||
|
||||
final BackupAuthCredentialRequest messagesCredential = backupAuthTestUtil.getRequest(messagesBackupKey, aci);
|
||||
final BackupAuthCredentialRequest mediaCredential = backupAuthTestUtil.getRequest(mediaBackupKey, aci);
|
||||
final BackupAuthManager authManager = create(BackupLevel.FREE, rateLimiter(aci, rateLimitBackupId, false));
|
||||
final BackupAuthCredentialRequest storedMessagesCredential = backupAuthTestUtil.getRequest(messagesBackupKey, aci);
|
||||
final BackupAuthCredentialRequest storedMediaCredential = backupAuthTestUtil.getRequest(mediaBackupKey, aci);
|
||||
final Account account = mockAccount(storedMessagesCredential, storedMediaCredential, null);
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getUuid()).thenReturn(aci);
|
||||
when(accountsManager.updateAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(account));
|
||||
final BackupAuthCredentialRequest newMessagesCredential = changeMessage
|
||||
? backupAuthTestUtil.getRequest(TestRandomUtil.nextBytes(32), aci)
|
||||
: storedMessagesCredential;
|
||||
|
||||
// Should be rate limited
|
||||
CompletableFutureTestUtil.assertFailsWithCause(RateLimitExceededException.class,
|
||||
authManager.commitBackupId(account, messagesCredential, mediaCredential));
|
||||
final BackupAuthCredentialRequest newMediaCredential = changeMedia
|
||||
? backupAuthTestUtil.getRequest(TestRandomUtil.nextBytes(32), aci)
|
||||
: storedMediaCredential;
|
||||
|
||||
// If we don't change the request, shouldn't be rate limited
|
||||
when(account.getBackupCredentialRequest(BackupCredentialType.MESSAGES))
|
||||
.thenReturn(Optional.of(backupAuthTestUtil.getRequest(messagesBackupKey, aci).serialize()));
|
||||
when(account.getBackupCredentialRequest(BackupCredentialType.MEDIA))
|
||||
.thenReturn(Optional.of(backupAuthTestUtil.getRequest(mediaBackupKey, aci).serialize()));
|
||||
assertDoesNotThrow(() -> authManager.commitBackupId(account, messagesCredential, mediaCredential).join());
|
||||
final boolean expectRateLimit = (changeMedia || changeMessage) && rateLimitBackupId;
|
||||
final CompletableFuture<Void> future = authManager.commitBackupId(account, newMessagesCredential, newMediaCredential);
|
||||
if (expectRateLimit) {
|
||||
CompletableFutureTestUtil.assertFailsWithCause(RateLimitExceededException.class, future);
|
||||
} else {
|
||||
assertDoesNotThrow(() -> future.join());
|
||||
}
|
||||
}
|
||||
|
||||
@CartesianTest
|
||||
void testChangePaidMediaIdRateLimits(
|
||||
@CartesianTest.Values(booleans = {true, false}) boolean changeMessage,
|
||||
@CartesianTest.Values(booleans = {true, false}) boolean changeMedia,
|
||||
@CartesianTest.Values(booleans = {true, false}) boolean paid,
|
||||
@CartesianTest.Values(booleans = {true, false}) boolean rateLimitPaidMedia) {
|
||||
|
||||
final BackupAuthManager authManager = create(BackupLevel.FREE, rateLimiter(aci, false, rateLimitPaidMedia));
|
||||
final BackupAuthCredentialRequest storedMessagesCredential = backupAuthTestUtil.getRequest(messagesBackupKey, aci);
|
||||
final BackupAuthCredentialRequest storedMediaCredential = backupAuthTestUtil.getRequest(mediaBackupKey, aci);
|
||||
// Set clock before the voucher expires if paid, otherwise after
|
||||
final Account.BackupVoucher backupVoucher = new Account.BackupVoucher(1, Instant.ofEpochSecond(100));
|
||||
clock.pin(paid ? Instant.ofEpochSecond(99) : Instant.ofEpochSecond(101));
|
||||
|
||||
final Account account = mockAccount(storedMessagesCredential, storedMediaCredential, backupVoucher);
|
||||
|
||||
final BackupAuthCredentialRequest newMessagesCredential = changeMessage
|
||||
? backupAuthTestUtil.getRequest(TestRandomUtil.nextBytes(32), aci)
|
||||
: storedMessagesCredential;
|
||||
|
||||
final BackupAuthCredentialRequest newMediaCredential = changeMedia
|
||||
? backupAuthTestUtil.getRequest(TestRandomUtil.nextBytes(32), aci)
|
||||
: storedMediaCredential;
|
||||
|
||||
// We should get rate limited iff we are out of paid media changes and we changed the media backup-id
|
||||
final boolean expectRateLimit = changeMedia && paid && rateLimitPaidMedia;
|
||||
final CompletableFuture<Void> future = authManager.commitBackupId(account, newMessagesCredential, newMediaCredential);
|
||||
if (expectRateLimit) {
|
||||
CompletableFutureTestUtil.assertFailsWithCause(RateLimitExceededException.class, future);
|
||||
} else {
|
||||
assertDoesNotThrow(() -> future.join());
|
||||
}
|
||||
}
|
||||
|
||||
private Account mockAccount(final BackupAuthCredentialRequest storedMessagesCredential, final BackupAuthCredentialRequest storedMediaCredential, Account.BackupVoucher backupVoucher) {
|
||||
final Account account = mock(Account.class);
|
||||
when(accountsManager.updateAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(account));
|
||||
if (storedMessagesCredential != null) {
|
||||
when(account.getBackupCredentialRequest(BackupCredentialType.MESSAGES))
|
||||
.thenReturn(Optional.of(storedMessagesCredential.serialize()));
|
||||
}
|
||||
if (storedMediaCredential != null) {
|
||||
when(account.getBackupCredentialRequest(BackupCredentialType.MEDIA))
|
||||
.thenReturn(Optional.of(storedMediaCredential.serialize()));
|
||||
}
|
||||
when(account.getUuid()).thenReturn(aci);
|
||||
when(account.getBackupVoucher()).thenReturn(backupVoucher);
|
||||
return account;
|
||||
}
|
||||
|
||||
|
||||
private static String experimentName(@Nullable BackupLevel backupLevel) {
|
||||
return switch (backupLevel) {
|
||||
case FREE -> BackupAuthManager.BACKUP_EXPERIMENT_NAME;
|
||||
@@ -491,20 +571,21 @@ public class BackupAuthManagerTest {
|
||||
};
|
||||
}
|
||||
|
||||
private static RateLimiters allowRateLimiter() {
|
||||
private static RateLimiters rateLimiter(final UUID aci, boolean rateLimitBackupId,
|
||||
boolean rateLimitPaidMediaBackupId) {
|
||||
final RateLimiters limiters = mock(RateLimiters.class);
|
||||
final RateLimiter limiter = mock(RateLimiter.class);
|
||||
when(limiter.validateAsync(any(UUID.class))).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(limiters.forDescriptor(RateLimiters.For.SET_BACKUP_ID)).thenReturn(limiter);
|
||||
return limiters;
|
||||
}
|
||||
|
||||
private static RateLimiters denyRateLimiter(final UUID aci) {
|
||||
final RateLimiters limiters = mock(RateLimiters.class);
|
||||
final RateLimiter limiter = mock(RateLimiter.class);
|
||||
when(limiter.validateAsync(aci))
|
||||
final RateLimiter allowLimiter = mock(RateLimiter.class);
|
||||
when(allowLimiter.validateAsync(aci)).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final RateLimiter denyLimiter = mock(RateLimiter.class);
|
||||
when(denyLimiter.validateAsync(aci))
|
||||
.thenReturn(CompletableFuture.failedFuture(new RateLimitExceededException(null)));
|
||||
when(limiters.forDescriptor(RateLimiters.For.SET_BACKUP_ID)).thenReturn(limiter);
|
||||
|
||||
when(limiters.forDescriptor(RateLimiters.For.SET_BACKUP_ID))
|
||||
.thenReturn(rateLimitBackupId ? denyLimiter : allowLimiter);
|
||||
when(limiters.forDescriptor(RateLimiters.For.SET_PAID_MEDIA_BACKUP_ID))
|
||||
.thenReturn(rateLimitPaidMediaBackupId ? denyLimiter : allowLimiter);
|
||||
return limiters;
|
||||
}
|
||||
}
|
||||
-181
@@ -1,181 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013 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.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.reset;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import io.dropwizard.auth.AuthValueFactoryProvider;
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import io.dropwizard.testing.junit5.ResourceExtension;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.CloudflareTurnCredentialsManager;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnToken;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
|
||||
import org.whispersystems.textsecuregcm.calls.routing.TurnCallRouter;
|
||||
import org.whispersystems.textsecuregcm.calls.routing.TurnServerOptions;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.TestRemoteAddressFilterProvider;
|
||||
|
||||
@ExtendWith(DropwizardExtensionsSupport.class)
|
||||
class CallRoutingControllerTest {
|
||||
|
||||
private static final String GET_CALL_ENDPOINTS_PATH = "v1/calling/relays";
|
||||
private static final String REMOTE_ADDRESS = "123.123.123.1";
|
||||
|
||||
private static final RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
private static final RateLimiter getCallEndpointLimiter = mock(RateLimiter.class);
|
||||
private static final ExperimentEnrollmentManager experimentEnrollmentManager = mock(
|
||||
ExperimentEnrollmentManager.class);
|
||||
private static final TurnTokenGenerator turnTokenGenerator =
|
||||
new TurnTokenGenerator("bloop".getBytes(StandardCharsets.UTF_8));
|
||||
private static final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager = mock(
|
||||
CloudflareTurnCredentialsManager.class);
|
||||
|
||||
private static final TurnCallRouter turnCallRouter = mock(TurnCallRouter.class);
|
||||
|
||||
private static final ResourceExtension resources = ResourceExtension.builder()
|
||||
.addProvider(AuthHelper.getAuthFilter())
|
||||
.addProvider(new AuthValueFactoryProvider.Binder<>(AuthenticatedDevice.class))
|
||||
.addProvider(new RateLimitExceededExceptionMapper())
|
||||
.addProvider(new TestRemoteAddressFilterProvider(REMOTE_ADDRESS))
|
||||
.setMapper(SystemMapper.jsonMapper())
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addResource(new CallRoutingController(rateLimiters, turnCallRouter, turnTokenGenerator,
|
||||
experimentEnrollmentManager, cloudflareTurnCredentialsManager))
|
||||
.build();
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
when(rateLimiters.getCallEndpointLimiter()).thenReturn(getCallEndpointLimiter);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
reset(experimentEnrollmentManager, rateLimiters, getCallEndpointLimiter, turnCallRouter);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetTurnEndpointsSuccess() throws UnknownHostException {
|
||||
TurnServerOptions options = new TurnServerOptions(
|
||||
"example.domain.org",
|
||||
Optional.of(List.of("stun:12.34.56.78")),
|
||||
Optional.of(List.of("stun:example.domain.org"))
|
||||
);
|
||||
|
||||
when(turnCallRouter.getRoutingFor(
|
||||
eq(AuthHelper.VALID_UUID),
|
||||
eq(Optional.of(InetAddress.getByName(REMOTE_ADDRESS))),
|
||||
anyInt())
|
||||
).thenReturn(options);
|
||||
try (Response response = resources.getJerseyTest()
|
||||
.target(GET_CALL_ENDPOINTS_PATH)
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get()) {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
TurnToken token = response.readEntity(TurnToken.class);
|
||||
assertThat(token.username()).isNotEmpty();
|
||||
assertThat(token.password()).isNotEmpty();
|
||||
assertThat(token.hostname()).isEqualTo(options.hostname());
|
||||
assertThat(token.urlsWithIps()).isEqualTo(options.urlsWithIps().get());
|
||||
assertThat(token.urls()).isEqualTo(options.urlsWithHostname().get());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetTurnEndpointsCloudflare() throws IOException {
|
||||
when(experimentEnrollmentManager.isEnrolled(AuthHelper.VALID_NUMBER, AuthHelper.VALID_UUID, "cloudflareTurn"))
|
||||
.thenReturn(true);
|
||||
|
||||
when(cloudflareTurnCredentialsManager.retrieveFromCloudflare()).thenReturn(new TurnToken("ABC", "XYZ",
|
||||
List.of("turn:cloudflare.example.com:3478?transport=udp"), Collections.emptyList(),
|
||||
"cf.example.com"));
|
||||
|
||||
try (Response response = resources.getJerseyTest()
|
||||
.target(GET_CALL_ENDPOINTS_PATH)
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get()) {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
TurnToken token = response.readEntity(TurnToken.class);
|
||||
assertThat(token.username()).isEqualTo("ABC");
|
||||
assertThat(token.password()).isEqualTo("XYZ");
|
||||
assertThat(token.hostname()).isEqualTo("cf.example.com");
|
||||
assertThat(token.urlsWithIps()).isEmpty();
|
||||
assertThat(token.urls()).isEqualTo(List.of("turn:cloudflare.example.com:3478?transport=udp"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetTurnEndpointsInvalidIpSuccess() throws UnknownHostException {
|
||||
TurnServerOptions options = new TurnServerOptions(
|
||||
"example.domain.org",
|
||||
Optional.of(List.of()),
|
||||
Optional.of(List.of("stun:example.domain.org"))
|
||||
);
|
||||
|
||||
when(turnCallRouter.getRoutingFor(
|
||||
eq(AuthHelper.VALID_UUID),
|
||||
eq(Optional.of(InetAddress.getByName(REMOTE_ADDRESS))),
|
||||
anyInt())
|
||||
).thenReturn(options);
|
||||
try (Response response = resources.getJerseyTest()
|
||||
.target(GET_CALL_ENDPOINTS_PATH)
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get()) {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
TurnToken token = response.readEntity(TurnToken.class);
|
||||
assertThat(token.username()).isNotEmpty();
|
||||
assertThat(token.password()).isNotEmpty();
|
||||
assertThat(token.hostname()).isEqualTo(options.hostname());
|
||||
assertThat(token.urlsWithIps()).isEqualTo(options.urlsWithIps().get());
|
||||
assertThat(token.urls()).isEqualTo(options.urlsWithHostname().get());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetTurnEndpointRateLimited() throws RateLimitExceededException {
|
||||
doThrow(new RateLimitExceededException(null))
|
||||
.when(getCallEndpointLimiter).validate(AuthHelper.VALID_UUID);
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target(GET_CALL_ENDPOINTS_PATH)
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get()) {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(429);
|
||||
}
|
||||
}
|
||||
}
|
||||
+6
-107
@@ -6,8 +6,6 @@
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.reset;
|
||||
@@ -18,11 +16,7 @@ import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import io.dropwizard.testing.junit5.ResourceExtension;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -31,10 +25,6 @@ import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.CloudflareTurnCredentialsManager;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnToken;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
|
||||
import org.whispersystems.textsecuregcm.calls.routing.TurnCallRouter;
|
||||
import org.whispersystems.textsecuregcm.calls.routing.TurnServerOptions;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
@@ -47,11 +37,6 @@ class CallRoutingControllerV2Test {
|
||||
|
||||
private static final String GET_CALL_RELAYS_PATH = "v2/calling/relays";
|
||||
private static final String REMOTE_ADDRESS = "123.123.123.1";
|
||||
private static final TurnServerOptions TURN_SERVER_OPTIONS = new TurnServerOptions(
|
||||
"example.domain.org",
|
||||
Optional.of(List.of("stun:12.34.56.78")),
|
||||
Optional.of(List.of("stun:example.domain.org"))
|
||||
);
|
||||
private static final TurnToken CLOUDFLARE_TURN_TOKEN = new TurnToken(
|
||||
"ABC",
|
||||
"XYZ",
|
||||
@@ -61,12 +46,8 @@ class CallRoutingControllerV2Test {
|
||||
|
||||
private static final RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
private static final RateLimiter getCallEndpointLimiter = mock(RateLimiter.class);
|
||||
private static final ExperimentEnrollmentManager experimentEnrollmentManager = mock(
|
||||
ExperimentEnrollmentManager.class);
|
||||
private static final TurnTokenGenerator turnTokenGenerator = new TurnTokenGenerator("bloop".getBytes(StandardCharsets.UTF_8));
|
||||
private static final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager = mock(
|
||||
CloudflareTurnCredentialsManager.class);
|
||||
private static final TurnCallRouter turnCallRouter = mock(TurnCallRouter.class);
|
||||
|
||||
private static final ResourceExtension resources = ResourceExtension.builder()
|
||||
.addProvider(AuthHelper.getAuthFilter())
|
||||
@@ -75,8 +56,7 @@ class CallRoutingControllerV2Test {
|
||||
.addProvider(new TestRemoteAddressFilterProvider(REMOTE_ADDRESS))
|
||||
.setMapper(SystemMapper.jsonMapper())
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addResource(new CallRoutingControllerV2(rateLimiters, turnCallRouter, turnTokenGenerator,
|
||||
experimentEnrollmentManager, cloudflareTurnCredentialsManager))
|
||||
.addResource(new CallRoutingControllerV2(rateLimiters, cloudflareTurnCredentialsManager))
|
||||
.build();
|
||||
|
||||
@BeforeEach
|
||||
@@ -86,58 +66,19 @@ class CallRoutingControllerV2Test {
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
reset(experimentEnrollmentManager, rateLimiters, getCallEndpointLimiter, turnCallRouter);
|
||||
reset( rateLimiters, getCallEndpointLimiter);
|
||||
}
|
||||
|
||||
void initializeMocksWith(Optional<TurnServerOptions> signalTurn, Optional<TurnToken> cloudflare) {
|
||||
signalTurn.ifPresent(options -> {
|
||||
void initializeMocksWith(TurnToken cloudflareToken) {
|
||||
try {
|
||||
when(turnCallRouter.getRoutingFor(
|
||||
eq(AuthHelper.VALID_UUID),
|
||||
eq(Optional.of(InetAddress.getByName(REMOTE_ADDRESS))))
|
||||
).thenReturn(options);
|
||||
} catch (UnknownHostException ignored) {
|
||||
}
|
||||
});
|
||||
cloudflare.ifPresent(token -> {
|
||||
when(experimentEnrollmentManager.isEnrolled(AuthHelper.VALID_NUMBER, AuthHelper.VALID_UUID, "cloudflareTurn"))
|
||||
.thenReturn(true);
|
||||
try {
|
||||
when(cloudflareTurnCredentialsManager.retrieveFromCloudflare()).thenReturn(token);
|
||||
when(cloudflareTurnCredentialsManager.retrieveFromCloudflare()).thenReturn(cloudflareToken);
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRelaysSignalRoutingOnly() {
|
||||
TurnServerOptions options = TURN_SERVER_OPTIONS;
|
||||
initializeMocksWith(Optional.of(options), Optional.empty());
|
||||
|
||||
try (Response rawResponse = resources.getJerseyTest()
|
||||
.target(GET_CALL_RELAYS_PATH)
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get()) {
|
||||
|
||||
assertThat(rawResponse.getStatus()).isEqualTo(200);
|
||||
|
||||
CallRoutingControllerV2.GetCallingRelaysResponse response = rawResponse.readEntity(
|
||||
CallRoutingControllerV2.GetCallingRelaysResponse.class);
|
||||
List<TurnToken> relays = response.relays();
|
||||
assertThat(relays).hasSize(1);
|
||||
assertThat(relays.getFirst().username()).isNotEmpty();
|
||||
assertThat(relays.getFirst().password()).isNotEmpty();
|
||||
assertThat(relays.getFirst().hostname()).isEqualTo(options.hostname());
|
||||
assertThat(relays.getFirst().urlsWithIps()).isEqualTo(options.urlsWithIps().get());
|
||||
assertThat(relays.getFirst().urls()).isEqualTo(options.urlsWithHostname().get());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRelaysBothRouting() {
|
||||
TurnServerOptions options = TURN_SERVER_OPTIONS;
|
||||
initializeMocksWith(Optional.of(options), Optional.of(CLOUDFLARE_TURN_TOKEN));
|
||||
initializeMocksWith(CLOUDFLARE_TURN_TOKEN);
|
||||
|
||||
try (Response rawResponse = resources.getJerseyTest()
|
||||
.target(GET_CALL_RELAYS_PATH)
|
||||
@@ -151,49 +92,7 @@ class CallRoutingControllerV2Test {
|
||||
CallRoutingControllerV2.GetCallingRelaysResponse.class);
|
||||
|
||||
List<TurnToken> relays = response.relays();
|
||||
assertThat(relays).hasSize(2);
|
||||
|
||||
assertThat(relays.getFirst()).isEqualTo(CLOUDFLARE_TURN_TOKEN);
|
||||
|
||||
TurnToken token = relays.get(1);
|
||||
assertThat(token.username()).isNotEmpty();
|
||||
assertThat(token.password()).isNotEmpty();
|
||||
assertThat(token.hostname()).isEqualTo(options.hostname());
|
||||
assertThat(token.urlsWithIps()).isEqualTo(options.urlsWithIps().get());
|
||||
assertThat(token.urls()).isEqualTo(options.urlsWithHostname().get());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRelaysInvalidIpSuccess() throws UnknownHostException {
|
||||
TurnServerOptions options = new TurnServerOptions(
|
||||
"example.domain.org",
|
||||
Optional.of(List.of()),
|
||||
Optional.of(List.of("stun:example.domain.org"))
|
||||
);
|
||||
|
||||
when(turnCallRouter.getRoutingFor(
|
||||
eq(AuthHelper.VALID_UUID),
|
||||
eq(Optional.of(InetAddress.getByName(REMOTE_ADDRESS))))
|
||||
).thenReturn(options);
|
||||
try (Response rawResponse = resources.getJerseyTest()
|
||||
.target(GET_CALL_RELAYS_PATH)
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get()) {
|
||||
|
||||
assertThat(rawResponse.getStatus()).isEqualTo(200);
|
||||
CallRoutingControllerV2.GetCallingRelaysResponse response = rawResponse.readEntity(
|
||||
CallRoutingControllerV2.GetCallingRelaysResponse.class
|
||||
);
|
||||
|
||||
assertThat(response.relays()).hasSize(1);
|
||||
TurnToken token = response.relays().getFirst();
|
||||
assertThat(token.username()).isNotEmpty();
|
||||
assertThat(token.password()).isNotEmpty();
|
||||
assertThat(token.hostname()).isEqualTo(options.hostname());
|
||||
assertThat(token.urlsWithIps()).isEqualTo(options.urlsWithIps().get());
|
||||
assertThat(token.urls()).isEqualTo(options.urlsWithHostname().get());
|
||||
assertThat(relays).isEqualTo(List.of(CLOUDFLARE_TURN_TOKEN));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+44
-7
@@ -12,7 +12,6 @@ import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyByte;
|
||||
import static org.mockito.Mockito.anyString;
|
||||
import static org.mockito.Mockito.clearInvocations;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
@@ -43,6 +42,7 @@ import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.glassfish.jersey.server.ServerProperties;
|
||||
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
@@ -52,6 +52,7 @@ import org.junit.jupiter.api.extension.ExtendWith;
|
||||
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.CsvSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.NullSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
@@ -90,6 +91,7 @@ import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceSpec;
|
||||
import org.whispersystems.textsecuregcm.storage.LinkDeviceTokenAlreadyUsedException;
|
||||
import org.whispersystems.textsecuregcm.storage.PersistentTimer;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
|
||||
@@ -104,6 +106,7 @@ class DeviceControllerTest {
|
||||
|
||||
private static final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
private static final ClientPublicKeysManager clientPublicKeysManager = mock(ClientPublicKeysManager.class);
|
||||
private static final PersistentTimer persistentTimer = mock(PersistentTimer.class);
|
||||
private static final RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
private static final RateLimiter rateLimiter = mock(RateLimiter.class);
|
||||
@SuppressWarnings("unchecked")
|
||||
@@ -123,6 +126,7 @@ class DeviceControllerTest {
|
||||
accountsManager,
|
||||
clientPublicKeysManager,
|
||||
rateLimiters,
|
||||
persistentTimer,
|
||||
deviceConfiguration);
|
||||
|
||||
@RegisterExtension
|
||||
@@ -161,6 +165,9 @@ class DeviceControllerTest {
|
||||
when(clientPublicKeysManager.setPublicKey(any(), anyByte(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
when(persistentTimer.start(anyString(), anyString()))
|
||||
.thenReturn(CompletableFuture.completedFuture(mock(PersistentTimer.Sample.class)));
|
||||
|
||||
AccountsHelper.setupMockUpdate(accountsManager);
|
||||
}
|
||||
|
||||
@@ -955,6 +962,8 @@ class DeviceControllerTest {
|
||||
.waitForNewLinkedDevice(eq(AuthHelper.VALID_UUID), eq(AuthHelper.VALID_DEVICE), eq(tokenIdentifier), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(deviceInfo)));
|
||||
|
||||
when(rateLimiter.validateAsync(AuthHelper.VALID_UUID)).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v1/devices/wait_for_linked_device/" + tokenIdentifier)
|
||||
.request()
|
||||
@@ -979,6 +988,8 @@ class DeviceControllerTest {
|
||||
.waitForNewLinkedDevice(eq(AuthHelper.VALID_UUID), eq(AuthHelper.VALID_DEVICE), eq(tokenIdentifier), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.empty()));
|
||||
|
||||
when(rateLimiter.validateAsync(AuthHelper.VALID_UUID)).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v1/devices/wait_for_linked_device/" + tokenIdentifier)
|
||||
.request()
|
||||
@@ -997,6 +1008,8 @@ class DeviceControllerTest {
|
||||
.waitForNewLinkedDevice(eq(AuthHelper.VALID_UUID), eq(AuthHelper.VALID_DEVICE), eq(tokenIdentifier), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(new IllegalArgumentException()));
|
||||
|
||||
when(rateLimiter.validateAsync(AuthHelper.VALID_UUID)).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v1/devices/wait_for_linked_device/" + tokenIdentifier)
|
||||
.request()
|
||||
@@ -1042,10 +1055,11 @@ class DeviceControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void waitForLinkedDeviceRateLimited() throws RateLimitExceededException {
|
||||
void waitForLinkedDeviceRateLimited() {
|
||||
final String tokenIdentifier = Base64.getUrlEncoder().withoutPadding().encodeToString(new byte[32]);
|
||||
|
||||
doThrow(new RateLimitExceededException(null)).when(rateLimiter).validate(AuthHelper.VALID_UUID);
|
||||
when(rateLimiter.validateAsync(AuthHelper.VALID_UUID))
|
||||
.thenReturn(CompletableFuture.failedFuture(new RateLimitExceededException(null)));
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v1/devices/wait_for_linked_device/" + tokenIdentifier)
|
||||
@@ -1255,7 +1269,7 @@ class DeviceControllerTest {
|
||||
void recordRestoreAccountRequest() {
|
||||
final String token = RandomStringUtils.secure().nextAlphanumeric(16);
|
||||
final RestoreAccountRequest restoreAccountRequest =
|
||||
new RestoreAccountRequest(RestoreAccountRequest.Method.LOCAL_BACKUP);
|
||||
new RestoreAccountRequest(RestoreAccountRequest.Method.LOCAL_BACKUP, null);
|
||||
|
||||
when(accountsManager.recordRestoreAccountRequest(token, restoreAccountRequest))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
@@ -1273,7 +1287,7 @@ class DeviceControllerTest {
|
||||
void recordRestoreAccountRequestBadToken() {
|
||||
final String token = RandomStringUtils.secure().nextAlphanumeric(128);
|
||||
final RestoreAccountRequest restoreAccountRequest =
|
||||
new RestoreAccountRequest(RestoreAccountRequest.Method.LOCAL_BACKUP);
|
||||
new RestoreAccountRequest(RestoreAccountRequest.Method.LOCAL_BACKUP, null);
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v1/devices/restore_account/" + token)
|
||||
@@ -1287,7 +1301,7 @@ class DeviceControllerTest {
|
||||
@Test
|
||||
void recordRestoreAccountRequestInvalidRequest() {
|
||||
final String token = RandomStringUtils.secure().nextAlphanumeric(16);
|
||||
final RestoreAccountRequest restoreAccountRequest = new RestoreAccountRequest(null);
|
||||
final RestoreAccountRequest restoreAccountRequest = new RestoreAccountRequest(null, null);
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v1/devices/restore_account/" + token)
|
||||
@@ -1298,11 +1312,34 @@ class DeviceControllerTest {
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"0, true",
|
||||
"4096, true",
|
||||
"4097, false"
|
||||
})
|
||||
void recordRestoreAccountRequestBootstrapLengthLimit(int bootstrapLength, boolean valid) {
|
||||
final String token = RandomStringUtils.secure().nextAlphanumeric(16);
|
||||
|
||||
final byte[] bootstrap = TestRandomUtil.nextBytes(bootstrapLength);
|
||||
final RestoreAccountRequest restoreAccountRequest = new RestoreAccountRequest(
|
||||
RestoreAccountRequest.Method.DEVICE_TRANSFER, bootstrap);
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v1/devices/restore_account/" + token)
|
||||
.request()
|
||||
.put(Entity.json(restoreAccountRequest))) {
|
||||
|
||||
assertEquals(valid ? 204 : 422, response.getStatus());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void waitForDeviceTransferRequest() {
|
||||
final String token = RandomStringUtils.secure().nextAlphanumeric(16);
|
||||
final RestoreAccountRequest restoreAccountRequest =
|
||||
new RestoreAccountRequest(RestoreAccountRequest.Method.LOCAL_BACKUP);
|
||||
new RestoreAccountRequest(RestoreAccountRequest.Method.LOCAL_BACKUP, null);
|
||||
|
||||
when(accountsManager.waitForRestoreAccountRequest(eq(token), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(restoreAccountRequest)));
|
||||
|
||||
+540
-775
File diff suppressed because it is too large.
Load diff
+33
@@ -50,6 +50,7 @@ import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.junitpioneer.jupiter.cartesian.ArgumentSets;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
@@ -59,6 +60,8 @@ import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockError;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountCreationResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ApnRegistrationId;
|
||||
import org.whispersystems.textsecuregcm.entities.DeviceActivationRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
@@ -748,6 +751,8 @@ class RegistrationControllerTest {
|
||||
|
||||
try (Response response = request.post(Entity.json(registrationRequest))) {
|
||||
assertEquals(200, response.getStatus());
|
||||
final AccountIdentityResponse identityResponse = response.readEntity(AccountIdentityResponse.class);
|
||||
assertEquals(accountIdentifier, identityResponse.uuid());
|
||||
}
|
||||
|
||||
verify(accountsManager).create(
|
||||
@@ -760,6 +765,34 @@ class RegistrationControllerTest {
|
||||
any());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void reregistrationFlag(final boolean existingAccount) throws InterruptedException {
|
||||
final RegistrationServiceSession registrationSession =
|
||||
new RegistrationServiceSession(new byte[16], NUMBER, true, null, null, null, SESSION_EXPIRATION_SECONDS);
|
||||
when(registrationServiceClient.getSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(registrationSession)));
|
||||
|
||||
final Optional<Account> maybeAccount = Optional.ofNullable(existingAccount ? mock(Account.class) : null);
|
||||
when(accountsManager.getByE164(any())).thenReturn(maybeAccount);
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getPrimaryDevice()).thenReturn(mock(Device.class));
|
||||
|
||||
when(accountsManager.create(any(), any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(account);
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/registration")
|
||||
.request()
|
||||
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD));
|
||||
try (Response response = request.post(Entity.json(requestJson("sessionId")))) {
|
||||
assertEquals(200, response.getStatus());
|
||||
final AccountCreationResponse creationResponse = response.readEntity(AccountCreationResponse.class);
|
||||
assertEquals(existingAccount, creationResponse.isReregistration());
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean accountAttributesEqual(final AccountAttributes a, final AccountAttributes b) {
|
||||
return a.getFetchesMessages() == b.getFetchesMessages()
|
||||
&& a.getRegistrationId() == b.getRegistrationId()
|
||||
|
||||
+4
-3
@@ -64,8 +64,6 @@ class OutgoingMessageEntityTest {
|
||||
|
||||
@Test
|
||||
void entityPreservesEnvelope() {
|
||||
final Random random = new Random();
|
||||
|
||||
final byte[] reportSpamToken = TestRandomUtil.nextBytes(8);
|
||||
|
||||
final Account account = new Account();
|
||||
@@ -79,11 +77,14 @@ class OutgoingMessageEntityTest {
|
||||
(byte) 123,
|
||||
System.currentTimeMillis(),
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
reportSpamToken);
|
||||
|
||||
MessageProtos.Envelope envelope = baseEnvelope.toBuilder().setServerGuid(UUID.randomUUID().toString()).build();
|
||||
|
||||
assertEquals(envelope, OutgoingMessageEntity.fromEnvelope(envelope).toEnvelope());
|
||||
// Note that outgoing message entities don't have an "ephemeral"/"online" flag
|
||||
assertEquals(envelope.toBuilder().clearEphemeral().build(),
|
||||
OutgoingMessageEntity.fromEnvelope(envelope).toEnvelope());
|
||||
}
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.filters;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import jakarta.ws.rs.WebApplicationException;
|
||||
import jakarta.ws.rs.core.SecurityContext;
|
||||
import java.net.URI;
|
||||
import java.util.UUID;
|
||||
import org.glassfish.jersey.server.ContainerRequest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.tests.util.FakeDynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
|
||||
class RestDeprecationFilterTest {
|
||||
|
||||
@Test
|
||||
void testNoConfig() throws Exception {
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
|
||||
new FakeDynamicConfigurationManager<>(new DynamicConfiguration());
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager = new ExperimentEnrollmentManager(dynamicConfigurationManager);
|
||||
|
||||
final RestDeprecationFilter filter = new RestDeprecationFilter(dynamicConfigurationManager, experimentEnrollmentManager);
|
||||
|
||||
final Account account = new Account();
|
||||
account.setUuid(UUID.randomUUID());
|
||||
final SecurityContext securityContext = mock(SecurityContext.class);
|
||||
when(securityContext.getUserPrincipal()).thenReturn(new AuthenticatedDevice(account, new Device()));
|
||||
final ContainerRequest req = new ContainerRequest(null, new URI("/some/uri"), "GET", securityContext, null, null);
|
||||
req.getHeaders().add(HttpHeaders.USER_AGENT, "Signal-Android/100.0.0");
|
||||
|
||||
filter.filter(req);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testOldClient() throws Exception {
|
||||
final DynamicConfiguration config = SystemMapper.yamlMapper().readValue(
|
||||
"""
|
||||
minimumRestFreeVersion:
|
||||
ANDROID: 200.0.0
|
||||
experiments:
|
||||
restDeprecation:
|
||||
uuidEnrollmentPercentage: 100
|
||||
""",
|
||||
DynamicConfiguration.class);
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = new FakeDynamicConfigurationManager<>(config);
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager = new ExperimentEnrollmentManager(dynamicConfigurationManager);
|
||||
|
||||
final RestDeprecationFilter filter = new RestDeprecationFilter(dynamicConfigurationManager, experimentEnrollmentManager);
|
||||
|
||||
final Account account = new Account();
|
||||
account.setUuid(UUID.randomUUID());
|
||||
final SecurityContext securityContext = mock(SecurityContext.class);
|
||||
when(securityContext.getUserPrincipal()).thenReturn(new AuthenticatedDevice(account, new Device()));
|
||||
final ContainerRequest req = new ContainerRequest(null, new URI("/some/uri"), "GET", securityContext, null, null);
|
||||
req.getHeaders().add(HttpHeaders.USER_AGENT, "Signal-Android/100.0.0");
|
||||
|
||||
filter.filter(req);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testBlocking() throws Exception {
|
||||
final DynamicConfiguration config = SystemMapper.yamlMapper().readValue(
|
||||
"""
|
||||
minimumRestFreeVersion:
|
||||
ANDROID: 10.10.10
|
||||
experiments:
|
||||
restDeprecation:
|
||||
enrollmentPercentage: 100
|
||||
""",
|
||||
DynamicConfiguration.class);
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = new FakeDynamicConfigurationManager<>(config);
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager = new ExperimentEnrollmentManager(dynamicConfigurationManager);
|
||||
|
||||
final RestDeprecationFilter filter = new RestDeprecationFilter(dynamicConfigurationManager, experimentEnrollmentManager);
|
||||
|
||||
final Account account = new Account();
|
||||
account.setUuid(UUID.randomUUID());
|
||||
final SecurityContext securityContext = mock(SecurityContext.class);
|
||||
when(securityContext.getUserPrincipal()).thenReturn(new AuthenticatedDevice(account, new Device()));
|
||||
final ContainerRequest req = new ContainerRequest(null, new URI("/some/path"), "GET", securityContext, null, null);
|
||||
|
||||
req.getHeaders().putSingle(HttpHeaders.USER_AGENT, "Signal-Android/10.9.15");
|
||||
filter.filter(req);
|
||||
|
||||
req.getHeaders().putSingle(HttpHeaders.USER_AGENT, "Signal-Android/10.10.9");
|
||||
filter.filter(req);
|
||||
|
||||
req.getHeaders().putSingle(HttpHeaders.USER_AGENT, "Signal-Android/10.10.10");
|
||||
assertThrows(WebApplicationException.class, () -> filter.filter(req));
|
||||
|
||||
req.getHeaders().putSingle(HttpHeaders.USER_AGENT, "Signal-Android/100.0.0");
|
||||
assertThrows(WebApplicationException.class, () -> filter.filter(req));
|
||||
}
|
||||
|
||||
}
|
||||
+2
-2
@@ -11,14 +11,14 @@ import org.whispersystems.textsecuregcm.storage.Device;
|
||||
|
||||
class MessageDeliveryLoopMonitorTest {
|
||||
|
||||
private MessageDeliveryLoopMonitor messageDeliveryLoopMonitor;
|
||||
private RedisMessageDeliveryLoopMonitor messageDeliveryLoopMonitor;
|
||||
|
||||
@RegisterExtension
|
||||
static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
messageDeliveryLoopMonitor = new MessageDeliveryLoopMonitor(REDIS_CLUSTER_EXTENSION.getRedisCluster());
|
||||
messageDeliveryLoopMonitor = new RedisMessageDeliveryLoopMonitor(REDIS_CLUSTER_EXTENSION.getRedisCluster());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+7
-4
@@ -90,7 +90,7 @@ class MetricsRequestEventListenerTest {
|
||||
final ContainerRequest request = mock(ContainerRequest.class);
|
||||
when(request.getMethod()).thenReturn(method);
|
||||
when(request.getRequestHeader(HttpHeaders.USER_AGENT)).thenReturn(
|
||||
Collections.singletonList("Signal-Android/4.53.7 (Android 8.1)"));
|
||||
Collections.singletonList("Signal-Android/7.6.2 Android/34 libsignal/0.46.0"));
|
||||
|
||||
final ContainerResponse response = mock(ContainerResponse.class);
|
||||
when(response.getStatus()).thenReturn(statusCode);
|
||||
@@ -116,12 +116,13 @@ class MetricsRequestEventListenerTest {
|
||||
tags.add(tag);
|
||||
}
|
||||
|
||||
assertEquals(5, tags.size());
|
||||
assertEquals(6, tags.size());
|
||||
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.PATH_TAG, path)));
|
||||
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.METHOD_TAG, method)));
|
||||
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.STATUS_CODE_TAG, String.valueOf(statusCode))));
|
||||
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.TRAFFIC_SOURCE_TAG, TRAFFIC_SOURCE.name().toLowerCase())));
|
||||
assertTrue(tags.contains(Tag.of(UserAgentTagUtil.PLATFORM_TAG, "android")));
|
||||
assertTrue(tags.contains(Tag.of(UserAgentTagUtil.LIBSIGNAL_TAG, "true")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -178,12 +179,13 @@ class MetricsRequestEventListenerTest {
|
||||
tags.add(tag);
|
||||
}
|
||||
|
||||
assertEquals(5, tags.size());
|
||||
assertEquals(6, tags.size());
|
||||
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.PATH_TAG, "/v1/test/hello")));
|
||||
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.METHOD_TAG, "GET")));
|
||||
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.STATUS_CODE_TAG, String.valueOf(200))));
|
||||
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.TRAFFIC_SOURCE_TAG, TRAFFIC_SOURCE.name().toLowerCase())));
|
||||
assertTrue(tags.contains(Tag.of(UserAgentTagUtil.PLATFORM_TAG, "android")));
|
||||
assertTrue(tags.contains(Tag.of(UserAgentTagUtil.LIBSIGNAL_TAG, "false")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -238,12 +240,13 @@ class MetricsRequestEventListenerTest {
|
||||
tags.add(tag);
|
||||
}
|
||||
|
||||
assertEquals(5, tags.size());
|
||||
assertEquals(6, tags.size());
|
||||
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.PATH_TAG, "/v1/test/hello")));
|
||||
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.METHOD_TAG, "GET")));
|
||||
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.STATUS_CODE_TAG, String.valueOf(200))));
|
||||
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.TRAFFIC_SOURCE_TAG, TRAFFIC_SOURCE.name().toLowerCase())));
|
||||
assertTrue(tags.contains(Tag.of(UserAgentTagUtil.PLATFORM_TAG, "unrecognized")));
|
||||
assertTrue(tags.contains(Tag.of(UserAgentTagUtil.LIBSIGNAL_TAG, "false")));
|
||||
}
|
||||
|
||||
private static SubProtocol.WebSocketResponseMessage getResponse(ArgumentCaptor<ByteBuffer> responseCaptor)
|
||||
|
||||
+60
-21
@@ -10,23 +10,25 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.anyByte;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
@@ -49,17 +51,21 @@ class MessageSenderTest {
|
||||
|
||||
@CartesianTest
|
||||
void sendMessage(@CartesianTest.Values(booleans = {true, false}) final boolean clientPresent,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean onlineMessage,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean ephemeral,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean urgent,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean hasPushToken) throws NotPushRegisteredException {
|
||||
|
||||
final boolean expectPushNotificationAttempt = !clientPresent && !onlineMessage;
|
||||
final boolean expectPushNotificationAttempt = !clientPresent && !ephemeral;
|
||||
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
final Device device = mock(Device.class);
|
||||
final MessageProtos.Envelope message = generateRandomMessage();
|
||||
final MessageProtos.Envelope message = MessageProtos.Envelope.newBuilder()
|
||||
.setEphemeral(ephemeral)
|
||||
.setUrgent(urgent)
|
||||
.build();
|
||||
|
||||
when(account.getUuid()).thenReturn(accountIdentifier);
|
||||
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
|
||||
@@ -72,18 +78,61 @@ class MessageSenderTest {
|
||||
.when(pushNotificationManager).sendNewMessageNotification(any(), anyByte(), anyBoolean());
|
||||
}
|
||||
|
||||
when(messagesManager.insert(eq(accountIdentifier), eq(deviceId), any())).thenReturn(clientPresent);
|
||||
when(messagesManager.insert(any(), any())).thenReturn(Map.of(deviceId, clientPresent));
|
||||
|
||||
assertDoesNotThrow(() -> messageSender.sendMessage(account, device, message, onlineMessage));
|
||||
assertDoesNotThrow(() -> messageSender.sendMessages(account, Map.of(device.getId(), message)));
|
||||
|
||||
final MessageProtos.Envelope expectedMessage = onlineMessage
|
||||
final MessageProtos.Envelope expectedMessage = ephemeral
|
||||
? message.toBuilder().setEphemeral(true).build()
|
||||
: message.toBuilder().build();
|
||||
|
||||
verify(messagesManager).insert(accountIdentifier, deviceId, expectedMessage);
|
||||
verify(messagesManager).insert(accountIdentifier, Map.of(deviceId, expectedMessage));
|
||||
|
||||
if (expectPushNotificationAttempt) {
|
||||
verify(pushNotificationManager).sendNewMessageNotification(account, deviceId, expectedMessage.getUrgent());
|
||||
verify(pushNotificationManager).sendNewMessageNotification(account, deviceId, urgent);
|
||||
} else {
|
||||
verifyNoInteractions(pushNotificationManager);
|
||||
}
|
||||
}
|
||||
|
||||
@CartesianTest
|
||||
void sendMultiRecipientMessage(@CartesianTest.Values(booleans = {true, false}) final boolean clientPresent,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean ephemeral,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean urgent,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean hasPushToken) throws NotPushRegisteredException {
|
||||
|
||||
final boolean expectPushNotificationAttempt = !clientPresent && !ephemeral;
|
||||
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
final Device device = mock(Device.class);
|
||||
|
||||
when(account.getUuid()).thenReturn(accountIdentifier);
|
||||
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
|
||||
when(device.getId()).thenReturn(deviceId);
|
||||
|
||||
if (hasPushToken) {
|
||||
when(device.getApnId()).thenReturn("apns-token");
|
||||
} else {
|
||||
doThrow(NotPushRegisteredException.class)
|
||||
.when(pushNotificationManager).sendNewMessageNotification(any(), anyByte(), anyBoolean());
|
||||
}
|
||||
|
||||
when(messagesManager.insertMultiRecipientMessage(any(), any(), anyLong(), anyBoolean(), anyBoolean(), anyBoolean()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Map.of(account, Map.of(deviceId, clientPresent))));
|
||||
|
||||
assertDoesNotThrow(() -> messageSender.sendMultiRecipientMessage(mock(SealedSenderMultiRecipientMessage.class),
|
||||
Collections.emptyMap(),
|
||||
System.currentTimeMillis(),
|
||||
false,
|
||||
ephemeral,
|
||||
urgent)
|
||||
.join());
|
||||
|
||||
if (expectPushNotificationAttempt) {
|
||||
verify(pushNotificationManager).sendNewMessageNotification(account, deviceId, urgent);
|
||||
} else {
|
||||
verifyNoInteractions(pushNotificationManager);
|
||||
}
|
||||
@@ -123,14 +172,4 @@ class MessageSenderTest {
|
||||
|
||||
return arguments;
|
||||
}
|
||||
|
||||
private MessageProtos.Envelope generateRandomMessage() {
|
||||
return MessageProtos.Envelope.newBuilder()
|
||||
.setClientTimestamp(System.currentTimeMillis())
|
||||
.setServerTimestamp(System.currentTimeMillis())
|
||||
.setContent(ByteString.copyFromUtf8(RandomStringUtils.secure().nextAlphanumeric(256)))
|
||||
.setType(MessageProtos.Envelope.Type.CIPHERTEXT)
|
||||
.setServerGuid(UUID.randomUUID().toString())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+10
-3
@@ -21,6 +21,7 @@ import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisServerExtension;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
@@ -33,7 +34,9 @@ import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
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.when;
|
||||
|
||||
@@ -178,8 +181,9 @@ public class AccountsManagerDeviceTransferIntegrationTest {
|
||||
@Test
|
||||
void waitForRestoreAccountRequest() {
|
||||
final String token = RandomStringUtils.secure().nextAlphanumeric(16);
|
||||
final byte[] deviceTransferBootstrap = TestRandomUtil.nextBytes(100);
|
||||
final RestoreAccountRequest restoreAccountRequest =
|
||||
new RestoreAccountRequest(RestoreAccountRequest.Method.DEVICE_TRANSFER);
|
||||
new RestoreAccountRequest(RestoreAccountRequest.Method.DEVICE_TRANSFER, deviceTransferBootstrap);
|
||||
|
||||
final CompletableFuture<Optional<RestoreAccountRequest>> displacedFuture =
|
||||
accountsManager.waitForRestoreAccountRequest(token, Duration.ofSeconds(5));
|
||||
@@ -191,14 +195,17 @@ public class AccountsManagerDeviceTransferIntegrationTest {
|
||||
|
||||
accountsManager.recordRestoreAccountRequest(token, restoreAccountRequest).join();
|
||||
|
||||
assertEquals(Optional.of(restoreAccountRequest), activeFuture.join());
|
||||
final Optional<RestoreAccountRequest> result = activeFuture.join();
|
||||
assertTrue(result.isPresent());
|
||||
assertEquals(restoreAccountRequest.method(), result.get().method());
|
||||
assertArrayEquals(restoreAccountRequest.deviceTransferBootstrap(), result.get().deviceTransferBootstrap());
|
||||
}
|
||||
|
||||
@Test
|
||||
void waitForRestoreAccountRequestAlreadyRequested() {
|
||||
final String token = RandomStringUtils.secure().nextAlphanumeric(16);
|
||||
final RestoreAccountRequest restoreAccountRequest =
|
||||
new RestoreAccountRequest(RestoreAccountRequest.Method.DEVICE_TRANSFER);
|
||||
new RestoreAccountRequest(RestoreAccountRequest.Method.DEVICE_TRANSFER, null);
|
||||
|
||||
accountsManager.recordRestoreAccountRequest(token, restoreAccountRequest).join();
|
||||
|
||||
|
||||
@@ -30,10 +30,12 @@ import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Random;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
@@ -56,6 +58,7 @@ import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.DevicesHelper;
|
||||
@@ -731,6 +734,22 @@ class AccountsTest {
|
||||
retrievedAccounts.stream().map(Account::getUuid).collect(Collectors.toSet()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllAccountIdentifiers() {
|
||||
final Set<UUID> expectedAccountIdentifiers = new HashSet<>();
|
||||
|
||||
for (int i = 1; i <= 100; i++) {
|
||||
final Account account = generateAccount("+1" + String.format("%03d", i), UUID.randomUUID(), UUID.randomUUID());
|
||||
expectedAccountIdentifiers.add(account.getIdentifier(IdentityType.ACI));
|
||||
createAccount(account);
|
||||
}
|
||||
|
||||
@SuppressWarnings("DataFlowIssue") final Set<UUID> retrievedAccountIdentifiers =
|
||||
new HashSet<>(accounts.getAllAccountIdentifiers(2, Schedulers.parallel()).collectList().block());
|
||||
|
||||
assertEquals(expectedAccountIdentifiers, retrievedAccountIdentifiers);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDelete() {
|
||||
final Device deletedDevice = generateDevice(DEVICE_ID_1);
|
||||
|
||||
+43
-17
@@ -22,6 +22,7 @@ import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -104,7 +105,7 @@ public class ChangeNumberManagerTest {
|
||||
changeNumberManager.changeNumber(account, "+18025551234", null, null, null, null, null);
|
||||
verify(accountsManager).changeNumber(account, "+18025551234", null, null, null, null);
|
||||
verify(accountsManager, never()).updateDevice(any(), anyByte(), any());
|
||||
verify(messageSender, never()).sendMessage(eq(account), any(), any(), eq(false));
|
||||
verify(messageSender, never()).sendMessages(eq(account), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -118,7 +119,7 @@ public class ChangeNumberManagerTest {
|
||||
|
||||
changeNumberManager.changeNumber(account, "+18025551234", pniIdentityKey, prekeys, null, Collections.emptyList(), Collections.emptyMap());
|
||||
verify(accountsManager).changeNumber(account, "+18025551234", pniIdentityKey, prekeys, null, Collections.emptyMap());
|
||||
verify(messageSender, never()).sendMessage(eq(account), any(), any(), eq(false));
|
||||
verify(messageSender, never()).sendMessages(eq(account), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -155,10 +156,15 @@ public class ChangeNumberManagerTest {
|
||||
|
||||
verify(accountsManager).changeNumber(account, changedE164, pniIdentityKey, prekeys, null, registrationIds);
|
||||
|
||||
final ArgumentCaptor<MessageProtos.Envelope> envelopeCaptor = ArgumentCaptor.forClass(MessageProtos.Envelope.class);
|
||||
verify(messageSender).sendMessage(any(), eq(d2), envelopeCaptor.capture(), eq(false));
|
||||
@SuppressWarnings("unchecked") final ArgumentCaptor<Map<Byte, MessageProtos.Envelope>> envelopeCaptor =
|
||||
ArgumentCaptor.forClass(Map.class);
|
||||
|
||||
final MessageProtos.Envelope envelope = envelopeCaptor.getValue();
|
||||
verify(messageSender).sendMessages(any(), envelopeCaptor.capture());
|
||||
|
||||
assertEquals(1, envelopeCaptor.getValue().size());
|
||||
assertEquals(Set.of(deviceId2), envelopeCaptor.getValue().keySet());
|
||||
|
||||
final MessageProtos.Envelope envelope = envelopeCaptor.getValue().get(deviceId2);
|
||||
|
||||
assertEquals(aci, UUID.fromString(envelope.getDestinationServiceId()));
|
||||
assertEquals(aci, UUID.fromString(envelope.getSourceServiceId()));
|
||||
@@ -203,10 +209,15 @@ public class ChangeNumberManagerTest {
|
||||
|
||||
verify(accountsManager).changeNumber(account, changedE164, pniIdentityKey, prekeys, pqPrekeys, registrationIds);
|
||||
|
||||
final ArgumentCaptor<MessageProtos.Envelope> envelopeCaptor = ArgumentCaptor.forClass(MessageProtos.Envelope.class);
|
||||
verify(messageSender).sendMessage(any(), eq(d2), envelopeCaptor.capture(), eq(false));
|
||||
@SuppressWarnings("unchecked") final ArgumentCaptor<Map<Byte, MessageProtos.Envelope>> envelopeCaptor =
|
||||
ArgumentCaptor.forClass(Map.class);
|
||||
|
||||
final MessageProtos.Envelope envelope = envelopeCaptor.getValue();
|
||||
verify(messageSender).sendMessages(any(), envelopeCaptor.capture());
|
||||
|
||||
assertEquals(1, envelopeCaptor.getValue().size());
|
||||
assertEquals(Set.of(deviceId2), envelopeCaptor.getValue().keySet());
|
||||
|
||||
final MessageProtos.Envelope envelope = envelopeCaptor.getValue().get(deviceId2);
|
||||
|
||||
assertEquals(aci, UUID.fromString(envelope.getDestinationServiceId()));
|
||||
assertEquals(aci, UUID.fromString(envelope.getSourceServiceId()));
|
||||
@@ -249,10 +260,15 @@ public class ChangeNumberManagerTest {
|
||||
|
||||
verify(accountsManager).updatePniKeys(account, pniIdentityKey, prekeys, pqPrekeys, registrationIds);
|
||||
|
||||
final ArgumentCaptor<MessageProtos.Envelope> envelopeCaptor = ArgumentCaptor.forClass(MessageProtos.Envelope.class);
|
||||
verify(messageSender).sendMessage(any(), eq(d2), envelopeCaptor.capture(), eq(false));
|
||||
@SuppressWarnings("unchecked") final ArgumentCaptor<Map<Byte, MessageProtos.Envelope>> envelopeCaptor =
|
||||
ArgumentCaptor.forClass(Map.class);
|
||||
|
||||
final MessageProtos.Envelope envelope = envelopeCaptor.getValue();
|
||||
verify(messageSender).sendMessages(any(), envelopeCaptor.capture());
|
||||
|
||||
assertEquals(1, envelopeCaptor.getValue().size());
|
||||
assertEquals(Set.of(deviceId2), envelopeCaptor.getValue().keySet());
|
||||
|
||||
final MessageProtos.Envelope envelope = envelopeCaptor.getValue().get(deviceId2);
|
||||
|
||||
assertEquals(aci, UUID.fromString(envelope.getDestinationServiceId()));
|
||||
assertEquals(aci, UUID.fromString(envelope.getSourceServiceId()));
|
||||
@@ -291,10 +307,15 @@ public class ChangeNumberManagerTest {
|
||||
|
||||
verify(accountsManager).updatePniKeys(account, pniIdentityKey, prekeys, null, registrationIds);
|
||||
|
||||
final ArgumentCaptor<MessageProtos.Envelope> envelopeCaptor = ArgumentCaptor.forClass(MessageProtos.Envelope.class);
|
||||
verify(messageSender).sendMessage(any(), eq(d2), envelopeCaptor.capture(), eq(false));
|
||||
@SuppressWarnings("unchecked") final ArgumentCaptor<Map<Byte, MessageProtos.Envelope>> envelopeCaptor =
|
||||
ArgumentCaptor.forClass(Map.class);
|
||||
|
||||
final MessageProtos.Envelope envelope = envelopeCaptor.getValue();
|
||||
verify(messageSender).sendMessages(any(), envelopeCaptor.capture());
|
||||
|
||||
assertEquals(1, envelopeCaptor.getValue().size());
|
||||
assertEquals(Set.of(deviceId2), envelopeCaptor.getValue().keySet());
|
||||
|
||||
final MessageProtos.Envelope envelope = envelopeCaptor.getValue().get(deviceId2);
|
||||
|
||||
assertEquals(aci, UUID.fromString(envelope.getDestinationServiceId()));
|
||||
assertEquals(aci, UUID.fromString(envelope.getSourceServiceId()));
|
||||
@@ -335,10 +356,15 @@ public class ChangeNumberManagerTest {
|
||||
|
||||
verify(accountsManager).updatePniKeys(account, pniIdentityKey, prekeys, pqPrekeys, registrationIds);
|
||||
|
||||
final ArgumentCaptor<MessageProtos.Envelope> envelopeCaptor = ArgumentCaptor.forClass(MessageProtos.Envelope.class);
|
||||
verify(messageSender).sendMessage(any(), eq(d2), envelopeCaptor.capture(), eq(false));
|
||||
@SuppressWarnings("unchecked") final ArgumentCaptor<Map<Byte, MessageProtos.Envelope>> envelopeCaptor =
|
||||
ArgumentCaptor.forClass(Map.class);
|
||||
|
||||
final MessageProtos.Envelope envelope = envelopeCaptor.getValue();
|
||||
verify(messageSender).sendMessages(any(), envelopeCaptor.capture());
|
||||
|
||||
assertEquals(1, envelopeCaptor.getValue().size());
|
||||
assertEquals(Set.of(deviceId2), envelopeCaptor.getValue().keySet());
|
||||
|
||||
final MessageProtos.Envelope envelope = envelopeCaptor.getValue().get(deviceId2);
|
||||
|
||||
assertEquals(aci, UUID.fromString(envelope.getDestinationServiceId()));
|
||||
assertEquals(aci, UUID.fromString(envelope.getSourceServiceId()));
|
||||
|
||||
+2
-2
@@ -84,7 +84,7 @@ class MessagePersisterIntegrationTest {
|
||||
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
messageDeliveryScheduler, messageDeletionExecutorService, Clock.systemUTC());
|
||||
messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, mock(ReportMessageManager.class),
|
||||
messageDeletionExecutorService);
|
||||
messageDeletionExecutorService, Clock.systemUTC());
|
||||
|
||||
websocketConnectionEventExecutor = Executors.newVirtualThreadPerTaskExecutor();
|
||||
asyncOperationQueueingExecutor = Executors.newSingleThreadExecutor();
|
||||
@@ -143,7 +143,7 @@ class MessagePersisterIntegrationTest {
|
||||
|
||||
final MessageProtos.Envelope message = generateRandomMessage(messageGuid, timestamp);
|
||||
|
||||
messagesCache.insert(messageGuid, account.getUuid(), Device.PRIMARY_ID, message);
|
||||
messagesCache.insert(messageGuid, account.getUuid(), Device.PRIMARY_ID, message).join();
|
||||
expectedMessages.add(message);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -358,7 +358,7 @@ class MessagePersisterTest {
|
||||
.setServerGuid(messageGuid.toString())
|
||||
.build();
|
||||
|
||||
messagesCache.insert(messageGuid, accountUuid, deviceId, envelope);
|
||||
messagesCache.insert(messageGuid, accountUuid, deviceId, envelope).join();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -40,7 +40,7 @@ class MessagesCacheGetItemsScriptTest {
|
||||
.setServerGuid(serverGuid)
|
||||
.build();
|
||||
|
||||
insertScript.execute(destinationUuid, deviceId, envelope1);
|
||||
insertScript.executeAsync(destinationUuid, deviceId, envelope1);
|
||||
|
||||
final MessagesCacheGetItemsScript getItemsScript = new MessagesCacheGetItemsScript(
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster());
|
||||
|
||||
+7
-7
@@ -41,7 +41,7 @@ class MessagesCacheInsertScriptTest {
|
||||
.setServerGuid(UUID.randomUUID().toString())
|
||||
.build();
|
||||
|
||||
insertScript.execute(destinationUuid, deviceId, envelope1);
|
||||
insertScript.executeAsync(destinationUuid, deviceId, envelope1);
|
||||
|
||||
assertEquals(List.of(envelope1), getStoredMessages(destinationUuid, deviceId));
|
||||
|
||||
@@ -50,11 +50,11 @@ class MessagesCacheInsertScriptTest {
|
||||
.setServerGuid(UUID.randomUUID().toString())
|
||||
.build();
|
||||
|
||||
insertScript.execute(destinationUuid, deviceId, envelope2);
|
||||
insertScript.executeAsync(destinationUuid, deviceId, envelope2);
|
||||
|
||||
assertEquals(List.of(envelope1, envelope2), getStoredMessages(destinationUuid, deviceId));
|
||||
|
||||
insertScript.execute(destinationUuid, deviceId, envelope1);
|
||||
insertScript.executeAsync(destinationUuid, deviceId, envelope1);
|
||||
|
||||
assertEquals(List.of(envelope1, envelope2), getStoredMessages(destinationUuid, deviceId),
|
||||
"Messages with same GUID should be deduplicated");
|
||||
@@ -89,10 +89,10 @@ class MessagesCacheInsertScriptTest {
|
||||
final MessagesCacheInsertScript insertScript =
|
||||
new MessagesCacheInsertScript(REDIS_CLUSTER_EXTENSION.getRedisCluster());
|
||||
|
||||
assertFalse(insertScript.execute(destinationUuid, deviceId, MessageProtos.Envelope.newBuilder()
|
||||
assertFalse(insertScript.executeAsync(destinationUuid, deviceId, MessageProtos.Envelope.newBuilder()
|
||||
.setServerTimestamp(Instant.now().getEpochSecond())
|
||||
.setServerGuid(UUID.randomUUID().toString())
|
||||
.build()));
|
||||
.build()).join());
|
||||
|
||||
final FaultTolerantPubSubClusterConnection<byte[], byte[]> pubSubClusterConnection =
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().createBinaryPubSubConnection();
|
||||
@@ -100,9 +100,9 @@ class MessagesCacheInsertScriptTest {
|
||||
pubSubClusterConnection.usePubSubConnection(connection ->
|
||||
connection.sync().ssubscribe(WebSocketConnectionEventManager.getClientEventChannel(destinationUuid, deviceId)));
|
||||
|
||||
assertTrue(insertScript.execute(destinationUuid, deviceId, MessageProtos.Envelope.newBuilder()
|
||||
assertTrue(insertScript.executeAsync(destinationUuid, deviceId, MessageProtos.Envelope.newBuilder()
|
||||
.setServerTimestamp(Instant.now().getEpochSecond())
|
||||
.setServerGuid(UUID.randomUUID().toString())
|
||||
.build()));
|
||||
.build()).join());
|
||||
}
|
||||
}
|
||||
+14
-8
@@ -6,7 +6,9 @@
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import io.lettuce.core.RedisCommandExecutionException;
|
||||
import java.util.ArrayList;
|
||||
@@ -14,8 +16,10 @@ import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import io.lettuce.core.RedisException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
@@ -39,8 +43,8 @@ class MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScriptTest {
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster());
|
||||
|
||||
final byte[] sharedMrmKey = MessagesCache.getSharedMrmKey(UUID.randomUUID());
|
||||
insertMrmScript.execute(sharedMrmKey,
|
||||
MessagesCacheTest.generateRandomMrmMessage(destinations));
|
||||
insertMrmScript.executeAsync(sharedMrmKey,
|
||||
MessagesCacheTest.generateRandomMrmMessage(destinations)).join();
|
||||
|
||||
final int totalDevices = destinations.values().stream().mapToInt(List::size).sum();
|
||||
final long hashFieldCount = REDIS_CLUSTER_EXTENSION.getRedisCluster()
|
||||
@@ -82,15 +86,17 @@ class MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScriptTest {
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster());
|
||||
|
||||
final byte[] sharedMrmKey = MessagesCache.getSharedMrmKey(UUID.randomUUID());
|
||||
insertMrmScript.execute(sharedMrmKey,
|
||||
MessagesCacheTest.generateRandomMrmMessage(new AciServiceIdentifier(UUID.randomUUID()), Device.PRIMARY_ID));
|
||||
insertMrmScript.executeAsync(sharedMrmKey,
|
||||
MessagesCacheTest.generateRandomMrmMessage(new AciServiceIdentifier(UUID.randomUUID()), Device.PRIMARY_ID)).join();
|
||||
|
||||
final RedisCommandExecutionException e = assertThrows(RedisCommandExecutionException.class,
|
||||
() -> insertMrmScript.execute(sharedMrmKey,
|
||||
final CompletionException completionException = assertThrows(CompletionException.class,
|
||||
() -> insertMrmScript.executeAsync(sharedMrmKey,
|
||||
MessagesCacheTest.generateRandomMrmMessage(new AciServiceIdentifier(UUID.randomUUID()),
|
||||
Device.PRIMARY_ID)));
|
||||
Device.PRIMARY_ID)).join());
|
||||
|
||||
assertEquals(MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript.ERROR_KEY_EXISTS, e.getMessage());
|
||||
assertInstanceOf(RedisException.class, completionException.getCause());
|
||||
assertTrue(completionException.getCause().getMessage()
|
||||
.contains(MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript.ERROR_KEY_EXISTS));
|
||||
}
|
||||
|
||||
}
|
||||
+1
-1
@@ -34,7 +34,7 @@ class MessagesCacheRemoveByGuidScriptTest {
|
||||
.setServerGuid(serverGuid.toString())
|
||||
.build();
|
||||
|
||||
insertScript.execute(destinationUuid, deviceId, envelope1);
|
||||
insertScript.executeAsync(destinationUuid, deviceId, envelope1);
|
||||
|
||||
final MessagesCacheRemoveByGuidScript removeByGuidScript = new MessagesCacheRemoveByGuidScript(
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster());
|
||||
|
||||
+1
-1
@@ -35,7 +35,7 @@ class MessagesCacheRemoveQueueScriptTest {
|
||||
.setServerGuid(UUID.randomUUID().toString())
|
||||
.build();
|
||||
|
||||
insertScript.execute(destinationUuid, deviceId, envelope1);
|
||||
insertScript.executeAsync(destinationUuid, deviceId, envelope1);
|
||||
|
||||
final MessagesCacheRemoveQueueScript removeScript = new MessagesCacheRemoveQueueScript(
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster());
|
||||
|
||||
+3
-4
@@ -41,8 +41,7 @@ class MessagesCacheRemoveRecipientViewFromMrmDataScriptTest {
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster());
|
||||
|
||||
final byte[] sharedMrmKey = MessagesCache.getSharedMrmKey(UUID.randomUUID());
|
||||
insertMrmScript.execute(sharedMrmKey,
|
||||
MessagesCacheTest.generateRandomMrmMessage(destinations));
|
||||
insertMrmScript.executeAsync(sharedMrmKey, MessagesCacheTest.generateRandomMrmMessage(destinations)).join();
|
||||
|
||||
final MessagesCacheRemoveRecipientViewFromMrmDataScript removeRecipientViewFromMrmDataScript = new MessagesCacheRemoveRecipientViewFromMrmDataScript(
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster());
|
||||
@@ -103,8 +102,8 @@ class MessagesCacheRemoveRecipientViewFromMrmDataScriptTest {
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster());
|
||||
|
||||
final byte[] sharedMrmKey = MessagesCache.getSharedMrmKey(UUID.randomUUID());
|
||||
insertMrmScript.execute(sharedMrmKey,
|
||||
MessagesCacheTest.generateRandomMrmMessage(serviceIdentifier, deviceId));
|
||||
insertMrmScript.executeAsync(sharedMrmKey,
|
||||
MessagesCacheTest.generateRandomMrmMessage(serviceIdentifier, deviceId)).join();
|
||||
|
||||
sharedMrmKeys.add(sharedMrmKey);
|
||||
}
|
||||
|
||||
+41
-28
@@ -122,7 +122,7 @@ class MessagesCacheTest {
|
||||
void testInsert(final boolean sealedSender) {
|
||||
final UUID messageGuid = UUID.randomUUID();
|
||||
assertDoesNotThrow(() -> messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID,
|
||||
generateRandomMessage(messageGuid, sealedSender)));
|
||||
generateRandomMessage(messageGuid, sealedSender))).join();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -130,8 +130,8 @@ class MessagesCacheTest {
|
||||
final UUID duplicateGuid = UUID.randomUUID();
|
||||
final MessageProtos.Envelope duplicateMessage = generateRandomMessage(duplicateGuid, false);
|
||||
|
||||
messagesCache.insert(duplicateGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, duplicateMessage);
|
||||
messagesCache.insert(duplicateGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, duplicateMessage);
|
||||
messagesCache.insert(duplicateGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, duplicateMessage).join();
|
||||
messagesCache.insert(duplicateGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, duplicateMessage).join();
|
||||
|
||||
assertEquals(1, messagesCache.getAllMessages(DESTINATION_UUID, DESTINATION_DEVICE_ID, 0, 10)
|
||||
.count()
|
||||
@@ -149,7 +149,7 @@ class MessagesCacheTest {
|
||||
|
||||
final MessageProtos.Envelope message = generateRandomMessage(messageGuid, sealedSender);
|
||||
|
||||
messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message);
|
||||
messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message).join();
|
||||
final Optional<RemovedMessage> maybeRemovedMessage = messagesCache.remove(DESTINATION_UUID,
|
||||
DESTINATION_DEVICE_ID, messageGuid).get(5, TimeUnit.SECONDS);
|
||||
|
||||
@@ -175,12 +175,12 @@ class MessagesCacheTest {
|
||||
|
||||
for (final MessageProtos.Envelope message : messagesToRemove) {
|
||||
messagesCache.insert(UUID.fromString(message.getServerGuid()), DESTINATION_UUID, DESTINATION_DEVICE_ID,
|
||||
message);
|
||||
message).join();
|
||||
}
|
||||
|
||||
for (final MessageProtos.Envelope message : messagesToPreserve) {
|
||||
messagesCache.insert(UUID.fromString(message.getServerGuid()), DESTINATION_UUID, DESTINATION_DEVICE_ID,
|
||||
message);
|
||||
message).join();
|
||||
}
|
||||
|
||||
final List<RemovedMessage> removedMessages = messagesCache.remove(DESTINATION_UUID, DESTINATION_DEVICE_ID,
|
||||
@@ -197,7 +197,7 @@ class MessagesCacheTest {
|
||||
|
||||
final UUID messageGuid = UUID.randomUUID();
|
||||
final MessageProtos.Envelope message = generateRandomMessage(messageGuid, true);
|
||||
messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message);
|
||||
messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message).join();
|
||||
|
||||
assertTrue(messagesCache.hasMessages(DESTINATION_UUID, DESTINATION_DEVICE_ID));
|
||||
}
|
||||
@@ -208,7 +208,7 @@ class MessagesCacheTest {
|
||||
|
||||
final UUID messageGuid = UUID.randomUUID();
|
||||
final MessageProtos.Envelope message = generateRandomMessage(messageGuid, true);
|
||||
messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message);
|
||||
messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message).join();
|
||||
|
||||
assertTrue(messagesCache.hasMessagesAsync(DESTINATION_UUID, DESTINATION_DEVICE_ID).join());
|
||||
}
|
||||
@@ -223,7 +223,7 @@ class MessagesCacheTest {
|
||||
for (int i = 0; i < messageCount; i++) {
|
||||
final UUID messageGuid = UUID.randomUUID();
|
||||
final MessageProtos.Envelope message = generateRandomMessage(messageGuid, i % 2 == 0);
|
||||
messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message);
|
||||
messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message).join();
|
||||
assertEquals(expectedOldestTimestamp,
|
||||
messagesCache.getEarliestUndeliveredTimestamp(DESTINATION_UUID, DESTINATION_DEVICE_ID).block());
|
||||
expectedMessages.add(message);
|
||||
@@ -248,7 +248,7 @@ class MessagesCacheTest {
|
||||
for (int i = 0; i < messageCount; i++) {
|
||||
final UUID messageGuid = UUID.randomUUID();
|
||||
final MessageProtos.Envelope message = generateRandomMessage(messageGuid, sealedSender);
|
||||
messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message);
|
||||
messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message).join();
|
||||
expectedMessages.add(message);
|
||||
}
|
||||
|
||||
@@ -262,7 +262,7 @@ class MessagesCacheTest {
|
||||
|
||||
final UUID message1Guid = UUID.randomUUID();
|
||||
final MessageProtos.Envelope message1 = generateRandomMessage(message1Guid, sealedSender);
|
||||
messagesCache.insert(message1Guid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message1);
|
||||
messagesCache.insert(message1Guid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message1).join();
|
||||
final List<MessageProtos.Envelope> get1 = get(DESTINATION_UUID, DESTINATION_DEVICE_ID,
|
||||
1);
|
||||
assertEquals(List.of(message1), get1);
|
||||
@@ -272,7 +272,7 @@ class MessagesCacheTest {
|
||||
final UUID message2Guid = UUID.randomUUID();
|
||||
final MessageProtos.Envelope message2 = generateRandomMessage(message2Guid, sealedSender);
|
||||
|
||||
messagesCache.insert(message2Guid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message2);
|
||||
messagesCache.insert(message2Guid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message2).join();
|
||||
|
||||
assertEquals(List.of(message2), get(DESTINATION_UUID, DESTINATION_DEVICE_ID, 1));
|
||||
}
|
||||
@@ -287,7 +287,7 @@ class MessagesCacheTest {
|
||||
for (int i = 0; i < messageCount; i++) {
|
||||
final UUID messageGuid = UUID.randomUUID();
|
||||
final MessageProtos.Envelope message = generateRandomMessage(messageGuid, true);
|
||||
messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message);
|
||||
messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message).join();
|
||||
|
||||
expectedMessages.add(message);
|
||||
}
|
||||
@@ -295,7 +295,7 @@ class MessagesCacheTest {
|
||||
final UUID ephemeralMessageGuid = UUID.randomUUID();
|
||||
final MessageProtos.Envelope ephemeralMessage = generateRandomMessage(ephemeralMessageGuid, true)
|
||||
.toBuilder().setEphemeral(true).build();
|
||||
messagesCache.insert(ephemeralMessageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, ephemeralMessage);
|
||||
messagesCache.insert(ephemeralMessageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, ephemeralMessage).join();
|
||||
|
||||
final Clock cacheClock;
|
||||
if (expectStale) {
|
||||
@@ -352,7 +352,7 @@ class MessagesCacheTest {
|
||||
final UUID messageGuid = UUID.randomUUID();
|
||||
final MessageProtos.Envelope message = generateRandomMessage(messageGuid, sealedSender);
|
||||
|
||||
messagesCache.insert(messageGuid, DESTINATION_UUID, deviceId, message);
|
||||
messagesCache.insert(messageGuid, DESTINATION_UUID, deviceId, message).join();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -372,7 +372,7 @@ class MessagesCacheTest {
|
||||
final UUID messageGuid = UUID.randomUUID();
|
||||
final MessageProtos.Envelope message = generateRandomMessage(messageGuid, sealedSender);
|
||||
|
||||
messagesCache.insert(messageGuid, DESTINATION_UUID, deviceId, message);
|
||||
messagesCache.insert(messageGuid, DESTINATION_UUID, deviceId, message).join();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -404,7 +404,7 @@ class MessagesCacheTest {
|
||||
final UUID messageGuid = UUID.randomUUID();
|
||||
|
||||
messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID,
|
||||
generateRandomMessage(messageGuid, sealedSender));
|
||||
generateRandomMessage(messageGuid, sealedSender)).join();
|
||||
final int slot = SlotHash.getSlot(DESTINATION_UUID + "::" + DESTINATION_DEVICE_ID);
|
||||
|
||||
assertTrue(messagesCache.getQueuesToPersist(slot + 1, Instant.now().plusSeconds(60), 100).isEmpty());
|
||||
@@ -427,7 +427,7 @@ class MessagesCacheTest {
|
||||
|
||||
final byte[] sharedMrmDataKey;
|
||||
if (sharedMrmKeyPresent) {
|
||||
sharedMrmDataKey = messagesCache.insertSharedMultiRecipientMessagePayload(mrm);
|
||||
sharedMrmDataKey = messagesCache.insertSharedMultiRecipientMessagePayload(mrm).join();
|
||||
} else {
|
||||
sharedMrmDataKey = "{1}".getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
@@ -440,29 +440,42 @@ class MessagesCacheTest {
|
||||
.setSharedMrmKey(ByteString.copyFrom(sharedMrmDataKey))
|
||||
.clearContent()
|
||||
.build();
|
||||
messagesCache.insert(guid, destinationServiceId.uuid(), deviceId, message);
|
||||
messagesCache.insert(guid, destinationServiceId.uuid(), deviceId, message).join();
|
||||
|
||||
assertEquals(sharedMrmKeyPresent ? 1 : 0, (long) REDIS_CLUSTER_EXTENSION.getRedisCluster()
|
||||
.withBinaryCluster(conn -> conn.sync().exists(sharedMrmDataKey)));
|
||||
|
||||
final List<MessageProtos.Envelope> messages = get(destinationServiceId.uuid(), deviceId, 1);
|
||||
|
||||
if (!sharedMrmKeyPresent) {
|
||||
assertTrue(messages.isEmpty());
|
||||
} else {
|
||||
|
||||
// the discard is purely async, so we just wait for it
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(1), () -> {
|
||||
boolean exists;
|
||||
do {
|
||||
exists = 1 == REDIS_CLUSTER_EXTENSION.getRedisCluster()
|
||||
.withBinaryCluster(conn ->
|
||||
conn.sync().hlen(MessagesCache.getMessageQueueKey(destinationServiceId.uuid(), deviceId)));
|
||||
} while (exists);
|
||||
}, "Stale MRM message should be deleted asynchronously");
|
||||
|
||||
} else {
|
||||
assertEquals(1, messages.size());
|
||||
|
||||
assertEquals(guid, UUID.fromString(messages.getFirst().getServerGuid()));
|
||||
assertFalse(messages.getFirst().hasSharedMrmKey());
|
||||
final SealedSenderMultiRecipientMessage.Recipient recipient = mrm.getRecipients()
|
||||
.get(destinationServiceId.toLibsignal());
|
||||
assertArrayEquals(mrm.messageForRecipient(recipient), messages.getFirst().getContent().toByteArray());
|
||||
|
||||
final Optional<RemovedMessage> removedMessage = messagesCache.remove(destinationServiceId.uuid(), deviceId, guid)
|
||||
.join();
|
||||
|
||||
assertTrue(removedMessage.isPresent());
|
||||
assertEquals(guid, UUID.fromString(removedMessage.get().serverGuid().toString()));
|
||||
}
|
||||
|
||||
final Optional<RemovedMessage> removedMessage = messagesCache.remove(destinationServiceId.uuid(), deviceId, guid)
|
||||
.join();
|
||||
|
||||
assertTrue(removedMessage.isPresent());
|
||||
assertEquals(guid, UUID.fromString(removedMessage.get().serverGuid().toString()));
|
||||
assertTrue(get(destinationServiceId.uuid(), deviceId, 1).isEmpty());
|
||||
|
||||
// updating the shared MRM data is purely async, so we just wait for it
|
||||
@@ -487,13 +500,13 @@ class MessagesCacheTest {
|
||||
final MessageProtos.Envelope message = generateRandomMessage(messageGuid,
|
||||
new AciServiceIdentifier(destinationUuid), true);
|
||||
|
||||
messagesCache.insert(messageGuid, destinationUuid, deviceId, message);
|
||||
messagesCache.insert(messageGuid, destinationUuid, deviceId, message).join();
|
||||
|
||||
final SealedSenderMultiRecipientMessage mrm = generateRandomMrmMessage(destinationServiceId, deviceId);
|
||||
|
||||
final byte[] sharedMrmDataKey;
|
||||
if (sharedMrmKeyPresent) {
|
||||
sharedMrmDataKey = messagesCache.insertSharedMultiRecipientMessagePayload(mrm);
|
||||
sharedMrmDataKey = messagesCache.insertSharedMultiRecipientMessagePayload(mrm).join();
|
||||
} else {
|
||||
sharedMrmDataKey = new byte[]{1};
|
||||
}
|
||||
@@ -505,7 +518,7 @@ class MessagesCacheTest {
|
||||
.clearContent()
|
||||
.setSharedMrmKey(ByteString.copyFrom(sharedMrmDataKey))
|
||||
.build();
|
||||
messagesCache.insert(mrmMessageGuid, destinationUuid, deviceId, mrmMessage);
|
||||
messagesCache.insert(mrmMessageGuid, destinationUuid, deviceId, mrmMessage).join();
|
||||
|
||||
final List<MessageProtos.Envelope> messages = messagesCache.getMessagesToPersist(destinationUuid, deviceId, 100);
|
||||
|
||||
|
||||
+132
-3
@@ -7,22 +7,42 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
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.never;
|
||||
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 com.google.protobuf.ByteString;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.signal.libsignal.protocol.InvalidMessageException;
|
||||
import org.signal.libsignal.protocol.InvalidVersionException;
|
||||
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
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.tests.util.MultiRecipientMessageHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.TestRecipient;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
class MessagesManagerTest {
|
||||
@@ -31,8 +51,15 @@ class MessagesManagerTest {
|
||||
private final MessagesCache messagesCache = mock(MessagesCache.class);
|
||||
private final ReportMessageManager reportMessageManager = mock(ReportMessageManager.class);
|
||||
|
||||
private static final TestClock CLOCK = TestClock.pinned(Instant.now());
|
||||
|
||||
private final MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache,
|
||||
reportMessageManager, Executors.newSingleThreadExecutor());
|
||||
reportMessageManager, Executors.newSingleThreadExecutor(), CLOCK);
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
when(messagesCache.insert(any(), any(), anyByte(), any())).thenReturn(CompletableFuture.completedFuture(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void insert() {
|
||||
@@ -43,7 +70,7 @@ class MessagesManagerTest {
|
||||
|
||||
final UUID destinationUuid = UUID.randomUUID();
|
||||
|
||||
messagesManager.insert(destinationUuid, Device.PRIMARY_ID, message);
|
||||
messagesManager.insert(destinationUuid, Map.of(Device.PRIMARY_ID, message));
|
||||
|
||||
verify(reportMessageManager).store(eq(sourceAci.toString()), any(UUID.class));
|
||||
|
||||
@@ -51,11 +78,113 @@ class MessagesManagerTest {
|
||||
.setSourceServiceId(destinationUuid.toString())
|
||||
.build();
|
||||
|
||||
messagesManager.insert(destinationUuid, Device.PRIMARY_ID, syncMessage);
|
||||
messagesManager.insert(destinationUuid, Map.of(Device.PRIMARY_ID, syncMessage));
|
||||
|
||||
verifyNoMoreInteractions(reportMessageManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
void insertMultiRecipientMessage() throws InvalidMessageException, InvalidVersionException {
|
||||
final ServiceIdentifier singleDeviceAccountAciServiceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final ServiceIdentifier singleDeviceAccountPniServiceIdentifier = new PniServiceIdentifier(UUID.randomUUID());
|
||||
final ServiceIdentifier multiDeviceAccountAciServiceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final ServiceIdentifier unresolvedAccountAciServiceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
|
||||
|
||||
final Account singleDeviceAccount = mock(Account.class);
|
||||
final Account multiDeviceAccount = mock(Account.class);
|
||||
|
||||
when(singleDeviceAccount.getIdentifier(IdentityType.ACI))
|
||||
.thenReturn(singleDeviceAccountAciServiceIdentifier.uuid());
|
||||
|
||||
when(multiDeviceAccount.getIdentifier(IdentityType.ACI))
|
||||
.thenReturn(multiDeviceAccountAciServiceIdentifier.uuid());
|
||||
|
||||
final byte[] multiRecipientMessageBytes = MultiRecipientMessageHelper.generateMultiRecipientMessage(List.of(
|
||||
new TestRecipient(singleDeviceAccountAciServiceIdentifier, Device.PRIMARY_ID, 1, new byte[48]),
|
||||
new TestRecipient(multiDeviceAccountAciServiceIdentifier, Device.PRIMARY_ID, 2, new byte[48]),
|
||||
new TestRecipient(multiDeviceAccountAciServiceIdentifier, (byte) (Device.PRIMARY_ID + 1), 3, new byte[48]),
|
||||
new TestRecipient(unresolvedAccountAciServiceIdentifier, Device.PRIMARY_ID, 4, new byte[48]),
|
||||
new TestRecipient(singleDeviceAccountPniServiceIdentifier, Device.PRIMARY_ID, 5, new byte[48])
|
||||
));
|
||||
|
||||
final SealedSenderMultiRecipientMessage multiRecipientMessage =
|
||||
SealedSenderMultiRecipientMessage.parse(multiRecipientMessageBytes);
|
||||
|
||||
final Map<SealedSenderMultiRecipientMessage.Recipient, Account> resolvedRecipients = new HashMap<>();
|
||||
|
||||
multiRecipientMessage.getRecipients().forEach(((serviceId, recipient) -> {
|
||||
if (serviceId.getRawUUID().equals(singleDeviceAccountAciServiceIdentifier.uuid()) ||
|
||||
serviceId.getRawUUID().equals(singleDeviceAccountPniServiceIdentifier.uuid())) {
|
||||
resolvedRecipients.put(recipient, singleDeviceAccount);
|
||||
} else if (serviceId.getRawUUID().equals(multiDeviceAccountAciServiceIdentifier.uuid())) {
|
||||
resolvedRecipients.put(recipient, multiDeviceAccount);
|
||||
}
|
||||
}));
|
||||
|
||||
final Map<Account, Map<Byte, Boolean>> expectedPresenceByAccountAndDeviceId = Map.of(
|
||||
singleDeviceAccount, Map.of(Device.PRIMARY_ID, true),
|
||||
multiDeviceAccount, Map.of(Device.PRIMARY_ID, false, (byte) (Device.PRIMARY_ID + 1), true)
|
||||
);
|
||||
|
||||
final Map<UUID, Map<Byte, Boolean>> presenceByAccountIdentifierAndDeviceId = Map.of(
|
||||
singleDeviceAccountAciServiceIdentifier.uuid(), Map.of(Device.PRIMARY_ID, true),
|
||||
multiDeviceAccountAciServiceIdentifier.uuid(), Map.of(Device.PRIMARY_ID, false, (byte) (Device.PRIMARY_ID + 1), true)
|
||||
);
|
||||
|
||||
final byte[] sharedMrmKey = "shared-mrm-key".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(messagesCache.insertSharedMultiRecipientMessagePayload(multiRecipientMessage))
|
||||
.thenReturn(CompletableFuture.completedFuture(sharedMrmKey));
|
||||
|
||||
when(messagesCache.insert(any(), any(), anyByte(), any()))
|
||||
.thenAnswer(invocation -> {
|
||||
final UUID accountIdentifier = invocation.getArgument(1);
|
||||
final byte deviceId = invocation.getArgument(2);
|
||||
|
||||
return CompletableFuture.completedFuture(
|
||||
presenceByAccountIdentifierAndDeviceId.getOrDefault(accountIdentifier, Collections.emptyMap())
|
||||
.getOrDefault(deviceId, false));
|
||||
});
|
||||
|
||||
final long clientTimestamp = System.currentTimeMillis();
|
||||
final boolean isStory = ThreadLocalRandom.current().nextBoolean();
|
||||
final boolean isEphemeral = ThreadLocalRandom.current().nextBoolean();
|
||||
final boolean isUrgent = ThreadLocalRandom.current().nextBoolean();
|
||||
|
||||
final Envelope prototypeExpectedMessage = Envelope.newBuilder()
|
||||
.setType(Envelope.Type.UNIDENTIFIED_SENDER)
|
||||
.setClientTimestamp(clientTimestamp)
|
||||
.setServerTimestamp(CLOCK.millis())
|
||||
.setStory(isStory)
|
||||
.setEphemeral(isEphemeral)
|
||||
.setUrgent(isUrgent)
|
||||
.setSharedMrmKey(ByteString.copyFrom(sharedMrmKey))
|
||||
.build();
|
||||
|
||||
assertEquals(expectedPresenceByAccountAndDeviceId,
|
||||
messagesManager.insertMultiRecipientMessage(multiRecipientMessage, resolvedRecipients, clientTimestamp, isStory, isEphemeral, isUrgent).join());
|
||||
|
||||
verify(messagesCache).insert(any(),
|
||||
eq(singleDeviceAccountAciServiceIdentifier.uuid()),
|
||||
eq(Device.PRIMARY_ID),
|
||||
eq(prototypeExpectedMessage.toBuilder().setDestinationServiceId(singleDeviceAccountAciServiceIdentifier.toServiceIdentifierString()).build()));
|
||||
|
||||
verify(messagesCache).insert(any(),
|
||||
eq(singleDeviceAccountAciServiceIdentifier.uuid()),
|
||||
eq(Device.PRIMARY_ID),
|
||||
eq(prototypeExpectedMessage.toBuilder().setDestinationServiceId(singleDeviceAccountPniServiceIdentifier.toServiceIdentifierString()).build()));
|
||||
|
||||
verify(messagesCache).insert(any(),
|
||||
eq(multiDeviceAccountAciServiceIdentifier.uuid()),
|
||||
eq((byte) (Device.PRIMARY_ID + 1)),
|
||||
eq(prototypeExpectedMessage.toBuilder().setDestinationServiceId(multiDeviceAccountAciServiceIdentifier.toServiceIdentifierString()).build()));
|
||||
|
||||
verify(messagesCache, never()).insert(any(),
|
||||
eq(unresolvedAccountAciServiceIdentifier.uuid()),
|
||||
anyByte(),
|
||||
any());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"false, false, false",
|
||||
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatNoException;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
|
||||
class PersistentTimerTest {
|
||||
|
||||
private static final String NAMESPACE = "namespace";
|
||||
private static final String KEY = "key";
|
||||
|
||||
@RegisterExtension
|
||||
private static final RedisClusterExtension CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
|
||||
private TestClock clock;
|
||||
private PersistentTimer timer;
|
||||
|
||||
@BeforeEach
|
||||
public void setup() {
|
||||
clock = TestClock.pinned(Instant.ofEpochSecond(10));
|
||||
timer = new PersistentTimer(CLUSTER_EXTENSION.getRedisCluster(), clock);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStop() {
|
||||
PersistentTimer.Sample sample = timer.start(NAMESPACE, KEY).join();
|
||||
final String redisKey = timer.redisKey(NAMESPACE, KEY);
|
||||
|
||||
final String actualStartString = CLUSTER_EXTENSION.getRedisCluster()
|
||||
.withCluster(conn -> conn.sync().get(redisKey));
|
||||
final Instant actualStart = Instant.ofEpochSecond(Long.parseLong(actualStartString));
|
||||
assertThat(actualStart).isEqualTo(clock.instant());
|
||||
|
||||
final long ttl = CLUSTER_EXTENSION.getRedisCluster()
|
||||
.withCluster(conn -> conn.sync().ttl(redisKey));
|
||||
|
||||
assertThat(ttl).isBetween(0L, PersistentTimer.TIMER_TTL.getSeconds());
|
||||
|
||||
Timer mockTimer = mock(Timer.class);
|
||||
clock.pin(clock.instant().plus(Duration.ofSeconds(5)));
|
||||
sample.stop(mockTimer).join();
|
||||
verify(mockTimer).record(Duration.ofSeconds(5));
|
||||
|
||||
final String afterDeletion = CLUSTER_EXTENSION.getRedisCluster()
|
||||
.withCluster(conn -> conn.sync().get(redisKey));
|
||||
|
||||
assertThat(afterDeletion).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNamespace() {
|
||||
Timer mockTimer = mock(Timer.class);
|
||||
|
||||
clock.pin(Instant.ofEpochSecond(10));
|
||||
PersistentTimer.Sample timer1 = timer.start("n1", KEY).join();
|
||||
clock.pin(Instant.ofEpochSecond(20));
|
||||
PersistentTimer.Sample timer2 = timer.start("n2", KEY).join();
|
||||
clock.pin(Instant.ofEpochSecond(30));
|
||||
|
||||
timer2.stop(mockTimer).join();
|
||||
verify(mockTimer).record(Duration.ofSeconds(10));
|
||||
|
||||
timer1.stop(mockTimer).join();
|
||||
verify(mockTimer).record(Duration.ofSeconds(20));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMultipleStart() {
|
||||
Timer mockTimer = mock(Timer.class);
|
||||
|
||||
clock.pin(Instant.ofEpochSecond(10));
|
||||
PersistentTimer.Sample timer1 = timer.start(NAMESPACE, KEY).join();
|
||||
clock.pin(Instant.ofEpochSecond(11));
|
||||
PersistentTimer.Sample timer2 = timer.start(NAMESPACE, KEY).join();
|
||||
clock.pin(Instant.ofEpochSecond(12));
|
||||
PersistentTimer.Sample timer3 = timer.start(NAMESPACE, KEY).join();
|
||||
|
||||
clock.pin(Instant.ofEpochSecond(20));
|
||||
timer2.stop(mockTimer).join();
|
||||
verify(mockTimer).record(Duration.ofSeconds(10));
|
||||
|
||||
assertThatNoException().isThrownBy(() -> timer1.stop(mockTimer).join());
|
||||
assertThatNoException().isThrownBy(() -> timer3.stop(mockTimer).join());
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+3
-2
@@ -29,6 +29,7 @@ class ReportMessageDynamoDbTest {
|
||||
void setUp() {
|
||||
this.reportMessageDynamoDb = new ReportMessageDynamoDb(
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbClient(),
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
|
||||
Tables.REPORT_MESSAGES.tableName(),
|
||||
Duration.ofDays(1));
|
||||
}
|
||||
@@ -44,8 +45,8 @@ class ReportMessageDynamoDbTest {
|
||||
() -> assertFalse(reportMessageDynamoDb.remove(hash2))
|
||||
);
|
||||
|
||||
reportMessageDynamoDb.store(hash1);
|
||||
reportMessageDynamoDb.store(hash2);
|
||||
reportMessageDynamoDb.store(hash1).join();
|
||||
reportMessageDynamoDb.store(hash2).join();
|
||||
|
||||
assertAll("both hashes should be found",
|
||||
() -> assertTrue(reportMessageDynamoDb.remove(hash1)),
|
||||
|
||||
+3
-2
@@ -18,6 +18,7 @@ import static org.mockito.Mockito.when;
|
||||
import java.time.Duration;
|
||||
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.junit.jupiter.api.extension.RegisterExtension;
|
||||
@@ -68,8 +69,8 @@ class ReportMessageManagerTest {
|
||||
|
||||
verify(reportMessageDynamoDb).store(any());
|
||||
|
||||
doThrow(RuntimeException.class)
|
||||
.when(reportMessageDynamoDb).store(any());
|
||||
when(reportMessageDynamoDb.store(any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(new RuntimeException()));
|
||||
|
||||
assertDoesNotThrow(() -> reportMessageManager.store(sourceAci.toString(), messageGuid));
|
||||
}
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.tests.util;
|
||||
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
|
||||
public class FakeDynamicConfigurationManager<T> extends DynamicConfigurationManager<T> {
|
||||
|
||||
T staticConfiguration;
|
||||
|
||||
public FakeDynamicConfigurationManager(T staticConfiguration) {
|
||||
super(null, (Class<T>) staticConfiguration.getClass());
|
||||
this.staticConfiguration = staticConfiguration;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T getConfiguration() {
|
||||
return staticConfiguration;
|
||||
}
|
||||
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.tests.util;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.List;
|
||||
|
||||
public class MultiRecipientMessageHelper {
|
||||
|
||||
private MultiRecipientMessageHelper() {
|
||||
}
|
||||
|
||||
public static byte[] generateMultiRecipientMessage(final List<TestRecipient> recipients) {
|
||||
return generateMultiRecipientMessage(recipients, 32);
|
||||
}
|
||||
|
||||
public static byte[] generateMultiRecipientMessage(final List<TestRecipient> recipients, final int sharedPayloadSize) {
|
||||
if (sharedPayloadSize < 32) {
|
||||
throw new IllegalArgumentException("Shared payload size must be at least 32 bytes");
|
||||
}
|
||||
|
||||
final ByteBuffer buffer = ByteBuffer.allocate(payloadSize(recipients, sharedPayloadSize));
|
||||
|
||||
// first write the header
|
||||
buffer.put((byte) 0x23); // version byte
|
||||
|
||||
// count varint
|
||||
writeVarint(buffer, recipients.size());
|
||||
|
||||
recipients.forEach(recipient -> {
|
||||
buffer.put(recipient.uuid().toFixedWidthByteArray());
|
||||
|
||||
assert recipient.deviceIds().length == recipient.registrationIds().length;
|
||||
|
||||
for (int i = 0; i < recipient.deviceIds().length; i++) {
|
||||
final int hasMore = i == recipient.deviceIds().length - 1 ? 0 : 0x8000;
|
||||
buffer.put(recipient.deviceIds()[i]); // device id (1 byte)
|
||||
buffer.putShort((short) (recipient.registrationIds()[i] | hasMore)); // registration id (2 bytes)
|
||||
}
|
||||
|
||||
buffer.put(recipient.perRecipientKeyMaterial()); // key material (48 bytes)
|
||||
});
|
||||
|
||||
// now write the actual message body (empty for now)
|
||||
writeVarint(buffer, sharedPayloadSize);
|
||||
buffer.put(new byte[sharedPayloadSize]);
|
||||
|
||||
return buffer.array();
|
||||
}
|
||||
|
||||
private static void writeVarint(final ByteBuffer buffer, long n) {
|
||||
if (n < 0) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
|
||||
while (n >= 0x80) {
|
||||
buffer.put ((byte) (n & 0x7F | 0x80));
|
||||
n >>= 7;
|
||||
}
|
||||
buffer.put((byte) (n & 0x7F));
|
||||
}
|
||||
|
||||
private static int payloadSize(final List<TestRecipient> recipients, final int sharedPayloadSize) {
|
||||
final int fixedBytesPerRecipient = 17 // Service identifier length
|
||||
+ 48; // Per-recipient key material
|
||||
|
||||
final int bytesForDevices = 3 * recipients.stream()
|
||||
.mapToInt(recipient -> recipient.deviceIds().length)
|
||||
.sum();
|
||||
|
||||
return 1 // Version byte
|
||||
+ varintLength(recipients.size())
|
||||
+ (recipients.size() * fixedBytesPerRecipient)
|
||||
+ bytesForDevices
|
||||
+ varintLength(sharedPayloadSize)
|
||||
+ sharedPayloadSize;
|
||||
}
|
||||
|
||||
private static int varintLength(long n) {
|
||||
int length = 0;
|
||||
|
||||
while (n >= 0x80) {
|
||||
length += 1;
|
||||
n >>= 7;
|
||||
}
|
||||
|
||||
return length + 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.tests.util;
|
||||
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
|
||||
public record TestRecipient(ServiceIdentifier uuid,
|
||||
byte[] deviceIds,
|
||||
int[] registrationIds,
|
||||
byte[] perRecipientKeyMaterial) {
|
||||
|
||||
public TestRecipient(ServiceIdentifier uuid,
|
||||
byte deviceId,
|
||||
int registrationId,
|
||||
byte[] perRecipientKeyMaterial) {
|
||||
|
||||
this(uuid, new byte[]{deviceId}, new int[]{registrationId}, perRecipientKeyMaterial);
|
||||
}
|
||||
}
|
||||
+6
-6
@@ -132,7 +132,7 @@ class WebSocketConnectionIntegrationTest {
|
||||
void testProcessStoredMessages(final int persistedMessageCount, final int cachedMessageCount) {
|
||||
final WebSocketConnection webSocketConnection = new WebSocketConnection(
|
||||
mock(ReceiptSender.class),
|
||||
new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager, sharedExecutorService),
|
||||
new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager, sharedExecutorService, Clock.systemUTC()),
|
||||
new MessageMetrics(),
|
||||
mock(PushNotificationManager.class),
|
||||
mock(PushNotificationScheduler.class),
|
||||
@@ -164,7 +164,7 @@ class WebSocketConnectionIntegrationTest {
|
||||
final UUID messageGuid = UUID.randomUUID();
|
||||
final MessageProtos.Envelope envelope = generateRandomMessage(messageGuid);
|
||||
|
||||
messagesCache.insert(messageGuid, account.getUuid(), device.getId(), envelope);
|
||||
messagesCache.insert(messageGuid, account.getUuid(), device.getId(), envelope).join();
|
||||
expectedMessages.add(envelope);
|
||||
}
|
||||
|
||||
@@ -220,7 +220,7 @@ class WebSocketConnectionIntegrationTest {
|
||||
void testProcessStoredMessagesClientClosed() {
|
||||
final WebSocketConnection webSocketConnection = new WebSocketConnection(
|
||||
mock(ReceiptSender.class),
|
||||
new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager, sharedExecutorService),
|
||||
new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager, sharedExecutorService, Clock.systemUTC()),
|
||||
new MessageMetrics(),
|
||||
mock(PushNotificationManager.class),
|
||||
mock(PushNotificationScheduler.class),
|
||||
@@ -253,7 +253,7 @@ class WebSocketConnectionIntegrationTest {
|
||||
for (int i = 0; i < cachedMessageCount; i++) {
|
||||
final UUID messageGuid = UUID.randomUUID();
|
||||
final MessageProtos.Envelope envelope = generateRandomMessage(messageGuid);
|
||||
messagesCache.insert(messageGuid, account.getUuid(), device.getId(), envelope);
|
||||
messagesCache.insert(messageGuid, account.getUuid(), device.getId(), envelope).join();
|
||||
|
||||
expectedMessages.add(envelope);
|
||||
}
|
||||
@@ -289,7 +289,7 @@ class WebSocketConnectionIntegrationTest {
|
||||
void testProcessStoredMessagesSendFutureTimeout() {
|
||||
final WebSocketConnection webSocketConnection = new WebSocketConnection(
|
||||
mock(ReceiptSender.class),
|
||||
new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager, sharedExecutorService),
|
||||
new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager, sharedExecutorService, Clock.systemUTC()),
|
||||
new MessageMetrics(),
|
||||
mock(PushNotificationManager.class),
|
||||
mock(PushNotificationScheduler.class),
|
||||
@@ -323,7 +323,7 @@ class WebSocketConnectionIntegrationTest {
|
||||
for (int i = 0; i < cachedMessageCount; i++) {
|
||||
final UUID messageGuid = UUID.randomUUID();
|
||||
final MessageProtos.Envelope envelope = generateRandomMessage(messageGuid);
|
||||
messagesCache.insert(messageGuid, account.getUuid(), device.getId(), envelope);
|
||||
messagesCache.insert(messageGuid, account.getUuid(), device.getId(), envelope).join();
|
||||
|
||||
expectedMessages.add(envelope);
|
||||
}
|
||||
|
||||
+272
@@ -0,0 +1,272 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
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.PhoneNumberUtil;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
|
||||
public class IdleWakeupEligibilityCheckerTest {
|
||||
|
||||
private static final Instant CURRENT_TIME = Instant.now();
|
||||
private final Clock clock = Clock.fixed(CURRENT_TIME, ZoneId.systemDefault());
|
||||
|
||||
private MessagesManager messagesManager;
|
||||
private IdleWakeupEligibilityChecker idleChecker;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
messagesManager = mock(MessagesManager.class);
|
||||
idleChecker = new IdleWakeupEligibilityChecker(clock, messagesManager);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void isDeviceEligible(final Account account,
|
||||
final Device device,
|
||||
final boolean mayHaveMessages,
|
||||
final boolean mayHaveUrgentMessages,
|
||||
final boolean expectEligible) {
|
||||
|
||||
when(messagesManager.mayHavePersistedMessages(account.getIdentifier(IdentityType.ACI), device))
|
||||
.thenReturn(CompletableFuture.completedFuture(mayHaveMessages));
|
||||
|
||||
when(messagesManager.mayHaveUrgentPersistedMessages(account.getIdentifier(IdentityType.ACI), device))
|
||||
.thenReturn(CompletableFuture.completedFuture(mayHaveUrgentMessages));
|
||||
|
||||
assertEquals(expectEligible, idleChecker.isDeviceEligible(account, device).join());
|
||||
}
|
||||
|
||||
private static List<Arguments> isDeviceEligible() {
|
||||
final List<Arguments> arguments = new ArrayList<>();
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getIdentifier(IdentityType.ACI)).thenReturn(UUID.randomUUID());
|
||||
when(account.getNumber()).thenReturn(PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164));
|
||||
|
||||
{
|
||||
// Long-idle device with push token and messages
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getApnId()).thenReturn("apns-token");
|
||||
when(device.getLastSeen()).thenReturn(
|
||||
CURRENT_TIME.minus(IdleWakeupEligibilityChecker.MIN_LONG_IDLE_DURATION).toEpochMilli());
|
||||
|
||||
arguments.add(Arguments.of(account, device, true, true, false));
|
||||
}
|
||||
|
||||
{
|
||||
// Long-idle device missing push token, but with messages
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getLastSeen()).thenReturn(
|
||||
CURRENT_TIME.minus(IdleWakeupEligibilityChecker.MIN_LONG_IDLE_DURATION).toEpochMilli());
|
||||
|
||||
arguments.add(Arguments.of(account, device, true, true, false));
|
||||
}
|
||||
|
||||
{
|
||||
// Long-idle device missing push token and messages
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getLastSeen()).thenReturn(
|
||||
CURRENT_TIME.minus(IdleWakeupEligibilityChecker.MIN_LONG_IDLE_DURATION).toEpochMilli());
|
||||
|
||||
arguments.add(Arguments.of(account, device, false, false, false));
|
||||
}
|
||||
|
||||
{
|
||||
// Long-idle device with push token, but no messages
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getLastSeen()).thenReturn(
|
||||
CURRENT_TIME.minus(IdleWakeupEligibilityChecker.MIN_LONG_IDLE_DURATION).toEpochMilli());
|
||||
when(device.getApnId()).thenReturn("apns-token");
|
||||
|
||||
arguments.add(Arguments.of(account, device, false, false, true));
|
||||
}
|
||||
|
||||
{
|
||||
// Short-idle device with push token and urgent messages
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getApnId()).thenReturn("apns-token");
|
||||
when(device.getLastSeen()).thenReturn(
|
||||
CURRENT_TIME.minus(IdleWakeupEligibilityChecker.MIN_SHORT_IDLE_DURATION).toEpochMilli());
|
||||
|
||||
arguments.add(Arguments.of(account, device, true, true, true));
|
||||
}
|
||||
|
||||
{
|
||||
// Short-idle device with push token and only non-urgent messages
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getApnId()).thenReturn("apns-token");
|
||||
when(device.getLastSeen()).thenReturn(
|
||||
CURRENT_TIME.minus(IdleWakeupEligibilityChecker.MIN_SHORT_IDLE_DURATION).toEpochMilli());
|
||||
|
||||
arguments.add(Arguments.of(account, device, true, false, false));
|
||||
}
|
||||
|
||||
{
|
||||
// Short-idle device missing push token, but with urgent messages
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getLastSeen()).thenReturn(
|
||||
CURRENT_TIME.minus(IdleWakeupEligibilityChecker.MIN_SHORT_IDLE_DURATION).toEpochMilli());
|
||||
|
||||
arguments.add(Arguments.of(account, device, true, true, false));
|
||||
}
|
||||
|
||||
{
|
||||
// Short-idle device missing push token and messages
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getLastSeen()).thenReturn(
|
||||
CURRENT_TIME.minus(IdleWakeupEligibilityChecker.MIN_SHORT_IDLE_DURATION).toEpochMilli());
|
||||
|
||||
arguments.add(Arguments.of(account, device, false, false, false));
|
||||
}
|
||||
|
||||
{
|
||||
// Short-idle device with push token, but no messages
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getLastSeen()).thenReturn(
|
||||
CURRENT_TIME.minus(IdleWakeupEligibilityChecker.MIN_SHORT_IDLE_DURATION).toEpochMilli());
|
||||
when(device.getApnId()).thenReturn("apns-token");
|
||||
|
||||
arguments.add(Arguments.of(account, device, false, false, false));
|
||||
}
|
||||
|
||||
{
|
||||
// Active device with push token and urgent messages
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getLastSeen()).thenReturn(CURRENT_TIME.toEpochMilli());
|
||||
when(device.getApnId()).thenReturn("apns-token");
|
||||
|
||||
arguments.add(Arguments.of(account, device, true, true, false));
|
||||
}
|
||||
|
||||
{
|
||||
// Active device missing push token, but with urgent messages
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getLastSeen()).thenReturn(CURRENT_TIME.toEpochMilli());
|
||||
|
||||
arguments.add(Arguments.of(account, device, true, true, false));
|
||||
}
|
||||
|
||||
{
|
||||
// Active device missing push token and messages
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getLastSeen()).thenReturn(CURRENT_TIME.toEpochMilli());
|
||||
|
||||
arguments.add(Arguments.of(account, device, false, false, false));
|
||||
}
|
||||
|
||||
{
|
||||
// Active device with push token, but no messages
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getLastSeen()).thenReturn(CURRENT_TIME.toEpochMilli());
|
||||
when(device.getApnId()).thenReturn("apns-token");
|
||||
|
||||
arguments.add(Arguments.of(account, device, false, false, false));
|
||||
}
|
||||
|
||||
return arguments;
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void isShortIdle(final Duration idleDuration, final boolean expectIdle) {
|
||||
final Instant currentTime = Instant.now();
|
||||
final Clock clock = Clock.fixed(currentTime, ZoneId.systemDefault());
|
||||
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getLastSeen()).thenReturn(currentTime.minus(idleDuration).toEpochMilli());
|
||||
|
||||
assertEquals(expectIdle, IdleWakeupEligibilityChecker.isShortIdle(device, clock));
|
||||
}
|
||||
|
||||
private static List<Arguments> isShortIdle() {
|
||||
return List.of(
|
||||
Arguments.of(IdleWakeupEligibilityChecker.MIN_SHORT_IDLE_DURATION, true),
|
||||
Arguments.of(IdleWakeupEligibilityChecker.MIN_SHORT_IDLE_DURATION.plusMillis(1), true),
|
||||
Arguments.of(IdleWakeupEligibilityChecker.MIN_SHORT_IDLE_DURATION.minusMillis(1), false),
|
||||
Arguments.of(IdleWakeupEligibilityChecker.MAX_SHORT_IDLE_DURATION, false),
|
||||
Arguments.of(IdleWakeupEligibilityChecker.MAX_SHORT_IDLE_DURATION.plusMillis(1), false),
|
||||
Arguments.of(IdleWakeupEligibilityChecker.MAX_SHORT_IDLE_DURATION.minusMillis(1), true)
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void isLongIdle(final Duration idleDuration, final boolean expectIdle) {
|
||||
final Instant currentTime = Instant.now();
|
||||
final Clock clock = Clock.fixed(currentTime, ZoneId.systemDefault());
|
||||
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getLastSeen()).thenReturn(currentTime.minus(idleDuration).toEpochMilli());
|
||||
|
||||
assertEquals(expectIdle, IdleWakeupEligibilityChecker.isLongIdle(device, clock));
|
||||
}
|
||||
|
||||
private static List<Arguments> isLongIdle() {
|
||||
return List.of(
|
||||
Arguments.of(IdleWakeupEligibilityChecker.MIN_LONG_IDLE_DURATION, true),
|
||||
Arguments.of(IdleWakeupEligibilityChecker.MIN_LONG_IDLE_DURATION.plusMillis(1), true),
|
||||
Arguments.of(IdleWakeupEligibilityChecker.MIN_LONG_IDLE_DURATION.minusMillis(1), false),
|
||||
Arguments.of(IdleWakeupEligibilityChecker.MAX_LONG_IDLE_DURATION, false),
|
||||
Arguments.of(IdleWakeupEligibilityChecker.MAX_LONG_IDLE_DURATION.plusMillis(1), false),
|
||||
Arguments.of(IdleWakeupEligibilityChecker.MAX_LONG_IDLE_DURATION.minusMillis(1), true)
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void hasPushToken(final Device device, final boolean expectHasPushToken) {
|
||||
assertEquals(expectHasPushToken, IdleWakeupEligibilityChecker.hasPushToken(device));
|
||||
}
|
||||
|
||||
private static List<Arguments> hasPushToken() {
|
||||
final List<Arguments> arguments = new ArrayList<>();
|
||||
|
||||
{
|
||||
// No token at all
|
||||
final Device device = mock(Device.class);
|
||||
|
||||
arguments.add(Arguments.of(device, false));
|
||||
}
|
||||
|
||||
{
|
||||
// FCM token
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getGcmId()).thenReturn("fcm-token");
|
||||
|
||||
arguments.add(Arguments.of(device, true));
|
||||
}
|
||||
|
||||
{
|
||||
// APNs token
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getApnId()).thenReturn("apns-token");
|
||||
|
||||
arguments.add(Arguments.of(device, true));
|
||||
}
|
||||
|
||||
return arguments;
|
||||
}
|
||||
}
|
||||
+1
-227
@@ -8,12 +8,9 @@ import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
@@ -21,8 +18,6 @@ import java.util.concurrent.CompletableFuture;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.push.IdleDeviceNotificationScheduler;
|
||||
@@ -124,7 +119,7 @@ class NotifyIdleDevicesCommandTest {
|
||||
when(eligibleDevice.getId()).thenReturn(Device.PRIMARY_ID);
|
||||
when(eligibleDevice.getApnId()).thenReturn("apns-token");
|
||||
when(eligibleDevice.getLastSeen())
|
||||
.thenReturn(CURRENT_TIME.minus(NotifyIdleDevicesCommand.MIN_LONG_IDLE_DURATION).toEpochMilli());
|
||||
.thenReturn(CURRENT_TIME.minus(IdleWakeupEligibilityChecker.MIN_LONG_IDLE_DURATION).toEpochMilli());
|
||||
|
||||
final Device ineligibleDevice = mock(Device.class);
|
||||
when(ineligibleDevice.getId()).thenReturn((byte) (Device.PRIMARY_ID + 1));
|
||||
@@ -147,225 +142,4 @@ class NotifyIdleDevicesCommandTest {
|
||||
|
||||
verify(idleDeviceNotificationScheduler, never()).scheduleNotification(eq(account), eq(ineligibleDevice), any());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void isDeviceEligible(final Account account,
|
||||
final Device device,
|
||||
final boolean mayHaveMessages,
|
||||
final boolean mayHaveUrgentMessages,
|
||||
final boolean expectEligible) {
|
||||
|
||||
when(messagesManager.mayHavePersistedMessages(account.getIdentifier(IdentityType.ACI), device))
|
||||
.thenReturn(CompletableFuture.completedFuture(mayHaveMessages));
|
||||
|
||||
when(messagesManager.mayHaveUrgentPersistedMessages(account.getIdentifier(IdentityType.ACI), device))
|
||||
.thenReturn(CompletableFuture.completedFuture(mayHaveUrgentMessages));
|
||||
|
||||
assertEquals(expectEligible,
|
||||
NotifyIdleDevicesCommand.isDeviceEligible(account, device, messagesManager, Clock.fixed(CURRENT_TIME, ZoneId.systemDefault())).block());
|
||||
}
|
||||
|
||||
private static List<Arguments> isDeviceEligible() {
|
||||
final List<Arguments> arguments = new ArrayList<>();
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getIdentifier(IdentityType.ACI)).thenReturn(UUID.randomUUID());
|
||||
when(account.getNumber()).thenReturn(PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164));
|
||||
|
||||
{
|
||||
// Long-idle device with push token and messages
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getApnId()).thenReturn("apns-token");
|
||||
when(device.getLastSeen()).thenReturn(CURRENT_TIME.minus(NotifyIdleDevicesCommand.MIN_LONG_IDLE_DURATION).toEpochMilli());
|
||||
|
||||
arguments.add(Arguments.of(account, device, true, true, false));
|
||||
}
|
||||
|
||||
{
|
||||
// Long-idle device missing push token, but with messages
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getLastSeen()).thenReturn(CURRENT_TIME.minus(NotifyIdleDevicesCommand.MIN_LONG_IDLE_DURATION).toEpochMilli());
|
||||
|
||||
arguments.add(Arguments.of(account, device, true, true, false));
|
||||
}
|
||||
|
||||
{
|
||||
// Long-idle device missing push token and messages
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getLastSeen()).thenReturn(CURRENT_TIME.minus(NotifyIdleDevicesCommand.MIN_LONG_IDLE_DURATION).toEpochMilli());
|
||||
|
||||
arguments.add(Arguments.of(account, device, false, false, false));
|
||||
}
|
||||
|
||||
{
|
||||
// Long-idle device with push token, but no messages
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getLastSeen()).thenReturn(CURRENT_TIME.minus(NotifyIdleDevicesCommand.MIN_LONG_IDLE_DURATION).toEpochMilli());
|
||||
when(device.getApnId()).thenReturn("apns-token");
|
||||
|
||||
arguments.add(Arguments.of(account, device, false, false, true));
|
||||
}
|
||||
|
||||
{
|
||||
// Short-idle device with push token and urgent messages
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getApnId()).thenReturn("apns-token");
|
||||
when(device.getLastSeen()).thenReturn(CURRENT_TIME.minus(NotifyIdleDevicesCommand.MIN_SHORT_IDLE_DURATION).toEpochMilli());
|
||||
|
||||
arguments.add(Arguments.of(account, device, true, true, true));
|
||||
}
|
||||
|
||||
{
|
||||
// Short-idle device with push token and only non-urgent messages
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getApnId()).thenReturn("apns-token");
|
||||
when(device.getLastSeen()).thenReturn(CURRENT_TIME.minus(NotifyIdleDevicesCommand.MIN_SHORT_IDLE_DURATION).toEpochMilli());
|
||||
|
||||
arguments.add(Arguments.of(account, device, true, false, false));
|
||||
}
|
||||
|
||||
{
|
||||
// Short-idle device missing push token, but with urgent messages
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getLastSeen()).thenReturn(CURRENT_TIME.minus(NotifyIdleDevicesCommand.MIN_SHORT_IDLE_DURATION).toEpochMilli());
|
||||
|
||||
arguments.add(Arguments.of(account, device, true, true, false));
|
||||
}
|
||||
|
||||
{
|
||||
// Short-idle device missing push token and messages
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getLastSeen()).thenReturn(CURRENT_TIME.minus(NotifyIdleDevicesCommand.MIN_SHORT_IDLE_DURATION).toEpochMilli());
|
||||
|
||||
arguments.add(Arguments.of(account, device, false, false, false));
|
||||
}
|
||||
|
||||
{
|
||||
// Short-idle device with push token, but no messages
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getLastSeen()).thenReturn(CURRENT_TIME.minus(NotifyIdleDevicesCommand.MIN_SHORT_IDLE_DURATION).toEpochMilli());
|
||||
when(device.getApnId()).thenReturn("apns-token");
|
||||
|
||||
arguments.add(Arguments.of(account, device, false, false, false));
|
||||
}
|
||||
|
||||
{
|
||||
// Active device with push token and urgent messages
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getLastSeen()).thenReturn(CURRENT_TIME.toEpochMilli());
|
||||
when(device.getApnId()).thenReturn("apns-token");
|
||||
|
||||
arguments.add(Arguments.of(account, device, true, true, false));
|
||||
}
|
||||
|
||||
{
|
||||
// Active device missing push token, but with urgent messages
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getLastSeen()).thenReturn(CURRENT_TIME.toEpochMilli());
|
||||
|
||||
arguments.add(Arguments.of(account, device, true, true, false));
|
||||
}
|
||||
|
||||
{
|
||||
// Active device missing push token and messages
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getLastSeen()).thenReturn(CURRENT_TIME.toEpochMilli());
|
||||
|
||||
arguments.add(Arguments.of(account, device, false, false, false));
|
||||
}
|
||||
|
||||
{
|
||||
// Active device with push token, but no messages
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getLastSeen()).thenReturn(CURRENT_TIME.toEpochMilli());
|
||||
when(device.getApnId()).thenReturn("apns-token");
|
||||
|
||||
arguments.add(Arguments.of(account, device, false, false, false));
|
||||
}
|
||||
|
||||
return arguments;
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void isShortIdle(final Duration idleDuration, final boolean expectIdle) {
|
||||
final Instant currentTime = Instant.now();
|
||||
final Clock clock = Clock.fixed(currentTime, ZoneId.systemDefault());
|
||||
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getLastSeen()).thenReturn(currentTime.minus(idleDuration).toEpochMilli());
|
||||
|
||||
assertEquals(expectIdle, NotifyIdleDevicesCommand.isShortIdle(device, clock));
|
||||
}
|
||||
|
||||
private static List<Arguments> isShortIdle() {
|
||||
return List.of(
|
||||
Arguments.of(NotifyIdleDevicesCommand.MIN_SHORT_IDLE_DURATION, true),
|
||||
Arguments.of(NotifyIdleDevicesCommand.MIN_SHORT_IDLE_DURATION.plusMillis(1), true),
|
||||
Arguments.of(NotifyIdleDevicesCommand.MIN_SHORT_IDLE_DURATION.minusMillis(1), false),
|
||||
Arguments.of(NotifyIdleDevicesCommand.MAX_SHORT_IDLE_DURATION, false),
|
||||
Arguments.of(NotifyIdleDevicesCommand.MAX_SHORT_IDLE_DURATION.plusMillis(1), false),
|
||||
Arguments.of(NotifyIdleDevicesCommand.MAX_SHORT_IDLE_DURATION.minusMillis(1), true)
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void isLongIdle(final Duration idleDuration, final boolean expectIdle) {
|
||||
final Instant currentTime = Instant.now();
|
||||
final Clock clock = Clock.fixed(currentTime, ZoneId.systemDefault());
|
||||
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getLastSeen()).thenReturn(currentTime.minus(idleDuration).toEpochMilli());
|
||||
|
||||
assertEquals(expectIdle, NotifyIdleDevicesCommand.isLongIdle(device, clock));
|
||||
}
|
||||
|
||||
private static List<Arguments> isLongIdle() {
|
||||
return List.of(
|
||||
Arguments.of(NotifyIdleDevicesCommand.MIN_LONG_IDLE_DURATION, true),
|
||||
Arguments.of(NotifyIdleDevicesCommand.MIN_LONG_IDLE_DURATION.plusMillis(1), true),
|
||||
Arguments.of(NotifyIdleDevicesCommand.MIN_LONG_IDLE_DURATION.minusMillis(1), false),
|
||||
Arguments.of(NotifyIdleDevicesCommand.MAX_LONG_IDLE_DURATION, false),
|
||||
Arguments.of(NotifyIdleDevicesCommand.MAX_LONG_IDLE_DURATION.plusMillis(1), false),
|
||||
Arguments.of(NotifyIdleDevicesCommand.MAX_LONG_IDLE_DURATION.minusMillis(1), true)
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void hasPushToken(final Device device, final boolean expectHasPushToken) {
|
||||
assertEquals(expectHasPushToken, NotifyIdleDevicesCommand.hasPushToken(device));
|
||||
}
|
||||
|
||||
private static List<Arguments> hasPushToken() {
|
||||
final List<Arguments> arguments = new ArrayList<>();
|
||||
|
||||
{
|
||||
// No token at all
|
||||
final Device device = mock(Device.class);
|
||||
|
||||
arguments.add(Arguments.of(device, false));
|
||||
}
|
||||
|
||||
{
|
||||
// FCM token
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getGcmId()).thenReturn("fcm-token");
|
||||
|
||||
arguments.add(Arguments.of(device, true));
|
||||
}
|
||||
|
||||
{
|
||||
// APNs token
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getApnId()).thenReturn("apns-token");
|
||||
|
||||
arguments.add(Arguments.of(device, true));
|
||||
}
|
||||
|
||||
return arguments;
|
||||
}
|
||||
}
|
||||
@@ -508,3 +508,6 @@ externalRequestFilter:
|
||||
- /example
|
||||
permittedInternalRanges:
|
||||
- 127.0.0.0/8
|
||||
|
||||
idlePrimaryDeviceReminder:
|
||||
minIdleDuration: P30D
|
||||
+1
-1
Submodule spam-filter updated: c9a4cb27b2...0e075eac15.
+3
@@ -76,6 +76,9 @@ public class WebSocketResourceProviderFactory<T extends Principal> extends Jetty
|
||||
authenticated = ReusableAuth.anonymous();
|
||||
}
|
||||
|
||||
Optional.ofNullable(environment.getAuthenticatedWebSocketUpgradeFilter())
|
||||
.ifPresent(filter -> filter.handleAuthentication(authenticated, request, response));
|
||||
|
||||
return new WebSocketResourceProvider<>(getRemoteAddress(request),
|
||||
remoteAddressPropertyName,
|
||||
this.jerseyApplicationHandler,
|
||||
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.websocket.auth;
|
||||
|
||||
import java.security.Principal;
|
||||
import org.eclipse.jetty.websocket.server.JettyServerUpgradeRequest;
|
||||
import org.eclipse.jetty.websocket.server.JettyServerUpgradeResponse;
|
||||
import org.whispersystems.websocket.ReusableAuth;
|
||||
|
||||
public interface AuthenticatedWebSocketUpgradeFilter<T extends Principal> {
|
||||
|
||||
void handleAuthentication(ReusableAuth<T> authenticated,
|
||||
JettyServerUpgradeRequest request,
|
||||
JettyServerUpgradeResponse response);
|
||||
}
|
||||
+13
@@ -11,11 +11,13 @@ import jakarta.validation.Validator;
|
||||
import java.security.Principal;
|
||||
import java.time.Duration;
|
||||
import org.glassfish.jersey.server.ResourceConfig;
|
||||
import org.whispersystems.websocket.auth.AuthenticatedWebSocketUpgradeFilter;
|
||||
import org.whispersystems.websocket.auth.WebSocketAuthenticator;
|
||||
import org.whispersystems.websocket.configuration.WebSocketConfiguration;
|
||||
import org.whispersystems.websocket.logging.WebsocketRequestLog;
|
||||
import org.whispersystems.websocket.messages.WebSocketMessageFactory;
|
||||
import org.whispersystems.websocket.messages.protobuf.ProtobufWebSocketMessageFactory;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
public class WebSocketEnvironment<T extends Principal> {
|
||||
|
||||
@@ -26,6 +28,7 @@ public class WebSocketEnvironment<T extends Principal> {
|
||||
private final Duration idleTimeout;
|
||||
|
||||
private WebSocketAuthenticator<T> authenticator;
|
||||
private AuthenticatedWebSocketUpgradeFilter<T> authenticatedWebSocketUpgradeFilter;
|
||||
private WebSocketMessageFactory messageFactory;
|
||||
private WebSocketConnectListener connectListener;
|
||||
|
||||
@@ -50,6 +53,7 @@ public class WebSocketEnvironment<T extends Principal> {
|
||||
return jerseyConfig;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public WebSocketAuthenticator<T> getAuthenticator() {
|
||||
return authenticator;
|
||||
}
|
||||
@@ -58,6 +62,15 @@ public class WebSocketEnvironment<T extends Principal> {
|
||||
this.authenticator = authenticator;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public AuthenticatedWebSocketUpgradeFilter<T> getAuthenticatedWebSocketUpgradeFilter() {
|
||||
return authenticatedWebSocketUpgradeFilter;
|
||||
}
|
||||
|
||||
public void setAuthenticatedWebSocketUpgradeFilter(final AuthenticatedWebSocketUpgradeFilter<T> authenticatedWebSocketUpgradeFilter) {
|
||||
this.authenticatedWebSocketUpgradeFilter = authenticatedWebSocketUpgradeFilter;
|
||||
}
|
||||
|
||||
public Duration getIdleTimeout() {
|
||||
return idleTimeout;
|
||||
}
|
||||
|
||||
+24
@@ -27,6 +27,7 @@ import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.websocket.auth.AuthenticationException;
|
||||
import org.whispersystems.websocket.auth.PrincipalSupplier;
|
||||
import org.whispersystems.websocket.auth.AuthenticatedWebSocketUpgradeFilter;
|
||||
import org.whispersystems.websocket.auth.WebSocketAuthenticator;
|
||||
import org.whispersystems.websocket.configuration.WebSocketConfiguration;
|
||||
import org.whispersystems.websocket.setup.WebSocketEnvironment;
|
||||
@@ -125,6 +126,29 @@ public class WebSocketResourceProviderFactoryTest {
|
||||
verify(servletFactory).setCreator(eq(factory));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAuthenticatedWebSocketUpgradeFilter() throws AuthenticationException {
|
||||
final Account account = new Account();
|
||||
final ReusableAuth<Account> reusableAuth =
|
||||
ReusableAuth.authenticated(account, PrincipalSupplier.forImmutablePrincipal());
|
||||
|
||||
when(environment.getAuthenticator()).thenReturn(authenticator);
|
||||
when(authenticator.authenticate(eq(request))).thenReturn(reusableAuth);
|
||||
when(environment.jersey()).thenReturn(jerseyEnvironment);
|
||||
final HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
|
||||
when(httpServletRequest.getAttribute(REMOTE_ADDRESS_PROPERTY_NAME)).thenReturn("127.0.0.1");
|
||||
when(request.getHttpServletRequest()).thenReturn(httpServletRequest);
|
||||
|
||||
final AuthenticatedWebSocketUpgradeFilter<Account> filter = mock(AuthenticatedWebSocketUpgradeFilter.class);
|
||||
when(environment.getAuthenticatedWebSocketUpgradeFilter()).thenReturn(filter);
|
||||
|
||||
final WebSocketResourceProviderFactory<?> factory = new WebSocketResourceProviderFactory<>(environment, Account.class,
|
||||
mock(WebSocketConfiguration.class), REMOTE_ADDRESS_PROPERTY_NAME);
|
||||
assertNotNull(factory.createWebSocket(request, response));
|
||||
|
||||
verify(filter).handleAuthentication(reusableAuth, request, response);
|
||||
}
|
||||
|
||||
|
||||
private static class Account implements Principal {
|
||||
@Override
|
||||
|
||||
Reference in new issue
Block a user