Compare commits

...
Author SHA1 Message Date
Ravi Khadiwala 80cd5d9ccc Increase message cache TTL to 46 days 2024-10-02 14:05:40 -05:00
Ravi Khadiwala 0eb7db8de5 Increase the linked device idle timeout to 45 days 2024-10-02 14:05:40 -05:00
Jon Chambers 100955a7db Migrate WebSocket duration instrumentation to OpenWebSocketCounter 2024-10-02 14:02:03 -05:00
Chris Eager 68814813c3 Add timestamp header to all responses 2024-10-02 14:01:19 -05:00
Jon Chambers 39590f1b28 Update to the latest version of the spam filter 2024-10-01 14:27:06 -04:00
Jon Chambers 92698efd39 Remove machinery for setting/storing APNs VOIP tokens 2024-10-01 14:17:39 -04:00
Jon Chambers b693cb98d0 Remove recurring background VOIP notification machinery 2024-10-01 14:17:39 -04:00
Jon Chambers 3ed142d0a9 Introduce OpenWebSocketCounter 2024-10-01 14:17:17 -04:00
Jon Chambers 581e61a85b Count open provisioning WebSockets 2024-10-01 14:17:17 -04:00
Jon Chambers 764b200289 Clarify open websocket gauge name 2024-10-01 14:17:17 -04:00
Jon Chambers 26503dffdf Use a consistent provisioning address 2024-10-01 13:34:37 -04:00
Jon Chambers b284e95394 Clarify ProvisioningAddress field naming 2024-10-01 12:59:58 -04:00
Jon Chambers b2211de8d8 Retire ProvisioningAddress and WebsocketAddress 2024-10-01 12:59:58 -04:00
Ameya Lokare 1bb0eb0e70 Integer comparison of captcha scores 2024-10-01 08:42:12 -07:00
Jon Chambers 0a1161048f Document ProvisioningController and ProvisioningConnectListener 2024-10-01 11:40:40 -04:00
Ameya Lokare 7a6ce00fed Add senderType tag to sendMessageLatency timer
This will allow us to differentiate between sealed vs unsealed sends
latency
2024-09-27 17:35:20 -04:00
Jon Chambers c0aa9ced8d Temporarily disable AWS SDK instrumentation 2024-09-27 17:34:46 -04:00
Jon Chambers 6b36df3f8f Remove unused imports/loggers 2024-09-27 17:34:46 -04:00
Jon Chambers df3caeb04a Expand the scope of the "notify idle devices" job to cover short-idle devices WITH messages 2024-09-27 16:30:51 -04:00
Jon Chambers 0e267509da Add a method for checking for persisted urgent messages 2024-09-27 16:30:51 -04:00
Jon Chambers bbe41278ed Drop an unused hasCachedMessages method 2024-09-27 16:30:51 -04:00
Jon Chambers d91a6b0c38 Retire the "notify idle devices with messages" experiment 2024-09-27 16:30:51 -04:00
Jon Chambers 694a93db6d Explicitly look for sha256sum inputs via stdin 2024-09-27 09:39:19 -04:00
Ameya Lokare 2f2dec87b1 Update to the latest version of the spam filter 2024-09-26 13:03:05 -07:00
Ameya Lokare 098288c290 Update to the latest version of the spam filter 2024-09-26 12:56:09 -07:00
Chris Eager ab2e6bb9a3 Use Mono.share() for mrmMessageMono 2024-09-26 14:48:06 -05:00
Chris Eager 513f19370a Add Experiment#compareMonoResult 2024-09-26 14:48:06 -05:00
Chris Eager e20a4c1f77 Refactor ProcessScheduledJobsServiceCommand to dispose of processing jobs on shutdown 2024-09-26 14:12:12 -05:00
Jon Chambers 946a486c4b Add metric publishers to DynamoDB clients 2024-09-26 15:00:10 -04:00
Jon Chambers 78b40397f9 Simplify metric publisher lifecycles 2024-09-26 15:00:10 -04:00
Jon Chambers 48e8d1c12f Add comments and constants to clarify the structure of metric collections 2024-09-26 15:00:10 -04:00
Jon Chambers b115e95da4 Add an AWS SDK metric publisher 2024-09-26 15:00:10 -04:00
Chris Eager ab0892cc41 Set executor shutdown time in ProcessScheduledJobsServiceCommand 2024-09-26 13:57:20 -05:00
Chris Eager e25291c74c Move MRM content parsing outside of “withBinaryClusterReactive” 2024-09-26 13:57:02 -05:00
Ravi Khadiwala 0e552bd602 Cancel play subscriptions when replacing them 2024-09-26 13:56:10 -05:00
Ameya Lokare e9b3e15556 Return report spam token from spam check instead of separate call 2024-09-26 11:53:40 -07:00
Ravi Khadiwala 237d0fd4e2 remove HTTP layer exceptions from Stripe/Braintree managers 2024-09-24 17:22:38 -05:00
Ravi Khadiwala 50bd30fb1f Fix cancelAtPeriodEnd calculation 2024-09-24 17:14:08 -05:00
Ravi Khadiwala 9fb4e2d272 set billingCycleAnchor in play billing responses 2024-09-24 17:14:08 -05:00
Jon Chambers 3e51366921 Narrow selection criterial for "notify idle devices with messages" experiment 2024-09-23 16:01:44 -04:00
Jonathan Klabunde Tomer 2d184b1ab6 return user's own username link handle in /whoami response 2024-09-23 12:46:10 -07:00
adel-signal befcdf55fe Balance TURN routing options across datacenters 2024-09-23 12:43:43 -07:00
Ravi Khadiwala ba12d39121 URLEncode shortCode paths 2024-09-23 14:43:15 -05:00
Ravi Khadiwala bf0f553ced Don't return 204s as exceptions
The jersey LoggingExceptionMapper automatically adds an entity to
WebApplicationExceptions. Jersey's HTTP server later strips the body on
204 responses, but our custom WebSocketResourceProvider does not
2024-09-23 14:43:04 -05:00
Chris Eager cd68a674bb Update protobuf-java to 3.25.5 2024-09-23 08:43:55 -05:00
Jon Chambers 315fc00eac Lazily evaluate jobs to give max concurrency meaningful "teeth" 2024-09-23 08:43:44 -05:00
Ameya Lokare 6142dcc7e6 Update to the latest version of the spam filter 2024-09-19 12:56:10 -07:00
Jonathan Klabunde Tomer c47141ffda yield json errors from 500s in sendMultiRecipientMessage 2024-09-19 12:36:52 -07:00
Jon Chambers 6c8566db60 Align "allocate device" and "verify device" default rate limits 2024-09-19 14:59:06 -04:00
97 changed files with 1596 additions and 1582 deletions

No files matched your search

@@ -10,6 +10,7 @@ import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import org.signal.integration.config.Config;
import org.whispersystems.textsecuregcm.metrics.NoopAwsSdkMetricPublisher;
import org.whispersystems.textsecuregcm.registration.VerificationSession;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswords;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
@@ -30,9 +31,11 @@ public class IntegrationTools {
public static IntegrationTools create(final Config config) {
final AwsCredentialsProvider credentialsProvider = DefaultCredentialsProvider.builder().build();
final DynamoDbAsyncClient dynamoDbAsyncClient = config.dynamoDbClient().buildAsyncClient(credentialsProvider);
final DynamoDbAsyncClient dynamoDbAsyncClient =
config.dynamoDbClient().buildAsyncClient(credentialsProvider, new NoopAwsSdkMetricPublisher());
final DynamoDbClient dynamoDbClient = config.dynamoDbClient().buildSyncClient(credentialsProvider);
final DynamoDbClient dynamoDbClient =
config.dynamoDbClient().buildSyncClient(credentialsProvider, new NoopAwsSdkMetricPublisher());
final RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
config.dynamoDbTables().registrationRecovery(), Duration.ofDays(1), dynamoDbClient, dynamoDbAsyncClient);
Vendored
+1 -1
View File
@@ -260,7 +260,7 @@ done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties"
if [ -n "$wrapperSha256Sum" ]; then
wrapperSha256Result=false
if command -v sha256sum > /dev/null; then
if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c > /dev/null 2>&1; then
if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c - > /dev/null 2>&1; then
wrapperSha256Result=true
fi
elif command -v shasum > /dev/null; then
+1 -1
View File
@@ -63,7 +63,7 @@
<luajava.version>3.4.0</luajava.version>
<micrometer.version>1.13.2</micrometer.version>
<netty.version>4.1.111.Final</netty.version>
<protobuf.version>3.25.2</protobuf.version> <!-- should be kept in sync with the value from Google libraries-bom -->
<protobuf.version>3.25.5</protobuf.version> <!-- must be greater than or equal to the value from Google libraries-bom, see https://protobuf.dev/support/cross-version-runtime-guarantee/ -->
<pushy.version>0.15.4</pushy.version>
<reactive.grpc.version>1.2.4</reactive.grpc.version>
<reactor-bom.version>2023.0.8</reactor-bom.version> <!-- 3.6.x, see https://github.com/reactor/reactor#bom-versioning-scheme -->
@@ -113,7 +113,6 @@ import org.whispersystems.textsecuregcm.controllers.ArtController;
import org.whispersystems.textsecuregcm.controllers.AttachmentControllerV2;
import org.whispersystems.textsecuregcm.controllers.AttachmentControllerV3;
import org.whispersystems.textsecuregcm.controllers.AttachmentControllerV4;
import org.whispersystems.textsecuregcm.controllers.OneTimeDonationController;
import org.whispersystems.textsecuregcm.controllers.CallLinkController;
import org.whispersystems.textsecuregcm.controllers.CallRoutingController;
import org.whispersystems.textsecuregcm.controllers.CertificateController;
@@ -125,6 +124,7 @@ import org.whispersystems.textsecuregcm.controllers.KeepAliveController;
import org.whispersystems.textsecuregcm.controllers.KeyTransparencyController;
import org.whispersystems.textsecuregcm.controllers.KeysController;
import org.whispersystems.textsecuregcm.controllers.MessageController;
import org.whispersystems.textsecuregcm.controllers.OneTimeDonationController;
import org.whispersystems.textsecuregcm.controllers.PaymentsController;
import org.whispersystems.textsecuregcm.controllers.ProfileController;
import org.whispersystems.textsecuregcm.controllers.ProvisioningController;
@@ -182,22 +182,22 @@ import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper
import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.ServerRejectedExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.SubscriptionProcessorExceptionMapper;
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
import org.whispersystems.textsecuregcm.metrics.MetricsApplicationEventListener;
import org.whispersystems.textsecuregcm.metrics.MetricsHttpChannelListener;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.MicrometerAwsSdkMetricPublisher;
import org.whispersystems.textsecuregcm.metrics.ReportedMessageMetricsListener;
import org.whispersystems.textsecuregcm.metrics.TrafficSource;
import org.whispersystems.textsecuregcm.providers.MultiRecipientMessageProvider;
import org.whispersystems.textsecuregcm.providers.RedisClusterHealthCheck;
import org.whispersystems.textsecuregcm.push.APNSender;
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
import org.whispersystems.textsecuregcm.push.FcmSender;
import org.whispersystems.textsecuregcm.push.MessageSender;
import org.whispersystems.textsecuregcm.push.ProvisioningManager;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
import org.whispersystems.textsecuregcm.push.ReceiptSender;
import org.whispersystems.textsecuregcm.redis.ConnectionEventLogger;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
@@ -209,7 +209,6 @@ import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2
import org.whispersystems.textsecuregcm.spam.ChallengeConstraintChecker;
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
import org.whispersystems.textsecuregcm.spam.RegistrationRecoveryChecker;
import org.whispersystems.textsecuregcm.spam.ReportSpamTokenProvider;
import org.whispersystems.textsecuregcm.spam.SpamChecker;
import org.whispersystems.textsecuregcm.spam.SpamFilter;
import org.whispersystems.textsecuregcm.storage.AccountLockManager;
@@ -262,12 +261,9 @@ import org.whispersystems.textsecuregcm.workers.BackupMetricsCommand;
import org.whispersystems.textsecuregcm.workers.CertificateCommand;
import org.whispersystems.textsecuregcm.workers.CheckDynamicConfigurationCommand;
import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
import org.whispersystems.textsecuregcm.workers.DiscardPushNotificationExperimentSamplesCommand;
import org.whispersystems.textsecuregcm.workers.FinishPushNotificationExperimentCommand;
import org.whispersystems.textsecuregcm.workers.IdleDeviceNotificationSchedulerFactory;
import org.whispersystems.textsecuregcm.workers.MessagePersisterServiceCommand;
import org.whispersystems.textsecuregcm.workers.NotifyIdleDevicesWithMessagesExperimentFactory;
import org.whispersystems.textsecuregcm.workers.NotifyIdleDevicesWithoutMessagesCommand;
import org.whispersystems.textsecuregcm.workers.NotifyIdleDevicesCommand;
import org.whispersystems.textsecuregcm.workers.ProcessScheduledJobsServiceCommand;
import org.whispersystems.textsecuregcm.workers.RemoveExpiredAccountsCommand;
import org.whispersystems.textsecuregcm.workers.RemoveExpiredBackupsCommand;
@@ -277,7 +273,6 @@ import org.whispersystems.textsecuregcm.workers.ScheduledApnPushNotificationSend
import org.whispersystems.textsecuregcm.workers.ServerVersionCommand;
import org.whispersystems.textsecuregcm.workers.SetRequestLoggingEnabledTask;
import org.whispersystems.textsecuregcm.workers.SetUserDiscoverabilityCommand;
import org.whispersystems.textsecuregcm.workers.StartPushNotificationExperimentCommand;
import org.whispersystems.textsecuregcm.workers.UnlinkDeviceCommand;
import org.whispersystems.textsecuregcm.workers.ZkParamsCommand;
import org.whispersystems.websocket.WebSocketResourceProviderFactory;
@@ -331,25 +326,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
bootstrap.addCommand(new RemoveExpiredBackupsCommand(Clock.systemUTC()));
bootstrap.addCommand(new BackupMetricsCommand(Clock.systemUTC()));
bootstrap.addCommand(new RemoveExpiredLinkedDevicesCommand());
bootstrap.addCommand(new NotifyIdleDevicesWithoutMessagesCommand());
bootstrap.addCommand(new NotifyIdleDevicesCommand());
bootstrap.addCommand(new ProcessScheduledJobsServiceCommand("process-idle-device-notification-jobs",
"Processes scheduled jobs to send notifications to idle devices",
new IdleDeviceNotificationSchedulerFactory()));
bootstrap.addCommand(
new StartPushNotificationExperimentCommand<>("start-notify-idle-devices-with-messages-experiment",
"Start an experiment to send push notifications to idle devices with pending messages",
new NotifyIdleDevicesWithMessagesExperimentFactory()));
bootstrap.addCommand(
new FinishPushNotificationExperimentCommand<>("finish-notify-idle-devices-with-messages-experiment",
"Finish an experiment to send push notifications to idle devices with pending messages",
new NotifyIdleDevicesWithMessagesExperimentFactory()));
bootstrap.addCommand(
new DiscardPushNotificationExperimentSamplesCommand("discard-notify-idle-devices-with-messages-samples",
"Discard samples from the \"notify idle devices with messages\" experiment",
new NotifyIdleDevicesWithMessagesExperimentFactory()));
}
@Override
@@ -395,10 +375,15 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
BankMandateTranslator bankMandateTranslator = new BankMandateTranslator(headerControlledResourceBundleLookup);
environment.lifecycle().manage(new ManagedAwsCrt());
DynamoDbAsyncClient dynamoDbAsyncClient = config.getDynamoDbClientConfiguration()
.buildAsyncClient(awsCredentialsProvider);
DynamoDbClient dynamoDbClient = config.getDynamoDbClientConfiguration().buildSyncClient(awsCredentialsProvider);
final ExecutorService awsSdkMetricsExecutor = environment.lifecycle()
.virtualExecutorService(name(getClass(), "awsSdkMetrics-%d"));
final DynamoDbAsyncClient dynamoDbAsyncClient = config.getDynamoDbClientConfiguration()
.buildAsyncClient(awsCredentialsProvider, new MicrometerAwsSdkMetricPublisher(awsSdkMetricsExecutor, "dynamoDbAsync"));
final DynamoDbClient dynamoDbClient = config.getDynamoDbClientConfiguration()
.buildSyncClient(awsCredentialsProvider, new MicrometerAwsSdkMetricPublisher(awsSdkMetricsExecutor, "dynamoDbSync"));
BlockingQueue<Runnable> messageDeletionQueue = new LinkedBlockingQueue<>();
Metrics.gaugeCollectionSize(name(getClass(), "messageDeletionQueueSize"), Collections.emptyList(),
@@ -974,6 +959,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final List<Filter> filters = new ArrayList<>();
filters.add(remoteDeprecationFilter);
filters.add(new RemoteAddressFilter());
filters.add(new TimestampResponseFilter());
for (Filter filter : filters) {
environment.servlets()
@@ -1028,7 +1014,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
webSocketEnvironment.jersey().register(MultiRecipientMessageProvider.class);
webSocketEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET, clientReleaseManager));
webSocketEnvironment.jersey().register(new KeepAliveController(clientPresenceManager));
webSocketEnvironment.jersey().register(new TimestampResponseFilter());
final List<SpamFilter> spamFilters = ServiceLoader.load(SpamFilter.class)
.stream()
@@ -1050,12 +1036,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
if (spamFilter.isEmpty()) {
log.warn("No spam filters installed");
}
final ReportSpamTokenProvider reportSpamTokenProvider = spamFilter
.map(SpamFilter::getReportSpamTokenProvider)
.orElseGet(() -> {
log.warn("No spam-reporting token providers found; using default (no-op) provider as a default");
return ReportSpamTokenProvider.noop();
});
final SpamChecker spamChecker = spamFilter
.map(SpamFilter::getSpamChecker)
.orElseGet(() -> {
@@ -1124,7 +1104,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new KeyTransparencyController(keyTransparencyServiceClient),
new MessageController(rateLimiters, messageByteLimitCardinalityEstimator, messageSender, receiptSender,
accountsManager, messagesManager, pushNotificationManager, pushNotificationScheduler, reportMessageManager,
multiRecipientMessageExecutor, messageDeliveryScheduler, reportSpamTokenProvider, clientReleaseManager,
multiRecipientMessageExecutor, messageDeliveryScheduler, clientReleaseManager,
dynamicConfigurationManager, zkSecretParams, spamChecker, messageMetrics, messageDeliveryLoopMonitor,
Clock.systemUTC()),
new PaymentsController(currencyManager, paymentsCredentialsGenerator),
@@ -1167,6 +1147,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
provisioningEnvironment.setConnectListener(new ProvisioningConnectListener(provisioningManager));
provisioningEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET, clientReleaseManager));
provisioningEnvironment.jersey().register(new KeepAliveController(clientPresenceManager));
provisioningEnvironment.jersey().register(new TimestampResponseFilter());
registerCorsFilter(environment);
registerExceptionMappers(environment, webSocketEnvironment, provisioningEnvironment);
@@ -1217,7 +1198,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new ImpossiblePhoneNumberExceptionMapper(),
new NonNormalizedPhoneNumberExceptionMapper(),
new RegistrationServiceSenderExceptionMapper(),
new SubscriptionProcessorExceptionMapper(),
new SubscriptionExceptionMapper(),
new JsonMappingExceptionMapper()
).forEach(exceptionMapper -> {
@@ -8,15 +8,16 @@ package org.whispersystems.textsecuregcm.calls.routing;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse;
import org.apache.commons.lang3.tuple.Triple;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.util.Util;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.util.*;
import java.util.function.Supplier;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
@@ -58,6 +59,7 @@ public class TurnCallRouter {
* @param aci aci of client
* @param clientAddress IP address to base routing on
* @param instanceLimit max instances to return options for
* @return Up to two * instanceLimit options, half in ipv4, half in ipv6
*/
public TurnServerOptions getRoutingFor(
@Nonnull final UUID aci,
@@ -121,8 +123,7 @@ public class TurnCallRouter {
List<String> urlsWithIps = getUrlsForInstances(
selectInstances(
datacenters,
instanceLimit,
(clientAddress.get() instanceof Inet6Address)
instanceLimit
));
return new TurnServerOptions(hostname, urlsWithIps, minimalRandomUrls());
}
@@ -134,25 +135,22 @@ public class TurnCallRouter {
.toList();
}
private List<String> selectInstances(List<String> datacenters, int limit, boolean preferV6) {
if(datacenters.isEmpty() || limit == 0) {
// returns balanced number of instances across provided datacenters, prioritizing the datacenters earlier in the list
private List<String> selectInstances(List<String> datacenters, int instanceLimit) {
if(datacenters.isEmpty() || instanceLimit == 0) {
return Collections.emptyList();
}
int numV6 = preferV6 ? (limit - limit / 3) : limit / 3;
int numV4 = limit - numV6;
CallDnsRecords dnsRecords = this.callDnsRecords.get();
List<InetAddress> ipv4Selection = datacenters.stream()
.flatMap(dc -> randomNOf(dnsRecords.aByRegion().get(dc), limit, stableSelect).stream())
List<List<InetAddress>> ipv4Options = datacenters.stream()
.map(dc -> randomNOf(dnsRecords.aByRegion().get(dc), instanceLimit, stableSelect))
.toList();
List<InetAddress> ipv6Selection = datacenters.stream()
.flatMap(dc -> randomNOf(dnsRecords.aaaaByRegion().get(dc), limit, stableSelect).stream())
List<List<InetAddress>> ipv6Options = datacenters.stream()
.map(dc -> randomNOf(dnsRecords.aaaaByRegion().get(dc), instanceLimit, stableSelect))
.toList();
// increase numV4 if not enough v6 options. vice-versa is also true
numV4 = Math.max(numV4, limit - ipv6Selection.size());
ipv4Selection = ipv4Selection.stream().limit(numV4).toList();
ipv6Selection = ipv6Selection.stream().limit(limit - ipv4Selection.size()).toList();
List<InetAddress> ipv4Selection = selectFromOptions(ipv4Options, instanceLimit);
List<InetAddress> ipv6Selection = selectFromOptions(ipv6Options, instanceLimit);
return Stream.concat(
ipv4Selection.stream().map(InetAddress::getHostAddress),
@@ -161,6 +159,19 @@ public class TurnCallRouter {
).toList();
}
private static List<InetAddress> selectFromOptions(List<List<InetAddress>> recordsByDc, int instanceLimit) {
return IntStream.range(0, recordsByDc.size())
.mapToObj(dcIndex -> IntStream.range(0, recordsByDc.get(dcIndex).size())
.mapToObj(addressIndex -> Triple.of(addressIndex, dcIndex, recordsByDc.get(dcIndex).get(addressIndex))))
.flatMap(i -> i)
.sorted(Comparator.comparingInt((Triple<Integer, Integer, InetAddress> t) -> t.getLeft())
.thenComparingInt(Triple::getMiddle))
.limit(instanceLimit)
.sorted(Comparator.comparingInt(Triple::getMiddle))
.map(Triple::getRight)
.toList();
}
private static <E> List<E> randomNOf(List<E> values, int n, boolean stableSelect) {
return stableSelect ? Util.randomNOfStable(values, n) : Util.randomNOfShuffled(values, n);
}
@@ -76,7 +76,13 @@ public class AssessmentResult {
if (!solved) {
return false;
}
return this.actualScore >= scoreThreshold.orElse(this.defaultScoreThreshold);
// Since HCaptcha scores are truncated to 2 decimal places, we can multiply by 100 and round to the nearest int for
// comparison instead of floating point comparisons
return normalizedIntScore(this.actualScore) >= normalizedIntScore(scoreThreshold.orElse(this.defaultScoreThreshold));
}
private static int normalizedIntScore(final float score) {
return Math.round(score * 100);
}
public String getScoreString() {
@@ -9,9 +9,11 @@ import io.micrometer.core.instrument.Metrics;
import org.apache.http.HttpStatus;
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
@@ -28,7 +30,7 @@ public class ShortCodeExpander {
}
public Optional<String> retrieve(final String shortCode) throws IOException {
final URI uri = shortenerHost.resolve(shortCode);
final URI uri = shortenerHost.resolve(URLEncoder.encode(shortCode, StandardCharsets.UTF_8));
final HttpRequest request = HttpRequest.newBuilder().uri(uri).GET().build();
try {
@@ -14,6 +14,7 @@ import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.http.crt.AwsCrtHttpClient;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
import software.amazon.awssdk.metrics.MetricPublisher;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
@@ -39,13 +40,14 @@ public record DynamoDbClientConfiguration(@NotBlank String region,
}
@Override
public DynamoDbClient buildSyncClient(final AwsCredentialsProvider credentialsProvider) {
public DynamoDbClient buildSyncClient(final AwsCredentialsProvider credentialsProvider, final MetricPublisher metricPublisher) {
return DynamoDbClient.builder()
.region(Region.of(region()))
.credentialsProvider(credentialsProvider)
.overrideConfiguration(ClientOverrideConfiguration.builder()
.apiCallTimeout(clientExecutionTimeout())
.apiCallAttemptTimeout(clientRequestTimeout())
.addMetricPublisher(metricPublisher)
.build())
.httpClientBuilder(AwsCrtHttpClient.builder()
.maxConcurrency(maxConnections()))
@@ -53,13 +55,14 @@ public record DynamoDbClientConfiguration(@NotBlank String region,
}
@Override
public DynamoDbAsyncClient buildAsyncClient(final AwsCredentialsProvider credentialsProvider) {
public DynamoDbAsyncClient buildAsyncClient(final AwsCredentialsProvider credentialsProvider, final MetricPublisher metricPublisher) {
return DynamoDbAsyncClient.builder()
.region(Region.of(region()))
.credentialsProvider(credentialsProvider)
.overrideConfiguration(ClientOverrideConfiguration.builder()
.apiCallTimeout(clientExecutionTimeout())
.apiCallAttemptTimeout(clientRequestTimeout())
.addMetricPublisher(metricPublisher)
.build())
.httpClientBuilder(NettyNioAsyncHttpClient.builder()
.maxConcurrency(maxConnections()))
@@ -8,13 +8,14 @@ package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import io.dropwizard.jackson.Discoverable;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.metrics.MetricPublisher;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = DynamoDbClientConfiguration.class)
public interface DynamoDbClientFactory extends Discoverable {
DynamoDbClient buildSyncClient(AwsCredentialsProvider awsCredentialsProvider);
DynamoDbClient buildSyncClient(AwsCredentialsProvider awsCredentialsProvider, MetricPublisher metricPublisher);
DynamoDbAsyncClient buildAsyncClient(AwsCredentialsProvider awsCredentialsProvider);
DynamoDbAsyncClient buildAsyncClient(AwsCredentialsProvider awsCredentialsProvider, MetricPublisher metricPublisher);
}
@@ -120,7 +120,6 @@ public class AccountController {
accounts.updateDevice(account, device.getId(), d -> {
d.setApnId(null);
d.setVoipApnId(null);
d.setGcmId(registrationId.gcmRegistrationId());
d.setFetchesMessages(false);
});
@@ -153,7 +152,6 @@ public class AccountController {
// unconditionally
accounts.updateDevice(account, device.getId(), d -> {
d.setApnId(registrationId.apnRegistrationId());
d.setVoipApnId(registrationId.voipRegistrationId());
d.setGcmId(null);
d.setFetchesMessages(false);
});
@@ -167,7 +165,6 @@ public class AccountController {
accounts.updateDevice(account, device.getId(), d -> {
d.setApnId(null);
d.setVoipApnId(null);
d.setFetchesMessages(false);
if (d.getId() == 1) {
d.setUserAgent("OWI");
@@ -252,6 +249,7 @@ public class AccountController {
auth.getAccount().getNumber(),
auth.getAccount().getPhoneNumberIdentifier(),
auth.getAccount().getUsernameHash().filter(h -> h.length > 0).orElse(null),
auth.getAccount().getUsernameLinkHandle(),
auth.getAccount().isStorageSupported());
}
@@ -150,6 +150,7 @@ public class AccountControllerV2 {
updatedAccount.getNumber(),
updatedAccount.getPhoneNumberIdentifier(),
updatedAccount.getUsernameHash().orElse(null),
updatedAccount.getUsernameLinkHandle(),
updatedAccount.isStorageSupported());
} catch (MismatchedDevicesException e) {
throw new WebApplicationException(Response.status(409)
@@ -208,6 +209,7 @@ public class AccountControllerV2 {
updatedAccount.getNumber(),
updatedAccount.getPhoneNumberIdentifier(),
updatedAccount.getUsernameHash().orElse(null),
updatedAccount.getUsernameLinkHandle(),
updatedAccount.isStorageSupported());
} catch (MismatchedDevicesException e) {
throw new WebApplicationException(Response.status(409)
@@ -35,7 +35,7 @@ import org.whispersystems.websocket.auth.ReadOnly;
@io.swagger.v3.oas.annotations.tags.Tag(name = "Calling")
public class CallRoutingController {
private static final int TURN_INSTANCE_LIMIT = 3;
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;
@@ -57,6 +57,7 @@ import org.whispersystems.textsecuregcm.entities.DeviceInfoList;
import org.whispersystems.textsecuregcm.entities.DeviceResponse;
import org.whispersystems.textsecuregcm.entities.LinkDeviceRequest;
import org.whispersystems.textsecuregcm.entities.PreKeySignatureValidator;
import org.whispersystems.textsecuregcm.entities.ProvisioningMessage;
import org.whispersystems.textsecuregcm.entities.SetPublicKeyRequest;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
@@ -146,9 +147,34 @@ public class DeviceController {
accounts.removeDevice(auth.getAccount(), deviceId).join();
}
/**
* Generates a signed device-linking token. Generally, primary devices will include the signed device-linking token in
* a provisioning message to a new device, and then the new device will include the token in its request to
* {@link #linkDevice(BasicAuthorizationHeader, String, LinkDeviceRequest, ContainerRequest)}.
*
* @param auth the authenticated account/device
*
* @return a signed device-linking token
*
* @throws RateLimitExceededException if the caller has made too many calls to this method in a set amount of time
* @throws DeviceLimitExceededException if the authenticated account has already reached the maximum number of linked
* devices
*
* @see ProvisioningController#sendProvisioningMessage(AuthenticatedDevice, String, ProvisioningMessage, String)
*/
@GET
@Path("/provisioning/code")
@Produces(MediaType.APPLICATION_JSON)
@Operation(
summary = "Generate a signed device-linking token",
description = """
Generate a signed device-linking token for transmission to a pending linked device via a provisioning message.
""")
@ApiResponse(responseCode="200", description="Token was generated successfully", useReturnTypeSchema=true)
@ApiResponse(responseCode = "411", description = "The authenticated account already has the maximum allowed number of linked devices")
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
name = "Retry-After",
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
public VerificationCode createDeviceToken(@ReadOnly @Auth AuthenticatedDevice auth)
throws RateLimitExceededException, DeviceLimitExceededException {
@@ -55,6 +55,7 @@ import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.NotAuthorizedException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.POST;
@@ -115,7 +116,6 @@ import org.whispersystems.textsecuregcm.push.MessageSender;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
import org.whispersystems.textsecuregcm.push.ReceiptSender;
import org.whispersystems.textsecuregcm.spam.ReportSpamTokenProvider;
import org.whispersystems.textsecuregcm.spam.SpamChecker;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
@@ -162,7 +162,6 @@ public class MessageController {
private final ReportMessageManager reportMessageManager;
private final ExecutorService multiRecipientMessageExecutor;
private final Scheduler messageDeliveryScheduler;
private final ReportSpamTokenProvider reportSpamTokenProvider;
private final ClientReleaseManager clientReleaseManager;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private final ServerSecretParams serverSecretParams;
@@ -182,10 +181,7 @@ public class MessageController {
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 Timer SEND_MESSAGE_LATENCY_TIMER =
Timer.builder(MetricsUtil.name(MessageController.class, "sendMessageLatency"))
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry);
private static final String SEND_MESSAGE_LATENCY_TIMER_NAME = MetricsUtil.name(MessageController.class, "sendMessageLatency");
private static final String EPHEMERAL_TAG_NAME = "ephemeral";
private static final String SENDER_TYPE_TAG_NAME = "senderType";
@@ -225,7 +221,6 @@ public class MessageController {
ReportMessageManager reportMessageManager,
@Nonnull ExecutorService multiRecipientMessageExecutor,
Scheduler messageDeliveryScheduler,
@Nonnull ReportSpamTokenProvider reportSpamTokenProvider,
final ClientReleaseManager clientReleaseManager,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final ServerSecretParams serverSecretParams,
@@ -244,7 +239,6 @@ public class MessageController {
this.reportMessageManager = reportMessageManager;
this.multiRecipientMessageExecutor = Objects.requireNonNull(multiRecipientMessageExecutor);
this.messageDeliveryScheduler = messageDeliveryScheduler;
this.reportSpamTokenProvider = reportSpamTokenProvider;
this.clientReleaseManager = clientReleaseManager;
this.dynamicConfigurationManager = dynamicConfigurationManager;
this.serverSecretParams = serverSecretParams;
@@ -254,7 +248,6 @@ public class MessageController {
this.clock = clock;
}
@Timed
@Path("/{destination}")
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@@ -300,25 +293,25 @@ public class MessageController {
@Context final ContainerRequestContext context) throws RateLimitExceededException {
if (source.isEmpty() && accessKey.isEmpty() && groupSendToken == null && !isStory) {
throw new WebApplicationException(Status.UNAUTHORIZED);
}
if (groupSendToken != null) {
if (source.isPresent() || accessKey.isPresent()) {
throw new BadRequestException(
"Group send endorsement tokens should not be combined with other authentication");
} else if (isStory) {
throw new BadRequestException("Group send endorsement tokens should not be sent for story messages");
}
}
final String senderType = source.map(
s -> s.getAccount().isIdentifiedBy(destinationIdentifier) ? SENDER_TYPE_SELF : SENDER_TYPE_IDENTIFIED)
.orElse(SENDER_TYPE_UNIDENTIFIED);
final Sample sample = Timer.start();
try {
if (source.isEmpty() && accessKey.isEmpty() && groupSendToken == null && !isStory) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
if (groupSendToken != null) {
if (source.isPresent() || accessKey.isPresent()) {
throw new BadRequestException(
"Group send endorsement tokens should not be combined with other authentication");
} else if (isStory) {
throw new BadRequestException("Group send endorsement tokens should not be sent for story messages");
}
}
final String senderType = source.map(
s -> s.getAccount().isIdentifiedBy(destinationIdentifier) ? SENDER_TYPE_SELF : SENDER_TYPE_IDENTIFIED)
.orElse(SENDER_TYPE_UNIDENTIFIED);
final boolean isSyncMessage = senderType.equals(SENDER_TYPE_SELF);
if (isSyncMessage && destinationIdentifier.identityType() == IdentityType.PNI) {
@@ -332,17 +325,14 @@ public class MessageController {
destination = source.map(AuthenticatedDevice::getAccount);
}
final Optional<Response> spamCheck = spamChecker.checkForSpam(
context, source.map(AuthenticatedDevice::getAccount), destination);
if (spamCheck.isPresent()) {
return spamCheck.get();
final SpamChecker.SpamCheckResult spamCheck = spamChecker.checkForSpam(
context, source, destination);
final Optional<byte[]> reportSpamToken;
switch (spamCheck) {
case final SpamChecker.Spam spam: return spam.response();
case final SpamChecker.NotSpam notSpam: reportSpamToken = notSpam.token();
}
final Optional<byte[]> spamReportToken = switch (senderType) {
case SENDER_TYPE_IDENTIFIED -> reportSpamTokenProvider.makeReportSpamToken(context, source.get(), destination);
default -> Optional.empty();
};
int totalContentLength = 0;
for (final IncomingMessage message : messages.messages()) {
@@ -452,7 +442,7 @@ public class MessageController {
messages.urgent(),
incomingMessage,
userAgent,
spamReportToken);
reportSpamToken);
});
}
@@ -470,7 +460,10 @@ public class MessageController {
.build());
}
} finally {
sample.stop(SEND_MESSAGE_LATENCY_TIMER);
sample.stop(Timer.builder(SEND_MESSAGE_LATENCY_TIMER_NAME)
.tags(SENDER_TYPE_TAG_NAME, senderType)
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry));
}
}
@@ -554,9 +547,9 @@ public class MessageController {
@Context ContainerRequestContext context) throws RateLimitExceededException {
final Optional<Response> spamCheck = spamChecker.checkForSpam(context, Optional.empty(), Optional.empty());
if (spamCheck.isPresent()) {
return spamCheck.get();
final SpamChecker.SpamCheckResult spamCheck = spamChecker.checkForSpam(context, Optional.empty(), Optional.empty());
if (spamCheck instanceof final SpamChecker.Spam spam) {
return spam.response();
}
if (groupSendToken == null && accessKeys == null && !isStory) {
@@ -697,13 +690,13 @@ public class MessageController {
.get();
} catch (InterruptedException e) {
logger.error("interrupted while delivering multi-recipient messages", e);
return Response.serverError().entity("interrupted during delivery").build();
throw new InternalServerErrorException("interrupted during delivery");
} catch (CancellationException e) {
logger.error("cancelled while delivering multi-recipient messages", e);
return Response.serverError().entity("delivery cancelled").build();
throw new InternalServerErrorException("delivery cancelled");
} catch (ExecutionException e) {
logger.error("partial failure while delivering multi-recipient messages", e.getCause());
return Response.serverError().entity("failure during delivery").build();
throw new InternalServerErrorException("failure during delivery");
}
return Response.ok(new SendMultiRecipientMessageResponse(Collections.emptyList())).build();
}
@@ -54,6 +54,7 @@ import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails;
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
import org.whispersystems.textsecuregcm.subscriptions.PaymentStatus;
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionCurrencyUtil;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
@@ -324,15 +325,15 @@ public class OneTimeDonationController {
return paymentDetailsFut.thenCompose(paymentDetails -> {
if (paymentDetails == null) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
switch (paymentDetails.status()) {
case PROCESSING -> throw new WebApplicationException(Response.Status.NO_CONTENT);
case SUCCEEDED -> {
}
default -> throw new WebApplicationException(Response.status(Response.Status.PAYMENT_REQUIRED)
} else if (paymentDetails.status() == PaymentStatus.PROCESSING) {
return CompletableFuture.completedFuture(Response.noContent().build());
} else if (paymentDetails.status() != PaymentStatus.SUCCEEDED) {
throw new WebApplicationException(Response.status(Response.Status.PAYMENT_REQUIRED)
.entity(new CreateBoostReceiptCredentialsErrorResponse(paymentDetails.chargeFailure())).build());
}
// The payment was successful, try to issue the receipt credential
long level = oneTimeDonationConfiguration.boost().level();
if (paymentDetails.customMetadata() != null) {
String levelMetadata = paymentDetails.customMetadata()
@@ -13,6 +13,9 @@ import io.dropwizard.auth.Auth;
import io.dropwizard.util.DataSize;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.Base64;
import javax.validation.Valid;
@@ -31,9 +34,18 @@ import org.whispersystems.textsecuregcm.entities.ProvisioningMessage;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.ProvisioningManager;
import org.whispersystems.textsecuregcm.websocket.ProvisioningAddress;
import org.whispersystems.websocket.auth.ReadOnly;
/**
* The provisioning controller facilitates transmission of provisioning messages from the primary device associated with
* an existing Signal account to a new device. To send a provisioning message, a primary device generally scans a QR
* code displayed by the new device that contains the device's "provisioning address" and a public key. The primary
* device then encrypts a use-case-specific provisioning message and posts it to
* {@link #sendProvisioningMessage(AuthenticatedDevice, String, ProvisioningMessage, String)}, at which point the server
* delivers the message to the new device via an open provisioning WebSocket.
*
* @see org.whispersystems.textsecuregcm.websocket.ProvisioningConnectListener
*/
@Path("/v1/provisioning")
@Tag(name = "Provisioning")
public class ProvisioningController {
@@ -56,22 +68,37 @@ public class ProvisioningController {
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public void sendProvisioningMessage(@ReadOnly @Auth AuthenticatedDevice auth,
@PathParam("destination") String destinationName,
@NotNull @Valid ProvisioningMessage message,
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent)
@Operation(
summary = "Send a provisioning message to a new device",
description = """
Send a provisioning message from an authenticated device to a device that (presumably) is not yet associated
with a Signal account.
""")
@ApiResponse(responseCode="204", description="The provisioning message was delivered to the given provisioning address")
@ApiResponse(responseCode="400", description="The provisioning message was too large")
@ApiResponse(responseCode="404", description="No device with the given provisioning address was connected at the time of the request")
public void sendProvisioningMessage(@ReadOnly @Auth final AuthenticatedDevice auth,
@Parameter(description = "The temporary provisioning address to which to send a provisioning message")
@PathParam("destination") final String provisioningAddress,
@Parameter(description = "The provisioning message to send to the given provisioning address")
@NotNull @Valid final ProvisioningMessage message,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent)
throws RateLimitExceededException {
if (message.body().length() > MAX_MESSAGE_SIZE) {
Metrics.counter(REJECT_OVERSIZE_MESSAGE_COUNTER, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)))
.increment();
Metrics.counter(REJECT_OVERSIZE_MESSAGE_COUNTER, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent))).increment();
throw new WebApplicationException(Response.Status.BAD_REQUEST);
}
rateLimiters.getMessagesLimiter().validate(auth.getAccount().getUuid());
if (!provisioningManager.sendProvisioningMessage(ProvisioningAddress.create(destinationName),
Base64.getMimeDecoder().decode(message.body()))) {
final boolean subscriberPresent =
provisioningManager.sendProvisioningMessage(provisioningAddress, Base64.getMimeDecoder().decode(message.body()));
if (!subscriberPresent) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
}
@@ -170,6 +170,7 @@ public class RegistrationController {
account.getNumber(),
account.getPhoneNumberIdentifier(),
account.getUsernameHash().orElse(null),
account.getUsernameLinkHandle(),
existingAccount.map(Account::isStorageSupported).orElse(false));
}
@@ -51,6 +51,7 @@ import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
@@ -419,6 +420,10 @@ public class SubscriptionController {
After calling this method, the payment is confirmed. Callers must durably store their subscriberId before calling
this method to ensure their payment is tracked.
Once a purchaseToken to is posted to a subscriberId, the same subscriberId must not be used with another payment
method. A different playbilling purchaseToken can be posted to the same subscriberId, in this case the subscription
associated with the old purchaseToken will be cancelled.
""")
@ApiResponse(responseCode = "200", description = "The purchaseToken was validated and acknowledged")
@ApiResponse(responseCode = "402", description = "The purchaseToken payment is incomplete or invalid")
@@ -526,7 +531,7 @@ public class SubscriptionController {
long level,
@Schema(
description = "If present, UNIX Epoch Timestamp in seconds, can be used to calculate next billing date. May be absent for IAP subscriptions",
description = "If present, UNIX Epoch Timestamp in seconds, can be used to calculate next billing date.",
externalDocs = @ExternalDocumentation(description = "Calculate next billing date", url = "https://stripe.com/docs/billing/subscriptions/billing-cycle"))
Instant billingCycleAnchor,
@@ -631,7 +636,10 @@ public class SubscriptionController {
UserAgentTagUtil.getPlatformTag(userAgent)))
.increment();
return Response.ok(new GetReceiptCredentialsResponse(receiptCredentialResponse.serialize())).build();
});
})
.exceptionally(ExceptionUtils.exceptionallyHandler(
SubscriptionException.ReceiptRequestedForOpenPayment.class,
e -> Response.noContent().build()));
}
@POST
@@ -27,6 +27,9 @@ public record AccountIdentityResponse(
@JsonDeserialize(using = ByteArrayBase64UrlAdapter.Deserializing.class)
@Nullable byte[] usernameHash,
@Schema(description="this account's username link handle, if set")
@Nullable UUID usernameLinkHandle,
@Schema(description="whether any of this account's devices support storage")
boolean storageCapable) {
}
@@ -7,6 +7,5 @@ package org.whispersystems.textsecuregcm.entities;
import javax.annotation.Nullable;
import javax.validation.constraints.NotEmpty;
public record ApnRegistrationId(@NotEmpty String apnRegistrationId,
@Nullable String voipRegistrationId) {
public record ApnRegistrationId(@NotEmpty String apnRegistrationId) {
}
@@ -5,7 +5,11 @@
package org.whispersystems.textsecuregcm.entities;
import io.swagger.v3.oas.annotations.media.Schema;
import javax.validation.constraints.NotEmpty;
public record ProvisioningMessage(@NotEmpty String body) {
public record ProvisioningMessage(
@Schema(description = "The MIME base64-encoded body of the provisioning message to send to the destination device")
@NotEmpty
String body) {
}
@@ -18,6 +18,7 @@ import java.util.concurrent.Executor;
import java.util.function.Supplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;
/**
* An experiment compares the results of two operations and records metrics to assess how frequently they match.
@@ -70,6 +71,14 @@ public class Experiment {
this.experimentNullMismatchTimer = experimentNullMismatchTimer;
}
public <T> void compareMonoResult(final T expected, final Mono<T> experimentMono) {
final Timer.Sample sample = Timer.start();
experimentMono.subscribe(
actual -> recordResult(expected, actual, sample),
cause -> recordError(cause, sample));
}
public <T> void compareFutureResult(final T expected, final CompletionStage<T> experimentStage) {
final Timer.Sample sample = Timer.start();
@@ -54,8 +54,7 @@ abstract class IdleDevicePushNotificationExperiment implements PushNotificationE
@VisibleForTesting
boolean hasPushToken(final Device device) {
// Exclude VOIP tokens since they have their own, distinct delivery mechanism
return !StringUtils.isAllBlank(device.getApnId(), device.getGcmId()) && StringUtils.isBlank(device.getVoipApnId());
return !StringUtils.isAllBlank(device.getApnId(), device.getGcmId());
}
@Override
@@ -1,76 +0,0 @@
package org.whispersystems.textsecuregcm.experiment;
import com.google.common.annotations.VisibleForTesting;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.push.IdleDeviceNotificationScheduler;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import java.time.Clock;
import java.time.Duration;
import java.time.LocalTime;
import java.util.concurrent.CompletableFuture;
public class NotifyIdleDevicesWithMessagesExperiment extends IdleDevicePushNotificationExperiment {
private final IdleDeviceNotificationScheduler idleDeviceNotificationScheduler;
private final MessagesManager messagesManager;
@VisibleForTesting
static final Duration MIN_IDLE_DURATION = Duration.ofDays(3);
@VisibleForTesting
static final Duration MAX_IDLE_DURATION = Duration.ofDays(14);
@VisibleForTesting
static final LocalTime PREFERRED_NOTIFICATION_TIME = LocalTime.of(14, 0);
public NotifyIdleDevicesWithMessagesExperiment(final IdleDeviceNotificationScheduler idleDeviceNotificationScheduler,
final MessagesManager messagesManager,
final Clock clock) {
super(clock);
this.idleDeviceNotificationScheduler = idleDeviceNotificationScheduler;
this.messagesManager = messagesManager;
}
@Override
protected Duration getMinIdleDuration() {
return MIN_IDLE_DURATION;
}
@Override
protected Duration getMaxIdleDuration() {
return MAX_IDLE_DURATION;
}
@Override
public String getExperimentName() {
return "notify-idle-devices-with-messages";
}
@Override
public CompletableFuture<Boolean> isDeviceEligible(final Account account, final Device device) {
if (!hasPushToken(device)) {
return CompletableFuture.completedFuture(false);
}
if (!isIdle(device)) {
return CompletableFuture.completedFuture(false);
}
return messagesManager.mayHavePersistedMessages(account.getIdentifier(IdentityType.ACI), device);
}
@Override
public Class<DeviceLastSeenState> getStateClass() {
return DeviceLastSeenState.class;
}
@Override
public CompletableFuture<Void> applyExperimentTreatment(final Account account, final Device device) {
return idleDeviceNotificationScheduler.scheduleNotification(account, device, PREFERRED_NOTIFICATION_TIME);
}
}
@@ -5,18 +5,37 @@
package org.whispersystems.textsecuregcm.filters;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import java.io.IOException;
/**
* Injects a timestamp header into all outbound responses.
*/
public class TimestampResponseFilter implements ContainerResponseFilter {
public class TimestampResponseFilter implements Filter, ContainerResponseFilter {
@Override
public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext) {
responseContext.getHeaders().add(HeaderUtils.TIMESTAMP_HEADER, System.currentTimeMillis());
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
throws ServletException, IOException {
if (response instanceof HttpServletResponse httpServletResponse) {
httpServletResponse.setHeader(HeaderUtils.TIMESTAMP_HEADER, String.valueOf(System.currentTimeMillis()));
}
chain.doFilter(request, response);
}
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
// not using add() - it's ok to overwrite any existing header, and we don't want a multi-value
responseContext.getHeaders().putSingle(HeaderUtils.TIMESTAMP_HEADER, System.currentTimeMillis());
}
}
@@ -110,7 +110,6 @@ public class DevicesGrpcService extends ReactorDevicesGrpc.DevicesImplBase {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
@Nullable final String apnsToken;
@Nullable final String apnsVoipToken;
@Nullable final String fcmToken;
switch (request.getTokenRequestCase()) {
@@ -118,12 +117,11 @@ public class DevicesGrpcService extends ReactorDevicesGrpc.DevicesImplBase {
case APNS_TOKEN_REQUEST -> {
final SetPushTokenRequest.ApnsTokenRequest apnsTokenRequest = request.getApnsTokenRequest();
if (StringUtils.isAllBlank(apnsTokenRequest.getApnsToken(), apnsTokenRequest.getApnsVoipToken())) {
throw Status.INVALID_ARGUMENT.withDescription("APNs tokens may not both be blank").asRuntimeException();
if (StringUtils.isBlank(apnsTokenRequest.getApnsToken())) {
throw Status.INVALID_ARGUMENT.withDescription("APNs token must not be blank").asRuntimeException();
}
apnsToken = StringUtils.stripToNull(apnsTokenRequest.getApnsToken());
apnsVoipToken = StringUtils.stripToNull(apnsTokenRequest.getApnsVoipToken());
fcmToken = null;
}
@@ -135,7 +133,6 @@ public class DevicesGrpcService extends ReactorDevicesGrpc.DevicesImplBase {
}
apnsToken = null;
apnsVoipToken = null;
fcmToken = StringUtils.stripToNull(fcmTokenRequest.getFcmToken());
}
@@ -150,14 +147,12 @@ public class DevicesGrpcService extends ReactorDevicesGrpc.DevicesImplBase {
final boolean tokenUnchanged =
Objects.equals(device.getApnId(), apnsToken) &&
Objects.equals(device.getVoipApnId(), apnsVoipToken) &&
Objects.equals(device.getGcmId(), fcmToken);
return tokenUnchanged
? Mono.empty()
: Mono.fromFuture(() -> accountsManager.updateDeviceAsync(account, authenticatedDevice.deviceId(), d -> {
d.setApnId(apnsToken);
d.setVoipApnId(apnsVoipToken);
d.setGcmId(fcmToken);
d.setFetchesMessages(false);
}));
@@ -172,14 +167,13 @@ public class DevicesGrpcService extends ReactorDevicesGrpc.DevicesImplBase {
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
.flatMap(account -> Mono.fromFuture(() -> accountsManager.updateDeviceAsync(account, authenticatedDevice.deviceId(), device -> {
if (StringUtils.isNotBlank(device.getApnId()) || StringUtils.isNotBlank(device.getVoipApnId())) {
if (StringUtils.isNotBlank(device.getApnId())) {
device.setUserAgent(device.isPrimary() ? "OWI" : "OWP");
} else if (StringUtils.isNotBlank(device.getGcmId())) {
device.setUserAgent("OWA");
}
device.setApnId(null);
device.setVoipApnId(null);
device.setGcmId(null);
device.setFetchesMessages(true);
})))
@@ -24,8 +24,8 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
PRE_KEYS("prekeys", false, new RateLimiterConfig(6, Duration.ofMinutes(10))),
MESSAGES("messages", false, new RateLimiterConfig(60, Duration.ofSeconds(1))),
STORIES("stories", false, new RateLimiterConfig(5_000, Duration.ofSeconds(8))),
ALLOCATE_DEVICE("allocateDevice", false, new RateLimiterConfig(2, Duration.ofMinutes(2))),
VERIFY_DEVICE("verifyDevice", false, new RateLimiterConfig(6, Duration.ofMinutes(10))),
ALLOCATE_DEVICE("allocateDevice", false, new RateLimiterConfig(6, Duration.ofMinutes(2))),
VERIFY_DEVICE("verifyDevice", false, new RateLimiterConfig(6, Duration.ofMinutes(2))),
TURN("turnAllocate", false, new RateLimiterConfig(60, Duration.ofSeconds(1))),
PROFILE("profile", false, new RateLimiterConfig(4320, Duration.ofSeconds(20))),
STICKER_PACK("stickerPack", false, new RateLimiterConfig(50, Duration.ofMinutes(72))),
@@ -5,17 +5,48 @@
package org.whispersystems.textsecuregcm.mappers;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.jersey.errors.ErrorMessage;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import org.whispersystems.textsecuregcm.storage.SubscriptionException;
import java.util.Map;
public class SubscriptionExceptionMapper implements ExceptionMapper<SubscriptionException> {
@VisibleForTesting
public static final int PROCESSOR_ERROR_STATUS_CODE = 440;
@Override
public Response toResponse(final SubscriptionException exception) {
// Some exceptions have specific error body formats
if (exception instanceof SubscriptionException.AmountTooSmall e) {
return Response
.status(Response.Status.BAD_REQUEST)
.entity(Map.of("error", "amount_too_small"))
.type(MediaType.APPLICATION_JSON_TYPE)
.build();
}
if (exception instanceof SubscriptionException.ProcessorException e) {
return Response.status(PROCESSOR_ERROR_STATUS_CODE)
.entity(Map.of(
"processor", e.getProcessor().name(),
"chargeFailure", e.getChargeFailure()
))
.type(MediaType.APPLICATION_JSON_TYPE)
.build();
}
if (exception instanceof SubscriptionException.ChargeFailurePaymentRequired e) {
return Response
.status(Response.Status.PAYMENT_REQUIRED)
.entity(Map.of("chargeFailure", e.getChargeFailure()))
.type(MediaType.APPLICATION_JSON_TYPE)
.build();
}
// Otherwise, we'll return a generic error message WebApplicationException, with a detailed error if one is provided
final Response.Status status = (switch (exception) {
case SubscriptionException.NotFound e -> Response.Status.NOT_FOUND;
case SubscriptionException.Forbidden e -> Response.Status.FORBIDDEN;
@@ -36,5 +67,6 @@ public class SubscriptionExceptionMapper implements ExceptionMapper<Subscription
.fromResponse(wae.getResponse())
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new ErrorMessage(wae.getResponse().getStatus(), wae.getLocalizedMessage())).build();
}
}
@@ -1,26 +0,0 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.mappers;
import java.util.Map;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
public class SubscriptionProcessorExceptionMapper implements ExceptionMapper<SubscriptionProcessorException> {
public static final int EXTERNAL_SERVICE_ERROR_STATUS_CODE = 440;
@Override
public Response toResponse(final SubscriptionProcessorException exception) {
return Response.status(EXTERNAL_SERVICE_ERROR_STATUS_CODE)
.entity(Map.of(
"processor", exception.getProcessor().name(),
"chargeFailure", exception.getChargeFailure()
))
.build();
}
}
@@ -0,0 +1,207 @@
package org.whispersystems.textsecuregcm.metrics;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.Timer;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.metrics.MetricPublisher;
import software.amazon.awssdk.metrics.MetricRecord;
import java.time.Duration;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
/**
* A Micrometer AWS SDK metric publisher consumes {@link MetricCollection} instances provided by the AWS SDK when it
* makes calls to the AWS API and publishes a subset of metrics from each call via the Micrometer metrics facade. A
* single {@code MicrometerAwsSdkMetricPublisher} should be bound to a single AWS service client instance; publishers
* should not be assigned to multiple service clients.
*
* @see <a href="https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/metrics-list.html">Service client metrics</a>
*/
public class MicrometerAwsSdkMetricPublisher implements MetricPublisher {
private final ExecutorService recordMetricsExecutorService;
private final String awsClientName;
private final AtomicInteger mostRecentMaxConcurrency;
// Note that these metric collection type names don't seem to appear anywhere in the AWS SDK documentation. The docs
// also hint at, but don't explicitly call out, the structure of a `MetricCollection` passed to the `#publish(...)`
// method. Empirically, for each AWS SDK operation, the SDK will call `#publish(...)` with a collection structured as
// follows:
//
// MetricCollection { name = "ApiCall" }
// +-- MetricRecord { name = "ApiCallDuration" }
// +-- MetricRecord { name = "ApiCallSuccessful" }
// +-- ...
// +-- MetricCollection { name = "ApiCallAttempt" }
// +-- MetricRecord { name = "AwsExtendedRequestId" }
// +-- MetricRecord { name = "AwsRequestId" }
// +-- ...
// +-- MetricCollection {name = "HttpClient" }
// +-- MetricRecord { name = "AvailableConcurrency" }
// +-- MetricRecord { name = "ConcurrencyAcquireDuration" }
// +-- ...
// +-- MetricCollection { name = "ApiCallAttempt" }
// +-- MetricRecord { name = "AwsExtendedRequestId" }
// +-- MetricRecord { name = "AwsRequestId" }
// +-- ...
// +-- MetricCollection {name = "HttpClient" }
// +-- MetricRecord { name = "AvailableConcurrency" }
// +-- MetricRecord { name = "ConcurrencyAcquireDuration" }
// +-- ...
// +-- ...
//
// Every `MetricCollection` passed to `#publish(...)` should have a name of "ApiCall," and the "ApiCall" collection
// will have a fixed collection of named metrics (which ARE documented!). The "ApiCall" collection should have one or
// more "ApiCallAttempt" `MetricCollection` as children, and each "ApiCallAttempt" collection should have exactly one
// "HttpClient" `MetricCollection` as a child.
private static final String METRIC_COLLECTION_TYPE_API_CALL = "ApiCall";
private static final String METRIC_COLLECTION_TYPE_API_CALL_ATTEMPT = "ApiCallAttempt";
private static final String METRIC_COLLECTION_TYPE_HTTP_METRICS = "HttpClient";
private static final String API_CALL_COUNTER_NAME =
MetricsUtil.name(MicrometerAwsSdkMetricPublisher.class, "apiCall");
private static final String API_CALL_RETRY_COUNT_DISTRIBUTION_NAME =
MetricsUtil.name(MicrometerAwsSdkMetricPublisher.class, "apiCallRetries");
private static final String CHANNEL_ACQUISITION_TIMER_NAME =
MetricsUtil.name(MicrometerAwsSdkMetricPublisher.class, "acquireChannelDuration");
private static final String PENDING_CHANNEL_ACQUISITIONS_DISTRIBUTION_NAME =
MetricsUtil.name(MicrometerAwsSdkMetricPublisher.class, "pendingChannelAcquisitions");
private static final String CONCURRENT_REQUESTS_DISTRIBUTION_NAME =
MetricsUtil.name(MicrometerAwsSdkMetricPublisher.class, "concurrentRequests");
private static final String CLIENT_NAME_TAG = "clientName";
/**
* Constructs a new metric publisher that uses the given executor service to record metrics and tags metrics with the
* given client name.
*
* @param recordMetricsExecutorService the executor service via which to record metrics
* @param awsClientName the name of AWS service client to which this publisher is attached
*/
public MicrometerAwsSdkMetricPublisher(final ExecutorService recordMetricsExecutorService, final String awsClientName) {
this.recordMetricsExecutorService = recordMetricsExecutorService;
this.awsClientName = awsClientName;
mostRecentMaxConcurrency = Metrics.gauge("maxConcurrency",
Tags.of(CLIENT_NAME_TAG, awsClientName),
new AtomicInteger(0));
}
@Override
public void publish(final MetricCollection metricCollection) {
/* if (METRIC_COLLECTION_TYPE_API_CALL.equals(metricCollection.name())) {
try {
recordMetricsExecutorService.submit(() -> recordApiCallMetrics(metricCollection));
} catch (final RejectedExecutionException ignored) {
// This can happen if clients make new calls to an upstream service while the server is shutting down
}
} */
}
private void recordApiCallMetrics(final MetricCollection apiCallMetricCollection) {
if (!apiCallMetricCollection.name().equals(METRIC_COLLECTION_TYPE_API_CALL)) {
throw new IllegalArgumentException("Unexpected API call metric collection name: " + apiCallMetricCollection.name());
}
final Map<String, MetricRecord<?>> metricsByName = toMetricMap(apiCallMetricCollection);
final Optional<String> maybeAwsServiceId = Optional.ofNullable(metricsByName.get("ServiceId"))
.map(metricRecord -> (String) metricRecord.value());
final Optional<String> maybeOperationName = Optional.ofNullable(metricsByName.get("OperationName"))
.map(metricRecord -> (String) metricRecord.value());
// Both the service ID and operation name SHOULD always be present, but since the metric collection is unstructured,
// we don't have any compile-time guarantees and so check that they're both present as a pedantic safety check.
if (maybeAwsServiceId.isPresent() && maybeOperationName.isPresent()) {
final String awsServiceId = maybeAwsServiceId.get();
final String operationName = maybeOperationName.get();
final boolean success = Optional.ofNullable(metricsByName.get("ApiCallSuccessful"))
.map(metricRecord -> (boolean) metricRecord.value())
.orElse(false);
final int retryCount = Optional.ofNullable(metricsByName.get("RetryCount"))
.map(metricRecord -> (int) metricRecord.value())
.orElse(0);
final Tags tags = Tags.of(
CLIENT_NAME_TAG, awsClientName,
"awsServiceId", awsServiceId,
"operationName", operationName,
"callSuccess", String.valueOf(success));
Metrics.counter(API_CALL_COUNTER_NAME, tags).increment();
DistributionSummary.builder(API_CALL_RETRY_COUNT_DISTRIBUTION_NAME)
.tags(tags)
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry)
.record(retryCount);
apiCallMetricCollection.childrenWithName(METRIC_COLLECTION_TYPE_API_CALL_ATTEMPT)
.forEach(callAttemptMetricCollection -> recordAttemptMetrics(callAttemptMetricCollection, tags));
}
}
private void recordAttemptMetrics(final MetricCollection apiCallAttemptMetricCollection, final Tags callTags) {
if (!apiCallAttemptMetricCollection.name().equals(METRIC_COLLECTION_TYPE_API_CALL_ATTEMPT)) {
throw new IllegalArgumentException("Unexpected API call attempt metric collection name: " + apiCallAttemptMetricCollection.name());
}
// A "call attempt" metric collection should always have exactly one HTTP metrics child collection, but we have no
// compiler-level guarantees and so do a pedantic check here just to be safe.
apiCallAttemptMetricCollection.childrenWithName(METRIC_COLLECTION_TYPE_HTTP_METRICS).findFirst().ifPresent(httpMetricCollection -> {
final Map<String, MetricRecord<?>> callAttemptMetricsByName = toMetricMap(apiCallAttemptMetricCollection);
final Map<String, MetricRecord<?>> httpMetricsByName = toMetricMap(httpMetricCollection);
Optional.ofNullable(httpMetricsByName.get("MaxConcurrency"))
.ifPresent(maxConcurrencyMetricRecord -> mostRecentMaxConcurrency.set((int) maxConcurrencyMetricRecord.value()));
final Tags attemptTags = Optional.ofNullable(callAttemptMetricsByName.get("ErrorType"))
.map(errorTypeMetricRecord -> callTags.and("error", errorTypeMetricRecord.value().toString()))
.orElse(callTags);
Optional.ofNullable(httpMetricsByName.get("ConcurrencyAcquireDuration"))
.ifPresent(channelAcquisitionDurationMetricRecord -> Timer.builder(CHANNEL_ACQUISITION_TIMER_NAME)
.tags(attemptTags)
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry)
.record((Duration) channelAcquisitionDurationMetricRecord.value()));
Optional.ofNullable(httpMetricsByName.get("LeasedConcurrency"))
.ifPresent(concurrentRequestsMetricRecord -> DistributionSummary.builder(CONCURRENT_REQUESTS_DISTRIBUTION_NAME)
.tags(attemptTags)
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry)
.record((int) concurrentRequestsMetricRecord.value()));
Optional.ofNullable(httpMetricsByName.get("PendingConcurrencyAcquires"))
.ifPresent(pendingChannelAcquisitionsMetricRecord -> DistributionSummary.builder(PENDING_CHANNEL_ACQUISITIONS_DISTRIBUTION_NAME)
.tags(attemptTags)
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry)
.record((int) pendingChannelAcquisitionsMetricRecord.value()));
});
}
private static Map<String, MetricRecord<?>> toMetricMap(final MetricCollection metricCollection) {
return metricCollection.stream()
.collect(Collectors.toMap(metricRecord -> metricRecord.metric().name(), metricRecord -> metricRecord));
}
@Override
public void close() {
}
}
@@ -0,0 +1,15 @@
package org.whispersystems.textsecuregcm.metrics;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.metrics.MetricPublisher;
public class NoopAwsSdkMetricPublisher implements MetricPublisher {
@Override
public void publish(final MetricCollection metricCollection) {
}
@Override
public void close() {
}
}
@@ -0,0 +1,103 @@
package org.whispersystems.textsecuregcm.metrics;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.Timer;
import org.whispersystems.textsecuregcm.util.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.Arrays;
import java.util.EnumMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;
public class OpenWebSocketCounter {
private final Map<ClientPlatform, AtomicInteger> openWebsocketsByClientPlatform;
private final AtomicInteger openWebsocketsFromUnknownPlatforms;
private final Map<ClientPlatform, Timer> durationTimersByClientPlatform;
private final Timer durationTimerForUnknownPlatforms;
public OpenWebSocketCounter(final String openWebSocketGaugeName, final String durationTimerName) {
this(openWebSocketGaugeName, durationTimerName, Tags.empty());
}
public OpenWebSocketCounter(final String openWebSocketGaugeName, final String durationTimerName, final Tags tags) {
openWebsocketsByClientPlatform = Arrays.stream(ClientPlatform.values())
.collect(Collectors.toMap(
Function.identity(),
clientPlatform -> buildGauge(openWebSocketGaugeName, clientPlatform.name().toLowerCase(), tags),
(a, b) -> {
throw new AssertionError("Duplicate client platform enumeration key");
},
() -> new EnumMap<>(ClientPlatform.class)
));
openWebsocketsFromUnknownPlatforms = buildGauge(openWebSocketGaugeName, "unknown", tags);
durationTimersByClientPlatform = Arrays.stream(ClientPlatform.values())
.collect(Collectors.toMap(
clientPlatform -> clientPlatform,
clientPlatform -> buildTimer(durationTimerName, clientPlatform.name().toLowerCase(), tags),
(a, b) -> {
throw new AssertionError("Duplicate client platform enumeration key");
},
() -> new EnumMap<>(ClientPlatform.class)
));
durationTimerForUnknownPlatforms = buildTimer(durationTimerName, "unknown", tags);
}
private static AtomicInteger buildGauge(final String gaugeName, final String clientPlatformName, final Tags tags) {
return Metrics.gauge(gaugeName,
tags.and(Tag.of(UserAgentTagUtil.PLATFORM_TAG, clientPlatformName)),
new AtomicInteger(0));
}
private static Timer buildTimer(final String timerName, final String clientPlatformName, final Tags tags) {
return Timer.builder(timerName)
.publishPercentileHistogram(true)
.tags(tags.and(Tag.of(UserAgentTagUtil.PLATFORM_TAG, clientPlatformName)))
.register(Metrics.globalRegistry);
}
public void countOpenWebSocket(final WebSocketSessionContext context) {
final Timer.Sample sample = Timer.start();
// We have to jump through some hoops here to have something "effectively final" for the close listener, but
// assignable from a `catch` block.
final AtomicInteger openWebSocketCounter;
final Timer durationTimer;
{
AtomicInteger calculatedOpenWebSocketCounter;
Timer calculatedDurationTimer;
try {
final ClientPlatform clientPlatform =
UserAgentUtil.parseUserAgentString(context.getClient().getUserAgent()).getPlatform();
calculatedOpenWebSocketCounter = openWebsocketsByClientPlatform.get(clientPlatform);
calculatedDurationTimer = durationTimersByClientPlatform.get(clientPlatform);
} catch (final UnrecognizedUserAgentException e) {
calculatedOpenWebSocketCounter = openWebsocketsFromUnknownPlatforms;
calculatedDurationTimer = durationTimerForUnknownPlatforms;
}
openWebSocketCounter = calculatedOpenWebSocketCounter;
durationTimer = calculatedDurationTimer;
}
openWebSocketCounter.incrementAndGet();
context.addWebsocketClosedListener((context1, statusCode, reason) -> {
sample.stop(durationTimer);
openWebSocketCounter.decrementAndGet();
});
}
}
@@ -34,12 +34,6 @@ public class APNSender implements Managed, PushNotificationSender {
private final String bundleId;
private final ApnsClient apnsClient;
@VisibleForTesting
static final String APN_VOIP_NOTIFICATION_PAYLOAD = new SimpleApnsPayloadBuilder()
.setSound("default")
.setLocalizedAlertMessage("APN_Message")
.build();
@VisibleForTesting
static final String APN_NSE_NOTIFICATION_PAYLOAD = new SimpleApnsPayloadBuilder()
.setMutableContent(true)
@@ -80,22 +74,8 @@ public class APNSender implements Managed, PushNotificationSender {
@Override
public CompletableFuture<SendPushNotificationResult> sendNotification(final PushNotification notification) {
final String topic = switch (notification.tokenType()) {
case APN -> bundleId;
case APN_VOIP -> bundleId + ".voip";
default -> throw new IllegalArgumentException("Unsupported token type: " + notification.tokenType());
};
final boolean isVoip = notification.tokenType() == PushNotification.TokenType.APN_VOIP;
final String payload = switch (notification.notificationType()) {
case NOTIFICATION -> {
if (isVoip) {
yield APN_VOIP_NOTIFICATION_PAYLOAD;
} else {
yield notification.urgent() ? APN_NSE_NOTIFICATION_PAYLOAD : APN_BACKGROUND_PAYLOAD;
}
}
case NOTIFICATION -> notification.urgent() ? APN_NSE_NOTIFICATION_PAYLOAD : APN_BACKGROUND_PAYLOAD;
case ATTEMPT_LOGIN_NOTIFICATION_HIGH_PRIORITY -> new SimpleApnsPayloadBuilder()
.setMutableContent(true)
@@ -115,13 +95,7 @@ public class APNSender implements Managed, PushNotificationSender {
};
final PushType pushType = switch (notification.notificationType()) {
case NOTIFICATION -> {
if (isVoip) {
yield PushType.VOIP;
} else {
yield notification.urgent() ? PushType.ALERT : PushType.BACKGROUND;
}
}
case NOTIFICATION -> notification.urgent() ? PushType.ALERT : PushType.BACKGROUND;
case ATTEMPT_LOGIN_NOTIFICATION_HIGH_PRIORITY -> PushType.ALERT;
case CHALLENGE, RATE_LIMIT_CHALLENGE -> PushType.BACKGROUND;
};
@@ -131,19 +105,17 @@ public class APNSender implements Managed, PushNotificationSender {
if (pushType == PushType.BACKGROUND) {
deliveryPriority = DeliveryPriority.CONSERVE_POWER;
} else {
deliveryPriority = (notification.urgent() || isVoip)
? DeliveryPriority.IMMEDIATE
: DeliveryPriority.CONSERVE_POWER;
deliveryPriority = notification.urgent() ? DeliveryPriority.IMMEDIATE : DeliveryPriority.CONSERVE_POWER;
}
final String collapseId =
(notification.notificationType() == PushNotification.NotificationType.NOTIFICATION && notification.urgent() && !isVoip)
(notification.notificationType() == PushNotification.NotificationType.NOTIFICATION && notification.urgent())
? "incoming-message" : null;
final Instant start = Instant.now();
return apnsClient.sendNotification(new SimpleApnsPushNotification(notification.deviceToken(),
topic,
bundleId,
payload,
MAX_EXPIRATION,
deliveryPriority,
@@ -28,8 +28,6 @@ import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguratio
import org.whispersystems.textsecuregcm.redis.RedisOperation;
import org.whispersystems.textsecuregcm.storage.PubSubProtos;
import org.whispersystems.textsecuregcm.util.CircuitBreakerUtil;
import org.whispersystems.textsecuregcm.websocket.InvalidWebsocketAddressException;
import org.whispersystems.textsecuregcm.websocket.ProvisioningAddress;
public class ProvisioningManager extends RedisPubSubAdapter<byte[], byte[]> implements Managed {
@@ -39,7 +37,7 @@ public class ProvisioningManager extends RedisPubSubAdapter<byte[], byte[]> impl
private final CircuitBreaker circuitBreaker;
private final Map<ProvisioningAddress, Consumer<PubSubProtos.PubSubMessage>> listenersByProvisioningAddress =
private final Map<String, Consumer<PubSubProtos.PubSubMessage>> listenersByProvisioningAddress =
new ConcurrentHashMap<>();
private static final String ACTIVE_LISTENERS_GAUGE_NAME = name(ProvisioningManager.class, "activeListeners");
@@ -82,21 +80,21 @@ public class ProvisioningManager extends RedisPubSubAdapter<byte[], byte[]> impl
redisClient.shutdown();
}
public void addListener(final ProvisioningAddress address, final Consumer<PubSubProtos.PubSubMessage> listener) {
public void addListener(final String address, final Consumer<PubSubProtos.PubSubMessage> listener) {
listenersByProvisioningAddress.put(address, listener);
circuitBreaker.executeRunnable(
() -> subscriptionConnection.sync().subscribe(address.serialize().getBytes(StandardCharsets.UTF_8)));
() -> subscriptionConnection.sync().subscribe(address.getBytes(StandardCharsets.UTF_8)));
}
public void removeListener(final ProvisioningAddress address) {
public void removeListener(final String address) {
RedisOperation.unchecked(() -> circuitBreaker.executeRunnable(
() -> subscriptionConnection.sync().unsubscribe(address.serialize().getBytes(StandardCharsets.UTF_8))));
() -> subscriptionConnection.sync().unsubscribe(address.getBytes(StandardCharsets.UTF_8))));
listenersByProvisioningAddress.remove(address);
}
public boolean sendProvisioningMessage(final ProvisioningAddress address, final byte[] body) {
public boolean sendProvisioningMessage(final String address, final byte[] body) {
final PubSubProtos.PubSubMessage pubSubMessage = PubSubProtos.PubSubMessage.newBuilder()
.setType(PubSubProtos.PubSubMessage.Type.DELIVER)
.setContent(ByteString.copyFrom(body))
@@ -104,7 +102,7 @@ public class ProvisioningManager extends RedisPubSubAdapter<byte[], byte[]> impl
final boolean receiverPresent = circuitBreaker.executeSupplier(
() -> publicationConnection.sync()
.publish(address.serialize().getBytes(StandardCharsets.UTF_8), pubSubMessage.toByteArray()) > 0);
.publish(address.getBytes(StandardCharsets.UTF_8), pubSubMessage.toByteArray()) > 0);
Metrics.counter(SEND_PROVISIONING_MESSAGE_COUNTER_NAME, "online", String.valueOf(receiverPresent)).increment();
@@ -114,7 +112,7 @@ public class ProvisioningManager extends RedisPubSubAdapter<byte[], byte[]> impl
@Override
public void message(final byte[] channel, final byte[] message) {
try {
final ProvisioningAddress address = new ProvisioningAddress(new String(channel, StandardCharsets.UTF_8));
final String address = new String(channel, StandardCharsets.UTF_8);
final PubSubProtos.PubSubMessage pubSubMessage = PubSubProtos.PubSubMessage.parseFrom(message);
if (pubSubMessage.getType() == PubSubProtos.PubSubMessage.Type.DELIVER) {
@@ -129,8 +127,6 @@ public class ProvisioningManager extends RedisPubSubAdapter<byte[], byte[]> impl
Metrics.counter(RECEIVE_PROVISIONING_MESSAGE_COUNTER_NAME, "listenerPresent", String.valueOf(listenerPresent)).increment();
}
} catch (final InvalidWebsocketAddressException e) {
logger.warn("Failed to parse provisioning address", e);
} catch (final InvalidProtocolBufferException e) {
logger.warn("Failed to parse pub/sub message", e);
}
@@ -138,10 +134,6 @@ public class ProvisioningManager extends RedisPubSubAdapter<byte[], byte[]> impl
@Override
public void unsubscribed(final byte[] channel, final long count) {
try {
listenersByProvisioningAddress.remove(new ProvisioningAddress(new String(channel)));
} catch (final InvalidWebsocketAddressException e) {
logger.warn("Failed to parse provisioning address for `unsubscribe` event", e);
}
listenersByProvisioningAddress.remove(new String(channel, StandardCharsets.UTF_8));
}
}
@@ -26,7 +26,6 @@ public record PushNotification(String deviceToken,
public enum TokenType {
FCM,
APN,
APN_VOIP,
APN
}
}
@@ -90,8 +90,6 @@ public class PushNotificationManager {
if (StringUtils.isNotBlank(device.getGcmId())) {
tokenAndType = new Pair<>(device.getGcmId(), PushNotification.TokenType.FCM);
} else if (StringUtils.isNotBlank(device.getVoipApnId())) {
tokenAndType = new Pair<>(device.getVoipApnId(), PushNotification.TokenType.APN_VOIP);
} else if (StringUtils.isNotBlank(device.getApnId())) {
tokenAndType = new Pair<>(device.getApnId(), PushNotification.TokenType.APN);
} else {
@@ -115,7 +113,7 @@ public class PushNotificationManager {
final PushNotificationSender sender = switch (pushNotification.tokenType()) {
case FCM -> fcmSender;
case APN, APN_VOIP -> apnSender;
case APN -> apnSender;
};
return sender.sendNotification(pushNotification).whenComplete((result, throwable) -> {
@@ -141,18 +139,6 @@ public class PushNotificationManager {
result.errorCode(),
result.unregisteredTimestamp());
}
if (result.accepted() &&
pushNotification.tokenType() == PushNotification.TokenType.APN_VOIP &&
pushNotification.notificationType() == PushNotification.NotificationType.NOTIFICATION &&
pushNotification.destination() != null &&
pushNotification.destinationDevice() != null) {
pushNotificationScheduler.scheduleRecurringApnsVoipNotification(
pushNotification.destination(),
pushNotification.destinationDevice())
.whenComplete(logErrors());
}
} else {
logger.debug("Failed to deliver {} push notification to {} ({})",
pushNotification.notificationType(), pushNotification.deviceToken(), pushNotification.tokenType(),
@@ -183,7 +169,7 @@ public class PushNotificationManager {
tokenInvalidationTimestamp.isAfter(Instant.ofEpochMilli(device.getPushTimestamp()))).orElse(true);
if (tokenExpired) {
if (tokenType == PushNotification.TokenType.APN || tokenType == PushNotification.TokenType.APN_VOIP) {
if (tokenType == PushNotification.TokenType.APN) {
pushNotificationScheduler.cancelScheduledNotifications(account, device).whenComplete(logErrors());
}
@@ -215,7 +201,6 @@ public class PushNotificationManager {
switch (tokenType) {
case FCM -> d.setGcmId(null);
case APN -> d.setApnId(null);
case APN_VOIP -> d.setVoipApnId(null);
}
}
})));
@@ -225,7 +210,6 @@ public class PushNotificationManager {
return switch (tokenType) {
case FCM -> device.getGcmId();
case APN -> device.getApnId();
case APN_VOIP -> device.getVoipApnId();
};
}
}
@@ -19,20 +19,17 @@ import java.io.IOException;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiFunction;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
import org.whispersystems.textsecuregcm.storage.Account;
@@ -41,14 +38,12 @@ import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.RedisClusterUtil;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public class PushNotificationScheduler implements Managed {
private static final Logger logger = LoggerFactory.getLogger(PushNotificationScheduler.class);
private static final String PENDING_RECURRING_VOIP_NOTIFICATIONS_KEY_PREFIX = "PENDING_APN";
private static final String PENDING_BACKGROUND_NOTIFICATIONS_KEY_PREFIX = "PENDING_BACKGROUND_APN";
private static final String LAST_BACKGROUND_NOTIFICATION_TIMESTAMP_KEY_PREFIX = "LAST_BACKGROUND_NOTIFICATION";
private static final String PENDING_DELAYED_NOTIFICATIONS_KEY_PREFIX = "DELAYED";
@@ -56,11 +51,6 @@ public class PushNotificationScheduler implements Managed {
@VisibleForTesting
static final String NEXT_SLOT_TO_PROCESS_KEY = "pending_notification_next_slot";
private static final Counter delivered = Metrics.counter("chat.ApnPushNotificationScheduler.voip_delivered");
private static final Counter sent = Metrics.counter("chat.ApnPushNotificationScheduler.voip_sent");
private static final Counter retry = Metrics.counter("chat.ApnPushNotificationScheduler.voip_retry");
private static final Counter evicted = Metrics.counter("chat.ApnPushNotificationScheduler.voip_evicted");
private static final Counter BACKGROUND_NOTIFICATION_SCHEDULED_COUNTER = Metrics.counter(name(PushNotificationScheduler.class, "backgroundNotification", "scheduled"));
private static final String BACKGROUND_NOTIFICATION_SENT_COUNTER_NAME = name(PushNotificationScheduler.class, "backgroundNotification", "sent");
@@ -75,10 +65,6 @@ public class PushNotificationScheduler implements Managed {
private final FaultTolerantRedisCluster pushSchedulingCluster;
private final Clock clock;
private final ClusterLuaScript getPendingVoipDestinationsScript;
private final ClusterLuaScript insertPendingVoipDestinationScript;
private final ClusterLuaScript removePendingVoipDestinationScript;
private final ClusterLuaScript scheduleBackgroundApnsNotificationScript;
private final Thread[] workerThreads;
@@ -117,37 +103,7 @@ public class PushNotificationScheduler implements Managed {
final int slot = (int) (pushSchedulingCluster.withCluster(connection ->
connection.sync().incr(NEXT_SLOT_TO_PROCESS_KEY)) % SlotHash.SLOT_COUNT);
return processRecurringApnsVoipNotifications(slot) +
processScheduledBackgroundApnsNotifications(slot) +
processScheduledDelayedNotifications(slot);
}
@VisibleForTesting
long processRecurringApnsVoipNotifications(final int slot) {
List<String> pendingDestinations;
long entriesProcessed = 0;
do {
pendingDestinations = getPendingDestinationsForRecurringApnsVoipNotifications(slot, PAGE_SIZE);
entriesProcessed += pendingDestinations.size();
Flux.fromIterable(pendingDestinations)
.flatMap(destination -> Mono.fromFuture(() -> getAccountAndDeviceFromPairString(destination))
.flatMap(maybeAccountAndDevice -> {
if (maybeAccountAndDevice.isPresent()) {
final Pair<Account, Device> accountAndDevice = maybeAccountAndDevice.get();
return Mono.fromFuture(() -> sendRecurringApnsVoipNotification(accountAndDevice.first(), accountAndDevice.second()));
} else {
final Pair<UUID, Byte> aciAndDeviceId = decodeAciAndDeviceId(destination);
return Mono.fromFuture(() -> removeRecurringApnsVoipNotificationEntry(aciAndDeviceId.first(), aciAndDeviceId.second()))
.then();
}
}), maxConcurrency)
.then()
.block();
} while (!pendingDestinations.isEmpty());
return entriesProcessed;
return processScheduledBackgroundApnsNotifications(slot) + processScheduledDelayedNotifications(slot);
}
@VisibleForTesting
@@ -216,13 +172,6 @@ public class PushNotificationScheduler implements Managed {
this.pushSchedulingCluster = pushSchedulingCluster;
this.clock = clock;
this.getPendingVoipDestinationsScript = ClusterLuaScript.fromResource(pushSchedulingCluster, "lua/apn/get.lua",
ScriptOutputType.MULTI);
this.insertPendingVoipDestinationScript = ClusterLuaScript.fromResource(pushSchedulingCluster, "lua/apn/insert.lua",
ScriptOutputType.VALUE);
this.removePendingVoipDestinationScript = ClusterLuaScript.fromResource(pushSchedulingCluster, "lua/apn/remove.lua",
ScriptOutputType.INTEGER);
this.scheduleBackgroundApnsNotificationScript = ClusterLuaScript.fromResource(pushSchedulingCluster,
"lua/apn/schedule_background_notification.lua", ScriptOutputType.VALUE);
@@ -233,17 +182,6 @@ public class PushNotificationScheduler implements Managed {
}
}
/**
* Schedule a recurring VOIP notification until {@link this#cancelScheduledNotifications} is called or the device is
* removed
*
* @return A CompletionStage that completes when the recurring notification has successfully been scheduled
*/
public CompletionStage<Void> scheduleRecurringApnsVoipNotification(Account account, Device device) {
sent.increment();
return insertRecurringApnsVoipNotificationEntry(account.getIdentifier(IdentityType.ACI), device.getId(), clock.millis() + (15 * 1000), (15 * 1000));
}
/**
* Schedule a background APNs notification to be sent some time in the future.
*
@@ -292,32 +230,16 @@ public class PushNotificationScheduler implements Managed {
}
/**
* Cancel a scheduled recurring VOIP notification
* Cancel scheduled notifications for the given account and device.
*
* @return A CompletionStage that completes when the scheduled task has been cancelled.
* @return A CompletionStage that completes when the scheduled notification has been cancelled.
*/
public CompletionStage<Void> cancelScheduledNotifications(Account account, Device device) {
return CompletableFuture.allOf(
cancelRecurringApnsVoipNotifications(account, device),
cancelBackgroundApnsNotifications(account, device),
cancelDelayedNotifications(account, device));
}
private CompletableFuture<Void> cancelRecurringApnsVoipNotifications(final Account account, final Device device) {
return removeRecurringApnsVoipNotificationEntry(account.getIdentifier(IdentityType.ACI), device.getId())
.thenCompose(removed -> {
if (removed) {
delivered.increment();
}
return pushSchedulingCluster.withCluster(connection ->
connection.async().zrem(
getPendingBackgroundApnsNotificationQueueKey(account, device),
encodeAciAndDeviceId(account, device)));
})
.thenRun(Util.NOOP)
.toCompletableFuture();
}
@VisibleForTesting
CompletableFuture<Void> cancelBackgroundApnsNotifications(final Account account, final Device device) {
return pushSchedulingCluster.withCluster(connection -> connection.async()
@@ -353,21 +275,6 @@ public class PushNotificationScheduler implements Managed {
}
}
private CompletableFuture<Void> sendRecurringApnsVoipNotification(final Account account, final Device device) {
if (StringUtils.isBlank(device.getVoipApnId())) {
return removeRecurringApnsVoipNotificationEntry(account.getIdentifier(IdentityType.ACI), device.getId())
.thenRun(Util.NOOP);
}
if (device.getLastSeen() < clock.millis() - TimeUnit.DAYS.toMillis(7)) {
return removeRecurringApnsVoipNotificationEntry(account.getIdentifier(IdentityType.ACI), device.getId())
.thenRun(evicted::increment);
}
return apnSender.sendNotification(new PushNotification(device.getVoipApnId(), PushNotification.TokenType.APN_VOIP, PushNotification.NotificationType.NOTIFICATION, null, account, device, true))
.thenRun(retry::increment);
}
@VisibleForTesting
CompletableFuture<Void> sendBackgroundApnsNotification(final Account account, final Device device) {
if (StringUtils.isBlank(device.getApnId())) {
@@ -443,48 +350,6 @@ public class PushNotificationScheduler implements Managed {
.flatMap(account -> account.getDevice(aciAndDeviceId.second()).map(device -> new Pair<>(account, device))));
}
private CompletableFuture<Boolean> removeRecurringApnsVoipNotificationEntry(final UUID aci, final byte deviceId) {
final String endpoint = getVoipEndpointKey(aci, deviceId);
return removePendingVoipDestinationScript.executeAsync(
List.of(getPendingRecurringApnsVoipNotificationQueueKey(endpoint), endpoint), Collections.emptyList())
.thenApply(result -> ((long) result) > 0);
}
@SuppressWarnings("unchecked")
@VisibleForTesting
List<String> getPendingDestinationsForRecurringApnsVoipNotifications(final int slot, final int limit) {
return (List<String>) getPendingVoipDestinationsScript.execute(
List.of(getPendingRecurringApnsVoipNotificationQueueKey(slot)),
List.of(String.valueOf(clock.millis()), String.valueOf(limit)));
}
@SuppressWarnings("SameParameterValue")
private CompletionStage<Void> insertRecurringApnsVoipNotificationEntry(final UUID aci, final byte deviceId, final long timestamp, final long interval) {
final String endpoint = getVoipEndpointKey(aci, deviceId);
return insertPendingVoipDestinationScript.executeAsync(
List.of(getPendingRecurringApnsVoipNotificationQueueKey(endpoint), endpoint),
List.of(String.valueOf(timestamp),
String.valueOf(interval),
aci.toString(),
String.valueOf(deviceId)))
.thenRun(Util.NOOP);
}
@VisibleForTesting
static String getVoipEndpointKey(final UUID aci, final byte deviceId) {
return "apn_device::{" + aci + "::" + deviceId + "}";
}
private static String getPendingRecurringApnsVoipNotificationQueueKey(final String endpoint) {
return getPendingRecurringApnsVoipNotificationQueueKey(SlotHash.getSlot(endpoint));
}
private static String getPendingRecurringApnsVoipNotificationQueueKey(final int slot) {
return PENDING_RECURRING_VOIP_NOTIFICATIONS_KEY_PREFIX + "::{" + RedisClusterUtil.getMinimalHashTag(slot) + "}";
}
@VisibleForTesting
static String getPendingBackgroundApnsNotificationQueueKey(final Account account, final Device device) {
return getPendingBackgroundApnsNotificationQueueKey(SlotHash.getSlot(encodeAciAndDeviceId(account, device)));
@@ -136,7 +136,7 @@ public abstract class JobScheduler {
*
* @see #processJob(byte[])
*/
public CompletableFuture<Void> processAvailableJobs() {
public Mono<Void> processAvailableJobs() {
return Flux.from(dynamoDbAsyncClient.queryPaginator(QueryRequest.builder()
.tableName(tableName)
.keyConditionExpression("#schedulerName = :schedulerName AND #runAt <= :maxRunAt")
@@ -153,7 +153,7 @@ public abstract class JobScheduler {
? item.get(ATTR_JOB_DATA).b().asByteArray()
: null;
return Mono.fromFuture(processJob(jobData))
return Mono.fromFuture(() -> processJob(jobData))
.doOnNext(outcome -> Metrics.counter(PROCESS_JOB_COUNTER_NAME,
SCHEDULER_NAME_TAG, getSchedulerName(),
OUTCOME_TAG, outcome)
@@ -164,8 +164,7 @@ public abstract class JobScheduler {
return Mono.empty();
});
}, MAX_CONCURRENCY)
.then()
.toFuture();
.then();
}
private CompletableFuture<Void> deleteJob(final AttributeValue schedulerName, final AttributeValue runAt) {
@@ -1,32 +0,0 @@
package org.whispersystems.textsecuregcm.spam;
import org.whispersystems.textsecuregcm.auth.AccountAndAuthenticatedDeviceHolder;
import org.whispersystems.textsecuregcm.storage.Account;
import javax.ws.rs.container.ContainerRequestContext;
import java.util.Optional;
/**
* Generates ReportSpamTokens to be used for spam reports.
*/
public interface ReportSpamTokenProvider {
/**
* Generate a new ReportSpamToken
*
* @param context the message request context
* @param sender the account that sent the unsealed sender message
* @param maybeDestination the intended recepient of the message if available
* @return either a generated token or nothing
*/
Optional<byte[]> makeReportSpamToken(ContainerRequestContext context, final AccountAndAuthenticatedDeviceHolder sender,
final Optional<Account> maybeDestination);
/**
* Provider which generates nothing
*
* @return the provider
*/
static ReportSpamTokenProvider noop() {
return (ignoredContext, ignoredSender, ignoredDest) -> Optional.empty();
}
}
@@ -4,6 +4,7 @@
*/
package org.whispersystems.textsecuregcm.spam;
import org.whispersystems.textsecuregcm.auth.AccountAndAuthenticatedDeviceHolder;
import org.whispersystems.textsecuregcm.storage.Account;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.core.Response;
@@ -11,6 +12,25 @@ import java.util.Optional;
public interface SpamChecker {
/**
* A result from the spam checker that is one of:
* <ul>
* <li>
* Message is determined to be spam, and a response is returned
* </li>
* <li>
* Message is not spam, and an optional spam token is returned
* </li>
* </ul>
*/
sealed interface SpamCheckResult {}
record Spam(Response response) implements SpamCheckResult {}
record NotSpam(Optional<byte[]> token) implements SpamCheckResult {
public static final NotSpam EMPTY_TOKEN = new NotSpam(Optional.empty());
}
/**
* Determine if a message may be spam
*
@@ -18,14 +38,14 @@ public interface SpamChecker {
* @param maybeSource The sender of the message, could be empty if this as message sent with sealed sender
* @param maybeDestination The destination of the message, could be empty if the destination does not exist or could
* not be retrieved
* @return A response to return if the request is determined to be spam, otherwise empty if the message should be sent
* @return A {@link SpamCheckResult}
*/
Optional<Response> checkForSpam(
SpamCheckResult checkForSpam(
final ContainerRequestContext requestContext,
final Optional<Account> maybeSource,
final Optional<? extends AccountAndAuthenticatedDeviceHolder> maybeSource,
final Optional<Account> maybeDestination);
static SpamChecker noop() {
return (ignoredContext, ignoredSource, ignoredDestination) -> Optional.empty();
return (ignoredContext, ignoredSource, ignoredDestination) -> NotSpam.EMPTY_TOKEN;
}
}
@@ -33,13 +33,6 @@ public interface SpamFilter extends Managed {
*/
void configure(String environmentName, Validator validator) throws IOException, ConfigurationValidationException;
/**
* Builds a spam report token provider. This will generate tokens used by the spam reporting system.
*
* @return the configured spam report token provider.
*/
ReportSpamTokenProvider getReportSpamTokenProvider();
/**
* Return a reported message listener controlled by the spam filter. Listeners will be registered with the
* {@link org.whispersystems.textsecuregcm.storage.ReportMessageManager}.
@@ -25,7 +25,7 @@ public class Device {
public static final List<Byte> ALL_POSSIBLE_DEVICE_IDS = IntStream.range(Device.PRIMARY_ID, MAXIMUM_DEVICE_ID).boxed()
.map(Integer::byteValue).collect(Collectors.toList());
private static final long ALLOWED_LINKED_IDLE_MILLIS = Duration.ofDays(30).toMillis();
private static final long ALLOWED_LINKED_IDLE_MILLIS = Duration.ofDays(45).toMillis();
private static final long ALLOWED_PRIMARY_IDLE_MILLIS = Duration.ofDays(180).toMillis();
@JsonDeserialize(using = DeviceIdDeserializer.class)
@@ -49,9 +49,6 @@ public class Device {
@JsonProperty
private String apnId;
@JsonProperty
private String voipApnId;
@JsonProperty
private long pushTimestamp;
@@ -89,14 +86,6 @@ public class Device {
}
}
public String getVoipApnId() {
return voipApnId;
}
public void setVoipApnId(String voipApnId) {
this.voipApnId = voipApnId;
}
public void setLastSeen(long lastSeen) {
this.lastSeen = lastSeen;
}
@@ -39,13 +39,8 @@ public record DeviceSpec(
device.setLastSeen(Util.todayInMillis());
device.setUserAgent(signalAgent());
apnRegistrationId().ifPresent(apnRegistrationId -> {
device.setApnId(apnRegistrationId.apnRegistrationId());
device.setVoipApnId(apnRegistrationId.voipRegistrationId());
});
gcmRegistrationId().ifPresent(gcmRegistrationId ->
device.setGcmId(gcmRegistrationId.gcmRegistrationId()));
apnRegistrationId().ifPresent(apnRegistrationId -> device.setApnId(apnRegistrationId.apnRegistrationId()));
gcmRegistrationId().ifPresent(gcmRegistrationId -> device.setGcmId(gcmRegistrationId.gcmRegistrationId()));
return device;
}
@@ -441,30 +441,30 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
ServiceIdentifier.valueOf(mrmMessage.getDestinationServiceId()), destinationDevice);
final Mono<MessageProtos.Envelope> mrmMessageMono = Mono.from(redisCluster.withBinaryClusterReactive(
conn -> conn.reactive().hmget(key, "data".getBytes(StandardCharsets.UTF_8), sharedMrmViewKey)
.collectList()
.publishOn(messageDeliveryScheduler)
.handle((mrmDataAndView, sink) -> {
try {
assert mrmDataAndView.size() == 2;
conn -> conn.reactive().hmget(key, "data".getBytes(StandardCharsets.UTF_8), sharedMrmViewKey)
.collectList()
.publishOn(messageDeliveryScheduler)))
.<MessageProtos.Envelope>handle((mrmDataAndView, sink) -> {
try {
assert mrmDataAndView.size() == 2;
final byte[] content = SealedSenderMultiRecipientMessage.messageForRecipient(
mrmDataAndView.getFirst().getValue(),
mrmDataAndView.getLast().getValue());
final byte[] content = SealedSenderMultiRecipientMessage.messageForRecipient(
mrmDataAndView.getFirst().getValue(),
mrmDataAndView.getLast().getValue());
sink.next(mrmMessage.toBuilder()
.clearSharedMrmKey()
.setContent(ByteString.copyFrom(content))
.build());
sink.next(mrmMessage.toBuilder()
.clearSharedMrmKey()
.setContent(ByteString.copyFrom(content))
.build());
mrmContentRetrievedCounter.increment();
} catch (Exception e) {
sink.error(e);
}
})));
mrmContentRetrievedCounter.increment();
} catch (Exception e) {
sink.error(e);
}
})
.share();
experiment.compareFutureResult(mrmMessage.toBuilder().clearSharedMrmKey().build(),
mrmMessageMono.toFuture());
experiment.compareMonoResult(mrmMessage.toBuilder().clearSharedMrmKey().build(), mrmMessageMono);
return mrmMessageMono;
} else {
@@ -24,7 +24,6 @@ import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.function.Predicate;
import java.util.stream.Stream;
import org.reactivestreams.Publisher;
import org.slf4j.Logger;
@@ -118,8 +117,7 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
}
public CompletableFuture<Boolean> mayHaveMessages(final UUID accountIdentifier, final Device device) {
return
dbAsyncClient.query(QueryRequest.builder()
return dbAsyncClient.query(QueryRequest.builder()
.tableName(tableName)
.consistentRead(false)
.limit(1)
@@ -129,6 +127,12 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
.thenApply(queryResponse -> queryResponse.count() > 0);
}
public CompletableFuture<Boolean> mayHaveUrgentMessages(final UUID accountIdentifier, final Device device) {
return Flux.from(load(accountIdentifier, device, null))
.any(MessageProtos.Envelope::getUrgent)
.toFuture();
}
public Publisher<MessageProtos.Envelope> load(final UUID destinationAccountUuid, final Device device, final Integer limit) {
QueryRequest.Builder queryRequestBuilder = QueryRequest.builder()
.tableName(tableName)
@@ -96,8 +96,8 @@ public class MessagesManager {
});
}
public boolean hasCachedMessages(final UUID destinationUuid, final byte destinationDevice) {
return messagesCache.hasMessages(destinationUuid, destinationDevice);
public CompletableFuture<Boolean> mayHaveUrgentPersistedMessages(final UUID destinationUuid, final Device destinationDevice) {
return messagesDynamoDb.mayHaveUrgentMessages(destinationUuid, destinationDevice);
}
public Mono<Pair<List<Envelope>, Boolean>> getMessagesForDevice(UUID destinationUuid, Device destinationDevice,
@@ -1,11 +0,0 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
public interface PubSubAddress {
String serialize();
}
@@ -6,6 +6,8 @@ package org.whispersystems.textsecuregcm.storage;
import java.util.Optional;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
public class SubscriptionException extends Exception {
@@ -53,30 +55,91 @@ public class SubscriptionException extends Exception {
}
public static class InvalidLevel extends InvalidArguments {
public InvalidLevel() {
super(null, null);
}
}
public static class AmountTooSmall extends InvalidArguments {
public AmountTooSmall() {
super(null, null);
}
}
public static class PaymentRequiresAction extends InvalidArguments {
public PaymentRequiresAction(String message) {
super(message, null);
}
public PaymentRequiresAction() {
super(null, null);
}
}
public static class PaymentRequired extends SubscriptionException {
public PaymentRequired() {
super(null, null);
}
public PaymentRequired(String message) {
super(null, message);
}
}
public static class ChargeFailurePaymentRequired extends SubscriptionException {
private final ChargeFailure chargeFailure;
public ChargeFailurePaymentRequired(final ChargeFailure chargeFailure) {
super(null, null);
this.chargeFailure = chargeFailure;
}
public ChargeFailure getChargeFailure() {
return chargeFailure;
}
}
public static class ProcessorException extends SubscriptionException {
private final PaymentProvider processor;
private final ChargeFailure chargeFailure;
public ProcessorException(final PaymentProvider processor, final ChargeFailure chargeFailure) {
super(null, null);
this.processor = processor;
this.chargeFailure = chargeFailure;
}
public PaymentProvider getProcessor() {
return processor;
}
public ChargeFailure getChargeFailure() {
return chargeFailure;
}
}
/**
* Attempted to retrieve a receipt for a subscription that hasn't yet been charged or the invoice is in the open
* state
*/
public static class ReceiptRequestedForOpenPayment extends SubscriptionException {
public ReceiptRequestedForOpenPayment() {
super(null, null);
}
}
public static class ProcessorConflict extends SubscriptionException {
public ProcessorConflict() {
super(null, null);
}
public ProcessorConflict(final String message) {
super(null, message);
}
@@ -349,29 +349,42 @@ public class SubscriptionManager {
final GooglePlayBillingManager googlePlayBillingManager,
final String purchaseToken) {
return getSubscriber(subscriberCredentials).thenCompose(record -> {
if (record.processorCustomer != null
&& record.processorCustomer.processor() != PaymentProvider.GOOGLE_PLAY_BILLING) {
return CompletableFuture.failedFuture(
new SubscriptionException.ProcessorConflict("existing processor does not match"));
}
// For IAP providers, the subscriptionId and the customerId are both just the purchaseToken. Changes to the
// subscription always just result in a new purchaseToken
final ProcessorCustomer pc = new ProcessorCustomer(purchaseToken, PaymentProvider.GOOGLE_PLAY_BILLING);
// For IAP providers, the subscriptionId and the customerId are both just the purchaseToken. Changes to the
// subscription always just result in a new purchaseToken
final ProcessorCustomer pc = new ProcessorCustomer(purchaseToken, PaymentProvider.GOOGLE_PLAY_BILLING);
return getSubscriber(subscriberCredentials)
return googlePlayBillingManager
// Validating ensures we don't allow a user-determined token that's totally bunk into the subscription manager,
// but we don't want to acknowledge it until it's successfully persisted.
.validateToken(purchaseToken)
// Store the purchaseToken with the subscriber
.thenCompose(validatedToken -> subscriptions.setIapPurchase(
record, pc, purchaseToken, validatedToken.getLevel(), subscriberCredentials.now())
// Now that the purchaseToken is durable, we can acknowledge it
.thenCompose(ignore -> validatedToken.acknowledgePurchase())
.thenApply(ignore -> validatedToken.getLevel()));
});
// Check the record for an existing subscription
.thenCompose(record -> {
if (record.processorCustomer != null
&& record.processorCustomer.processor() != PaymentProvider.GOOGLE_PLAY_BILLING) {
return CompletableFuture.failedFuture(
new SubscriptionException.ProcessorConflict("existing processor does not match"));
}
// If we're replacing an existing purchaseToken, cancel it first
return Optional.ofNullable(record.processorCustomer)
.map(ProcessorCustomer::customerId)
.filter(existingToken -> !purchaseToken.equals(existingToken))
.map(googlePlayBillingManager::cancelAllActiveSubscriptions)
.orElseGet(() -> CompletableFuture.completedFuture(null))
.thenApply(ignored -> record);
})
// Validate and set the purchaseToken
.thenCompose(record -> googlePlayBillingManager
// Validating ensures we don't allow a user-determined token that's totally bunk into the subscription manager,
// but we don't want to acknowledge it until it's successfully persisted.
.validateToken(purchaseToken)
// Store the purchaseToken with the subscriber
.thenCompose(validatedToken -> subscriptions.setIapPurchase(
record, pc, purchaseToken, validatedToken.getLevel(), subscriberCredentials.now())
// Now that the purchaseToken is durable, we can acknowledge it
.thenCompose(ignore -> validatedToken.acknowledgePurchase())
.thenApply(ignore -> validatedToken.getLevel())));
}
private SubscriptionPaymentProcessor getProcessor(PaymentProvider provider) {
@@ -23,6 +23,7 @@ import com.google.cloud.pubsub.v1.PublisherInterface;
import com.google.common.annotations.VisibleForTesting;
import com.google.pubsub.v1.PubsubMessage;
import io.micrometer.core.instrument.Metrics;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.Instant;
@@ -39,9 +40,6 @@ import java.util.concurrent.CompletionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import javax.annotation.Nullable;
import javax.ws.rs.ClientErrorException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
@@ -49,6 +47,8 @@ import org.whispersystems.textsecuregcm.currency.CurrencyConversionManager;
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.storage.PaymentTime;
import org.whispersystems.textsecuregcm.storage.SubscriptionException;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.GoogleApiUtil;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
@@ -197,8 +197,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
);
if (search.getMaximumSize() == 0) {
return CompletableFuture.failedFuture(
new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR));
return CompletableFuture.failedFuture(ExceptionUtils.wrap(new IOException()));
}
final Transaction successfulTx = search.getFirst();
@@ -212,13 +211,12 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
return switch (unsuccessfulTx.getProcessorResponseCode()) {
case GENERIC_DECLINED_PROCESSOR_CODE, PAYPAL_FUNDING_INSTRUMENT_DECLINED_PROCESSOR_CODE ->
CompletableFuture.failedFuture(
new SubscriptionProcessorException(getProvider(), createChargeFailure(unsuccessfulTx)));
new SubscriptionException.ProcessorException(getProvider(), createChargeFailure(unsuccessfulTx)));
default -> {
logger.info("PayPal charge unexpectedly failed: {}", unsuccessfulTx.getProcessorResponseCode());
yield CompletableFuture.failedFuture(
new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR));
yield CompletableFuture.failedFuture(ExceptionUtils.wrap(new IOException()));
}
};
}, executor));
@@ -389,7 +387,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
return getDefaultPaymentMethod(customerId)
.thenCompose(paymentMethod -> {
if (paymentMethod == null) {
throw new ClientErrorException(Response.Status.CONFLICT);
throw ExceptionUtils.wrap(new SubscriptionException.ProcessorConflict());
}
final Optional<Subscription> maybeExistingSubscription = paymentMethod.getSubscriptions().stream()
@@ -424,7 +422,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
if (result.getTarget() != null) {
completionException = result.getTarget().getTransactions().stream().findFirst()
.map(transaction -> new CompletionException(
new SubscriptionProcessorException(getProvider(), createChargeFailure(transaction))))
new SubscriptionException.ProcessorException(getProvider(), createChargeFailure(transaction))))
.orElseGet(() -> new CompletionException(new BraintreeException(result.getMessage())));
} else {
completionException = new CompletionException(new BraintreeException(result.getMessage()));
@@ -458,9 +456,8 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
return cancelSubscriptionAtEndOfCurrentPeriod(subscription)
.thenCompose(ignored -> {
final Transaction transaction = getLatestTransactionForSubscription(subscription).orElseThrow(
() -> new ClientErrorException(
Response.Status.CONFLICT));
final Transaction transaction = getLatestTransactionForSubscription(subscription)
.orElseThrow(() -> ExceptionUtils.wrap(new SubscriptionException.ProcessorConflict()));
final Customer customer = transaction.getCustomer();
@@ -611,12 +608,9 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
if (!getPaymentStatus(transaction.getStatus()).equals(PaymentStatus.SUCCEEDED)) {
final SubscriptionStatus subscriptionStatus = getSubscriptionStatus(subscription.getStatus(), true);
if (subscriptionStatus.equals(SubscriptionStatus.ACTIVE) || subscriptionStatus.equals(SubscriptionStatus.PAST_DUE)) {
throw new WebApplicationException(Response.Status.NO_CONTENT);
throw ExceptionUtils.wrap(new SubscriptionException.ReceiptRequestedForOpenPayment());
}
throw new WebApplicationException(Response.status(Response.Status.PAYMENT_REQUIRED)
.entity(Map.of("chargeFailure", createChargeFailure(transaction)))
.build());
throw ExceptionUtils.wrap(new SubscriptionException.ChargeFailurePaymentRequired(createChargeFailure(transaction)));
}
final Instant paidAt = transaction.getSubscriptionDetails().getBillingPeriodStartDate().toInstant();
@@ -632,7 +626,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
return new ReceiptItem(transaction.getId(), PaymentTime.periodStart(paidAt), metadata.level());
})
.orElseThrow(() -> new WebApplicationException(Response.Status.NO_CONTENT)));
.orElseThrow(() -> ExceptionUtils.wrap(new SubscriptionException.ReceiptRequestedForOpenPayment())));
}
private static Subscription getSubscription(Object subscriptionObj) {
@@ -12,6 +12,7 @@ import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.androidpublisher.AndroidPublisher;
import com.google.api.services.androidpublisher.AndroidPublisherRequest;
import com.google.api.services.androidpublisher.AndroidPublisherScopes;
import com.google.api.services.androidpublisher.model.AutoRenewingPlan;
import com.google.api.services.androidpublisher.model.BasePlan;
import com.google.api.services.androidpublisher.model.OfferDetails;
import com.google.api.services.androidpublisher.model.RegionalBasePlanConfig;
@@ -230,6 +231,7 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
return subscriptionFuture.thenCombineAsync(priceFuture, (subscription, price) -> {
final SubscriptionPurchaseLineItem lineItem = getLineItem(subscription);
final Optional<Instant> billingCycleAnchor = getStartTime(subscription);
final Optional<Instant> expiration = getExpiration(lineItem);
final SubscriptionStatus status = switch (SubscriptionState
@@ -243,12 +245,17 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
case UNSPECIFIED -> SubscriptionStatus.UNKNOWN;
};
final boolean autoRenewEnabled = Optional
.ofNullable(lineItem.getAutoRenewingPlan())
.map(AutoRenewingPlan::getAutoRenewEnabled) // returns null or false if auto-renew disabled
.orElse(false);
return new SubscriptionInformation(
price,
productIdToLevel(lineItem.getProductId()),
null, expiration.orElse(null),
billingCycleAnchor.orElse(null),
expiration.orElse(null),
expiration.map(clock.instant()::isBefore).orElse(false),
lineItem.getAutoRenewingPlan() != null && lineItem.getAutoRenewingPlan().getAutoRenewEnabled(),
!autoRenewEnabled,
status,
PaymentProvider.GOOGLE_PLAY_BILLING,
PaymentMethod.GOOGLE_PLAY_BILLING,
@@ -385,18 +392,27 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
"acknowledgementState", subscription.getAcknowledgementState());
}
private Optional<Instant> getStartTime(final SubscriptionPurchaseV2 subscription) {
return parseTimestamp(subscription.getStartTime());
}
private Optional<Instant> getExpiration(final SubscriptionPurchaseLineItem purchaseLineItem) {
if (StringUtils.isBlank(purchaseLineItem.getExpiryTime())) {
return parseTimestamp(purchaseLineItem.getExpiryTime());
}
private Optional<Instant> parseTimestamp(final String timestamp) {
if (StringUtils.isBlank(timestamp)) {
return Optional.empty();
}
try {
return Optional.of(Instant.parse(purchaseLineItem.getExpiryTime()));
return Optional.of(Instant.parse(timestamp));
} catch (DateTimeParseException e) {
logger.warn("received an expiry time with an invalid format: {}", purchaseLineItem.getExpiryTime());
logger.warn("received a timestamp with an invalid format: {}", timestamp);
return Optional.empty();
}
}
// https://developers.google.com/android-publisher/api-ref/rest/v3/purchases.subscriptionsv2#SubscriptionState
@VisibleForTesting
enum SubscriptionState {
@@ -456,5 +472,4 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
return s;
}
}
}
@@ -40,6 +40,7 @@ import com.stripe.param.SubscriptionRetrieveParams;
import com.stripe.param.SubscriptionUpdateParams;
import com.stripe.param.SubscriptionUpdateParams.BillingCycleAnchor;
import com.stripe.param.SubscriptionUpdateParams.ProrationBehavior;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
@@ -55,6 +56,7 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
@@ -64,17 +66,13 @@ import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.ws.rs.ClientErrorException;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.storage.PaymentTime;
import org.whispersystems.textsecuregcm.storage.SubscriptionException;
import org.whispersystems.textsecuregcm.util.Conversions;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor {
@@ -199,7 +197,8 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
}
/**
* Creates a payment intent. May throw a 400 WebApplicationException if the amount is too small.
* Creates a payment intent. May throw a
* {@link SubscriptionException.AmountTooSmall} if the amount is too small.
*/
public CompletableFuture<PaymentIntent> createPaymentIntent(final String currency,
final long amount,
@@ -221,10 +220,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
return stripeClient.paymentIntents().create(builder.build(), commonOptions());
} catch (StripeException e) {
if ("amount_too_small".equalsIgnoreCase(e.getCode())) {
throw new WebApplicationException(Response
.status(Status.BAD_REQUEST)
.entity(Map.of("error", "amount_too_small"))
.build());
throw ExceptionUtils.wrap(new SubscriptionException.AmountTooSmall());
} else {
throw new CompletionException(e);
}
@@ -301,7 +297,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
if (e instanceof CardException ce) {
throw new CompletionException(
new SubscriptionProcessorException(getProvider(), createChargeFailureFromCardException(e, ce)));
new SubscriptionException.ProcessorException(getProvider(), createChargeFailureFromCardException(e, ce)));
}
throw new CompletionException(e);
@@ -354,10 +350,10 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
} catch (StripeException e) {
if (e instanceof CardException ce) {
throw new CompletionException(
new SubscriptionProcessorException(getProvider(), createChargeFailureFromCardException(e, ce)));
throw ExceptionUtils.wrap(
new SubscriptionException.ProcessorException(getProvider(), createChargeFailureFromCardException(e, ce)));
}
throw new CompletionException(e);
throw ExceptionUtils.wrap(e);
}
}, executor)
@@ -383,8 +379,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
public CompletableFuture<Void> cancelAllActiveSubscriptions(String customerId) {
return getCustomer(customerId).thenCompose(customer -> {
if (customer == null) {
throw new InternalServerErrorException(
"no customer record found for id " + customerId);
throw ExceptionUtils.wrap(new IOException("no customer record found for id " + customerId));
}
return listNonCanceledSubscriptions(customer);
}).thenCompose(subscriptions -> {
@@ -607,20 +602,23 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
private CompletableFuture<ReceiptItem> convertInvoiceToReceipt(Invoice latestSubscriptionInvoice, String subscriptionId) {
if (latestSubscriptionInvoice == null) {
throw new WebApplicationException(Status.NO_CONTENT);
return CompletableFuture.failedFuture(
ExceptionUtils.wrap(new SubscriptionException.ReceiptRequestedForOpenPayment()));
}
if (StringUtils.equalsIgnoreCase("open", latestSubscriptionInvoice.getStatus())) {
throw new WebApplicationException(Status.NO_CONTENT);
return CompletableFuture.failedFuture(
ExceptionUtils.wrap(new SubscriptionException.ReceiptRequestedForOpenPayment()));
}
if (!StringUtils.equalsIgnoreCase("paid", latestSubscriptionInvoice.getStatus())) {
final Response.ResponseBuilder responseBuilder = Response.status(Status.PAYMENT_REQUIRED);
if (latestSubscriptionInvoice.getChargeObject() != null) {
final Charge charge = latestSubscriptionInvoice.getChargeObject();
if (charge.getFailureCode() != null || charge.getFailureMessage() != null) {
responseBuilder.entity(Map.of("chargeFailure", createChargeFailure(charge)));
}
}
throw new WebApplicationException(responseBuilder.build());
return CompletableFuture.failedFuture(ExceptionUtils.wrap(Optional
.ofNullable(latestSubscriptionInvoice.getChargeObject())
// If the charge object has a failure reason we can present to the user, create a detailed exception
.filter(charge -> charge.getFailureCode() != null || charge.getFailureMessage() != null)
.<SubscriptionException> map(charge -> new SubscriptionException.ChargeFailurePaymentRequired(createChargeFailure(charge)))
// Otherwise, return a generic payment required error
.orElseGet(() -> new SubscriptionException.PaymentRequired())));
}
return getInvoiceLineItemsForInvoice(latestSubscriptionInvoice).thenCompose(invoiceLineItems -> {
@@ -684,15 +682,15 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
// This usually indicates that the client has made requests out of order, either by not confirming
// the SetupIntent or not having the user authorize the transaction.
logger.debug("setupIntent {} missing expected fields", setupIntentId);
throw new ClientErrorException(Status.CONFLICT);
throw ExceptionUtils.wrap(new SubscriptionException.ProcessorConflict());
}
return setupIntent.getLatestAttemptObject().getPaymentMethodDetails().getIdeal().getGeneratedSepaDebit();
} catch (StripeException e) {
if (e.getStatusCode() == 404) {
throw new NotFoundException();
throw ExceptionUtils.wrap(new SubscriptionException.NotFound());
}
logger.error("unexpected error from Stripe when retrieving setupIntent {}", setupIntentId, e);
throw new CompletionException(e);
throw ExceptionUtils.wrap(e);
}
}, executor);
}
@@ -1,26 +0,0 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.subscriptions;
public class SubscriptionProcessorException extends Exception {
private final PaymentProvider processor;
private final ChargeFailure chargeFailure;
public SubscriptionProcessorException(final PaymentProvider processor,
final ChargeFailure chargeFailure) {
this.processor = processor;
this.chargeFailure = chargeFailure;
}
public PaymentProvider getProcessor() {
return processor;
}
public ChargeFailure getChargeFailure() {
return chargeFailure;
}
}
@@ -7,22 +7,17 @@ package org.whispersystems.textsecuregcm.websocket;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.Timer;
import java.util.EnumMap;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor;
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.metrics.OpenWebSocketCounter;
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
@@ -30,19 +25,15 @@ import org.whispersystems.textsecuregcm.push.ReceiptSender;
import org.whispersystems.textsecuregcm.redis.RedisOperation;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
import org.whispersystems.websocket.session.WebSocketSessionContext;
import org.whispersystems.websocket.setup.WebSocketConnectListener;
import reactor.core.scheduler.Scheduler;
public class AuthenticatedConnectListener implements WebSocketConnectListener {
private static final String OPEN_WEBSOCKET_COUNTER_NAME =
name(WebSocketConnection.class, "openWebsockets");
private static final String CONNECTED_DURATION_TIMER_NAME = name(AuthenticatedConnectListener.class,
"connectedDuration");
private static final String OPEN_WEBSOCKET_GAUGE_NAME = name(WebSocketConnection.class, "openWebsockets");
private static final String CONNECTED_DURATION_TIMER_NAME =
name(AuthenticatedConnectListener.class, "connectedDuration");
private static final String AUTHENTICATED_TAG_NAME = "authenticated";
@@ -61,15 +52,8 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
private final ClientReleaseManager clientReleaseManager;
private final MessageDeliveryLoopMonitor messageDeliveryLoopMonitor;
private final Map<ClientPlatform, AtomicInteger> openAuthenticatedWebsocketsByClientPlatform;
private final Map<ClientPlatform, AtomicInteger> openUnauthenticatedWebsocketsByClientPlatform;
private final Map<ClientPlatform, Timer> durationTimersByClientPlatform;
private final Map<ClientPlatform, Timer> unauthenticatedDurationTimersByClientPlatform;
private final AtomicInteger openAuthenticatedWebsocketsFromUnknownPlatforms;
private final AtomicInteger openUnauthenticatedWebsocketsFromUnknownPlatforms;
private final Timer durationTimerForUnknownPlatforms;
private final Timer unauthenticatedDurationTimerForUnknownPlatforms;
private final OpenWebSocketCounter openAuthenticatedWebSocketCounter;
private final OpenWebSocketCounter openUnauthenticatedWebSocketCounter;
public AuthenticatedConnectListener(ReceiptSender receiptSender,
MessagesManager messagesManager,
@@ -92,60 +76,24 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
this.clientReleaseManager = clientReleaseManager;
this.messageDeliveryLoopMonitor = messageDeliveryLoopMonitor;
openAuthenticatedWebsocketsByClientPlatform = new EnumMap<>(ClientPlatform.class);
openUnauthenticatedWebsocketsByClientPlatform = new EnumMap<>(ClientPlatform.class);
durationTimersByClientPlatform = new EnumMap<>(ClientPlatform.class);
unauthenticatedDurationTimersByClientPlatform = new EnumMap<>(ClientPlatform.class);
openAuthenticatedWebSocketCounter =
new OpenWebSocketCounter(OPEN_WEBSOCKET_GAUGE_NAME, CONNECTED_DURATION_TIMER_NAME, Tags.of(AUTHENTICATED_TAG_NAME, "true"));
final Tags authenticatedTag = Tags.of(AUTHENTICATED_TAG_NAME, "true");
final Tags unauthenticatedTag = Tags.of(AUTHENTICATED_TAG_NAME, "false");
for (final ClientPlatform clientPlatform : ClientPlatform.values()) {
openAuthenticatedWebsocketsByClientPlatform.put(clientPlatform, new AtomicInteger(0));
openUnauthenticatedWebsocketsByClientPlatform.put(clientPlatform, new AtomicInteger(0));
final Tags clientPlatformTag = Tags.of(UserAgentTagUtil.PLATFORM_TAG, clientPlatform.name().toLowerCase());
Metrics.gauge(OPEN_WEBSOCKET_COUNTER_NAME, clientPlatformTag.and(authenticatedTag),
openAuthenticatedWebsocketsByClientPlatform.get(clientPlatform));
Metrics.gauge(OPEN_WEBSOCKET_COUNTER_NAME, clientPlatformTag.and(unauthenticatedTag),
openUnauthenticatedWebsocketsByClientPlatform.get(clientPlatform));
durationTimersByClientPlatform.put(clientPlatform,
Metrics.timer(CONNECTED_DURATION_TIMER_NAME, clientPlatformTag.and(authenticatedTag)));
unauthenticatedDurationTimersByClientPlatform.put(clientPlatform,
Metrics.timer(CONNECTED_DURATION_TIMER_NAME, clientPlatformTag.and(unauthenticatedTag)));
}
openAuthenticatedWebsocketsFromUnknownPlatforms = new AtomicInteger(0);
openUnauthenticatedWebsocketsFromUnknownPlatforms = new AtomicInteger(0);
final Tags unrecognizedPlatform = Tags.of(UserAgentTagUtil.PLATFORM_TAG, "unrecognized");
Metrics.gauge(OPEN_WEBSOCKET_COUNTER_NAME, unrecognizedPlatform.and(authenticatedTag),
openAuthenticatedWebsocketsFromUnknownPlatforms);
Metrics.gauge(OPEN_WEBSOCKET_COUNTER_NAME, unrecognizedPlatform.and(unauthenticatedTag),
openUnauthenticatedWebsocketsFromUnknownPlatforms);
durationTimerForUnknownPlatforms = Metrics.timer(CONNECTED_DURATION_TIMER_NAME,
unrecognizedPlatform.and(authenticatedTag));
unauthenticatedDurationTimerForUnknownPlatforms = Metrics.timer(CONNECTED_DURATION_TIMER_NAME,
unrecognizedPlatform.and(unauthenticatedTag));
openUnauthenticatedWebSocketCounter =
new OpenWebSocketCounter(OPEN_WEBSOCKET_GAUGE_NAME, CONNECTED_DURATION_TIMER_NAME, Tags.of(AUTHENTICATED_TAG_NAME, "false"));
}
@Override
public void onWebSocketConnect(WebSocketSessionContext context) {
final boolean authenticated = (context.getAuthenticated() != null);
final String userAgent = context.getClient().getUserAgent();
final AtomicInteger openWebsocketAtomicInteger = getOpenWebsocketCounter(userAgent, authenticated);
final Timer connectionTimer = getConnectionTimer(userAgent, authenticated);
final OpenWebSocketCounter openWebSocketCounter =
authenticated ? openAuthenticatedWebSocketCounter : openUnauthenticatedWebSocketCounter;
openWebSocketCounter.countOpenWebSocket(context);
if (authenticated) {
final AuthenticatedDevice auth = context.getAuthenticated(AuthenticatedDevice.class);
final Timer.Sample sample = Timer.start();
final WebSocketConnection connection = new WebSocketConnection(receiptSender,
messagesManager,
messageMetrics,
@@ -158,14 +106,9 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
clientReleaseManager,
messageDeliveryLoopMonitor);
openWebsocketAtomicInteger.incrementAndGet();
final AtomicReference<ScheduledFuture<?>> renewPresenceFutureReference = new AtomicReference<>();
context.addWebsocketClosedListener((closingContext, statusCode, reason) -> {
openWebsocketAtomicInteger.decrementAndGet();
sample.stop(connectionTimer);
final ScheduledFuture<?> renewPresenceFuture = renewPresenceFutureReference.get();
if (renewPresenceFuture != null) {
@@ -214,40 +157,6 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
log.warn("Failed to initialize websocket", e);
context.getClient().close(1011, "Unexpected error initializing connection");
}
} else {
openWebsocketAtomicInteger.incrementAndGet();
final Timer.Sample sample = Timer.start();
context.addWebsocketClosedListener((context1, statusCode, reason) -> {
openWebsocketAtomicInteger.decrementAndGet();
sample.stop(connectionTimer);
});
}
}
private AtomicInteger getOpenWebsocketCounter(final String userAgentString, final boolean authenticated) {
try {
final ClientPlatform platform = UserAgentUtil.parseUserAgentString(userAgentString).getPlatform();
return authenticated
? openAuthenticatedWebsocketsByClientPlatform.get(platform)
: openUnauthenticatedWebsocketsByClientPlatform.get(platform);
} catch (final UnrecognizedUserAgentException e) {
return authenticated
? openAuthenticatedWebsocketsFromUnknownPlatforms
: openUnauthenticatedWebsocketsFromUnknownPlatforms;
}
}
private Timer getConnectionTimer(final String userAgentString,
final boolean authenticated) {
try {
final ClientPlatform platform = UserAgentUtil.parseUserAgentString(userAgentString).getPlatform();
return authenticated
? durationTimersByClientPlatform.get(platform)
: unauthenticatedDurationTimersByClientPlatform.get(platform);
} catch (final UnrecognizedUserAgentException e) {
return authenticated
? durationTimerForUnknownPlatforms
: unauthenticatedDurationTimerForUnknownPlatforms;
}
}
}
@@ -1,37 +0,0 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.websocket;
import java.security.SecureRandom;
import java.util.Base64;
public class ProvisioningAddress extends WebsocketAddress {
public static byte DEVICE_ID = 0;
public static ProvisioningAddress create(String address) {
return new ProvisioningAddress(address, DEVICE_ID);
}
private ProvisioningAddress(String address, byte deviceId) {
super(address, deviceId);
}
public ProvisioningAddress(String serialized) throws InvalidWebsocketAddressException {
super(serialized);
}
public String getAddress() {
return getNumber();
}
public static ProvisioningAddress generate() {
byte[] random = new byte[16];
new SecureRandom().nextBytes(random);
return create(Base64.getUrlEncoder().withoutPadding().encodeToString(random));
}
}
@@ -5,26 +5,52 @@
package org.whispersystems.textsecuregcm.websocket;
import com.google.common.annotations.VisibleForTesting;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.List;
import java.util.Optional;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.entities.ProvisioningMessage;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.OpenWebSocketCounter;
import org.whispersystems.textsecuregcm.push.ProvisioningManager;
import org.whispersystems.textsecuregcm.storage.PubSubProtos;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.websocket.session.WebSocketSessionContext;
import org.whispersystems.websocket.setup.WebSocketConnectListener;
import java.util.List;
import java.util.Optional;
/**
* A "provisioning WebSocket" provides a mechanism for sending a caller-defined provisioning message from the primary
* device associated with a Signal account to a new device that is not yet associated with a Signal account. Generally,
* the message contains key material and credentials the new device needs to associate itself with the primary device's
* Signal account.
* <p>
* New devices initiate the provisioning process by opening a provisioning WebSocket. The server assigns the new device
* a random, temporary "provisioning address," which it transmits via the newly-opened WebSocket. From there, the new
* device generally displays the provisioning address (and a public key) as a QR code. After that, the primary device
* will scan the QR code and send an encrypted provisioning message to the new device via
* {@link org.whispersystems.textsecuregcm.controllers.ProvisioningController#sendProvisioningMessage(AuthenticatedDevice, String, ProvisioningMessage, String)}.
* Once the server receives the message from the primary device, it sends the message to the new device via the open
* WebSocket, then closes the WebSocket connection.
*/
public class ProvisioningConnectListener implements WebSocketConnectListener {
private final ProvisioningManager provisioningManager;
private final OpenWebSocketCounter openWebSocketCounter;
public ProvisioningConnectListener(final ProvisioningManager provisioningManager) {
this.provisioningManager = provisioningManager;
this.openWebSocketCounter = new OpenWebSocketCounter(MetricsUtil.name(getClass(), "openWebsockets"),
MetricsUtil.name(getClass(), "sessionDuration"));
}
@Override
public void onWebSocketConnect(WebSocketSessionContext context) {
final ProvisioningAddress provisioningAddress = ProvisioningAddress.generate();
openWebSocketCounter.countOpenWebSocket(context);
final String provisioningAddress = generateProvisioningAddress();
context.addWebsocketClosedListener((context1, statusCode, reason) -> provisioningManager.removeListener(provisioningAddress));
provisioningManager.addListener(provisioningAddress, message -> {
@@ -37,9 +63,16 @@ public class ProvisioningConnectListener implements WebSocketConnectListener {
});
context.getClient().sendRequest("PUT", "/v1/address", List.of(HeaderUtils.getTimestampHeader()),
Optional.of(MessageProtos.ProvisioningUuid.newBuilder()
.setUuid(provisioningAddress.getAddress())
.build()
.toByteArray()));
Optional.of(MessageProtos.ProvisioningAddress.newBuilder()
.setAddress(provisioningAddress)
.build().toByteArray()));
}
@VisibleForTesting
public static String generateProvisioningAddress() {
final byte[] provisioningAddress = new byte[16];
new SecureRandom().nextBytes(provisioningAddress);
return Base64.getUrlEncoder().encodeToString(provisioningAddress);
}
}
@@ -1,68 +0,0 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.websocket;
import org.whispersystems.textsecuregcm.storage.PubSubAddress;
public class WebsocketAddress implements PubSubAddress {
private final String number;
private final byte deviceId;
public WebsocketAddress(String number, byte deviceId) {
this.number = number;
this.deviceId = deviceId;
}
public WebsocketAddress(String serialized) throws InvalidWebsocketAddressException {
try {
String[] parts = serialized.split(":", 2);
if (parts.length != 2) {
throw new InvalidWebsocketAddressException("Bad address: " + serialized);
}
this.number = parts[0];
this.deviceId = Byte.parseByte(parts[1]);
} catch (NumberFormatException e) {
throw new InvalidWebsocketAddressException(e);
}
}
public String getNumber() {
return number;
}
public byte getDeviceId() {
return deviceId;
}
public String serialize() {
return number + ":" + deviceId;
}
public String toString() {
return serialize();
}
@Override
public boolean equals(Object other) {
if (other == null) return false;
if (!(other instanceof WebsocketAddress)) return false;
WebsocketAddress that = (WebsocketAddress)other;
return
this.number.equals(that.number) &&
this.deviceId == that.deviceId;
}
@Override
public int hashCode() {
return number.hashCode() ^ (int)deviceId;
}
}
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.workers;
import static com.codahale.metrics.MetricRegistry.name;
import com.codahale.metrics.MetricRegistry;
import com.fasterxml.jackson.databind.DeserializationFeature;
import io.dropwizard.core.setup.Environment;
import io.lettuce.core.resource.ClientResources;
@@ -32,6 +33,8 @@ import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery2Controller;
import org.whispersystems.textsecuregcm.experiment.PushNotificationExperimentSamples;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.MicrometerAwsSdkMetricPublisher;
import org.whispersystems.textsecuregcm.metrics.NoopAwsSdkMetricPublisher;
import org.whispersystems.textsecuregcm.push.APNSender;
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
@@ -148,11 +151,14 @@ record CommandDependencies(
ExternalServiceCredentialsGenerator secureValueRecoveryCredentialsGenerator = SecureValueRecovery2Controller.credentialsGenerator(
configuration.getSvr2Configuration());
final ExecutorService awsSdkMetricsExecutor = environment.lifecycle()
.virtualExecutorService(MetricRegistry.name(CommandDependencies.class, "awsSdkMetrics-%d"));
DynamoDbAsyncClient dynamoDbAsyncClient = configuration.getDynamoDbClientConfiguration()
.buildAsyncClient(awsCredentialsProvider);
.buildAsyncClient(awsCredentialsProvider, new MicrometerAwsSdkMetricPublisher(awsSdkMetricsExecutor, "dynamoDbAsyncCommand"));
DynamoDbClient dynamoDbClient = configuration.getDynamoDbClientConfiguration()
.buildSyncClient(awsCredentialsProvider);
.buildSyncClient(awsCredentialsProvider, new MicrometerAwsSdkMetricPublisher(awsSdkMetricsExecutor, "dynamoDbSyncCommand"));
RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
configuration.getDynamoDbTables().getRegistrationRecovery().getTableName(),
@@ -22,7 +22,7 @@ import java.time.Duration;
import java.time.Instant;
import java.time.LocalTime;
public class NotifyIdleDevicesWithoutMessagesCommand extends AbstractSinglePassCrawlAccountsCommand {
public class NotifyIdleDevicesCommand extends AbstractSinglePassCrawlAccountsCommand {
private static final int DEFAULT_MAX_CONCURRENCY = 16;
@@ -36,23 +36,29 @@ public class NotifyIdleDevicesWithoutMessagesCommand extends AbstractSinglePassC
static final LocalTime PREFERRED_NOTIFICATION_TIME = LocalTime.of(14, 0);
@VisibleForTesting
static final Duration MIN_IDLE_DURATION = Duration.ofDays(30);
static final Duration MIN_SHORT_IDLE_DURATION = Duration.ofDays(3);
@VisibleForTesting
static final Duration MAX_IDLE_DURATION = Duration.ofDays(45);
static final Duration MAX_SHORT_IDLE_DURATION = Duration.ofDays(30);
@VisibleForTesting
static final Duration MIN_LONG_IDLE_DURATION = Duration.ofDays(30);
@VisibleForTesting
static final Duration MAX_LONG_IDLE_DURATION = Duration.ofDays(45);
private static final Counter DEVICE_INSPECTED_COUNTER =
Metrics.counter(MetricsUtil.name(NotifyIdleDevicesWithoutMessagesCommand.class, "deviceInspected"));
Metrics.counter(MetricsUtil.name(NotifyIdleDevicesCommand.class, "deviceInspected"));
private static final String SCHEDULED_NOTIFICATION_COUNTER_NAME =
MetricsUtil.name(NotifyIdleDevicesWithoutMessagesCommand.class, "scheduleNotification");
MetricsUtil.name(NotifyIdleDevicesCommand.class, "scheduleNotification");
private static final String DRY_RUN_TAG_NAME = "dryRun";
private static final Logger log = LoggerFactory.getLogger(NotifyIdleDevicesWithoutMessagesCommand.class);
private static final Logger log = LoggerFactory.getLogger(NotifyIdleDevicesCommand.class);
public NotifyIdleDevicesWithoutMessagesCommand() {
super("notify-idle-devices-without-messages", "Schedules push notifications for devices that have been idle for a long time, but have no pending messages");
public NotifyIdleDevicesCommand() {
super("notify-idle-devices", "Schedules push notifications for idle devices");
}
@Override
@@ -136,28 +142,46 @@ public class NotifyIdleDevicesWithoutMessagesCommand extends AbstractSinglePassC
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 (!isIdle(device, clock)) {
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);
}
return Mono.fromFuture(messagesManager.mayHavePersistedMessages(account.getIdentifier(IdentityType.ACI), device))
.map(mayHavePersistedMessages -> !mayHavePersistedMessages);
}
@VisibleForTesting
static boolean isIdle(final Device device, final Clock clock) {
static boolean isShortIdle(final Device device, final Clock clock) {
final Duration idleDuration = Duration.between(Instant.ofEpochMilli(device.getLastSeen()), clock.instant());
return idleDuration.compareTo(MIN_IDLE_DURATION) >= 0 && idleDuration.compareTo(MAX_IDLE_DURATION) < 0;
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) {
// Exclude VOIP tokens since they have their own, distinct delivery mechanism
return !StringUtils.isAllBlank(device.getApnId(), device.getGcmId()) && StringUtils.isBlank(device.getVoipApnId());
return !StringUtils.isAllBlank(device.getApnId(), device.getGcmId());
}
}
@@ -1,31 +0,0 @@
package org.whispersystems.textsecuregcm.workers;
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
import org.whispersystems.textsecuregcm.configuration.DynamoDbTables;
import org.whispersystems.textsecuregcm.experiment.DeviceLastSeenState;
import org.whispersystems.textsecuregcm.experiment.NotifyIdleDevicesWithMessagesExperiment;
import org.whispersystems.textsecuregcm.experiment.PushNotificationExperiment;
import org.whispersystems.textsecuregcm.push.IdleDeviceNotificationScheduler;
import java.time.Clock;
public class NotifyIdleDevicesWithMessagesExperimentFactory implements PushNotificationExperimentFactory<DeviceLastSeenState> {
@Override
public PushNotificationExperiment<DeviceLastSeenState> buildExperiment(final CommandDependencies commandDependencies,
final WhisperServerConfiguration configuration) {
final DynamoDbTables.TableWithExpiration tableConfiguration = configuration.getDynamoDbTables().getScheduledJobs();
final Clock clock = Clock.systemUTC();
return new NotifyIdleDevicesWithMessagesExperiment(new IdleDeviceNotificationScheduler(
commandDependencies.accountsManager(),
commandDependencies.pushNotificationManager(),
commandDependencies.dynamoDbAsyncClient(),
tableConfiguration.getTableName(),
tableConfiguration.getExpiration(),
clock),
commandDependencies.messagesManager(),
clock);
}
}
@@ -1,11 +1,17 @@
package org.whispersystems.textsecuregcm.workers;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.core.Application;
import io.dropwizard.core.cli.ServerCommand;
import io.dropwizard.core.server.DefaultServerFactory;
import io.dropwizard.core.setup.Environment;
import io.dropwizard.jetty.HttpsConnectorFactory;
import io.dropwizard.lifecycle.Managed;
import io.dropwizard.util.Duration;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import org.slf4j.Logger;
@@ -14,9 +20,8 @@ import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.scheduler.JobScheduler;
import org.whispersystems.textsecuregcm.util.logging.UncaughtExceptionHandler;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import reactor.core.Disposable;
import reactor.core.Disposables;
public class ProcessScheduledJobsServiceCommand extends ServerCommand<WhisperServerConfiguration> {
@@ -25,10 +30,13 @@ public class ProcessScheduledJobsServiceCommand extends ServerCommand<WhisperSer
private static final String FIXED_DELAY_SECONDS_ARGUMENT = "fixedDelay";
private static final int DEFAULT_FIXED_DELAY_SECONDS = 60;
private static final String SHUTDOWN_WAIT_SECONDS_ARGUMENT = "shutdownWait";
private static final int DEFAULT_SHUTDOWN_WAIT_SECONDS = 60;
private static final Logger log = LoggerFactory.getLogger(ProcessScheduledJobsServiceCommand.class);
private static class ScheduledJobProcessor implements Managed {
@VisibleForTesting
static class ScheduledJobProcessor implements Managed {
private final JobScheduler jobScheduler;
@@ -36,8 +44,11 @@ public class ProcessScheduledJobsServiceCommand extends ServerCommand<WhisperSer
private final int fixedDelaySeconds;
private ScheduledFuture<?> processJobsFuture;
private Disposable processAvailableJobsDisposableReference = Disposables.disposed();
private boolean stopped = false;
private ScheduledJobProcessor(final JobScheduler jobScheduler,
@VisibleForTesting
ScheduledJobProcessor(final JobScheduler jobScheduler,
final ScheduledExecutorService scheduledExecutorService,
final int fixedDelaySeconds) {
@@ -49,20 +60,41 @@ public class ProcessScheduledJobsServiceCommand extends ServerCommand<WhisperSer
@Override
public void start() {
processJobsFuture = scheduledExecutorService.scheduleWithFixedDelay(() -> {
final CountDownLatch latch = new CountDownLatch(1);
synchronized (this) {
if (stopped) {
return;
}
processAvailableJobsDisposableReference = jobScheduler.processAvailableJobs()
// this CountDownLatch pattern is how Mono.block() is implemented
.doOnCancel(latch::countDown)
.doOnTerminate(latch::countDown)
.doOnError(e ->
log.warn("Failed to process available jobs for scheduler: {}", jobScheduler.getSchedulerName(), e))
.subscribe();
}
try {
jobScheduler.processAvailableJobs().join();
} catch (final Exception e) {
latch.await();
} catch (final InterruptedException e) {
log.warn("Failed to process available jobs for scheduler: {}", jobScheduler.getSchedulerName(), e);
}
}, 0, fixedDelaySeconds, TimeUnit.SECONDS);
}
@Override
public void stop() {
public synchronized void stop() {
stopped = true;
if (processJobsFuture != null) {
processJobsFuture.cancel(false);
}
processAvailableJobsDisposableReference.dispose();
processJobsFuture = null;
}
}
@@ -91,6 +123,12 @@ public class ProcessScheduledJobsServiceCommand extends ServerCommand<WhisperSer
.dest(FIXED_DELAY_SECONDS_ARGUMENT)
.setDefault(DEFAULT_FIXED_DELAY_SECONDS)
.help("The delay, in seconds, between queries for jobs to process");
subparser.addArgument("--shutdown-wait")
.type(Integer.class)
.dest(SHUTDOWN_WAIT_SECONDS_ARGUMENT)
.setDefault(DEFAULT_SHUTDOWN_WAIT_SECONDS)
.help("The duration, in seconds, to wait for in-flight jobs to finish at shutdown");
}
@Override
@@ -104,6 +142,7 @@ public class ProcessScheduledJobsServiceCommand extends ServerCommand<WhisperSer
final CommandDependencies commandDependencies = CommandDependencies.build(name, environment, configuration);
final int fixedDelaySeconds = namespace.getInt(FIXED_DELAY_SECONDS_ARGUMENT);
final int shutdownWaitSeconds = namespace.getInt(SHUTDOWN_WAIT_SECONDS_ARGUMENT);
MetricsUtil.configureRegistries(configuration, environment, commandDependencies.dynamicConfigurationManager());
@@ -120,6 +159,7 @@ public class ProcessScheduledJobsServiceCommand extends ServerCommand<WhisperSer
final ScheduledExecutorService scheduledExecutorService =
environment.lifecycle().scheduledExecutorService("scheduled-job-processor-%d", false)
.shutdownTime(Duration.seconds(shutdownWaitSeconds))
.build();
final JobScheduler jobScheduler = jobSchedulerFactory.buildJobScheduler(commandDependencies, configuration);
+2 -2
View File
@@ -38,8 +38,8 @@ message Envelope {
// next: 19
}
message ProvisioningUuid {
optional string uuid = 1;
message ProvisioningAddress {
optional string address = 1;
}
message ServerCertificate {
@@ -107,13 +107,6 @@ message SetPushTokenRequest {
* A "standard" APNs device token.
*/
string apns_token = 1;
/**
* A VoIP APNs device token. If present, the server will prefer to send
* message notifications to the device using this token on a VOIP APNs
* topic.
*/
string apns_voip_token = 2;
}
message FcmTokenRequest {
@@ -1,70 +0,0 @@
local pendingNotificationQueue = KEYS[1]
local maxTime = ARGV[1]
local limit = ARGV[2]
local hgetall = function (key)
local bulk = redis.call('HGETALL', key)
local result = {}
local nextkey
for i, v in ipairs(bulk) do
if i % 2 == 1 then
nextkey = v
else
result[nextkey] = v
end
end
return result
end
local getNextInterval = function(interval)
if interval < 20000 then
return 20000
end
if interval < 40000 then
return 40000
end
if interval < 80000 then
return 80000
end
if interval < 160000 then
return 160000
end
if interval < 600000 then
return 600000
end
if interval < 1800000 then
return 1800000
end
return 3600000
end
local results = redis.call("ZRANGE", pendingNotificationQueue, 0, maxTime, "BYSCORE", "LIMIT", 0, limit)
local collated = {}
if results and next(results) then
for i, name in ipairs(results) do
local pending = hgetall(name)
local lastInterval = pending["interval"]
if lastInterval == nil then
lastInterval = 0
end
local nextInterval = getNextInterval(tonumber(lastInterval))
redis.call("HSET", name, "interval", nextInterval)
redis.call("ZADD", pendingNotificationQueue, tonumber(maxTime) + nextInterval, name)
collated[i] = pending["account"] .. ":" .. pending["device"]
end
end
return collated
@@ -1,14 +0,0 @@
local pendingNotificationQueue = KEYS[1]
local endpoint = KEYS[2]
local timestamp = ARGV[1]
local interval = ARGV[2]
local account = ARGV[3]
local deviceId = ARGV[4]
redis.call("HSET", endpoint, "created", timestamp)
redis.call("HSET", endpoint, "interval", interval)
redis.call("HSET", endpoint, "account", account)
redis.call("HSET", endpoint, "device", deviceId)
redis.call("ZADD", pendingNotificationQueue, timestamp, endpoint)
@@ -1,5 +0,0 @@
local pendingNotificationQueue = KEYS[1]
local endpoint = KEYS[2]
redis.call("DEL", endpoint)
return redis.call("ZREM", pendingNotificationQueue, endpoint)
@@ -17,8 +17,8 @@ local messageId = redis.call("HINCRBY", queueMetadataKey, "counter", 1)
redis.call("ZADD", queueKey, "NX", messageId, message)
redis.call("HSET", queueMetadataKey, guid, messageId)
redis.call("EXPIRE", queueKey, 2678400) -- 31 days
redis.call("EXPIRE", queueMetadataKey, 2678400) -- 31 days
redis.call("EXPIRE", queueKey, 3974400) -- 46 days
redis.call("EXPIRE", queueMetadataKey, 3974400) -- 46 days
redis.call("ZADD", queueTotalIndexKey, "NX", currentTime, queueKey)
return messageId
@@ -13,19 +13,23 @@ import io.dropwizard.testing.junit5.DropwizardAppExtension;
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
import io.dropwizard.util.Resources;
import java.net.URI;
import java.util.List;
import java.util.Map;
import javax.ws.rs.client.Client;
import javax.ws.rs.core.Response;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.whispersystems.textsecuregcm.metrics.NoopAwsSdkMetricPublisher;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtension;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema;
import org.whispersystems.textsecuregcm.tests.util.TestWebsocketListener;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.websocket.messages.WebSocketResponseMessage;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
@@ -91,15 +95,42 @@ class WhisperServerServiceTest {
@Test
void websocket() throws Exception {
// test unauthenticated websocket
final long start = System.currentTimeMillis();
final TestWebsocketListener testWebsocketListener = new TestWebsocketListener();
webSocketClient.connect(testWebsocketListener,
final Session session = webSocketClient.connect(testWebsocketListener,
URI.create(String.format("ws://localhost:%d/v1/websocket/", EXTENSION.getLocalPort())))
.join();
final long sessionTimestamp = Long.parseLong(session.getUpgradeResponse().getHeader(HeaderUtils.TIMESTAMP_HEADER));
assertTrue(sessionTimestamp >= start);
final WebSocketResponseMessage keepAlive = testWebsocketListener.doGet("/v1/keepalive").join();
assertEquals(200, keepAlive.getStatus());
final long keepAliveTimestamp = Long.parseLong(
keepAlive.getHeaders().get(HeaderUtils.TIMESTAMP_HEADER.toLowerCase()));
assertTrue(keepAliveTimestamp >= start);
final WebSocketResponseMessage whoami = testWebsocketListener.doGet("/v1/accounts/whoami").join();
assertEquals(401, whoami.getStatus());
final long whoamiTimestamp = Long.parseLong(whoami.getHeaders().get(HeaderUtils.TIMESTAMP_HEADER.toLowerCase()));
assertTrue(whoamiTimestamp >= start);
}
@Test
void rest() throws Exception {
// test unauthenticated rest
final long start = System.currentTimeMillis();
final Response whoami = EXTENSION.client().target(
"http://localhost:%d/v1/accounts/whoami".formatted(EXTENSION.getLocalPort())).request().get();
assertEquals(401, whoami.getStatus());
final List<Object> timestampValues = whoami.getHeaders().get(HeaderUtils.TIMESTAMP_HEADER.toLowerCase());
assertEquals(1, timestampValues.size());
final long whoamiTimestamp = Long.parseLong(timestampValues.getFirst().toString());
assertTrue(whoamiTimestamp >= start);
}
@Test
@@ -110,7 +141,7 @@ class WhisperServerServiceTest {
.build();
try (DynamoDbClient dynamoDbClient = EXTENSION.getConfiguration().getDynamoDbClientConfiguration()
.buildSyncClient(awsCredentialsProvider)) {
.buildSyncClient(awsCredentialsProvider, new NoopAwsSdkMetricPublisher())) {
final DynamoDbExtension.TableSchema numbers = DynamoDbExtensionSchema.Tables.NUMBERS;
final AttributeValue numberAV = AttributeValues.s("+12125550001");
@@ -139,7 +170,6 @@ class WhisperServerServiceTest {
.key(Map.of(numbers.hashKeyName(), numberAV))
.build());
}
}
}
@@ -85,7 +85,12 @@ public class TurnCallRouterTest {
InetAddress.getByName("9.9.9.2")
),
"dc-performance2", List.of(InetAddress.getByName("9.9.9.3")),
"dc-performance3", List.of(InetAddress.getByName("9.9.9.4"))
"dc-performance3", List.of(InetAddress.getByName("9.9.9.4")),
"dc-performance4", List.of(
InetAddress.getByName("9.9.9.5"),
InetAddress.getByName("9.9.9.6"),
InetAddress.getByName("9.9.9.7")
)
),
Map.of(
"dc-manual", List.of(InetAddress.getByName("2222:1111:0:dead::")),
@@ -94,7 +99,12 @@ public class TurnCallRouterTest {
InetAddress.getByName("2222:1111:0:abc1::")
),
"dc-performance2", List.of(InetAddress.getByName("2222:1111:0:abc2::")),
"dc-performance3", List.of(InetAddress.getByName("2222:1111:0:abc3::"))
"dc-performance3", List.of(InetAddress.getByName("2222:1111:0:abc3::")),
"dc-performance4", List.of(
InetAddress.getByName("2222:1111:0:abc4::"),
InetAddress.getByName("2222:1111:0:abc5::"),
InetAddress.getByName("2222:1111:0:abc6::")
)
)
);
} catch (UnknownHostException e) {
@@ -205,11 +215,12 @@ public class TurnCallRouterTest {
}
@Test
public void testLimitReturnsPreferredProtocolAndPrioritizesPerformance() throws UnknownHostException {
public void testLimitPrioritizesBestDataCenters() throws UnknownHostException {
when(performanceTable.getDatacentersFor(any(), any(), any(), any()))
.thenReturn(List.of("dc-performance3", "dc-performance2", "dc-performance1"));
.thenReturn(List.of("dc-performance3", "dc-performance2", "dc-performance3"));
assertThat(router().getRoutingFor(aci, Optional.of(InetAddress.getByName("0.0.0.1")), 3))
// gets one instance from best two datacenters
assertThat(router().getRoutingFor(aci, Optional.of(InetAddress.getByName("0.0.0.1")), 2))
.isEqualTo(optionsWithUrls(List.of(
"turn:9.9.9.4",
"turn:9.9.9.4:80?transport=tcp",
@@ -221,10 +232,14 @@ public class TurnCallRouterTest {
"turn:[2222:1111:0:abc3:0:0:0:0]",
"turn:[2222:1111:0:abc3:0:0:0:0]:80?transport=tcp",
"turns:[2222:1111:0:abc3:0:0:0:0]:443?transport=tcp"
"turns:[2222:1111:0:abc3:0:0:0:0]:443?transport=tcp",
"turn:[2222:1111:0:abc2:0:0:0:0]",
"turn:[2222:1111:0:abc2:0:0:0:0]:80?transport=tcp",
"turns:[2222:1111:0:abc2:0:0:0:0]:443?transport=tcp"
)));
assertThat(router().getRoutingFor(aci, Optional.of(InetAddress.getByName("2222:1111:0:abc2:0:0:0:1")), 3))
assertThat(router().getRoutingFor(aci, Optional.of(InetAddress.getByName("2222:1111:0:abc2:0:0:0:1")), 1))
.isEqualTo(optionsWithUrls(List.of(
"turn:9.9.9.4",
"turn:9.9.9.4:80?transport=tcp",
@@ -232,11 +247,56 @@ public class TurnCallRouterTest {
"turn:[2222:1111:0:abc3:0:0:0:0]",
"turn:[2222:1111:0:abc3:0:0:0:0]:80?transport=tcp",
"turns:[2222:1111:0:abc3:0:0:0:0]:443?transport=tcp",
"turns:[2222:1111:0:abc3:0:0:0:0]:443?transport=tcp"
)));
}
@Test
public void testBackFillsUpToLimit() throws UnknownHostException {
when(performanceTable.getDatacentersFor(any(), any(), any(), any()))
.thenReturn(List.of("dc-performance4", "dc-performance2", "dc-performance3"));
assertThat(router().getRoutingFor(aci, Optional.of(InetAddress.getByName("0.0.0.1")), 5))
.isEqualTo(optionsWithUrls(List.of(
"turn:9.9.9.5",
"turn:9.9.9.5:80?transport=tcp",
"turns:9.9.9.5:443?transport=tcp",
"turn:9.9.9.6",
"turn:9.9.9.6:80?transport=tcp",
"turns:9.9.9.6:443?transport=tcp",
"turn:9.9.9.7",
"turn:9.9.9.7:80?transport=tcp",
"turns:9.9.9.7:443?transport=tcp",
"turn:9.9.9.3",
"turn:9.9.9.3:80?transport=tcp",
"turns:9.9.9.3:443?transport=tcp",
"turn:9.9.9.4",
"turn:9.9.9.4:80?transport=tcp",
"turns:9.9.9.4:443?transport=tcp",
"turn:[2222:1111:0:abc4:0:0:0:0]",
"turn:[2222:1111:0:abc4:0:0:0:0]:80?transport=tcp",
"turns:[2222:1111:0:abc4:0:0:0:0]:443?transport=tcp",
"turn:[2222:1111:0:abc5:0:0:0:0]",
"turn:[2222:1111:0:abc5:0:0:0:0]:80?transport=tcp",
"turns:[2222:1111:0:abc5:0:0:0:0]:443?transport=tcp",
"turn:[2222:1111:0:abc6:0:0:0:0]",
"turn:[2222:1111:0:abc6:0:0:0:0]:80?transport=tcp",
"turns:[2222:1111:0:abc6:0:0:0:0]:443?transport=tcp",
"turn:[2222:1111:0:abc2:0:0:0:0]",
"turn:[2222:1111:0:abc2:0:0:0:0]:80?transport=tcp",
"turns:[2222:1111:0:abc2:0:0:0:0]:443?transport=tcp"
"turns:[2222:1111:0:abc2:0:0:0:0]:443?transport=tcp",
"turn:[2222:1111:0:abc3:0:0:0:0]",
"turn:[2222:1111:0:abc3:0:0:0:0]:80?transport=tcp",
"turns:[2222:1111:0:abc3:0:0:0:0]:443?transport=tcp"
)));
}
@@ -35,16 +35,20 @@ public class HCaptchaClientTest {
static Stream<Arguments> captchaProcessed() {
return Stream.of(
Arguments.of(true, 0.6f, true),
Arguments.of(false, 0.6f, false),
Arguments.of(true, 0.4f, false),
Arguments.of(false, 0.4f, false)
// hCaptcha scores are inverted compared to recaptcha scores. (low score is good)
Arguments.of(true, 0.4f, 0.5f, true),
Arguments.of(false, 0.4f, 0.5f, false),
Arguments.of(true, 0.6f, 0.5f, false),
Arguments.of(false, 0.6f, 0.5f, false),
Arguments.of(true, 0.6f, 0.4f, true),
Arguments.of(true, 0.61f, 0.4f, false),
Arguments.of(true, 0.7f, 0.3f, true)
);
}
@ParameterizedTest
@MethodSource
public void captchaProcessed(final boolean success, final float score, final boolean expectedResult)
public void captchaProcessed(final boolean success, final float hCaptchaScore, final float scoreFloor, final boolean expectedResult)
throws IOException, InterruptedException {
final FaultTolerantHttpClient client = mockResponder(200, String.format("""
@@ -54,9 +58,9 @@ public class HCaptchaClientTest {
"score-reasons": ["great job doing this captcha"]
}
""",
success, 1 - score)); // hCaptcha scores are inverted compared to recaptcha scores. (low score is good)
success, hCaptchaScore));
final AssessmentResult result = new HCaptchaClient("fake", client, mockConfig(true, 0.5))
final AssessmentResult result = new HCaptchaClient("fake", client, mockConfig(true, scoreFloor))
.verify(SITE_KEY, Action.CHALLENGE, TOKEN, null, USER_AGENT);
if (!success) {
assertThat(result).isEqualTo(AssessmentResult.invalid());
@@ -9,6 +9,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtension;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.metrics.MetricPublisher;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
@@ -29,12 +30,12 @@ public class LocalDynamoDbFactory implements DynamoDbClientFactory {
}
@Override
public DynamoDbClient buildSyncClient(final AwsCredentialsProvider awsCredentialsProvider) {
public DynamoDbClient buildSyncClient(final AwsCredentialsProvider awsCredentialsProvider, final MetricPublisher metricPublisher) {
return EXTENSION.getDynamoDbClient();
}
@Override
public DynamoDbAsyncClient buildAsyncClient(final AwsCredentialsProvider awsCredentialsProvider) {
public DynamoDbAsyncClient buildAsyncClient(final AwsCredentialsProvider awsCredentialsProvider, final MetricPublisher metricPublisher) {
return EXTENSION.getDynamoDbAsyncClient();
}
}
@@ -308,29 +308,11 @@ class AccountControllerTest {
.request()
.header(HttpHeaders.AUTHORIZATION,
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_3, AuthHelper.VALID_PASSWORD_3_PRIMARY))
.put(Entity.json(new ApnRegistrationId("first", "second")))) {
.put(Entity.json(new ApnRegistrationId("first")))) {
assertThat(response.getStatus()).isEqualTo(204);
verify(AuthHelper.VALID_DEVICE_3_PRIMARY, times(1)).setApnId(eq("first"));
verify(AuthHelper.VALID_DEVICE_3_PRIMARY, times(1)).setVoipApnId(eq("second"));
verify(accountsManager, times(1)).updateDevice(eq(AuthHelper.VALID_ACCOUNT_3), anyByte(), any());
}
}
@Test
void testSetApnIdNoVoip() {
try (final Response response = resources.getJerseyTest()
.target("/v1/accounts/apn/")
.request()
.header(HttpHeaders.AUTHORIZATION,
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_3, AuthHelper.VALID_PASSWORD_3_PRIMARY))
.put(Entity.json(new ApnRegistrationId("first", null)))) {
assertThat(response.getStatus()).isEqualTo(204);
verify(AuthHelper.VALID_DEVICE_3_PRIMARY, times(1)).setApnId(eq("first"));
verify(AuthHelper.VALID_DEVICE_3_PRIMARY, times(1)).setVoipApnId(null);
verify(accountsManager, times(1)).updateDevice(eq(AuthHelper.VALID_ACCOUNT_3), anyByte(), any());
}
}
@@ -177,7 +177,6 @@ class DeviceControllerTest {
final Optional<ApnRegistrationId> apnRegistrationId,
final Optional<GcmRegistrationId> gcmRegistrationId,
final Optional<String> expectedApnsToken,
final Optional<String> expectedApnsVoipToken,
final Optional<String> expectedGcmToken) {
final Device existingDevice = mock(Device.class);
@@ -240,9 +239,6 @@ class DeviceControllerTest {
expectedApnsToken.ifPresentOrElse(expectedToken -> assertEquals(expectedToken, device.getApnId()),
() -> assertNull(device.getApnId()));
expectedApnsVoipToken.ifPresentOrElse(expectedToken -> assertEquals(expectedToken, device.getVoipApnId()),
() -> assertNull(device.getVoipApnId()));
expectedGcmToken.ifPresentOrElse(expectedToken -> assertEquals(expectedToken, device.getGcmId()),
() -> assertNull(device.getGcmId()));
@@ -251,14 +247,13 @@ class DeviceControllerTest {
private static Stream<Arguments> linkDeviceAtomic() {
final String apnsToken = "apns-token";
final String apnsVoipToken = "apns-voip-token";
final String gcmToken = "gcm-token";
return Stream.of(
Arguments.of(true, Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()),
Arguments.of(false, Optional.of(new ApnRegistrationId(apnsToken, null)), Optional.empty(), Optional.of(apnsToken), Optional.empty(), Optional.empty()),
Arguments.of(false, Optional.of(new ApnRegistrationId(apnsToken, apnsVoipToken)), Optional.empty(), Optional.of(apnsToken), Optional.of(apnsVoipToken), Optional.empty()),
Arguments.of(false, Optional.empty(), Optional.of(new GcmRegistrationId(gcmToken)), Optional.empty(), Optional.empty(), Optional.of(gcmToken))
Arguments.of(true, Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()),
Arguments.of(false, Optional.of(new ApnRegistrationId(apnsToken)), Optional.empty(), Optional.of(apnsToken), Optional.empty()),
Arguments.of(false, Optional.of(new ApnRegistrationId(apnsToken)), Optional.empty(), Optional.of(apnsToken), Optional.empty()),
Arguments.of(false, Optional.empty(), Optional.of(new GcmRegistrationId(gcmToken)), Optional.empty(), Optional.of(gcmToken))
);
}
@@ -496,10 +491,10 @@ class DeviceControllerTest {
private static Stream<Arguments> linkDeviceAtomicConflictingChannel() {
return Stream.of(
Arguments.of(true, Optional.of(new ApnRegistrationId("apns-token", null)), Optional.of(new GcmRegistrationId("gcm-token"))),
Arguments.of(true, Optional.of(new ApnRegistrationId("apns-token")), Optional.of(new GcmRegistrationId("gcm-token"))),
Arguments.of(true, Optional.empty(), Optional.of(new GcmRegistrationId("gcm-token"))),
Arguments.of(true, Optional.of(new ApnRegistrationId("apns-token", null)), Optional.empty()),
Arguments.of(false, Optional.of(new ApnRegistrationId("apns-token", null)), Optional.of(new GcmRegistrationId("gcm-token")))
Arguments.of(true, Optional.of(new ApnRegistrationId("apns-token")), Optional.empty()),
Arguments.of(false, Optional.of(new ApnRegistrationId("apns-token")), Optional.of(new GcmRegistrationId("gcm-token")))
);
}
@@ -737,7 +732,7 @@ class DeviceControllerTest {
final LinkDeviceRequest request = new LinkDeviceRequest(deviceCode.verificationCode(),
new AccountAttributes(false, registrationId, pniRegistrationId, null, null, true, new DeviceCapabilities(true, true, true, false, false)),
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.of(new ApnRegistrationId("apn", null)), Optional.empty()));
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.of(new ApnRegistrationId("apn")), Optional.empty()));
try (final Response response = resources.getJerseyTest()
.target("/v1/devices/link")
@@ -114,7 +114,6 @@ import org.whispersystems.textsecuregcm.push.MessageSender;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
import org.whispersystems.textsecuregcm.push.ReceiptSender;
import org.whispersystems.textsecuregcm.spam.ReportSpamTokenProvider;
import org.whispersystems.textsecuregcm.spam.SpamChecker;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
@@ -207,7 +206,7 @@ class MessageControllerTest {
.addResource(
new MessageController(rateLimiters, cardinalityEstimator, messageSender, receiptSender, accountsManager,
messagesManager, pushNotificationManager, pushNotificationScheduler, reportMessageManager, multiRecipientMessageExecutor,
messageDeliveryScheduler, ReportSpamTokenProvider.noop(), mock(ClientReleaseManager.class), dynamicConfigurationManager,
messageDeliveryScheduler, mock(ClientReleaseManager.class), dynamicConfigurationManager,
serverSecretParams, SpamChecker.noop(), new MessageMetrics(), mock(MessageDeliveryLoopMonitor.class),
clock))
.build();
@@ -5,7 +5,6 @@
package org.whispersystems.textsecuregcm.controllers;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
@@ -21,15 +20,14 @@ import io.dropwizard.testing.junit5.ResourceExtension;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Base64;
import java.util.UUID;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.commons.lang3.RandomStringUtils;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.entities.ProvisioningMessage;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
@@ -38,7 +36,7 @@ import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper
import org.whispersystems.textsecuregcm.push.ProvisioningManager;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.websocket.ProvisioningAddress;
import org.whispersystems.textsecuregcm.websocket.ProvisioningConnectListener;
@ExtendWith(DropwizardExtensionsSupport.class)
class ProvisioningControllerTest {
@@ -67,13 +65,13 @@ class ProvisioningControllerTest {
@Test
void sendProvisioningMessage() {
final String destination = UUID.randomUUID().toString();
final String provisioningAddress = ProvisioningConnectListener.generateProvisioningAddress();
final byte[] messageBody = "test".getBytes(StandardCharsets.UTF_8);
when(provisioningManager.sendProvisioningMessage(any(), any())).thenReturn(true);
try (final Response response = RESOURCE_EXTENSION.getJerseyTest()
.target("/v1/provisioning/" + destination)
.target("/v1/provisioning/" + provisioningAddress)
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.entity(new ProvisioningMessage(Base64.getMimeEncoder().encodeToString(messageBody)),
@@ -81,31 +79,20 @@ class ProvisioningControllerTest {
assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus());
final ArgumentCaptor<ProvisioningAddress> provisioningAddressCaptor =
ArgumentCaptor.forClass(ProvisioningAddress.class);
final ArgumentCaptor<byte[]> provisioningMessageCaptor = ArgumentCaptor.forClass(byte[].class);
verify(provisioningManager).sendProvisioningMessage(provisioningAddressCaptor.capture(),
provisioningMessageCaptor.capture());
assertEquals(destination, provisioningAddressCaptor.getValue().getAddress());
assertEquals(ProvisioningAddress.DEVICE_ID, provisioningAddressCaptor.getValue().getDeviceId());
assertArrayEquals(messageBody, provisioningMessageCaptor.getValue());
verify(provisioningManager).sendProvisioningMessage(provisioningAddress, messageBody);
}
}
@Test
void sendProvisioningMessageRateLimited() throws RateLimitExceededException {
final String destination = UUID.randomUUID().toString();
final String provisioningAddress = ProvisioningConnectListener.generateProvisioningAddress();
final byte[] messageBody = "test".getBytes(StandardCharsets.UTF_8);
doThrow(new RateLimitExceededException(Duration.ZERO))
.when(messagesRateLimiter).validate(AuthHelper.VALID_UUID);
try (final Response response = RESOURCE_EXTENSION.getJerseyTest()
.target("/v1/provisioning/" + destination)
.target("/v1/provisioning/" + provisioningAddress)
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.entity(new ProvisioningMessage(Base64.getMimeEncoder().encodeToString(messageBody)),
@@ -543,7 +543,7 @@ class RegistrationControllerTest {
pniSignedPreKey,
aciPqLastResortPreKey,
pniPqLastResortPreKey,
Optional.of(new ApnRegistrationId("apns-token", null)),
Optional.of(new ApnRegistrationId("apns-token")),
Optional.empty())),
// "Fetches messages" is true, but an FCM (GCM) token is provided
@@ -571,7 +571,7 @@ class RegistrationControllerTest {
pniSignedPreKey,
aciPqLastResortPreKey,
pniPqLastResortPreKey,
Optional.of(new ApnRegistrationId("apns-token", null)),
Optional.of(new ApnRegistrationId("apns-token")),
Optional.of(new GcmRegistrationId("gcm-token"))))
);
}
@@ -795,7 +795,6 @@ class RegistrationControllerTest {
new AccountAttributes(false, registrationId, pniRegistrationId, "test".getBytes(StandardCharsets.UTF_8), null, true, new Device.DeviceCapabilities(false, false, false, false, false));
final String apnsToken = "apns-token";
final String apnsVoipToken = "apns-voip-token";
final String gcmToken = "gcm-token";
return Stream.of(
@@ -840,7 +839,7 @@ class RegistrationControllerTest {
pniSignedPreKey,
aciPqLastResortPreKey,
pniPqLastResortPreKey,
Optional.of(new ApnRegistrationId(apnsToken, apnsVoipToken)),
Optional.of(new ApnRegistrationId(apnsToken)),
Optional.empty()),
aciIdentityKey,
pniIdentityKey,
@@ -852,7 +851,7 @@ class RegistrationControllerTest {
registrationId,
pniRegistrationId,
false,
Optional.of(new ApnRegistrationId(apnsToken, apnsVoipToken)),
Optional.of(new ApnRegistrationId(apnsToken)),
Optional.empty(),
aciSignedPreKey,
pniSignedPreKey,
@@ -76,10 +76,10 @@ import org.whispersystems.textsecuregcm.entities.Badge;
import org.whispersystems.textsecuregcm.entities.BadgeSvg;
import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.SubscriptionProcessorExceptionMapper;
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
import org.whispersystems.textsecuregcm.storage.PaymentTime;
import org.whispersystems.textsecuregcm.storage.SubscriptionException;
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
import org.whispersystems.textsecuregcm.storage.Subscriptions;
import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator;
@@ -93,7 +93,6 @@ import org.whispersystems.textsecuregcm.subscriptions.PaymentStatus;
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.util.MockUtils;
@@ -133,7 +132,6 @@ class SubscriptionControllerTest {
.addProperty(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE)
.addProvider(AuthHelper.getAuthFilter())
.addProvider(CompletionExceptionMapper.class)
.addProvider(SubscriptionProcessorExceptionMapper.class)
.addProvider(new AuthValueFactoryProvider.Binder<>(AuthenticatedDevice.class))
.addProvider(SubscriptionExceptionMapper.class)
.setMapper(SystemMapper.jsonMapper())
@@ -340,7 +338,7 @@ class SubscriptionControllerTest {
when(BRAINTREE_MANAGER.captureOneTimePayment(anyString(), anyString(), anyString(), anyString(), anyLong(),
anyLong(), any()))
.thenReturn(CompletableFuture.failedFuture(new SubscriptionProcessorException(PaymentProvider.BRAINTREE,
.thenReturn(CompletableFuture.failedFuture(new SubscriptionException.ProcessorException(PaymentProvider.BRAINTREE,
new ChargeFailure("2046", "Declined", null, null, null))));
final Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/paypal/confirm")
@@ -351,7 +349,7 @@ class SubscriptionControllerTest {
"currency", "usd",
"amount", 123)));
assertThat(response.getStatus()).isEqualTo(SubscriptionProcessorExceptionMapper.EXTERNAL_SERVICE_ERROR_STATUS_CODE);
assertThat(response.getStatus()).isEqualTo(SubscriptionExceptionMapper.PROCESSOR_ERROR_STATUS_CODE);
final Map responseMap = response.readEntity(Map.class);
assertThat(responseMap.get("processor")).isEqualTo("BRAINTREE");
@@ -419,7 +417,7 @@ class SubscriptionControllerTest {
@Test
void createSubscriptionProcessorDeclined() {
when(STRIPE_MANAGER.createSubscription(any(), any(), anyLong(), anyLong()))
.thenReturn(CompletableFuture.failedFuture(new SubscriptionProcessorException(PaymentProvider.STRIPE,
.thenReturn(CompletableFuture.failedFuture(new SubscriptionException.ProcessorException(PaymentProvider.STRIPE,
new ChargeFailure("card_declined", "Insufficient funds", null, null, null))));
final String level = String.valueOf(levelId);
@@ -429,8 +427,7 @@ class SubscriptionControllerTest {
.request()
.put(Entity.json(""));
assertThat(response.getStatus()).isEqualTo(
SubscriptionProcessorExceptionMapper.EXTERNAL_SERVICE_ERROR_STATUS_CODE);
assertThat(response.getStatus()).isEqualTo(SubscriptionExceptionMapper.PROCESSOR_ERROR_STATUS_CODE);
final Map responseMap = response.readEntity(Map.class);
assertThat(responseMap.get("processor")).isEqualTo("STRIPE");
@@ -905,6 +902,56 @@ class SubscriptionControllerTest {
eq(now));
}
@Test
public void replacePlayPurchaseToken() {
final String oldPurchaseToken = "oldPurchaseToken";
final String newPurchaseToken = "newPurchaseToken";
final byte[] subscriberUserAndKey = new byte[32];
Arrays.fill(subscriberUserAndKey, (byte) 1);
final byte[] user = Arrays.copyOfRange(subscriberUserAndKey, 0, 16);
final String subscriberId = Base64.getEncoder().encodeToString(subscriberUserAndKey);
final Instant now = Instant.now();
when(CLOCK.instant()).thenReturn(now);
final ProcessorCustomer oldPc = new ProcessorCustomer(oldPurchaseToken, PaymentProvider.GOOGLE_PLAY_BILLING);
final Map<String, AttributeValue> dynamoItem = Map.of(Subscriptions.KEY_PASSWORD, b(new byte[16]),
Subscriptions.KEY_CREATED_AT, n(Instant.now().getEpochSecond()),
Subscriptions.KEY_ACCESSED_AT, n(Instant.now().getEpochSecond()),
Subscriptions.KEY_PROCESSOR_ID_CUSTOMER_ID, b(oldPc.toDynamoBytes()));
final Subscriptions.Record record = Subscriptions.Record.from(user, dynamoItem);
when(SUBSCRIPTIONS.get(any(), any()))
.thenReturn(CompletableFuture.completedFuture(Subscriptions.GetResult.found(record)));
final GooglePlayBillingManager.ValidatedToken validatedToken = mock(GooglePlayBillingManager.ValidatedToken.class);
when(validatedToken.getLevel()).thenReturn(99L);
when(validatedToken.acknowledgePurchase()).thenReturn(CompletableFuture.completedFuture(null));
when(PLAY_MANAGER.validateToken(eq(newPurchaseToken))).thenReturn(CompletableFuture.completedFuture(validatedToken));
when(PLAY_MANAGER.cancelAllActiveSubscriptions(eq(oldPurchaseToken)))
.thenReturn(CompletableFuture.completedFuture(null));
when(SUBSCRIPTIONS.setIapPurchase(any(), any(), anyString(), anyLong(), any()))
.thenReturn(CompletableFuture.completedFuture(null));
final Response response = RESOURCE_EXTENSION
.target(String.format("/v1/subscription/%s/playbilling/%s", subscriberId, newPurchaseToken))
.request()
.post(Entity.json(""));
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.readEntity(SubscriptionController.SetSubscriptionLevelSuccessResponse.class).level())
.isEqualTo(99L);
verify(SUBSCRIPTIONS, times(1)).setIapPurchase(
any(),
eq(new ProcessorCustomer(newPurchaseToken, PaymentProvider.GOOGLE_PLAY_BILLING)),
eq(newPurchaseToken),
eq(99L),
eq(now));
verify(PLAY_MANAGER, times(1)).cancelAllActiveSubscriptions(oldPurchaseToken);
}
@ParameterizedTest
@CsvSource({"5, P45D", "201, P13D"})
public void createReceiptCredential(long level, Duration expectedExpirationWindow)
@@ -56,15 +56,6 @@ abstract class IdleDevicePushNotificationExperimentTest {
arguments.add(Arguments.of(device, true));
}
{
// APNs VOIP token
final Device device = mock(Device.class);
when(device.getApnId()).thenReturn("apns-token");
when(device.getVoipApnId()).thenReturn("apns-voip-token");
arguments.add(Arguments.of(device, false));
}
return arguments;
}
@@ -1,171 +0,0 @@
package org.whispersystems.textsecuregcm.experiment;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
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.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.api.Test;
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.push.IdleDeviceNotificationScheduler;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
class NotifyIdleDevicesWithMessagesExperimentTest extends IdleDevicePushNotificationExperimentTest {
private IdleDeviceNotificationScheduler idleDeviceNotificationScheduler;
private MessagesManager messagesManager;
private NotifyIdleDevicesWithMessagesExperiment experiment;
@BeforeEach
void setUp() {
idleDeviceNotificationScheduler = mock(IdleDeviceNotificationScheduler.class);
messagesManager = mock(MessagesManager.class);
experiment = new NotifyIdleDevicesWithMessagesExperiment(idleDeviceNotificationScheduler,
messagesManager,
Clock.fixed(CURRENT_TIME, ZoneId.systemDefault()));
}
@Override
protected IdleDevicePushNotificationExperiment getExperiment() {
return experiment;
}
@ParameterizedTest
@MethodSource
void isDeviceEligible(final Account account,
final Device device,
final boolean mayHaveMessages,
final boolean expectEligible) {
when(messagesManager.mayHavePersistedMessages(account.getIdentifier(IdentityType.ACI), device))
.thenReturn(CompletableFuture.completedFuture(mayHaveMessages));
assertEquals(expectEligible, experiment.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));
{
// 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(NotifyIdleDevicesWithMessagesExperiment.MIN_IDLE_DURATION).toEpochMilli());
arguments.add(Arguments.of(account, device, true, true));
}
{
// Idle device missing push token, but with messages
final Device device = mock(Device.class);
when(device.getLastSeen()).thenReturn(CURRENT_TIME.minus(NotifyIdleDevicesWithMessagesExperiment.MIN_IDLE_DURATION).toEpochMilli());
arguments.add(Arguments.of(account, device, true, false));
}
{
// Idle device missing push token and messages
final Device device = mock(Device.class);
when(device.getLastSeen()).thenReturn(CURRENT_TIME.minus(NotifyIdleDevicesWithMessagesExperiment.MIN_IDLE_DURATION).toEpochMilli());
arguments.add(Arguments.of(account, device, false, false));
}
{
// Idle device with push token, but no messages
final Device device = mock(Device.class);
when(device.getLastSeen()).thenReturn(CURRENT_TIME.minus(NotifyIdleDevicesWithMessagesExperiment.MIN_IDLE_DURATION).toEpochMilli());
when(device.getApnId()).thenReturn("apns-token");
arguments.add(Arguments.of(account, device, false, false));
}
{
// Active device with push token and 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, false));
}
{
// Active device missing push token, but with messages
final Device device = mock(Device.class);
when(device.getLastSeen()).thenReturn(CURRENT_TIME.toEpochMilli());
arguments.add(Arguments.of(account, device, 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));
}
{
// 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));
}
return arguments;
}
@ParameterizedTest
@MethodSource
void isIdle(final Duration idleDuration, final boolean expectIdle) {
final Device device = mock(Device.class);
when(device.getLastSeen()).thenReturn(CURRENT_TIME.minus(idleDuration).toEpochMilli());
assertEquals(expectIdle, experiment.isIdle(device));
}
private static List<Arguments> isIdle() {
return List.of(
Arguments.of(NotifyIdleDevicesWithMessagesExperiment.MIN_IDLE_DURATION, true),
Arguments.of(NotifyIdleDevicesWithMessagesExperiment.MIN_IDLE_DURATION.plusMillis(1), true),
Arguments.of(NotifyIdleDevicesWithMessagesExperiment.MIN_IDLE_DURATION.minusMillis(1), false),
Arguments.of(NotifyIdleDevicesWithMessagesExperiment.MAX_IDLE_DURATION, false),
Arguments.of(NotifyIdleDevicesWithMessagesExperiment.MAX_IDLE_DURATION.plusMillis(1), false),
Arguments.of(NotifyIdleDevicesWithMessagesExperiment.MAX_IDLE_DURATION.minusMillis(1), true)
);
}
@Test
void applyExperimentTreatment() {
final Account account = mock(Account.class);
final Device device = mock(Device.class);
experiment.applyExperimentTreatment(account, device);
verify(idleDeviceNotificationScheduler)
.scheduleNotification(account, device, NotifyIdleDevicesWithMessagesExperiment.PREFERRED_NOTIFICATION_TIME);
}
}
@@ -6,28 +6,42 @@
package org.whispersystems.textsecuregcm.filters;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.matches;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.core.MultivaluedMap;
import org.glassfish.jersey.message.internal.HeaderUtils;
import org.junit.jupiter.api.Test;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
class TimestampResponseFilterTest {
@Test
void testFilter() {
final ContainerRequestContext requestContext = mock(ContainerRequestContext.class);
final ContainerResponseContext responseContext = mock(ContainerResponseContext.class);
@Test
void testJerseyFilter() {
final ContainerRequestContext requestContext = mock(ContainerRequestContext.class);
final ContainerResponseContext responseContext = mock(ContainerResponseContext.class);
final MultivaluedMap<String, Object> headers = org.glassfish.jersey.message.internal.HeaderUtils.createOutbound();
when(responseContext.getHeaders()).thenReturn(headers);
final MultivaluedMap<String, Object> headers = HeaderUtils.createOutbound();
new TimestampResponseFilter().filter(requestContext, responseContext);
when(responseContext.getHeaders()).thenReturn(headers);
assertTrue(headers.containsKey(org.whispersystems.textsecuregcm.util.HeaderUtils.TIMESTAMP_HEADER));
}
new TimestampResponseFilter().filter(requestContext, responseContext);
@Test
void testServletFilter() throws Exception {
final HttpServletRequest request = mock(HttpServletRequest.class);
final HttpServletResponse response = mock(HttpServletResponse.class);
assertTrue(headers.containsKey(org.whispersystems.textsecuregcm.util.HeaderUtils.TIMESTAMP_HEADER));
}
new TimestampResponseFilter().doFilter(request, response, mock(FilterChain.class));
verify(response).setHeader(eq(HeaderUtils.TIMESTAMP_HEADER), matches("\\d{10,}"));
}
}
@@ -217,7 +217,6 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
void setPushToken(final byte deviceId,
final SetPushTokenRequest request,
@Nullable final String expectedApnsToken,
@Nullable final String expectedApnsVoipToken,
@Nullable final String expectedFcmToken) {
mockAuthenticationInterceptor().setAuthenticatedDevice(AUTHENTICATED_ACI, deviceId);
@@ -228,14 +227,12 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
final SetPushTokenResponse ignored = authenticatedServiceStub().setPushToken(request);
verify(device).setApnId(expectedApnsToken);
verify(device).setVoipApnId(expectedApnsVoipToken);
verify(device).setGcmId(expectedFcmToken);
verify(device).setFetchesMessages(false);
}
private static Stream<Arguments> setPushToken() {
final String apnsToken = "apns-token";
final String apnsVoipToken = "apns-voip-token";
final String fcmToken = "fcm-token";
final Stream.Builder<Arguments> streamBuilder = Stream.builder();
@@ -245,18 +242,9 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
SetPushTokenRequest.newBuilder()
.setApnsTokenRequest(SetPushTokenRequest.ApnsTokenRequest.newBuilder()
.setApnsToken(apnsToken)
.setApnsVoipToken(apnsVoipToken)
.build())
.build(),
apnsToken, apnsVoipToken, null));
streamBuilder.add(Arguments.of(deviceId,
SetPushTokenRequest.newBuilder()
.setApnsTokenRequest(SetPushTokenRequest.ApnsTokenRequest.newBuilder()
.setApnsToken(apnsToken)
.build())
.build(),
apnsToken, null, null));
apnsToken, null));
streamBuilder.add(Arguments.of(deviceId,
SetPushTokenRequest.newBuilder()
@@ -264,7 +252,7 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
.setFcmToken(fcmToken)
.build())
.build(),
null, null, fcmToken));
null, fcmToken));
}
return streamBuilder.build();
@@ -274,12 +262,10 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
@MethodSource
void setPushTokenUnchanged(final SetPushTokenRequest request,
@Nullable final String apnsToken,
@Nullable final String apnsVoipToken,
@Nullable final String fcmToken) {
final Device device = mock(Device.class);
when(device.getApnId()).thenReturn(apnsToken);
when(device.getVoipApnId()).thenReturn(apnsVoipToken);
when(device.getGcmId()).thenReturn(fcmToken);
when(authenticatedAccount.getDevice(AUTHENTICATED_DEVICE_ID)).thenReturn(Optional.of(device));
@@ -291,31 +277,22 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
private static Stream<Arguments> setPushTokenUnchanged() {
final String apnsToken = "apns-token";
final String apnsVoipToken = "apns-voip-token";
final String fcmToken = "fcm-token";
return Stream.of(
Arguments.of(SetPushTokenRequest.newBuilder()
.setApnsTokenRequest(SetPushTokenRequest.ApnsTokenRequest.newBuilder()
.setApnsToken(apnsToken)
.setApnsVoipToken(apnsVoipToken)
.build())
.build(),
apnsToken, apnsVoipToken, null, false),
Arguments.of(SetPushTokenRequest.newBuilder()
.setApnsTokenRequest(SetPushTokenRequest.ApnsTokenRequest.newBuilder()
.setApnsToken(apnsToken)
.build())
.build(),
apnsToken, null, null, false),
apnsToken, null, false),
Arguments.of(SetPushTokenRequest.newBuilder()
.setFcmTokenRequest(SetPushTokenRequest.FcmTokenRequest.newBuilder()
.setFcmToken(fcmToken)
.build())
.build(),
null, null, fcmToken, false)
null, fcmToken, false)
);
}
@@ -346,7 +323,6 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
@MethodSource
void clearPushToken(final byte deviceId,
@Nullable final String apnsToken,
@Nullable final String apnsVoipToken,
@Nullable final String fcmToken,
@Nullable final String expectedUserAgent) {
@@ -356,14 +332,12 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
when(device.getId()).thenReturn(deviceId);
when(device.isPrimary()).thenReturn(deviceId == Device.PRIMARY_ID);
when(device.getApnId()).thenReturn(apnsToken);
when(device.getVoipApnId()).thenReturn(apnsVoipToken);
when(device.getGcmId()).thenReturn(fcmToken);
when(authenticatedAccount.getDevice(deviceId)).thenReturn(Optional.of(device));
final ClearPushTokenResponse ignored = authenticatedServiceStub().clearPushToken(ClearPushTokenRequest.newBuilder().build());
verify(device).setApnId(null);
verify(device).setVoipApnId(null);
verify(device).setGcmId(null);
verify(device).setFetchesMessages(true);
@@ -376,16 +350,12 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
private static Stream<Arguments> clearPushToken() {
return Stream.of(
Arguments.of(Device.PRIMARY_ID, "apns-token", null, null, "OWI"),
Arguments.of(Device.PRIMARY_ID, "apns-token", "apns-voip-token", null, "OWI"),
Arguments.of(Device.PRIMARY_ID, null, "apns-voip-token", null, "OWI"),
Arguments.of(Device.PRIMARY_ID, null, null, "fcm-token", "OWA"),
Arguments.of(Device.PRIMARY_ID, null, null, null, null),
Arguments.of((byte) (Device.PRIMARY_ID + 1), "apns-token", null, null, "OWP"),
Arguments.of((byte) (Device.PRIMARY_ID + 1), "apns-token", "apns-voip-token", null, "OWP"),
Arguments.of((byte) (Device.PRIMARY_ID + 1), null, "apns-voip-token", null, "OWP"),
Arguments.of((byte) (Device.PRIMARY_ID + 1), null, null, "fcm-token", "OWA"),
Arguments.of((byte) (Device.PRIMARY_ID + 1), null, null, null, null)
Arguments.of(Device.PRIMARY_ID, "apns-token", null, "OWI"),
Arguments.of(Device.PRIMARY_ID, null, "fcm-token", "OWA"),
Arguments.of(Device.PRIMARY_ID, null, null, null),
Arguments.of((byte) (Device.PRIMARY_ID + 1), "apns-token", null, "OWP"),
Arguments.of((byte) (Device.PRIMARY_ID + 1), null, "fcm-token", "OWA"),
Arguments.of((byte) (Device.PRIMARY_ID + 1), null, null, null)
);
}
@@ -58,38 +58,6 @@ class APNSenderTest {
when(destinationDevice.getApnId()).thenReturn(DESTINATION_DEVICE_TOKEN);
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void testSendVoip(final boolean urgent) {
PushNotificationResponse<SimpleApnsPushNotification> response = mock(PushNotificationResponse.class);
when(response.isAccepted()).thenReturn(true);
when(apnsClient.sendNotification(any(SimpleApnsPushNotification.class)))
.thenAnswer(
(Answer) invocationOnMock -> new MockPushNotificationFuture<>(invocationOnMock.getArgument(0), response));
PushNotification pushNotification = new PushNotification(DESTINATION_DEVICE_TOKEN, PushNotification.TokenType.APN_VOIP,
PushNotification.NotificationType.NOTIFICATION, null, destinationAccount, destinationDevice, urgent);
final SendPushNotificationResult result = apnSender.sendNotification(pushNotification).join();
ArgumentCaptor<SimpleApnsPushNotification> notification = ArgumentCaptor.forClass(SimpleApnsPushNotification.class);
verify(apnsClient).sendNotification(notification.capture());
assertThat(notification.getValue().getToken()).isEqualTo(DESTINATION_DEVICE_TOKEN);
assertThat(notification.getValue().getExpiration()).isEqualTo(APNSender.MAX_EXPIRATION);
assertThat(notification.getValue().getPayload()).isEqualTo(APNSender.APN_VOIP_NOTIFICATION_PAYLOAD);
// Delivery priority should always be `IMMEDIATE` for VOIP notifications
assertThat(notification.getValue().getPriority()).isEqualTo(DeliveryPriority.IMMEDIATE);
assertThat(notification.getValue().getTopic()).isEqualTo(BUNDLE_ID + ".voip");
assertThat(result.accepted()).isTrue();
assertThat(result.errorCode()).isEmpty();
assertThat(result.unregistered()).isFalse();
verifyNoMoreInteractions(apnsClient);
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void testSendApns(final boolean urgent) {
@@ -144,7 +112,7 @@ class APNSenderTest {
.thenAnswer(
(Answer) invocationOnMock -> new MockPushNotificationFuture<>(invocationOnMock.getArgument(0), response));
PushNotification pushNotification = new PushNotification(DESTINATION_DEVICE_TOKEN, PushNotification.TokenType.APN_VOIP,
PushNotification pushNotification = new PushNotification(DESTINATION_DEVICE_TOKEN, PushNotification.TokenType.APN,
PushNotification.NotificationType.NOTIFICATION, null, destinationAccount, destinationDevice, true);
when(destinationDevice.getApnId()).thenReturn(DESTINATION_DEVICE_TOKEN);
@@ -157,7 +125,7 @@ class APNSenderTest {
assertThat(notification.getValue().getToken()).isEqualTo(DESTINATION_DEVICE_TOKEN);
assertThat(notification.getValue().getExpiration()).isEqualTo(APNSender.MAX_EXPIRATION);
assertThat(notification.getValue().getPayload()).isEqualTo(APNSender.APN_VOIP_NOTIFICATION_PAYLOAD);
assertThat(notification.getValue().getPayload()).isEqualTo(APNSender.APN_NSE_NOTIFICATION_PAYLOAD);
assertThat(notification.getValue().getPriority()).isEqualTo(DeliveryPriority.IMMEDIATE);
assertThat(result.accepted()).isFalse();
@@ -175,7 +143,7 @@ class APNSenderTest {
.thenAnswer(
(Answer) invocationOnMock -> new MockPushNotificationFuture<>(invocationOnMock.getArgument(0), response));
PushNotification pushNotification = new PushNotification(DESTINATION_DEVICE_TOKEN, PushNotification.TokenType.APN_VOIP,
PushNotification pushNotification = new PushNotification(DESTINATION_DEVICE_TOKEN, PushNotification.TokenType.APN,
PushNotification.NotificationType.NOTIFICATION, null, destinationAccount, destinationDevice, true);
final SendPushNotificationResult result = apnSender.sendNotification(pushNotification).join();
@@ -185,7 +153,7 @@ class APNSenderTest {
assertThat(notification.getValue().getToken()).isEqualTo(DESTINATION_DEVICE_TOKEN);
assertThat(notification.getValue().getExpiration()).isEqualTo(APNSender.MAX_EXPIRATION);
assertThat(notification.getValue().getPayload()).isEqualTo(APNSender.APN_VOIP_NOTIFICATION_PAYLOAD);
assertThat(notification.getValue().getPayload()).isEqualTo(APNSender.APN_NSE_NOTIFICATION_PAYLOAD);
assertThat(notification.getValue().getPriority()).isEqualTo(DeliveryPriority.IMMEDIATE);
assertThat(result.accepted()).isFalse();
@@ -202,7 +170,7 @@ class APNSenderTest {
.thenAnswer((Answer) invocationOnMock -> new MockPushNotificationFuture<>(invocationOnMock.getArgument(0),
new IOException("lost connection")));
PushNotification pushNotification = new PushNotification(DESTINATION_DEVICE_TOKEN, PushNotification.TokenType.APN_VOIP,
PushNotification pushNotification = new PushNotification(DESTINATION_DEVICE_TOKEN, PushNotification.TokenType.APN,
PushNotification.NotificationType.NOTIFICATION, null, destinationAccount, destinationDevice, true);
assertThatThrownBy(() -> apnSender.sendNotification(pushNotification).join())
@@ -8,6 +8,7 @@ import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import com.google.protobuf.ByteString;
import java.util.UUID;
import java.util.function.Consumer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
@@ -18,7 +19,6 @@ import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguratio
import org.whispersystems.textsecuregcm.redis.RedisSingletonExtension;
import org.whispersystems.textsecuregcm.storage.PubSubProtos;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import org.whispersystems.textsecuregcm.websocket.ProvisioningAddress;
class ProvisioningManagerTest {
@@ -42,14 +42,13 @@ class ProvisioningManagerTest {
@Test
void sendProvisioningMessage() {
final ProvisioningAddress address = ProvisioningAddress.create("address");
final String provisioningAddress = UUID.randomUUID().toString();
final byte[] content = TestRandomUtil.nextBytes(16);
@SuppressWarnings("unchecked") final Consumer<PubSubProtos.PubSubMessage> subscribedConsumer = mock(Consumer.class);
provisioningManager.addListener(address, subscribedConsumer);
provisioningManager.sendProvisioningMessage(address, content);
provisioningManager.addListener(provisioningAddress, subscribedConsumer);
provisioningManager.sendProvisioningMessage(provisioningAddress, content);
final ArgumentCaptor<PubSubProtos.PubSubMessage> messageCaptor =
ArgumentCaptor.forClass(PubSubProtos.PubSubMessage.class);
@@ -62,15 +61,14 @@ class ProvisioningManagerTest {
@Test
void removeListener() {
final ProvisioningAddress address = ProvisioningAddress.create("address");
final String provisioningAddress = UUID.randomUUID().toString();
final byte[] content = TestRandomUtil.nextBytes(16);
@SuppressWarnings("unchecked") final Consumer<PubSubProtos.PubSubMessage> subscribedConsumer = mock(Consumer.class);
provisioningManager.addListener(address, subscribedConsumer);
provisioningManager.removeListener(address);
provisioningManager.sendProvisioningMessage(address, content);
provisioningManager.addListener(provisioningAddress, subscribedConsumer);
provisioningManager.removeListener(provisioningAddress);
provisioningManager.sendProvisioningMessage(provisioningAddress, content);
// Make sure that we give the message enough time to show up (if it was going to) before declaring victory
verify(subscribedConsumer, after(PUBSUB_TIMEOUT_MILLIS).never()).accept(any());
@@ -77,8 +77,8 @@ class PushNotificationManagerTest {
when(apnSender.sendNotification(any()))
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(true, Optional.empty(), false, Optional.empty())));
pushNotificationManager.sendRegistrationChallengeNotification(deviceToken, PushNotification.TokenType.APN_VOIP, challengeToken);
verify(apnSender).sendNotification(new PushNotification(deviceToken, PushNotification.TokenType.APN_VOIP, PushNotification.NotificationType.CHALLENGE, challengeToken, null, null, true));
pushNotificationManager.sendRegistrationChallengeNotification(deviceToken, PushNotification.TokenType.APN, challengeToken);
verify(apnSender).sendNotification(new PushNotification(deviceToken, PushNotification.TokenType.APN, PushNotification.NotificationType.CHALLENGE, challengeToken, null, null, true));
}
@Test
@@ -188,32 +188,6 @@ class PushNotificationManagerTest {
}
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void testSendNotificationApnVoip(final boolean urgent) {
final Account account = mock(Account.class);
final Device device = mock(Device.class);
when(device.getId()).thenReturn(Device.PRIMARY_ID);
when(account.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(device));
final PushNotification pushNotification = new PushNotification(
"token", PushNotification.TokenType.APN_VOIP, PushNotification.NotificationType.NOTIFICATION, null, account, device, urgent);
when(apnSender.sendNotification(pushNotification))
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(true, Optional.empty(), false, Optional.empty())));
pushNotificationManager.sendNotification(pushNotification);
verify(apnSender).sendNotification(pushNotification);
verifyNoInteractions(fcmSender);
verify(accountsManager, never()).updateDevice(eq(account), eq(Device.PRIMARY_ID), any());
verify(device, never()).setGcmId(any());
verify(pushNotificationScheduler).scheduleRecurringApnsVoipNotification(account, device);
verify(pushNotificationScheduler, never()).scheduleBackgroundApnsNotification(any(), any());
}
@Test
void testSendNotificationUnregisteredFcm() {
final Account account = mock(Account.class);
@@ -246,13 +220,12 @@ class PushNotificationManagerTest {
final UUID aci = UUID.randomUUID();
when(device.getId()).thenReturn(Device.PRIMARY_ID);
when(device.getApnId()).thenReturn("apns-token");
when(device.getVoipApnId()).thenReturn("apns-voip-token");
when(account.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(device));
when(account.getUuid()).thenReturn(aci);
when(accountsManager.getByAccountIdentifier(aci)).thenReturn(Optional.of(account));
final PushNotification pushNotification = new PushNotification(
"token", PushNotification.TokenType.APN_VOIP, PushNotification.NotificationType.NOTIFICATION, null, account, device, true);
"token", PushNotification.TokenType.APN, PushNotification.NotificationType.NOTIFICATION, null, account, device, true);
when(apnSender.sendNotification(pushNotification))
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(false, Optional.empty(), true, Optional.empty())));
@@ -264,8 +237,7 @@ class PushNotificationManagerTest {
verifyNoInteractions(fcmSender);
verify(accountsManager).updateDevice(eq(account), eq(Device.PRIMARY_ID), any());
verify(device).setVoipApnId(null);
verify(device, never()).setApnId(any());
verify(device).setApnId(null);
verify(pushNotificationScheduler).cancelScheduledNotifications(account, device);
}
@@ -278,14 +250,13 @@ class PushNotificationManagerTest {
final UUID aci = UUID.randomUUID();
when(device.getId()).thenReturn(Device.PRIMARY_ID);
when(device.getApnId()).thenReturn("apns-token");
when(device.getVoipApnId()).thenReturn("apns-voip-token");
when(device.getPushTimestamp()).thenReturn(tokenTimestamp.toEpochMilli());
when(account.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(device));
when(account.getUuid()).thenReturn(aci);
when(accountsManager.getByAccountIdentifier(aci)).thenReturn(Optional.of(account));
final PushNotification pushNotification = new PushNotification(
"token", PushNotification.TokenType.APN_VOIP, PushNotification.NotificationType.NOTIFICATION, null, account, device, true);
"token", PushNotification.TokenType.APN, PushNotification.NotificationType.NOTIFICATION, null, account, device, true);
when(apnSender.sendNotification(pushNotification))
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(false, Optional.empty(), true, Optional.of(tokenTimestamp.minusSeconds(60)))));
@@ -297,7 +268,6 @@ class PushNotificationManagerTest {
verifyNoInteractions(fcmSender);
verify(accountsManager, never()).updateDevice(eq(account), eq(Device.PRIMARY_ID), any());
verify(device, never()).setVoipApnId(any());
verify(device, never()).setApnId(any());
verify(pushNotificationScheduler, never()).cancelScheduledNotifications(account, device);
}
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.push;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
@@ -20,7 +19,6 @@ import io.lettuce.core.cluster.SlotHash;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@@ -38,7 +36,6 @@ import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.TestClock;
class PushNotificationSchedulerTest {
@@ -59,7 +56,6 @@ class PushNotificationSchedulerTest {
private static final String ACCOUNT_NUMBER = "+18005551234";
private static final byte DEVICE_ID = 1;
private static final String APN_ID = RandomStringUtils.randomAlphanumeric(32);
private static final String VOIP_APN_ID = RandomStringUtils.randomAlphanumeric(32);
@BeforeEach
void setUp() throws Exception {
@@ -67,7 +63,6 @@ class PushNotificationSchedulerTest {
device = mock(Device.class);
when(device.getId()).thenReturn(DEVICE_ID);
when(device.getApnId()).thenReturn(APN_ID);
when(device.getVoipApnId()).thenReturn(VOIP_APN_ID);
when(device.getLastSeen()).thenReturn(System.currentTimeMillis());
account = mock(Account.class);
@@ -95,57 +90,6 @@ class PushNotificationSchedulerTest {
apnSender, fcmSender, accountsManager, clock, 1, 1);
}
@Test
void testClusterInsert() throws ExecutionException, InterruptedException {
final String endpoint = PushNotificationScheduler.getVoipEndpointKey(ACCOUNT_UUID, DEVICE_ID);
final long currentTimeMillis = System.currentTimeMillis();
assertTrue(
pushNotificationScheduler.getPendingDestinationsForRecurringApnsVoipNotifications(SlotHash.getSlot(endpoint), 1).isEmpty());
clock.pin(Instant.ofEpochMilli(currentTimeMillis - 30_000));
pushNotificationScheduler.scheduleRecurringApnsVoipNotification(account, device).toCompletableFuture().get();
clock.pin(Instant.ofEpochMilli(currentTimeMillis));
final List<String> pendingDestinations = pushNotificationScheduler.getPendingDestinationsForRecurringApnsVoipNotifications(SlotHash.getSlot(endpoint), 2);
assertEquals(1, pendingDestinations.size());
final Pair<UUID, Byte> aciAndDeviceId =
PushNotificationScheduler.decodeAciAndDeviceId(pendingDestinations.getFirst());
assertEquals(ACCOUNT_UUID, aciAndDeviceId.first());
assertEquals(DEVICE_ID, aciAndDeviceId.second());
assertTrue(
pushNotificationScheduler.getPendingDestinationsForRecurringApnsVoipNotifications(SlotHash.getSlot(endpoint), 1).isEmpty());
}
@Test
void testProcessRecurringVoipNotifications() throws ExecutionException, InterruptedException {
final PushNotificationScheduler.NotificationWorker worker = pushNotificationScheduler.new NotificationWorker(1);
final long currentTimeMillis = System.currentTimeMillis();
clock.pin(Instant.ofEpochMilli(currentTimeMillis - 30_000));
pushNotificationScheduler.scheduleRecurringApnsVoipNotification(account, device).toCompletableFuture().get();
clock.pin(Instant.ofEpochMilli(currentTimeMillis));
final int slot = SlotHash.getSlot(PushNotificationScheduler.getVoipEndpointKey(ACCOUNT_UUID, DEVICE_ID));
assertEquals(1, worker.processRecurringApnsVoipNotifications(slot));
final ArgumentCaptor<PushNotification> notificationCaptor = ArgumentCaptor.forClass(PushNotification.class);
verify(apnSender).sendNotification(notificationCaptor.capture());
final PushNotification pushNotification = notificationCaptor.getValue();
assertEquals(VOIP_APN_ID, pushNotification.deviceToken());
assertEquals(account, pushNotification.destination());
assertEquals(device, pushNotification.destinationDevice());
assertEquals(0, worker.processRecurringApnsVoipNotifications(slot));
}
@Test
void testScheduleBackgroundNotificationWithNoRecentApnsNotification() throws ExecutionException, InterruptedException {
final Instant now = Instant.now().truncatedTo(ChronoUnit.MILLIS);
@@ -228,8 +172,6 @@ class PushNotificationSchedulerTest {
assertEquals(PushNotification.NotificationType.NOTIFICATION, pushNotification.notificationType());
assertFalse(pushNotification.urgent());
assertEquals(0, worker.processRecurringApnsVoipNotifications(slot));
assertEquals(Optional.empty(),
pushNotificationScheduler.getNextScheduledBackgroundApnsNotificationTimestamp(account, device));
}
@@ -1,14 +1,10 @@
package org.whispersystems.textsecuregcm.scheduler;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtension;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema;
import org.whispersystems.textsecuregcm.util.TestClock;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
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 javax.annotation.Nullable;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
@@ -16,8 +12,14 @@ import java.time.ZoneId;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.*;
import javax.annotation.Nullable;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtension;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema;
import org.whispersystems.textsecuregcm.util.TestClock;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
class JobSchedulerTest {
@@ -80,16 +82,16 @@ class JobSchedulerTest {
// Clock time is before scheduled job time
testClock.pin(CURRENT_TIME.minusMillis(1));
scheduler.processAvailableJobs().join();
scheduler.processAvailableJobs().block();
assertEquals(0, scheduler.jobsProcessed.get());
// Clock time is after scheduled job time
testClock.pin(CURRENT_TIME.plusMillis(1));
scheduler.processAvailableJobs().join();
scheduler.processAvailableJobs().block();
assertEquals(1, scheduler.jobsProcessed.get());
scheduler.processAvailableJobs().join();
scheduler.processAvailableJobs().block();
assertEquals(1, scheduler.jobsProcessed.get(),
"Jobs should be cleared after successful processing; job counter should not increment on second run");
}
@@ -112,10 +114,10 @@ class JobSchedulerTest {
scheduler.scheduleJob(scheduler.buildRunAtAttribute(CURRENT_TIME, 0L), CURRENT_TIME, null).join();
scheduler.processAvailableJobs().join();
scheduler.processAvailableJobs().block();
assertEquals(1, jobsEncountered.get());
scheduler.processAvailableJobs().join();
scheduler.processAvailableJobs().block();
assertEquals(2, jobsEncountered.get(),
"Jobs should not be cleared after failed processing; encountered job counter should increment on second run");
}
@@ -77,7 +77,7 @@ public class AccountCreationDeletionIntegrationTest {
private KeysManager keysManager;
private ClientPublicKeysManager clientPublicKeysManager;
record DeliveryChannels(boolean fetchesMessages, String apnsToken, String apnsVoipToken, String fcmToken) {}
record DeliveryChannels(boolean fetchesMessages, String apnsToken, String fcmToken) {}
@BeforeEach
void setUp() {
@@ -212,8 +212,8 @@ public class AccountCreationDeletionIntegrationTest {
final KEMSignedPreKey pniPqLastResortPreKey = KeysHelper.signedKEMPreKey(4, pniKeyPair);
final Optional<ApnRegistrationId> maybeApnRegistrationId =
deliveryChannels.apnsToken() != null || deliveryChannels.apnsVoipToken() != null
? Optional.of(new ApnRegistrationId(deliveryChannels.apnsToken(), deliveryChannels.apnsVoipToken()))
deliveryChannels.apnsToken() != null
? Optional.of(new ApnRegistrationId(deliveryChannels.apnsToken()))
: Optional.empty();
final Optional<GcmRegistrationId> maybeGcmRegistrationId = deliveryChannels.fcmToken() != null
@@ -271,10 +271,10 @@ public class AccountCreationDeletionIntegrationTest {
return ArgumentSets
// deliveryChannels
.argumentsForFirstParameter(
new DeliveryChannels(true, null, null, null),
new DeliveryChannels(false, "apns-token", null, null),
new DeliveryChannels(false, "apns-token", "apns-voip-token", null),
new DeliveryChannels(false, null, null, "fcm-token"))
new DeliveryChannels(true, null, null),
new DeliveryChannels(false, "apns-token", null),
new DeliveryChannels(false, "apns-token", null),
new DeliveryChannels(false, null, "fcm-token"))
// discoverableByPhoneNumber
.argumentsForNextParameter(true, false);
@@ -359,8 +359,8 @@ public class AccountCreationDeletionIntegrationTest {
final KEMSignedPreKey pniPqLastResortPreKey = KeysHelper.signedKEMPreKey(4, pniKeyPair);
final Optional<ApnRegistrationId> maybeApnRegistrationId =
deliveryChannels.apnsToken() != null || deliveryChannels.apnsVoipToken() != null
? Optional.of(new ApnRegistrationId(deliveryChannels.apnsToken(), deliveryChannels.apnsVoipToken()))
deliveryChannels.apnsToken() != null
? Optional.of(new ApnRegistrationId(deliveryChannels.apnsToken()))
: Optional.empty();
final Optional<GcmRegistrationId> maybeGcmRegistrationId = deliveryChannels.fcmToken() != null
@@ -519,19 +519,13 @@ public class AccountCreationDeletionIntegrationTest {
assertEquals(deviceCapabilities, primaryDevice.getCapabilities());
assertEquals(badges, account.getBadges());
maybeApnRegistrationId.ifPresentOrElse(apnRegistrationId -> {
assertEquals(apnRegistrationId.apnRegistrationId(), primaryDevice.getApnId());
assertEquals(apnRegistrationId.voipRegistrationId(), primaryDevice.getVoipApnId());
}, () -> {
assertNull(primaryDevice.getApnId());
assertNull(primaryDevice.getVoipApnId());
});
maybeApnRegistrationId.ifPresentOrElse(
apnRegistrationId -> assertEquals(apnRegistrationId.apnRegistrationId(), primaryDevice.getApnId()),
() -> assertNull(primaryDevice.getApnId()));
maybeGcmRegistrationId.ifPresentOrElse(gcmRegistrationId -> {
assertEquals(deliveryChannels.fcmToken(), primaryDevice.getGcmId());
}, () -> {
assertNull(primaryDevice.getGcmId());
});
maybeGcmRegistrationId.ifPresentOrElse(
gcmRegistrationId -> assertEquals(deliveryChannels.fcmToken(), primaryDevice.getGcmId()),
() -> assertNull(primaryDevice.getGcmId()));
assertTrue(account.getRegistrationLock().verify(registrationLockSecret));
assertTrue(primaryDevice.getAuthTokenHash().verify(password));
@@ -986,7 +986,6 @@ class AccountsManagerTest {
assertEquals(pniRegistrationId, device.getPhoneNumberIdentityRegistrationId().getAsInt());
assertTrue(device.getFetchesMessages());
assertNull(device.getApnId());
assertNull(device.getVoipApnId());
assertNull(device.getGcmId());
}
@@ -22,8 +22,8 @@ class DeviceTest {
"true, P180D, false",
"true, P181D, true",
"false, P1D, false",
"false, P30D, false",
"false, P31D, true",
"false, P45D, false",
"false, P46D, true",
"false, P180D, true",
})
public void testIsExpired(final boolean primary, final Duration timeSinceLastSeen, final boolean expectExpired) {
@@ -575,7 +575,7 @@ class MessagesCacheTest {
if (sharedMrmKeyPresent) {
sharedMrmDataKey = messagesCache.insertSharedMultiRecipientMessagePayload(mrm);
} else {
sharedMrmDataKey = new byte[]{1};
sharedMrmDataKey = "{1}".getBytes(StandardCharsets.UTF_8);
}
final UUID guid = UUID.randomUUID();
@@ -304,4 +304,37 @@ class MessagesDynamoDbTest {
assertThat(messagesDynamoDb.mayHaveMessages(destinationUuid, destinationDevice).join()).isTrue();
}
@Test
void mayHaveUrgentMessages() {
final UUID destinationUuid = UUID.randomUUID();
final byte destinationDeviceId = (byte) (random.nextInt(Device.MAXIMUM_DEVICE_ID) + 1);
final Device destinationDevice = DevicesHelper.createDevice(destinationDeviceId);
assertThat(messagesDynamoDb.mayHaveUrgentMessages(destinationUuid, destinationDevice).join()).isFalse();
{
final MessageProtos.Envelope nonUrgentMessage = MessageProtos.Envelope.newBuilder()
.setUrgent(false)
.setServerGuid(UUID.randomUUID().toString())
.setDestinationServiceId(UUID.randomUUID().toString())
.build();
messagesDynamoDb.store(List.of(nonUrgentMessage), destinationUuid, destinationDevice);
}
assertThat(messagesDynamoDb.mayHaveUrgentMessages(destinationUuid, destinationDevice).join()).isFalse();
{
final MessageProtos.Envelope urgentMessage = MessageProtos.Envelope.newBuilder()
.setUrgent(true)
.setServerGuid(UUID.randomUUID().toString())
.setDestinationServiceId(UUID.randomUUID().toString())
.build();
messagesDynamoDb.store(List.of(urgentMessage), destinationUuid, destinationDevice);
}
assertThat(messagesDynamoDb.mayHaveUrgentMessages(destinationUuid, destinationDevice).join()).isTrue();
}
}
@@ -16,6 +16,7 @@ import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import com.google.api.services.androidpublisher.AndroidPublisher;
import com.google.api.services.androidpublisher.model.AutoRenewingPlan;
import com.google.api.services.androidpublisher.model.BasePlan;
import com.google.api.services.androidpublisher.model.Money;
import com.google.api.services.androidpublisher.model.OfferDetails;
@@ -234,6 +235,7 @@ class GooglePlayBillingManagerTest {
.setRegionCode("US")
.setLineItems(List.of(new SubscriptionPurchaseLineItem()
.setExpiryTime(Instant.now().plus(Duration.ofDays(1)).toString())
.setAutoRenewingPlan(new AutoRenewingPlan().setAutoRenewEnabled(null))
.setProductId(PRODUCT_ID)
.setOfferDetails(new OfferDetails().setBasePlanId(basePlanId)))));
@@ -251,6 +253,8 @@ class GooglePlayBillingManagerTest {
assertThat(info.price().currency()).isEqualTo("USD");
assertThat(info.price().amount().compareTo(new BigDecimal("175"))).isEqualTo(0); // 175 cents
assertThat(info.level()).isEqualTo(201L);
assertThat(info.cancelAtPeriodEnd()).isTrue();
}
}
@@ -0,0 +1,63 @@
package org.whispersystems.textsecuregcm.websocket;
import com.google.protobuf.InvalidProtocolBufferException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.push.ProvisioningManager;
import org.whispersystems.websocket.WebSocketClient;
import org.whispersystems.websocket.session.WebSocketSessionContext;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
class ProvisioningConnectListenerTest {
private ProvisioningManager provisioningManager;
private ProvisioningConnectListener provisioningConnectListener;
@BeforeEach
void setUp() {
provisioningManager = mock(ProvisioningManager.class);
provisioningConnectListener = new ProvisioningConnectListener(provisioningManager);
}
@Test
void onWebSocketConnect() {
final WebSocketClient webSocketClient = mock(WebSocketClient.class);
final WebSocketSessionContext context = new WebSocketSessionContext(webSocketClient);
provisioningConnectListener.onWebSocketConnect(context);
context.notifyClosed(1000, "Test");
final ArgumentCaptor<String> addListenerProvisioningAddressCaptor = ArgumentCaptor.forClass(String.class);
final ArgumentCaptor<String> removeListenerProvisioningAddressCaptor = ArgumentCaptor.forClass(String.class);
@SuppressWarnings("unchecked") final ArgumentCaptor<Optional<byte[]>> sendAddressCaptor =
ArgumentCaptor.forClass(Optional.class);
verify(provisioningManager).addListener(addListenerProvisioningAddressCaptor.capture(), any());
verify(provisioningManager).removeListener(removeListenerProvisioningAddressCaptor.capture());
verify(webSocketClient).sendRequest(eq("PUT"), eq("/v1/address"), any(), sendAddressCaptor.capture());
final String sentProvisioningAddress = sendAddressCaptor.getValue()
.map(provisioningAddressBytes -> {
try {
return MessageProtos.ProvisioningAddress.parseFrom(provisioningAddressBytes);
} catch (final InvalidProtocolBufferException e) {
throw new RuntimeException(e);
}
})
.map(MessageProtos.ProvisioningAddress::getAddress)
.orElseThrow();
assertEquals(addListenerProvisioningAddressCaptor.getValue(), removeListenerProvisioningAddressCaptor.getValue());
assertEquals(addListenerProvisioningAddressCaptor.getValue(), sentProvisioningAddress);
}
}
@@ -31,23 +31,23 @@ import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import reactor.core.publisher.Flux;
class NotifyIdleDevicesWithoutMessagesCommandTest {
class NotifyIdleDevicesCommandTest {
private MessagesManager messagesManager;
private IdleDeviceNotificationScheduler idleDeviceNotificationScheduler;
private TestNotifyIdleDevicesWithoutMessagesCommand notifyIdleDevicesWithoutMessagesCommand;
private TestNotifyIdleDevicesCommand notifyIdleDevicesWithoutMessagesCommand;
private static final Instant CURRENT_TIME = Instant.now();
private static class TestNotifyIdleDevicesWithoutMessagesCommand extends NotifyIdleDevicesWithoutMessagesCommand {
private static class TestNotifyIdleDevicesCommand extends NotifyIdleDevicesCommand {
private final CommandDependencies commandDependencies;
private final IdleDeviceNotificationScheduler idleDeviceNotificationScheduler;
private boolean dryRun = false;
private TestNotifyIdleDevicesWithoutMessagesCommand(final MessagesManager messagesManager,
private TestNotifyIdleDevicesCommand(final MessagesManager messagesManager,
final IdleDeviceNotificationScheduler idleDeviceNotificationScheduler) {
this.commandDependencies = new CommandDependencies(
@@ -94,8 +94,8 @@ class NotifyIdleDevicesWithoutMessagesCommandTest {
@Override
protected Namespace getNamespace() {
return new Namespace(Map.of(
NotifyIdleDevicesWithoutMessagesCommand.MAX_CONCURRENCY_ARGUMENT, 1,
NotifyIdleDevicesWithoutMessagesCommand.DRY_RUN_ARGUMENT, dryRun));
NotifyIdleDevicesCommand.MAX_CONCURRENCY_ARGUMENT, 1,
NotifyIdleDevicesCommand.DRY_RUN_ARGUMENT, dryRun));
}
}
@@ -108,7 +108,7 @@ class NotifyIdleDevicesWithoutMessagesCommandTest {
.thenReturn(CompletableFuture.completedFuture(null));
notifyIdleDevicesWithoutMessagesCommand =
new TestNotifyIdleDevicesWithoutMessagesCommand(messagesManager, idleDeviceNotificationScheduler);
new TestNotifyIdleDevicesCommand(messagesManager, idleDeviceNotificationScheduler);
}
@ParameterizedTest
@@ -122,7 +122,7 @@ class NotifyIdleDevicesWithoutMessagesCommandTest {
when(eligibleDevice.getId()).thenReturn(Device.PRIMARY_ID);
when(eligibleDevice.getApnId()).thenReturn("apns-token");
when(eligibleDevice.getLastSeen())
.thenReturn(CURRENT_TIME.minus(NotifyIdleDevicesWithoutMessagesCommand.MIN_IDLE_DURATION).toEpochMilli());
.thenReturn(CURRENT_TIME.minus(NotifyIdleDevicesCommand.MIN_LONG_IDLE_DURATION).toEpochMilli());
final Device ineligibleDevice = mock(Device.class);
when(ineligibleDevice.getId()).thenReturn((byte) (Device.PRIMARY_ID + 1));
@@ -138,9 +138,9 @@ class NotifyIdleDevicesWithoutMessagesCommandTest {
notifyIdleDevicesWithoutMessagesCommand.crawlAccounts(Flux.just(account));
if (dryRun) {
verify(idleDeviceNotificationScheduler, never()).scheduleNotification(account, eligibleDevice, NotifyIdleDevicesWithoutMessagesCommand.PREFERRED_NOTIFICATION_TIME);
verify(idleDeviceNotificationScheduler, never()).scheduleNotification(account, eligibleDevice, NotifyIdleDevicesCommand.PREFERRED_NOTIFICATION_TIME);
} else {
verify(idleDeviceNotificationScheduler).scheduleNotification(account, eligibleDevice, NotifyIdleDevicesWithoutMessagesCommand.PREFERRED_NOTIFICATION_TIME);
verify(idleDeviceNotificationScheduler).scheduleNotification(account, eligibleDevice, NotifyIdleDevicesCommand.PREFERRED_NOTIFICATION_TIME);
}
verify(idleDeviceNotificationScheduler, never()).scheduleNotification(eq(account), eq(ineligibleDevice), any());
@@ -151,13 +151,17 @@ class NotifyIdleDevicesWithoutMessagesCommandTest {
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,
NotifyIdleDevicesWithoutMessagesCommand.isDeviceEligible(account, device, messagesManager, Clock.fixed(CURRENT_TIME, ZoneId.systemDefault())).block());
NotifyIdleDevicesCommand.isDeviceEligible(account, device, messagesManager, Clock.fixed(CURRENT_TIME, ZoneId.systemDefault())).block());
}
private static List<Arguments> isDeviceEligible() {
@@ -169,54 +173,97 @@ class NotifyIdleDevicesWithoutMessagesCommandTest {
PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164));
{
// Idle device with push token and messages
// 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(NotifyIdleDevicesWithoutMessagesCommand.MIN_IDLE_DURATION).toEpochMilli());
when(device.getLastSeen()).thenReturn(CURRENT_TIME.minus(NotifyIdleDevicesCommand.MIN_LONG_IDLE_DURATION).toEpochMilli());
arguments.add(Arguments.of(account, device, true, false));
arguments.add(Arguments.of(account, device, true, true, false));
}
{
// Idle device missing push token, but with messages
// Long-idle device missing push token, but with messages
final Device device = mock(Device.class);
when(device.getLastSeen()).thenReturn(CURRENT_TIME.minus(NotifyIdleDevicesWithoutMessagesCommand.MIN_IDLE_DURATION).toEpochMilli());
when(device.getLastSeen()).thenReturn(CURRENT_TIME.minus(NotifyIdleDevicesCommand.MIN_LONG_IDLE_DURATION).toEpochMilli());
arguments.add(Arguments.of(account, device, true, false));
arguments.add(Arguments.of(account, device, true, true, false));
}
{
// Idle device missing push token and messages
// Long-idle device missing push token and messages
final Device device = mock(Device.class);
when(device.getLastSeen()).thenReturn(CURRENT_TIME.minus(NotifyIdleDevicesWithoutMessagesCommand.MIN_IDLE_DURATION).toEpochMilli());
when(device.getLastSeen()).thenReturn(CURRENT_TIME.minus(NotifyIdleDevicesCommand.MIN_LONG_IDLE_DURATION).toEpochMilli());
arguments.add(Arguments.of(account, device, false, false));
arguments.add(Arguments.of(account, device, false, false, false));
}
{
// Idle device with push token, but no messages
// Long-idle device with push token, but no messages
final Device device = mock(Device.class);
when(device.getLastSeen()).thenReturn(CURRENT_TIME.minus(NotifyIdleDevicesWithoutMessagesCommand.MIN_IDLE_DURATION).toEpochMilli());
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, true));
arguments.add(Arguments.of(account, device, false, false, true));
}
{
// Active device with push token and messages
// 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, false));
arguments.add(Arguments.of(account, device, true, true, false));
}
{
// Active device missing push token, but with messages
// 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, false));
arguments.add(Arguments.of(account, device, true, true, false));
}
{
@@ -224,7 +271,7 @@ class NotifyIdleDevicesWithoutMessagesCommandTest {
final Device device = mock(Device.class);
when(device.getLastSeen()).thenReturn(CURRENT_TIME.toEpochMilli());
arguments.add(Arguments.of(account, device, false, false));
arguments.add(Arguments.of(account, device, false, false, false));
}
{
@@ -233,7 +280,7 @@ class NotifyIdleDevicesWithoutMessagesCommandTest {
when(device.getLastSeen()).thenReturn(CURRENT_TIME.toEpochMilli());
when(device.getApnId()).thenReturn("apns-token");
arguments.add(Arguments.of(account, device, false, false));
arguments.add(Arguments.of(account, device, false, false, false));
}
return arguments;
@@ -241,31 +288,54 @@ class NotifyIdleDevicesWithoutMessagesCommandTest {
@ParameterizedTest
@MethodSource
void isIdle(final Duration idleDuration, final boolean expectIdle) {
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, NotifyIdleDevicesWithoutMessagesCommand.isIdle(device, clock));
assertEquals(expectIdle, NotifyIdleDevicesCommand.isShortIdle(device, clock));
}
private static List<Arguments> isIdle() {
private static List<Arguments> isShortIdle() {
return List.of(
Arguments.of(NotifyIdleDevicesWithoutMessagesCommand.MIN_IDLE_DURATION, true),
Arguments.of(NotifyIdleDevicesWithoutMessagesCommand.MIN_IDLE_DURATION.plusMillis(1), true),
Arguments.of(NotifyIdleDevicesWithoutMessagesCommand.MIN_IDLE_DURATION.minusMillis(1), false),
Arguments.of(NotifyIdleDevicesWithoutMessagesCommand.MAX_IDLE_DURATION, false),
Arguments.of(NotifyIdleDevicesWithoutMessagesCommand.MAX_IDLE_DURATION.plusMillis(1), false),
Arguments.of(NotifyIdleDevicesWithoutMessagesCommand.MAX_IDLE_DURATION.minusMillis(1), true)
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, NotifyIdleDevicesWithoutMessagesCommand.hasPushToken(device));
assertEquals(expectHasPushToken, NotifyIdleDevicesCommand.hasPushToken(device));
}
private static List<Arguments> hasPushToken() {
@@ -294,15 +364,6 @@ class NotifyIdleDevicesWithoutMessagesCommandTest {
arguments.add(Arguments.of(device, true));
}
{
// APNs VOIP token
final Device device = mock(Device.class);
when(device.getApnId()).thenReturn("apns-token");
when(device.getVoipApnId()).thenReturn("apns-voip-token");
arguments.add(Arguments.of(device, false));
}
return arguments;
}
}
@@ -0,0 +1,123 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.workers;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.whispersystems.textsecuregcm.scheduler.JobScheduler;
import reactor.core.publisher.Mono;
import reactor.test.publisher.TestPublisher;
@Timeout(value = 5, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
class ProcessScheduledJobsServiceCommandTest {
private ScheduledExecutorService scheduledExecutorService;
@BeforeEach
void setUp() {
scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
}
@Test
void testDisposeOnStopCancels() throws Exception {
// This test publisher will never emit any values or intentionally complete
final TestPublisher<Integer> testPublisher = TestPublisher.create();
final TestJobScheduler testJobScheduler = new TestJobScheduler(testPublisher);
final ProcessScheduledJobsServiceCommand.ScheduledJobProcessor scheduledJobProcessor =
new ProcessScheduledJobsServiceCommand.ScheduledJobProcessor(testJobScheduler, scheduledExecutorService, 60);
scheduledJobProcessor.start();
testJobScheduler.getStartLatch().await();
scheduledJobProcessor.stop();
testJobScheduler.getEndLatch().await();
scheduledExecutorService.shutdown();
assertTrue(scheduledExecutorService.awaitTermination(1, TimeUnit.SECONDS), "The submitted task should complete");
testPublisher.assertCancelled();
}
@Test
void testCompletedPublisher() throws Exception {
final TestPublisher<Integer> testPublisher = TestPublisher.create();
testPublisher.complete();
final TestJobScheduler testJobScheduler = new TestJobScheduler(testPublisher);
final ProcessScheduledJobsServiceCommand.ScheduledJobProcessor scheduledJobProcessor =
new ProcessScheduledJobsServiceCommand.ScheduledJobProcessor(testJobScheduler, scheduledExecutorService, 60);
scheduledJobProcessor.start();
testJobScheduler.getStartLatch().await();
scheduledJobProcessor.stop();
testJobScheduler.getEndLatch().await();
scheduledExecutorService.shutdown();
assertTrue(scheduledExecutorService.awaitTermination(1, TimeUnit.SECONDS), "The submitted task should complete");
testPublisher.assertNotCancelled();
}
private static class TestJobScheduler extends JobScheduler {
private final TestPublisher<Integer> testPublisher;
private final CountDownLatch startLatch = new CountDownLatch(1);
private final CountDownLatch endLatch = new CountDownLatch(1);
protected TestJobScheduler(TestPublisher<Integer> testPublisher) {
super(null, null, null, null);
this.testPublisher = testPublisher;
}
/**
* A {@link CountDownLatch} indicating whether the {@link Mono} returned by {@link #processAvailableJobs()} has been
* subscribed to.
*/
public CountDownLatch getStartLatch() {
return startLatch;
}
/**
* A {@link CountDownLatch} indicating whether the {@link Mono} returned by {@link #processAvailableJobs()} has
* terminated or been canceled.
*/
public CountDownLatch getEndLatch() {
return endLatch;
}
@Override
public String getSchedulerName() {
return "test";
}
@Override
protected CompletableFuture<String> processJob(@Nullable byte[] jobData) {
return CompletableFuture.failedFuture(new IllegalStateException("Not implemented"));
}
@Override
public Mono<Void> processAvailableJobs() {
return testPublisher.flux()
.then()
.doOnSubscribe(ignored -> startLatch.countDown())
.doOnTerminate(endLatch::countDown)
.doOnCancel(endLatch::countDown);
}
}
}
@@ -11,7 +11,6 @@
"salt": null,
"gcmId": null,
"apnId": null,
"voipApnId": null,
"pushTimestamp": 0,
"uninstalledFeedback": 0,
"fetchesMessages": true,